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