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 front::map as ast_map;
17 use rustc_front::visit::{self, Visitor};
18 use rustc_front::attr::{self, AttrMetaMethods};
20 use middle::{def, pat_util, privacy, ty};
21 use middle::def_id::{DefId};
23 use util::nodemap::NodeSet;
25 use std::collections::HashSet;
26 use syntax::{ast, codemap};
28 // Any local node that may call something in its body block should be
29 // explored. For example, if it's a live NodeItem that is a
30 // function, then we should explore its block to check for codes that
31 // may need to be marked as live.
32 fn should_explore(tcx: &ty::ctxt, def_id: DefId) -> bool {
33 if !def_id.is_local() {
37 match tcx.map.find(def_id.node) {
38 Some(ast_map::NodeItem(..))
39 | Some(ast_map::NodeImplItem(..))
40 | Some(ast_map::NodeForeignItem(..))
41 | Some(ast_map::NodeTraitItem(..)) => true,
46 struct MarkSymbolVisitor<'a, 'tcx: 'a> {
47 worklist: Vec<ast::NodeId>,
48 tcx: &'a ty::ctxt<'tcx>,
49 live_symbols: Box<HashSet<ast::NodeId>>,
50 struct_has_extern_repr: bool,
51 ignore_non_const_paths: bool,
52 inherited_pub_visibility: bool,
53 ignore_variant_stack: Vec<ast::NodeId>,
56 impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> {
57 fn new(tcx: &'a ty::ctxt<'tcx>,
58 worklist: Vec<ast::NodeId>) -> MarkSymbolVisitor<'a, 'tcx> {
62 live_symbols: box HashSet::new(),
63 struct_has_extern_repr: false,
64 ignore_non_const_paths: false,
65 inherited_pub_visibility: false,
66 ignore_variant_stack: vec![],
70 fn check_def_id(&mut self, def_id: DefId) {
71 if should_explore(self.tcx, def_id) {
72 self.worklist.push(def_id.node);
74 self.live_symbols.insert(def_id.node);
77 fn lookup_and_handle_definition(&mut self, id: &ast::NodeId) {
78 use middle::ty::TypeVariants::{TyEnum, TyStruct};
80 // If `bar` is a trait item, make sure to mark Foo as alive in `Foo::bar`
81 self.tcx.tables.borrow().item_substs.get(id)
82 .and_then(|substs| substs.substs.self_ty())
83 .map(|ty| match ty.sty {
84 TyEnum(tyid, _) | TyStruct(tyid, _) => self.check_def_id(tyid.did),
88 self.tcx.def_map.borrow().get(id).map(|def| {
89 match def.full_def() {
90 def::DefConst(_) | def::DefAssociatedConst(..) => {
91 self.check_def_id(def.def_id())
93 _ if self.ignore_non_const_paths => (),
94 def::DefPrimTy(_) => (),
95 def::DefVariant(enum_id, variant_id, _) => {
96 self.check_def_id(enum_id);
97 if !self.ignore_variant_stack.contains(&variant_id.node) {
98 self.check_def_id(variant_id);
102 self.check_def_id(def.def_id());
108 fn lookup_and_handle_method(&mut self, id: ast::NodeId) {
109 let method_call = ty::MethodCall::expr(id);
110 let method = self.tcx.tables.borrow().method_map[&method_call];
111 self.check_def_id(method.def_id);
114 fn handle_field_access(&mut self, lhs: &hir::Expr, name: ast::Name) {
115 if let ty::TyStruct(def, _) = self.tcx.expr_ty_adjusted(lhs).sty {
116 self.live_symbols.insert(def.struct_variant().field_named(name).did.node);
118 self.tcx.sess.span_bug(lhs.span, "named field access on non-struct")
122 fn handle_tup_field_access(&mut self, lhs: &hir::Expr, idx: usize) {
123 if let ty::TyStruct(def, _) = self.tcx.expr_ty_adjusted(lhs).sty {
124 self.live_symbols.insert(def.struct_variant().fields[idx].did.node);
128 fn handle_field_pattern_match(&mut self, lhs: &hir::Pat,
129 pats: &[codemap::Spanned<hir::FieldPat>]) {
130 let def = self.tcx.def_map.borrow().get(&lhs.id).unwrap().full_def();
131 let pat_ty = self.tcx.node_id_to_type(lhs.id);
132 let variant = match pat_ty.sty {
133 ty::TyStruct(adt, _) | ty::TyEnum(adt, _) => adt.variant_of_def(def),
134 _ => self.tcx.sess.span_bug(lhs.span, "non-ADT in struct pattern")
137 if let hir::PatWild(hir::PatWildSingle) = pat.node.pat.node {
140 self.live_symbols.insert(variant.field_named(pat.node.ident.name).did.node);
144 fn mark_live_symbols(&mut self) {
145 let mut scanned = HashSet::new();
146 while !self.worklist.is_empty() {
147 let id = self.worklist.pop().unwrap();
148 if scanned.contains(&id) {
153 match self.tcx.map.find(id) {
155 self.live_symbols.insert(id);
156 self.visit_node(node);
163 fn visit_node(&mut self, node: &ast_map::Node) {
164 let had_extern_repr = self.struct_has_extern_repr;
165 self.struct_has_extern_repr = false;
166 let had_inherited_pub_visibility = self.inherited_pub_visibility;
167 self.inherited_pub_visibility = false;
169 ast_map::NodeItem(item) => {
171 hir::ItemStruct(..) => {
172 self.struct_has_extern_repr = item.attrs.iter().any(|attr| {
173 attr::find_repr_attrs(self.tcx.sess.diagnostic(), attr)
174 .contains(&attr::ReprExtern)
177 visit::walk_item(self, &*item);
179 hir::ItemEnum(..) => {
180 self.inherited_pub_visibility = item.vis == hir::Public;
181 visit::walk_item(self, &*item);
185 | hir::ItemStatic(..)
186 | hir::ItemConst(..) => {
187 visit::walk_item(self, &*item);
192 ast_map::NodeTraitItem(trait_item) => {
193 visit::walk_trait_item(self, trait_item);
195 ast_map::NodeImplItem(impl_item) => {
196 visit::walk_impl_item(self, impl_item);
198 ast_map::NodeForeignItem(foreign_item) => {
199 visit::walk_foreign_item(self, &*foreign_item);
203 self.struct_has_extern_repr = had_extern_repr;
204 self.inherited_pub_visibility = had_inherited_pub_visibility;
208 impl<'a, 'tcx, 'v> Visitor<'v> for MarkSymbolVisitor<'a, 'tcx> {
210 fn visit_struct_def(&mut self, def: &hir::StructDef, _: ast::Ident,
211 _: &hir::Generics, _: ast::NodeId) {
212 let has_extern_repr = self.struct_has_extern_repr;
213 let inherited_pub_visibility = self.inherited_pub_visibility;
214 let live_fields = def.fields.iter().filter(|f| {
215 has_extern_repr || inherited_pub_visibility || match f.node.kind {
216 hir::NamedField(_, hir::Public) => true,
220 self.live_symbols.extend(live_fields.map(|f| f.node.id));
222 visit::walk_struct_def(self, def);
225 fn visit_expr(&mut self, expr: &hir::Expr) {
227 hir::ExprMethodCall(..) => {
228 self.lookup_and_handle_method(expr.id);
230 hir::ExprField(ref lhs, ref ident) => {
231 self.handle_field_access(&**lhs, ident.node.name);
233 hir::ExprTupField(ref lhs, idx) => {
234 self.handle_tup_field_access(&**lhs, idx.node);
239 visit::walk_expr(self, expr);
242 fn visit_arm(&mut self, arm: &hir::Arm) {
243 if arm.pats.len() == 1 {
244 let pat = &*arm.pats[0];
245 let variants = pat_util::necessary_variants(&self.tcx.def_map, pat);
247 // Inside the body, ignore constructions of variants
248 // necessary for the pattern to match. Those construction sites
249 // can't be reached unless the variant is constructed elsewhere.
250 let len = self.ignore_variant_stack.len();
251 self.ignore_variant_stack.push_all(&*variants);
252 visit::walk_arm(self, arm);
253 self.ignore_variant_stack.truncate(len);
255 visit::walk_arm(self, arm);
259 fn visit_pat(&mut self, pat: &hir::Pat) {
260 let def_map = &self.tcx.def_map;
262 hir::PatStruct(_, ref fields, _) => {
263 self.handle_field_pattern_match(pat, fields);
265 _ if pat_util::pat_is_const(def_map, pat) => {
266 // it might be the only use of a const
267 self.lookup_and_handle_definition(&pat.id)
272 self.ignore_non_const_paths = true;
273 visit::walk_pat(self, pat);
274 self.ignore_non_const_paths = false;
277 fn visit_path(&mut self, path: &hir::Path, id: ast::NodeId) {
278 self.lookup_and_handle_definition(&id);
279 visit::walk_path(self, path);
282 fn visit_item(&mut self, _: &hir::Item) {
283 // Do not recurse into items. These items will be added to the
284 // worklist and recursed into manually if necessary.
288 fn has_allow_dead_code_or_lang_attr(attrs: &[hir::Attribute]) -> bool {
289 if attr::contains_name(attrs, "lang") {
293 let dead_code = lint::builtin::DEAD_CODE.name_lower();
294 for attr in lint::gather_attrs_from_hir(attrs) {
296 Ok((ref name, lint::Allow, _))
297 if &name[..] == dead_code => return true,
304 // This visitor seeds items that
305 // 1) We want to explicitly consider as live:
306 // * Item annotated with #[allow(dead_code)]
307 // - This is done so that if we want to suppress warnings for a
308 // group of dead functions, we only have to annotate the "root".
309 // For example, if both `f` and `g` are dead and `f` calls `g`,
310 // then annotating `f` with `#[allow(dead_code)]` will suppress
311 // warning for both `f` and `g`.
312 // * Item annotated with #[lang=".."]
313 // - This is because lang items are always callable from elsewhere.
315 // 2) We are not sure to be live or not
316 // * Implementation of a trait method
318 worklist: Vec<ast::NodeId>
321 impl<'v> Visitor<'v> for LifeSeeder {
322 fn visit_item(&mut self, item: &hir::Item) {
323 let allow_dead_code = has_allow_dead_code_or_lang_attr(&item.attrs);
325 self.worklist.push(item.id);
328 hir::ItemEnum(ref enum_def, _) if allow_dead_code => {
329 self.worklist.extend(enum_def.variants.iter().map(|variant| variant.node.id));
331 hir::ItemTrait(_, _, _, ref trait_items) => {
332 for trait_item in trait_items {
333 match trait_item.node {
334 hir::ConstTraitItem(_, Some(_)) |
335 hir::MethodTraitItem(_, Some(_)) => {
336 if has_allow_dead_code_or_lang_attr(&trait_item.attrs) {
337 self.worklist.push(trait_item.id);
344 hir::ItemImpl(_, _, _, ref opt_trait, _, ref impl_items) => {
345 for impl_item in impl_items {
346 match impl_item.node {
347 hir::ConstImplItem(..) |
348 hir::MethodImplItem(..) => {
349 if opt_trait.is_some() ||
350 has_allow_dead_code_or_lang_attr(&impl_item.attrs) {
351 self.worklist.push(impl_item.id);
354 hir::TypeImplItem(_) => {}
360 visit::walk_item(self, item);
364 fn create_and_seed_worklist(tcx: &ty::ctxt,
365 exported_items: &privacy::ExportedItems,
366 reachable_symbols: &NodeSet,
367 krate: &hir::Crate) -> Vec<ast::NodeId> {
368 let mut worklist = Vec::new();
370 // Preferably, we would only need to seed the worklist with reachable
371 // symbols. However, since the set of reachable symbols differs
372 // depending on whether a crate is built as bin or lib, and we want
373 // the warning to be consistent, we also seed the worklist with
375 for id in exported_items {
378 for id in reachable_symbols {
379 // Reachable variants can be dead, because we warn about
380 // variants never constructed, not variants never used.
381 if let Some(ast_map::NodeVariant(..)) = tcx.map.find(*id) {
388 match *tcx.sess.entry_fn.borrow() {
389 Some((id, _)) => worklist.push(id),
393 // Seed implemented trait items
394 let mut life_seeder = LifeSeeder {
397 visit::walk_crate(&mut life_seeder, krate);
399 return life_seeder.worklist;
402 fn find_live(tcx: &ty::ctxt,
403 exported_items: &privacy::ExportedItems,
404 reachable_symbols: &NodeSet,
406 -> Box<HashSet<ast::NodeId>> {
407 let worklist = create_and_seed_worklist(tcx, exported_items,
408 reachable_symbols, krate);
409 let mut symbol_visitor = MarkSymbolVisitor::new(tcx, worklist);
410 symbol_visitor.mark_live_symbols();
411 symbol_visitor.live_symbols
414 fn get_struct_ctor_id(item: &hir::Item) -> Option<ast::NodeId> {
416 hir::ItemStruct(ref struct_def, _) => struct_def.ctor_id,
421 struct DeadVisitor<'a, 'tcx: 'a> {
422 tcx: &'a ty::ctxt<'tcx>,
423 live_symbols: Box<HashSet<ast::NodeId>>,
426 impl<'a, 'tcx> DeadVisitor<'a, 'tcx> {
427 fn should_warn_about_item(&mut self, item: &hir::Item) -> bool {
428 let should_warn = match item.node {
433 | hir::ItemStruct(..) => true,
436 let ctor_id = get_struct_ctor_id(item);
437 should_warn && !self.symbol_is_live(item.id, ctor_id)
440 fn should_warn_about_field(&mut self, node: &hir::StructField_) -> bool {
441 let is_named = node.ident().is_some();
442 let field_type = self.tcx.node_id_to_type(node.id);
443 let is_marker_field = match field_type.ty_to_def_id() {
444 Some(def_id) => self.tcx.lang_items.items().any(|(_, item)| *item == Some(def_id)),
448 && !self.symbol_is_live(node.id, None)
450 && !has_allow_dead_code_or_lang_attr(&node.attrs)
453 fn should_warn_about_variant(&mut self, variant: &hir::Variant_) -> bool {
454 !self.symbol_is_live(variant.id, None)
455 && !has_allow_dead_code_or_lang_attr(&variant.attrs)
458 // id := node id of an item's definition.
459 // ctor_id := `Some` if the item is a struct_ctor (tuple struct),
461 // If the item is a struct_ctor, then either its `id` or
462 // `ctor_id` (unwrapped) is in the live_symbols set. More specifically,
463 // DefMap maps the ExprPath of a struct_ctor to the node referred by
464 // `ctor_id`. On the other hand, in a statement like
465 // `type <ident> <generics> = <ty>;` where <ty> refers to a struct_ctor,
466 // DefMap maps <ty> to `id` instead.
467 fn symbol_is_live(&mut self, id: ast::NodeId,
468 ctor_id: Option<ast::NodeId>) -> bool {
469 if self.live_symbols.contains(&id)
470 || ctor_id.map_or(false,
471 |ctor| self.live_symbols.contains(&ctor)) {
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
478 let impl_items = self.tcx.impl_items.borrow();
479 match self.tcx.inherent_impls.borrow().get(&DefId::local(id)) {
482 for impl_did in impl_list.iter() {
483 for item_did in impl_items.get(impl_did).unwrap().iter() {
484 if self.live_symbols.contains(&item_did.def_id()
495 fn warn_dead_code(&mut self,
500 let name = name.as_str();
501 if !name.starts_with("_") {
504 .add_lint(lint::builtin::DEAD_CODE,
507 format!("{} is never used: `{}`", node_type, name));
512 impl<'a, 'tcx, 'v> Visitor<'v> for DeadVisitor<'a, 'tcx> {
513 fn visit_item(&mut self, item: &hir::Item) {
514 if self.should_warn_about_item(item) {
519 item.node.descriptive_variant()
523 hir::ItemEnum(ref enum_def, _) => {
524 for variant in &enum_def.variants {
525 if self.should_warn_about_variant(&variant.node) {
526 self.warn_dead_code(variant.node.id, variant.span,
527 variant.node.name.name, "variant");
534 visit::walk_item(self, item);
537 fn visit_foreign_item(&mut self, fi: &hir::ForeignItem) {
538 if !self.symbol_is_live(fi.id, None) {
539 self.warn_dead_code(fi.id, fi.span, fi.ident.name, fi.node.descriptive_variant());
541 visit::walk_foreign_item(self, fi);
544 fn visit_struct_field(&mut self, field: &hir::StructField) {
545 if self.should_warn_about_field(&field.node) {
546 self.warn_dead_code(field.node.id, field.span,
547 field.node.ident().unwrap().name, "struct field");
550 visit::walk_struct_field(self, field);
553 fn visit_impl_item(&mut self, impl_item: &hir::ImplItem) {
554 match impl_item.node {
555 hir::ConstImplItem(_, ref expr) => {
556 if !self.symbol_is_live(impl_item.id, None) {
557 self.warn_dead_code(impl_item.id, impl_item.span,
558 impl_item.ident.name, "associated const");
560 visit::walk_expr(self, expr)
562 hir::MethodImplItem(_, ref body) => {
563 if !self.symbol_is_live(impl_item.id, None) {
564 self.warn_dead_code(impl_item.id, impl_item.span,
565 impl_item.ident.name, "method");
567 visit::walk_block(self, body)
569 hir::TypeImplItem(..) => {}
573 // Overwrite so that we don't warn the trait item itself.
574 fn visit_trait_item(&mut self, trait_item: &hir::TraitItem) {
575 match trait_item.node {
576 hir::ConstTraitItem(_, Some(ref expr)) => {
577 visit::walk_expr(self, expr)
579 hir::MethodTraitItem(_, Some(ref body)) => {
580 visit::walk_block(self, body)
582 hir::ConstTraitItem(_, None) |
583 hir::MethodTraitItem(_, None) |
584 hir::TypeTraitItem(..) => {}
589 pub fn check_crate(tcx: &ty::ctxt,
590 exported_items: &privacy::ExportedItems,
591 reachable_symbols: &NodeSet) {
592 let krate = tcx.map.krate();
593 let live_symbols = find_live(tcx, exported_items,
594 reachable_symbols, krate);
595 let mut visitor = DeadVisitor { tcx: tcx, live_symbols: live_symbols };
596 visit::walk_crate(&mut visitor, krate);