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