]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/dead.rs
Auto merge of #22541 - Manishearth:rollup, r=Gankro
[rust.git] / src / librustc / middle / dead.rs
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.
4 //
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.
10
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.
14
15 use middle::{def, pat_util, privacy, ty};
16 use lint;
17 use util::nodemap::NodeSet;
18
19 use std::collections::HashSet;
20 use syntax::{ast, ast_map, codemap};
21 use syntax::ast_util::{local_def, is_local, PostExpansionMethod};
22 use syntax::attr::{self, AttrMetaMethods};
23 use syntax::visit::{self, Visitor};
24
25 // Any local node that may call something in its body block should be
26 // explored. For example, if it's a live NodeItem that is a
27 // function, then we should explore its block to check for codes that
28 // may need to be marked as live.
29 fn should_explore(tcx: &ty::ctxt, def_id: ast::DefId) -> bool {
30     if !is_local(def_id) {
31         return false;
32     }
33
34     match tcx.map.find(def_id.node) {
35         Some(ast_map::NodeItem(..))
36         | Some(ast_map::NodeImplItem(..))
37         | Some(ast_map::NodeForeignItem(..))
38         | Some(ast_map::NodeTraitItem(..)) => true,
39         _ => false
40     }
41 }
42
43 struct MarkSymbolVisitor<'a, 'tcx: 'a> {
44     worklist: Vec<ast::NodeId>,
45     tcx: &'a ty::ctxt<'tcx>,
46     live_symbols: Box<HashSet<ast::NodeId>>,
47     struct_has_extern_repr: bool,
48     ignore_non_const_paths: bool,
49     inherited_pub_visibility: bool,
50 }
51
52 impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> {
53     fn new(tcx: &'a ty::ctxt<'tcx>,
54            worklist: Vec<ast::NodeId>) -> MarkSymbolVisitor<'a, 'tcx> {
55         MarkSymbolVisitor {
56             worklist: worklist,
57             tcx: tcx,
58             live_symbols: box HashSet::new(),
59             struct_has_extern_repr: false,
60             ignore_non_const_paths: false,
61             inherited_pub_visibility: false,
62         }
63     }
64
65     fn check_def_id(&mut self, def_id: ast::DefId) {
66         if should_explore(self.tcx, def_id) {
67             self.worklist.push(def_id.node);
68         }
69         self.live_symbols.insert(def_id.node);
70     }
71
72     fn lookup_and_handle_definition(&mut self, id: &ast::NodeId) {
73         self.tcx.def_map.borrow().get(id).map(|def| {
74             match def {
75                 &def::DefConst(_) => {
76                     self.check_def_id(def.def_id())
77                 }
78                 _ if self.ignore_non_const_paths => (),
79                 &def::DefPrimTy(_) => (),
80                 &def::DefVariant(enum_id, variant_id, _) => {
81                     self.check_def_id(enum_id);
82                     self.check_def_id(variant_id);
83                 }
84                 _ => {
85                     self.check_def_id(def.def_id());
86                 }
87             }
88         });
89     }
90
91     fn lookup_and_handle_method(&mut self, id: ast::NodeId,
92                                 span: codemap::Span) {
93         let method_call = ty::MethodCall::expr(id);
94         match self.tcx.method_map.borrow().get(&method_call) {
95             Some(method) => {
96                 match method.origin {
97                     ty::MethodStatic(def_id) => {
98                         match ty::provided_source(self.tcx, def_id) {
99                             Some(p_did) => self.check_def_id(p_did),
100                             None => self.check_def_id(def_id)
101                         }
102                     }
103                     ty::MethodStaticClosure(_) => {}
104                     ty::MethodTypeParam(ty::MethodParam {
105                         ref trait_ref,
106                         method_num: index,
107                         ..
108                     }) |
109                     ty::MethodTraitObject(ty::MethodObject {
110                         ref trait_ref,
111                         method_num: index,
112                         ..
113                     }) => {
114                         let trait_item = ty::trait_item(self.tcx,
115                                                         trait_ref.def_id,
116                                                         index);
117                         match trait_item {
118                             ty::MethodTraitItem(method) => {
119                                 self.check_def_id(method.def_id);
120                             }
121                             ty::TypeTraitItem(typedef) => {
122                                 self.check_def_id(typedef.def_id);
123                             }
124                         }
125                     }
126                 }
127             }
128             None => {
129                 self.tcx.sess.span_bug(span,
130                                        "method call expression not \
131                                         in method map?!")
132             }
133         }
134     }
135
136     fn handle_field_access(&mut self, lhs: &ast::Expr, name: &ast::Ident) {
137         match ty::expr_ty_adjusted(self.tcx, lhs).sty {
138             ty::ty_struct(id, _) => {
139                 let fields = ty::lookup_struct_fields(self.tcx, id);
140                 let field_id = fields.iter()
141                     .find(|field| field.name == name.name).unwrap().id;
142                 self.live_symbols.insert(field_id.node);
143             },
144             _ => ()
145         }
146     }
147
148     fn handle_tup_field_access(&mut self, lhs: &ast::Expr, idx: uint) {
149         match ty::expr_ty_adjusted(self.tcx, lhs).sty {
150             ty::ty_struct(id, _) => {
151                 let fields = ty::lookup_struct_fields(self.tcx, id);
152                 let field_id = fields[idx].id;
153                 self.live_symbols.insert(field_id.node);
154             },
155             _ => ()
156         }
157     }
158
159     fn handle_field_pattern_match(&mut self, lhs: &ast::Pat,
160                                   pats: &[codemap::Spanned<ast::FieldPat>]) {
161         let id = match (*self.tcx.def_map.borrow())[lhs.id] {
162             def::DefVariant(_, id, _) => id,
163             _ => {
164                 match ty::ty_to_def_id(ty::node_id_to_type(self.tcx,
165                                                            lhs.id)) {
166                     None => {
167                         self.tcx.sess.span_bug(lhs.span,
168                                                "struct pattern wasn't of a \
169                                                 type with a def ID?!")
170                     }
171                     Some(def_id) => def_id,
172                 }
173             }
174         };
175         let fields = ty::lookup_struct_fields(self.tcx, id);
176         for pat in pats {
177             let field_id = fields.iter()
178                 .find(|field| field.name == pat.node.ident.name).unwrap().id;
179             self.live_symbols.insert(field_id.node);
180         }
181     }
182
183     fn mark_live_symbols(&mut self) {
184         let mut scanned = HashSet::new();
185         while self.worklist.len() > 0 {
186             let id = self.worklist.pop().unwrap();
187             if scanned.contains(&id) {
188                 continue
189             }
190             scanned.insert(id);
191
192             match self.tcx.map.find(id) {
193                 Some(ref node) => {
194                     self.live_symbols.insert(id);
195                     self.visit_node(node);
196                 }
197                 None => (),
198             }
199         }
200     }
201
202     fn visit_node(&mut self, node: &ast_map::Node) {
203         let had_extern_repr = self.struct_has_extern_repr;
204         self.struct_has_extern_repr = false;
205         let had_inherited_pub_visibility = self.inherited_pub_visibility;
206         self.inherited_pub_visibility = false;
207         match *node {
208             ast_map::NodeItem(item) => {
209                 match item.node {
210                     ast::ItemStruct(..) => {
211                         self.struct_has_extern_repr = item.attrs.iter().any(|attr| {
212                             attr::find_repr_attrs(self.tcx.sess.diagnostic(), attr)
213                                 .contains(&attr::ReprExtern)
214                         });
215
216                         visit::walk_item(self, &*item);
217                     }
218                     ast::ItemEnum(..) => {
219                         self.inherited_pub_visibility = item.vis == ast::Public;
220                         visit::walk_item(self, &*item);
221                     }
222                     ast::ItemFn(..)
223                     | ast::ItemTy(..)
224                     | ast::ItemStatic(..)
225                     | ast::ItemConst(..) => {
226                         visit::walk_item(self, &*item);
227                     }
228                     _ => ()
229                 }
230             }
231             ast_map::NodeTraitItem(trait_method) => {
232                 visit::walk_trait_item(self, trait_method);
233             }
234             ast_map::NodeImplItem(impl_item) => {
235                 match *impl_item {
236                     ast::MethodImplItem(ref method) => {
237                         visit::walk_method_helper(self, method);
238                     }
239                     ast::TypeImplItem(_) => {}
240                 }
241             }
242             ast_map::NodeForeignItem(foreign_item) => {
243                 visit::walk_foreign_item(self, &*foreign_item);
244             }
245             _ => ()
246         }
247         self.struct_has_extern_repr = had_extern_repr;
248         self.inherited_pub_visibility = had_inherited_pub_visibility;
249     }
250 }
251
252 impl<'a, 'tcx, 'v> Visitor<'v> for MarkSymbolVisitor<'a, 'tcx> {
253
254     fn visit_struct_def(&mut self, def: &ast::StructDef, _: ast::Ident,
255                         _: &ast::Generics, _: ast::NodeId) {
256         let has_extern_repr = self.struct_has_extern_repr;
257         let inherited_pub_visibility = self.inherited_pub_visibility;
258         let live_fields = def.fields.iter().filter(|f| {
259             has_extern_repr || inherited_pub_visibility || match f.node.kind {
260                 ast::NamedField(_, ast::Public) => true,
261                 _ => false
262             }
263         });
264         self.live_symbols.extend(live_fields.map(|f| f.node.id));
265
266         visit::walk_struct_def(self, def);
267     }
268
269     fn visit_expr(&mut self, expr: &ast::Expr) {
270         match expr.node {
271             ast::ExprMethodCall(..) => {
272                 self.lookup_and_handle_method(expr.id, expr.span);
273             }
274             ast::ExprField(ref lhs, ref ident) => {
275                 self.handle_field_access(&**lhs, &ident.node);
276             }
277             ast::ExprTupField(ref lhs, idx) => {
278                 self.handle_tup_field_access(&**lhs, idx.node);
279             }
280             _ => ()
281         }
282
283         visit::walk_expr(self, expr);
284     }
285
286     fn visit_pat(&mut self, pat: &ast::Pat) {
287         let def_map = &self.tcx.def_map;
288         match pat.node {
289             ast::PatStruct(_, ref fields, _) => {
290                 self.handle_field_pattern_match(pat, fields);
291             }
292             _ if pat_util::pat_is_const(def_map, pat) => {
293                 // it might be the only use of a const
294                 self.lookup_and_handle_definition(&pat.id)
295             }
296             _ => ()
297         }
298
299         self.ignore_non_const_paths = true;
300         visit::walk_pat(self, pat);
301         self.ignore_non_const_paths = false;
302     }
303
304     fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId) {
305         self.lookup_and_handle_definition(&id);
306         visit::walk_path(self, path);
307     }
308
309     fn visit_item(&mut self, _: &ast::Item) {
310         // Do not recurse into items. These items will be added to the
311         // worklist and recursed into manually if necessary.
312     }
313 }
314
315 fn has_allow_dead_code_or_lang_attr(attrs: &[ast::Attribute]) -> bool {
316     if attr::contains_name(attrs, "lang") {
317         return true;
318     }
319
320     let dead_code = lint::builtin::DEAD_CODE.name_lower();
321     for attr in lint::gather_attrs(attrs) {
322         match attr {
323             Ok((ref name, lint::Allow, _))
324                 if &name[..] == dead_code => return true,
325             _ => (),
326         }
327     }
328     false
329 }
330
331 // This visitor seeds items that
332 //   1) We want to explicitly consider as live:
333 //     * Item annotated with #[allow(dead_code)]
334 //         - This is done so that if we want to suppress warnings for a
335 //           group of dead functions, we only have to annotate the "root".
336 //           For example, if both `f` and `g` are dead and `f` calls `g`,
337 //           then annotating `f` with `#[allow(dead_code)]` will suppress
338 //           warning for both `f` and `g`.
339 //     * Item annotated with #[lang=".."]
340 //         - This is because lang items are always callable from elsewhere.
341 //   or
342 //   2) We are not sure to be live or not
343 //     * Implementation of a trait method
344 struct LifeSeeder {
345     worklist: Vec<ast::NodeId>
346 }
347
348 impl<'v> Visitor<'v> for LifeSeeder {
349     fn visit_item(&mut self, item: &ast::Item) {
350         let allow_dead_code = has_allow_dead_code_or_lang_attr(&item.attrs);
351         if allow_dead_code {
352             self.worklist.push(item.id);
353         }
354         match item.node {
355             ast::ItemEnum(ref enum_def, _) if allow_dead_code => {
356                 self.worklist.extend(enum_def.variants.iter().map(|variant| variant.node.id));
357             }
358             ast::ItemImpl(_, _, _, Some(ref _trait_ref), _, ref impl_items) => {
359                 for impl_item in impl_items {
360                     match *impl_item {
361                         ast::MethodImplItem(ref method) => {
362                             self.worklist.push(method.id);
363                         }
364                         ast::TypeImplItem(_) => {}
365                     }
366                 }
367             }
368             _ => ()
369         }
370         visit::walk_item(self, item);
371     }
372
373     fn visit_fn(&mut self, fk: visit::FnKind<'v>,
374                 _: &'v ast::FnDecl, block: &'v ast::Block,
375                 _: codemap::Span, id: ast::NodeId) {
376         // Check for method here because methods are not ast::Item
377         match fk {
378             visit::FkMethod(_, _, method) => {
379                 if has_allow_dead_code_or_lang_attr(&method.attrs) {
380                     self.worklist.push(id);
381                 }
382             }
383             _ => ()
384         }
385         visit::walk_block(self, block);
386     }
387 }
388
389 fn create_and_seed_worklist(tcx: &ty::ctxt,
390                             exported_items: &privacy::ExportedItems,
391                             reachable_symbols: &NodeSet,
392                             krate: &ast::Crate) -> Vec<ast::NodeId> {
393     let mut worklist = Vec::new();
394
395     // Preferably, we would only need to seed the worklist with reachable
396     // symbols. However, since the set of reachable symbols differs
397     // depending on whether a crate is built as bin or lib, and we want
398     // the warning to be consistent, we also seed the worklist with
399     // exported symbols.
400     for id in exported_items {
401         worklist.push(*id);
402     }
403     for id in reachable_symbols {
404         worklist.push(*id);
405     }
406
407     // Seed entry point
408     match *tcx.sess.entry_fn.borrow() {
409         Some((id, _)) => worklist.push(id),
410         None => ()
411     }
412
413     // Seed implemented trait methods
414     let mut life_seeder = LifeSeeder {
415         worklist: worklist
416     };
417     visit::walk_crate(&mut life_seeder, krate);
418
419     return life_seeder.worklist;
420 }
421
422 fn find_live(tcx: &ty::ctxt,
423              exported_items: &privacy::ExportedItems,
424              reachable_symbols: &NodeSet,
425              krate: &ast::Crate)
426              -> Box<HashSet<ast::NodeId>> {
427     let worklist = create_and_seed_worklist(tcx, exported_items,
428                                             reachable_symbols, krate);
429     let mut symbol_visitor = MarkSymbolVisitor::new(tcx, worklist);
430     symbol_visitor.mark_live_symbols();
431     symbol_visitor.live_symbols
432 }
433
434 fn get_struct_ctor_id(item: &ast::Item) -> Option<ast::NodeId> {
435     match item.node {
436         ast::ItemStruct(ref struct_def, _) => struct_def.ctor_id,
437         _ => None
438     }
439 }
440
441 struct DeadVisitor<'a, 'tcx: 'a> {
442     tcx: &'a ty::ctxt<'tcx>,
443     live_symbols: Box<HashSet<ast::NodeId>>,
444 }
445
446 impl<'a, 'tcx> DeadVisitor<'a, 'tcx> {
447     fn should_warn_about_item(&mut self, item: &ast::Item) -> bool {
448         let should_warn = match item.node {
449             ast::ItemStatic(..)
450             | ast::ItemConst(..)
451             | ast::ItemFn(..)
452             | ast::ItemEnum(..)
453             | ast::ItemStruct(..) => true,
454             _ => false
455         };
456         let ctor_id = get_struct_ctor_id(item);
457         should_warn && !self.symbol_is_live(item.id, ctor_id)
458     }
459
460     fn should_warn_about_field(&mut self, node: &ast::StructField_) -> bool {
461         let is_named = node.ident().is_some();
462         let field_type = ty::node_id_to_type(self.tcx, node.id);
463         let is_marker_field = match ty::ty_to_def_id(field_type) {
464             Some(def_id) => self.tcx.lang_items.items().any(|(_, item)| *item == Some(def_id)),
465             _ => false
466         };
467         is_named
468             && !self.symbol_is_live(node.id, None)
469             && !is_marker_field
470             && !has_allow_dead_code_or_lang_attr(&node.attrs)
471     }
472
473     fn should_warn_about_variant(&mut self, variant: &ast::Variant_) -> bool {
474         !self.symbol_is_live(variant.id, None)
475             && !has_allow_dead_code_or_lang_attr(&variant.attrs)
476     }
477
478     // id := node id of an item's definition.
479     // ctor_id := `Some` if the item is a struct_ctor (tuple struct),
480     //            `None` otherwise.
481     // If the item is a struct_ctor, then either its `id` or
482     // `ctor_id` (unwrapped) is in the live_symbols set. More specifically,
483     // DefMap maps the ExprPath of a struct_ctor to the node referred by
484     // `ctor_id`. On the other hand, in a statement like
485     // `type <ident> <generics> = <ty>;` where <ty> refers to a struct_ctor,
486     // DefMap maps <ty> to `id` instead.
487     fn symbol_is_live(&mut self, id: ast::NodeId,
488                       ctor_id: Option<ast::NodeId>) -> bool {
489         if self.live_symbols.contains(&id)
490            || ctor_id.map_or(false,
491                              |ctor| self.live_symbols.contains(&ctor)) {
492             return true;
493         }
494         // If it's a type whose methods are live, then it's live, too.
495         // This is done to handle the case where, for example, the static
496         // method of a private type is used, but the type itself is never
497         // called directly.
498         let impl_items = self.tcx.impl_items.borrow();
499         match self.tcx.inherent_impls.borrow().get(&local_def(id)) {
500             None => (),
501             Some(impl_list) => {
502                 for impl_did in &**impl_list {
503                     for item_did in &(*impl_items)[*impl_did] {
504                         if self.live_symbols.contains(&item_did.def_id()
505                                                                .node) {
506                             return true;
507                         }
508                     }
509                 }
510             }
511         }
512         false
513     }
514
515     fn warn_dead_code(&mut self,
516                       id: ast::NodeId,
517                       span: codemap::Span,
518                       ident: ast::Ident,
519                       node_type: &str) {
520         let name = ident.as_str();
521         if !name.starts_with("_") {
522             self.tcx
523                 .sess
524                 .add_lint(lint::builtin::DEAD_CODE,
525                           id,
526                           span,
527                           format!("{} is never used: `{}`", node_type, name));
528         }
529     }
530 }
531
532 impl<'a, 'tcx, 'v> Visitor<'v> for DeadVisitor<'a, 'tcx> {
533     fn visit_item(&mut self, item: &ast::Item) {
534         if self.should_warn_about_item(item) {
535             self.warn_dead_code(item.id, item.span, item.ident, item.node.descriptive_variant());
536         } else {
537             match item.node {
538                 ast::ItemEnum(ref enum_def, _) => {
539                     for variant in &enum_def.variants {
540                         if self.should_warn_about_variant(&variant.node) {
541                             self.warn_dead_code(variant.node.id, variant.span,
542                                                 variant.node.name, "variant");
543                         }
544                     }
545                 },
546                 _ => ()
547             }
548         }
549         visit::walk_item(self, item);
550     }
551
552     fn visit_foreign_item(&mut self, fi: &ast::ForeignItem) {
553         if !self.symbol_is_live(fi.id, None) {
554             self.warn_dead_code(fi.id, fi.span, fi.ident, fi.node.descriptive_variant());
555         }
556         visit::walk_foreign_item(self, fi);
557     }
558
559     fn visit_fn(&mut self, fk: visit::FnKind<'v>,
560                 _: &'v ast::FnDecl, block: &'v ast::Block,
561                 span: codemap::Span, id: ast::NodeId) {
562         // Have to warn method here because methods are not ast::Item
563         match fk {
564             visit::FkMethod(name, _, _) => {
565                 if !self.symbol_is_live(id, None) {
566                     self.warn_dead_code(id, span, name, "method");
567                 }
568             }
569             _ => ()
570         }
571         visit::walk_block(self, block);
572     }
573
574     fn visit_struct_field(&mut self, field: &ast::StructField) {
575         if self.should_warn_about_field(&field.node) {
576             self.warn_dead_code(field.node.id, field.span,
577                                 field.node.ident().unwrap(), "struct field");
578         }
579
580         visit::walk_struct_field(self, field);
581     }
582
583     // Overwrite so that we don't warn the trait method itself.
584     fn visit_trait_item(&mut self, trait_method: &ast::TraitItem) {
585         match *trait_method {
586             ast::ProvidedMethod(ref method) => {
587                 visit::walk_block(self, &*method.pe_body())
588             }
589             ast::RequiredMethod(_) => {}
590             ast::TypeTraitItem(_) => {}
591         }
592     }
593 }
594
595 pub fn check_crate(tcx: &ty::ctxt,
596                    exported_items: &privacy::ExportedItems,
597                    reachable_symbols: &NodeSet) {
598     let krate = tcx.map.krate();
599     let live_symbols = find_live(tcx, exported_items,
600                                  reachable_symbols, krate);
601     let mut visitor = DeadVisitor { tcx: tcx, live_symbols: live_symbols };
602     visit::walk_crate(&mut visitor, krate);
603 }