]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/check_unused.rs
Rollup merge of #102634 - andrewpollack:refactor-test-rustcflags, r=Mark-Simulacrum
[rust.git] / compiler / rustc_hir_analysis / src / check_unused.rs
1 use crate::errors::{ExternCrateNotIdiomatic, UnusedExternCrate};
2 use rustc_data_structures::fx::FxHashMap;
3 use rustc_data_structures::unord::UnordSet;
4 use rustc_hir as hir;
5 use rustc_hir::def::DefKind;
6 use rustc_hir::def_id::{DefId, LocalDefId};
7 use rustc_middle::ty::TyCtxt;
8 use rustc_session::lint;
9 use rustc_span::{Span, Symbol};
10
11 pub fn check_crate(tcx: TyCtxt<'_>) {
12     let mut used_trait_imports: UnordSet<LocalDefId> = Default::default();
13
14     for item_def_id in tcx.hir().body_owners() {
15         let imports = tcx.used_trait_imports(item_def_id);
16         debug!("GatherVisitor: item_def_id={:?} with imports {:#?}", item_def_id, imports);
17         used_trait_imports.extend(imports.items().copied());
18     }
19
20     for &id in tcx.maybe_unused_trait_imports(()) {
21         debug_assert_eq!(tcx.def_kind(id), DefKind::Use);
22         if tcx.visibility(id).is_public() {
23             continue;
24         }
25         if used_trait_imports.contains(&id) {
26             continue;
27         }
28         let item = tcx.hir().expect_item(id);
29         if item.span.is_dummy() {
30             continue;
31         }
32         let hir::ItemKind::Use(path, _) = item.kind else { unreachable!() };
33         let msg = if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(path.span) {
34             format!("unused import: `{}`", snippet)
35         } else {
36             "unused import".to_owned()
37         };
38         tcx.struct_span_lint_hir(
39             lint::builtin::UNUSED_IMPORTS,
40             item.hir_id(),
41             path.span,
42             msg,
43             |lint| lint,
44         );
45     }
46
47     unused_crates_lint(tcx);
48 }
49
50 fn unused_crates_lint(tcx: TyCtxt<'_>) {
51     let lint = lint::builtin::UNUSED_EXTERN_CRATES;
52
53     // Collect first the crates that are completely unused.  These we
54     // can always suggest removing (no matter which edition we are
55     // in).
56     let unused_extern_crates: FxHashMap<LocalDefId, Span> = tcx
57         .maybe_unused_extern_crates(())
58         .iter()
59         .filter(|&&(def_id, _)| {
60             // The `def_id` here actually was calculated during resolution (at least
61             // at the time of this writing) and is being shipped to us via a side
62             // channel of the tcx. There may have been extra expansion phases,
63             // however, which ended up removing the `def_id` *after* expansion.
64             //
65             // As a result we need to verify that `def_id` is indeed still valid for
66             // our AST and actually present in the HIR map. If it's not there then
67             // there's safely nothing to warn about, and otherwise we carry on with
68             // our execution.
69             //
70             // Note that if we carry through to the `extern_mod_stmt_cnum` query
71             // below it'll cause a panic because `def_id` is actually bogus at this
72             // point in time otherwise.
73             if tcx.hir().find(tcx.hir().local_def_id_to_hir_id(def_id)).is_none() {
74                 return false;
75             }
76             true
77         })
78         .filter(|&&(def_id, _)| {
79             tcx.extern_mod_stmt_cnum(def_id).map_or(true, |cnum| {
80                 !tcx.is_compiler_builtins(cnum)
81                     && !tcx.is_panic_runtime(cnum)
82                     && !tcx.has_global_allocator(cnum)
83                     && !tcx.has_panic_handler(cnum)
84             })
85         })
86         .cloned()
87         .collect();
88
89     // Collect all the extern crates (in a reliable order).
90     let mut crates_to_lint = vec![];
91
92     for id in tcx.hir().items() {
93         if matches!(tcx.def_kind(id.def_id), DefKind::ExternCrate) {
94             let item = tcx.hir().item(id);
95             if let hir::ItemKind::ExternCrate(orig_name) = item.kind {
96                 crates_to_lint.push(ExternCrateToLint {
97                     def_id: item.def_id.to_def_id(),
98                     span: item.span,
99                     orig_name,
100                     warn_if_unused: !item.ident.as_str().starts_with('_'),
101                 });
102             }
103         }
104     }
105
106     let extern_prelude = &tcx.resolutions(()).extern_prelude;
107
108     for extern_crate in &crates_to_lint {
109         let def_id = extern_crate.def_id.expect_local();
110         let item = tcx.hir().expect_item(def_id);
111
112         // If the crate is fully unused, we suggest removing it altogether.
113         // We do this in any edition.
114         if extern_crate.warn_if_unused {
115             if let Some(&span) = unused_extern_crates.get(&def_id) {
116                 // Removal suggestion span needs to include attributes (Issue #54400)
117                 let id = tcx.hir().local_def_id_to_hir_id(def_id);
118                 let span_with_attrs = tcx
119                     .hir()
120                     .attrs(id)
121                     .iter()
122                     .map(|attr| attr.span)
123                     .fold(span, |acc, attr_span| acc.to(attr_span));
124
125                 tcx.emit_spanned_lint(lint, id, span, UnusedExternCrate { span: span_with_attrs });
126                 continue;
127             }
128         }
129
130         // If we are not in Rust 2018 edition, then we don't make any further
131         // suggestions.
132         if !tcx.sess.rust_2018() {
133             continue;
134         }
135
136         // If the extern crate isn't in the extern prelude,
137         // there is no way it can be written as a `use`.
138         let orig_name = extern_crate.orig_name.unwrap_or(item.ident.name);
139         if !extern_prelude.get(&orig_name).map_or(false, |from_item| !from_item) {
140             continue;
141         }
142
143         // If the extern crate is renamed, then we cannot suggest replacing it with a use as this
144         // would not insert the new name into the prelude, where other imports in the crate may be
145         // expecting it.
146         if extern_crate.orig_name.is_some() {
147             continue;
148         }
149
150         let id = tcx.hir().local_def_id_to_hir_id(def_id);
151         // If the extern crate has any attributes, they may have funky
152         // semantics we can't faithfully represent using `use` (most
153         // notably `#[macro_use]`). Ignore it.
154         if !tcx.hir().attrs(id).is_empty() {
155             continue;
156         }
157
158         let base_replacement = match extern_crate.orig_name {
159             Some(orig_name) => format!("use {} as {};", orig_name, item.ident.name),
160             None => format!("use {};", item.ident.name),
161         };
162         let vis = tcx.sess.source_map().span_to_snippet(item.vis_span).unwrap_or_default();
163         let add_vis = |to| if vis.is_empty() { to } else { format!("{} {}", vis, to) };
164         tcx.emit_spanned_lint(
165             lint,
166             id,
167             extern_crate.span,
168             ExternCrateNotIdiomatic {
169                 span: extern_crate.span,
170                 msg_code: add_vis("use".to_string()),
171                 suggestion_code: add_vis(base_replacement),
172             },
173         );
174     }
175 }
176
177 struct ExternCrateToLint {
178     /// `DefId` of the extern crate
179     def_id: DefId,
180
181     /// span from the item
182     span: Span,
183
184     /// if `Some`, then this is renamed (`extern crate orig_name as
185     /// crate_name`), and -- perhaps surprisingly -- this stores the
186     /// *original* name (`item.name` will contain the new name)
187     orig_name: Option<Symbol>,
188
189     /// if `false`, the original name started with `_`, so we shouldn't lint
190     /// about it going unused (but we should still emit idiom lints).
191     warn_if_unused: bool,
192 }