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