Skip to content

Commit c06dd0e

Browse files
committed
Add dead-code warning pass
1 parent 49b751d commit c06dd0e

33 files changed

+572
-53
lines changed

src/etc/extract-tests.py

+1
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@
6464
#[ allow(dead_assignment) ];\n
6565
#[ allow(unused_mut) ];\n
6666
#[ allow(attribute_usage) ];\n
67+
#[ allow(dead_code) ];\n
6768
#[ feature(macro_rules, globs, struct_variant, managed_boxes) ];\n
6869
""" + block
6970
if xfail:

src/librustc/driver/driver.rs

+4-13
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,10 @@ pub fn phase_3_run_analysis_passes(sess: Session,
310310
time(time_passes, "reachability checking", (), |_|
311311
reachable::find_reachable(ty_cx, method_map, &exported_items));
312312

313+
time(time_passes, "death checking", (), |_|
314+
middle::dead::check_crate(ty_cx, method_map,
315+
&exported_items, reachable_map, crate));
316+
313317
time(time_passes, "lint checking", (), |_|
314318
lint::check_crate(ty_cx, &exported_items, crate));
315319

@@ -510,19 +514,6 @@ pub fn pretty_print_input(sess: Session,
510514
cfg: ast::CrateConfig,
511515
input: &input,
512516
ppm: PpMode) {
513-
fn ann_typed_post(tcx: ty::ctxt, node: pprust::ann_node) {
514-
match node {
515-
pprust::node_expr(s, expr) => {
516-
pp::space(s.s);
517-
pp::word(s.s, "as");
518-
pp::space(s.s);
519-
pp::word(s.s, ppaux::ty_to_str(tcx, ty::expr_ty(tcx, expr)));
520-
pprust::pclose(s);
521-
}
522-
_ => ()
523-
}
524-
}
525-
526517
let crate = phase_1_parse_input(sess, cfg.clone(), input);
527518

528519
let (crate, is_expanded) = match ppm {

src/librustc/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ pub mod middle {
7777
pub mod reachable;
7878
pub mod graph;
7979
pub mod cfg;
80+
pub mod dead;
8081
}
8182

8283
pub mod front {

src/librustc/middle/dead.rs

+352
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,352 @@
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.
4+
//
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.
10+
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.
14+
15+
use middle::ty;
16+
use middle::typeck;
17+
use middle::privacy;
18+
use middle::lint::dead_code;
19+
20+
use std::hashmap::HashSet;
21+
use syntax::ast;
22+
use syntax::ast_map;
23+
use syntax::ast_util::{local_def, def_id_of_def, is_local};
24+
use syntax::codemap;
25+
use syntax::parse::token;
26+
use syntax::visit::Visitor;
27+
use syntax::visit;
28+
29+
// Any local node that may call something in its body block should be
30+
// explored. For example, if it's a live node_item that is a
31+
// function, then we should explore its block to check for codes that
32+
// may need to be marked as live.
33+
fn should_explore(tcx: ty::ctxt, def_id: ast::DefId) -> bool {
34+
if !is_local(def_id) {
35+
return false;
36+
}
37+
match tcx.items.find(&def_id.node) {
38+
Some(&ast_map::node_item(..))
39+
| Some(&ast_map::node_method(..))
40+
| Some(&ast_map::node_trait_method(..)) => true,
41+
_ => false
42+
}
43+
}
44+
45+
struct MarkSymbolVisitor {
46+
worklist: ~[ast::NodeId],
47+
method_map: typeck::method_map,
48+
tcx: ty::ctxt,
49+
live_symbols: ~HashSet<ast::NodeId>,
50+
}
51+
52+
impl MarkSymbolVisitor {
53+
fn new(tcx: ty::ctxt,
54+
method_map: typeck::method_map,
55+
worklist: ~[ast::NodeId]) -> MarkSymbolVisitor {
56+
MarkSymbolVisitor {
57+
worklist: worklist,
58+
method_map: method_map,
59+
tcx: tcx,
60+
live_symbols: ~HashSet::new(),
61+
}
62+
}
63+
64+
fn lookup_and_handle_definition(&mut self, id: &ast::NodeId,
65+
span: codemap::Span) {
66+
let def = match self.tcx.def_map.find(id) {
67+
Some(&def) => def,
68+
None => self.tcx.sess.span_bug(span, "def ID not in def map?!"),
69+
};
70+
let def_id = match def {
71+
ast::DefVariant(enum_id, _, _) => Some(enum_id),
72+
ast::DefPrimTy(_) => None,
73+
_ => Some(def_id_of_def(def)),
74+
};
75+
match def_id {
76+
Some(def_id) => {
77+
if should_explore(self.tcx, def_id) {
78+
self.worklist.push(def_id.node);
79+
}
80+
self.live_symbols.insert(def_id.node);
81+
}
82+
None => (),
83+
}
84+
}
85+
86+
fn mark_live_symbols(&mut self) {
87+
let mut scanned = HashSet::new();
88+
while self.worklist.len() > 0 {
89+
let id = self.worklist.pop();
90+
if scanned.contains(&id) {
91+
continue
92+
}
93+
scanned.insert(id);
94+
match self.tcx.items.find(&id) {
95+
Some(node) => {
96+
self.live_symbols.insert(id);
97+
self.visit_node(node);
98+
}
99+
None => (),
100+
}
101+
}
102+
}
103+
104+
fn visit_node(&mut self, node: &ast_map::ast_node) {
105+
match *node {
106+
ast_map::node_item(item, _) => {
107+
match item.node {
108+
ast::item_fn(..)
109+
| ast::item_ty(..)
110+
| ast::item_static(..)
111+
| ast::item_foreign_mod(_) => {
112+
visit::walk_item(self, item, ());
113+
}
114+
_ => ()
115+
}
116+
}
117+
ast_map::node_trait_method(trait_method, _, _) => {
118+
visit::walk_trait_method(self, trait_method, ());
119+
}
120+
ast_map::node_method(method, _, _) => {
121+
visit::walk_block(self, method.body, ());
122+
}
123+
_ => ()
124+
}
125+
}
126+
}
127+
128+
impl Visitor<()> for MarkSymbolVisitor {
129+
130+
fn visit_expr(&mut self, expr: @ast::Expr, _: ()) {
131+
match expr.node {
132+
ast::ExprPath(_) | ast::ExprStruct(..) => {
133+
self.lookup_and_handle_definition(&expr.id, expr.span);
134+
}
135+
ast::ExprMethodCall(..) => {
136+
match self.method_map.find(&expr.id) {
137+
Some(&typeck::method_map_entry {
138+
origin: typeck::method_static(def_id),
139+
..
140+
}) => {
141+
if should_explore(self.tcx, def_id) {
142+
self.worklist.push(def_id.node);
143+
}
144+
self.live_symbols.insert(def_id.node);
145+
}
146+
Some(_) => (),
147+
None => {
148+
self.tcx.sess.span_bug(expr.span,
149+
"method call expression not \
150+
in method map?!")
151+
}
152+
}
153+
}
154+
_ => ()
155+
}
156+
157+
visit::walk_expr(self, expr, ())
158+
}
159+
160+
fn visit_ty(&mut self, typ: &ast::Ty, _: ()) {
161+
match typ.node {
162+
ast::ty_path(_, _, ref id) => {
163+
self.lookup_and_handle_definition(id, typ.span);
164+
}
165+
_ => visit::walk_ty(self, typ, ()),
166+
}
167+
}
168+
169+
fn visit_item(&mut self, _item: @ast::item, _: ()) {
170+
// Do not recurse into items. These items will be added to the
171+
// worklist and recursed into manually if necessary.
172+
}
173+
}
174+
175+
// This visitor is used to mark the implemented methods of a trait. Since we
176+
// can not be sure if such methods are live or dead, we simply mark them
177+
// as live.
178+
struct TraitMethodSeeder {
179+
worklist: ~[ast::NodeId],
180+
}
181+
182+
impl Visitor<()> for TraitMethodSeeder {
183+
fn visit_item(&mut self, item: @ast::item, _: ()) {
184+
match item.node {
185+
ast::item_impl(_, Some(ref _trait_ref), _, ref methods) => {
186+
for method in methods.iter() {
187+
self.worklist.push(method.id);
188+
}
189+
}
190+
ast::item_mod(..) | ast::item_fn(..) => {
191+
visit::walk_item(self, item, ());
192+
}
193+
_ => ()
194+
}
195+
}
196+
}
197+
198+
fn create_and_seed_worklist(tcx: ty::ctxt,
199+
exported_items: &privacy::ExportedItems,
200+
reachable_symbols: &HashSet<ast::NodeId>,
201+
crate: &ast::Crate) -> ~[ast::NodeId] {
202+
let mut worklist = ~[];
203+
204+
// Preferably, we would only need to seed the worklist with reachable
205+
// symbols. However, since the set of reachable symbols differs
206+
// depending on whether a crate is built as bin or lib, and we want
207+
// the warning to be consistent, we also seed the worklist with
208+
// exported symbols.
209+
for &id in exported_items.iter() {
210+
worklist.push(id);
211+
}
212+
for &id in reachable_symbols.iter() {
213+
worklist.push(id);
214+
}
215+
216+
// Seed entry point
217+
match *tcx.sess.entry_fn {
218+
Some((id, _)) => worklist.push(id),
219+
None => ()
220+
}
221+
222+
// Seed implemeneted trait methods
223+
let mut trait_method_seeder = TraitMethodSeeder {
224+
worklist: worklist
225+
};
226+
visit::walk_crate(&mut trait_method_seeder, crate, ());
227+
228+
return trait_method_seeder.worklist;
229+
}
230+
231+
fn find_live(tcx: ty::ctxt,
232+
method_map: typeck::method_map,
233+
exported_items: &privacy::ExportedItems,
234+
reachable_symbols: &HashSet<ast::NodeId>,
235+
crate: &ast::Crate)
236+
-> ~HashSet<ast::NodeId> {
237+
let worklist = create_and_seed_worklist(tcx, exported_items,
238+
reachable_symbols, crate);
239+
let mut symbol_visitor = MarkSymbolVisitor::new(tcx, method_map, worklist);
240+
symbol_visitor.mark_live_symbols();
241+
symbol_visitor.live_symbols
242+
}
243+
244+
fn should_warn(item: @ast::item) -> bool {
245+
match item.node {
246+
ast::item_static(..)
247+
| ast::item_fn(..)
248+
| ast::item_enum(..)
249+
| ast::item_struct(..) => true,
250+
_ => false
251+
}
252+
}
253+
254+
fn get_struct_ctor_id(item: &ast::item) -> Option<ast::NodeId> {
255+
match item.node {
256+
ast::item_struct(struct_def, _) => struct_def.ctor_id,
257+
_ => None
258+
}
259+
}
260+
261+
struct DeadVisitor {
262+
tcx: ty::ctxt,
263+
live_symbols: ~HashSet<ast::NodeId>,
264+
}
265+
266+
impl DeadVisitor {
267+
// id := node id of an item's definition.
268+
// ctor_id := `Some` if the item is a struct_ctor (tuple struct),
269+
// `None` otherwise.
270+
// If the item is a struct_ctor, then either its `id` or
271+
// `ctor_id` (unwrapped) is in the live_symbols set. More specifically,
272+
// DefMap maps the ExprPath of a struct_ctor to the node referred by
273+
// `ctor_id`. On the other hand, in a statement like
274+
// `type <ident> <generics> = <ty>;` where <ty> refers to a struct_ctor,
275+
// DefMap maps <ty> to `id` instead.
276+
fn symbol_is_live(&mut self, id: ast::NodeId,
277+
ctor_id: Option<ast::NodeId>) -> bool {
278+
if self.live_symbols.contains(&id)
279+
|| ctor_id.map_default(false,
280+
|ctor| self.live_symbols.contains(&ctor)) {
281+
return true;
282+
}
283+
// If it's a type whose methods are live, then it's live, too.
284+
// This is done to handle the case where, for example, the static
285+
// method of a private type is used, but the type itself is never
286+
// called directly.
287+
let def_id = local_def(id);
288+
match self.tcx.inherent_impls.find(&def_id) {
289+
None => (),
290+
Some(ref impl_list) => {
291+
for impl_ in impl_list.iter() {
292+
for method in impl_.methods.iter() {
293+
if self.live_symbols.contains(&method.def_id.node) {
294+
return true;
295+
}
296+
}
297+
}
298+
}
299+
}
300+
false
301+
}
302+
}
303+
304+
impl Visitor<()> for DeadVisitor {
305+
fn visit_item(&mut self, item: @ast::item, _: ()) {
306+
let ctor_id = get_struct_ctor_id(item);
307+
if !self.symbol_is_live(item.id, ctor_id) && should_warn(item) {
308+
self.tcx.sess.add_lint(dead_code, item.id, item.span,
309+
format!("code is never used: `{}`",
310+
token::ident_to_str(&item.ident)));
311+
}
312+
visit::walk_item(self, item, ());
313+
}
314+
315+
fn visit_fn(&mut self, fk: &visit::fn_kind,
316+
_: &ast::fn_decl, block: ast::P<ast::Block>,
317+
span: codemap::Span, id: ast::NodeId, _: ()) {
318+
// Have to warn method here because methods are not ast::item
319+
match *fk {
320+
visit::fk_method(..) => {
321+
let ident = visit::name_of_fn(fk);
322+
if !self.symbol_is_live(id, None) {
323+
self.tcx.sess
324+
.add_lint(dead_code, id, span,
325+
format!("code is never used: `{}`",
326+
token::ident_to_str(&ident)));
327+
}
328+
}
329+
_ => ()
330+
}
331+
visit::walk_block(self, block, ());
332+
}
333+
334+
// Overwrite so that we don't warn the trait method itself.
335+
fn visit_trait_method(&mut self, trait_method :&ast::trait_method, _: ()) {
336+
match *trait_method {
337+
ast::provided(method) => visit::walk_block(self, method.body, ()),
338+
ast::required(_) => ()
339+
}
340+
}
341+
}
342+
343+
pub fn check_crate(tcx: ty::ctxt,
344+
method_map: typeck::method_map,
345+
exported_items: &privacy::ExportedItems,
346+
reachable_symbols: &HashSet<ast::NodeId>,
347+
crate: &ast::Crate) {
348+
let live_symbols = find_live(tcx, method_map, exported_items,
349+
reachable_symbols, crate);
350+
let mut visitor = DeadVisitor { tcx: tcx, live_symbols: live_symbols };
351+
visit::walk_crate(&mut visitor, crate, ());
352+
}

0 commit comments

Comments
 (0)