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