1 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
2 use rustc_errors::Applicability;
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};
10 pub fn check_crate(tcx: TyCtxt<'_>) {
11 let mut used_trait_imports: FxHashSet<LocalDefId> = FxHashSet::default();
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());
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() {
24 if used_trait_imports.contains(&id) {
27 let item = tcx.hir().expect_item(id);
28 if item.span.is_dummy() {
31 let hir::ItemKind::Use(path, _) = item.kind else { unreachable!() };
32 tcx.struct_span_lint_hir(lint::builtin::UNUSED_IMPORTS, item.hir_id(), path.span, |lint| {
33 let msg = if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(path.span) {
34 format!("unused import: `{}`", snippet)
36 "unused import".to_owned()
38 lint.build(&msg).emit();
42 unused_crates_lint(tcx);
45 fn unused_crates_lint(tcx: TyCtxt<'_>) {
46 let lint = lint::builtin::UNUSED_EXTERN_CRATES;
48 // Collect first the crates that are completely unused. These we
49 // can always suggest removing (no matter which edition we are
51 let unused_extern_crates: FxHashMap<LocalDefId, Span> = tcx
52 .maybe_unused_extern_crates(())
54 .filter(|&&(def_id, _)| {
55 // The `def_id` here actually was calculated during resolution (at least
56 // at the time of this writing) and is being shipped to us via a side
57 // channel of the tcx. There may have been extra expansion phases,
58 // however, which ended up removing the `def_id` *after* expansion.
60 // As a result we need to verify that `def_id` is indeed still valid for
61 // our AST and actually present in the HIR map. If it's not there then
62 // there's safely nothing to warn about, and otherwise we carry on with
65 // Note that if we carry through to the `extern_mod_stmt_cnum` query
66 // below it'll cause a panic because `def_id` is actually bogus at this
67 // point in time otherwise.
68 if tcx.hir().find(tcx.hir().local_def_id_to_hir_id(def_id)).is_none() {
73 .filter(|&&(def_id, _)| {
74 tcx.extern_mod_stmt_cnum(def_id).map_or(true, |cnum| {
75 !tcx.is_compiler_builtins(cnum)
76 && !tcx.is_panic_runtime(cnum)
77 && !tcx.has_global_allocator(cnum)
78 && !tcx.has_panic_handler(cnum)
84 // Collect all the extern crates (in a reliable order).
85 let mut crates_to_lint = vec![];
87 for id in tcx.hir().items() {
88 if matches!(tcx.def_kind(id.def_id), DefKind::ExternCrate) {
89 let item = tcx.hir().item(id);
90 if let hir::ItemKind::ExternCrate(orig_name) = item.kind {
91 crates_to_lint.push(ExternCrateToLint {
92 def_id: item.def_id.to_def_id(),
95 warn_if_unused: !item.ident.as_str().starts_with('_'),
101 let extern_prelude = &tcx.resolutions(()).extern_prelude;
103 for extern_crate in &crates_to_lint {
104 let def_id = extern_crate.def_id.expect_local();
105 let item = tcx.hir().expect_item(def_id);
107 // If the crate is fully unused, we suggest removing it altogether.
108 // We do this in any edition.
109 if extern_crate.warn_if_unused {
110 if let Some(&span) = unused_extern_crates.get(&def_id) {
111 let id = tcx.hir().local_def_id_to_hir_id(def_id);
112 tcx.struct_span_lint_hir(lint, id, span, |lint| {
113 // Removal suggestion span needs to include attributes (Issue #54400)
114 let span_with_attrs = tcx
118 .map(|attr| attr.span)
119 .fold(span, |acc, attr_span| acc.to(attr_span));
121 lint.build("unused extern crate")
122 .span_suggestion_short(
126 Applicability::MachineApplicable,
134 // If we are not in Rust 2018 edition, then we don't make any further
136 if !tcx.sess.rust_2018() {
140 // If the extern crate isn't in the extern prelude,
141 // there is no way it can be written as a `use`.
142 let orig_name = extern_crate.orig_name.unwrap_or(item.ident.name);
143 if !extern_prelude.get(&orig_name).map_or(false, |from_item| !from_item) {
147 // If the extern crate is renamed, then we cannot suggest replacing it with a use as this
148 // would not insert the new name into the prelude, where other imports in the crate may be
150 if extern_crate.orig_name.is_some() {
154 let id = tcx.hir().local_def_id_to_hir_id(def_id);
155 // If the extern crate has any attributes, they may have funky
156 // semantics we can't faithfully represent using `use` (most
157 // notably `#[macro_use]`). Ignore it.
158 if !tcx.hir().attrs(id).is_empty() {
161 tcx.struct_span_lint_hir(lint, id, extern_crate.span, |lint| {
162 // Otherwise, we can convert it into a `use` of some kind.
163 let base_replacement = match extern_crate.orig_name {
164 Some(orig_name) => format!("use {} as {};", orig_name, item.ident.name),
165 None => format!("use {};", item.ident.name),
167 let vis = tcx.sess.source_map().span_to_snippet(item.vis_span).unwrap_or_default();
168 let add_vis = |to| if vis.is_empty() { to } else { format!("{} {}", vis, to) };
169 lint.build("`extern crate` is not idiomatic in the new edition")
170 .span_suggestion_short(
172 &format!("convert it to a `{}`", add_vis("use".to_string())),
173 add_vis(base_replacement),
174 Applicability::MachineApplicable,
181 struct ExternCrateToLint {
182 /// `DefId` of the extern crate
185 /// span from the item
188 /// if `Some`, then this is renamed (`extern crate orig_name as
189 /// crate_name`), and -- perhaps surprisingly -- this stores the
190 /// *original* name (`item.name` will contain the new name)
191 orig_name: Option<Symbol>,
193 /// if `false`, the original name started with `_`, so we shouldn't lint
194 /// about it going unused (but we should still emit idiom lints).
195 warn_if_unused: bool,