]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check_unused.rs
Auto merge of #96139 - erikdesjardins:revertinl2, r=Mark-Simulacrum
[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::DefKind;
5 use rustc_hir::def_id::{DefId, LocalDefId};
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<LocalDefId> = FxHashSet::default();
12
13     for item_def_id in tcx.hir().body_owners() {
14         let imports = tcx.used_trait_imports(item_def_id);
15         debug!("GatherVisitor: item_def_id={:?} with imports {:#?}", item_def_id, imports);
16         used_trait_imports.extend(imports.iter());
17     }
18
19     for id in tcx.hir().items() {
20         if matches!(tcx.hir().def_kind(id.def_id), DefKind::Use) {
21             let item = tcx.hir().item(id);
22             if item.vis.node.is_pub() || item.span.is_dummy() {
23                 continue;
24             }
25             if let hir::ItemKind::Use(path, _) = item.kind {
26                 check_import(tcx, &mut used_trait_imports, item.item_id(), path.span);
27             }
28         }
29     }
30
31     unused_crates_lint(tcx);
32 }
33
34 fn check_import<'tcx>(
35     tcx: TyCtxt<'tcx>,
36     used_trait_imports: &mut FxHashSet<LocalDefId>,
37     item_id: hir::ItemId,
38     span: Span,
39 ) {
40     if !tcx.maybe_unused_trait_import(item_id.def_id) {
41         return;
42     }
43
44     if used_trait_imports.contains(&item_id.def_id) {
45         return;
46     }
47
48     tcx.struct_span_lint_hir(lint::builtin::UNUSED_IMPORTS, item_id.hir_id(), span, |lint| {
49         let msg = if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(span) {
50             format!("unused import: `{}`", snippet)
51         } else {
52             "unused import".to_owned()
53         };
54         lint.build(&msg).emit();
55     });
56 }
57
58 fn unused_crates_lint(tcx: TyCtxt<'_>) {
59     let lint = lint::builtin::UNUSED_EXTERN_CRATES;
60
61     // Collect first the crates that are completely unused.  These we
62     // can always suggest removing (no matter which edition we are
63     // in).
64     let unused_extern_crates: FxHashMap<LocalDefId, Span> = tcx
65         .maybe_unused_extern_crates(())
66         .iter()
67         .filter(|&&(def_id, _)| {
68             // The `def_id` here actually was calculated during resolution (at least
69             // at the time of this writing) and is being shipped to us via a side
70             // channel of the tcx. There may have been extra expansion phases,
71             // however, which ended up removing the `def_id` *after* expansion.
72             //
73             // As a result we need to verify that `def_id` is indeed still valid for
74             // our AST and actually present in the HIR map. If it's not there then
75             // there's safely nothing to warn about, and otherwise we carry on with
76             // our execution.
77             //
78             // Note that if we carry through to the `extern_mod_stmt_cnum` query
79             // below it'll cause a panic because `def_id` is actually bogus at this
80             // point in time otherwise.
81             if tcx.hir().find(tcx.hir().local_def_id_to_hir_id(def_id)).is_none() {
82                 return false;
83             }
84             true
85         })
86         .filter(|&&(def_id, _)| {
87             tcx.extern_mod_stmt_cnum(def_id).map_or(true, |cnum| {
88                 !tcx.is_compiler_builtins(cnum)
89                     && !tcx.is_panic_runtime(cnum)
90                     && !tcx.has_global_allocator(cnum)
91                     && !tcx.has_panic_handler(cnum)
92             })
93         })
94         .cloned()
95         .collect();
96
97     // Collect all the extern crates (in a reliable order).
98     let mut crates_to_lint = vec![];
99
100     for id in tcx.hir().items() {
101         if matches!(tcx.hir().def_kind(id.def_id), DefKind::ExternCrate) {
102             let item = tcx.hir().item(id);
103             if let hir::ItemKind::ExternCrate(orig_name) = item.kind {
104                 crates_to_lint.push(ExternCrateToLint {
105                     def_id: item.def_id.to_def_id(),
106                     span: item.span,
107                     orig_name,
108                     warn_if_unused: !item.ident.as_str().starts_with('_'),
109                 });
110             }
111         }
112     }
113
114     let extern_prelude = &tcx.resolutions(()).extern_prelude;
115
116     for extern_crate in &crates_to_lint {
117         let def_id = extern_crate.def_id.expect_local();
118         let item = tcx.hir().expect_item(def_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(&def_id) {
124                 let id = tcx.hir().local_def_id_to_hir_id(def_id);
125                 tcx.struct_span_lint_hir(lint, id, span, |lint| {
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                     lint.build("unused extern crate")
134                         .span_suggestion_short(
135                             span_with_attrs,
136                             "remove it",
137                             String::new(),
138                             Applicability::MachineApplicable,
139                         )
140                         .emit();
141                 });
142                 continue;
143             }
144         }
145
146         // If we are not in Rust 2018 edition, then we don't make any further
147         // suggestions.
148         if !tcx.sess.rust_2018() {
149             continue;
150         }
151
152         // If the extern crate isn't in the extern prelude,
153         // there is no way it can be written as a `use`.
154         let orig_name = extern_crate.orig_name.unwrap_or(item.ident.name);
155         if !extern_prelude.get(&orig_name).map_or(false, |from_item| !from_item) {
156             continue;
157         }
158
159         // If the extern crate is renamed, then we cannot suggest replacing it with a use as this
160         // would not insert the new name into the prelude, where other imports in the crate may be
161         // expecting it.
162         if extern_crate.orig_name.is_some() {
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         let id = tcx.hir().local_def_id_to_hir_id(def_id);
173         tcx.struct_span_lint_hir(lint, id, extern_crate.span, |lint| {
174             // Otherwise, we can convert it into a `use` of some kind.
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 vis = tcx.sess.source_map().span_to_snippet(item.vis.span).unwrap_or_default();
180             let add_vis = |to| if vis.is_empty() { to } else { format!("{} {}", vis, to) };
181             lint.build("`extern crate` is not idiomatic in the new edition")
182                 .span_suggestion_short(
183                     extern_crate.span,
184                     &format!("convert it to a `{}`", add_vis("use".to_string())),
185                     add_vis(base_replacement),
186                     Applicability::MachineApplicable,
187                 )
188                 .emit();
189         })
190     }
191 }
192
193 struct ExternCrateToLint {
194     /// `DefId` of the extern crate
195     def_id: DefId,
196
197     /// span from the item
198     span: Span,
199
200     /// if `Some`, then this is renamed (`extern crate orig_name as
201     /// crate_name`), and -- perhaps surprisingly -- this stores the
202     /// *original* name (`item.name` will contain the new name)
203     orig_name: Option<Symbol>,
204
205     /// if `false`, the original name started with `_`, so we shouldn't lint
206     /// about it going unused (but we should still emit idiom lints).
207     warn_if_unused: bool,
208 }