]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/dead.rs
Simplify PatIdent to contain an Ident rather than a Path
[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 middle::def;
16 use lint;
17 use middle::privacy;
18 use middle::ty;
19 use middle::typeck;
20 use util::nodemap::NodeSet;
21
22 use std::collections::HashSet;
23 use syntax::ast;
24 use syntax::ast_map;
25 use syntax::ast_util::{local_def, is_local};
26 use syntax::attr::AttrMetaMethods;
27 use syntax::attr;
28 use syntax::codemap;
29 use syntax::parse::token;
30 use syntax::visit::Visitor;
31 use syntax::visit;
32
33 // Any local node that may call something in its body block should be
34 // explored. For example, if it's a live NodeItem that is a
35 // function, then we should explore its block to check for codes that
36 // may need to be marked as live.
37 fn should_explore(tcx: &ty::ctxt, def_id: ast::DefId) -> bool {
38     if !is_local(def_id) {
39         return false;
40     }
41
42     match tcx.map.find(def_id.node) {
43         Some(ast_map::NodeItem(..))
44         | Some(ast_map::NodeMethod(..))
45         | Some(ast_map::NodeForeignItem(..))
46         | Some(ast_map::NodeTraitMethod(..)) => true,
47         _ => false
48     }
49 }
50
51 struct MarkSymbolVisitor<'a> {
52     worklist: Vec<ast::NodeId>,
53     tcx: &'a ty::ctxt,
54     live_symbols: Box<HashSet<ast::NodeId>>,
55 }
56
57 #[deriving(Clone)]
58 struct MarkSymbolVisitorContext {
59     struct_has_extern_repr: bool
60 }
61
62 impl<'a> MarkSymbolVisitor<'a> {
63     fn new(tcx: &'a ty::ctxt,
64            worklist: Vec<ast::NodeId>) -> MarkSymbolVisitor<'a> {
65         MarkSymbolVisitor {
66             worklist: worklist,
67             tcx: tcx,
68             live_symbols: box HashSet::new(),
69         }
70     }
71
72     fn check_def_id(&mut self, def_id: ast::DefId) {
73         if should_explore(self.tcx, def_id) {
74             self.worklist.push(def_id.node);
75         }
76         self.live_symbols.insert(def_id.node);
77     }
78
79     fn lookup_and_handle_definition(&mut self, id: &ast::NodeId) {
80         let def = match self.tcx.def_map.borrow().find(id) {
81             Some(&def) => def,
82             None => return
83         };
84         let def_id = match def {
85             def::DefVariant(enum_id, _, _) => Some(enum_id),
86             def::DefPrimTy(_) => None,
87             _ => Some(def.def_id())
88         };
89         match def_id {
90             Some(def_id) => self.check_def_id(def_id),
91             None => (),
92         }
93     }
94
95     fn lookup_and_handle_method(&mut self, id: ast::NodeId,
96                                 span: codemap::Span) {
97         let method_call = typeck::MethodCall::expr(id);
98         match self.tcx.method_map.borrow().find(&method_call) {
99             Some(method) => {
100                 match method.origin {
101                     typeck::MethodStatic(def_id) => {
102                         match ty::provided_source(self.tcx, def_id) {
103                             Some(p_did) => self.check_def_id(p_did),
104                             None => self.check_def_id(def_id)
105                         }
106                     }
107                     typeck::MethodParam(typeck::MethodParam {
108                         trait_id: trait_id,
109                         method_num: index,
110                         ..
111                     })
112                     | typeck::MethodObject(typeck::MethodObject {
113                         trait_id: trait_id,
114                         method_num: index,
115                         ..
116                     }) => {
117                         let def_id = ty::trait_method(self.tcx,
118                                                       trait_id, index).def_id;
119                         self.check_def_id(def_id);
120                     }
121                 }
122             }
123             None => {
124                 self.tcx.sess.span_bug(span,
125                                        "method call expression not \
126                                         in method map?!")
127             }
128         }
129     }
130
131     fn handle_field_access(&mut self, lhs: &ast::Expr, name: &ast::Ident) {
132         match ty::get(ty::expr_ty_adjusted(self.tcx, lhs)).sty {
133             ty::ty_struct(id, _) => {
134                 let fields = ty::lookup_struct_fields(self.tcx, id);
135                 let field_id = fields.iter()
136                     .find(|field| field.name == name.name).unwrap().id;
137                 self.live_symbols.insert(field_id.node);
138             },
139             _ => ()
140         }
141     }
142
143     fn handle_field_pattern_match(&mut self, lhs: &ast::Pat, pats: &[ast::FieldPat]) {
144         match self.tcx.def_map.borrow().get(&lhs.id) {
145             &def::DefStruct(id) | &def::DefVariant(_, id, _) => {
146                 let fields = ty::lookup_struct_fields(self.tcx, id);
147                 for pat in pats.iter() {
148                     let field_id = fields.iter()
149                         .find(|field| field.name == pat.ident.name).unwrap().id;
150                     self.live_symbols.insert(field_id.node);
151                 }
152             }
153             _ => ()
154         }
155     }
156
157     fn mark_live_symbols(&mut self) {
158         let mut scanned = HashSet::new();
159         while self.worklist.len() > 0 {
160             let id = self.worklist.pop().unwrap();
161             if scanned.contains(&id) {
162                 continue
163             }
164             scanned.insert(id);
165
166             match self.tcx.map.find(id) {
167                 Some(ref node) => {
168                     self.live_symbols.insert(id);
169                     self.visit_node(node);
170                 }
171                 None => (),
172             }
173         }
174     }
175
176     fn visit_node(&mut self, node: &ast_map::Node) {
177         let ctxt = MarkSymbolVisitorContext {
178             struct_has_extern_repr: false
179         };
180         match *node {
181             ast_map::NodeItem(item) => {
182                 match item.node {
183                     ast::ItemStruct(..) => {
184                         let has_extern_repr = item.attrs.iter().fold(attr::ReprAny, |acc, attr| {
185                             attr::find_repr_attr(self.tcx.sess.diagnostic(), attr, acc)
186                         }) == attr::ReprExtern;
187
188                         visit::walk_item(self, &*item, MarkSymbolVisitorContext {
189                             struct_has_extern_repr: has_extern_repr,
190                             ..(ctxt)
191                         });
192                     }
193                     ast::ItemFn(..)
194                     | ast::ItemEnum(..)
195                     | ast::ItemTy(..)
196                     | ast::ItemStatic(..) => {
197                         visit::walk_item(self, &*item, ctxt);
198                     }
199                     _ => ()
200                 }
201             }
202             ast_map::NodeTraitMethod(trait_method) => {
203                 visit::walk_trait_method(self, &*trait_method, ctxt);
204             }
205             ast_map::NodeMethod(method) => {
206                 visit::walk_block(self, &*method.body, ctxt);
207             }
208             ast_map::NodeForeignItem(foreign_item) => {
209                 visit::walk_foreign_item(self, &*foreign_item, ctxt);
210             }
211             _ => ()
212         }
213     }
214 }
215
216 impl<'a> Visitor<MarkSymbolVisitorContext> for MarkSymbolVisitor<'a> {
217
218     fn visit_struct_def(&mut self, def: &ast::StructDef, _: ast::Ident, _: &ast::Generics,
219                         _: ast::NodeId, ctxt: MarkSymbolVisitorContext) {
220         let live_fields = def.fields.iter().filter(|f| {
221             ctxt.struct_has_extern_repr || match f.node.kind {
222                 ast::NamedField(_, ast::Public) => true,
223                 _ => false
224             }
225         });
226         self.live_symbols.extend(live_fields.map(|f| f.node.id));
227
228         visit::walk_struct_def(self, def, ctxt);
229     }
230
231     fn visit_expr(&mut self, expr: &ast::Expr, ctxt: MarkSymbolVisitorContext) {
232         match expr.node {
233             ast::ExprMethodCall(..) => {
234                 self.lookup_and_handle_method(expr.id, expr.span);
235             }
236             ast::ExprField(ref lhs, ref ident, _) => {
237                 self.handle_field_access(&**lhs, &ident.node);
238             }
239             _ => ()
240         }
241
242         visit::walk_expr(self, expr, ctxt);
243     }
244
245     fn visit_pat(&mut self, pat: &ast::Pat, ctxt: MarkSymbolVisitorContext) {
246         match pat.node {
247             ast::PatStruct(_, ref fields, _) => {
248                 self.handle_field_pattern_match(pat, fields.as_slice());
249             }
250             ast::PatIdent(_, _, _) => {
251                 // it might be the only use of a static:
252                 self.lookup_and_handle_definition(&pat.id)
253             }
254             _ => ()
255         }
256
257         visit::walk_pat(self, pat, ctxt);
258     }
259
260     fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId, ctxt: MarkSymbolVisitorContext) {
261         self.lookup_and_handle_definition(&id);
262         visit::walk_path(self, path, ctxt);
263     }
264
265     fn visit_item(&mut self, _: &ast::Item, _: MarkSymbolVisitorContext) {
266         // Do not recurse into items. These items will be added to the
267         // worklist and recursed into manually if necessary.
268     }
269 }
270
271 fn has_allow_dead_code_or_lang_attr(attrs: &[ast::Attribute]) -> bool {
272     if attr::contains_name(attrs.as_slice(), "lang") {
273         return true;
274     }
275
276     let dead_code = lint::builtin::DEAD_CODE.name_lower();
277     for attr in lint::gather_attrs(attrs).move_iter() {
278         match attr {
279             Ok((ref name, lint::Allow, _))
280                 if name.get() == dead_code.as_slice() => return true,
281             _ => (),
282         }
283     }
284     false
285 }
286
287 // This visitor seeds items that
288 //   1) We want to explicitly consider as live:
289 //     * Item annotated with #[allow(dead_code)]
290 //         - This is done so that if we want to suppress warnings for a
291 //           group of dead functions, we only have to annotate the "root".
292 //           For example, if both `f` and `g` are dead and `f` calls `g`,
293 //           then annotating `f` with `#[allow(dead_code)]` will suppress
294 //           warning for both `f` and `g`.
295 //     * Item annotated with #[lang=".."]
296 //         - This is because lang items are always callable from elsewhere.
297 //   or
298 //   2) We are not sure to be live or not
299 //     * Implementation of a trait method
300 struct LifeSeeder {
301     worklist: Vec<ast::NodeId> ,
302 }
303
304 impl Visitor<()> for LifeSeeder {
305     fn visit_item(&mut self, item: &ast::Item, _: ()) {
306         if has_allow_dead_code_or_lang_attr(item.attrs.as_slice()) {
307             self.worklist.push(item.id);
308         }
309         match item.node {
310             ast::ItemImpl(_, Some(ref _trait_ref), _, ref methods) => {
311                 for method in methods.iter() {
312                     self.worklist.push(method.id);
313                 }
314             }
315             _ => ()
316         }
317         visit::walk_item(self, item, ());
318     }
319
320     fn visit_fn(&mut self, fk: &visit::FnKind,
321                 _: &ast::FnDecl, block: &ast::Block,
322                 _: codemap::Span, id: ast::NodeId, _: ()) {
323         // Check for method here because methods are not ast::Item
324         match *fk {
325             visit::FkMethod(_, _, method) => {
326                 if has_allow_dead_code_or_lang_attr(method.attrs.as_slice()) {
327                     self.worklist.push(id);
328                 }
329             }
330             _ => ()
331         }
332         visit::walk_block(self, block, ());
333     }
334 }
335
336 fn create_and_seed_worklist(tcx: &ty::ctxt,
337                             exported_items: &privacy::ExportedItems,
338                             reachable_symbols: &NodeSet,
339                             krate: &ast::Crate) -> Vec<ast::NodeId> {
340     let mut worklist = Vec::new();
341
342     // Preferably, we would only need to seed the worklist with reachable
343     // symbols. However, since the set of reachable symbols differs
344     // depending on whether a crate is built as bin or lib, and we want
345     // the warning to be consistent, we also seed the worklist with
346     // exported symbols.
347     for &id in exported_items.iter() {
348         worklist.push(id);
349     }
350     for &id in reachable_symbols.iter() {
351         worklist.push(id);
352     }
353
354     // Seed entry point
355     match *tcx.sess.entry_fn.borrow() {
356         Some((id, _)) => worklist.push(id),
357         None => ()
358     }
359
360     // Seed implemented trait methods
361     let mut life_seeder = LifeSeeder {
362         worklist: worklist
363     };
364     visit::walk_crate(&mut life_seeder, krate, ());
365
366     return life_seeder.worklist;
367 }
368
369 fn find_live(tcx: &ty::ctxt,
370              exported_items: &privacy::ExportedItems,
371              reachable_symbols: &NodeSet,
372              krate: &ast::Crate)
373              -> Box<HashSet<ast::NodeId>> {
374     let worklist = create_and_seed_worklist(tcx, exported_items,
375                                             reachable_symbols, krate);
376     let mut symbol_visitor = MarkSymbolVisitor::new(tcx, worklist);
377     symbol_visitor.mark_live_symbols();
378     symbol_visitor.live_symbols
379 }
380
381 fn should_warn(item: &ast::Item) -> bool {
382     match item.node {
383         ast::ItemStatic(..)
384         | ast::ItemFn(..)
385         | ast::ItemEnum(..)
386         | ast::ItemStruct(..) => true,
387         _ => false
388     }
389 }
390
391 fn get_struct_ctor_id(item: &ast::Item) -> Option<ast::NodeId> {
392     match item.node {
393         ast::ItemStruct(struct_def, _) => struct_def.ctor_id,
394         _ => None
395     }
396 }
397
398 struct DeadVisitor<'a> {
399     tcx: &'a ty::ctxt,
400     live_symbols: Box<HashSet<ast::NodeId>>,
401 }
402
403 impl<'a> DeadVisitor<'a> {
404     fn should_warn_about_field(&mut self, node: &ast::StructField_) -> bool {
405         let (is_named, has_leading_underscore) = match node.ident() {
406             Some(ref ident) => (true, token::get_ident(*ident).get().as_bytes()[0] == ('_' as u8)),
407             _ => (false, false)
408         };
409         let field_type = ty::node_id_to_type(self.tcx, node.id);
410         let is_marker_field = match ty::ty_to_def_id(field_type) {
411             Some(def_id) => self.tcx.lang_items.items().any(|(_, item)| *item == Some(def_id)),
412             _ => false
413         };
414         is_named
415             && !self.symbol_is_live(node.id, None)
416             && !has_leading_underscore
417             && !is_marker_field
418             && !has_allow_dead_code_or_lang_attr(node.attrs.as_slice())
419     }
420
421     // id := node id of an item's definition.
422     // ctor_id := `Some` if the item is a struct_ctor (tuple struct),
423     //            `None` otherwise.
424     // If the item is a struct_ctor, then either its `id` or
425     // `ctor_id` (unwrapped) is in the live_symbols set. More specifically,
426     // DefMap maps the ExprPath of a struct_ctor to the node referred by
427     // `ctor_id`. On the other hand, in a statement like
428     // `type <ident> <generics> = <ty>;` where <ty> refers to a struct_ctor,
429     // DefMap maps <ty> to `id` instead.
430     fn symbol_is_live(&mut self, id: ast::NodeId,
431                       ctor_id: Option<ast::NodeId>) -> bool {
432         if self.live_symbols.contains(&id)
433            || ctor_id.map_or(false,
434                              |ctor| self.live_symbols.contains(&ctor)) {
435             return true;
436         }
437         // If it's a type whose methods are live, then it's live, too.
438         // This is done to handle the case where, for example, the static
439         // method of a private type is used, but the type itself is never
440         // called directly.
441         let impl_methods = self.tcx.impl_methods.borrow();
442         match self.tcx.inherent_impls.borrow().find(&local_def(id)) {
443             None => (),
444             Some(impl_list) => {
445                 for impl_did in impl_list.borrow().iter() {
446                     for method_did in impl_methods.get(impl_did).iter() {
447                         if self.live_symbols.contains(&method_did.node) {
448                             return true;
449                         }
450                     }
451                 }
452             }
453         }
454         false
455     }
456
457     fn warn_dead_code(&mut self,
458                       id: ast::NodeId,
459                       span: codemap::Span,
460                       ident: ast::Ident) {
461         self.tcx
462             .sess
463             .add_lint(lint::builtin::DEAD_CODE,
464                       id,
465                       span,
466                       format!("code is never used: `{}`",
467                               token::get_ident(ident)));
468     }
469 }
470
471 impl<'a> Visitor<()> for DeadVisitor<'a> {
472     fn visit_item(&mut self, item: &ast::Item, _: ()) {
473         let ctor_id = get_struct_ctor_id(item);
474         if !self.symbol_is_live(item.id, ctor_id) && should_warn(item) {
475             self.warn_dead_code(item.id, item.span, item.ident);
476         }
477         visit::walk_item(self, item, ());
478     }
479
480     fn visit_foreign_item(&mut self, fi: &ast::ForeignItem, _: ()) {
481         if !self.symbol_is_live(fi.id, None) {
482             self.warn_dead_code(fi.id, fi.span, fi.ident);
483         }
484         visit::walk_foreign_item(self, fi, ());
485     }
486
487     fn visit_fn(&mut self, fk: &visit::FnKind,
488                 _: &ast::FnDecl, block: &ast::Block,
489                 span: codemap::Span, id: ast::NodeId, _: ()) {
490         // Have to warn method here because methods are not ast::Item
491         match *fk {
492             visit::FkMethod(..) => {
493                 let ident = visit::name_of_fn(fk);
494                 if !self.symbol_is_live(id, None) {
495                     self.warn_dead_code(id, span, ident);
496                 }
497             }
498             _ => ()
499         }
500         visit::walk_block(self, block, ());
501     }
502
503     fn visit_struct_field(&mut self, field: &ast::StructField, _: ()) {
504         if self.should_warn_about_field(&field.node) {
505             self.warn_dead_code(field.node.id, field.span, field.node.ident().unwrap());
506         }
507
508         visit::walk_struct_field(self, field, ());
509     }
510
511     // Overwrite so that we don't warn the trait method itself.
512     fn visit_trait_method(&mut self, trait_method: &ast::TraitMethod, _: ()) {
513         match *trait_method {
514             ast::Provided(ref method) => visit::walk_block(self, &*method.body, ()),
515             ast::Required(_) => ()
516         }
517     }
518 }
519
520 pub fn check_crate(tcx: &ty::ctxt,
521                    exported_items: &privacy::ExportedItems,
522                    reachable_symbols: &NodeSet,
523                    krate: &ast::Crate) {
524     let live_symbols = find_live(tcx, exported_items,
525                                  reachable_symbols, krate);
526     let mut visitor = DeadVisitor { tcx: tcx, live_symbols: live_symbols };
527     visit::walk_crate(&mut visitor, krate, ());
528 }