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