Skip to content

Commit e66b6d0

Browse files
committed
Auto merge of rust-lang#117772 - surechen:for_117448, r=<try>
Enhance lint unused_imports to check unnecessary imports in std::prelude fixes rust-lang#117448 detects unnecessary imports in std::prelude that can be eliminated. For example import: ```rust use std::{option::{Iter, IterMut, IntoIter, Option::{self, Some}}, convert::{TryFrom, TryInto}, mem::drop}; ``` detect : `Option::{self, Some}` `mem::drop`
2 parents c1fc1d1 + 5d81f5c commit e66b6d0

21 files changed

+249
-113
lines changed

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;

compiler/rustc_hir_analysis/src/check/check.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ 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::{ErrorGuaranteed, MultiSpan};
8+
use rustc_errors::MultiSpan;
99
use rustc_hir as hir;
1010
use rustc_hir::def::{CtorKind, DefKind};
1111
use rustc_hir::def_id::LocalModDefId;

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};
@@ -363,7 +363,7 @@ impl<'a, 'b, 'tcx> BuildReducedGraphVisitor<'a, 'b, 'tcx> {
363363
root_span,
364364
root_id,
365365
vis: Cell::new(Some(vis)),
366-
used: Cell::new(false),
366+
used: Default::default(),
367367
});
368368

369369
self.r.indeterminate_imports.push(import);
@@ -858,7 +858,7 @@ impl<'a, 'b, 'tcx> BuildReducedGraphVisitor<'a, 'b, 'tcx> {
858858
span: item.span,
859859
module_path: Vec::new(),
860860
vis: Cell::new(Some(vis)),
861-
used: Cell::new(used),
861+
used: Cell::new(used.then_some(Used::Other)),
862862
});
863863
self.r.potentially_unused_imports.push(import);
864864
let imported_binding = self.r.import(binding, import);
@@ -1066,7 +1066,7 @@ impl<'a, 'b, 'tcx> BuildReducedGraphVisitor<'a, 'b, 'tcx> {
10661066
span,
10671067
module_path: Vec::new(),
10681068
vis: Cell::new(Some(ty::Visibility::Restricted(CRATE_DEF_ID))),
1069-
used: Cell::new(false),
1069+
used: Default::default(),
10701070
})
10711071
};
10721072

@@ -1227,7 +1227,7 @@ impl<'a, 'b, 'tcx> BuildReducedGraphVisitor<'a, 'b, 'tcx> {
12271227
span,
12281228
module_path: Vec::new(),
12291229
vis: Cell::new(Some(vis)),
1230-
used: Cell::new(true),
1230+
used: Cell::new(Some(Used::Other)),
12311231
});
12321232
let import_binding = self.r.import(binding, import);
12331233
self.r.define(self.r.graph_root, ident, MacroNS, import_binding);

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,
@@ -99,9 +100,9 @@ impl<'a, 'b, 'tcx> UnusedImportCheckVisitor<'a, 'b, 'tcx> {
99100
}
100101
}
101102

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

107108
self.unused_imports.entry(id).or_insert_with(|| UnusedImport {
@@ -196,7 +197,7 @@ enum UnusedSpanResult {
196197
}
197198

198199
fn calc_unused_spans(
199-
unused_import: &UnusedImport<'_>,
200+
unused_import: &UnusedImport,
200201
use_tree: &ast::UseTree,
201202
use_tree_id: ast::NodeId,
202203
) -> UnusedSpanResult {
@@ -286,7 +287,7 @@ impl Resolver<'_, '_> {
286287

287288
for import in self.potentially_unused_imports.iter() {
288289
match import.kind {
289-
_ if import.used.get()
290+
_ if import.used.get().is_some()
290291
|| import.expect_vis().is_public()
291292
|| import.span.is_dummy() =>
292293
{
@@ -335,7 +336,7 @@ impl Resolver<'_, '_> {
335336

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

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};

compiler/rustc_resolve/src/diagnostics.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@ use crate::errors::{AddedMacroUse, ChangeImportBinding, ChangeImportBindingSugge
3131
use crate::errors::{ConsiderAddingADerive, ExplicitUnsafeTraits, MaybeMissingMacroRulesName};
3232
use crate::imports::{Import, ImportKind};
3333
use crate::late::{PatternSource, Rib};
34-
use crate::path_names_to_string;
3534
use crate::{errors as errs, BindingKey};
35+
use crate::{path_names_to_string, Used};
3636
use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingError, Finalize};
3737
use crate::{HasGenericParams, MacroRulesScope, Module, ModuleKind, ModuleOrUniformRoot};
3838
use crate::{LexicalScopeBinding, NameBinding, NameBindingKind, PrivacyError, VisResolutionError};
@@ -1487,7 +1487,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
14871487
);
14881488
// Silence the 'unused import' warning we might get,
14891489
// since this diagnostic already covers that import.
1490-
self.record_use(ident, binding, false);
1490+
self.record_use(ident, binding, Used::Other);
14911491
return;
14921492
}
14931493
}

compiler/rustc_resolve/src/ident.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ use crate::late::{
1414
ConstantHasGenerics, HasGenericParams, NoConstantGenericsReason, PathSource, Rib, RibKind,
1515
};
1616
use crate::macros::{sub_namespace_match, MacroRulesScope};
17-
use crate::BindingKey;
1817
use crate::{errors, AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, Determinacy, Finalize};
18+
use crate::{BindingKey, Used};
1919
use crate::{ImportKind, LexicalScopeBinding, Module, ModuleKind, ModuleOrUniformRoot};
2020
use crate::{NameBinding, NameBindingKind, ParentScope, PathResult, PrivacyError, Res};
2121
use crate::{ResolutionError, Resolver, Scope, ScopeSet, Segment, ToNameBinding, Weak};
@@ -341,7 +341,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
341341
ident,
342342
ns,
343343
parent_scope,
344-
finalize,
344+
finalize.map(|finalize| Finalize { used: Used::Scope, ..finalize }),
345345
ignore_binding,
346346
);
347347
if let Ok(binding) = item {
@@ -507,7 +507,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
507507
ns,
508508
adjusted_parent_scope,
509509
!matches!(scope_set, ScopeSet::Late(..)),
510-
finalize,
510+
finalize.map(|finalize| Finalize { used: Used::Scope, ..finalize }),
511511
ignore_binding,
512512
);
513513
match binding {
@@ -858,7 +858,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
858858
.into_iter()
859859
.find_map(|binding| if binding == ignore_binding { None } else { binding });
860860

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

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

0 commit comments

Comments
 (0)