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