Skip to content

Commit e4f534c

Browse files
committed
Warn unused trait imports
1 parent 4c01c93 commit e4f534c

File tree

13 files changed

+169
-25
lines changed

13 files changed

+169
-25
lines changed

src/librustc/dep_graph/dep_node.rs

+2
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ pub enum DepNode<D: Clone + Debug> {
5959
TypeckItemBody(D),
6060
Dropck,
6161
DropckImpl(D),
62+
UnusedTraitCheck,
6263
CheckConst(D),
6364
Privacy,
6465
IntrinsicCheck(D),
@@ -164,6 +165,7 @@ impl<D: Clone + Debug> DepNode<D> {
164165
CheckEntryFn => Some(CheckEntryFn),
165166
Variance => Some(Variance),
166167
Dropck => Some(Dropck),
168+
UnusedTraitCheck => Some(UnusedTraitCheck),
167169
Privacy => Some(Privacy),
168170
Reachability => Some(Reachability),
169171
DeadCheck => Some(DeadCheck),

src/librustc/hir/mod.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -1637,8 +1637,13 @@ pub type FreevarMap = NodeMap<Vec<Freevar>>;
16371637

16381638
pub type CaptureModeMap = NodeMap<CaptureClause>;
16391639

1640+
pub struct TraitCandidate {
1641+
pub def_id: DefId,
1642+
pub import_id: Option<NodeId>,
1643+
}
1644+
16401645
// Trait method resolution
1641-
pub type TraitMap = NodeMap<Vec<DefId>>;
1646+
pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
16421647

16431648
// Map from the NodeId of a glob import to a list of items which are actually
16441649
// imported.

src/librustc/ty/context.rs

+9
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,8 @@ pub struct TyCtxt<'tcx> {
285285
// scratch every time.
286286
pub freevars: RefCell<FreevarMap>,
287287

288+
pub maybe_unused_trait_imports: NodeSet,
289+
288290
// Records the type of every item.
289291
pub tcache: RefCell<DepTrackingMap<maps::Tcache<'tcx>>>,
290292

@@ -334,6 +336,10 @@ pub struct TyCtxt<'tcx> {
334336
/// about.
335337
pub used_mut_nodes: RefCell<NodeSet>,
336338

339+
/// Set of trait imports actually used in the method resolution.
340+
/// This is used for warning unused imports.
341+
pub used_trait_imports: RefCell<NodeSet>,
342+
337343
/// The set of external nominal types whose implementations have been read.
338344
/// This is used for lazy resolution of methods.
339345
pub populated_external_types: RefCell<DefIdSet>,
@@ -524,6 +530,7 @@ impl<'tcx> TyCtxt<'tcx> {
524530
named_region_map: resolve_lifetime::NamedRegionMap,
525531
map: ast_map::Map<'tcx>,
526532
freevars: FreevarMap,
533+
maybe_unused_trait_imports: NodeSet,
527534
region_maps: RegionMaps,
528535
lang_items: middle::lang_items::LanguageItems,
529536
stability: stability::Index<'tcx>,
@@ -560,6 +567,7 @@ impl<'tcx> TyCtxt<'tcx> {
560567
fulfilled_predicates: RefCell::new(fulfilled_predicates),
561568
map: map,
562569
freevars: RefCell::new(freevars),
570+
maybe_unused_trait_imports: maybe_unused_trait_imports,
563571
tcache: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
564572
rcache: RefCell::new(FnvHashMap()),
565573
tc_cache: RefCell::new(FnvHashMap()),
@@ -574,6 +582,7 @@ impl<'tcx> TyCtxt<'tcx> {
574582
impl_items: RefCell::new(DepTrackingMap::new(dep_graph.clone())),
575583
used_unsafe: RefCell::new(NodeSet()),
576584
used_mut_nodes: RefCell::new(NodeSet()),
585+
used_trait_imports: RefCell::new(NodeSet()),
577586
populated_external_types: RefCell::new(DefIdSet()),
578587
populated_external_primitive_impls: RefCell::new(DefIdSet()),
579588
extern_const_statics: RefCell::new(DefIdMap()),

src/librustc_driver/driver.rs

+2
Original file line numberDiff line numberDiff line change
@@ -775,6 +775,7 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
775775
let resolve::CrateMap {
776776
def_map,
777777
freevars,
778+
maybe_unused_trait_imports,
778779
export_map,
779780
trait_map,
780781
glob_map,
@@ -824,6 +825,7 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
824825
named_region_map,
825826
hir_map,
826827
freevars,
828+
maybe_unused_trait_imports,
827829
region_map,
828830
lang_items,
829831
index,

src/librustc_driver/test.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ fn test_env<F>(source_string: &str,
129129

130130
// run just enough stuff to build a tcx:
131131
let lang_items = lang_items::collect_language_items(&sess, &ast_map);
132-
let resolve::CrateMap { def_map, freevars, .. } =
132+
let resolve::CrateMap { def_map, freevars, maybe_unused_trait_imports, .. } =
133133
resolve::resolve_crate(&sess, &ast_map, resolve::MakeGlobMap::No);
134134
let named_region_map = resolve_lifetime::krate(&sess, &ast_map, &def_map.borrow());
135135
let region_map = region::resolve_crate(&sess, &ast_map);
@@ -140,6 +140,7 @@ fn test_env<F>(source_string: &str,
140140
named_region_map.unwrap(),
141141
ast_map,
142142
freevars,
143+
maybe_unused_trait_imports,
143144
region_map,
144145
lang_items,
145146
index,

src/librustc_resolve/check_unused.rs

+10
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
// resolve data structures and because it finalises the privacy information for
1717
// `use` directives.
1818
//
19+
// Unused trait imports can't be checked until the method resolution. We save
20+
// candidates here, and do the acutal check in librustc_typeck/check_unused.rs.
1921

2022
use std::ops::{Deref, DerefMut};
2123

@@ -55,10 +57,18 @@ impl<'a, 'b, 'tcx> UnusedImportCheckVisitor<'a, 'b, 'tcx> {
5557
fn check_import(&mut self, id: ast::NodeId, span: Span) {
5658
if !self.used_imports.contains(&(id, TypeNS)) &&
5759
!self.used_imports.contains(&(id, ValueNS)) {
60+
if self.maybe_unused_trait_imports.contains(&id) {
61+
// Check later.
62+
return;
63+
}
5864
self.session.add_lint(lint::builtin::UNUSED_IMPORTS,
5965
id,
6066
span,
6167
"unused import".to_string());
68+
} else {
69+
// This trait import is definitely used, in a way other than
70+
// method resolution.
71+
self.maybe_unused_trait_imports.remove(&id);
6272
}
6373
}
6474
}

src/librustc_resolve/lib.rs

+32-13
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,8 @@ use rustc::hir::def_id::DefId;
5353
use rustc::hir::pat_util::pat_bindings;
5454
use rustc::ty;
5555
use rustc::ty::subst::{ParamSpace, FnSpace, TypeSpace};
56-
use rustc::hir::{Freevar, FreevarMap, TraitMap, GlobMap};
57-
use rustc::util::nodemap::{NodeMap, FnvHashMap, FnvHashSet};
56+
use rustc::hir::{Freevar, FreevarMap, TraitCandidate, TraitMap, GlobMap};
57+
use rustc::util::nodemap::{NodeMap, NodeSet, FnvHashMap, FnvHashSet};
5858

5959
use syntax::ast::{self, FloatTy};
6060
use syntax::ast::{CRATE_NODE_ID, Name, NodeId, CrateNum, IntTy, UintTy};
@@ -1091,6 +1091,7 @@ pub struct Resolver<'a, 'tcx: 'a> {
10911091

10921092
used_imports: HashSet<(NodeId, Namespace)>,
10931093
used_crates: HashSet<CrateNum>,
1094+
maybe_unused_trait_imports: NodeSet,
10941095

10951096
// Callback function for intercepting walks
10961097
callback: Option<Box<Fn(hir_map::Node, &mut bool) -> bool>>,
@@ -1181,13 +1182,15 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
11811182
export_map: NodeMap(),
11821183
trait_map: NodeMap(),
11831184
module_map: NodeMap(),
1184-
used_imports: HashSet::new(),
1185-
used_crates: HashSet::new(),
11861185

11871186
emit_errors: true,
11881187
make_glob_map: make_glob_map == MakeGlobMap::Yes,
11891188
glob_map: NodeMap(),
11901189

1190+
used_imports: HashSet::new(),
1191+
used_crates: HashSet::new(),
1192+
maybe_unused_trait_imports: NodeSet(),
1193+
11911194
callback: None,
11921195
resolved: false,
11931196
privacy_errors: Vec::new(),
@@ -1230,7 +1233,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
12301233
}
12311234

12321235
#[inline]
1233-
fn record_use(&mut self, name: Name, ns: Namespace, binding: &'a NameBinding<'a>) {
1236+
fn record_use(&mut self, name: Name, binding: &'a NameBinding<'a>) {
12341237
// track extern crates for unused_extern_crate lint
12351238
if let Some(DefId { krate, .. }) = binding.module().and_then(ModuleS::def_id) {
12361239
self.used_crates.insert(krate);
@@ -1242,7 +1245,6 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
12421245
_ => return,
12431246
};
12441247

1245-
self.used_imports.insert((directive.id, ns));
12461248
if let Some(error) = privacy_error.as_ref() {
12471249
self.privacy_errors.push((**error).clone());
12481250
}
@@ -1553,7 +1555,10 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
15531555
false => module.resolve_name(name, namespace, false),
15541556
}.and_then(|binding| {
15551557
if record_used {
1556-
self.record_use(name, namespace, binding);
1558+
if let NameBindingKind::Import { directive, .. } = binding.kind {
1559+
self.used_imports.insert((directive.id, namespace));
1560+
}
1561+
self.record_use(name, binding);
15571562
}
15581563
Success(binding)
15591564
})
@@ -3215,21 +3220,27 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
32153220
}
32163221
}
32173222

3218-
fn get_traits_containing_item(&mut self, name: Name) -> Vec<DefId> {
3223+
fn get_traits_containing_item(&mut self, name: Name) -> Vec<TraitCandidate> {
32193224
debug!("(getting traits containing item) looking for '{}'", name);
32203225

3221-
fn add_trait_info(found_traits: &mut Vec<DefId>, trait_def_id: DefId, name: Name) {
3226+
fn add_trait_info(found_traits: &mut Vec<TraitCandidate>,
3227+
trait_def_id: DefId,
3228+
import_id: Option<NodeId>,
3229+
name: Name) {
32223230
debug!("(adding trait info) found trait {:?} for method '{}'",
32233231
trait_def_id,
32243232
name);
3225-
found_traits.push(trait_def_id);
3233+
found_traits.push(TraitCandidate {
3234+
def_id: trait_def_id,
3235+
import_id: import_id,
3236+
});
32263237
}
32273238

32283239
let mut found_traits = Vec::new();
32293240
// Look for the current trait.
32303241
if let Some((trait_def_id, _)) = self.current_trait_ref {
32313242
if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3232-
add_trait_info(&mut found_traits, trait_def_id, name);
3243+
add_trait_info(&mut found_traits, trait_def_id, None, name);
32333244
}
32343245
}
32353246

@@ -3252,9 +3263,15 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
32523263
for binding in traits.as_ref().unwrap().iter() {
32533264
let trait_def_id = binding.def().unwrap().def_id();
32543265
if self.trait_item_map.contains_key(&(name, trait_def_id)) {
3255-
add_trait_info(&mut found_traits, trait_def_id, name);
3266+
let mut import_id = None;
3267+
if let NameBindingKind::Import { directive, .. } = binding.kind {
3268+
let id = directive.id;
3269+
self.maybe_unused_trait_imports.insert(id);
3270+
import_id = Some(id);
3271+
}
3272+
add_trait_info(&mut found_traits, trait_def_id, import_id, name);
32563273
let trait_name = self.get_trait_name(trait_def_id);
3257-
self.record_use(trait_name, TypeNS, binding);
3274+
self.record_use(trait_name, binding);
32583275
}
32593276
}
32603277
};
@@ -3634,6 +3651,7 @@ fn err_path_resolution() -> PathResolution {
36343651
pub struct CrateMap {
36353652
pub def_map: RefCell<DefMap>,
36363653
pub freevars: FreevarMap,
3654+
pub maybe_unused_trait_imports: NodeSet,
36373655
pub export_map: ExportMap,
36383656
pub trait_map: TraitMap,
36393657
pub glob_map: Option<GlobMap>,
@@ -3671,6 +3689,7 @@ pub fn resolve_crate<'a, 'tcx>(session: &'a Session,
36713689
CrateMap {
36723690
def_map: resolver.def_map,
36733691
freevars: resolver.freevars,
3692+
maybe_unused_trait_imports: resolver.maybe_unused_trait_imports,
36743693
export_map: resolver.export_map,
36753694
trait_map: resolver.trait_map,
36763695
glob_map: if resolver.make_glob_map {

src/librustc_typeck/check/method/mod.rs

+10-1
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,11 @@ pub fn lookup<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
128128
let mode = probe::Mode::MethodCall;
129129
let self_ty = fcx.infcx().resolve_type_vars_if_possible(&self_ty);
130130
let pick = probe::probe(fcx, span, mode, method_name, self_ty, call_expr.id)?;
131+
132+
if let Some(import_id) = pick.import_id {
133+
fcx.tcx().used_trait_imports.borrow_mut().insert(import_id);
134+
}
135+
131136
Ok(confirm::confirm(fcx, span, self_expr, call_expr, self_ty, pick, supplied_method_types))
132137
}
133138

@@ -339,8 +344,12 @@ pub fn resolve_ufcs<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
339344
{
340345
let mode = probe::Mode::Path;
341346
let pick = probe::probe(fcx, span, mode, method_name, self_ty, expr_id)?;
342-
let def = pick.item.def();
343347

348+
if let Some(import_id) = pick.import_id {
349+
fcx.tcx().used_trait_imports.borrow_mut().insert(import_id);
350+
}
351+
352+
let def = pick.item.def();
344353
if let probe::InherentImplPick = pick.kind {
345354
if !pick.item.vis().is_accessible_from(fcx.body_id, &fcx.tcx().map) {
346355
let msg = format!("{} `{}` is private", def.kind_name(), &method_name.as_str());

0 commit comments

Comments
 (0)