]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check_unused.rs
bf767726ef715d9f2321aecf4c6fd1c4c7ae9999
[rust.git] / src / librustc_typeck / check_unused.rs
1 use lint;
2 use rustc::ty::TyCtxt;
3
4 use errors::Applicability;
5 use syntax::ast;
6 use syntax_pos::Span;
7
8 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
9 use rustc::hir::itemlikevisit::ItemLikeVisitor;
10 use rustc::hir::print::visibility_qualified;
11 use rustc::hir;
12 use rustc::util::nodemap::DefIdSet;
13
14 use rustc_data_structures::fx::FxHashMap;
15
16 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
17     let mut used_trait_imports = DefIdSet::default();
18     for &body_id in tcx.hir().krate().bodies.keys() {
19         let item_def_id = tcx.hir().body_owner_def_id(body_id);
20         let imports = tcx.used_trait_imports(item_def_id);
21         debug!("GatherVisitor: item_def_id={:?} with imports {:#?}", item_def_id, imports);
22         used_trait_imports.extend(imports.iter());
23     }
24
25     let mut visitor = CheckVisitor { tcx, used_trait_imports };
26     tcx.hir().krate().visit_all_item_likes(&mut visitor);
27
28     unused_crates_lint(tcx);
29 }
30
31 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for CheckVisitor<'a, 'tcx> {
32     fn visit_item(&mut self, item: &hir::Item) {
33         if item.vis.node.is_pub() || item.span.is_dummy() {
34             return;
35         }
36         if let hir::ItemKind::Use(ref path, _) = item.node {
37             self.check_import(item.id, path.span);
38         }
39     }
40
41     fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
42     }
43
44     fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
45     }
46 }
47
48 struct CheckVisitor<'a, 'tcx: 'a> {
49     tcx: TyCtxt<'a, 'tcx, 'tcx>,
50     used_trait_imports: DefIdSet,
51 }
52
53 impl<'a, 'tcx> CheckVisitor<'a, 'tcx> {
54     fn check_import(&self, id: ast::NodeId, span: Span) {
55         let def_id = self.tcx.hir().local_def_id(id);
56         if !self.tcx.maybe_unused_trait_import(def_id) {
57             return;
58         }
59
60         let import_def_id = self.tcx.hir().local_def_id(id);
61         if self.used_trait_imports.contains(&import_def_id) {
62             return;
63         }
64
65         let msg = if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
66             format!("unused import: `{}`", snippet)
67         } else {
68             "unused import".to_owned()
69         };
70         self.tcx.lint_node(lint::builtin::UNUSED_IMPORTS, id, span, &msg);
71     }
72 }
73
74 fn unused_crates_lint<'tcx>(tcx: TyCtxt<'_, 'tcx, 'tcx>) {
75     let lint = lint::builtin::UNUSED_EXTERN_CRATES;
76
77     // Collect first the crates that are completely unused.  These we
78     // can always suggest removing (no matter which edition we are
79     // in).
80     let unused_extern_crates: FxHashMap<DefId, Span> =
81         tcx.maybe_unused_extern_crates(LOCAL_CRATE)
82         .iter()
83         .filter(|&&(def_id, _)| {
84             // The `def_id` here actually was calculated during resolution (at least
85             // at the time of this writing) and is being shipped to us via a side
86             // channel of the tcx. There may have been extra expansion phases,
87             // however, which ended up removing the `def_id` *after* expansion such
88             // as the `ReplaceBodyWithLoop` pass (which is a bit of a hack, but hey)
89             //
90             // As a result we need to verify that `def_id` is indeed still valid for
91             // our AST and actually present in the HIR map. If it's not there then
92             // there's safely nothing to warn about, and otherwise we carry on with
93             // our execution.
94             //
95             // Note that if we carry through to the `extern_mod_stmt_cnum` query
96             // below it'll cause a panic because `def_id` is actually bogus at this
97             // point in time otherwise.
98             if let Some(id) = tcx.hir().as_local_node_id(def_id) {
99                 if tcx.hir().find(id).is_none() {
100                     return false;
101                 }
102             }
103             true
104         })
105         .filter(|&&(def_id, _)| {
106             tcx.extern_mod_stmt_cnum(def_id).map_or(true, |cnum| {
107                 !tcx.is_compiler_builtins(cnum) &&
108                 !tcx.is_panic_runtime(cnum) &&
109                 !tcx.has_global_allocator(cnum) &&
110                 !tcx.has_panic_handler(cnum)
111             })
112         })
113         .cloned()
114         .collect();
115
116     // Collect all the extern crates (in a reliable order).
117     let mut crates_to_lint = vec![];
118     tcx.hir().krate().visit_all_item_likes(&mut CollectExternCrateVisitor {
119         tcx,
120         crates_to_lint: &mut crates_to_lint,
121     });
122
123     for extern_crate in &crates_to_lint {
124         let id = tcx.hir().as_local_node_id(extern_crate.def_id).unwrap();
125         let item = tcx.hir().expect_item(id);
126
127         // If the crate is fully unused, we suggest removing it altogether.
128         // We do this in any edition.
129         if extern_crate.warn_if_unused {
130             if let Some(&span) = unused_extern_crates.get(&extern_crate.def_id) {
131                 let msg = "unused extern crate";
132
133                 // Removal suggestion span needs to include attributes (Issue #54400)
134                 let span_with_attrs = tcx.get_attrs(extern_crate.def_id).iter()
135                     .map(|attr| attr.span)
136                     .fold(span, |acc, attr_span| acc.to(attr_span));
137
138                 tcx.struct_span_lint_node(lint, id, span, msg)
139                     .span_suggestion_short_with_applicability(
140                         span_with_attrs,
141                         "remove it",
142                         String::new(),
143                         Applicability::MachineApplicable)
144                     .emit();
145                 continue;
146             }
147         }
148
149         // If we are not in Rust 2018 edition, then we don't make any further
150         // suggestions.
151         if !tcx.sess.rust_2018() {
152             continue;
153         }
154
155         // If the extern crate isn't in the extern prelude,
156         // there is no way it can be written as an `use`.
157         let orig_name = extern_crate.orig_name.unwrap_or(item.ident.name);
158         if !tcx.extern_prelude.get(&orig_name).map_or(false, |from_item| !from_item) {
159             continue;
160         }
161
162         // If the extern crate has any attributes, they may have funky
163         // semantics we can't faithfully represent using `use` (most
164         // notably `#[macro_use]`). Ignore it.
165         if !tcx.get_attrs(extern_crate.def_id).is_empty() {
166             continue;
167         }
168
169         // Otherwise, we can convert it into a `use` of some kind.
170         let msg = "`extern crate` is not idiomatic in the new edition";
171         let help = format!(
172             "convert it to a `{}`",
173             visibility_qualified(&item.vis, "use")
174         );
175         let base_replacement = match extern_crate.orig_name {
176             Some(orig_name) => format!("use {} as {};", orig_name, item.ident.name),
177             None => format!("use {};", item.ident.name),
178         };
179         let replacement = visibility_qualified(&item.vis, base_replacement);
180         tcx.struct_span_lint_node(lint, id, extern_crate.span, msg)
181             .span_suggestion_short_with_applicability(
182                 extern_crate.span,
183                 &help,
184                 replacement,
185                 Applicability::MachineApplicable,
186             )
187             .emit();
188     }
189 }
190
191 struct CollectExternCrateVisitor<'a, 'tcx: 'a> {
192     tcx: TyCtxt<'a, 'tcx, 'tcx>,
193     crates_to_lint: &'a mut Vec<ExternCrateToLint>,
194 }
195
196 struct ExternCrateToLint {
197     /// def-id of the extern crate
198     def_id: DefId,
199
200     /// span from the item
201     span: Span,
202
203     /// if `Some`, then this is renamed (`extern crate orig_name as
204     /// crate_name`), and -- perhaps surprisingly -- this stores the
205     /// *original* name (`item.name` will contain the new name)
206     orig_name: Option<ast::Name>,
207
208     /// if `false`, the original name started with `_`, so we shouldn't lint
209     /// about it going unused (but we should still emit idiom lints).
210     warn_if_unused: bool,
211 }
212
213 impl<'a, 'tcx, 'v> ItemLikeVisitor<'v> for CollectExternCrateVisitor<'a, 'tcx> {
214     fn visit_item(&mut self, item: &hir::Item) {
215         if let hir::ItemKind::ExternCrate(orig_name) = item.node {
216             let extern_crate_def_id = self.tcx.hir().local_def_id(item.id);
217             self.crates_to_lint.push(
218                 ExternCrateToLint {
219                     def_id: extern_crate_def_id,
220                     span: item.span,
221                     orig_name,
222                     warn_if_unused: !item.ident.as_str().starts_with('_'),
223                 }
224             );
225         }
226     }
227
228     fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem) {
229     }
230
231     fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem) {
232     }
233 }