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