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