1 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
2 use rustc_errors::Applicability;
4 use rustc_hir::def_id::{DefId, LocalDefId};
5 use rustc_hir::itemlikevisit::ItemLikeVisitor;
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::default();
12 for &body_id in tcx.hir().krate().bodies.keys() {
13 let item_def_id = tcx.hir().body_owner_def_id(body_id);
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 let mut visitor = CheckVisitor { tcx, used_trait_imports };
20 tcx.hir().krate().visit_all_item_likes(&mut visitor);
22 unused_crates_lint(tcx);
25 impl ItemLikeVisitor<'v> for CheckVisitor<'tcx> {
26 fn visit_item(&mut self, item: &hir::Item<'_>) {
27 if item.vis.node.is_pub() || item.span.is_dummy() {
30 if let hir::ItemKind::Use(ref path, _) = item.kind {
31 self.check_import(item.item_id(), path.span);
35 fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {}
37 fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {}
39 fn visit_foreign_item(&mut self, _foreign_item: &hir::ForeignItem<'_>) {}
42 struct CheckVisitor<'tcx> {
44 used_trait_imports: FxHashSet<LocalDefId>,
47 impl CheckVisitor<'tcx> {
48 fn check_import(&self, item_id: hir::ItemId, span: Span) {
49 if !self.tcx.maybe_unused_trait_import(item_id.def_id) {
53 if self.used_trait_imports.contains(&item_id.def_id) {
57 self.tcx.struct_span_lint_hir(
58 lint::builtin::UNUSED_IMPORTS,
62 let msg = if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
63 format!("unused import: `{}`", snippet)
65 "unused import".to_owned()
67 lint.build(&msg).emit();
73 fn unused_crates_lint(tcx: TyCtxt<'_>) {
74 let lint = lint::builtin::UNUSED_EXTERN_CRATES;
76 // Collect first the crates that are completely unused. These we
77 // can always suggest removing (no matter which edition we are
79 let unused_extern_crates: FxHashMap<LocalDefId, Span> = tcx
80 .maybe_unused_extern_crates(())
82 .filter(|&&(def_id, _)| {
83 // The `def_id` here actually was calculated during resolution (at least
84 // at the time of this writing) and is being shipped to us via a side
85 // channel of the tcx. There may have been extra expansion phases,
86 // however, which ended up removing the `def_id` *after* expansion such
87 // as the `ReplaceBodyWithLoop` pass (which is a bit of a hack, but hey)
89 // As a result we need to verify that `def_id` is indeed still valid for
90 // our AST and actually present in the HIR map. If it's not there then
91 // there's safely nothing to warn about, and otherwise we carry on with
94 // Note that if we carry through to the `extern_mod_stmt_cnum` query
95 // below it'll cause a panic because `def_id` is actually bogus at this
96 // point in time otherwise.
97 if tcx.hir().find(tcx.hir().local_def_id_to_hir_id(def_id)).is_none() {
102 .filter(|&&(def_id, _)| {
103 tcx.extern_mod_stmt_cnum(def_id).map_or(true, |cnum| {
104 !tcx.is_compiler_builtins(cnum)
105 && !tcx.is_panic_runtime(cnum)
106 && !tcx.has_global_allocator(cnum)
107 && !tcx.has_panic_handler(cnum)
113 // Collect all the extern crates (in a reliable order).
114 let mut crates_to_lint = vec![];
115 tcx.hir().krate().visit_all_item_likes(&mut CollectExternCrateVisitor {
116 crates_to_lint: &mut crates_to_lint,
119 for extern_crate in &crates_to_lint {
120 let def_id = extern_crate.def_id.expect_local();
121 let id = tcx.hir().local_def_id_to_hir_id(def_id);
122 let item = tcx.hir().expect_item(id);
124 // If the crate is fully unused, we suggest removing it altogether.
125 // We do this in any edition.
126 if extern_crate.warn_if_unused {
127 if let Some(&span) = unused_extern_crates.get(&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 .get_attrs(extern_crate.def_id)
133 .map(|attr| attr.span)
134 .fold(span, |acc, attr_span| acc.to(attr_span));
136 lint.build("unused extern crate")
137 .span_suggestion_short(
141 Applicability::MachineApplicable,
149 // If we are not in Rust 2018 edition, then we don't make any further
151 if !tcx.sess.rust_2018() {
155 // If the extern crate isn't in the extern prelude,
156 // there is no way it can be written as an `use`.
157 let orig_name = extern_crate.orig_name.unwrap_or(item.ident.name);
158 if !tcx.extern_prelude.get(&orig_name).map_or(false, |from_item| !from_item) {
162 // If the extern crate is renamed, then we cannot suggest replacing it with a use as this
163 // would not insert the new name into the prelude, where other imports in the crate may be
165 if extern_crate.orig_name.is_some() {
169 // If the extern crate has any attributes, they may have funky
170 // semantics we can't faithfully represent using `use` (most
171 // notably `#[macro_use]`). Ignore it.
172 if !tcx.get_attrs(extern_crate.def_id).is_empty() {
175 tcx.struct_span_lint_hir(lint, id, extern_crate.span, |lint| {
176 // Otherwise, we can convert it into a `use` of some kind.
177 let base_replacement = match extern_crate.orig_name {
178 Some(orig_name) => format!("use {} as {};", orig_name, item.ident.name),
179 None => format!("use {};", item.ident.name),
181 let vis = tcx.sess.source_map().span_to_snippet(item.vis.span).unwrap_or_default();
182 let add_vis = |to| if vis.is_empty() { to } else { format!("{} {}", vis, to) };
183 lint.build("`extern crate` is not idiomatic in the new edition")
184 .span_suggestion_short(
186 &format!("convert it to a `{}`", add_vis("use".to_string())),
187 add_vis(base_replacement),
188 Applicability::MachineApplicable,
195 struct CollectExternCrateVisitor<'a> {
196 crates_to_lint: &'a mut Vec<ExternCrateToLint>,
199 struct ExternCrateToLint {
200 /// `DefId` of the extern crate
203 /// span from the item
206 /// if `Some`, then this is renamed (`extern crate orig_name as
207 /// crate_name`), and -- perhaps surprisingly -- this stores the
208 /// *original* name (`item.name` will contain the new name)
209 orig_name: Option<Symbol>,
211 /// if `false`, the original name started with `_`, so we shouldn't lint
212 /// about it going unused (but we should still emit idiom lints).
213 warn_if_unused: bool,
216 impl<'a, 'v> ItemLikeVisitor<'v> for CollectExternCrateVisitor<'a> {
217 fn visit_item(&mut self, item: &hir::Item<'_>) {
218 if let hir::ItemKind::ExternCrate(orig_name) = item.kind {
219 self.crates_to_lint.push(ExternCrateToLint {
220 def_id: item.def_id.to_def_id(),
223 warn_if_unused: !item.ident.as_str().starts_with('_'),
228 fn visit_trait_item(&mut self, _trait_item: &hir::TraitItem<'_>) {}
230 fn visit_impl_item(&mut self, _impl_item: &hir::ImplItem<'_>) {}
232 fn visit_foreign_item(&mut self, _foreign_item: &hir::ForeignItem<'_>) {}