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