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