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