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