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.
20 use util::nodemap::NodeSet;
22 use std::collections::HashSet;
25 use syntax::ast_util::{local_def, is_local, PostExpansionMethod};
26 use syntax::attr::AttrMetaMethods;
29 use syntax::visit::Visitor;
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) {
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,
50 struct MarkSymbolVisitor<'a, 'tcx: 'a> {
51 worklist: Vec<ast::NodeId>,
52 tcx: &'a ty::ctxt<'tcx>,
53 live_symbols: Box<HashSet<ast::NodeId>>,
57 struct MarkSymbolVisitorContext {
58 struct_has_extern_repr: bool
61 impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> {
62 fn new(tcx: &'a ty::ctxt<'tcx>,
63 worklist: Vec<ast::NodeId>) -> MarkSymbolVisitor<'a, 'tcx> {
67 live_symbols: box HashSet::new(),
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);
75 self.live_symbols.insert(def_id.node);
78 fn lookup_and_handle_definition(&mut self, id: &ast::NodeId) {
79 let def = match self.tcx.def_map.borrow().find(id) {
83 let def_id = match def {
84 def::DefVariant(enum_id, _, _) => Some(enum_id),
85 def::DefPrimTy(_) => None,
86 _ => Some(def.def_id())
89 Some(def_id) => self.check_def_id(def_id),
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) {
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)
106 typeck::MethodStaticUnboxedClosure(_) => {}
107 typeck::MethodParam(typeck::MethodParam {
112 | typeck::MethodObject(typeck::MethodObject {
117 let trait_item = ty::trait_item(self.tcx,
121 ty::MethodTraitItem(method) => {
122 self.check_def_id(method.def_id);
129 self.tcx.sess.span_bug(span,
130 "method call expression not \
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);
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);
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,
163 match ty::ty_to_def_id(ty::node_id_to_type(self.tcx,
166 self.tcx.sess.span_bug(lhs.span,
167 "struct pattern wasn't of a \
168 type with a def ID?!")
170 Some(def_id) => def_id,
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);
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) {
191 match self.tcx.map.find(id) {
193 self.live_symbols.insert(id);
194 self.visit_node(node);
201 fn visit_node(&mut self, node: &ast_map::Node) {
202 let ctxt = MarkSymbolVisitorContext {
203 struct_has_extern_repr: false
206 ast_map::NodeItem(item) => {
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)
214 visit::walk_item(self, &*item, MarkSymbolVisitorContext {
215 struct_has_extern_repr: has_extern_repr,
222 | ast::ItemStatic(..) => {
223 visit::walk_item(self, &*item, ctxt);
228 ast_map::NodeTraitItem(trait_method) => {
229 visit::walk_trait_item(self, &*trait_method, ctxt);
231 ast_map::NodeImplItem(impl_item) => {
233 ast::MethodImplItem(method) => {
234 visit::walk_block(self, &*method.pe_body(), ctxt);
238 ast_map::NodeForeignItem(foreign_item) => {
239 visit::walk_foreign_item(self, &*foreign_item, ctxt);
246 impl<'a, 'tcx> Visitor<MarkSymbolVisitorContext> for MarkSymbolVisitor<'a, 'tcx> {
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,
256 self.live_symbols.extend(live_fields.map(|f| f.node.id));
258 visit::walk_struct_def(self, def, ctxt);
261 fn visit_expr(&mut self, expr: &ast::Expr, ctxt: MarkSymbolVisitorContext) {
263 ast::ExprMethodCall(..) => {
264 self.lookup_and_handle_method(expr.id, expr.span);
266 ast::ExprField(ref lhs, ref ident, _) => {
267 self.handle_field_access(&**lhs, &ident.node);
269 ast::ExprTupField(ref lhs, idx, _) => {
270 self.handle_tup_field_access(&**lhs, idx.node);
275 visit::walk_expr(self, expr, ctxt);
278 fn visit_pat(&mut self, pat: &ast::Pat, ctxt: MarkSymbolVisitorContext) {
280 ast::PatStruct(_, ref fields, _) => {
281 self.handle_field_pattern_match(pat, fields.as_slice());
283 ast::PatIdent(_, _, _) => {
284 // it might be the only use of a static:
285 self.lookup_and_handle_definition(&pat.id)
290 visit::walk_pat(self, pat, ctxt);
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);
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.
304 fn has_allow_dead_code_or_lang_attr(attrs: &[ast::Attribute]) -> bool {
305 if attr::contains_name(attrs.as_slice(), "lang") {
309 let dead_code = lint::builtin::DEAD_CODE.name_lower();
310 for attr in lint::gather_attrs(attrs).move_iter() {
312 Ok((ref name, lint::Allow, _))
313 if name.get() == dead_code.as_slice() => return true,
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.
331 // 2) We are not sure to be live or not
332 // * Implementation of a trait method
334 worklist: Vec<ast::NodeId> ,
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);
343 ast::ItemImpl(_, Some(ref _trait_ref), _, ref impl_items) => {
344 for impl_item in impl_items.iter() {
346 ast::MethodImplItem(method) => {
347 self.worklist.push(method.id);
354 visit::walk_item(self, item, ());
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
362 visit::FkMethod(_, _, method) => {
363 if has_allow_dead_code_or_lang_attr(method.attrs.as_slice()) {
364 self.worklist.push(id);
369 visit::walk_block(self, block, ());
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();
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
384 for id in exported_items.iter() {
387 for id in reachable_symbols.iter() {
392 match *tcx.sess.entry_fn.borrow() {
393 Some((id, _)) => worklist.push(id),
397 // Seed implemented trait methods
398 let mut life_seeder = LifeSeeder {
401 visit::walk_crate(&mut life_seeder, krate, ());
403 return life_seeder.worklist;
406 fn find_live(tcx: &ty::ctxt,
407 exported_items: &privacy::ExportedItems,
408 reachable_symbols: &NodeSet,
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
418 fn should_warn(item: &ast::Item) -> bool {
423 | ast::ItemStruct(..) => true,
428 fn get_struct_ctor_id(item: &ast::Item) -> Option<ast::NodeId> {
430 ast::ItemStruct(struct_def, _) => struct_def.ctor_id,
435 struct DeadVisitor<'a, 'tcx: 'a> {
436 tcx: &'a ty::ctxt<'tcx>,
437 live_symbols: Box<HashSet<ast::NodeId>>,
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)),
449 && !self.symbol_is_live(node.id, None)
451 && !has_allow_dead_code_or_lang_attr(node.attrs.as_slice())
454 // id := node id of an item's definition.
455 // ctor_id := `Some` if the item is a struct_ctor (tuple struct),
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)) {
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
474 let impl_items = self.tcx.impl_items.borrow();
475 match self.tcx.inherent_impls.borrow().find(&local_def(id)) {
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()
491 fn warn_dead_code(&mut self,
495 let name = ident.as_str();
496 if !name.starts_with("_") {
499 .add_lint(lint::builtin::DEAD_CODE,
502 format!("code is never used: `{}`", name));
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);
513 visit::walk_item(self, item, ());
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);
520 visit::walk_foreign_item(self, fi, ());
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
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);
536 visit::walk_block(self, block, ());
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());
544 visit::walk_struct_field(self, field, ());
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(), ())
553 ast::RequiredMethod(_) => ()
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, ());