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