2014-12-19 07:13:54 +00:00
|
|
|
//
|
|
|
|
// Unused import checking
|
|
|
|
//
|
|
|
|
// Although this is mostly a lint pass, it lives in here because it depends on
|
|
|
|
// resolve data structures and because it finalises the privacy information for
|
2020-03-07 16:02:32 +00:00
|
|
|
// `use` items.
|
2014-12-19 07:13:54 +00:00
|
|
|
//
|
2016-04-19 13:43:10 +00:00
|
|
|
// Unused trait imports can't be checked until the method resolution. We save
|
2022-09-26 11:00:29 +00:00
|
|
|
// candidates here, and do the actual check in rustc_hir_analysis/check_unused.rs.
|
2018-12-08 11:45:13 +00:00
|
|
|
//
|
|
|
|
// Checking for unused imports is split into three steps:
|
|
|
|
//
|
|
|
|
// - `UnusedImportCheckVisitor` walks the AST to find all the unused imports
|
|
|
|
// inside of `UseTree`s, recording their `NodeId`s and grouping them by
|
|
|
|
// the parent `use` item
|
|
|
|
//
|
|
|
|
// - `calc_unused_spans` then walks over all the `use` items marked in the
|
|
|
|
// previous step to collect the spans associated with the `NodeId`s and to
|
|
|
|
// calculate the spans that can be removed by rustfix; This is done in a
|
|
|
|
// separate step to be able to collapse the adjacent spans that rustfix
|
|
|
|
// will remove
|
|
|
|
//
|
2024-01-09 23:39:53 +00:00
|
|
|
// - `check_unused` finally emits the diagnostics based on the data generated
|
2018-12-08 11:45:13 +00:00
|
|
|
// in the last step
|
2014-12-19 07:13:54 +00:00
|
|
|
|
2020-04-27 17:56:11 +00:00
|
|
|
use rustc_ast as ast;
|
2020-02-29 17:37:32 +00:00
|
|
|
use rustc_ast::visit::{self, Visitor};
|
2023-11-10 02:11:24 +00:00
|
|
|
use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet};
|
2023-01-17 11:05:01 +00:00
|
|
|
use rustc_data_structures::unord::UnordSet;
|
2024-04-14 17:59:54 +00:00
|
|
|
use rustc_errors::MultiSpan;
|
2023-03-22 14:38:58 +00:00
|
|
|
use rustc_hir::def::{DefKind, Res};
|
2024-02-29 05:40:44 +00:00
|
|
|
use rustc_session::lint::BuiltinLintDiag;
|
2024-03-11 14:39:02 +00:00
|
|
|
use rustc_session::lint::builtin::{
|
|
|
|
MACRO_USE_EXTERN_CRATE, UNUSED_EXTERN_CRATES, UNUSED_IMPORTS, UNUSED_QUALIFICATIONS,
|
|
|
|
};
|
2024-12-12 23:29:23 +00:00
|
|
|
use rustc_span::{DUMMY_SP, Ident, Span, kw};
|
2015-07-31 07:04:06 +00:00
|
|
|
|
2024-03-11 14:39:02 +00:00
|
|
|
use crate::imports::{Import, ImportKind};
|
|
|
|
use crate::{LexicalScopeBinding, NameBindingKind, Resolver, module_to_string};
|
2024-07-28 22:13:50 +00:00
|
|
|
|
2023-11-10 02:11:24 +00:00
|
|
|
struct UnusedImport {
|
|
|
|
use_tree: ast::UseTree,
|
2018-12-08 11:45:13 +00:00
|
|
|
use_tree_id: ast::NodeId,
|
|
|
|
item_span: Span,
|
2023-01-17 11:05:01 +00:00
|
|
|
unused: UnordSet<ast::NodeId>,
|
2018-12-08 11:45:13 +00:00
|
|
|
}
|
|
|
|
|
2023-11-10 02:11:24 +00:00
|
|
|
impl UnusedImport {
|
2018-12-08 11:45:13 +00:00
|
|
|
fn add(&mut self, id: ast::NodeId) {
|
|
|
|
self.unused.insert(id);
|
|
|
|
}
|
|
|
|
}
|
2014-12-19 07:13:54 +00:00
|
|
|
|
2024-09-10 06:19:40 +00:00
|
|
|
struct UnusedImportCheckVisitor<'a, 'ra, 'tcx> {
|
|
|
|
r: &'a mut Resolver<'ra, 'tcx>,
|
2016-10-26 06:24:09 +00:00
|
|
|
/// All the (so far) unused imports, grouped path list
|
2023-11-10 02:11:24 +00:00
|
|
|
unused_imports: FxIndexMap<ast::NodeId, UnusedImport>,
|
2023-02-22 20:25:10 +00:00
|
|
|
extern_crate_items: Vec<ExternCrateToLint>,
|
2018-12-08 11:45:13 +00:00
|
|
|
base_use_tree: Option<&'a ast::UseTree>,
|
2017-09-26 21:04:00 +00:00
|
|
|
base_id: ast::NodeId,
|
|
|
|
item_span: Span,
|
2014-12-19 07:13:54 +00:00
|
|
|
}
|
|
|
|
|
2023-02-22 20:25:10 +00:00
|
|
|
struct ExternCrateToLint {
|
|
|
|
id: ast::NodeId,
|
|
|
|
/// Span from the item
|
|
|
|
span: Span,
|
|
|
|
/// Span to use to suggest complete removal.
|
|
|
|
span_with_attributes: Span,
|
|
|
|
/// Span of the visibility, if any.
|
|
|
|
vis_span: Span,
|
|
|
|
/// Whether the item has attrs.
|
|
|
|
has_attrs: bool,
|
|
|
|
/// Name used to refer to the crate.
|
|
|
|
ident: Ident,
|
2023-02-25 13:43:21 +00:00
|
|
|
/// Whether the statement renames the crate `extern crate orig_name as new_name;`.
|
|
|
|
renames: bool,
|
2023-02-22 20:25:10 +00:00
|
|
|
}
|
|
|
|
|
2024-09-10 06:19:40 +00:00
|
|
|
impl<'a, 'ra, 'tcx> UnusedImportCheckVisitor<'a, 'ra, 'tcx> {
|
2020-03-07 16:02:32 +00:00
|
|
|
// We have information about whether `use` (import) items are actually
|
2016-04-04 11:32:42 +00:00
|
|
|
// used now. If an import is not used at all, we signal a lint error.
|
2018-12-08 11:45:13 +00:00
|
|
|
fn check_import(&mut self, id: ast::NodeId) {
|
2021-08-22 14:50:59 +00:00
|
|
|
let used = self.r.used_imports.contains(&id);
|
2020-06-20 18:59:29 +00:00
|
|
|
let def_id = self.r.local_def_id(id);
|
2016-11-10 06:19:54 +00:00
|
|
|
if !used {
|
2020-05-24 11:18:22 +00:00
|
|
|
if self.r.maybe_unused_trait_imports.contains(&def_id) {
|
2016-04-19 13:43:10 +00:00
|
|
|
// Check later.
|
|
|
|
return;
|
|
|
|
}
|
2018-12-08 11:45:13 +00:00
|
|
|
self.unused_import(self.base_id).add(id);
|
2016-04-19 13:43:10 +00:00
|
|
|
} else {
|
|
|
|
// This trait import is definitely used, in a way other than
|
|
|
|
// method resolution.
|
2024-01-28 20:53:28 +00:00
|
|
|
// FIXME(#120456) - is `swap_remove` correct?
|
|
|
|
self.r.maybe_unused_trait_imports.swap_remove(&def_id);
|
2018-12-08 11:45:13 +00:00
|
|
|
if let Some(i) = self.unused_imports.get_mut(&self.base_id) {
|
|
|
|
i.unused.remove(&id);
|
2016-10-26 06:24:09 +00:00
|
|
|
}
|
2014-12-19 07:13:54 +00:00
|
|
|
}
|
|
|
|
}
|
2018-12-08 11:45:13 +00:00
|
|
|
|
2023-11-10 02:11:24 +00:00
|
|
|
fn unused_import(&mut self, id: ast::NodeId) -> &mut UnusedImport {
|
2018-12-08 11:45:13 +00:00
|
|
|
let use_tree_id = self.base_id;
|
2023-11-10 02:11:24 +00:00
|
|
|
let use_tree = self.base_use_tree.unwrap().clone();
|
2018-12-08 11:45:13 +00:00
|
|
|
let item_span = self.item_span;
|
|
|
|
|
|
|
|
self.unused_imports.entry(id).or_insert_with(|| UnusedImport {
|
|
|
|
use_tree,
|
|
|
|
use_tree_id,
|
|
|
|
item_span,
|
2023-01-17 11:05:01 +00:00
|
|
|
unused: Default::default(),
|
2018-12-08 11:45:13 +00:00
|
|
|
})
|
|
|
|
}
|
2023-03-22 14:38:58 +00:00
|
|
|
|
|
|
|
fn check_import_as_underscore(&mut self, item: &ast::UseTree, id: ast::NodeId) {
|
|
|
|
match item.kind {
|
|
|
|
ast::UseTreeKind::Simple(Some(ident)) => {
|
|
|
|
if ident.name == kw::Underscore
|
2023-05-24 14:33:43 +00:00
|
|
|
&& !self.r.import_res_map.get(&id).is_some_and(|per_ns| {
|
|
|
|
per_ns.iter().filter_map(|res| res.as_ref()).any(|res| {
|
|
|
|
matches!(res, Res::Def(DefKind::Trait | DefKind::TraitAlias, _))
|
2023-03-22 14:38:58 +00:00
|
|
|
})
|
2023-05-24 14:33:43 +00:00
|
|
|
})
|
2023-03-22 14:38:58 +00:00
|
|
|
{
|
|
|
|
self.unused_import(self.base_id).add(id);
|
|
|
|
}
|
|
|
|
}
|
2024-04-01 22:26:10 +00:00
|
|
|
ast::UseTreeKind::Nested { ref items, .. } => self.check_imports_as_underscore(items),
|
2023-03-22 14:38:58 +00:00
|
|
|
_ => {}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn check_imports_as_underscore(&mut self, items: &[(ast::UseTree, ast::NodeId)]) {
|
|
|
|
for (item, id) in items {
|
|
|
|
self.check_import_as_underscore(item, *id);
|
|
|
|
}
|
|
|
|
}
|
2024-03-04 02:24:23 +00:00
|
|
|
|
|
|
|
fn report_unused_extern_crate_items(
|
|
|
|
&mut self,
|
|
|
|
maybe_unused_extern_crates: FxHashMap<ast::NodeId, Span>,
|
|
|
|
) {
|
|
|
|
let tcx = self.r.tcx();
|
|
|
|
for extern_crate in &self.extern_crate_items {
|
|
|
|
let warn_if_unused = !extern_crate.ident.name.as_str().starts_with('_');
|
|
|
|
|
|
|
|
// If the crate is fully unused, we suggest removing it altogether.
|
|
|
|
// We do this in any edition.
|
|
|
|
if warn_if_unused {
|
|
|
|
if let Some(&span) = maybe_unused_extern_crates.get(&extern_crate.id) {
|
2024-05-20 17:47:54 +00:00
|
|
|
self.r.lint_buffer.buffer_lint(
|
2024-03-04 02:24:23 +00:00
|
|
|
UNUSED_EXTERN_CRATES,
|
|
|
|
extern_crate.id,
|
|
|
|
span,
|
|
|
|
BuiltinLintDiag::UnusedExternCrate {
|
|
|
|
removal_span: extern_crate.span_with_attributes,
|
|
|
|
},
|
|
|
|
);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we are not in Rust 2018 edition, then we don't make any further
|
|
|
|
// suggestions.
|
|
|
|
if !tcx.sess.at_least_rust_2018() {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the extern crate has any attributes, they may have funky
|
|
|
|
// semantics we can't faithfully represent using `use` (most
|
|
|
|
// notably `#[macro_use]`). Ignore it.
|
|
|
|
if extern_crate.has_attrs {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the extern crate is renamed, then we cannot suggest replacing it with a use as this
|
|
|
|
// would not insert the new name into the prelude, where other imports in the crate may be
|
|
|
|
// expecting it.
|
|
|
|
if extern_crate.renames {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the extern crate isn't in the extern prelude,
|
|
|
|
// there is no way it can be written as a `use`.
|
2024-10-17 06:32:21 +00:00
|
|
|
if self
|
2024-03-04 02:24:23 +00:00
|
|
|
.r
|
|
|
|
.extern_prelude
|
|
|
|
.get(&extern_crate.ident)
|
2024-10-17 06:32:21 +00:00
|
|
|
.is_none_or(|entry| entry.introduced_by_item)
|
2024-03-04 02:24:23 +00:00
|
|
|
{
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
let vis_span = extern_crate
|
|
|
|
.vis_span
|
|
|
|
.find_ancestor_inside(extern_crate.span)
|
|
|
|
.unwrap_or(extern_crate.vis_span);
|
|
|
|
let ident_span = extern_crate
|
|
|
|
.ident
|
|
|
|
.span
|
|
|
|
.find_ancestor_inside(extern_crate.span)
|
|
|
|
.unwrap_or(extern_crate.ident.span);
|
2024-05-20 17:47:54 +00:00
|
|
|
self.r.lint_buffer.buffer_lint(
|
2024-03-04 02:24:23 +00:00
|
|
|
UNUSED_EXTERN_CRATES,
|
|
|
|
extern_crate.id,
|
|
|
|
extern_crate.span,
|
|
|
|
BuiltinLintDiag::ExternCrateNotIdiomatic { vis_span, ident_span },
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
2014-12-19 07:13:54 +00:00
|
|
|
}
|
|
|
|
|
2024-09-10 06:19:40 +00:00
|
|
|
impl<'a, 'ra, 'tcx> Visitor<'a> for UnusedImportCheckVisitor<'a, 'ra, 'tcx> {
|
2016-12-06 10:26:52 +00:00
|
|
|
fn visit_item(&mut self, item: &'a ast::Item) {
|
2023-02-22 20:25:10 +00:00
|
|
|
match item.kind {
|
|
|
|
// Ignore is_public import statements because there's no way to be sure
|
|
|
|
// whether they're used or not. Also ignore imports with a dummy span
|
|
|
|
// because this means that they were generated in some fashion by the
|
|
|
|
// compiler and we don't need to consider them.
|
2023-03-22 14:38:58 +00:00
|
|
|
ast::ItemKind::Use(..) if item.span.is_dummy() => return,
|
Move `ast::Item::ident` into `ast::ItemKind`.
`ast::Item` has an `ident` field.
- It's always non-empty for these item kinds: `ExternCrate`, `Static`,
`Const`, `Fn`, `Mod`, `TyAlias`, `Enum`, `Struct`, `Union`,
`Trait`, `TraitAlias`, `MacroDef`, `Delegation`.
- It's always empty for these item kinds: `Use`, `ForeignMod`,
`GlobalAsm`, `Impl`, `MacCall`, `DelegationMac`.
There is a similar story for `AssocItemKind` and `ForeignItemKind`.
Some sites that handle items check for an empty ident, some don't. This
is a very C-like way of doing things, but this is Rust, we have sum
types, we can do this properly and never forget to check for the
exceptional case and never YOLO possibly empty identifiers (or possibly
dummy spans) around and hope that things will work out.
The commit is large but it's mostly obvious plumbing work. Some notable
things.
- `ast::Item` got 8 bytes bigger. This could be avoided by boxing the
fields within some of the `ast::ItemKind` variants (specifically:
`Struct`, `Union`, `Enum`). I might do that in a follow-up; this
commit is big enough already.
- For the visitors: `FnKind` no longer needs an `ident` field because
the `Fn` within how has one.
- In the parser, the `ItemInfo` typedef is no longer needed. It was used
in various places to return an `Ident` alongside an `ItemKind`, but
now the `Ident` (if present) is within the `ItemKind`.
- In a few places I renamed identifier variables called `name` (or
`foo_name`) as `ident` (or `foo_ident`), to better match the type, and
because `name` is normally used for `Symbol`s. It's confusing to see
something like `foo_name.name`.
2025-03-20 22:47:43 +00:00
|
|
|
ast::ItemKind::ExternCrate(orig_name, ident) => {
|
2023-02-22 20:25:10 +00:00
|
|
|
self.extern_crate_items.push(ExternCrateToLint {
|
|
|
|
id: item.id,
|
|
|
|
span: item.span,
|
|
|
|
vis_span: item.vis.span,
|
|
|
|
span_with_attributes: item.span_with_attributes(),
|
|
|
|
has_attrs: !item.attrs.is_empty(),
|
Move `ast::Item::ident` into `ast::ItemKind`.
`ast::Item` has an `ident` field.
- It's always non-empty for these item kinds: `ExternCrate`, `Static`,
`Const`, `Fn`, `Mod`, `TyAlias`, `Enum`, `Struct`, `Union`,
`Trait`, `TraitAlias`, `MacroDef`, `Delegation`.
- It's always empty for these item kinds: `Use`, `ForeignMod`,
`GlobalAsm`, `Impl`, `MacCall`, `DelegationMac`.
There is a similar story for `AssocItemKind` and `ForeignItemKind`.
Some sites that handle items check for an empty ident, some don't. This
is a very C-like way of doing things, but this is Rust, we have sum
types, we can do this properly and never forget to check for the
exceptional case and never YOLO possibly empty identifiers (or possibly
dummy spans) around and hope that things will work out.
The commit is large but it's mostly obvious plumbing work. Some notable
things.
- `ast::Item` got 8 bytes bigger. This could be avoided by boxing the
fields within some of the `ast::ItemKind` variants (specifically:
`Struct`, `Union`, `Enum`). I might do that in a follow-up; this
commit is big enough already.
- For the visitors: `FnKind` no longer needs an `ident` field because
the `Fn` within how has one.
- In the parser, the `ItemInfo` typedef is no longer needed. It was used
in various places to return an `Ident` alongside an `ItemKind`, but
now the `Ident` (if present) is within the `ItemKind`.
- In a few places I renamed identifier variables called `name` (or
`foo_name`) as `ident` (or `foo_ident`), to better match the type, and
because `name` is normally used for `Symbol`s. It's confusing to see
something like `foo_name.name`.
2025-03-20 22:47:43 +00:00
|
|
|
ident,
|
2023-02-25 13:43:21 +00:00
|
|
|
renames: orig_name.is_some(),
|
2023-02-22 20:25:10 +00:00
|
|
|
});
|
2017-09-26 21:04:00 +00:00
|
|
|
}
|
2023-02-22 20:25:10 +00:00
|
|
|
_ => {}
|
2017-09-26 21:04:00 +00:00
|
|
|
}
|
|
|
|
|
2023-02-22 20:25:10 +00:00
|
|
|
self.item_span = item.span_with_attributes();
|
2017-09-26 21:04:00 +00:00
|
|
|
visit::walk_item(self, item);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn visit_use_tree(&mut self, use_tree: &'a ast::UseTree, id: ast::NodeId, nested: bool) {
|
|
|
|
// Use the base UseTree's NodeId as the item id
|
|
|
|
// This allows the grouping of all the lints in the same item
|
|
|
|
if !nested {
|
|
|
|
self.base_id = id;
|
2018-12-08 11:45:13 +00:00
|
|
|
self.base_use_tree = Some(use_tree);
|
2014-12-19 07:13:54 +00:00
|
|
|
}
|
|
|
|
|
2023-10-15 11:38:22 +00:00
|
|
|
if self.r.effective_visibilities.is_exported(self.r.local_def_id(id)) {
|
2023-03-22 14:38:58 +00:00
|
|
|
self.check_import_as_underscore(use_tree, id);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2024-04-01 22:26:10 +00:00
|
|
|
if let ast::UseTreeKind::Nested { ref items, .. } = use_tree.kind {
|
2018-10-17 09:13:44 +00:00
|
|
|
if items.is_empty() {
|
2018-12-08 11:45:13 +00:00
|
|
|
self.unused_import(self.base_id).add(id);
|
2014-12-19 07:13:54 +00:00
|
|
|
}
|
2017-09-26 21:04:00 +00:00
|
|
|
} else {
|
2018-12-08 11:45:13 +00:00
|
|
|
self.check_import(id);
|
2014-12-19 07:13:54 +00:00
|
|
|
}
|
2017-09-26 21:04:00 +00:00
|
|
|
|
|
|
|
visit::walk_use_tree(self, use_tree, id);
|
2014-12-19 07:13:54 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-12-08 11:45:13 +00:00
|
|
|
enum UnusedSpanResult {
|
|
|
|
Used,
|
2024-04-01 21:42:33 +00:00
|
|
|
Unused { spans: Vec<Span>, remove: Span },
|
|
|
|
PartialUnused { spans: Vec<Span>, remove: Vec<Span> },
|
2018-12-08 11:45:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn calc_unused_spans(
|
2023-11-10 02:11:24 +00:00
|
|
|
unused_import: &UnusedImport,
|
2018-12-08 11:45:13 +00:00
|
|
|
use_tree: &ast::UseTree,
|
|
|
|
use_tree_id: ast::NodeId,
|
|
|
|
) -> UnusedSpanResult {
|
|
|
|
// The full span is the whole item's span if this current tree is not nested inside another
|
|
|
|
// This tells rustfix to remove the whole item if all the imports are unused
|
|
|
|
let full_span = if unused_import.use_tree.span == use_tree.span {
|
|
|
|
unused_import.item_span
|
|
|
|
} else {
|
|
|
|
use_tree.span
|
|
|
|
};
|
|
|
|
match use_tree.kind {
|
|
|
|
ast::UseTreeKind::Simple(..) | ast::UseTreeKind::Glob => {
|
|
|
|
if unused_import.unused.contains(&use_tree_id) {
|
2024-04-01 21:42:33 +00:00
|
|
|
UnusedSpanResult::Unused { spans: vec![use_tree.span], remove: full_span }
|
2018-12-08 11:45:13 +00:00
|
|
|
} else {
|
|
|
|
UnusedSpanResult::Used
|
|
|
|
}
|
|
|
|
}
|
2024-04-14 16:40:49 +00:00
|
|
|
ast::UseTreeKind::Nested { items: ref nested, span: tree_span } => {
|
2020-02-28 13:20:33 +00:00
|
|
|
if nested.is_empty() {
|
2024-04-01 21:42:33 +00:00
|
|
|
return UnusedSpanResult::Unused { spans: vec![use_tree.span], remove: full_span };
|
2018-12-08 11:45:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
let mut unused_spans = Vec::new();
|
|
|
|
let mut to_remove = Vec::new();
|
2024-05-19 08:23:31 +00:00
|
|
|
let mut used_children = 0;
|
2024-04-14 16:40:49 +00:00
|
|
|
let mut contains_self = false;
|
2018-12-08 11:45:13 +00:00
|
|
|
let mut previous_unused = false;
|
|
|
|
for (pos, (use_tree, use_tree_id)) in nested.iter().enumerate() {
|
|
|
|
let remove = match calc_unused_spans(unused_import, use_tree, *use_tree_id) {
|
|
|
|
UnusedSpanResult::Used => {
|
2024-05-19 08:23:31 +00:00
|
|
|
used_children += 1;
|
2018-12-08 11:45:13 +00:00
|
|
|
None
|
|
|
|
}
|
2024-04-01 21:42:33 +00:00
|
|
|
UnusedSpanResult::Unused { mut spans, remove } => {
|
2018-12-08 11:45:13 +00:00
|
|
|
unused_spans.append(&mut spans);
|
|
|
|
Some(remove)
|
|
|
|
}
|
2024-04-01 21:42:33 +00:00
|
|
|
UnusedSpanResult::PartialUnused { mut spans, remove: mut to_remove_extra } => {
|
2024-05-19 08:23:31 +00:00
|
|
|
used_children += 1;
|
2018-12-08 11:45:13 +00:00
|
|
|
unused_spans.append(&mut spans);
|
|
|
|
to_remove.append(&mut to_remove_extra);
|
|
|
|
None
|
|
|
|
}
|
|
|
|
};
|
|
|
|
if let Some(remove) = remove {
|
|
|
|
let remove_span = if nested.len() == 1 {
|
|
|
|
remove
|
2024-05-19 08:23:31 +00:00
|
|
|
} else if pos == nested.len() - 1 || used_children > 0 {
|
2018-12-08 11:45:13 +00:00
|
|
|
// Delete everything from the end of the last import, to delete the
|
|
|
|
// previous comma
|
|
|
|
nested[pos - 1].0.span.shrink_to_hi().to(use_tree.span)
|
|
|
|
} else {
|
|
|
|
// Delete everything until the next import, to delete the trailing commas
|
|
|
|
use_tree.span.to(nested[pos + 1].0.span.shrink_to_lo())
|
|
|
|
};
|
|
|
|
|
|
|
|
// Try to collapse adjacent spans into a single one. This prevents all cases of
|
|
|
|
// overlapping removals, which are not supported by rustfix
|
|
|
|
if previous_unused && !to_remove.is_empty() {
|
|
|
|
let previous = to_remove.pop().unwrap();
|
|
|
|
to_remove.push(previous.to(remove_span));
|
|
|
|
} else {
|
|
|
|
to_remove.push(remove_span);
|
|
|
|
}
|
|
|
|
}
|
2024-04-14 16:40:49 +00:00
|
|
|
contains_self |= use_tree.prefix == kw::SelfLower
|
2025-03-24 10:53:09 +00:00
|
|
|
&& matches!(use_tree.kind, ast::UseTreeKind::Simple(_))
|
|
|
|
&& !unused_import.unused.contains(&use_tree_id);
|
2018-12-08 11:45:13 +00:00
|
|
|
previous_unused = remove.is_some();
|
|
|
|
}
|
|
|
|
if unused_spans.is_empty() {
|
|
|
|
UnusedSpanResult::Used
|
2024-05-19 08:23:31 +00:00
|
|
|
} else if used_children == 0 {
|
2024-04-01 21:42:33 +00:00
|
|
|
UnusedSpanResult::Unused { spans: unused_spans, remove: full_span }
|
2018-12-08 11:45:13 +00:00
|
|
|
} else {
|
2024-04-14 16:40:49 +00:00
|
|
|
// If there is only one remaining child that is used, the braces around the use
|
|
|
|
// tree are not needed anymore. In that case, we determine the span of the left
|
|
|
|
// brace and the right brace, and tell rustfix to remove them as well.
|
|
|
|
//
|
|
|
|
// This means that `use a::{B, C};` will be turned into `use a::B;` rather than
|
|
|
|
// `use a::{B};`, removing a rustfmt roundtrip.
|
|
|
|
//
|
|
|
|
// Note that we cannot remove the braces if the only item inside the use tree is
|
|
|
|
// `self`: `use foo::{self};` is valid Rust syntax, while `use foo::self;` errors
|
|
|
|
// out. We also cannot turn `use foo::{self}` into `use foo`, as the former doesn't
|
|
|
|
// import types with the same name as the module.
|
2024-05-19 08:23:31 +00:00
|
|
|
if used_children == 1 && !contains_self {
|
2024-04-14 16:40:49 +00:00
|
|
|
// Left brace, from the start of the nested group to the first item.
|
|
|
|
to_remove.push(
|
|
|
|
tree_span.shrink_to_lo().to(nested.first().unwrap().0.span.shrink_to_lo()),
|
|
|
|
);
|
|
|
|
// Right brace, from the end of the last item to the end of the nested group.
|
|
|
|
to_remove.push(
|
|
|
|
nested.last().unwrap().0.span.shrink_to_hi().to(tree_span.shrink_to_hi()),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2024-04-01 21:42:33 +00:00
|
|
|
UnusedSpanResult::PartialUnused { spans: unused_spans, remove: to_remove }
|
2018-12-08 11:45:13 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-12-08 12:59:02 +00:00
|
|
|
impl Resolver<'_, '_> {
|
2022-05-20 23:51:09 +00:00
|
|
|
pub(crate) fn check_unused(&mut self, krate: &ast::Crate) {
|
2023-02-22 20:25:10 +00:00
|
|
|
let tcx = self.tcx;
|
|
|
|
let mut maybe_unused_extern_crates = FxHashMap::default();
|
|
|
|
|
2020-03-07 16:02:32 +00:00
|
|
|
for import in self.potentially_unused_imports.iter() {
|
|
|
|
match import.kind {
|
2024-08-09 10:33:20 +00:00
|
|
|
_ if import.vis.is_public()
|
|
|
|
|| import.span.is_dummy()
|
|
|
|
|| self.import_use_map.contains_key(import) =>
|
2019-08-08 20:32:58 +00:00
|
|
|
{
|
2023-12-28 07:18:49 +00:00
|
|
|
if let ImportKind::MacroUse { .. } = import.kind {
|
2020-03-07 16:02:32 +00:00
|
|
|
if !import.span.is_dummy() {
|
2024-05-20 17:47:54 +00:00
|
|
|
self.lint_buffer.buffer_lint(
|
2020-03-11 11:49:08 +00:00
|
|
|
MACRO_USE_EXTERN_CRATE,
|
2022-10-30 09:35:31 +00:00
|
|
|
import.root_id,
|
2020-03-07 16:02:32 +00:00
|
|
|
import.span,
|
2024-04-14 20:11:14 +00:00
|
|
|
BuiltinLintDiag::MacroUseDeprecated,
|
2019-08-08 20:32:58 +00:00
|
|
|
);
|
|
|
|
}
|
2018-07-11 21:25:29 +00:00
|
|
|
}
|
|
|
|
}
|
2022-10-30 09:35:31 +00:00
|
|
|
ImportKind::ExternCrate { id, .. } => {
|
|
|
|
let def_id = self.local_def_id(id);
|
2025-01-19 19:15:00 +00:00
|
|
|
if self.extern_crate_map.get(&def_id).is_none_or(|&cnum| {
|
2023-02-22 20:25:10 +00:00
|
|
|
!tcx.is_compiler_builtins(cnum)
|
|
|
|
&& !tcx.is_panic_runtime(cnum)
|
|
|
|
&& !tcx.has_global_allocator(cnum)
|
|
|
|
&& !tcx.has_panic_handler(cnum)
|
|
|
|
}) {
|
|
|
|
maybe_unused_extern_crates.insert(id, import.span);
|
|
|
|
}
|
2019-08-08 20:32:58 +00:00
|
|
|
}
|
2023-12-28 07:18:49 +00:00
|
|
|
ImportKind::MacroUse { .. } => {
|
2024-05-20 17:47:54 +00:00
|
|
|
self.lint_buffer.buffer_lint(
|
2024-04-14 20:11:14 +00:00
|
|
|
UNUSED_IMPORTS,
|
|
|
|
import.root_id,
|
|
|
|
import.span,
|
|
|
|
BuiltinLintDiag::UnusedMacroUse,
|
|
|
|
);
|
2019-08-08 20:32:58 +00:00
|
|
|
}
|
|
|
|
_ => {}
|
2018-07-11 21:25:29 +00:00
|
|
|
}
|
2017-01-14 07:35:54 +00:00
|
|
|
}
|
|
|
|
|
2019-08-08 20:32:58 +00:00
|
|
|
let mut visitor = UnusedImportCheckVisitor {
|
|
|
|
r: self,
|
|
|
|
unused_imports: Default::default(),
|
2023-02-22 20:25:10 +00:00
|
|
|
extern_crate_items: Default::default(),
|
2019-08-08 20:32:58 +00:00
|
|
|
base_use_tree: None,
|
|
|
|
base_id: ast::DUMMY_NODE_ID,
|
|
|
|
item_span: DUMMY_SP,
|
2018-12-08 11:45:13 +00:00
|
|
|
};
|
2019-08-08 20:32:58 +00:00
|
|
|
visit::walk_crate(&mut visitor, krate);
|
2018-12-08 11:45:13 +00:00
|
|
|
|
2024-03-04 02:24:23 +00:00
|
|
|
visitor.report_unused_extern_crate_items(maybe_unused_extern_crates);
|
|
|
|
|
2019-08-08 20:32:58 +00:00
|
|
|
for unused in visitor.unused_imports.values() {
|
2024-04-15 18:07:22 +00:00
|
|
|
let (spans, remove_spans) =
|
|
|
|
match calc_unused_spans(unused, &unused.use_tree, unused.use_tree_id) {
|
|
|
|
UnusedSpanResult::Used => continue,
|
|
|
|
UnusedSpanResult::Unused { spans, remove } => (spans, vec![remove]),
|
|
|
|
UnusedSpanResult::PartialUnused { spans, remove } => (spans, remove),
|
|
|
|
};
|
2018-12-08 11:45:13 +00:00
|
|
|
|
2023-10-18 21:24:35 +00:00
|
|
|
let ms = MultiSpan::from_spans(spans);
|
|
|
|
|
|
|
|
let mut span_snippets = ms
|
|
|
|
.primary_spans()
|
2019-08-08 20:32:58 +00:00
|
|
|
.iter()
|
2023-10-18 21:24:35 +00:00
|
|
|
.filter_map(|span| tcx.sess.source_map().span_to_snippet(*span).ok())
|
|
|
|
.map(|s| format!("`{s}`"))
|
2019-08-08 20:32:58 +00:00
|
|
|
.collect::<Vec<String>>();
|
|
|
|
span_snippets.sort();
|
2023-10-18 21:24:35 +00:00
|
|
|
|
2024-04-15 18:07:22 +00:00
|
|
|
let remove_whole_use = remove_spans.len() == 1 && remove_spans[0] == unused.item_span;
|
|
|
|
let num_to_remove = ms.primary_spans().len();
|
2019-08-08 20:32:58 +00:00
|
|
|
|
2022-05-02 21:46:25 +00:00
|
|
|
// If we are in the `--test` mode, suppress a help that adds the `#[cfg(test)]`
|
|
|
|
// attribute; however, if not, suggest adding the attribute. There is no way to
|
|
|
|
// retrieve attributes here because we do not have a `TyCtxt` yet.
|
2023-04-09 19:37:31 +00:00
|
|
|
let test_module_span = if tcx.sess.is_test_crate() {
|
2022-05-02 21:46:25 +00:00
|
|
|
None
|
|
|
|
} else {
|
|
|
|
let parent_module = visitor.r.get_nearest_non_block_module(
|
|
|
|
visitor.r.local_def_id(unused.use_tree_id).to_def_id(),
|
|
|
|
);
|
|
|
|
match module_to_string(parent_module) {
|
|
|
|
Some(module)
|
|
|
|
if module == "test"
|
|
|
|
|| module == "tests"
|
|
|
|
|| module.starts_with("test_")
|
|
|
|
|| module.starts_with("tests_")
|
|
|
|
|| module.ends_with("_test")
|
|
|
|
|| module.ends_with("_tests") =>
|
|
|
|
{
|
|
|
|
Some(parent_module.span)
|
|
|
|
}
|
|
|
|
_ => None,
|
2021-10-23 09:55:02 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2024-05-20 17:47:54 +00:00
|
|
|
visitor.r.lint_buffer.buffer_lint(
|
2020-03-11 11:49:08 +00:00
|
|
|
UNUSED_IMPORTS,
|
2019-08-08 20:32:58 +00:00
|
|
|
unused.use_tree_id,
|
|
|
|
ms,
|
2024-04-14 17:59:54 +00:00
|
|
|
BuiltinLintDiag::UnusedImports {
|
2024-04-15 18:07:22 +00:00
|
|
|
remove_whole_use,
|
|
|
|
num_to_remove,
|
|
|
|
remove_spans,
|
2024-04-14 17:59:54 +00:00
|
|
|
test_module_span,
|
|
|
|
span_snippets,
|
|
|
|
},
|
2019-08-08 20:32:58 +00:00
|
|
|
);
|
|
|
|
}
|
2023-02-22 20:25:10 +00:00
|
|
|
|
2023-11-10 02:11:24 +00:00
|
|
|
let unused_imports = visitor.unused_imports;
|
|
|
|
let mut check_redundant_imports = FxIndexSet::default();
|
|
|
|
for module in self.arenas.local_modules().iter() {
|
|
|
|
for (_key, resolution) in self.resolutions(*module).borrow().iter() {
|
|
|
|
let resolution = resolution.borrow();
|
|
|
|
|
|
|
|
if let Some(binding) = resolution.binding
|
|
|
|
&& let NameBindingKind::Import { import, .. } = binding.kind
|
|
|
|
&& let ImportKind::Single { id, .. } = import.kind
|
|
|
|
{
|
|
|
|
if let Some(unused_import) = unused_imports.get(&import.root_id)
|
|
|
|
&& unused_import.unused.contains(&id)
|
|
|
|
{
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
|
|
|
check_redundant_imports.insert(import);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-03-11 14:39:02 +00:00
|
|
|
let mut redundant_imports = UnordSet::default();
|
2023-11-10 02:11:24 +00:00
|
|
|
for import in check_redundant_imports {
|
2024-03-11 14:39:02 +00:00
|
|
|
if self.check_for_redundant_imports(import)
|
|
|
|
&& let Some(id) = import.id()
|
|
|
|
{
|
|
|
|
redundant_imports.insert(id);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// The lint fixes for unused_import and unnecessary_qualification may conflict.
|
|
|
|
// Deleting both unused imports and unnecessary segments of an item may result
|
|
|
|
// in the item not being found.
|
|
|
|
for unn_qua in &self.potentially_unnecessary_qualifications {
|
|
|
|
if let LexicalScopeBinding::Item(name_binding) = unn_qua.binding
|
|
|
|
&& let NameBindingKind::Import { import, .. } = name_binding.kind
|
|
|
|
&& (is_unused_import(import, &unused_imports)
|
|
|
|
|| is_redundant_import(import, &redundant_imports))
|
|
|
|
{
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
|
2024-05-20 17:47:54 +00:00
|
|
|
self.lint_buffer.buffer_lint(
|
2024-03-11 14:39:02 +00:00
|
|
|
UNUSED_QUALIFICATIONS,
|
|
|
|
unn_qua.node_id,
|
|
|
|
unn_qua.path_span,
|
|
|
|
BuiltinLintDiag::UnusedQualifications { removal_span: unn_qua.removal_span },
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn is_redundant_import(
|
|
|
|
import: Import<'_>,
|
|
|
|
redundant_imports: &UnordSet<ast::NodeId>,
|
|
|
|
) -> bool {
|
|
|
|
if let Some(id) = import.id()
|
|
|
|
&& redundant_imports.contains(&id)
|
|
|
|
{
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
false
|
|
|
|
}
|
|
|
|
|
|
|
|
fn is_unused_import(
|
|
|
|
import: Import<'_>,
|
|
|
|
unused_imports: &FxIndexMap<ast::NodeId, UnusedImport>,
|
|
|
|
) -> bool {
|
|
|
|
if let Some(unused_import) = unused_imports.get(&import.root_id)
|
|
|
|
&& let Some(id) = import.id()
|
|
|
|
&& unused_import.unused.contains(&id)
|
|
|
|
{
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
false
|
2023-11-10 02:11:24 +00:00
|
|
|
}
|
2016-10-26 06:24:09 +00:00
|
|
|
}
|
2014-12-19 07:13:54 +00:00
|
|
|
}
|