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.
16 use middle::lint::{Allow, contains_lint, DeadCode};
20 use util::nodemap::NodeSet;
22 use std::collections::HashSet;
25 use syntax::ast_util::{local_def, is_local};
28 use syntax::parse::token;
29 use syntax::visit::Visitor;
32 pub static DEAD_CODE_LINT_STR: &'static str = "dead_code";
34 // Any local node that may call something in its body block should be
35 // explored. For example, if it's a live NodeItem that is a
36 // function, then we should explore its block to check for codes that
37 // may need to be marked as live.
38 fn should_explore(tcx: &ty::ctxt, def_id: ast::DefId) -> bool {
39 if !is_local(def_id) {
43 match tcx.map.find(def_id.node) {
44 Some(ast_map::NodeItem(..))
45 | Some(ast_map::NodeMethod(..))
46 | Some(ast_map::NodeForeignItem(..))
47 | Some(ast_map::NodeTraitMethod(..)) => true,
52 struct MarkSymbolVisitor<'a> {
53 worklist: Vec<ast::NodeId>,
55 live_symbols: Box<HashSet<ast::NodeId>>,
58 impl<'a> MarkSymbolVisitor<'a> {
59 fn new(tcx: &'a ty::ctxt,
60 worklist: Vec<ast::NodeId>) -> MarkSymbolVisitor<'a> {
64 live_symbols: box HashSet::new(),
68 fn check_def_id(&mut self, def_id: ast::DefId) {
69 if should_explore(self.tcx, def_id) {
70 self.worklist.push(def_id.node);
72 self.live_symbols.insert(def_id.node);
75 fn lookup_and_handle_definition(&mut self, id: &ast::NodeId) {
76 let def = match self.tcx.def_map.borrow().find(id) {
80 let def_id = match def {
81 def::DefVariant(enum_id, _, _) => Some(enum_id),
82 def::DefPrimTy(_) => None,
83 _ => Some(def.def_id())
86 Some(def_id) => self.check_def_id(def_id),
91 fn lookup_and_handle_method(&mut self, id: ast::NodeId,
92 span: codemap::Span) {
93 let method_call = typeck::MethodCall::expr(id);
94 match self.tcx.method_map.borrow().find(&method_call) {
97 typeck::MethodStatic(def_id) => {
98 match ty::provided_source(self.tcx, def_id) {
99 Some(p_did) => self.check_def_id(p_did),
100 None => self.check_def_id(def_id)
103 typeck::MethodParam(typeck::MethodParam {
108 | typeck::MethodObject(typeck::MethodObject {
113 let def_id = ty::trait_method(self.tcx,
114 trait_id, index).def_id;
115 self.check_def_id(def_id);
120 self.tcx.sess.span_bug(span,
121 "method call expression not \
127 fn handle_field_access(&mut self, lhs: &ast::Expr, name: &ast::Ident) {
128 match ty::get(ty::expr_ty_adjusted(self.tcx, lhs)).sty {
129 ty::ty_struct(id, _) => {
130 let fields = ty::lookup_struct_fields(self.tcx, id);
131 let field_id = fields.iter()
132 .find(|field| field.name == name.name).unwrap().id;
133 self.live_symbols.insert(field_id.node);
139 fn handle_field_pattern_match(&mut self, lhs: &ast::Pat, pats: &[ast::FieldPat]) {
140 match self.tcx.def_map.borrow().get(&lhs.id) {
141 &def::DefStruct(id) | &def::DefVariant(_, id, _) => {
142 let fields = ty::lookup_struct_fields(self.tcx, id);
143 for pat in pats.iter() {
144 let field_id = fields.iter()
145 .find(|field| field.name == pat.ident.name).unwrap().id;
146 self.live_symbols.insert(field_id.node);
153 fn mark_live_symbols(&mut self) {
154 let mut scanned = HashSet::new();
155 while self.worklist.len() > 0 {
156 let id = self.worklist.pop().unwrap();
157 if scanned.contains(&id) {
162 match self.tcx.map.find(id) {
164 self.live_symbols.insert(id);
165 self.visit_node(node);
172 fn visit_node(&mut self, node: &ast_map::Node) {
174 ast_map::NodeItem(item) => {
176 ast::ItemStruct(struct_def, _) => {
177 let has_extern_repr = item.attrs.iter().fold(attr::ReprAny, |acc, attr| {
178 attr::find_repr_attr(self.tcx.sess.diagnostic(), attr, acc)
179 }) == attr::ReprExtern;
180 let live_fields = struct_def.fields.iter().filter(|f| {
181 has_extern_repr || match f.node.kind {
182 ast::NamedField(_, ast::Public) => true,
186 self.live_symbols.extend(live_fields.map(|f| f.node.id));
187 visit::walk_item(self, &*item, ());
192 | ast::ItemStatic(..) => {
193 visit::walk_item(self, &*item, ());
198 ast_map::NodeTraitMethod(trait_method) => {
199 visit::walk_trait_method(self, &*trait_method, ());
201 ast_map::NodeMethod(method) => {
202 visit::walk_block(self, &*method.body, ());
204 ast_map::NodeForeignItem(foreign_item) => {
205 visit::walk_foreign_item(self, &*foreign_item, ());
212 impl<'a> Visitor<()> for MarkSymbolVisitor<'a> {
214 fn visit_expr(&mut self, expr: &ast::Expr, _: ()) {
216 ast::ExprMethodCall(..) => {
217 self.lookup_and_handle_method(expr.id, expr.span);
219 ast::ExprField(ref lhs, ref ident, _) => {
220 self.handle_field_access(&**lhs, ident);
225 visit::walk_expr(self, expr, ())
228 fn visit_pat(&mut self, pat: &ast::Pat, _: ()) {
230 ast::PatStruct(_, ref fields, _) => {
231 self.handle_field_pattern_match(pat, fields.as_slice());
236 visit::walk_pat(self, pat, ())
239 fn visit_path(&mut self, path: &ast::Path, id: ast::NodeId, _: ()) {
240 self.lookup_and_handle_definition(&id);
241 visit::walk_path(self, path, ());
244 fn visit_item(&mut self, _: &ast::Item, _: ()) {
245 // Do not recurse into items. These items will be added to the
246 // worklist and recursed into manually if necessary.
250 fn has_allow_dead_code_or_lang_attr(attrs: &[ast::Attribute]) -> bool {
251 contains_lint(attrs, Allow, DEAD_CODE_LINT_STR)
252 || attr::contains_name(attrs.as_slice(), "lang")
255 // This visitor seeds items that
256 // 1) We want to explicitly consider as live:
257 // * Item annotated with #[allow(dead_code)]
258 // - This is done so that if we want to suppress warnings for a
259 // group of dead functions, we only have to annotate the "root".
260 // For example, if both `f` and `g` are dead and `f` calls `g`,
261 // then annotating `f` with `#[allow(dead_code)]` will suppress
262 // warning for both `f` and `g`.
263 // * Item annotated with #[lang=".."]
264 // - This is because lang items are always callable from elsewhere.
266 // 2) We are not sure to be live or not
267 // * Implementation of a trait method
269 worklist: Vec<ast::NodeId> ,
272 impl Visitor<()> for LifeSeeder {
273 fn visit_item(&mut self, item: &ast::Item, _: ()) {
274 if has_allow_dead_code_or_lang_attr(item.attrs.as_slice()) {
275 self.worklist.push(item.id);
278 ast::ItemImpl(_, Some(ref _trait_ref), _, ref methods) => {
279 for method in methods.iter() {
280 self.worklist.push(method.id);
285 visit::walk_item(self, item, ());
288 fn visit_fn(&mut self, fk: &visit::FnKind,
289 _: &ast::FnDecl, block: &ast::Block,
290 _: codemap::Span, id: ast::NodeId, _: ()) {
291 // Check for method here because methods are not ast::Item
293 visit::FkMethod(_, _, method) => {
294 if has_allow_dead_code_or_lang_attr(method.attrs.as_slice()) {
295 self.worklist.push(id);
300 visit::walk_block(self, block, ());
304 fn create_and_seed_worklist(tcx: &ty::ctxt,
305 exported_items: &privacy::ExportedItems,
306 reachable_symbols: &NodeSet,
307 krate: &ast::Crate) -> Vec<ast::NodeId> {
308 let mut worklist = Vec::new();
310 // Preferably, we would only need to seed the worklist with reachable
311 // symbols. However, since the set of reachable symbols differs
312 // depending on whether a crate is built as bin or lib, and we want
313 // the warning to be consistent, we also seed the worklist with
315 for &id in exported_items.iter() {
318 for &id in reachable_symbols.iter() {
323 match *tcx.sess.entry_fn.borrow() {
324 Some((id, _)) => worklist.push(id),
328 // Seed implemented trait methods
329 let mut life_seeder = LifeSeeder {
332 visit::walk_crate(&mut life_seeder, krate, ());
334 return life_seeder.worklist;
337 fn find_live(tcx: &ty::ctxt,
338 exported_items: &privacy::ExportedItems,
339 reachable_symbols: &NodeSet,
341 -> Box<HashSet<ast::NodeId>> {
342 let worklist = create_and_seed_worklist(tcx, exported_items,
343 reachable_symbols, krate);
344 let mut symbol_visitor = MarkSymbolVisitor::new(tcx, worklist);
345 symbol_visitor.mark_live_symbols();
346 symbol_visitor.live_symbols
349 fn should_warn(item: &ast::Item) -> bool {
354 | ast::ItemStruct(..) => true,
359 fn get_struct_ctor_id(item: &ast::Item) -> Option<ast::NodeId> {
361 ast::ItemStruct(struct_def, _) => struct_def.ctor_id,
366 struct DeadVisitor<'a> {
368 live_symbols: Box<HashSet<ast::NodeId>>,
371 impl<'a> DeadVisitor<'a> {
372 fn should_warn_about_field(&mut self, node: &ast::StructField_) -> bool {
373 let (is_named, has_leading_underscore) = match node.ident() {
374 Some(ref ident) => (true, token::get_ident(*ident).get()[0] == ('_' as u8)),
377 let field_type = ty::node_id_to_type(self.tcx, node.id);
378 let is_marker_field = match ty::ty_to_def_id(field_type) {
379 Some(def_id) => self.tcx.lang_items.items().any(|(_, item)| *item == Some(def_id)),
383 && !self.symbol_is_live(node.id, None)
384 && !has_leading_underscore
386 && !has_allow_dead_code_or_lang_attr(node.attrs.as_slice())
389 // id := node id of an item's definition.
390 // ctor_id := `Some` if the item is a struct_ctor (tuple struct),
392 // If the item is a struct_ctor, then either its `id` or
393 // `ctor_id` (unwrapped) is in the live_symbols set. More specifically,
394 // DefMap maps the ExprPath of a struct_ctor to the node referred by
395 // `ctor_id`. On the other hand, in a statement like
396 // `type <ident> <generics> = <ty>;` where <ty> refers to a struct_ctor,
397 // DefMap maps <ty> to `id` instead.
398 fn symbol_is_live(&mut self, id: ast::NodeId,
399 ctor_id: Option<ast::NodeId>) -> bool {
400 if self.live_symbols.contains(&id)
401 || ctor_id.map_or(false,
402 |ctor| self.live_symbols.contains(&ctor)) {
405 // If it's a type whose methods are live, then it's live, too.
406 // This is done to handle the case where, for example, the static
407 // method of a private type is used, but the type itself is never
409 let impl_methods = self.tcx.impl_methods.borrow();
410 match self.tcx.inherent_impls.borrow().find(&local_def(id)) {
413 for impl_did in impl_list.borrow().iter() {
414 for method_did in impl_methods.get(impl_did).iter() {
415 if self.live_symbols.contains(&method_did.node) {
425 fn warn_dead_code(&mut self,
434 format!("code is never used: `{}`",
435 token::get_ident(ident)));
439 impl<'a> Visitor<()> for DeadVisitor<'a> {
440 fn visit_item(&mut self, item: &ast::Item, _: ()) {
441 let ctor_id = get_struct_ctor_id(item);
442 if !self.symbol_is_live(item.id, ctor_id) && should_warn(item) {
443 self.warn_dead_code(item.id, item.span, item.ident);
445 visit::walk_item(self, item, ());
448 fn visit_foreign_item(&mut self, fi: &ast::ForeignItem, _: ()) {
449 if !self.symbol_is_live(fi.id, None) {
450 self.warn_dead_code(fi.id, fi.span, fi.ident);
452 visit::walk_foreign_item(self, fi, ());
455 fn visit_fn(&mut self, fk: &visit::FnKind,
456 _: &ast::FnDecl, block: &ast::Block,
457 span: codemap::Span, id: ast::NodeId, _: ()) {
458 // Have to warn method here because methods are not ast::Item
460 visit::FkMethod(..) => {
461 let ident = visit::name_of_fn(fk);
462 if !self.symbol_is_live(id, None) {
463 self.warn_dead_code(id, span, ident);
468 visit::walk_block(self, block, ());
471 fn visit_struct_field(&mut self, field: &ast::StructField, _: ()) {
472 if self.should_warn_about_field(&field.node) {
473 self.warn_dead_code(field.node.id, field.span, field.node.ident().unwrap());
476 visit::walk_struct_field(self, field, ());
479 // Overwrite so that we don't warn the trait method itself.
480 fn visit_trait_method(&mut self, trait_method: &ast::TraitMethod, _: ()) {
481 match *trait_method {
482 ast::Provided(ref method) => visit::walk_block(self, &*method.body, ()),
483 ast::Required(_) => ()
488 pub fn check_crate(tcx: &ty::ctxt,
489 exported_items: &privacy::ExportedItems,
490 reachable_symbols: &NodeSet,
491 krate: &ast::Crate) {
492 let live_symbols = find_live(tcx, exported_items,
493 reachable_symbols, krate);
494 let mut visitor = DeadVisitor { tcx: tcx, live_symbols: live_symbols };
495 visit::walk_crate(&mut visitor, krate, ());