1use std::cmp::Ordering;
4use std::mem;
5
6use rustc_ast::NodeId;
7use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
8use rustc_data_structures::intern::Interned;
9use rustc_errors::{Applicability, BufferedEarlyLint, Diagnostic};
10use rustc_expand::base::SyntaxExtensionKind;
11use rustc_hir::def::{self, DefKind, PartialRes};
12use rustc_hir::def_id::{DefId, LocalDefId, LocalDefIdMap};
13use rustc_middle::metadata::{AmbigModChild, ModChild, Reexport};
14use rustc_middle::span_bug;
15use rustc_middle::ty::Visibility;
16use rustc_session::errors::feature_err;
17use rustc_session::lint::LintId;
18use rustc_session::lint::builtin::{
19 AMBIGUOUS_GLOB_REEXPORTS, EXPORTED_PRIVATE_DEPENDENCIES, HIDDEN_GLOB_REEXPORTS,
20 PUB_USE_OF_PRIVATE_EXTERN_CRATE, REDUNDANT_IMPORTS, UNUSED_IMPORTS,
21};
22use rustc_span::edit_distance::find_best_match_for_name;
23use rustc_span::hygiene::LocalExpnId;
24use rustc_span::{Ident, Span, Symbol, kw, sym};
25use tracing::debug;
26
27use crate::Namespace::{self, *};
28use crate::diagnostics::{
29 self, CannotBeReexportedCratePublic, CannotBeReexportedCratePublicNS,
30 CannotBeReexportedPrivate, CannotBeReexportedPrivateNS, CannotDetermineImportResolution,
31 CannotGlobImportAllCrates, ConsiderAddingMacroExport, ConsiderMarkingAsPub,
32 ConsiderMarkingAsPubCrate,
33};
34use crate::error_helper::{OnUnknownData, Suggestion};
35use crate::ref_mut::{CmCell, CmRefCell};
36use crate::{
37 AmbiguityError, BindingKey, CmResolver, Decl, DeclData, DeclKind, Determinacy, Finalize,
38 IdentKey, ImportSuggestion, ImportSummary, LocalModule, ModuleOrUniformRoot, ParentScope,
39 PathResult, PerNS, Res, ResolutionError, Resolver, ScopeSet, Segment, Used, module_to_string,
40 names_to_string,
41};
42
43#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for PendingDecl<'ra> {
#[inline]
fn clone(&self) -> PendingDecl<'ra> {
let _: ::core::clone::AssertParamIsClone<Option<Decl<'ra>>>;
*self
}
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for PendingDecl<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::default::Default for PendingDecl<'ra> {
#[inline]
fn default() -> PendingDecl<'ra> { Self::Pending }
}Default, #[automatically_derived]
impl<'ra> ::core::cmp::PartialEq for PendingDecl<'ra> {
#[inline]
fn eq(&self, other: &PendingDecl<'ra>) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(PendingDecl::Ready(__self_0), PendingDecl::Ready(__arg1_0))
=> __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for PendingDecl<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
PendingDecl::Ready(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f, "Ready",
&__self_0),
PendingDecl::Pending =>
::core::fmt::Formatter::write_str(f, "Pending"),
}
}
}Debug)]
46pub(crate) enum PendingDecl<'ra> {
47 Ready(Option<Decl<'ra>>),
48 #[default]
49 Pending,
50}
51
52enum ImportResolutionKind<'ra> {
53 Single(PerNS<PendingDecl<'ra>>),
54 Glob(Vec<(Decl<'ra>, BindingKey, Span )>),
55}
56
57struct ImportResolution<'ra> {
58 kind: ImportResolutionKind<'ra>,
59 imported_module: ModuleOrUniformRoot<'ra>,
60}
61
62impl<'ra> PendingDecl<'ra> {
63 pub(crate) fn decl(self) -> Option<Decl<'ra>> {
64 match self {
65 PendingDecl::Ready(decl) => decl,
66 PendingDecl::Pending => None,
67 }
68 }
69}
70
71#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for ImportKind<'ra> {
#[inline]
fn clone(&self) -> ImportKind<'ra> {
match self {
ImportKind::Single {
source: __self_0,
target: __self_1,
decls: __self_2,
nested: __self_3,
id: __self_4,
def_id: __self_5 } =>
ImportKind::Single {
source: ::core::clone::Clone::clone(__self_0),
target: ::core::clone::Clone::clone(__self_1),
decls: ::core::clone::Clone::clone(__self_2),
nested: ::core::clone::Clone::clone(__self_3),
id: ::core::clone::Clone::clone(__self_4),
def_id: ::core::clone::Clone::clone(__self_5),
},
ImportKind::Glob {
max_vis: __self_0, id: __self_1, def_id: __self_2 } =>
ImportKind::Glob {
max_vis: ::core::clone::Clone::clone(__self_0),
id: ::core::clone::Clone::clone(__self_1),
def_id: ::core::clone::Clone::clone(__self_2),
},
ImportKind::ExternCrate {
source: __self_0,
target: __self_1,
id: __self_2,
def_id: __self_3 } =>
ImportKind::ExternCrate {
source: ::core::clone::Clone::clone(__self_0),
target: ::core::clone::Clone::clone(__self_1),
id: ::core::clone::Clone::clone(__self_2),
def_id: ::core::clone::Clone::clone(__self_3),
},
ImportKind::MacroUse { warn_private: __self_0 } =>
ImportKind::MacroUse {
warn_private: ::core::clone::Clone::clone(__self_0),
},
ImportKind::MacroExport => ImportKind::MacroExport,
}
}
}Clone)]
73pub(crate) enum ImportKind<'ra> {
74 Single {
75 source: Ident,
77 target: Ident,
80 decls: PerNS<CmCell<PendingDecl<'ra>>>,
82 nested: bool,
84 id: NodeId,
96 def_id: LocalDefId,
97 },
98 Glob {
99 max_vis: CmCell<Option<Visibility>>,
102 id: NodeId,
103 def_id: LocalDefId,
104 },
105 ExternCrate {
106 source: Option<Symbol>,
107 target: Ident,
108 id: NodeId,
109 def_id: LocalDefId,
110 },
111 MacroUse {
112 warn_private: bool,
115 },
116 MacroExport,
117}
118
119impl<'ra> std::fmt::Debug for ImportKind<'ra> {
122 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
123 use ImportKind::*;
124 match self {
125 Single { source, target, decls, nested, id, def_id } => f
126 .debug_struct("Single")
127 .field("source", source)
128 .field("target", target)
129 .field(
131 "decls",
132 &decls.clone().map(|b| b.into_inner().decl().map(|_| format_args!("..")format_args!(".."))),
133 )
134 .field("nested", nested)
135 .field("id", id)
136 .field("def_id", def_id)
137 .finish(),
138 Glob { max_vis, id, def_id } => f
139 .debug_struct("Glob")
140 .field("max_vis", max_vis)
141 .field("id", id)
142 .field("def_id", def_id)
143 .finish(),
144 ExternCrate { source, target, id, def_id } => f
145 .debug_struct("ExternCrate")
146 .field("source", source)
147 .field("target", target)
148 .field("id", id)
149 .field("def_id", def_id)
150 .finish(),
151 MacroUse { warn_private } => {
152 f.debug_struct("MacroUse").field("warn_private", warn_private).finish()
153 }
154 MacroExport => f.debug_struct("MacroExport").finish(),
155 }
156 }
157}
158
159#[derive(#[automatically_derived]
impl<'ra> ::core::fmt::Debug for ImportData<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["kind", "root_id", "use_span", "use_span_with_attributes",
"has_attributes", "span", "root_span", "parent_scope",
"module_path", "imported_module", "vis", "vis_span",
"on_unknown_attr"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.kind, &self.root_id, &self.use_span,
&self.use_span_with_attributes, &self.has_attributes,
&self.span, &self.root_span, &self.parent_scope,
&self.module_path, &self.imported_module, &self.vis,
&self.vis_span, &&self.on_unknown_attr];
::core::fmt::Formatter::debug_struct_fields_finish(f, "ImportData",
names, values)
}
}Debug, #[automatically_derived]
impl<'ra> ::core::clone::Clone for ImportData<'ra> {
#[inline]
fn clone(&self) -> ImportData<'ra> {
ImportData {
kind: ::core::clone::Clone::clone(&self.kind),
root_id: ::core::clone::Clone::clone(&self.root_id),
use_span: ::core::clone::Clone::clone(&self.use_span),
use_span_with_attributes: ::core::clone::Clone::clone(&self.use_span_with_attributes),
has_attributes: ::core::clone::Clone::clone(&self.has_attributes),
span: ::core::clone::Clone::clone(&self.span),
root_span: ::core::clone::Clone::clone(&self.root_span),
parent_scope: ::core::clone::Clone::clone(&self.parent_scope),
module_path: ::core::clone::Clone::clone(&self.module_path),
imported_module: ::core::clone::Clone::clone(&self.imported_module),
vis: ::core::clone::Clone::clone(&self.vis),
vis_span: ::core::clone::Clone::clone(&self.vis_span),
on_unknown_attr: ::core::clone::Clone::clone(&self.on_unknown_attr),
}
}
}Clone)]
161pub(crate) struct ImportData<'ra> {
162 pub kind: ImportKind<'ra>,
163
164 pub root_id: NodeId,
174
175 pub use_span: Span,
177
178 pub use_span_with_attributes: Span,
180
181 pub has_attributes: bool,
183
184 pub span: Span,
186
187 pub root_span: Span,
189
190 pub parent_scope: ParentScope<'ra>,
191 pub module_path: Vec<Segment>,
192 pub imported_module: CmCell<Option<ModuleOrUniformRoot<'ra>>>,
201 pub vis: Visibility,
202
203 pub vis_span: Span,
205
206 pub on_unknown_attr: Option<OnUnknownData>,
212}
213
214pub(crate) type Import<'ra> = Interned<'ra, ImportData<'ra>>;
217
218impl std::hash::Hash for ImportData<'_> {
223 fn hash<H>(&self, _: &mut H)
224 where
225 H: std::hash::Hasher,
226 {
227 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
228 }
229}
230
231impl<'ra> ImportData<'ra> {
232 pub(crate) fn is_glob(&self) -> bool {
233 #[allow(non_exhaustive_omitted_patterns)] match self.kind {
ImportKind::Glob { .. } => true,
_ => false,
}matches!(self.kind, ImportKind::Glob { .. })
234 }
235
236 pub(crate) fn is_nested(&self) -> bool {
237 match self.kind {
238 ImportKind::Single { nested, .. } => nested,
239 _ => false,
240 }
241 }
242
243 pub(crate) fn id(&self) -> Option<NodeId> {
244 match self.kind {
245 ImportKind::Single { id, .. }
246 | ImportKind::Glob { id, .. }
247 | ImportKind::ExternCrate { id, .. } => Some(id),
248 ImportKind::MacroUse { .. } | ImportKind::MacroExport => None,
249 }
250 }
251
252 pub(crate) fn def_id(&self) -> Option<LocalDefId> {
253 match self.kind {
254 ImportKind::Single { def_id, .. }
255 | ImportKind::Glob { def_id, .. }
256 | ImportKind::ExternCrate { def_id, .. } => Some(def_id),
257 ImportKind::MacroUse { .. } | ImportKind::MacroExport => None,
258 }
259 }
260
261 pub(crate) fn simplify(&self) -> Reexport {
262 match self.kind {
263 ImportKind::Single { def_id, .. } => Reexport::Single(def_id.to_def_id()),
264 ImportKind::Glob { def_id, .. } => Reexport::Glob(def_id.to_def_id()),
265 ImportKind::ExternCrate { def_id, .. } => Reexport::ExternCrate(def_id.to_def_id()),
266 ImportKind::MacroUse { .. } => Reexport::MacroUse,
267 ImportKind::MacroExport => Reexport::MacroExport,
268 }
269 }
270
271 fn summary(&self) -> ImportSummary {
272 ImportSummary {
273 vis: self.vis,
274 nearest_parent_mod: self.parent_scope.module.nearest_parent_mod().expect_local(),
275 is_single: #[allow(non_exhaustive_omitted_patterns)] match self.kind {
ImportKind::Single { .. } => true,
_ => false,
}matches!(self.kind, ImportKind::Single { .. }),
276 priv_macro_use: #[allow(non_exhaustive_omitted_patterns)] match self.kind {
ImportKind::MacroUse { warn_private: true } => true,
_ => false,
}matches!(self.kind, ImportKind::MacroUse { warn_private: true }),
277 span: self.span,
278 }
279 }
280}
281
282#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for NameResolution<'ra> {
#[inline]
fn clone(&self) -> NameResolution<'ra> {
NameResolution {
single_imports: ::core::clone::Clone::clone(&self.single_imports),
non_glob_decl: ::core::clone::Clone::clone(&self.non_glob_decl),
glob_decl: ::core::clone::Clone::clone(&self.glob_decl),
orig_ident_span: ::core::clone::Clone::clone(&self.orig_ident_span),
}
}
}Clone, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for NameResolution<'ra> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field4_finish(f,
"NameResolution", "single_imports", &self.single_imports,
"non_glob_decl", &self.non_glob_decl, "glob_decl",
&self.glob_decl, "orig_ident_span", &&self.orig_ident_span)
}
}Debug)]
284pub(crate) struct NameResolution<'ra> {
285 pub single_imports: FxIndexSet<Import<'ra>>,
288 pub non_glob_decl: Option<Decl<'ra>> = None,
290 pub glob_decl: Option<Decl<'ra>> = None,
292 pub orig_ident_span: Span,
293}
294
295pub(crate) type NameResolutionRef<'ra> = Interned<'ra, CmRefCell<NameResolution<'ra>>>;
296
297impl<'ra> NameResolution<'ra> {
298 pub(crate) fn new(orig_ident_span: Span) -> Self {
299 NameResolution { single_imports: FxIndexSet::default(), orig_ident_span, .. }
300 }
301
302 pub(crate) fn determined_decl(&self) -> Option<Decl<'ra>> {
311 if self.non_glob_decl.is_some() {
312 self.non_glob_decl
313 } else if self.glob_decl.is_some() && self.single_imports.is_empty() {
314 self.glob_decl
315 } else {
316 None
317 }
318 }
319
320 pub(crate) fn best_decl(&self) -> Option<Decl<'ra>> {
321 self.non_glob_decl.or(self.glob_decl)
322 }
323}
324
325pub(crate) mod cycle_detection {
327 use std::ptr;
328
329 use crate::CacheRefCell;
330 use crate::imports::NameResolutionRef;
331
332 #[doc = r" During import resolution, recursive imports can form cycles."]
#[doc =
r" This set stores the active resolution stack for the current thread."]
#[doc = r" So it's essentially a recursion stack."]
#[doc = r""]
#[doc =
r" The key is the interned address of a `RefCell<NameResolution<'ra>>` allocated"]
#[doc =
r" in the `Resolver Arenas` (lifetime `'ra`), it is thus stable and allows casting"]
#[doc =
r" to a `*const ()` for comparison. This is done because we can't use lifetimes"]
#[doc = r" other than `'static` in thread local storage."]
const ACTIVE_RESOLUTIONS:
::std::thread::LocalKey<CacheRefCell<Vec<*const ()>>> =
{
#[inline]
fn __rust_std_internal_init_fn() -> CacheRefCell<Vec<*const ()>> {
Default::default()
}
unsafe {
::std::thread::LocalKey::new(const {
if ::std::mem::needs_drop::<CacheRefCell<Vec<*const ()>>>()
{
|__rust_std_internal_init|
{
#[thread_local]
static __RUST_STD_INTERNAL_VAL:
::std::thread::local_impl::LazyStorage<CacheRefCell<Vec<*const ()>>,
()> =
::std::thread::local_impl::LazyStorage::new();
__RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init,
__rust_std_internal_init_fn)
}
} else {
|__rust_std_internal_init|
{
#[thread_local]
static __RUST_STD_INTERNAL_VAL:
::std::thread::local_impl::LazyStorage<CacheRefCell<Vec<*const ()>>,
!> =
::std::thread::local_impl::LazyStorage::new();
__RUST_STD_INTERNAL_VAL.get_or_init(__rust_std_internal_init,
__rust_std_internal_init_fn)
}
}
})
}
};thread_local!(
333 static ACTIVE_RESOLUTIONS: CacheRefCell<Vec<*const ()>> = Default::default();
342 );
343
344 pub(crate) struct ActiveResolutionGuard {
345 key: *const (),
346 }
347
348 impl Drop for ActiveResolutionGuard {
349 fn drop(&mut self) {
350 ACTIVE_RESOLUTIONS.with_borrow_mut(|ar| {
351 if !(Some(self.key) == ar.pop()) {
{
::core::panicking::panic_fmt(format_args!("This guard should be the only one removing this key"));
}
};assert!(
353 Some(self.key) == ar.pop(),
354 "This guard should be the only one removing this key"
355 );
356 });
357 }
358 }
359
360 pub(crate) fn enter_cycle_detector<'ra>(
363 resolution: NameResolutionRef<'ra>,
364 ) -> Result<ActiveResolutionGuard, ()> {
365 let key = ptr::from_ref(resolution.0).cast::<()>();
366 ACTIVE_RESOLUTIONS.with_borrow_mut(|ar| {
367 if ar.contains(&key) {
368 return Err(());
369 }
370 ar.push(key);
371 Ok(ActiveResolutionGuard { key })
372 })
373 }
374}
375
376#[derive(#[automatically_derived]
impl ::core::fmt::Debug for UnresolvedImportError {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
let names: &'static _ =
&["span", "label", "note", "suggestion", "candidates", "segment",
"module", "on_unknown_attr"];
let values: &[&dyn ::core::fmt::Debug] =
&[&self.span, &self.label, &self.note, &self.suggestion,
&self.candidates, &self.segment, &self.module,
&&self.on_unknown_attr];
::core::fmt::Formatter::debug_struct_fields_finish(f,
"UnresolvedImportError", names, values)
}
}Debug, #[automatically_derived]
impl ::core::clone::Clone for UnresolvedImportError {
#[inline]
fn clone(&self) -> UnresolvedImportError {
UnresolvedImportError {
span: ::core::clone::Clone::clone(&self.span),
label: ::core::clone::Clone::clone(&self.label),
note: ::core::clone::Clone::clone(&self.note),
suggestion: ::core::clone::Clone::clone(&self.suggestion),
candidates: ::core::clone::Clone::clone(&self.candidates),
segment: ::core::clone::Clone::clone(&self.segment),
module: ::core::clone::Clone::clone(&self.module),
on_unknown_attr: ::core::clone::Clone::clone(&self.on_unknown_attr),
}
}
}Clone)]
379pub(crate) struct UnresolvedImportError {
380 pub(crate) span: Span,
381 pub(crate) label: Option<String>,
382 pub(crate) note: Option<String>,
383 pub(crate) suggestion: Option<Suggestion>,
384 pub(crate) candidates: Option<Vec<ImportSuggestion>>,
385 pub(crate) segment: Option<Ident>,
386 pub(crate) module: Option<DefId>,
388 pub(crate) on_unknown_attr: Option<OnUnknownData>,
389}
390
391fn pub_use_of_private_extern_crate_hack(
394 import: ImportSummary,
395 decl: Decl<'_>,
396) -> Option<LocalDefId> {
397 match (import.is_single, decl.kind) {
398 (true, DeclKind::Import { import: decl_import, .. })
399 if let ImportKind::ExternCrate { def_id, .. } = decl_import.kind
400 && import.vis.is_public() =>
401 {
402 Some(def_id)
403 }
404 _ => None,
405 }
406}
407
408fn remove_same_import<'ra>(d1: Decl<'ra>, d2: Decl<'ra>) -> (Decl<'ra>, Decl<'ra>) {
410 if let DeclKind::Import { import: import1, source_decl: d1_next } = d1.kind
411 && let DeclKind::Import { import: import2, source_decl: d2_next } = d2.kind
412 && import1 == import2
413 {
414 {
match (&d1.expansion, &d2.expansion) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(d1.expansion, d2.expansion);
415 {
match (&d1.span, &d2.span) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(d1.span, d2.span);
416 if d1.ambiguity.get() != d2.ambiguity.get() {
417 if !d1.ambiguity.get().is_some() {
::core::panicking::panic("assertion failed: d1.ambiguity.get().is_some()")
};assert!(d1.ambiguity.get().is_some());
418 }
419 remove_same_import(d1_next, d2_next)
422 } else {
423 (d1, d2)
424 }
425}
426
427impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
428 pub(crate) fn import_decl_vis(&self, decl: Decl<'ra>, import: ImportSummary) -> Visibility {
429 self.import_decl_vis_ext(decl, import, false)
430 }
431
432 pub(crate) fn import_decl_vis_ext(
433 &self,
434 decl: Decl<'ra>,
435 import: ImportSummary,
436 min: bool,
437 ) -> Visibility {
438 if !import.vis.is_accessible_from(import.nearest_parent_mod, self.tcx) {
::core::panicking::panic("assertion failed: import.vis.is_accessible_from(import.nearest_parent_mod, self.tcx)")
};assert!(import.vis.is_accessible_from(import.nearest_parent_mod, self.tcx));
439 let decl_vis = if min { decl.min_vis() } else { decl.vis() };
440 let ord = decl_vis.partial_cmp(import.vis, self.tcx);
441 let extern_crate_hack = pub_use_of_private_extern_crate_hack(import, decl).is_some();
442 if ord == Some(Ordering::Less)
443 && decl_vis.is_accessible_from(import.nearest_parent_mod, self.tcx)
444 && !extern_crate_hack
445 {
446 decl_vis.expect_local()
449 } else {
450 if !min
458 && #[allow(non_exhaustive_omitted_patterns)] match ord {
None | Some(Ordering::Less) => true,
_ => false,
}matches!(ord, None | Some(Ordering::Less))
459 && !extern_crate_hack
460 && !import.priv_macro_use
461 {
462 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("cannot extend visibility from {1:?} to {0:?}",
import.vis, decl_vis))
})format!("cannot extend visibility from {decl_vis:?} to {:?}", import.vis);
463 self.dcx().span_delayed_bug(import.span, msg);
464 }
465 import.vis
466 }
467 }
468
469 pub(crate) fn new_import_decl(&self, decl: Decl<'ra>, import: Import<'ra>) -> Decl<'ra> {
472 let vis = self.import_decl_vis(decl, import.summary());
473
474 if let ImportKind::Glob { ref max_vis, .. } = import.kind
475 && (vis == import.vis
476 || max_vis.get().is_none_or(|max_vis| vis.greater_than(max_vis, self.tcx)))
477 {
478 max_vis.set(Some(vis), self)
480 }
481
482 self.arenas.alloc_decl(DeclData {
483 kind: DeclKind::Import { source_decl: decl, import },
484 ambiguity: CmCell::new(None),
485 span: import.span,
486 initial_vis: vis.to_def_id(),
487 ambiguity_vis_max: CmCell::new(None),
488 ambiguity_vis_min: CmCell::new(None),
489 expansion: import.parent_scope.expansion,
490 parent_module: Some(import.parent_scope.module),
491 })
492 }
493
494 fn is_noise_0_7_0(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> bool {
495 let DeclKind::Import { import: i1, .. } = glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
496 let DeclKind::Import { import: i2, .. } = old_glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
497 let [seg1, seg2] = &i1.module_path[..] else { return false };
498 if seg1.ident.name != kw::SelfLower || seg2.ident.name.as_str() != "perlin_surflet" {
499 return false;
500 }
501 let [seg1, seg2] = &i2.module_path[..] else { return false };
502 if seg1.ident.name != kw::SelfLower || seg2.ident.name.as_str() != "perlin" {
503 return false;
504 }
505 let Some(def_id1) = glob_decl.res().opt_def_id() else { return false };
506 let Some(def_id2) = old_glob_decl.res().opt_def_id() else { return false };
507 self.def_path_str(def_id1).ends_with("noise_fns::generators::perlin_surflet::Perlin")
508 && self.def_path_str(def_id2).ends_with("noise_fns::generators::perlin::Perlin")
509 }
510
511 fn is_rustybuzz_0_4_0(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> bool {
512 let DeclKind::Import { import: i1, .. } = glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
513 let DeclKind::Import { import: i2, .. } = old_glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
514 let [seg1, seg2] = &i1.module_path[..] else { return false };
515 if seg1.ident.name != kw::Super || seg2.ident.name.as_str() != "gsubgpos" {
516 return false;
517 }
518 let [seg1] = &i2.module_path[..] else { return false };
519 if seg1.ident.name != kw::Super {
520 return false;
521 }
522 let Some(def_id1) = glob_decl.res().opt_def_id() else { return false };
523 let Some(def_id2) = old_glob_decl.res().opt_def_id() else { return false };
524 self.def_path_str(def_id1).ends_with("tables::gsubgpos::Class")
525 && self.def_path_str(def_id2).ends_with("ggg::Class")
526 }
527
528 fn is_pdf_0_9_0(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> bool {
529 let DeclKind::Import { import: i1, .. } = glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
530 let DeclKind::Import { import: i2, .. } = old_glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
531 let [seg1, seg2] = &i1.module_path[..] else { return false };
532 if seg1.ident.name != kw::Crate || seg2.ident.name.as_str() != "content" {
533 return false;
534 }
535 let [seg1, seg2] = &i2.module_path[..] else { return false };
536 if seg1.ident.name != kw::Crate || seg2.ident.name.as_str() != "object" {
537 return false;
538 }
539 let Some(def_id1) = glob_decl.res().opt_def_id() else { return false };
540 let Some(def_id2) = old_glob_decl.res().opt_def_id() else { return false };
541 self.def_path_str(def_id1).ends_with("crate::content::Rect")
542 && self.def_path_str(def_id2).ends_with("crate::object::types::Rect")
543 }
544
545 fn is_net2_0_2_39(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> bool {
546 let DeclKind::Import { import: i1, .. } = glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
547 let DeclKind::Import { import: i2, .. } = old_glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
548 let [seg1, seg2, seg3, seg4] = &i1.module_path[..] else { return false };
549 if seg1.ident.name != kw::PathRoot
550 || seg2.ident.name.as_str() != "winapi"
551 || seg3.ident.name.as_str() != "shared"
552 || seg4.ident.name.as_str() != "ws2def"
553 {
554 return false;
555 }
556 let [seg1, seg2, seg3, seg4] = &i2.module_path[..] else { return false };
557 if seg1.ident.name != kw::PathRoot
558 || seg2.ident.name.as_str() != "winapi"
559 || seg3.ident.name.as_str() != "um"
560 || seg4.ident.name.as_str() != "winsock2"
561 {
562 return false;
563 }
564 let Some(def_id1) = glob_decl.res().opt_def_id() else { return false };
565 let Some(def_id2) = old_glob_decl.res().opt_def_id() else { return false };
566 self.def_path_str(def_id1).starts_with("winapi::shared::ws2def::")
567 && self.def_path_str(def_id2).starts_with("winapi::um::winsock2::")
568 }
569
570 fn select_glob_decl(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> Decl<'ra> {
573 if !glob_decl.is_glob_import() {
::core::panicking::panic("assertion failed: glob_decl.is_glob_import()")
};assert!(glob_decl.is_glob_import());
574 if !old_glob_decl.is_glob_import() {
::core::panicking::panic("assertion failed: old_glob_decl.is_glob_import()")
};assert!(old_glob_decl.is_glob_import());
575 {
match (&glob_decl, &old_glob_decl) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_ne!(glob_decl, old_glob_decl);
576 let (old_deep_decl, deep_decl) = remove_same_import(old_glob_decl, glob_decl);
588 if deep_decl != glob_decl {
589 {
match (&old_deep_decl, &old_glob_decl) {
(left_val, right_val) => {
if *left_val == *right_val {
let kind = ::core::panicking::AssertKind::Ne;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_ne!(old_deep_decl, old_glob_decl);
591 if !!deep_decl.is_glob_import() {
::core::panicking::panic("assertion failed: !deep_decl.is_glob_import()")
};assert!(!deep_decl.is_glob_import());
592 if let Some((old_ambig, _)) = old_glob_decl.ambiguity.get()
593 && glob_decl.ambiguity.get().is_none()
594 {
595 glob_decl.ambiguity.set(Some((old_ambig, true)), self);
597 }
598 glob_decl
599 } else if glob_decl.res() != old_glob_decl.res() {
600 let warning = self.is_noise_0_7_0(old_glob_decl, glob_decl)
601 || self.is_rustybuzz_0_4_0(old_glob_decl, glob_decl)
602 || self.is_pdf_0_9_0(old_glob_decl, glob_decl)
603 || self.is_net2_0_2_39(old_glob_decl, glob_decl);
604 old_glob_decl.ambiguity.set(Some((glob_decl, warning)), self);
605 old_glob_decl
606 } else if let old_vis = old_glob_decl.vis()
607 && let vis = glob_decl.vis()
608 && old_vis != vis
609 {
610 if vis.greater_than(old_vis, self.tcx) {
613 old_glob_decl.ambiguity_vis_max.set(Some(glob_decl), self);
614 } else if let old_min_vis = old_glob_decl.min_vis()
615 && old_min_vis != vis
616 && old_min_vis.greater_than(vis, self.tcx)
617 {
618 old_glob_decl.ambiguity_vis_min.set(Some(glob_decl), self);
619 }
620 old_glob_decl
621 } else if glob_decl.is_ambiguity_recursive() && !old_glob_decl.is_ambiguity_recursive() {
622 old_glob_decl.ambiguity.set(Some((glob_decl, true)), self);
624 old_glob_decl
625 } else {
626 old_glob_decl
627 }
628 }
629
630 pub(crate) fn try_plant_decl_into_local_module(
633 &mut self,
634 ident: IdentKey,
635 orig_ident_span: Span,
636 ns: Namespace,
637 decl: Decl<'ra>,
638 ) -> Result<(), Decl<'ra>> {
639 if !decl.ambiguity.get().is_none() {
::core::panicking::panic("assertion failed: decl.ambiguity.get().is_none()")
};assert!(decl.ambiguity.get().is_none());
640 if !decl.ambiguity_vis_max.get().is_none() {
::core::panicking::panic("assertion failed: decl.ambiguity_vis_max.get().is_none()")
};assert!(decl.ambiguity_vis_max.get().is_none());
641 if !decl.ambiguity_vis_min.get().is_none() {
::core::panicking::panic("assertion failed: decl.ambiguity_vis_min.get().is_none()")
};assert!(decl.ambiguity_vis_min.get().is_none());
642 let module = decl.parent_module.unwrap().expect_local();
643 if !self.is_accessible_from(decl.vis(), module.to_module()) {
::core::panicking::panic("assertion failed: self.is_accessible_from(decl.vis(), module.to_module())")
};assert!(self.is_accessible_from(decl.vis(), module.to_module()));
644 let res = decl.res();
645 self.check_reserved_macro_name(ident.name, orig_ident_span, res);
646 let key = BindingKey::new_disambiguated(ident, ns, || {
650 module.underscore_disambiguator.update(self, |d| d + 1);
651 module.underscore_disambiguator.get()
652 });
653 self.update_local_resolution(module, key, orig_ident_span, |this, resolution| {
654 if res == Res::Err
655 && let Some(old_decl) = resolution.best_decl()
656 && old_decl.res() != Res::Err
657 {
658 return Ok(());
662 }
663 if decl.is_glob_import() {
664 resolution.glob_decl = Some(match resolution.glob_decl {
665 Some(old_decl) => this.select_glob_decl(old_decl, decl),
666 None => decl,
667 });
668 } else {
669 resolution.non_glob_decl = Some(match resolution.non_glob_decl {
670 Some(old_decl) => return Err(old_decl),
671 None => decl,
672 })
673 }
674
675 Ok(())
676 })
677 }
678
679 fn update_local_resolution<T, F>(
682 &mut self,
683 module: LocalModule<'ra>,
684 key: BindingKey,
685 orig_ident_span: Span,
686 f: F,
687 ) -> T
688 where
689 F: FnOnce(&Resolver<'ra, 'tcx>, &mut NameResolution<'ra>) -> T,
690 {
691 let (binding, t) = {
694 let resolution = &mut *self
695 .resolution_or_default(module.to_module(), key, orig_ident_span)
696 .0
697 .borrow_mut(self);
698 let old_decl = resolution.determined_decl();
699 let old_vis = old_decl.map(|d| d.vis());
700
701 let t = f(self, resolution);
702
703 if let Some(binding) = resolution.determined_decl()
704 && (old_decl != Some(binding) || old_vis != Some(binding.vis()))
705 {
706 (binding, t)
707 } else {
708 return t;
709 }
710 };
711
712 let Ok(glob_importers) = module.glob_importers.try_borrow_mut(self) else {
713 return t;
714 };
715
716 for import in glob_importers.iter() {
718 let mut ident = key.ident;
719 let scope = match ident
720 .ctxt
721 .update_unchecked(|ctxt| ctxt.reverse_glob_adjust(module.expansion, import.span))
722 {
723 Some(Some(def)) => self.expn_def_scope(def),
724 Some(None) => import.parent_scope.module,
725 None => continue,
726 };
727 if self.is_accessible_from(binding.vis(), scope) {
728 let import_decl = self.new_import_decl(binding, *import);
729 self.try_plant_decl_into_local_module(ident, orig_ident_span, key.ns, import_decl)
730 .expect("planting a glob cannot fail");
731 }
732 }
733
734 t
735 }
736
737 fn import_dummy_binding(&mut self, import: Import<'ra>, is_indeterminate: bool) {
740 if let ImportKind::Single { target, ref decls, .. } = import.kind {
741 if !(is_indeterminate || decls.iter().all(|d| d.get().decl().is_none())) {
742 return; }
744 let dummy_decl = self.dummy_decl;
745 let dummy_decl = self.new_import_decl(dummy_decl, import);
746 self.per_ns(|this, ns| {
747 let ident = IdentKey::new(target);
748 let _ = this.try_plant_decl_into_local_module(ident, target.span, ns, dummy_decl);
750 if target.name != kw::Underscore {
752 let key = BindingKey::new(ident, ns);
753 this.update_local_resolution(
754 import.parent_scope.module.expect_local(),
755 key,
756 target.span,
757 |_, resolution| {
758 resolution.single_imports.swap_remove(&import);
759 },
760 )
761 }
762 });
763 self.record_use(target, dummy_decl, Used::Other);
764 } else if import.imported_module.get().is_none() {
765 self.import_use_map.insert(import, Used::Other);
766 if let Some(id) = import.id() {
767 self.used_imports.insert(id);
768 }
769 }
770 }
771
772 pub(crate) fn resolve_imports(&mut self) {
784 let mut prev_indeterminate_count = usize::MAX;
785 let mut indeterminate_count = self.indeterminate_imports.len() * 3;
786 while indeterminate_count < prev_indeterminate_count {
787 prev_indeterminate_count = indeterminate_count;
788 indeterminate_count = 0;
789 let mut resolutions = Vec::new();
790 self.assert_speculative = true;
791 for import in mem::take(&mut self.indeterminate_imports) {
792 let (resolution, import_indeterminate_count) = self.cm().resolve_import(import);
793 indeterminate_count += import_indeterminate_count;
794 match import_indeterminate_count {
795 0 => self.determined_imports.push(import),
796 _ => self.indeterminate_imports.push(import),
797 }
798 if let Some(resolution) = resolution {
799 resolutions.push((import, resolution));
800 }
801 }
802 self.assert_speculative = false;
803 self.write_import_resolutions(resolutions);
804 }
805 }
806
807 fn write_import_resolutions(
808 &mut self,
809 import_resolutions: Vec<(Import<'ra>, ImportResolution<'ra>)>,
810 ) {
811 for (import, resolution) in &import_resolutions {
812 let ImportResolution { imported_module, .. } = resolution;
813 import.imported_module.set(Some(*imported_module), self);
814
815 if import.is_glob()
816 && let ModuleOrUniformRoot::Module(module) = imported_module
817 && import.parent_scope.module != *module
818 && module.is_local()
819 {
820 module.glob_importers.borrow_mut(self).push(*import);
821 }
822 }
823
824 for (import, resolution) in import_resolutions {
825 let ImportResolution { imported_module, kind: resolution_kind } = resolution;
826
827 match (&import.kind, resolution_kind) {
828 (
829 ImportKind::Single { target, decls, .. },
830 ImportResolutionKind::Single(import_decls),
831 ) => {
832 self.per_ns(|this, ns| {
833 match import_decls[ns] {
834 PendingDecl::Ready(Some(import_decl)) => {
835 if import_decl.is_assoc_item()
836 && !this.features.import_trait_associated_functions()
837 {
838 feature_err(
839 this.tcx.sess,
840 sym::import_trait_associated_functions,
841 import.span,
842 "`use` associated items of traits is unstable",
843 )
844 .emit();
845 }
846 this.plant_decl_into_local_module(
847 IdentKey::new(*target),
848 target.span,
849 ns,
850 import_decl,
851 );
852 decls[ns].set(PendingDecl::Ready(Some(import_decl)), this);
853 }
854 PendingDecl::Ready(None) => {
855 if target.name != kw::Underscore {
857 let key = BindingKey::new(IdentKey::new(*target), ns);
858 this.update_local_resolution(
859 import.parent_scope.module.expect_local(),
860 key,
861 target.span,
862 |_, resolution| {
863 resolution.single_imports.swap_remove(&import);
864 },
865 );
866 }
867 decls[ns].set(PendingDecl::Ready(None), this);
868 }
869 PendingDecl::Pending => {}
870 }
871 });
872 }
873 (ImportKind::Glob { id, .. }, ImportResolutionKind::Glob(imported_decls)) => {
874 let ModuleOrUniformRoot::Module(module) = imported_module else {
875 self.dcx().emit_err(CannotGlobImportAllCrates { span: import.span });
876 continue;
877 };
878
879 if module.is_trait() && !self.features.import_trait_associated_functions() {
880 feature_err(
881 self.tcx.sess,
882 sym::import_trait_associated_functions,
883 import.span,
884 "`use` associated items of traits is unstable",
885 )
886 .emit();
887 }
888
889 for (binding, key, orig_ident_span) in imported_decls {
890 let import_decl = self.new_import_decl(binding, import);
891 let _ = self
892 .try_plant_decl_into_local_module(
893 key.ident,
894 orig_ident_span,
895 key.ns,
896 import_decl,
897 )
898 .expect("planting a glob cannot fail");
899 }
900
901 self.record_partial_res(*id, PartialRes::new(module.res().unwrap()));
902 }
903
904 _ => {
::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
format_args!("mismatched import and resolution kind")));
}unreachable!("mismatched import and resolution kind"),
906 }
907 }
908 }
909
910 pub(crate) fn finalize_imports(&mut self) {
911 let mut module_children = Default::default();
912 let mut ambig_module_children = Default::default();
913 for module in &self.local_modules {
914 self.finalize_resolutions_in(*module, &mut module_children, &mut ambig_module_children);
915 }
916 self.module_children = module_children;
917 self.ambig_module_children = ambig_module_children;
918
919 let mut seen_spans = FxHashSet::default();
920 let mut errors = ::alloc::vec::Vec::new()vec![];
921 let mut prev_root_id: NodeId = NodeId::ZERO;
922 let determined_imports = mem::take(&mut self.determined_imports);
923 let indeterminate_imports = mem::take(&mut self.indeterminate_imports);
924
925 let mut glob_error = false;
926 for (is_indeterminate, import) in determined_imports
927 .iter()
928 .map(|i| (false, i))
929 .chain(indeterminate_imports.iter().map(|i| (true, i)))
930 {
931 let unresolved_import_error = self.finalize_import(*import);
932 self.import_dummy_binding(*import, is_indeterminate);
935
936 let Some(err) = unresolved_import_error else { continue };
937
938 glob_error |= import.is_glob();
939
940 if let ImportKind::Single { source, ref decls, .. } = import.kind
941 && source.name == kw::SelfLower
942 && let PendingDecl::Ready(None) = decls.value_ns.get()
944 {
945 continue;
946 }
947
948 if prev_root_id != NodeId::ZERO && prev_root_id != import.root_id && !errors.is_empty()
949 {
950 self.throw_unresolved_import_error(errors, glob_error);
953 errors = ::alloc::vec::Vec::new()vec![];
954 }
955 if seen_spans.insert(err.span) {
956 errors.push((*import, err));
957 prev_root_id = import.root_id;
958 }
959 }
960
961 if self.cstore().had_extern_crate_load_failure() {
962 self.tcx.sess.dcx().abort_if_errors();
963 }
964
965 if !errors.is_empty() {
966 self.throw_unresolved_import_error(errors, glob_error);
967 return;
968 }
969
970 for import in &indeterminate_imports {
971 let path = import_path_to_string(
972 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
973 &import.kind,
974 import.span,
975 );
976 if path.contains("::") {
979 let err = UnresolvedImportError {
980 span: import.span,
981 label: None,
982 note: None,
983 suggestion: None,
984 candidates: None,
985 segment: None,
986 module: None,
987 on_unknown_attr: import.on_unknown_attr.clone(),
988 };
989 errors.push((*import, err))
990 }
991 }
992
993 if !errors.is_empty() {
994 self.throw_unresolved_import_error(errors, glob_error);
995 }
996 }
997
998 pub(crate) fn lint_reexports(&mut self, exported_ambiguities: FxHashSet<Decl<'ra>>) {
999 for module in &self.local_modules {
1000 for (key, resolution) in self.resolutions(module.to_module()).borrow().iter() {
1001 let resolution = resolution.borrow();
1002 let Some(binding) = resolution.best_decl() else { continue };
1003
1004 for decl in [resolution.non_glob_decl, resolution.glob_decl] {
1007 if let Some(decl) = decl
1008 && let DeclKind::Import { source_decl, import } = decl.kind
1009 && decl.ambiguity_vis_max.get().is_none()
1013 {
1014 let ord = source_decl.vis().partial_cmp(decl.vis(), self.tcx);
1017 if #[allow(non_exhaustive_omitted_patterns)] match ord {
None | Some(Ordering::Less) => true,
_ => false,
}matches!(ord, None | Some(Ordering::Less)) {
1018 let ident = match import.kind {
1019 ImportKind::Single { source, .. } => source,
1020 _ => key.ident.orig(resolution.orig_ident_span),
1021 };
1022 if let Some(lint) =
1023 self.report_cannot_reexport(import, source_decl, ident, key.ns)
1024 {
1025 self.lint_buffer.add_early_lint(lint);
1026 }
1027 }
1028 }
1029 }
1030
1031 if let DeclKind::Import { import, .. } = binding.kind
1032 && let Some((amb_binding, _)) = binding.ambiguity.get()
1033 && binding.res() != Res::Err
1034 && exported_ambiguities.contains(&binding)
1035 {
1036 self.lint_buffer.buffer_lint(
1037 AMBIGUOUS_GLOB_REEXPORTS,
1038 import.root_id,
1039 import.root_span,
1040 diagnostics::AmbiguousGlobReexports {
1041 name: key.ident.name.to_string(),
1042 namespace: key.ns.descr().to_string(),
1043 first_reexport: import.root_span,
1044 duplicate_reexport: amb_binding.span,
1045 },
1046 );
1047 }
1048
1049 if let Some(glob_decl) = resolution.glob_decl
1050 && resolution.non_glob_decl.is_some()
1051 {
1052 if binding.res() != Res::Err
1053 && glob_decl.res() != Res::Err
1054 && let DeclKind::Import { import: glob_import, .. } = glob_decl.kind
1055 && let Some(glob_import_def_id) = glob_import.def_id()
1056 && self.effective_visibilities.is_exported(glob_import_def_id)
1057 && glob_decl.vis().is_public()
1058 && !binding.vis().is_public()
1059 {
1060 let binding_id = match binding.kind {
1061 DeclKind::Def(res) => {
1062 Some(self.def_id_to_node_id(res.def_id().expect_local()))
1063 }
1064 DeclKind::Import { import, .. } => import.id(),
1065 };
1066 if let Some(binding_id) = binding_id {
1067 self.lint_buffer.buffer_lint(
1068 HIDDEN_GLOB_REEXPORTS,
1069 binding_id,
1070 binding.span,
1071 diagnostics::HiddenGlobReexports {
1072 name: key.ident.name.to_string(),
1073 namespace: key.ns.descr().to_owned(),
1074 glob_reexport: glob_decl.span,
1075 private_item: binding.span,
1076 },
1077 );
1078 }
1079 }
1080 }
1081
1082 if let DeclKind::Import { import, .. } = binding.kind
1083 && let Some(binding_id) = import.id()
1084 && let import_def_id = import.def_id().unwrap()
1085 && self.effective_visibilities.is_exported(import_def_id)
1086 && let Res::Def(reexported_kind, reexported_def_id) = binding.res()
1087 && !#[allow(non_exhaustive_omitted_patterns)] match reexported_kind {
DefKind::Ctor(..) => true,
_ => false,
}matches!(reexported_kind, DefKind::Ctor(..))
1088 && !reexported_def_id.is_local()
1089 && self.tcx.is_private_dep(reexported_def_id.krate)
1090 {
1091 self.lint_buffer.buffer_lint(
1092 EXPORTED_PRIVATE_DEPENDENCIES,
1093 binding_id,
1094 binding.span,
1095 crate::diagnostics::ReexportPrivateDependency {
1096 name: key.ident.name,
1097 kind: binding.res().descr(),
1098 krate: self.tcx.crate_name(reexported_def_id.krate),
1099 },
1100 );
1101 }
1102 }
1103 }
1104 }
1105
1106 fn resolve_import<'r>(
1112 mut self: CmResolver<'r, 'ra, 'tcx>,
1113 import: Import<'ra>,
1114 ) -> (Option<ImportResolution<'ra>>, usize) {
1115 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/imports.rs:1115",
"rustc_resolve::imports", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/imports.rs"),
::tracing_core::__macro_support::Option::Some(1115u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::imports"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("(resolving import for module) resolving import `{0}::{1}` in `{2}`",
Segment::names_to_string(&import.module_path),
import_kind_to_string(&import.kind),
module_to_string(import.parent_scope.module).unwrap_or_else(||
"???".to_string())) as &dyn Value))])
});
} else { ; }
};debug!(
1116 "(resolving import for module) resolving import `{}::{}` in `{}`",
1117 Segment::names_to_string(&import.module_path),
1118 import_kind_to_string(&import.kind),
1119 module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
1120 );
1121 let module = if let Some(module) = import.imported_module.get() {
1122 module
1123 } else {
1124 let path_res = self.reborrow().maybe_resolve_path(
1125 &import.module_path,
1126 None,
1127 &import.parent_scope,
1128 Some(import),
1129 );
1130
1131 match path_res {
1132 PathResult::Module(module) => module,
1133 PathResult::Indeterminate => return (None, 3),
1134 PathResult::NonModule(..) | PathResult::Failed { .. } => return (None, 0),
1135 }
1136 };
1137
1138 let (source, bindings) = match import.kind {
1139 ImportKind::Single { source, ref decls, .. } => (source, decls),
1140 ImportKind::Glob { .. } => {
1141 let import_resolution = ImportResolution {
1142 imported_module: module,
1143 kind: self.resolve_glob_import(import, module),
1144 };
1145 return (Some(import_resolution), 0);
1146 }
1147 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1148 };
1149
1150 let mut import_decls = PerNS::default();
1151 let mut indeterminate_count = 0;
1152 self.per_ns_cm(|mut this, ns| {
1153 if bindings[ns].get() != PendingDecl::Pending {
1154 return;
1155 };
1156 let binding_result = this.reborrow().maybe_resolve_ident_in_module(
1157 module,
1158 source,
1159 ns,
1160 &import.parent_scope,
1161 Some(import),
1162 );
1163 let pending_decl = match binding_result {
1164 Ok(binding) => {
1165 let import_decl = this.new_import_decl(binding, import);
1167 PendingDecl::Ready(Some(import_decl))
1168 }
1169 Err(Determinacy::Determined) => PendingDecl::Ready(None),
1170 Err(Determinacy::Undetermined) => {
1171 indeterminate_count += 1;
1172 PendingDecl::Pending
1173 }
1174 };
1175 import_decls[ns] = pending_decl;
1176 });
1177 let import_resolution = ImportResolution {
1178 imported_module: module,
1179 kind: ImportResolutionKind::Single(import_decls),
1180 };
1181
1182 (Some(import_resolution), indeterminate_count)
1183 }
1184
1185 fn finalize_import(&mut self, import: Import<'ra>) -> Option<UnresolvedImportError> {
1190 let ignore_decl = match &import.kind {
1191 ImportKind::Single { decls, .. } => decls[TypeNS].get().decl(),
1192 _ => None,
1193 };
1194 let ambiguity_errors_len = |errors: &Vec<AmbiguityError<'_>>| {
1195 errors.iter().filter(|error| error.warning.is_none()).count()
1196 };
1197 let prev_ambiguity_errors_len = ambiguity_errors_len(&self.ambiguity_errors);
1198 let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
1199
1200 let privacy_errors_len = self.privacy_errors.len();
1202
1203 let path_res = self.cm().resolve_path(
1204 &import.module_path,
1205 None,
1206 &import.parent_scope,
1207 Some(finalize),
1208 ignore_decl,
1209 Some(import),
1210 );
1211
1212 let no_ambiguity =
1213 ambiguity_errors_len(&self.ambiguity_errors) == prev_ambiguity_errors_len;
1214
1215 let module = match path_res {
1216 PathResult::Module(module) => {
1217 if let Some(initial_module) = import.imported_module.get() {
1219 if module != initial_module && no_ambiguity && !self.issue_145575_hack_applied {
1220 ::rustc_middle::util::bug::span_bug_fmt(import.span,
format_args!("inconsistent resolution for an import"));span_bug!(import.span, "inconsistent resolution for an import");
1221 }
1222 } else if self.privacy_errors.is_empty() {
1223 self.dcx()
1224 .create_err(CannotDetermineImportResolution { span: import.span })
1225 .emit();
1226 }
1227
1228 module
1229 }
1230 PathResult::Failed {
1231 is_error_from_last_segment: false,
1232 span,
1233 segment,
1234 label,
1235 suggestion,
1236 module,
1237 error_implied_by_parse_error: _,
1238 message,
1239 note: _,
1240 } => {
1241 if no_ambiguity {
1242 if !self.issue_145575_hack_applied {
1243 if !import.imported_module.get().is_none() {
::core::panicking::panic("assertion failed: import.imported_module.get().is_none()")
};assert!(import.imported_module.get().is_none());
1244 }
1245 self.report_error(
1246 span,
1247 ResolutionError::FailedToResolve {
1248 segment: segment.name,
1249 label,
1250 suggestion,
1251 module,
1252 message,
1253 },
1254 );
1255 }
1256 return None;
1257 }
1258 PathResult::Failed {
1259 is_error_from_last_segment: true,
1260 span,
1261 label,
1262 suggestion,
1263 module,
1264 segment,
1265 note,
1266 ..
1267 } => {
1268 if no_ambiguity {
1269 if !self.issue_145575_hack_applied {
1270 if !import.imported_module.get().is_none() {
::core::panicking::panic("assertion failed: import.imported_module.get().is_none()")
};assert!(import.imported_module.get().is_none());
1271 }
1272 let module = if let Some(ModuleOrUniformRoot::Module(m)) = module {
1273 m.opt_def_id()
1274 } else {
1275 None
1276 };
1277 let err = match self
1278 .make_path_suggestion(import.module_path.clone(), &import.parent_scope)
1279 {
1280 Some((suggestion, note)) => UnresolvedImportError {
1281 span,
1282 label: None,
1283 note,
1284 suggestion: Some((
1285 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(span, Segment::names_to_string(&suggestion))]))vec![(span, Segment::names_to_string(&suggestion))],
1286 String::from("a similar path exists"),
1287 Applicability::MaybeIncorrect,
1288 )),
1289 candidates: None,
1290 segment: Some(segment),
1291 module,
1292 on_unknown_attr: import.on_unknown_attr.clone(),
1293 },
1294 None => UnresolvedImportError {
1295 span,
1296 label: Some(label),
1297 note,
1298 suggestion,
1299 candidates: None,
1300 segment: Some(segment),
1301 module,
1302 on_unknown_attr: import.on_unknown_attr.clone(),
1303 },
1304 };
1305 return Some(err);
1306 }
1307 return None;
1308 }
1309 PathResult::NonModule(partial_res) => {
1310 if no_ambiguity && partial_res.full_res() != Some(Res::Err) {
1311 if !import.imported_module.get().is_none() {
::core::panicking::panic("assertion failed: import.imported_module.get().is_none()")
};assert!(import.imported_module.get().is_none());
1313 }
1314 return None;
1316 }
1317 PathResult::Indeterminate => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1318 };
1319
1320 let (ident, target, bindings, import_id) = match import.kind {
1321 ImportKind::Single { source, target, ref decls, id, .. } => (source, target, decls, id),
1322 ImportKind::Glob { ref max_vis, id, def_id } => {
1323 if import.module_path.len() <= 1 {
1324 let mut full_path = import.module_path.clone();
1327 full_path.push(Segment::from_ident(Ident::dummy()));
1328 self.lint_if_path_starts_with_module(finalize, &full_path, None);
1329 }
1330
1331 if let ModuleOrUniformRoot::Module(module) = module
1332 && module == import.parent_scope.module
1333 {
1334 return Some(UnresolvedImportError {
1336 span: import.span,
1337 label: Some(String::from("cannot glob-import a module into itself")),
1338 note: None,
1339 suggestion: None,
1340 candidates: None,
1341 segment: None,
1342 module: None,
1343 on_unknown_attr: None,
1344 });
1345 }
1346 if let Some(max_vis) = max_vis.get()
1347 && import.vis.greater_than(max_vis, self.tcx)
1348 {
1349 self.lint_buffer.buffer_lint(
1350 UNUSED_IMPORTS,
1351 id,
1352 import.span,
1353 crate::diagnostics::RedundantImportVisibility {
1354 span: import.span,
1355 help: (),
1356 max_vis: max_vis.to_string(def_id, self.tcx),
1357 import_vis: import.vis.to_string(def_id, self.tcx),
1358 },
1359 );
1360 }
1361 return None;
1362 }
1363 _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1364 };
1365
1366 if self.privacy_errors.len() != privacy_errors_len {
1367 let mut path = import.module_path.clone();
1370 path.push(Segment::from_ident(ident));
1371 if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.cm().resolve_path(
1372 &path,
1373 None,
1374 &import.parent_scope,
1375 Some(finalize),
1376 ignore_decl,
1377 None,
1378 ) {
1379 let res = module.res().map(|r| (r, ident));
1380 for error in &mut self.privacy_errors[privacy_errors_len..] {
1381 error.outermost_res = res;
1382 }
1383 } else {
1384 for ns in [TypeNS, ValueNS, MacroNS] {
1388 if let Ok(binding) = self.cm().resolve_ident_in_module(
1389 module,
1390 ident,
1391 ns,
1392 &import.parent_scope,
1393 None,
1394 ignore_decl,
1395 None,
1396 ) {
1397 let res = binding.res();
1398 for error in &mut self.privacy_errors[privacy_errors_len..] {
1399 error.outermost_res = Some((res, ident));
1400 }
1401 break;
1402 }
1403 }
1404 }
1405 }
1406
1407 let mut all_ns_err = true;
1408 self.per_ns(|this, ns| {
1409 let binding = this.cm().resolve_ident_in_module(
1410 module,
1411 ident,
1412 ns,
1413 &import.parent_scope,
1414 Some(Finalize {
1415 report_private: false,
1416 import: Some(import.summary()),
1417 ..finalize
1418 }),
1419 bindings[ns].get().decl(),
1420 Some(import),
1421 );
1422
1423 match binding {
1424 Ok(binding) => {
1425 let initial_res = bindings[ns].get().decl().map(|binding| {
1427 let initial_binding = binding.import_source();
1428 all_ns_err = false;
1429 if target.name == kw::Underscore
1430 && initial_binding.is_extern_crate()
1431 && !initial_binding.is_import()
1432 {
1433 let used = if import.module_path.is_empty() {
1434 Used::Scope
1435 } else {
1436 Used::Other
1437 };
1438 this.record_use(ident, binding, used);
1439 }
1440 initial_binding.res()
1441 });
1442 let res = binding.res();
1443 let has_ambiguity_error =
1444 this.ambiguity_errors.iter().any(|error| error.warning.is_none());
1445 if res == Res::Err || has_ambiguity_error {
1446 this.dcx()
1447 .span_delayed_bug(import.span, "some error happened for an import");
1448 return;
1449 }
1450 if let Some(initial_res) = initial_res {
1451 if res != initial_res && !this.issue_145575_hack_applied {
1452 ::rustc_middle::util::bug::span_bug_fmt(import.span,
format_args!("inconsistent resolution for an import"));span_bug!(import.span, "inconsistent resolution for an import");
1453 }
1454 } else if this.privacy_errors.is_empty() {
1455 this.dcx()
1456 .create_err(CannotDetermineImportResolution { span: import.span })
1457 .emit();
1458 }
1459 }
1460 Err(..) => {
1461 }
1468 }
1469 });
1470
1471 if all_ns_err {
1472 let mut all_ns_failed = true;
1473 self.per_ns(|this, ns| {
1474 let binding = this.cm().resolve_ident_in_module(
1475 module,
1476 ident,
1477 ns,
1478 &import.parent_scope,
1479 Some(finalize),
1480 None,
1481 None,
1482 );
1483 if binding.is_ok() {
1484 all_ns_failed = false;
1485 }
1486 });
1487
1488 return if all_ns_failed {
1489 let names = match module {
1490 ModuleOrUniformRoot::Module(module) => {
1491 self.resolutions(module)
1492 .borrow()
1493 .iter()
1494 .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1495 if i.name == ident.name {
1496 return None;
1497 } if i.name == kw::Underscore {
1499 return None;
1500 } let resolution = resolution.borrow();
1503 if let Some(name_binding) = resolution.best_decl() {
1504 match name_binding.kind {
1505 DeclKind::Import { source_decl, .. } => {
1506 match source_decl.kind {
1507 DeclKind::Def(Res::Err) => None,
1510 _ => Some(i.name),
1511 }
1512 }
1513 _ => Some(i.name),
1514 }
1515 } else if resolution.single_imports.is_empty() {
1516 None
1517 } else {
1518 Some(i.name)
1519 }
1520 })
1521 .collect()
1522 }
1523 _ => Vec::new(),
1524 };
1525
1526 let lev_suggestion =
1527 find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
1528 (
1529 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(ident.span, suggestion.to_string())]))vec![(ident.span, suggestion.to_string())],
1530 String::from("a similar name exists in the module"),
1531 Applicability::MaybeIncorrect,
1532 )
1533 });
1534
1535 let (suggestion, note) =
1536 match self.check_for_module_export_macro(import, module, ident) {
1537 Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1538 _ => (lev_suggestion, None),
1539 };
1540
1541 let note = if self.features.import_trait_associated_functions()
1544 && let PathResult::Module(ModuleOrUniformRoot::Module(m)) = path_res
1545 && let Some(Res::Def(DefKind::Enum, _)) = m.res()
1546 {
1547 note.or(Some(
1548 "cannot import inherent associated items, only trait associated items"
1549 .to_string(),
1550 ))
1551 } else {
1552 note
1553 };
1554
1555 let label = match module {
1556 ModuleOrUniformRoot::Module(module) => {
1557 let module_str = module_to_string(module);
1558 if let Some(module_str) = module_str {
1559 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in `{1}`", ident,
module_str))
})format!("no `{ident}` in `{module_str}`")
1560 } else {
1561 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
})format!("no `{ident}` in the root")
1562 }
1563 }
1564 _ => {
1565 if !ident.is_path_segment_keyword() {
1566 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no external crate `{0}`", ident))
})format!("no external crate `{ident}`")
1567 } else {
1568 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
})format!("no `{ident}` in the root")
1571 }
1572 }
1573 };
1574
1575 let parent_suggestion =
1576 self.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true);
1577
1578 Some(UnresolvedImportError {
1579 span: import.span,
1580 label: Some(label),
1581 note,
1582 suggestion,
1583 candidates: if !parent_suggestion.is_empty() {
1584 Some(parent_suggestion)
1585 } else {
1586 None
1587 },
1588 module: import.imported_module.get().and_then(|module| {
1589 if let ModuleOrUniformRoot::Module(m) = module {
1590 m.opt_def_id()
1591 } else {
1592 None
1593 }
1594 }),
1595 segment: Some(ident),
1596 on_unknown_attr: import.on_unknown_attr.clone(),
1597 })
1598 } else {
1599 None
1601 };
1602 }
1603
1604 let mut reexport_error = None;
1605 let mut any_successful_reexport = false;
1606 self.per_ns(|this, ns| {
1607 let Some(binding) = bindings[ns].get().decl() else {
1608 return;
1609 };
1610
1611 if import.vis.greater_than(binding.vis(), this.tcx) {
1612 reexport_error = Some((ns, binding.import_source()));
1616 } else {
1617 any_successful_reexport = true;
1618 }
1619 });
1620
1621 if !any_successful_reexport {
1622 let (ns, binding) = reexport_error.unwrap();
1623 if let Some(lint) = self.report_cannot_reexport(import, binding, ident, ns) {
1624 self.lint_buffer.add_early_lint(lint);
1625 }
1626 }
1627
1628 if import.module_path.len() <= 1 {
1629 let mut full_path = import.module_path.clone();
1632 full_path.push(Segment::from_ident(ident));
1633 self.per_ns(|this, ns| {
1634 if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1635 this.lint_if_path_starts_with_module(finalize, &full_path, Some(binding));
1636 }
1637 });
1638 }
1639
1640 self.per_ns(|this, ns| {
1644 if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1645 this.owners.get_mut(&import_id).unwrap().import_res[ns] = Some(binding.res());
1646 }
1647 });
1648
1649 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/imports.rs:1649",
"rustc_resolve::imports", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/imports.rs"),
::tracing_core::__macro_support::Option::Some(1649u32),
::tracing_core::__macro_support::Option::Some("rustc_resolve::imports"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("(resolving single import) successfully resolved import")
as &dyn Value))])
});
} else { ; }
};debug!("(resolving single import) successfully resolved import");
1650 None
1651 }
1652
1653 fn report_cannot_reexport(
1654 &self,
1655 import: Import<'ra>,
1656 decl: Decl<'ra>,
1657 ident: Ident,
1658 ns: Namespace,
1659 ) -> Option<BufferedEarlyLint> {
1660 let crate_private_reexport = match decl.vis() {
1661 Visibility::Restricted(def_id) if def_id.is_top_level_module() => true,
1662 _ => false,
1663 };
1664
1665 if let Some(extern_crate_id) = pub_use_of_private_extern_crate_hack(import.summary(), decl)
1666 {
1667 let ImportKind::Single { id, .. } = import.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
1668 let sugg = self.tcx.source_span(extern_crate_id).shrink_to_lo();
1669 let diagnostic = crate::diagnostics::PrivateExternCrateReexport { ident, sugg };
1670 return Some(BufferedEarlyLint {
1671 lint_id: LintId::of(PUB_USE_OF_PRIVATE_EXTERN_CRATE),
1672 node_id: id,
1673 span: Some(import.span.into()),
1674 diagnostic: diagnostic.into(),
1675 });
1676 } else if ns == TypeNS {
1677 let err = if crate_private_reexport {
1678 self.dcx().create_err(CannotBeReexportedCratePublicNS { span: import.span, ident })
1679 } else {
1680 self.dcx().create_err(CannotBeReexportedPrivateNS { span: import.span, ident })
1681 };
1682 err.emit();
1683 } else {
1684 let mut err = if crate_private_reexport {
1685 self.dcx().create_err(CannotBeReexportedCratePublic { span: import.span, ident })
1686 } else {
1687 self.dcx().create_err(CannotBeReexportedPrivate { span: import.span, ident })
1688 };
1689
1690 match decl.kind {
1691 DeclKind::Def(Res::Def(DefKind::Macro(_), def_id))
1693 if let SyntaxExtensionKind::MacroRules(mr) =
1694 &self.get_macro_by_def_id(def_id).kind
1695 && mr.is_macro_rules() =>
1696 {
1697 err.subdiagnostic(ConsiderAddingMacroExport { span: decl.span });
1698 err.subdiagnostic(ConsiderMarkingAsPubCrate { vis_span: import.vis_span });
1699 }
1700 _ => {
1701 err.subdiagnostic(ConsiderMarkingAsPub { span: import.span, ident });
1702 }
1703 }
1704 err.emit();
1705 }
1706
1707 None
1708 }
1709
1710 pub(crate) fn check_for_redundant_imports(&mut self, import: Import<'ra>) -> bool {
1711 let ImportKind::Single { source, target, ref decls, id, def_id, .. } = import.kind else {
1713 ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1714 };
1715
1716 if source != target {
1718 return false;
1719 }
1720
1721 if import.parent_scope.expansion != LocalExpnId::ROOT {
1723 return false;
1724 }
1725
1726 if self.import_use_map.get(&import) == Some(&Used::Other)
1731 || self.effective_visibilities.is_exported(def_id)
1732 {
1733 return false;
1734 }
1735
1736 let mut is_redundant = true;
1737 let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1738 self.per_ns(|this, ns| {
1739 let binding = decls[ns].get().decl().map(|b| b.import_source());
1740 if is_redundant && let Some(binding) = binding {
1741 if binding.res() == Res::Err {
1742 return;
1743 }
1744
1745 match this.cm().resolve_ident_in_scope_set(
1746 target,
1747 ScopeSet::All(ns),
1748 &import.parent_scope,
1749 None,
1750 decls[ns].get().decl(),
1751 None,
1752 ) {
1753 Ok(other_binding) => {
1754 is_redundant = binding.res() == other_binding.res()
1755 && !other_binding.is_ambiguity_recursive();
1756 if is_redundant {
1757 redundant_span[ns] =
1758 Some((other_binding.span, other_binding.is_import()));
1759 }
1760 }
1761 Err(_) => is_redundant = false,
1762 }
1763 }
1764 });
1765
1766 if is_redundant && !redundant_span.is_empty() {
1767 let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1768 redundant_spans.sort();
1769 redundant_spans.dedup();
1770 self.lint_buffer.dyn_buffer_lint(
1771 REDUNDANT_IMPORTS,
1772 id,
1773 import.span,
1774 move |dcx, level| {
1775 let ident = source;
1776 let subs = redundant_spans
1777 .into_iter()
1778 .map(|(span, is_imported)| match (span.is_dummy(), is_imported) {
1779 (false, true) => {
1780 diagnostics::RedundantImportSub::ImportedHere { span, ident }
1781 }
1782 (false, false) => {
1783 diagnostics::RedundantImportSub::DefinedHere { span, ident }
1784 }
1785 (true, true) => {
1786 diagnostics::RedundantImportSub::ImportedPrelude { span, ident }
1787 }
1788 (true, false) => {
1789 diagnostics::RedundantImportSub::DefinedPrelude { span, ident }
1790 }
1791 })
1792 .collect();
1793 diagnostics::RedundantImport { subs, ident }.into_diag(dcx, level)
1794 },
1795 );
1796 return true;
1797 }
1798
1799 false
1800 }
1801
1802 fn resolve_glob_import(
1803 &self,
1804 import: Import<'ra>,
1805 imported_module: ModuleOrUniformRoot<'ra>,
1806 ) -> ImportResolutionKind<'ra> {
1807 let import_bindings = match imported_module {
1808 ModuleOrUniformRoot::Module(module) if module != import.parent_scope.module => self
1809 .resolutions(module)
1810 .borrow()
1811 .iter()
1812 .filter_map(|(key, resolution)| {
1813 let res = resolution.borrow();
1814 let decl = res.determined_decl()?;
1815 let mut key = *key;
1816 let scope = match key.ident.ctxt.update_unchecked(|ctxt| {
1817 ctxt.reverse_glob_adjust(module.expansion, import.span)
1818 }) {
1819 Some(Some(def)) => self.expn_def_scope(def),
1820 Some(None) => import.parent_scope.module,
1821 None => return None,
1822 };
1823 self.is_accessible_from(decl.vis(), scope).then_some((
1824 decl,
1825 key,
1826 res.orig_ident_span,
1827 ))
1828 })
1829 .collect::<Vec<_>>(),
1830
1831 _ => ::alloc::vec::Vec::new()vec![],
1833 };
1834
1835 ImportResolutionKind::Glob(import_bindings)
1836 }
1837
1838 fn rust_embed_hack(&self, module: LocalModule<'ra>, decl: Decl<'ra>) -> bool {
1840 if let DeclKind::Import { source_decl, import } = decl.kind
1849 && let ImportKind::Single { source, .. } = import.kind
1851 && source.name == sym::RustEmbed
1852 && let DeclKind::Import { import, .. } = source_decl.kind
1854 && #[allow(non_exhaustive_omitted_patterns)] match import.kind {
ImportKind::MacroUse { .. } => true,
_ => false,
}matches!(import.kind, ImportKind::MacroUse { .. })
1855 && self.macro_use_prelude.contains_key(&source.name) && let Some(y_decl) = self
1858 .resolution(module.to_module(), BindingKey::new(IdentKey::new(source), MacroNS))
1859 .and_then(|res| res.best_decl())
1860 && y_decl.is_glob_import()
1862 && y_decl.vis().is_public()
1863 {
1864 return true;
1865 }
1866
1867 false
1868 }
1869
1870 fn finalize_resolutions_in(
1873 &self,
1874 module: LocalModule<'ra>,
1875 module_children: &mut LocalDefIdMap<Vec<ModChild>>,
1876 ambig_module_children: &mut LocalDefIdMap<Vec<AmbigModChild>>,
1877 ) {
1878 *module.globs.borrow_mut(self) = Vec::new();
1880
1881 let Some(def_id) = module.opt_def_id() else { return };
1882
1883 let mut children = Vec::new();
1884 let mut ambig_children = Vec::new();
1885
1886 module.to_module().for_each_child(self, |this, ident, orig_ident_span, _, decl| {
1887 let res = decl.res().expect_non_local();
1888 if res != def::Res::Err {
1889 let vis = if this.rust_embed_hack(module, decl) {
1890 Visibility::Public
1891 } else {
1892 decl.vis()
1893 };
1894 let ident = ident.orig(orig_ident_span);
1895 let child = |reexport_chain| ModChild { ident, res, vis, reexport_chain };
1896 if let Some((ambig_binding1, ambig_binding2)) = decl.descent_to_ambiguity() {
1897 let main = child(ambig_binding1.reexport_chain());
1898 let second = ModChild {
1899 ident,
1900 res: ambig_binding2.res().expect_non_local(),
1901 vis: ambig_binding2.vis(),
1902 reexport_chain: ambig_binding2.reexport_chain(),
1903 };
1904 ambig_children.push(AmbigModChild { main, second })
1905 } else {
1906 children.push(child(decl.reexport_chain()));
1907 }
1908 }
1909 });
1910
1911 if !children.is_empty() {
1912 module_children.insert(def_id.expect_local(), children);
1913 }
1914 if !ambig_children.is_empty() {
1915 ambig_module_children.insert(def_id.expect_local(), ambig_children);
1916 }
1917 }
1918}
1919
1920pub(crate) fn import_path_to_string(
1921 names: &[Ident],
1922 import_kind: &ImportKind<'_>,
1923 span: Span,
1924) -> String {
1925 let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1926 let global = !names.is_empty() && names[0].name == kw::PathRoot;
1927 if let Some(pos) = pos {
1928 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1929 names_to_string(names.iter().map(|ident| ident.name))
1930 } else {
1931 let names = if global { &names[1..] } else { names };
1932 if names.is_empty() {
1933 import_kind_to_string(import_kind)
1934 } else {
1935 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}::{1}",
names_to_string(names.iter().map(|ident| ident.name)),
import_kind_to_string(import_kind)))
})format!(
1936 "{}::{}",
1937 names_to_string(names.iter().map(|ident| ident.name)),
1938 import_kind_to_string(import_kind),
1939 )
1940 }
1941 }
1942}
1943
1944fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1945 match import_kind {
1946 ImportKind::Single { source, .. } => source.to_string(),
1947 ImportKind::Glob { .. } => "*".to_string(),
1948 ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1949 ImportKind::MacroUse { .. } => "#[macro_use]".to_string(),
1950 ImportKind::MacroExport => "#[macro_export]".to_string(),
1951 }
1952}