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};
26 use syntax::attr::AttrMetaMethods;
29 use syntax::parse::token;
30 use syntax::visit::Visitor;
33 // Any local node that may call something in its body block should be
34 // explored. For example, if it's a live NodeItem that is a
35 // function, then we should explore its block to check for codes that
36 // may need to be marked as live.
37 fn should_explore(tcx: &ty::ctxt, def_id: ast::DefId) -> bool {
38 if !is_local(def_id) {
42 match tcx.map.find(def_id.node) {
43 Some(ast_map::NodeItem(..))
44 | Some(ast_map::NodeMethod(..))
45 | Some(ast_map::NodeForeignItem(..))
46 | Some(ast_map::NodeTraitMethod(..)) => true,
51 struct MarkSymbolVisitor<'a> {
52 worklist: Vec<ast::NodeId>,
54 live_symbols: Box<HashSet<ast::NodeId>>,
58 struct MarkSymbolVisitorContext {
59 struct_has_extern_repr: bool
62 impl<'a> MarkSymbolVisitor<'a> {
63 fn new(tcx: &'a ty::ctxt,
64 worklist: Vec<ast::NodeId>) -> MarkSymbolVisitor<'a> {
68 live_symbols: box HashSet::new(),
72 fn check_def_id(&mut self, def_id: ast::DefId) {
73 if should_explore(self.tcx, def_id) {
74 self.worklist.push(def_id.node);
76 self.live_symbols.insert(def_id.node);
79 fn lookup_and_handle_definition(&mut self, id: &ast::NodeId) {
80 let def = match self.tcx.def_map.borrow().find(id) {
84 let def_id = match def {
85 def::DefVariant(enum_id, _, _) => Some(enum_id),
86 def::DefPrimTy(_) => None,
87 _ => Some(def.def_id())
90 Some(def_id) => self.check_def_id(def_id),
95 fn lookup_and_handle_method(&mut self, id: ast::NodeId,
96 span: codemap::Span) {
97 let method_call = typeck::MethodCall::expr(id);
98 match self.tcx.method_map.borrow().find(&method_call) {
100 match method.origin {
101 typeck::MethodStatic(def_id) => {
102 match ty::provided_source(self.tcx, def_id) {
103 Some(p_did) => self.check_def_id(p_did),
104 None => self.check_def_id(def_id)
107 typeck::MethodParam(typeck::MethodParam {
112 | typeck::MethodObject(typeck::MethodObject {
117 let def_id = ty::trait_method(self.tcx,
118 trait_id, index).def_id;
119 self.check_def_id(def_id);
124 self.tcx.sess.span_bug(span,
125 "method call expression not \
131 fn handle_field_access(&mut self, lhs: &ast::Expr, name: &ast::Ident) {
132 match ty::get(ty::expr_ty_adjusted(self.tcx, lhs)).sty {
133 ty::ty_struct(id, _) => {
134 let fields = ty::lookup_struct_fields(self.tcx, id);
135 let field_id = fields.iter()
136 .find(|field| field.name == name.name).unwrap().id;
137 self.live_symbols.insert(field_id.node);
143 fn handle_field_pattern_match(&mut self, lhs: &ast::Pat, pats: &[ast::FieldPat]) {
144 match self.tcx.def_map.borrow().get(&lhs.id) {
145 &def::DefStruct(id) | &def::DefVariant(_, id, _) => {
146 let fields = ty::lookup_struct_fields(self.tcx, id);
147 for pat in pats.iter() {
148 let field_id = fields.iter()
149 .find(|field| field.name == pat.ident.name).unwrap().id;
150 self.live_symbols.insert(field_id.node);
157 fn mark_live_symbols(&mut self) {
158 let mut scanned = HashSet::new();
159 while self.worklist.len() > 0 {
160 let id = self.worklist.pop().unwrap();
161 if scanned.contains(&id) {
166 match self.tcx.map.find(id) {
168 self.live_symbols.insert(id);
169 self.visit_node(node);
176 fn visit_node(&mut self, node: &ast_map::Node) {
177 let ctxt = MarkSymbolVisitorContext {
178 struct_has_extern_repr: false
181 ast_map::NodeItem(item) => {
183 ast::ItemStruct(..) => {
184 let has_extern_repr = item.attrs.iter().fold(attr::ReprAny, |acc, attr| {
185 attr::find_repr_attr(self.tcx.sess.diagnostic(), attr, acc)
186 }) == attr::ReprExtern;
188 visit::walk_item(self, &*item, MarkSymbolVisitorContext {
189 struct_has_extern_repr: has_extern_repr,
196 | ast::ItemStatic(..) => {
197 visit::walk_item(self, &*item, ctxt);
202 ast_map::NodeTraitMethod(trait_method) => {
203 visit::walk_trait_method(self, &*trait_method, ctxt);
205 ast_map::NodeMethod(method) => {
206 visit::walk_block(self, &*method.body, ctxt);
208 ast_map::NodeForeignItem(foreign_item) => {
209 visit::walk_foreign_item(self, &*foreign_item, ctxt);
216 impl<'a> Visitor<MarkSymbolVisitorContext> for MarkSymbolVisitor<'a> {
218 fn visit_struct_def(&mut self, def: &ast::StructDef, _: ast::Ident, _: &ast::Generics,
219 _: ast::NodeId, ctxt: MarkSymbolVisitorContext) {
220 let live_fields = def.fields.iter().filter(|f| {
221 ctxt.struct_has_extern_repr || match f.node.kind {
222 ast::NamedField(_, ast::Public) => true,
226 self.live_symbols.extend(live_fields.map(|f| f.node.id));
228 visit::walk_struct_def(self, def, ctxt);
231 fn visit_expr(&mut self, expr: &ast::Expr, ctxt: MarkSymbolVisitorContext) {
233 ast::ExprMethodCall(..) => {
234 self.lookup_and_handle_method(expr.id, expr.span);
236 ast::ExprField(ref lhs, ref ident, _) => {
237 self.handle_field_access(&**lhs, &ident.node);
242 visit::walk_expr(self, expr, ctxt);
245 fn visit_pat(&mut self, pat: &ast::Pat, ctxt: MarkSymbolVisitorContext) {
247 ast::PatStruct(_, ref fields, _) => {
248 self.handle_field_pattern_match(pat, fields.as_slice());
250 ast::PatIdent(_, _, _) => {
251 // it might be the only use of a static:
252 self.lookup_and_handle_definition(&pat.id)
257 visit::walk_pat(self, pat, ctxt);
260 fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId, ctxt: MarkSymbolVisitorContext) {
261 self.lookup_and_handle_definition(&id);
262 visit::walk_path(self, path, ctxt);
265 fn visit_item(&mut self, _: &ast::Item, _: MarkSymbolVisitorContext) {
266 // Do not recurse into items. These items will be added to the
267 // worklist and recursed into manually if necessary.
271 fn has_allow_dead_code_or_lang_attr(attrs: &[ast::Attribute]) -> bool {
272 if attr::contains_name(attrs.as_slice(), "lang") {
276 let dead_code = lint::builtin::DEAD_CODE.name_lower();
277 for attr in lint::gather_attrs(attrs).move_iter() {
279 Ok((ref name, lint::Allow, _))
280 if name.get() == dead_code.as_slice() => return true,
287 // This visitor seeds items that
288 // 1) We want to explicitly consider as live:
289 // * Item annotated with #[allow(dead_code)]
290 // - This is done so that if we want to suppress warnings for a
291 // group of dead functions, we only have to annotate the "root".
292 // For example, if both `f` and `g` are dead and `f` calls `g`,
293 // then annotating `f` with `#[allow(dead_code)]` will suppress
294 // warning for both `f` and `g`.
295 // * Item annotated with #[lang=".."]
296 // - This is because lang items are always callable from elsewhere.
298 // 2) We are not sure to be live or not
299 // * Implementation of a trait method
301 worklist: Vec<ast::NodeId> ,
304 impl Visitor<()> for LifeSeeder {
305 fn visit_item(&mut self, item: &ast::Item, _: ()) {
306 if has_allow_dead_code_or_lang_attr(item.attrs.as_slice()) {
307 self.worklist.push(item.id);
310 ast::ItemImpl(_, Some(ref _trait_ref), _, ref methods) => {
311 for method in methods.iter() {
312 self.worklist.push(method.id);
317 visit::walk_item(self, item, ());
320 fn visit_fn(&mut self, fk: &visit::FnKind,
321 _: &ast::FnDecl, block: &ast::Block,
322 _: codemap::Span, id: ast::NodeId, _: ()) {
323 // Check for method here because methods are not ast::Item
325 visit::FkMethod(_, _, method) => {
326 if has_allow_dead_code_or_lang_attr(method.attrs.as_slice()) {
327 self.worklist.push(id);
332 visit::walk_block(self, block, ());
336 fn create_and_seed_worklist(tcx: &ty::ctxt,
337 exported_items: &privacy::ExportedItems,
338 reachable_symbols: &NodeSet,
339 krate: &ast::Crate) -> Vec<ast::NodeId> {
340 let mut worklist = Vec::new();
342 // Preferably, we would only need to seed the worklist with reachable
343 // symbols. However, since the set of reachable symbols differs
344 // depending on whether a crate is built as bin or lib, and we want
345 // the warning to be consistent, we also seed the worklist with
347 for &id in exported_items.iter() {
350 for &id in reachable_symbols.iter() {
355 match *tcx.sess.entry_fn.borrow() {
356 Some((id, _)) => worklist.push(id),
360 // Seed implemented trait methods
361 let mut life_seeder = LifeSeeder {
364 visit::walk_crate(&mut life_seeder, krate, ());
366 return life_seeder.worklist;
369 fn find_live(tcx: &ty::ctxt,
370 exported_items: &privacy::ExportedItems,
371 reachable_symbols: &NodeSet,
373 -> Box<HashSet<ast::NodeId>> {
374 let worklist = create_and_seed_worklist(tcx, exported_items,
375 reachable_symbols, krate);
376 let mut symbol_visitor = MarkSymbolVisitor::new(tcx, worklist);
377 symbol_visitor.mark_live_symbols();
378 symbol_visitor.live_symbols
381 fn should_warn(item: &ast::Item) -> bool {
386 | ast::ItemStruct(..) => true,
391 fn get_struct_ctor_id(item: &ast::Item) -> Option<ast::NodeId> {
393 ast::ItemStruct(struct_def, _) => struct_def.ctor_id,
398 struct DeadVisitor<'a> {
400 live_symbols: Box<HashSet<ast::NodeId>>,
403 impl<'a> DeadVisitor<'a> {
404 fn should_warn_about_field(&mut self, node: &ast::StructField_) -> bool {
405 let (is_named, has_leading_underscore) = match node.ident() {
406 Some(ref ident) => (true, token::get_ident(*ident).get().as_bytes()[0] == ('_' as u8)),
409 let field_type = ty::node_id_to_type(self.tcx, node.id);
410 let is_marker_field = match ty::ty_to_def_id(field_type) {
411 Some(def_id) => self.tcx.lang_items.items().any(|(_, item)| *item == Some(def_id)),
415 && !self.symbol_is_live(node.id, None)
416 && !has_leading_underscore
418 && !has_allow_dead_code_or_lang_attr(node.attrs.as_slice())
421 // id := node id of an item's definition.
422 // ctor_id := `Some` if the item is a struct_ctor (tuple struct),
424 // If the item is a struct_ctor, then either its `id` or
425 // `ctor_id` (unwrapped) is in the live_symbols set. More specifically,
426 // DefMap maps the ExprPath of a struct_ctor to the node referred by
427 // `ctor_id`. On the other hand, in a statement like
428 // `type <ident> <generics> = <ty>;` where <ty> refers to a struct_ctor,
429 // DefMap maps <ty> to `id` instead.
430 fn symbol_is_live(&mut self, id: ast::NodeId,
431 ctor_id: Option<ast::NodeId>) -> bool {
432 if self.live_symbols.contains(&id)
433 || ctor_id.map_or(false,
434 |ctor| self.live_symbols.contains(&ctor)) {
437 // If it's a type whose methods are live, then it's live, too.
438 // This is done to handle the case where, for example, the static
439 // method of a private type is used, but the type itself is never
441 let impl_methods = self.tcx.impl_methods.borrow();
442 match self.tcx.inherent_impls.borrow().find(&local_def(id)) {
445 for impl_did in impl_list.borrow().iter() {
446 for method_did in impl_methods.get(impl_did).iter() {
447 if self.live_symbols.contains(&method_did.node) {
457 fn warn_dead_code(&mut self,
463 .add_lint(lint::builtin::DEAD_CODE,
466 format!("code is never used: `{}`",
467 token::get_ident(ident)));
471 impl<'a> Visitor<()> for DeadVisitor<'a> {
472 fn visit_item(&mut self, item: &ast::Item, _: ()) {
473 let ctor_id = get_struct_ctor_id(item);
474 if !self.symbol_is_live(item.id, ctor_id) && should_warn(item) {
475 self.warn_dead_code(item.id, item.span, item.ident);
477 visit::walk_item(self, item, ());
480 fn visit_foreign_item(&mut self, fi: &ast::ForeignItem, _: ()) {
481 if !self.symbol_is_live(fi.id, None) {
482 self.warn_dead_code(fi.id, fi.span, fi.ident);
484 visit::walk_foreign_item(self, fi, ());
487 fn visit_fn(&mut self, fk: &visit::FnKind,
488 _: &ast::FnDecl, block: &ast::Block,
489 span: codemap::Span, id: ast::NodeId, _: ()) {
490 // Have to warn method here because methods are not ast::Item
492 visit::FkMethod(..) => {
493 let ident = visit::name_of_fn(fk);
494 if !self.symbol_is_live(id, None) {
495 self.warn_dead_code(id, span, ident);
500 visit::walk_block(self, block, ());
503 fn visit_struct_field(&mut self, field: &ast::StructField, _: ()) {
504 if self.should_warn_about_field(&field.node) {
505 self.warn_dead_code(field.node.id, field.span, field.node.ident().unwrap());
508 visit::walk_struct_field(self, field, ());
511 // Overwrite so that we don't warn the trait method itself.
512 fn visit_trait_method(&mut self, trait_method: &ast::TraitMethod, _: ()) {
513 match *trait_method {
514 ast::Provided(ref method) => visit::walk_block(self, &*method.body, ()),
515 ast::Required(_) => ()
520 pub fn check_crate(tcx: &ty::ctxt,
521 exported_items: &privacy::ExportedItems,
522 reachable_symbols: &NodeSet,
523 krate: &ast::Crate) {
524 let live_symbols = find_live(tcx, exported_items,
525 reachable_symbols, krate);
526 let mut visitor = DeadVisitor { tcx: tcx, live_symbols: live_symbols };
527 visit::walk_crate(&mut visitor, krate, ());