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