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