1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 // This implements the dead-code warning pass. It follows middle::reachable
12 // closely. The idea is that all reachable symbols are live, codes called
13 // from live codes are live, and everything else is dead.
16 use middle::lint::{Allow, contains_lint, DeadCode};
20 use util::nodemap::NodeSet;
22 use std::collections::HashSet;
25 use syntax::ast_util::{local_def, is_local};
28 use syntax::parse::token;
29 use syntax::visit::Visitor;
32 pub static DEAD_CODE_LINT_STR: &'static str = "dead_code";
34 // Any local node that may call something in its body block should be
35 // explored. For example, if it's a live NodeItem that is a
36 // function, then we should explore its block to check for codes that
37 // may need to be marked as live.
38 fn should_explore(tcx: &ty::ctxt, def_id: ast::DefId) -> bool {
39 if !is_local(def_id) {
43 match tcx.map.find(def_id.node) {
44 Some(ast_map::NodeItem(..))
45 | Some(ast_map::NodeMethod(..))
46 | Some(ast_map::NodeForeignItem(..))
47 | Some(ast_map::NodeTraitMethod(..)) => true,
52 struct MarkSymbolVisitor<'a> {
53 worklist: Vec<ast::NodeId>,
55 live_symbols: Box<HashSet<ast::NodeId>>,
59 struct MarkSymbolVisitorContext {
60 struct_has_extern_repr: bool
63 impl<'a> MarkSymbolVisitor<'a> {
64 fn new(tcx: &'a ty::ctxt,
65 worklist: Vec<ast::NodeId>) -> MarkSymbolVisitor<'a> {
69 live_symbols: box HashSet::new(),
73 fn check_def_id(&mut self, def_id: ast::DefId) {
74 if should_explore(self.tcx, def_id) {
75 self.worklist.push(def_id.node);
77 self.live_symbols.insert(def_id.node);
80 fn lookup_and_handle_definition(&mut self, id: &ast::NodeId) {
81 let def = match self.tcx.def_map.borrow().find(id) {
85 let def_id = match def {
86 def::DefVariant(enum_id, _, _) => Some(enum_id),
87 def::DefPrimTy(_) => None,
88 _ => Some(def.def_id())
91 Some(def_id) => self.check_def_id(def_id),
96 fn lookup_and_handle_method(&mut self, id: ast::NodeId,
97 span: codemap::Span) {
98 let method_call = typeck::MethodCall::expr(id);
99 match self.tcx.method_map.borrow().find(&method_call) {
101 match method.origin {
102 typeck::MethodStatic(def_id) => {
103 match ty::provided_source(self.tcx, def_id) {
104 Some(p_did) => self.check_def_id(p_did),
105 None => self.check_def_id(def_id)
108 typeck::MethodParam(typeck::MethodParam {
113 | typeck::MethodObject(typeck::MethodObject {
118 let def_id = ty::trait_method(self.tcx,
119 trait_id, index).def_id;
120 self.check_def_id(def_id);
125 self.tcx.sess.span_bug(span,
126 "method call expression not \
132 fn handle_field_access(&mut self, lhs: &ast::Expr, name: &ast::Ident) {
133 match ty::get(ty::expr_ty_adjusted(self.tcx, lhs)).sty {
134 ty::ty_struct(id, _) => {
135 let fields = ty::lookup_struct_fields(self.tcx, id);
136 let field_id = fields.iter()
137 .find(|field| field.name == name.name).unwrap().id;
138 self.live_symbols.insert(field_id.node);
144 fn handle_field_pattern_match(&mut self, lhs: &ast::Pat, pats: &[ast::FieldPat]) {
145 match self.tcx.def_map.borrow().get(&lhs.id) {
146 &def::DefStruct(id) | &def::DefVariant(_, id, _) => {
147 let fields = ty::lookup_struct_fields(self.tcx, id);
148 for pat in pats.iter() {
149 let field_id = fields.iter()
150 .find(|field| field.name == pat.ident.name).unwrap().id;
151 self.live_symbols.insert(field_id.node);
158 fn mark_live_symbols(&mut self) {
159 let mut scanned = HashSet::new();
160 while self.worklist.len() > 0 {
161 let id = self.worklist.pop().unwrap();
162 if scanned.contains(&id) {
167 match self.tcx.map.find(id) {
169 self.live_symbols.insert(id);
170 self.visit_node(node);
177 fn visit_node(&mut self, node: &ast_map::Node) {
178 let ctxt = MarkSymbolVisitorContext {
179 struct_has_extern_repr: false
182 ast_map::NodeItem(item) => {
184 ast::ItemStruct(..) => {
185 let has_extern_repr = item.attrs.iter().fold(attr::ReprAny, |acc, attr| {
186 attr::find_repr_attr(self.tcx.sess.diagnostic(), attr, acc)
187 }) == attr::ReprExtern;
189 visit::walk_item(self, &*item, MarkSymbolVisitorContext {
190 struct_has_extern_repr: has_extern_repr,
197 | ast::ItemStatic(..) => {
198 visit::walk_item(self, &*item, ctxt);
203 ast_map::NodeTraitMethod(trait_method) => {
204 visit::walk_trait_method(self, &*trait_method, ctxt);
206 ast_map::NodeMethod(method) => {
207 visit::walk_block(self, &*method.body, ctxt);
209 ast_map::NodeForeignItem(foreign_item) => {
210 visit::walk_foreign_item(self, &*foreign_item, ctxt);
217 impl<'a> Visitor<MarkSymbolVisitorContext> for MarkSymbolVisitor<'a> {
219 fn visit_struct_def(&mut self, def: &ast::StructDef, _: ast::Ident, _: &ast::Generics,
220 _: ast::NodeId, ctxt: MarkSymbolVisitorContext) {
221 let live_fields = def.fields.iter().filter(|f| {
222 ctxt.struct_has_extern_repr || match f.node.kind {
223 ast::NamedField(_, ast::Public) => true,
227 self.live_symbols.extend(live_fields.map(|f| f.node.id));
229 visit::walk_struct_def(self, def, ctxt);
232 fn visit_expr(&mut self, expr: &ast::Expr, ctxt: MarkSymbolVisitorContext) {
234 ast::ExprMethodCall(..) => {
235 self.lookup_and_handle_method(expr.id, expr.span);
237 ast::ExprField(ref lhs, ref ident, _) => {
238 self.handle_field_access(&**lhs, ident);
243 visit::walk_expr(self, expr, ctxt);
246 fn visit_pat(&mut self, pat: &ast::Pat, ctxt: MarkSymbolVisitorContext) {
248 ast::PatStruct(_, ref fields, _) => {
249 self.handle_field_pattern_match(pat, fields.as_slice());
254 visit::walk_pat(self, pat, ctxt);
257 fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId, ctxt: MarkSymbolVisitorContext) {
258 self.lookup_and_handle_definition(&id);
259 visit::walk_path(self, path, ctxt);
262 fn visit_item(&mut self, _: &ast::Item, _: MarkSymbolVisitorContext) {
263 // Do not recurse into items. These items will be added to the
264 // worklist and recursed into manually if necessary.
268 fn has_allow_dead_code_or_lang_attr(attrs: &[ast::Attribute]) -> bool {
269 contains_lint(attrs, Allow, DEAD_CODE_LINT_STR)
270 || attr::contains_name(attrs.as_slice(), "lang")
273 // This visitor seeds items that
274 // 1) We want to explicitly consider as live:
275 // * Item annotated with #[allow(dead_code)]
276 // - This is done so that if we want to suppress warnings for a
277 // group of dead functions, we only have to annotate the "root".
278 // For example, if both `f` and `g` are dead and `f` calls `g`,
279 // then annotating `f` with `#[allow(dead_code)]` will suppress
280 // warning for both `f` and `g`.
281 // * Item annotated with #[lang=".."]
282 // - This is because lang items are always callable from elsewhere.
284 // 2) We are not sure to be live or not
285 // * Implementation of a trait method
287 worklist: Vec<ast::NodeId> ,
290 impl Visitor<()> for LifeSeeder {
291 fn visit_item(&mut self, item: &ast::Item, _: ()) {
292 if has_allow_dead_code_or_lang_attr(item.attrs.as_slice()) {
293 self.worklist.push(item.id);
296 ast::ItemImpl(_, Some(ref _trait_ref), _, ref methods) => {
297 for method in methods.iter() {
298 self.worklist.push(method.id);
303 visit::walk_item(self, item, ());
306 fn visit_fn(&mut self, fk: &visit::FnKind,
307 _: &ast::FnDecl, block: &ast::Block,
308 _: codemap::Span, id: ast::NodeId, _: ()) {
309 // Check for method here because methods are not ast::Item
311 visit::FkMethod(_, _, method) => {
312 if has_allow_dead_code_or_lang_attr(method.attrs.as_slice()) {
313 self.worklist.push(id);
318 visit::walk_block(self, block, ());
322 fn create_and_seed_worklist(tcx: &ty::ctxt,
323 exported_items: &privacy::ExportedItems,
324 reachable_symbols: &NodeSet,
325 krate: &ast::Crate) -> Vec<ast::NodeId> {
326 let mut worklist = Vec::new();
328 // Preferably, we would only need to seed the worklist with reachable
329 // symbols. However, since the set of reachable symbols differs
330 // depending on whether a crate is built as bin or lib, and we want
331 // the warning to be consistent, we also seed the worklist with
333 for &id in exported_items.iter() {
336 for &id in reachable_symbols.iter() {
341 match *tcx.sess.entry_fn.borrow() {
342 Some((id, _)) => worklist.push(id),
346 // Seed implemented trait methods
347 let mut life_seeder = LifeSeeder {
350 visit::walk_crate(&mut life_seeder, krate, ());
352 return life_seeder.worklist;
355 fn find_live(tcx: &ty::ctxt,
356 exported_items: &privacy::ExportedItems,
357 reachable_symbols: &NodeSet,
359 -> Box<HashSet<ast::NodeId>> {
360 let worklist = create_and_seed_worklist(tcx, exported_items,
361 reachable_symbols, krate);
362 let mut symbol_visitor = MarkSymbolVisitor::new(tcx, worklist);
363 symbol_visitor.mark_live_symbols();
364 symbol_visitor.live_symbols
367 fn should_warn(item: &ast::Item) -> bool {
372 | ast::ItemStruct(..) => true,
377 fn get_struct_ctor_id(item: &ast::Item) -> Option<ast::NodeId> {
379 ast::ItemStruct(struct_def, _) => struct_def.ctor_id,
384 struct DeadVisitor<'a> {
386 live_symbols: Box<HashSet<ast::NodeId>>,
389 impl<'a> DeadVisitor<'a> {
390 fn should_warn_about_field(&mut self, node: &ast::StructField_) -> bool {
391 let (is_named, has_leading_underscore) = match node.ident() {
392 Some(ref ident) => (true, token::get_ident(*ident).get()[0] == ('_' as u8)),
395 let field_type = ty::node_id_to_type(self.tcx, node.id);
396 let is_marker_field = match ty::ty_to_def_id(field_type) {
397 Some(def_id) => self.tcx.lang_items.items().any(|(_, item)| *item == Some(def_id)),
401 && !self.symbol_is_live(node.id, None)
402 && !has_leading_underscore
404 && !has_allow_dead_code_or_lang_attr(node.attrs.as_slice())
407 // id := node id of an item's definition.
408 // ctor_id := `Some` if the item is a struct_ctor (tuple struct),
410 // If the item is a struct_ctor, then either its `id` or
411 // `ctor_id` (unwrapped) is in the live_symbols set. More specifically,
412 // DefMap maps the ExprPath of a struct_ctor to the node referred by
413 // `ctor_id`. On the other hand, in a statement like
414 // `type <ident> <generics> = <ty>;` where <ty> refers to a struct_ctor,
415 // DefMap maps <ty> to `id` instead.
416 fn symbol_is_live(&mut self, id: ast::NodeId,
417 ctor_id: Option<ast::NodeId>) -> bool {
418 if self.live_symbols.contains(&id)
419 || ctor_id.map_or(false,
420 |ctor| self.live_symbols.contains(&ctor)) {
423 // If it's a type whose methods are live, then it's live, too.
424 // This is done to handle the case where, for example, the static
425 // method of a private type is used, but the type itself is never
427 let impl_methods = self.tcx.impl_methods.borrow();
428 match self.tcx.inherent_impls.borrow().find(&local_def(id)) {
431 for impl_did in impl_list.borrow().iter() {
432 for method_did in impl_methods.get(impl_did).iter() {
433 if self.live_symbols.contains(&method_did.node) {
443 fn warn_dead_code(&mut self,
452 format!("code is never used: `{}`",
453 token::get_ident(ident)));
457 impl<'a> Visitor<()> for DeadVisitor<'a> {
458 fn visit_item(&mut self, item: &ast::Item, _: ()) {
459 let ctor_id = get_struct_ctor_id(item);
460 if !self.symbol_is_live(item.id, ctor_id) && should_warn(item) {
461 self.warn_dead_code(item.id, item.span, item.ident);
463 visit::walk_item(self, item, ());
466 fn visit_foreign_item(&mut self, fi: &ast::ForeignItem, _: ()) {
467 if !self.symbol_is_live(fi.id, None) {
468 self.warn_dead_code(fi.id, fi.span, fi.ident);
470 visit::walk_foreign_item(self, fi, ());
473 fn visit_fn(&mut self, fk: &visit::FnKind,
474 _: &ast::FnDecl, block: &ast::Block,
475 span: codemap::Span, id: ast::NodeId, _: ()) {
476 // Have to warn method here because methods are not ast::Item
478 visit::FkMethod(..) => {
479 let ident = visit::name_of_fn(fk);
480 if !self.symbol_is_live(id, None) {
481 self.warn_dead_code(id, span, ident);
486 visit::walk_block(self, block, ());
489 fn visit_struct_field(&mut self, field: &ast::StructField, _: ()) {
490 if self.should_warn_about_field(&field.node) {
491 self.warn_dead_code(field.node.id, field.span, field.node.ident().unwrap());
494 visit::walk_struct_field(self, field, ());
497 // Overwrite so that we don't warn the trait method itself.
498 fn visit_trait_method(&mut self, trait_method: &ast::TraitMethod, _: ()) {
499 match *trait_method {
500 ast::Provided(ref method) => visit::walk_block(self, &*method.body, ()),
501 ast::Required(_) => ()
506 pub fn check_crate(tcx: &ty::ctxt,
507 exported_items: &privacy::ExportedItems,
508 reachable_symbols: &NodeSet,
509 krate: &ast::Crate) {
510 let live_symbols = find_live(tcx, exported_items,
511 reachable_symbols, krate);
512 let mut visitor = DeadVisitor { tcx: tcx, live_symbols: live_symbols };
513 visit::walk_crate(&mut visitor, krate, ());