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