]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check_unused.rs
Fixes issue #43205: ICE in Rvalue::Len evaluation.
[rust.git] / src / librustc_typeck / check_unused.rs
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.
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 use lint;
12 use rustc::ty::TyCtxt;
13
14 use syntax::ast;
15 use syntax_pos::{Span, DUMMY_SP};
16
17 use rustc::hir;
18 use rustc::hir::itemlikevisit::ItemLikeVisitor;
19 use rustc::util::nodemap::DefIdSet;
20
21 struct CheckVisitor<'a, 'tcx: 'a> {
22     tcx: TyCtxt<'a, 'tcx, 'tcx>,
23     used_trait_imports: DefIdSet,
24 }
25
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) {
29             return;
30         }
31
32         let import_def_id = self.tcx.hir.local_def_id(id);
33         if self.used_trait_imports.contains(&import_def_id) {
34             return;
35         }
36
37         let msg = if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(span) {
38             format!("unused import: `{}`", snippet)
39         } else {
40             "unused import".to_string()
41         };
42         self.tcx.lint_node(lint::builtin::UNUSED_IMPORTS, id, span, &msg);
43     }
44 }
45
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 {
49             return;
50         }
51         if let hir::ItemUse(ref path, _) = item.node {
52             self.check_import(item.id, path.span);
53         }
54     }
55
56     fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
57     }
58
59     fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
60     }
61 }
62
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);
71     }
72
73     let mut visitor = CheckVisitor { tcx, used_trait_imports };
74     tcx.hir.krate().visit_all_item_likes(&mut visitor);
75 }