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.
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.
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.
15 use dep_graph::DepNode;
16 use hir::map as ast_map;
17 use hir::{self, pat_util, PatKind};
18 use hir::intravisit::{self, Visitor};
19 use hir::itemlikevisit::ItemLikeVisitor;
22 use ty::{self, TyCtxt};
24 use hir::def_id::{DefId};
26 use util::nodemap::FxHashSet;
28 use syntax::{ast, codemap};
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<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
37 node_id: ast::NodeId) -> bool {
38 match tcx.map.find(node_id) {
39 Some(ast_map::NodeItem(..)) |
40 Some(ast_map::NodeImplItem(..)) |
41 Some(ast_map::NodeForeignItem(..)) |
42 Some(ast_map::NodeTraitItem(..)) =>
49 struct MarkSymbolVisitor<'a, 'tcx: 'a> {
50 worklist: Vec<ast::NodeId>,
51 tcx: TyCtxt<'a, 'tcx, '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>,
59 impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> {
60 fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
61 worklist: Vec<ast::NodeId>) -> MarkSymbolVisitor<'a, 'tcx> {
65 live_symbols: box FxHashSet(),
66 struct_has_extern_repr: false,
67 ignore_non_const_paths: false,
68 inherited_pub_visibility: false,
69 ignore_variant_stack: vec![],
73 fn check_def_id(&mut self, def_id: DefId) {
74 if let Some(node_id) = self.tcx.map.as_local_node_id(def_id) {
75 if should_explore(self.tcx, node_id) {
76 self.worklist.push(node_id);
78 self.live_symbols.insert(node_id);
82 fn insert_def_id(&mut self, def_id: DefId) {
83 if let Some(node_id) = self.tcx.map.as_local_node_id(def_id) {
84 debug_assert!(!should_explore(self.tcx, node_id));
85 self.live_symbols.insert(node_id);
89 fn lookup_and_handle_definition(&mut self, id: ast::NodeId) {
90 let def = self.tcx.expect_def(id);
92 // If `bar` is a trait item, make sure to mark Foo as alive in `Foo::bar`
94 Def::AssociatedTy(..) | Def::Method(_) | Def::AssociatedConst(_)
95 if self.tcx.trait_of_item(def.def_id()).is_some() => {
96 if let Some(substs) = self.tcx.tables().item_substs.get(&id) {
97 if let ty::TyAdt(tyid, _) = substs.substs.type_at(0).sty {
98 self.check_def_id(tyid.did);
106 Def::Const(_) | Def::AssociatedConst(..) => {
107 self.check_def_id(def.def_id());
109 _ if self.ignore_non_const_paths => (),
110 Def::PrimTy(..) | Def::SelfTy(..) => (),
111 Def::Variant(variant_id) | Def::VariantCtor(variant_id, ..) => {
112 if let Some(enum_id) = self.tcx.parent_def_id(variant_id) {
113 self.check_def_id(enum_id);
115 if !self.ignore_variant_stack.contains(&variant_id) {
116 self.check_def_id(variant_id);
120 self.check_def_id(def.def_id());
125 fn lookup_and_handle_method(&mut self, id: ast::NodeId) {
126 let method_call = ty::MethodCall::expr(id);
127 let method = self.tcx.tables().method_map[&method_call];
128 self.check_def_id(method.def_id);
131 fn handle_field_access(&mut self, lhs: &hir::Expr, name: ast::Name) {
132 match self.tcx.tables().expr_ty_adjusted(lhs).sty {
133 ty::TyAdt(def, _) => {
134 self.insert_def_id(def.struct_variant().field_named(name).did);
136 _ => span_bug!(lhs.span, "named field access on non-ADT"),
140 fn handle_tup_field_access(&mut self, lhs: &hir::Expr, idx: usize) {
141 match self.tcx.tables().expr_ty_adjusted(lhs).sty {
142 ty::TyAdt(def, _) => {
143 self.insert_def_id(def.struct_variant().fields[idx].did);
145 ty::TyTuple(..) => {}
146 _ => span_bug!(lhs.span, "numeric field access on non-ADT"),
150 fn handle_field_pattern_match(&mut self, lhs: &hir::Pat,
151 pats: &[codemap::Spanned<hir::FieldPat>]) {
152 let variant = match self.tcx.tables().node_id_to_type(lhs.id).sty {
153 ty::TyAdt(adt, _) => {
154 adt.variant_of_def(self.tcx.expect_def(lhs.id))
156 _ => span_bug!(lhs.span, "non-ADT in struct pattern")
159 if let PatKind::Wild = pat.node.pat.node {
162 self.insert_def_id(variant.field_named(pat.node.name).did);
166 fn mark_live_symbols(&mut self) {
167 let mut scanned = FxHashSet();
168 while !self.worklist.is_empty() {
169 let id = self.worklist.pop().unwrap();
170 if scanned.contains(&id) {
175 if let Some(ref node) = self.tcx.map.find(id) {
176 self.live_symbols.insert(id);
177 self.visit_node(node);
182 fn visit_node(&mut self, node: &ast_map::Node) {
183 let had_extern_repr = self.struct_has_extern_repr;
184 self.struct_has_extern_repr = false;
185 let had_inherited_pub_visibility = self.inherited_pub_visibility;
186 self.inherited_pub_visibility = false;
188 ast_map::NodeItem(item) => {
190 hir::ItemStruct(..) | hir::ItemUnion(..) => {
191 self.struct_has_extern_repr = item.attrs.iter().any(|attr| {
192 attr::find_repr_attrs(self.tcx.sess.diagnostic(), attr)
193 .contains(&attr::ReprExtern)
196 intravisit::walk_item(self, &item);
198 hir::ItemEnum(..) => {
199 self.inherited_pub_visibility = item.vis == hir::Public;
200 intravisit::walk_item(self, &item);
204 | hir::ItemStatic(..)
205 | hir::ItemConst(..) => {
206 intravisit::walk_item(self, &item);
211 ast_map::NodeTraitItem(trait_item) => {
212 intravisit::walk_trait_item(self, trait_item);
214 ast_map::NodeImplItem(impl_item) => {
215 intravisit::walk_impl_item(self, impl_item);
217 ast_map::NodeForeignItem(foreign_item) => {
218 intravisit::walk_foreign_item(self, &foreign_item);
222 self.struct_has_extern_repr = had_extern_repr;
223 self.inherited_pub_visibility = had_inherited_pub_visibility;
227 impl<'a, 'tcx, 'v> Visitor<'v> for MarkSymbolVisitor<'a, 'tcx> {
229 fn visit_variant_data(&mut self, def: &hir::VariantData, _: ast::Name,
230 _: &hir::Generics, _: ast::NodeId, _: syntax_pos::Span) {
231 let has_extern_repr = self.struct_has_extern_repr;
232 let inherited_pub_visibility = self.inherited_pub_visibility;
233 let live_fields = def.fields().iter().filter(|f| {
234 has_extern_repr || inherited_pub_visibility || f.vis == hir::Public
236 self.live_symbols.extend(live_fields.map(|f| f.id));
238 intravisit::walk_struct_def(self, def);
241 fn visit_expr(&mut self, expr: &hir::Expr) {
243 hir::ExprPath(hir::QPath::TypeRelative(..)) => {
244 self.lookup_and_handle_definition(expr.id);
246 hir::ExprMethodCall(..) => {
247 self.lookup_and_handle_method(expr.id);
249 hir::ExprField(ref lhs, ref name) => {
250 self.handle_field_access(&lhs, name.node);
252 hir::ExprTupField(ref lhs, idx) => {
253 self.handle_tup_field_access(&lhs, idx.node);
258 intravisit::walk_expr(self, expr);
261 fn visit_arm(&mut self, arm: &hir::Arm) {
262 if arm.pats.len() == 1 {
263 let pat = &*arm.pats[0];
264 let variants = pat_util::necessary_variants(&self.tcx.def_map.borrow(), pat);
266 // Inside the body, ignore constructions of variants
267 // necessary for the pattern to match. Those construction sites
268 // can't be reached unless the variant is constructed elsewhere.
269 let len = self.ignore_variant_stack.len();
270 self.ignore_variant_stack.extend_from_slice(&variants);
271 intravisit::walk_arm(self, arm);
272 self.ignore_variant_stack.truncate(len);
274 intravisit::walk_arm(self, arm);
278 fn visit_pat(&mut self, pat: &hir::Pat) {
279 let def_map = &self.tcx.def_map;
281 PatKind::Struct(_, ref fields, _) => {
282 self.handle_field_pattern_match(pat, fields);
284 _ if pat_util::pat_is_const(&def_map.borrow(), pat) => {
285 // it might be the only use of a const
286 self.lookup_and_handle_definition(pat.id)
291 self.ignore_non_const_paths = true;
292 intravisit::walk_pat(self, pat);
293 self.ignore_non_const_paths = false;
296 fn visit_path(&mut self, path: &hir::Path, id: ast::NodeId) {
297 self.lookup_and_handle_definition(id);
298 intravisit::walk_path(self, path);
301 fn visit_path_list_item(&mut self, path: &hir::Path, item: &hir::PathListItem) {
302 self.lookup_and_handle_definition(item.node.id);
303 intravisit::walk_path_list_item(self, path, item);
307 fn has_allow_dead_code_or_lang_attr(attrs: &[ast::Attribute]) -> bool {
308 if attr::contains_name(attrs, "lang") {
312 let dead_code = lint::builtin::DEAD_CODE.name_lower();
313 for attr in lint::gather_attrs(attrs) {
315 Ok((name, lint::Allow, _)) if name == &*dead_code => return true,
322 // This visitor seeds items that
323 // 1) We want to explicitly consider as live:
324 // * Item annotated with #[allow(dead_code)]
325 // - This is done so that if we want to suppress warnings for a
326 // group of dead functions, we only have to annotate the "root".
327 // For example, if both `f` and `g` are dead and `f` calls `g`,
328 // then annotating `f` with `#[allow(dead_code)]` will suppress
329 // warning for both `f` and `g`.
330 // * Item annotated with #[lang=".."]
331 // - This is because lang items are always callable from elsewhere.
333 // 2) We are not sure to be live or not
334 // * Implementation of a trait method
335 struct LifeSeeder<'k> {
336 worklist: Vec<ast::NodeId>,
337 krate: &'k hir::Crate,
340 impl<'v, 'k> ItemLikeVisitor<'v> for LifeSeeder<'k> {
341 fn visit_item(&mut self, item: &hir::Item) {
342 let allow_dead_code = has_allow_dead_code_or_lang_attr(&item.attrs);
344 self.worklist.push(item.id);
347 hir::ItemEnum(ref enum_def, _) if allow_dead_code => {
348 self.worklist.extend(enum_def.variants.iter()
349 .map(|variant| variant.node.data.id()));
351 hir::ItemTrait(.., ref trait_items) => {
352 for trait_item in trait_items {
353 match trait_item.node {
354 hir::ConstTraitItem(_, Some(_)) |
355 hir::MethodTraitItem(_, Some(_)) => {
356 if has_allow_dead_code_or_lang_attr(&trait_item.attrs) {
357 self.worklist.push(trait_item.id);
364 hir::ItemImpl(.., ref opt_trait, _, ref impl_item_refs) => {
365 for impl_item_ref in impl_item_refs {
366 let impl_item = self.krate.impl_item(impl_item_ref.id);
367 if opt_trait.is_some() ||
368 has_allow_dead_code_or_lang_attr(&impl_item.attrs) {
369 self.worklist.push(impl_item_ref.id.node_id);
377 fn visit_impl_item(&mut self, _item: &hir::ImplItem) {
378 // ignore: we are handling this in `visit_item` above
382 fn create_and_seed_worklist<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
383 access_levels: &privacy::AccessLevels,
385 -> Vec<ast::NodeId> {
386 let mut worklist = Vec::new();
387 for (id, _) in &access_levels.map {
392 if let Some((id, _)) = *tcx.sess.entry_fn.borrow() {
396 // Seed implemented trait items
397 let mut life_seeder = LifeSeeder {
401 krate.visit_all_item_likes(&mut life_seeder);
403 return life_seeder.worklist;
406 fn find_live<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
407 access_levels: &privacy::AccessLevels,
409 -> Box<FxHashSet<ast::NodeId>> {
410 let worklist = create_and_seed_worklist(tcx, access_levels, krate);
411 let mut symbol_visitor = MarkSymbolVisitor::new(tcx, worklist);
412 symbol_visitor.mark_live_symbols();
413 symbol_visitor.live_symbols
416 fn get_struct_ctor_id(item: &hir::Item) -> Option<ast::NodeId> {
418 hir::ItemStruct(ref struct_def, _) if !struct_def.is_struct() => {
419 Some(struct_def.id())
425 struct DeadVisitor<'a, 'tcx: 'a> {
426 tcx: TyCtxt<'a, 'tcx, 'tcx>,
427 live_symbols: Box<FxHashSet<ast::NodeId>>,
430 impl<'a, 'tcx> DeadVisitor<'a, 'tcx> {
431 fn should_warn_about_item(&mut self, item: &hir::Item) -> bool {
432 let should_warn = match item.node {
437 | hir::ItemStruct(..)
438 | hir::ItemUnion(..) => true,
441 let ctor_id = get_struct_ctor_id(item);
442 should_warn && !self.symbol_is_live(item.id, ctor_id)
445 fn should_warn_about_field(&mut self, field: &hir::StructField) -> bool {
446 let field_type = self.tcx.item_type(self.tcx.map.local_def_id(field.id));
447 let is_marker_field = match field_type.ty_to_def_id() {
448 Some(def_id) => self.tcx.lang_items.items().iter().any(|item| *item == Some(def_id)),
451 !field.is_positional()
452 && !self.symbol_is_live(field.id, None)
454 && !has_allow_dead_code_or_lang_attr(&field.attrs)
457 fn should_warn_about_variant(&mut self, variant: &hir::Variant_) -> bool {
458 !self.symbol_is_live(variant.data.id(), None)
459 && !has_allow_dead_code_or_lang_attr(&variant.attrs)
462 // id := node id of an item's definition.
463 // ctor_id := `Some` if the item is a struct_ctor (tuple struct),
465 // If the item is a struct_ctor, then either its `id` or
466 // `ctor_id` (unwrapped) is in the live_symbols set. More specifically,
467 // DefMap maps the ExprPath of a struct_ctor to the node referred by
468 // `ctor_id`. On the other hand, in a statement like
469 // `type <ident> <generics> = <ty>;` where <ty> refers to a struct_ctor,
470 // DefMap maps <ty> to `id` instead.
471 fn symbol_is_live(&mut self,
473 ctor_id: Option<ast::NodeId>)
475 if self.live_symbols.contains(&id)
476 || ctor_id.map_or(false,
477 |ctor| self.live_symbols.contains(&ctor)) {
480 // If it's a type whose items are live, then it's live, too.
481 // This is done to handle the case where, for example, the static
482 // method of a private type is used, but the type itself is never
484 if let Some(impl_list) =
485 self.tcx.inherent_impls.borrow().get(&self.tcx.map.local_def_id(id)) {
486 for &impl_did in impl_list.iter() {
487 for &item_did in &self.tcx.associated_item_def_ids(impl_did)[..] {
488 if let Some(item_node_id) = self.tcx.map.as_local_node_id(item_did) {
489 if self.live_symbols.contains(&item_node_id) {
499 fn warn_dead_code(&mut self,
501 span: syntax_pos::Span,
504 if !name.as_str().starts_with("_") {
507 .add_lint(lint::builtin::DEAD_CODE,
510 format!("{} is never used: `{}`", node_type, name));
515 impl<'a, 'tcx> Visitor<'tcx> for DeadVisitor<'a, 'tcx> {
516 /// Walk nested items in place so that we don't report dead-code
517 /// on inner functions when the outer function is already getting
518 /// an error. We could do this also by checking the parents, but
519 /// this is how the code is setup and it seems harmless enough.
520 fn nested_visit_map(&mut self) -> Option<&hir::map::Map<'tcx>> {
524 fn visit_item(&mut self, item: &'tcx hir::Item) {
525 if self.should_warn_about_item(item) {
530 item.node.descriptive_variant()
533 // Only continue if we didn't warn
534 intravisit::walk_item(self, item);
538 fn visit_variant(&mut self,
539 variant: &'tcx hir::Variant,
540 g: &'tcx hir::Generics,
542 if self.should_warn_about_variant(&variant.node) {
543 self.warn_dead_code(variant.node.data.id(), variant.span,
544 variant.node.name, "variant");
546 intravisit::walk_variant(self, variant, g, id);
550 fn visit_foreign_item(&mut self, fi: &'tcx hir::ForeignItem) {
551 if !self.symbol_is_live(fi.id, None) {
552 self.warn_dead_code(fi.id, fi.span, fi.name, fi.node.descriptive_variant());
554 intravisit::walk_foreign_item(self, fi);
557 fn visit_struct_field(&mut self, field: &'tcx hir::StructField) {
558 if self.should_warn_about_field(&field) {
559 self.warn_dead_code(field.id, field.span,
560 field.name, "field");
563 intravisit::walk_struct_field(self, field);
566 fn visit_impl_item(&mut self, impl_item: &'tcx hir::ImplItem) {
567 match impl_item.node {
568 hir::ImplItemKind::Const(_, ref expr) => {
569 if !self.symbol_is_live(impl_item.id, None) {
570 self.warn_dead_code(impl_item.id, impl_item.span,
571 impl_item.name, "associated const");
573 intravisit::walk_expr(self, expr)
575 hir::ImplItemKind::Method(_, ref body) => {
576 if !self.symbol_is_live(impl_item.id, None) {
577 self.warn_dead_code(impl_item.id, impl_item.span,
578 impl_item.name, "method");
580 intravisit::walk_expr(self, body)
582 hir::ImplItemKind::Type(..) => {}
586 // Overwrite so that we don't warn the trait item itself.
587 fn visit_trait_item(&mut self, trait_item: &'tcx hir::TraitItem) {
588 match trait_item.node {
589 hir::ConstTraitItem(_, Some(ref body))|
590 hir::MethodTraitItem(_, Some(ref body)) => {
591 intravisit::walk_expr(self, body)
593 hir::ConstTraitItem(_, None) |
594 hir::MethodTraitItem(_, None) |
595 hir::TypeTraitItem(..) => {}
600 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
601 access_levels: &privacy::AccessLevels) {
602 let _task = tcx.dep_graph.in_task(DepNode::DeadCheck);
603 let krate = tcx.map.krate();
604 let live_symbols = find_live(tcx, access_levels, krate);
605 let mut visitor = DeadVisitor { tcx: tcx, live_symbols: live_symbols };
606 intravisit::walk_crate(&mut visitor, krate);