1 // Copyright 2016 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.
12 use rustc::ty::TyCtxt;
15 use syntax_pos::{Span, DUMMY_SP};
18 use rustc::hir::itemlikevisit::ItemLikeVisitor;
19 use rustc::util::nodemap::DefIdSet;
21 struct CheckVisitor<'a, 'tcx: 'a> {
22 tcx: TyCtxt<'a, 'tcx, 'tcx>,
23 used_trait_imports: DefIdSet,
26 impl<'a, 'tcx> CheckVisitor<'a, 'tcx> {
27 fn check_import(&self, id: ast::NodeId, span: Span) {
28 if !self.tcx.maybe_unused_trait_imports.contains(&id) {
32 let import_def_id = self.tcx.hir.local_def_id(id);
33 if self.used_trait_imports.contains(&import_def_id) {
37 let msg = if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
38 format!("unused import: `{}`", snippet)
40 "unused import".to_string()
42 self.tcx.lint_node(lint::builtin::UNUSED_IMPORTS, id, span, &msg);
46 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for CheckVisitor<'a, 'tcx> {
47 fn visit_item(&mut self, item: &hir::Item) {
48 if item.vis == hir::Public || item.span == DUMMY_SP {
51 if let hir::ItemUse(ref path, _) = item.node {
52 self.check_import(item.id, path.span);
56 fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
59 fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
63 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
64 let mut used_trait_imports = DefIdSet();
65 for &body_id in tcx.hir.krate().bodies.keys() {
66 let item_def_id = tcx.hir.body_owner_def_id(body_id);
67 let tables = tcx.typeck_tables_of(item_def_id);
68 let imports = &tables.used_trait_imports;
69 debug!("GatherVisitor: item_def_id={:?} with imports {:#?}", item_def_id, imports);
70 used_trait_imports.extend(imports);
73 let mut visitor = CheckVisitor { tcx, used_trait_imports };
74 tcx.hir.krate().visit_all_item_likes(&mut visitor);