Skip to content

Commit 8b21296

Browse files
committed
Auto merge of rust-lang#117772 - surechen:for_117448, r=petrochenkov
Tracking import use types for more accurate redundant import checking fixes rust-lang#117448 By tracking import use types to check whether it is scope uses or the other situations like module-relative uses, we can do more accurate redundant import checking. For example unnecessary imports in std::prelude that can be eliminated: ```rust use std::option::Option::Some;//~ WARNING the item `Some` is imported redundantly use std::option::Option::None; //~ WARNING the item `None` is imported redundantly ```
2 parents 6f72620 + a61126c commit 8b21296

File tree

52 files changed

+283
-167
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

52 files changed

+283
-167
lines changed

Diff for: compiler/rustc_data_structures/src/owned_slice.rs

+6-6
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use crate::sync::Lrc;
44
// Use our fake Send/Sync traits when on not parallel compiler,
55
// so that `OwnedSlice` only implements/requires Send/Sync
66
// for parallel compiler builds.
7-
use crate::sync::{Send, Sync};
7+
use crate::sync;
88

99
/// An owned slice.
1010
///
@@ -33,7 +33,7 @@ pub struct OwnedSlice {
3333
// \/
3434
// ⊂(´・◡・⊂ )∘˚˳° (I am the phantom remnant of #97770)
3535
#[expect(dead_code)]
36-
owner: Lrc<dyn Send + Sync>,
36+
owner: Lrc<dyn sync::Send + sync::Sync>,
3737
}
3838

3939
/// Makes an [`OwnedSlice`] out of an `owner` and a `slicer` function.
@@ -60,7 +60,7 @@ pub struct OwnedSlice {
6060
/// ```
6161
pub fn slice_owned<O, F>(owner: O, slicer: F) -> OwnedSlice
6262
where
63-
O: Send + Sync + 'static,
63+
O: sync::Send + sync::Sync + 'static,
6464
F: FnOnce(&O) -> &[u8],
6565
{
6666
try_slice_owned(owner, |x| Ok::<_, !>(slicer(x))).into_ok()
@@ -71,7 +71,7 @@ where
7171
/// See [`slice_owned`] for the infallible version.
7272
pub fn try_slice_owned<O, F, E>(owner: O, slicer: F) -> Result<OwnedSlice, E>
7373
where
74-
O: Send + Sync + 'static,
74+
O: sync::Send + sync::Sync + 'static,
7575
F: FnOnce(&O) -> Result<&[u8], E>,
7676
{
7777
// We wrap the owner of the bytes in, so it doesn't move.
@@ -139,11 +139,11 @@ impl Borrow<[u8]> for OwnedSlice {
139139

140140
// Safety: `OwnedSlice` is conceptually `(&'self.1 [u8], Arc<dyn Send + Sync>)`, which is `Send`
141141
#[cfg(parallel_compiler)]
142-
unsafe impl Send for OwnedSlice {}
142+
unsafe impl sync::Send for OwnedSlice {}
143143

144144
// Safety: `OwnedSlice` is conceptually `(&'self.1 [u8], Arc<dyn Send + Sync>)`, which is `Sync`
145145
#[cfg(parallel_compiler)]
146-
unsafe impl Sync for OwnedSlice {}
146+
unsafe impl sync::Sync for OwnedSlice {}
147147

148148
#[cfg(test)]
149149
mod tests;

Diff for: compiler/rustc_hir_analysis/src/check/check.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,9 @@ use super::compare_impl_item::check_type_bounds;
55
use super::compare_impl_item::{compare_impl_method, compare_impl_ty};
66
use super::*;
77
use rustc_attr as attr;
8-
use rustc_errors::{codes::*, ErrorGuaranteed, MultiSpan};
8+
use rustc_errors::{codes::*, MultiSpan};
99
use rustc_hir as hir;
1010
use rustc_hir::def::{CtorKind, DefKind};
11-
use rustc_hir::def_id::{DefId, LocalDefId};
1211
use rustc_hir::Node;
1312
use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt};
1413
use rustc_infer::traits::{Obligation, TraitEngineExt as _};

Diff for: compiler/rustc_hir_analysis/src/structured_errors/missing_cast_for_variadic_arg.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::{errors, structured_errors::StructuredDiagnostic};
2-
use rustc_errors::{codes::*, DiagnosticBuilder, ErrCode};
2+
use rustc_errors::{codes::*, DiagnosticBuilder};
33
use rustc_middle::ty::{Ty, TypeVisitableExt};
44
use rustc_session::Session;
55
use rustc_span::Span;

Diff for: compiler/rustc_hir_analysis/src/structured_errors/sized_unsized_cast.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::{errors, structured_errors::StructuredDiagnostic};
2-
use rustc_errors::{codes::*, DiagnosticBuilder, ErrCode};
2+
use rustc_errors::{codes::*, DiagnosticBuilder};
33
use rustc_middle::ty::{Ty, TypeVisitableExt};
44
use rustc_session::Session;
55
use rustc_span::Span;

Diff for: compiler/rustc_hir_analysis/src/structured_errors/wrong_number_of_generic_args.rs

+1-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
use crate::structured_errors::StructuredDiagnostic;
2-
use rustc_errors::{
3-
codes::*, pluralize, Applicability, Diagnostic, DiagnosticBuilder, ErrCode, MultiSpan,
4-
};
2+
use rustc_errors::{codes::*, pluralize, Applicability, Diagnostic, DiagnosticBuilder, MultiSpan};
53
use rustc_hir as hir;
64
use rustc_middle::ty::{self as ty, AssocItems, AssocKind, TyCtxt};
75
use rustc_session::Session;

Diff for: compiler/rustc_hir_typeck/src/expr.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ use rustc_data_structures::stack::ensure_sufficient_stack;
2727
use rustc_data_structures::unord::UnordMap;
2828
use rustc_errors::{
2929
codes::*, pluralize, struct_span_code_err, AddToDiagnostic, Applicability, Diagnostic,
30-
DiagnosticBuilder, ErrCode, ErrorGuaranteed, StashKey,
30+
DiagnosticBuilder, ErrorGuaranteed, StashKey,
3131
};
3232
use rustc_hir as hir;
3333
use rustc_hir::def::{CtorKind, DefKind, Res};

Diff for: compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use itertools::Itertools;
1313
use rustc_ast as ast;
1414
use rustc_data_structures::fx::FxIndexSet;
1515
use rustc_errors::{
16-
codes::*, pluralize, Applicability, Diagnostic, ErrCode, ErrorGuaranteed, MultiSpan, StashKey,
16+
codes::*, pluralize, Applicability, Diagnostic, ErrorGuaranteed, MultiSpan, StashKey,
1717
};
1818
use rustc_hir as hir;
1919
use rustc_hir::def::{CtorOf, DefKind, Res};

Diff for: compiler/rustc_hir_typeck/src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ use crate::expectation::Expectation;
5353
use crate::fn_ctxt::LoweredTy;
5454
use crate::gather_locals::GatherLocalsVisitor;
5555
use rustc_data_structures::unord::UnordSet;
56-
use rustc_errors::{codes::*, struct_span_code_err, ErrCode, ErrorGuaranteed};
56+
use rustc_errors::{codes::*, struct_span_code_err, ErrorGuaranteed};
5757
use rustc_hir as hir;
5858
use rustc_hir::def::{DefKind, Res};
5959
use rustc_hir::intravisit::Visitor;

Diff for: compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ use crate::errors::{
55
use crate::infer::error_reporting::TypeErrCtxt;
66
use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
77
use crate::infer::InferCtxt;
8-
use rustc_errors::{codes::*, DiagnosticBuilder, ErrCode, IntoDiagnosticArg};
8+
use rustc_errors::{codes::*, DiagnosticBuilder, IntoDiagnosticArg};
99
use rustc_hir as hir;
1010
use rustc_hir::def::Res;
1111
use rustc_hir::def::{CtorOf, DefKind, Namespace};

Diff for: compiler/rustc_metadata/src/rmeta/decoder.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ use rustc_data_structures::unhash::UnhashMap;
1313
use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
1414
use rustc_expand::proc_macro::{AttrProcMacro, BangProcMacro, DeriveProcMacro};
1515
use rustc_hir::def::Res;
16-
use rustc_hir::def_id::{DefIdMap, CRATE_DEF_INDEX, LOCAL_CRATE};
16+
use rustc_hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE};
1717
use rustc_hir::definitions::{DefPath, DefPathData};
1818
use rustc_hir::diagnostic_items::DiagnosticItems;
1919
use rustc_index::Idx;

Diff for: compiler/rustc_middle/src/mir/syntax.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ use crate::ty::{Region, UserTypeAnnotationIndex};
1515
use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
1616
use rustc_data_structures::packed::Pu128;
1717
use rustc_hir::def_id::DefId;
18-
use rustc_hir::{self, CoroutineKind};
18+
use rustc_hir::CoroutineKind;
1919
use rustc_index::IndexVec;
2020
use rustc_span::source_map::Spanned;
2121
use rustc_target::abi::{FieldIdx, VariantIdx};

Diff for: compiler/rustc_resolve/src/build_reduced_graph.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@
88
use crate::def_collector::collect_definitions;
99
use crate::imports::{ImportData, ImportKind};
1010
use crate::macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef};
11-
use crate::Namespace::{self, MacroNS, TypeNS, ValueNS};
11+
use crate::Namespace::{MacroNS, TypeNS, ValueNS};
1212
use crate::{errors, BindingKey, MacroData, NameBindingData};
1313
use crate::{Determinacy, ExternPreludeEntry, Finalize, Module, ModuleKind, ModuleOrUniformRoot};
14-
use crate::{NameBinding, NameBindingKind, ParentScope, PathResult, PerNS, ResolutionError};
15-
use crate::{Resolver, ResolverArenas, Segment, ToNameBinding, VisResolutionError};
14+
use crate::{NameBinding, NameBindingKind, ParentScope, PathResult, ResolutionError};
15+
use crate::{Resolver, ResolverArenas, Segment, ToNameBinding, Used, VisResolutionError};
1616

1717
use rustc_ast::visit::{self, AssocCtxt, Visitor};
1818
use rustc_ast::{self as ast, AssocItem, AssocItemKind, MetaItemKind, StmtKind};
@@ -362,7 +362,7 @@ impl<'a, 'b, 'tcx> BuildReducedGraphVisitor<'a, 'b, 'tcx> {
362362
root_span,
363363
root_id,
364364
vis: Cell::new(Some(vis)),
365-
used: Cell::new(false),
365+
used: Default::default(),
366366
});
367367

368368
self.r.indeterminate_imports.push(import);
@@ -885,7 +885,7 @@ impl<'a, 'b, 'tcx> BuildReducedGraphVisitor<'a, 'b, 'tcx> {
885885
span: item.span,
886886
module_path: Vec::new(),
887887
vis: Cell::new(Some(vis)),
888-
used: Cell::new(used),
888+
used: Cell::new(used.then_some(Used::Other)),
889889
});
890890
self.r.potentially_unused_imports.push(import);
891891
let imported_binding = self.r.import(binding, import);
@@ -1090,7 +1090,7 @@ impl<'a, 'b, 'tcx> BuildReducedGraphVisitor<'a, 'b, 'tcx> {
10901090
span,
10911091
module_path: Vec::new(),
10921092
vis: Cell::new(Some(ty::Visibility::Restricted(CRATE_DEF_ID))),
1093-
used: Cell::new(false),
1093+
used: Default::default(),
10941094
})
10951095
};
10961096

@@ -1261,7 +1261,7 @@ impl<'a, 'b, 'tcx> BuildReducedGraphVisitor<'a, 'b, 'tcx> {
12611261
span,
12621262
module_path: Vec::new(),
12631263
vis: Cell::new(Some(vis)),
1264-
used: Cell::new(true),
1264+
used: Cell::new(Some(Used::Other)),
12651265
});
12661266
let import_binding = self.r.import(binding, import);
12671267
self.r.define(self.r.graph_root, ident, MacroNS, import_binding);

Diff for: compiler/rustc_resolve/src/check_unused.rs

+36-10
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,10 @@ use crate::imports::ImportKind;
2727
use crate::module_to_string;
2828
use crate::Resolver;
2929

30+
use crate::NameBindingKind;
3031
use rustc_ast as ast;
3132
use rustc_ast::visit::{self, Visitor};
32-
use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
33+
use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet};
3334
use rustc_data_structures::unord::UnordSet;
3435
use rustc_errors::{pluralize, MultiSpan};
3536
use rustc_hir::def::{DefKind, Res};
@@ -38,14 +39,14 @@ use rustc_session::lint::BuiltinLintDiagnostics;
3839
use rustc_span::symbol::{kw, Ident};
3940
use rustc_span::{Span, DUMMY_SP};
4041

41-
struct UnusedImport<'a> {
42-
use_tree: &'a ast::UseTree,
42+
struct UnusedImport {
43+
use_tree: ast::UseTree,
4344
use_tree_id: ast::NodeId,
4445
item_span: Span,
4546
unused: UnordSet<ast::NodeId>,
4647
}
4748

48-
impl<'a> UnusedImport<'a> {
49+
impl UnusedImport {
4950
fn add(&mut self, id: ast::NodeId) {
5051
self.unused.insert(id);
5152
}
@@ -54,7 +55,7 @@ impl<'a> UnusedImport<'a> {
5455
struct UnusedImportCheckVisitor<'a, 'b, 'tcx> {
5556
r: &'a mut Resolver<'b, 'tcx>,
5657
/// All the (so far) unused imports, grouped path list
57-
unused_imports: FxIndexMap<ast::NodeId, UnusedImport<'a>>,
58+
unused_imports: FxIndexMap<ast::NodeId, UnusedImport>,
5859
extern_crate_items: Vec<ExternCrateToLint>,
5960
base_use_tree: Option<&'a ast::UseTree>,
6061
base_id: ast::NodeId,
@@ -100,9 +101,9 @@ impl<'a, 'b, 'tcx> UnusedImportCheckVisitor<'a, 'b, 'tcx> {
100101
}
101102
}
102103

103-
fn unused_import(&mut self, id: ast::NodeId) -> &mut UnusedImport<'a> {
104+
fn unused_import(&mut self, id: ast::NodeId) -> &mut UnusedImport {
104105
let use_tree_id = self.base_id;
105-
let use_tree = self.base_use_tree.unwrap();
106+
let use_tree = self.base_use_tree.unwrap().clone();
106107
let item_span = self.item_span;
107108

108109
self.unused_imports.entry(id).or_insert_with(|| UnusedImport {
@@ -197,7 +198,7 @@ enum UnusedSpanResult {
197198
}
198199

199200
fn calc_unused_spans(
200-
unused_import: &UnusedImport<'_>,
201+
unused_import: &UnusedImport,
201202
use_tree: &ast::UseTree,
202203
use_tree_id: ast::NodeId,
203204
) -> UnusedSpanResult {
@@ -287,7 +288,7 @@ impl Resolver<'_, '_> {
287288

288289
for import in self.potentially_unused_imports.iter() {
289290
match import.kind {
290-
_ if import.used.get()
291+
_ if import.used.get().is_some()
291292
|| import.expect_vis().is_public()
292293
|| import.span.is_dummy() =>
293294
{
@@ -336,7 +337,7 @@ impl Resolver<'_, '_> {
336337

337338
for unused in visitor.unused_imports.values() {
338339
let mut fixes = Vec::new();
339-
let spans = match calc_unused_spans(unused, unused.use_tree, unused.use_tree_id) {
340+
let spans = match calc_unused_spans(unused, &unused.use_tree, unused.use_tree_id) {
340341
UnusedSpanResult::Used => continue,
341342
UnusedSpanResult::FlatUnused(span, remove) => {
342343
fixes.push((remove, String::new()));
@@ -483,5 +484,30 @@ impl Resolver<'_, '_> {
483484
BuiltinLintDiagnostics::ExternCrateNotIdiomatic { vis_span, ident_span },
484485
);
485486
}
487+
488+
let unused_imports = visitor.unused_imports;
489+
let mut check_redundant_imports = FxIndexSet::default();
490+
for module in self.arenas.local_modules().iter() {
491+
for (_key, resolution) in self.resolutions(*module).borrow().iter() {
492+
let resolution = resolution.borrow();
493+
494+
if let Some(binding) = resolution.binding
495+
&& let NameBindingKind::Import { import, .. } = binding.kind
496+
&& let ImportKind::Single { id, .. } = import.kind
497+
{
498+
if let Some(unused_import) = unused_imports.get(&import.root_id)
499+
&& unused_import.unused.contains(&id)
500+
{
501+
continue;
502+
}
503+
504+
check_redundant_imports.insert(import);
505+
}
506+
}
507+
}
508+
509+
for import in check_redundant_imports {
510+
self.check_for_redundant_imports(import);
511+
}
486512
}
487513
}

Diff for: compiler/rustc_resolve/src/def_collector.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::{ImplTraitContext, Resolver};
2-
use rustc_ast::visit::{self, FnKind};
2+
use rustc_ast::visit::FnKind;
33
use rustc_ast::*;
44
use rustc_expand::expand::AstFragment;
55
use rustc_hir::def::{CtorKind, CtorOf, DefKind};

Diff for: compiler/rustc_resolve/src/diagnostics.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ use crate::errors::{AddedMacroUse, ChangeImportBinding, ChangeImportBindingSugge
3333
use crate::errors::{ConsiderAddingADerive, ExplicitUnsafeTraits, MaybeMissingMacroRulesName};
3434
use crate::imports::{Import, ImportKind};
3535
use crate::late::{PatternSource, Rib};
36-
use crate::path_names_to_string;
3736
use crate::{errors as errs, BindingKey};
37+
use crate::{path_names_to_string, Used};
3838
use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingError, Finalize};
3939
use crate::{HasGenericParams, MacroRulesScope, Module, ModuleKind, ModuleOrUniformRoot};
4040
use crate::{LexicalScopeBinding, NameBinding, NameBindingKind, PrivacyError, VisResolutionError};
@@ -1503,7 +1503,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
15031503
);
15041504
// Silence the 'unused import' warning we might get,
15051505
// since this diagnostic already covers that import.
1506-
self.record_use(ident, binding, false);
1506+
self.record_use(ident, binding, Used::Other);
15071507
return;
15081508
}
15091509
}

Diff for: compiler/rustc_resolve/src/ident.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@ use rustc_span::Span;
1212
use crate::errors::{ParamKindInEnumDiscriminant, ParamKindInNonTrivialAnonConst};
1313
use crate::late::{ConstantHasGenerics, NoConstantGenericsReason, PathSource, Rib, RibKind};
1414
use crate::macros::{sub_namespace_match, MacroRulesScope};
15-
use crate::BindingKey;
1615
use crate::{errors, AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, Determinacy, Finalize};
16+
use crate::{BindingKey, Used};
1717
use crate::{ImportKind, LexicalScopeBinding, Module, ModuleKind, ModuleOrUniformRoot};
1818
use crate::{NameBinding, NameBindingKind, ParentScope, PathResult, PrivacyError, Res};
1919
use crate::{ResolutionError, Resolver, Scope, ScopeSet, Segment, ToNameBinding, Weak};
@@ -339,7 +339,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
339339
ident,
340340
ns,
341341
parent_scope,
342-
finalize,
342+
finalize.map(|finalize| Finalize { used: Used::Scope, ..finalize }),
343343
ignore_binding,
344344
);
345345
if let Ok(binding) = item {
@@ -506,7 +506,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
506506
ns,
507507
adjusted_parent_scope,
508508
!matches!(scope_set, ScopeSet::Late(..)),
509-
finalize,
509+
finalize.map(|finalize| Finalize { used: Used::Scope, ..finalize }),
510510
ignore_binding,
511511
);
512512
match binding {
@@ -857,7 +857,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
857857
.into_iter()
858858
.find_map(|binding| if binding == ignore_binding { None } else { binding });
859859

860-
if let Some(Finalize { path_span, report_private, .. }) = finalize {
860+
if let Some(Finalize { path_span, report_private, used, .. }) = finalize {
861861
let Some(binding) = binding else {
862862
return Err((Determined, Weak::No));
863863
};
@@ -901,7 +901,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
901901
}
902902
}
903903

904-
self.record_use(ident, binding, restricted_shadowing);
904+
self.record_use(ident, binding, used);
905905
return Ok(binding);
906906
}
907907

0 commit comments

Comments
 (0)