]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/dead.rs
Rollup merge of #41456 - jessicah:haiku-support, r=alexcrichton
[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 hir::map as hir_map;
16 use hir::{self, PatKind};
17 use hir::intravisit::{self, Visitor, NestedVisitorMap};
18 use hir::itemlikevisit::ItemLikeVisitor;
19
20 use middle::privacy;
21 use ty::{self, TyCtxt};
22 use hir::def::Def;
23 use hir::def_id::{DefId, LOCAL_CRATE};
24 use lint;
25 use util::nodemap::FxHashSet;
26
27 use syntax::{ast, codemap};
28 use syntax::attr;
29 use syntax_pos;
30
31 // Any local node that may call something in its body block should be
32 // explored. For example, if it's a live NodeItem that is a
33 // function, then we should explore its block to check for codes that
34 // may need to be marked as live.
35 fn should_explore<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
36                             node_id: ast::NodeId) -> bool {
37     match tcx.hir.find(node_id) {
38         Some(hir_map::NodeItem(..)) |
39         Some(hir_map::NodeImplItem(..)) |
40         Some(hir_map::NodeForeignItem(..)) |
41         Some(hir_map::NodeTraitItem(..)) =>
42             true,
43         _ =>
44             false
45     }
46 }
47
48 struct MarkSymbolVisitor<'a, 'tcx: 'a> {
49     worklist: Vec<ast::NodeId>,
50     tcx: TyCtxt<'a, 'tcx, 'tcx>,
51     tables: &'a ty::TypeckTables<'tcx>,
52     live_symbols: Box<FxHashSet<ast::NodeId>>,
53     struct_has_extern_repr: bool,
54     ignore_non_const_paths: bool,
55     inherited_pub_visibility: bool,
56     ignore_variant_stack: Vec<DefId>,
57 }
58
59 impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> {
60     fn check_def_id(&mut self, def_id: DefId) {
61         if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
62             if should_explore(self.tcx, node_id) {
63                 self.worklist.push(node_id);
64             }
65             self.live_symbols.insert(node_id);
66         }
67     }
68
69     fn insert_def_id(&mut self, def_id: DefId) {
70         if let Some(node_id) = self.tcx.hir.as_local_node_id(def_id) {
71             debug_assert!(!should_explore(self.tcx, node_id));
72             self.live_symbols.insert(node_id);
73         }
74     }
75
76     fn handle_definition(&mut self, def: Def) {
77         match def {
78             Def::Const(_) | Def::AssociatedConst(..) => {
79                 self.check_def_id(def.def_id());
80             }
81             _ if self.ignore_non_const_paths => (),
82             Def::PrimTy(..) | Def::SelfTy(..) => (),
83             Def::Variant(variant_id) | Def::VariantCtor(variant_id, ..) => {
84                 if let Some(enum_id) = self.tcx.parent_def_id(variant_id) {
85                     self.check_def_id(enum_id);
86                 }
87                 if !self.ignore_variant_stack.contains(&variant_id) {
88                     self.check_def_id(variant_id);
89                 }
90             }
91             _ => {
92                 self.check_def_id(def.def_id());
93             }
94         }
95     }
96
97     fn lookup_and_handle_method(&mut self, id: ast::NodeId) {
98         let method_call = ty::MethodCall::expr(id);
99         let method = self.tables.method_map[&method_call];
100         self.check_def_id(method.def_id);
101     }
102
103     fn handle_field_access(&mut self, lhs: &hir::Expr, name: ast::Name) {
104         match self.tables.expr_ty_adjusted(lhs).sty {
105             ty::TyAdt(def, _) => {
106                 self.insert_def_id(def.struct_variant().field_named(name).did);
107             }
108             _ => span_bug!(lhs.span, "named field access on non-ADT"),
109         }
110     }
111
112     fn handle_tup_field_access(&mut self, lhs: &hir::Expr, idx: usize) {
113         match self.tables.expr_ty_adjusted(lhs).sty {
114             ty::TyAdt(def, _) => {
115                 self.insert_def_id(def.struct_variant().fields[idx].did);
116             }
117             ty::TyTuple(..) => {}
118             _ => span_bug!(lhs.span, "numeric field access on non-ADT"),
119         }
120     }
121
122     fn handle_field_pattern_match(&mut self, lhs: &hir::Pat, def: Def,
123                                   pats: &[codemap::Spanned<hir::FieldPat>]) {
124         let variant = match self.tables.node_id_to_type(lhs.id).sty {
125             ty::TyAdt(adt, _) => adt.variant_of_def(def),
126             _ => span_bug!(lhs.span, "non-ADT in struct pattern")
127         };
128         for pat in pats {
129             if let PatKind::Wild = pat.node.pat.node {
130                 continue;
131             }
132             self.insert_def_id(variant.field_named(pat.node.name).did);
133         }
134     }
135
136     fn mark_live_symbols(&mut self) {
137         let mut scanned = FxHashSet();
138         while !self.worklist.is_empty() {
139             let id = self.worklist.pop().unwrap();
140             if scanned.contains(&id) {
141                 continue
142             }
143             scanned.insert(id);
144
145             if let Some(ref node) = self.tcx.hir.find(id) {
146                 self.live_symbols.insert(id);
147                 self.visit_node(node);
148             }
149         }
150     }
151
152     fn visit_node(&mut self, node: &hir_map::Node<'tcx>) {
153         let had_extern_repr = self.struct_has_extern_repr;
154         self.struct_has_extern_repr = false;
155         let had_inherited_pub_visibility = self.inherited_pub_visibility;
156         self.inherited_pub_visibility = false;
157         match *node {
158             hir_map::NodeItem(item) => {
159                 match item.node {
160                     hir::ItemStruct(..) | hir::ItemUnion(..) => {
161                         let def_id = self.tcx.hir.local_def_id(item.id);
162                         let def = self.tcx.adt_def(def_id);
163                         self.struct_has_extern_repr = def.repr.c();
164
165                         intravisit::walk_item(self, &item);
166                     }
167                     hir::ItemEnum(..) => {
168                         self.inherited_pub_visibility = item.vis == hir::Public;
169                         intravisit::walk_item(self, &item);
170                     }
171                     hir::ItemFn(..)
172                     | hir::ItemTy(..)
173                     | hir::ItemStatic(..)
174                     | hir::ItemConst(..) => {
175                         intravisit::walk_item(self, &item);
176                     }
177                     _ => ()
178                 }
179             }
180             hir_map::NodeTraitItem(trait_item) => {
181                 intravisit::walk_trait_item(self, trait_item);
182             }
183             hir_map::NodeImplItem(impl_item) => {
184                 intravisit::walk_impl_item(self, impl_item);
185             }
186             hir_map::NodeForeignItem(foreign_item) => {
187                 intravisit::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> Visitor<'tcx> for MarkSymbolVisitor<'a, 'tcx> {
197     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
198         NestedVisitorMap::None
199     }
200
201     fn visit_nested_body(&mut self, body: hir::BodyId) {
202         let old_tables = self.tables;
203         self.tables = self.tcx.body_tables(body);
204         let body = self.tcx.hir.body(body);
205         self.visit_body(body);
206         self.tables = old_tables;
207     }
208
209     fn visit_variant_data(&mut self, def: &'tcx hir::VariantData, _: ast::Name,
210                         _: &hir::Generics, _: ast::NodeId, _: syntax_pos::Span) {
211         let has_extern_repr = self.struct_has_extern_repr;
212         let inherited_pub_visibility = self.inherited_pub_visibility;
213         let live_fields = def.fields().iter().filter(|f| {
214             has_extern_repr || inherited_pub_visibility || f.vis == hir::Public
215         });
216         self.live_symbols.extend(live_fields.map(|f| f.id));
217
218         intravisit::walk_struct_def(self, def);
219     }
220
221     fn visit_expr(&mut self, expr: &'tcx hir::Expr) {
222         match expr.node {
223             hir::ExprPath(ref qpath @ hir::QPath::TypeRelative(..)) => {
224                 let def = self.tables.qpath_def(qpath, expr.id);
225                 self.handle_definition(def);
226             }
227             hir::ExprMethodCall(..) => {
228                 self.lookup_and_handle_method(expr.id);
229             }
230             hir::ExprField(ref lhs, ref name) => {
231                 self.handle_field_access(&lhs, name.node);
232             }
233             hir::ExprTupField(ref lhs, idx) => {
234                 self.handle_tup_field_access(&lhs, idx.node);
235             }
236             _ => ()
237         }
238
239         intravisit::walk_expr(self, expr);
240     }
241
242     fn visit_arm(&mut self, arm: &'tcx hir::Arm) {
243         if arm.pats.len() == 1 {
244             let variants = arm.pats[0].necessary_variants();
245
246             // Inside the body, ignore constructions of variants
247             // necessary for the pattern to match. Those construction sites
248             // can't be reached unless the variant is constructed elsewhere.
249             let len = self.ignore_variant_stack.len();
250             self.ignore_variant_stack.extend_from_slice(&variants);
251             intravisit::walk_arm(self, arm);
252             self.ignore_variant_stack.truncate(len);
253         } else {
254             intravisit::walk_arm(self, arm);
255         }
256     }
257
258     fn visit_pat(&mut self, pat: &'tcx hir::Pat) {
259         match pat.node {
260             PatKind::Struct(hir::QPath::Resolved(_, ref path), ref fields, _) => {
261                 self.handle_field_pattern_match(pat, path.def, fields);
262             }
263             PatKind::Path(ref qpath @ hir::QPath::TypeRelative(..)) => {
264                 let def = self.tables.qpath_def(qpath, pat.id);
265                 self.handle_definition(def);
266             }
267             _ => ()
268         }
269
270         self.ignore_non_const_paths = true;
271         intravisit::walk_pat(self, pat);
272         self.ignore_non_const_paths = false;
273     }
274
275     fn visit_path(&mut self, path: &'tcx hir::Path, _: ast::NodeId) {
276         self.handle_definition(path.def);
277         intravisit::walk_path(self, path);
278     }
279 }
280
281 fn has_allow_dead_code_or_lang_attr(attrs: &[ast::Attribute]) -> bool {
282     if attr::contains_name(attrs, "lang") {
283         return true;
284     }
285
286     let dead_code = lint::builtin::DEAD_CODE.name_lower();
287     for attr in lint::gather_attrs(attrs) {
288         match attr {
289             Ok((name, lint::Allow, _)) if name == &*dead_code => return true,
290             _ => (),
291         }
292     }
293     false
294 }
295
296 // This visitor seeds items that
297 //   1) We want to explicitly consider as live:
298 //     * Item annotated with #[allow(dead_code)]
299 //         - This is done so that if we want to suppress warnings for a
300 //           group of dead functions, we only have to annotate the "root".
301 //           For example, if both `f` and `g` are dead and `f` calls `g`,
302 //           then annotating `f` with `#[allow(dead_code)]` will suppress
303 //           warning for both `f` and `g`.
304 //     * Item annotated with #[lang=".."]
305 //         - This is because lang items are always callable from elsewhere.
306 //   or
307 //   2) We are not sure to be live or not
308 //     * Implementation of a trait method
309 struct LifeSeeder<'k> {
310     worklist: Vec<ast::NodeId>,
311     krate: &'k hir::Crate,
312 }
313
314 impl<'v, 'k> ItemLikeVisitor<'v> for LifeSeeder<'k> {
315     fn visit_item(&mut self, item: &hir::Item) {
316         let allow_dead_code = has_allow_dead_code_or_lang_attr(&item.attrs);
317         if allow_dead_code {
318             self.worklist.push(item.id);
319         }
320         match item.node {
321             hir::ItemEnum(ref enum_def, _) if allow_dead_code => {
322                 self.worklist.extend(enum_def.variants.iter()
323                                                       .map(|variant| variant.node.data.id()));
324             }
325             hir::ItemTrait(.., ref trait_item_refs) => {
326                 for trait_item_ref in trait_item_refs {
327                     let trait_item = self.krate.trait_item(trait_item_ref.id);
328                     match trait_item.node {
329                         hir::TraitItemKind::Const(_, Some(_)) |
330                         hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(_)) => {
331                             if has_allow_dead_code_or_lang_attr(&trait_item.attrs) {
332                                 self.worklist.push(trait_item.id);
333                             }
334                         }
335                         _ => {}
336                     }
337                 }
338             }
339             hir::ItemImpl(.., ref opt_trait, _, ref impl_item_refs) => {
340                 for impl_item_ref in impl_item_refs {
341                     let impl_item = self.krate.impl_item(impl_item_ref.id);
342                     if opt_trait.is_some() ||
343                             has_allow_dead_code_or_lang_attr(&impl_item.attrs) {
344                         self.worklist.push(impl_item_ref.id.node_id);
345                     }
346                 }
347             }
348             _ => ()
349         }
350     }
351
352     fn visit_trait_item(&mut self, _item: &hir::TraitItem) {
353         // ignore: we are handling this in `visit_item` above
354     }
355
356     fn visit_impl_item(&mut self, _item: &hir::ImplItem) {
357         // ignore: we are handling this in `visit_item` above
358     }
359 }
360
361 fn create_and_seed_worklist<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
362                                       access_levels: &privacy::AccessLevels,
363                                       krate: &hir::Crate)
364                                       -> Vec<ast::NodeId> {
365     let mut worklist = Vec::new();
366     for (id, _) in &access_levels.map {
367         worklist.push(*id);
368     }
369
370     // Seed entry point
371     if let Some((id, _)) = *tcx.sess.entry_fn.borrow() {
372         worklist.push(id);
373     }
374
375     // Seed implemented trait items
376     let mut life_seeder = LifeSeeder {
377         worklist: worklist,
378         krate: krate,
379     };
380     krate.visit_all_item_likes(&mut life_seeder);
381
382     return life_seeder.worklist;
383 }
384
385 fn find_live<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
386                        access_levels: &privacy::AccessLevels,
387                        krate: &hir::Crate)
388                        -> Box<FxHashSet<ast::NodeId>> {
389     let worklist = create_and_seed_worklist(tcx, access_levels, krate);
390     let mut symbol_visitor = MarkSymbolVisitor {
391         worklist: worklist,
392         tcx: tcx,
393         tables: &ty::TypeckTables::empty(),
394         live_symbols: box FxHashSet(),
395         struct_has_extern_repr: false,
396         ignore_non_const_paths: false,
397         inherited_pub_visibility: false,
398         ignore_variant_stack: vec![],
399     };
400     symbol_visitor.mark_live_symbols();
401     symbol_visitor.live_symbols
402 }
403
404 fn get_struct_ctor_id(item: &hir::Item) -> Option<ast::NodeId> {
405     match item.node {
406         hir::ItemStruct(ref struct_def, _) if !struct_def.is_struct() => {
407             Some(struct_def.id())
408         }
409         _ => None
410     }
411 }
412
413 struct DeadVisitor<'a, 'tcx: 'a> {
414     tcx: TyCtxt<'a, 'tcx, 'tcx>,
415     live_symbols: Box<FxHashSet<ast::NodeId>>,
416 }
417
418 impl<'a, 'tcx> DeadVisitor<'a, 'tcx> {
419     fn should_warn_about_item(&mut self, item: &hir::Item) -> bool {
420         let should_warn = match item.node {
421             hir::ItemStatic(..)
422             | hir::ItemConst(..)
423             | hir::ItemFn(..)
424             | hir::ItemTy(..)
425             | hir::ItemEnum(..)
426             | hir::ItemStruct(..)
427             | hir::ItemUnion(..) => true,
428             _ => false
429         };
430         let ctor_id = get_struct_ctor_id(item);
431         should_warn && !self.symbol_is_live(item.id, ctor_id)
432     }
433
434     fn should_warn_about_field(&mut self, field: &hir::StructField) -> bool {
435         let field_type = self.tcx.type_of(self.tcx.hir.local_def_id(field.id));
436         let is_marker_field = match field_type.ty_to_def_id() {
437             Some(def_id) => self.tcx.lang_items.items().iter().any(|item| *item == Some(def_id)),
438             _ => false
439         };
440         !field.is_positional()
441             && !self.symbol_is_live(field.id, None)
442             && !is_marker_field
443             && !has_allow_dead_code_or_lang_attr(&field.attrs)
444     }
445
446     fn should_warn_about_variant(&mut self, variant: &hir::Variant_) -> bool {
447         !self.symbol_is_live(variant.data.id(), None)
448             && !has_allow_dead_code_or_lang_attr(&variant.attrs)
449     }
450
451     fn should_warn_about_foreign_item(&mut self, fi: &hir::ForeignItem) -> bool {
452         !self.symbol_is_live(fi.id, None)
453             && !has_allow_dead_code_or_lang_attr(&fi.attrs)
454     }
455
456     // id := node id of an item's definition.
457     // ctor_id := `Some` if the item is a struct_ctor (tuple struct),
458     //            `None` otherwise.
459     // If the item is a struct_ctor, then either its `id` or
460     // `ctor_id` (unwrapped) is in the live_symbols set. More specifically,
461     // DefMap maps the ExprPath of a struct_ctor to the node referred by
462     // `ctor_id`. On the other hand, in a statement like
463     // `type <ident> <generics> = <ty>;` where <ty> refers to a struct_ctor,
464     // DefMap maps <ty> to `id` instead.
465     fn symbol_is_live(&mut self,
466                       id: ast::NodeId,
467                       ctor_id: Option<ast::NodeId>)
468                       -> bool {
469         if self.live_symbols.contains(&id)
470            || ctor_id.map_or(false,
471                              |ctor| self.live_symbols.contains(&ctor)) {
472             return true;
473         }
474         // If it's a type whose items are live, then it's live, too.
475         // This is done to handle the case where, for example, the static
476         // method of a private type is used, but the type itself is never
477         // called directly.
478         if let Some(impl_list) =
479                 self.tcx.maps.inherent_impls.borrow().get(&self.tcx.hir.local_def_id(id)) {
480             for &impl_did in impl_list.iter() {
481                 for &item_did in &self.tcx.associated_item_def_ids(impl_did)[..] {
482                     if let Some(item_node_id) = self.tcx.hir.as_local_node_id(item_did) {
483                         if self.live_symbols.contains(&item_node_id) {
484                             return true;
485                         }
486                     }
487                 }
488             }
489         }
490         false
491     }
492
493     fn warn_dead_code(&mut self,
494                       id: ast::NodeId,
495                       span: syntax_pos::Span,
496                       name: ast::Name,
497                       node_type: &str) {
498         if !name.as_str().starts_with("_") {
499             self.tcx
500                 .sess
501                 .add_lint(lint::builtin::DEAD_CODE,
502                           id,
503                           span,
504                           format!("{} is never used: `{}`", node_type, name));
505         }
506     }
507 }
508
509 impl<'a, 'tcx> Visitor<'tcx> for DeadVisitor<'a, 'tcx> {
510     /// Walk nested items in place so that we don't report dead-code
511     /// on inner functions when the outer function is already getting
512     /// an error. We could do this also by checking the parents, but
513     /// this is how the code is setup and it seems harmless enough.
514     fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'tcx> {
515         NestedVisitorMap::All(&self.tcx.hir)
516     }
517
518     fn visit_item(&mut self, item: &'tcx hir::Item) {
519         if self.should_warn_about_item(item) {
520             self.warn_dead_code(
521                 item.id,
522                 item.span,
523                 item.name,
524                 item.node.descriptive_variant()
525             );
526         } else {
527             // Only continue if we didn't warn
528             intravisit::walk_item(self, item);
529         }
530     }
531
532     fn visit_variant(&mut self,
533                      variant: &'tcx hir::Variant,
534                      g: &'tcx hir::Generics,
535                      id: ast::NodeId) {
536         if self.should_warn_about_variant(&variant.node) {
537             self.warn_dead_code(variant.node.data.id(), variant.span,
538                                 variant.node.name, "variant");
539         } else {
540             intravisit::walk_variant(self, variant, g, id);
541         }
542     }
543
544     fn visit_foreign_item(&mut self, fi: &'tcx hir::ForeignItem) {
545         if self.should_warn_about_foreign_item(fi) {
546             self.warn_dead_code(fi.id, fi.span, fi.name, fi.node.descriptive_variant());
547         }
548         intravisit::walk_foreign_item(self, fi);
549     }
550
551     fn visit_struct_field(&mut self, field: &'tcx hir::StructField) {
552         if self.should_warn_about_field(&field) {
553             self.warn_dead_code(field.id, field.span,
554                                 field.name, "field");
555         }
556
557         intravisit::walk_struct_field(self, field);
558     }
559
560     fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
561         match impl_item.node {
562             hir::ImplItemKind::Const(_, body_id) => {
563                 if !self.symbol_is_live(impl_item.id, None) {
564                     self.warn_dead_code(impl_item.id, impl_item.span,
565                                         impl_item.name, "associated const");
566                 }
567                 self.visit_nested_body(body_id)
568             }
569             hir::ImplItemKind::Method(_, body_id) => {
570                 if !self.symbol_is_live(impl_item.id, None) {
571                     self.warn_dead_code(impl_item.id, impl_item.span,
572                                         impl_item.name, "method");
573                 }
574                 self.visit_nested_body(body_id)
575             }
576             hir::ImplItemKind::Type(..) => {}
577         }
578     }
579
580     // Overwrite so that we don't warn the trait item itself.
581     fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
582         match trait_item.node {
583             hir::TraitItemKind::Const(_, Some(body_id)) |
584             hir::TraitItemKind::Method(_, hir::TraitMethod::Provided(body_id)) => {
585                 self.visit_nested_body(body_id)
586             }
587             hir::TraitItemKind::Const(_, None) |
588             hir::TraitItemKind::Method(_, hir::TraitMethod::Required(_)) |
589             hir::TraitItemKind::Type(..) => {}
590         }
591     }
592 }
593
594 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
595     let access_levels = &tcx.privacy_access_levels(LOCAL_CRATE);
596     let krate = tcx.hir.krate();
597     let live_symbols = find_live(tcx, access_levels, krate);
598     let mut visitor = DeadVisitor { tcx: tcx, live_symbols: live_symbols };
599     intravisit::walk_crate(&mut visitor, krate);
600 }