Skip to main content

rustc_resolve/
imports.rs

1//! A bunch of methods and structures more or less related to resolving imports.
2
3use 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_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::metadata::{AmbigModChild, ModChild, Reexport};
19use rustc_middle::span_bug;
20use rustc_middle::ty::Visibility;
21use rustc_session::diagnostics::feature_err;
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::impls::{OnUnknownData, Suggestion};
29use crate::diagnostics::{
30    self, CannotBeReexportedCratePublic, CannotBeReexportedCratePublicNS,
31    CannotBeReexportedPrivate, CannotBeReexportedPrivateNS, CannotDetermineImportResolution,
32    CannotGlobImportAllCrates, ConsiderAddingMacroExport, ConsiderMarkingAsPub,
33    ConsiderMarkingAsPubCrate,
34};
35use crate::ref_mut::{CmCell, CmRefCell};
36use crate::{
37    AmbiguityError, BindingKey, Decl, DeclData, DeclKind, Determinacy, Finalize, IdentKey,
38    ImportSuggestion, ImportSummary, LocalModule, ModuleOrUniformRoot, ParentScope, PathResult,
39    PerNS, Res, ResolutionError, Resolver, ScopeSet, Segment, Used, module_to_string,
40    names_to_string,
41};
42
43/// A potential import declaration in the process of being planted into a module.
44/// Also used for lazily planting names from `--extern` flags to extern prelude.
45#[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) -> 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::marker::StructuralPartialEq for PendingDecl<'ra> { }
#[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    // these are the decls the import imports, not the import declarations themselves
54    Single(PerNS<PendingDecl<'ra>>),
55    Glob(Vec<(Decl<'ra>, BindingKey, Span /* orig_ident_span */)>),
56}
57
58pub(crate) struct ImportResolution<'ra> {
59    kind: ImportResolutionKind<'ra>,
60    imported_module: ModuleOrUniformRoot<'ra>,
61}
62
63impl<'ra> PendingDecl<'ra> {
64    pub(crate) fn decl(self) -> Option<Decl<'ra>> {
65        match self {
66            PendingDecl::Ready(decl) => decl,
67            PendingDecl::Pending => None,
68        }
69    }
70}
71
72/// Contains data for specific kinds of imports.
73pub(crate) enum ImportKind<'ra> {
74    Single {
75        /// `source` in `use prefix::source as target`.
76        source: Ident,
77        /// `target` in `use prefix::source as target`.
78        /// It will directly use `source` when the format is `use prefix::source`.
79        target: Ident,
80        /// Name declarations introduced by the import.
81        decls: PerNS<CmCell<PendingDecl<'ra>>>,
82        /// Did this import result from a nested import? i.e. `use foo::{bar, baz};`
83        nested: bool,
84        /// The ID of the `UseTree` that imported this `Import`.
85        ///
86        /// In the case where the `Import` was expanded from a "nested" use tree,
87        /// this id is the ID of the leaf tree. For example:
88        ///
89        /// ```ignore (pacify the merciless tidy)
90        /// use foo::bar::{a, b}
91        /// ```
92        ///
93        /// If this is the import for `foo::bar::a`, we would have the ID of the `UseTree`
94        /// for `a` in this field.
95        id: NodeId,
96        def_id: LocalDefId,
97    },
98    Glob {
99        // The visibility of the greatest re-export.
100        // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
101        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        /// A field has been added indicating whether it should be reported as a lint,
113        /// addressing issue#119301.
114        warn_private: bool,
115    },
116    MacroExport,
117}
118
119/// Manually implement `Debug` for `ImportKind` because the `source/target_bindings`
120/// contain `Cell`s which can introduce infinite loops while printing.
121impl<'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                // Ignore the nested bindings to avoid an infinite loop while printing.
130                .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/// One import.
160#[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)]
161pub(crate) struct ImportData<'ra> {
162    pub kind: ImportKind<'ra>,
163
164    /// Node ID of the "root" use item -- this is always the same as `ImportKind`'s `id`
165    /// (if it exists) except in the case of "nested" use trees, in which case
166    /// it will be the ID of the root use tree. e.g., in the example
167    /// ```ignore (incomplete code)
168    /// use foo::bar::{a, b}
169    /// ```
170    /// this would be the ID of the `use foo::bar` `UseTree` node.
171    /// In case of imports without their own node ID it's the closest node that can be used,
172    /// for example, for reporting lints.
173    pub root_id: NodeId,
174
175    /// Span of the entire use statement.
176    pub use_span: Span,
177
178    /// Span of the entire use statement with attributes.
179    pub use_span_with_attributes: Span,
180
181    /// Did the use statement have any attributes?
182    pub has_attributes: bool,
183
184    /// Span of this use tree.
185    pub span: Span,
186
187    /// Span of the *root* use tree (see `root_id`).
188    pub root_span: Span,
189
190    pub parent_scope: ParentScope<'ra>,
191    pub module_path: Vec<Segment>,
192    /// The resolution of `module_path`:
193    ///
194    /// | `module_path` | `imported_module` | remark |
195    /// |-|-|-|
196    /// |`use prefix::foo`| `ModuleOrUniformRoot::Module(prefix)`         | - |
197    /// |`use ::foo`      | `ModuleOrUniformRoot::ExternPrelude`          | 2018+ editions |
198    /// |`use ::foo`      | `ModuleOrUniformRoot::ModuleAndExternPrelude` | a special case in 2015 edition |
199    /// |`use foo`        | `ModuleOrUniformRoot::CurrentScope`           | - |
200    pub imported_module: CmCell<Option<ModuleOrUniformRoot<'ra>>>,
201    pub vis: Visibility,
202
203    /// Span of the visibility.
204    pub vis_span: Span,
205
206    /// A `#[diagnostic::on_unknown]` attribute applied
207    /// to the given import. This allows crates to specify
208    /// custom error messages for a specific import
209    ///
210    /// This is `None` if the feature flag for `diagnostic::on_unknown` is disabled.
211    pub on_unknown_attr: Option<OnUnknownData>,
212}
213
214/// `Interned` is used because values of this type have "identity" and compare as unequal even if
215/// they have the same contents.
216pub(crate) type Import<'ra> = Interned<'ra, ImportData<'ra>>;
217
218impl<'ra> ImportData<'ra> {
219    pub(crate) fn is_glob(&self) -> bool {
220        #[allow(non_exhaustive_omitted_patterns)] match self.kind {
    ImportKind::Glob { .. } => true,
    _ => false,
}matches!(self.kind, ImportKind::Glob { .. })
221    }
222
223    pub(crate) fn is_nested(&self) -> bool {
224        match self.kind {
225            ImportKind::Single { nested, .. } => nested,
226            _ => false,
227        }
228    }
229
230    pub(crate) fn id(&self) -> Option<NodeId> {
231        match self.kind {
232            ImportKind::Single { id, .. }
233            | ImportKind::Glob { id, .. }
234            | ImportKind::ExternCrate { id, .. } => Some(id),
235            ImportKind::MacroUse { .. } | ImportKind::MacroExport => None,
236        }
237    }
238
239    pub(crate) fn def_id(&self) -> Option<LocalDefId> {
240        match self.kind {
241            ImportKind::Single { def_id, .. }
242            | ImportKind::Glob { def_id, .. }
243            | ImportKind::ExternCrate { def_id, .. } => Some(def_id),
244            ImportKind::MacroUse { .. } | ImportKind::MacroExport => None,
245        }
246    }
247
248    pub(crate) fn simplify(&self) -> Reexport {
249        match self.kind {
250            ImportKind::Single { def_id, .. } => Reexport::Single(def_id.to_def_id()),
251            ImportKind::Glob { def_id, .. } => Reexport::Glob(def_id.to_def_id()),
252            ImportKind::ExternCrate { def_id, .. } => Reexport::ExternCrate(def_id.to_def_id()),
253            ImportKind::MacroUse { .. } => Reexport::MacroUse,
254            ImportKind::MacroExport => Reexport::MacroExport,
255        }
256    }
257
258    fn summary(&self) -> ImportSummary {
259        ImportSummary {
260            vis: self.vis,
261            nearest_parent_mod: self.parent_scope.module.nearest_parent_mod().expect_local(),
262            is_single: #[allow(non_exhaustive_omitted_patterns)] match self.kind {
    ImportKind::Single { .. } => true,
    _ => false,
}matches!(self.kind, ImportKind::Single { .. }),
263            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 }),
264            span: self.span,
265        }
266    }
267}
268
269/// Records information about the resolution of a name in a namespace of a module.
270#[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)]
271pub(crate) struct NameResolution<'ra> {
272    /// Single imports that may define the name in the namespace.
273    /// Imports are arena-allocated, so it's ok to use pointers as keys.
274    pub single_imports: FxIndexSet<Import<'ra>>,
275    /// The non-glob declaration for this name, if it is known to exist.
276    pub non_glob_decl: Option<Decl<'ra>> = None,
277    /// The glob declaration for this name, if it is known to exist.
278    pub glob_decl: Option<Decl<'ra>> = None,
279    pub orig_ident_span: Span,
280}
281
282/// `Interned` is used because values of this type have "identity" and compare as unequal even if
283/// they have the same contents.
284pub(crate) type NameResolutionRef<'ra> = Interned<'ra, CmRefCell<NameResolution<'ra>>>;
285
286impl<'ra> NameResolution<'ra> {
287    pub(crate) fn new(orig_ident_span: Span) -> Self {
288        NameResolution { single_imports: FxIndexSet::default(), orig_ident_span, .. }
289    }
290
291    /// Returns the best declaration if it is not going to change, and `None` if the best
292    /// declaration may still change to something else.
293    /// FIXME: this function considers `single_imports`, but not `unexpanded_invocations`, so
294    /// the returned declaration may actually change after expanding macros in the same module,
295    /// because of this fact we have glob overwriting (`select_glob_decl`). Consider using
296    /// `unexpanded_invocations` here and avoiding glob overwriting entirely, if it doesn't cause
297    /// code breakage in practice.
298    /// FIXME: relationship between this function and similar `DeclData::determined` is unclear.
299    pub(crate) fn determined_decl(&self) -> Option<Decl<'ra>> {
300        if self.non_glob_decl.is_some() {
301            self.non_glob_decl
302        } else if self.glob_decl.is_some() && self.single_imports.is_empty() {
303            self.glob_decl
304        } else {
305            None
306        }
307    }
308
309    pub(crate) fn best_decl(&self) -> Option<Decl<'ra>> {
310        self.non_glob_decl.or(self.glob_decl)
311    }
312}
313
314// module to keep the TLS private and only accessible through the function `enter_cycle_detector`.
315pub(crate) mod cycle_detection {
316    use std::cell::RefCell;
317    use std::ptr;
318
319    use crate::{BindingKey, LocalModule};
320
321    #[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!(
322        /// During import resolution, recursive imports can form cycles.
323        /// This set stores the active resolution stack for the current thread.
324        /// By keeping track of the module and `BindingKey` pair that identifies
325        /// the specific resolution.
326        ///
327        /// The pointer is the interned address of a `Interned<'ra, ModuleData>` allocated
328        /// in the `Resolver Arenas` (lifetime `'ra`), it is thus stable and allows casting
329        /// to a `*const ()` for comparison. This is done because we can't use lifetimes
330        /// other than `'static` in thread local storage.
331        static ACTIVE_RESOLUTIONS: RefCell<Vec<(*const (), BindingKey)>> = Default::default();
332    );
333
334    pub(crate) struct ActiveResolutionGuard {
335        key: (*const (), BindingKey),
336    }
337
338    impl Drop for ActiveResolutionGuard {
339        fn drop(&mut self) {
340            ACTIVE_RESOLUTIONS.with_borrow_mut(|ar| {
341                // Only this guard is allowed to remove this key.
342                if !(Some(self.key) == ar.pop()) {
    {
        ::core::panicking::panic_fmt(format_args!("This guard should be the only one removing this key"));
    }
};assert!(
343                    Some(self.key) == ar.pop(),
344                    "This guard should be the only one removing this key"
345                );
346            });
347        }
348    }
349
350    /// Returns `Err(())` if a cycle is detected, otherwise this returns a
351    /// guard that will remove the resolution when dropped.
352    pub(crate) fn enter_cycle_detector<'ra>(
353        module: LocalModule<'ra>,
354        binding_key: BindingKey,
355    ) -> Result<ActiveResolutionGuard, ()> {
356        let module_key = ptr::from_ref(module.0.0).cast();
357        let key = (module_key, binding_key);
358        ACTIVE_RESOLUTIONS.with_borrow_mut(|ar| {
359            if ar.contains(&key) {
360                return Err(());
361            }
362            ar.push(key);
363            Ok(ActiveResolutionGuard { key })
364        })
365    }
366}
367
368/// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
369/// import errors within the same use tree into a single diagnostic.
370#[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)]
371pub(crate) struct UnresolvedImportError {
372    pub(crate) span: Span,
373    pub(crate) label: Option<String>,
374    pub(crate) note: Option<String>,
375    pub(crate) suggestion: Option<Suggestion>,
376    pub(crate) help: Option<String>,
377    pub(crate) candidates: Option<Vec<ImportSuggestion>>,
378    pub(crate) segment: Option<Ident>,
379    /// comes from `PathRes::Failed { module }`
380    pub(crate) module: Option<DefId>,
381    pub(crate) on_unknown_attr: Option<OnUnknownData>,
382}
383
384// Reexports of the form `pub use foo as bar;` where `foo` is `extern crate foo;`
385// are permitted for backward-compatibility under a deprecation lint.
386fn pub_use_of_private_extern_crate_hack(
387    import: ImportSummary,
388    decl: Decl<'_>,
389) -> Option<LocalDefId> {
390    match (import.is_single, &decl.kind) {
391        (true, DeclKind::Import { import: decl_import, .. })
392            if let ImportKind::ExternCrate { def_id, .. } = decl_import.kind
393                && import.vis.is_public() =>
394        {
395            Some(def_id)
396        }
397        _ => None,
398    }
399}
400
401/// Removes identical import layers from two declarations.
402fn remove_same_import<'ra>(d1: Decl<'ra>, d2: Decl<'ra>) -> (Decl<'ra>, Decl<'ra>) {
403    if let DeclKind::Import { import: import1, source_decl: d1_next } = d1.kind
404        && let DeclKind::Import { import: import2, source_decl: d2_next } = d2.kind
405        && import1 == import2
406    {
407        {
    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);
408        {
    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);
409        if d1.ambiguity.get() != d2.ambiguity.get() {
410            if !d1.ambiguity.get().is_some() {
    ::core::panicking::panic("assertion failed: d1.ambiguity.get().is_some()")
};assert!(d1.ambiguity.get().is_some());
411        }
412        // Visibility of the new import declaration may be different,
413        // because it already incorporates the visibility of the source binding.
414        remove_same_import(d1_next, d2_next)
415    } else {
416        (d1, d2)
417    }
418}
419
420impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
421    pub(crate) fn import_decl_vis(&self, decl: Decl<'ra>, import: ImportSummary) -> Visibility {
422        self.import_decl_vis_ext(decl, import, false)
423    }
424
425    pub(crate) fn import_decl_vis_ext(
426        &self,
427        decl: Decl<'ra>,
428        import: ImportSummary,
429        min: bool,
430    ) -> Visibility {
431        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));
432        let decl_vis = if min { decl.min_vis() } else { decl.vis() };
433        let ord = decl_vis.partial_cmp(import.vis, self.tcx);
434        let extern_crate_hack = pub_use_of_private_extern_crate_hack(import, decl).is_some();
435        if ord == Some(Ordering::Less)
436            && decl_vis.is_accessible_from(import.nearest_parent_mod, self.tcx)
437            && !extern_crate_hack
438        {
439            // Imported declaration is less visible than the import, but is still visible
440            // from the current module, use the declaration's visibility.
441            decl_vis.expect_local()
442        } else {
443            // Good case - imported declaration is more visible than the import, or the same,
444            // use the import's visibility.
445            //
446            // Bad case - imported declaration is too private for the current module.
447            // It doesn't matter what visibility we choose here (except in the `PRIVATE_MACRO_USE`
448            // and `PUB_USE_OF_PRIVATE_EXTERN_CRATE` cases), because an error will be reported.
449            // Use import visibility to keep the all declaration visibilities in a module ordered.
450            if !min
451                && #[allow(non_exhaustive_omitted_patterns)] match ord {
    None | Some(Ordering::Less) => true,
    _ => false,
}matches!(ord, None | Some(Ordering::Less))
452                && !extern_crate_hack
453                && !import.priv_macro_use
454            {
455                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);
456                self.dcx().span_delayed_bug(import.span, msg);
457            }
458            import.vis
459        }
460    }
461
462    /// Given an import and the declaration that it points to,
463    /// create the corresponding import declaration.
464    pub(crate) fn new_import_decl(&self, decl: Decl<'ra>, import: Import<'ra>) -> Decl<'ra> {
465        let vis = self.import_decl_vis(decl, import.summary());
466
467        if let ImportKind::Glob { ref max_vis, .. } = import.kind
468            && (vis == import.vis
469                || max_vis.get().is_none_or(|max_vis| vis.greater_than(max_vis, self.tcx)))
470        {
471            // `set` can't fail because this can only happen during "write_import_resolutions"
472            max_vis.set_checked(Some(vis), self)
473        }
474
475        self.arenas.alloc_decl(DeclData {
476            kind: DeclKind::Import { source_decl: decl, import },
477            ambiguity: CmCell::new(None),
478            span: import.span,
479            initial_vis: vis.to_mod_id(),
480            ambiguity_vis_max: CmCell::new(None),
481            ambiguity_vis_min: CmCell::new(None),
482            expansion: import.parent_scope.expansion,
483            parent_module: Some(import.parent_scope.module),
484        })
485    }
486
487    fn is_noise_0_7_0(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> bool {
488        let DeclKind::Import { import: i1, .. } = glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
489        let DeclKind::Import { import: i2, .. } = old_glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
490        let [seg1, seg2] = &i1.module_path[..] else { return false };
491        if seg1.ident.name != kw::SelfLower || seg2.ident.name.as_str() != "perlin_surflet" {
492            return false;
493        }
494        let [seg1, seg2] = &i2.module_path[..] else { return false };
495        if seg1.ident.name != kw::SelfLower || seg2.ident.name.as_str() != "perlin" {
496            return false;
497        }
498        let Some(def_id1) = glob_decl.res().opt_def_id() else { return false };
499        let Some(def_id2) = old_glob_decl.res().opt_def_id() else { return false };
500        self.def_path_str(def_id1).ends_with("noise_fns::generators::perlin_surflet::Perlin")
501            && self.def_path_str(def_id2).ends_with("noise_fns::generators::perlin::Perlin")
502    }
503
504    fn is_rustybuzz_0_4_0(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> bool {
505        let DeclKind::Import { import: i1, .. } = glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
506        let DeclKind::Import { import: i2, .. } = old_glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
507        let [seg1, seg2] = &i1.module_path[..] else { return false };
508        if seg1.ident.name != kw::Super || seg2.ident.name.as_str() != "gsubgpos" {
509            return false;
510        }
511        let [seg1] = &i2.module_path[..] else { return false };
512        if seg1.ident.name != kw::Super {
513            return false;
514        }
515        let Some(def_id1) = glob_decl.res().opt_def_id() else { return false };
516        let Some(def_id2) = old_glob_decl.res().opt_def_id() else { return false };
517        self.def_path_str(def_id1).ends_with("tables::gsubgpos::Class")
518            && self.def_path_str(def_id2).ends_with("ggg::Class")
519    }
520
521    fn is_pdf_0_9_0(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> bool {
522        let DeclKind::Import { import: i1, .. } = glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
523        let DeclKind::Import { import: i2, .. } = old_glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
524        let [seg1, seg2] = &i1.module_path[..] else { return false };
525        if seg1.ident.name != kw::Crate || seg2.ident.name.as_str() != "content" {
526            return false;
527        }
528        let [seg1, seg2] = &i2.module_path[..] else { return false };
529        if seg1.ident.name != kw::Crate || seg2.ident.name.as_str() != "object" {
530            return false;
531        }
532        let Some(def_id1) = glob_decl.res().opt_def_id() else { return false };
533        let Some(def_id2) = old_glob_decl.res().opt_def_id() else { return false };
534        self.def_path_str(def_id1).ends_with("crate::content::Rect")
535            && self.def_path_str(def_id2).ends_with("crate::object::types::Rect")
536    }
537
538    fn is_net2_0_2_39(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> bool {
539        let DeclKind::Import { import: i1, .. } = glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
540        let DeclKind::Import { import: i2, .. } = old_glob_decl.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
541        let [seg1, seg2, seg3, seg4] = &i1.module_path[..] else { return false };
542        if seg1.ident.name != kw::PathRoot
543            || seg2.ident.name.as_str() != "winapi"
544            || seg3.ident.name.as_str() != "shared"
545            || seg4.ident.name.as_str() != "ws2def"
546        {
547            return false;
548        }
549        let [seg1, seg2, seg3, seg4] = &i2.module_path[..] else { return false };
550        if seg1.ident.name != kw::PathRoot
551            || seg2.ident.name.as_str() != "winapi"
552            || seg3.ident.name.as_str() != "um"
553            || seg4.ident.name.as_str() != "winsock2"
554        {
555            return false;
556        }
557        let Some(def_id1) = glob_decl.res().opt_def_id() else { return false };
558        let Some(def_id2) = old_glob_decl.res().opt_def_id() else { return false };
559        self.def_path_str(def_id1).starts_with("winapi::shared::ws2def::")
560            && self.def_path_str(def_id2).starts_with("winapi::um::winsock2::")
561    }
562
563    /// If `glob_decl` attempts to overwrite `old_glob_decl` in a module,
564    /// decide which one to keep.
565    fn select_glob_decl(&self, old_glob_decl: Decl<'ra>, glob_decl: Decl<'ra>) -> Decl<'ra> {
566        if !glob_decl.is_glob_import() {
    ::core::panicking::panic("assertion failed: glob_decl.is_glob_import()")
};assert!(glob_decl.is_glob_import());
567        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());
568        {
    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);
569        // `best_decl` with a given key in a module may be overwritten in a
570        // number of cases (all of them can be seen below in the `match` in `try_define_local`),
571        // all these overwrites will be re-fetched by glob imports importing
572        // from that module without generating new ambiguities.
573        // - A glob decl is overwritten by a non-glob decl arriving later.
574        // - A glob decl is overwritten by a glob decl re-fetching an
575        //   overwritten decl from other module (the recursive case).
576        // Here we are detecting all such re-fetches and overwrite old decls
577        // with the re-fetched decls.
578        // This is probably incorrect in corner cases, and the outdated decls still get
579        // propagated to other places and get stuck there, but that's what we have at the moment.
580        let (old_deep_decl, deep_decl) = remove_same_import(old_glob_decl, glob_decl);
581        if deep_decl != glob_decl {
582            // Some import layers have been removed, need to overwrite.
583            {
    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);
584            if !!deep_decl.is_glob_import() {
    ::core::panicking::panic("assertion failed: !deep_decl.is_glob_import()")
};assert!(!deep_decl.is_glob_import());
585            if let Some((old_ambig, _)) = old_glob_decl.ambiguity.get()
586                && glob_decl.ambiguity.get().is_none()
587            {
588                // Do not lose glob ambiguities when re-fetching the glob.
589                glob_decl.ambiguity.set_checked(Some((old_ambig, true)), self);
590            }
591            glob_decl
592        } else if glob_decl.res() != old_glob_decl.res() {
593            let warning = self.is_noise_0_7_0(old_glob_decl, glob_decl)
594                || self.is_rustybuzz_0_4_0(old_glob_decl, glob_decl)
595                || self.is_pdf_0_9_0(old_glob_decl, glob_decl)
596                || self.is_net2_0_2_39(old_glob_decl, glob_decl);
597            old_glob_decl.ambiguity.set_checked(Some((glob_decl, warning)), self);
598            old_glob_decl
599        } else if let old_vis = old_glob_decl.vis()
600            && let vis = glob_decl.vis()
601            && old_vis != vis
602        {
603            // We are glob-importing the same item but with a different visibility.
604            // All visibilities here are ordered because all of them are ancestors of `module`.
605            if vis.greater_than(old_vis, self.tcx) {
606                old_glob_decl.ambiguity_vis_max.set_checked(Some(glob_decl), self);
607            } else if let old_min_vis = old_glob_decl.min_vis()
608                && old_min_vis != vis
609                && old_min_vis.greater_than(vis, self.tcx)
610            {
611                old_glob_decl.ambiguity_vis_min.set_checked(Some(glob_decl), self);
612            }
613            old_glob_decl
614        } else if glob_decl.is_ambiguity_recursive() && !old_glob_decl.is_ambiguity_recursive() {
615            // Overwriting a non-ambiguous glob import with an ambiguous glob import.
616            old_glob_decl.ambiguity.set_checked(Some((glob_decl, true)), self);
617            old_glob_decl
618        } else {
619            old_glob_decl
620        }
621    }
622
623    /// Attempt to put the declaration with the given name and namespace into the module,
624    /// and return existing declaration if there is a collision.
625    pub(crate) fn try_plant_decl_into_local_module(
626        &mut self,
627        ident: IdentKey,
628        orig_ident_span: Span,
629        ns: Namespace,
630        decl: Decl<'ra>,
631    ) -> Result<(), Decl<'ra>> {
632        if !decl.ambiguity.get().is_none() {
    ::core::panicking::panic("assertion failed: decl.ambiguity.get().is_none()")
};assert!(decl.ambiguity.get().is_none());
633        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());
634        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());
635        let module = decl.parent_module.unwrap().expect_local();
636        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()));
637        let res = decl.res();
638        self.check_reserved_macro_name(ident.name, orig_ident_span, res);
639        // Even if underscore names cannot be looked up, we still need to add them to modules,
640        // because they can be fetched by glob imports from those modules, and bring traits
641        // into scope both directly and through glob imports.
642        let key = BindingKey::new_disambiguated(ident, ns, || {
643            module.underscore_disambiguator.update(self, |d| d + 1);
644            module.underscore_disambiguator.get()
645        });
646        self.update_local_resolution(module, key, orig_ident_span, |this, resolution| {
647            if res == Res::Err
648                && let Some(old_decl) = resolution.best_decl()
649                && old_decl.res() != Res::Err
650            {
651                // Do not override real declarations with `Res::Err`s from error recovery.
652                // FIXME: this special case shouldn't be necessary, but removing it triggers an ICE
653                // due to some other issues (#157406, tests/ui/imports/dummy-import-ice.rs).
654                return Ok(());
655            }
656            if decl.is_glob_import() {
657                resolution.glob_decl = Some(match resolution.glob_decl {
658                    Some(old_decl) => this.select_glob_decl(old_decl, decl),
659                    None => decl,
660                });
661            } else {
662                resolution.non_glob_decl = Some(match resolution.non_glob_decl {
663                    Some(old_decl) => return Err(old_decl),
664                    None => decl,
665                })
666            }
667
668            Ok(())
669        })
670    }
671
672    // Use `f` to mutate the resolution of the name in the module.
673    // If the resolution becomes a success, define it in the module's glob importers.
674    fn update_local_resolution<T, F>(
675        &mut self,
676        module: LocalModule<'ra>,
677        key: BindingKey,
678        orig_ident_span: Span,
679        f: F,
680    ) -> T
681    where
682        F: FnOnce(&Resolver<'ra, 'tcx>, &mut NameResolution<'ra>) -> T,
683    {
684        // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
685        // during which the resolution might end up getting re-defined via a glob cycle.
686        let (binding, t) = {
687            let resolution = &mut *self
688                .resolution_or_default(module.to_module(), key, orig_ident_span)
689                .0
690                .borrow_mut(self);
691            let old_decl = resolution.determined_decl();
692            let old_vis = old_decl.map(|d| d.vis());
693
694            let t = f(self, resolution);
695
696            if let Some(binding) = resolution.determined_decl()
697                && (old_decl != Some(binding) || old_vis != Some(binding.vis()))
698            {
699                (binding, t)
700            } else {
701                return t;
702            }
703        };
704
705        let Ok(glob_importers) = module.glob_importers.try_borrow_mut(self) else {
706            return t;
707        };
708
709        // Define or update `binding` in `module`s glob importers.
710        for import in glob_importers.iter() {
711            let mut ident = key.ident;
712            let scope = match ident
713                .ctxt
714                .update_unchecked(|ctxt| ctxt.reverse_glob_adjust(module.expansion, import.span))
715            {
716                Some(Some(def)) => self.expn_def_scope(def),
717                Some(None) => import.parent_scope.module,
718                None => continue,
719            };
720            if self.is_accessible_from(binding.vis(), scope) {
721                let import_decl = self.new_import_decl(binding, *import);
722                self.try_plant_decl_into_local_module(ident, orig_ident_span, key.ns, import_decl)
723                    .expect("planting a glob cannot fail");
724            }
725        }
726
727        t
728    }
729
730    // Define a dummy resolution containing a `Res::Err` as a placeholder for a failed
731    // or indeterminate resolution, also mark such failed imports as used to avoid duplicate diagnostics.
732    fn import_dummy_binding(&mut self, import: Import<'ra>, is_indeterminate: bool) {
733        if let ImportKind::Single { target, ref decls, .. } = import.kind {
734            if !(is_indeterminate || decls.iter().all(|d| d.get().decl().is_none())) {
735                return; // Has resolution, do not create the dummy binding
736            }
737            let dummy_decl = self.dummy_decl;
738            let dummy_decl = self.new_import_decl(dummy_decl, import);
739            self.per_ns_mut(|this, ns| {
740                let ident = IdentKey::new(target);
741                // This can fail, dummies are inserted only in non-occupied slots.
742                let _ = this.try_plant_decl_into_local_module(ident, target.span, ns, dummy_decl);
743                // Don't remove underscores from `single_imports`, they were never added.
744                if target.name != kw::Underscore {
745                    let key = BindingKey::new(ident, ns);
746                    this.update_local_resolution(
747                        import.parent_scope.module.expect_local(),
748                        key,
749                        target.span,
750                        |_, resolution| {
751                            resolution.single_imports.swap_remove(&import);
752                        },
753                    )
754                }
755            });
756            self.record_use(target, dummy_decl, Used::Other);
757        } else if import.imported_module.get().is_none() {
758            self.import_use_map.insert(import, Used::Other);
759            if let Some(id) = import.id() {
760                self.used_imports.insert(id);
761            }
762        }
763    }
764
765    // Import resolution
766    //
767    // This is a batched fixed-point algorithm. Each import is resolved in
768    // isolation, with any resolutions collected for later.
769    // After a full pass over the current set of `indeterminate_imports`,
770    // the collected resolutions are committed together. The process
771    // repeats until either no imports remain or no further progress can
772    // be made.
773
774    /// Resolves all imports for the crate. This method performs the fixed-
775    /// point iteration.
776    pub(crate) fn resolve_imports(&mut self) {
777        let mut prev_indeterminate_count = usize::MAX;
778        let mut indeterminate_count = self.indeterminate_imports.len() * 3;
779        while indeterminate_count < prev_indeterminate_count {
780            prev_indeterminate_count = indeterminate_count;
781            indeterminate_count = 0;
782
783            let mut imports_to_resolve = mem::take(&mut self.indeterminate_imports);
784
785            // SAFETY: This is a "top-level" function used by the macro expansion code, unless some
786            // weird thing is done, all `tracked` borrows done in the previous call of
787            // `resolve_imports` are dropped when that call ended.
788            unsafe { self.speculative_flag.set(true) };
789            rustc_data_structures::sync::par_for_each_slice(
790                &mut imports_to_resolve,
791                |(import, resolution, indeterminate_count)| {
792                    (*resolution, *indeterminate_count) = self.resolve_import(*import);
793                },
794            );
795            // SAFETY: All `untracked` borrows are dropped after the `par_for_each_slice` call,
796            // as they cannot escape since they are tied to the `CmRefCell` they borrowed from.
797            //
798            // Note: Some `CmRefCell`s are arena allocated and thus have the `'ra` lifetime,
799            // allowing these borrows to escape, but that does not and should not happen.
800            unsafe { self.speculative_flag.set(false) };
801
802            self.write_import_resolutions(&imports_to_resolve);
803
804            self.indeterminate_imports = imports_to_resolve
805                .extract_if(.., |(_, _, count)| {
806                    indeterminate_count += *count;
807                    *count > 0
808                })
809                .collect();
810            self.determined_imports.extend(imports_to_resolve.into_iter().map(|(i, _, _)| i));
811        }
812    }
813
814    fn write_import_resolutions(
815        &mut self,
816        import_resolutions: &[(Import<'ra>, Option<ImportResolution<'ra>>, usize)],
817    ) {
818        for &(import, ref resolution, _) in import_resolutions {
819            let Some(ImportResolution { imported_module, .. }) = resolution else {
820                continue;
821            };
822            import.imported_module.set(Some(*imported_module), self);
823
824            if import.is_glob()
825                && let ModuleOrUniformRoot::Module(module) = imported_module
826                && import.parent_scope.module != *module
827                && module.is_local()
828            {
829                module.glob_importers.borrow_mut(self).push(import);
830            }
831        }
832
833        for &(import, ref resolution, _) in import_resolutions {
834            let Some(ImportResolution { imported_module, kind: resolution_kind }) = resolution
835            else {
836                continue;
837            };
838
839            match (&import.kind, resolution_kind) {
840                (
841                    ImportKind::Single { target, decls, .. },
842                    ImportResolutionKind::Single(import_decls),
843                ) => {
844                    self.per_ns_mut(|this, ns| {
845                        match import_decls[ns] {
846                            PendingDecl::Ready(Some(decl)) => {
847                                // We need the `target`, `source` can be extracted.
848                                let import_decl = this.new_import_decl(decl, import);
849                                if import_decl.is_assoc_item()
850                                    && !this.features.import_trait_associated_functions()
851                                {
852                                    feature_err(
853                                        this.tcx.sess,
854                                        sym::import_trait_associated_functions,
855                                        import.span,
856                                        "`use` associated items of traits is unstable",
857                                    )
858                                    .emit();
859                                }
860                                this.plant_decl_into_local_module(
861                                    IdentKey::new(*target),
862                                    target.span,
863                                    ns,
864                                    import_decl,
865                                );
866                                decls[ns].set(PendingDecl::Ready(Some(import_decl)), this);
867                            }
868                            PendingDecl::Ready(None) => {
869                                // Don't remove underscores from `single_imports`, they were never added.
870                                if target.name != kw::Underscore {
871                                    let key = BindingKey::new(IdentKey::new(*target), ns);
872                                    this.update_local_resolution(
873                                        import.parent_scope.module.expect_local(),
874                                        key,
875                                        target.span,
876                                        |_, resolution| {
877                                            resolution.single_imports.swap_remove(&import);
878                                        },
879                                    );
880                                }
881                                decls[ns].set(PendingDecl::Ready(None), this);
882                            }
883                            PendingDecl::Pending => {}
884                        }
885                    });
886                }
887                (ImportKind::Glob { id, .. }, ImportResolutionKind::Glob(imported_decls)) => {
888                    let ModuleOrUniformRoot::Module(module) = imported_module else {
889                        self.dcx().emit_err(CannotGlobImportAllCrates { span: import.span });
890                        continue;
891                    };
892
893                    if module.is_trait() && !self.features.import_trait_associated_functions() {
894                        feature_err(
895                            self.tcx.sess,
896                            sym::import_trait_associated_functions,
897                            import.span,
898                            "`use` associated items of traits is unstable",
899                        )
900                        .emit();
901                    }
902
903                    for (binding, key, orig_ident_span) in imported_decls {
904                        let import_decl = self.new_import_decl(*binding, import);
905                        let _ = self
906                            .try_plant_decl_into_local_module(
907                                key.ident,
908                                *orig_ident_span,
909                                key.ns,
910                                import_decl,
911                            )
912                            .expect("planting a glob cannot fail");
913                    }
914
915                    self.record_partial_res(*id, PartialRes::new(module.res().unwrap()));
916                }
917
918                // Something weird happened, which shouldn't have happened.
919                _ => {
    ::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"),
920            }
921        }
922    }
923
924    pub(crate) fn finalize_imports(&mut self) {
925        let mut module_children = Default::default();
926        let mut ambig_module_children = Default::default();
927        for module in &self.local_modules {
928            self.finalize_resolutions_in(*module, &mut module_children, &mut ambig_module_children);
929        }
930        self.module_children = module_children;
931        self.ambig_module_children = ambig_module_children;
932
933        let mut seen_spans = FxHashSet::default();
934        let mut errors = ::alloc::vec::Vec::new()vec![];
935        let mut prev_root_id: NodeId = NodeId::ZERO;
936        let determined_imports = mem::take(&mut self.determined_imports);
937        let indeterminate_imports = mem::take(&mut self.indeterminate_imports);
938
939        let mut glob_error = false;
940        for (is_indeterminate, import) in determined_imports
941            .iter()
942            .map(|i| (false, i))
943            .chain(indeterminate_imports.iter().map(|(i, _, _)| (true, i)))
944        {
945            let unresolved_import_error = self.finalize_import(*import);
946            // If this import is unresolved then create a dummy import
947            // resolution for it so that later resolve stages won't complain.
948            self.import_dummy_binding(*import, is_indeterminate);
949
950            let Some(err) = unresolved_import_error else { continue };
951
952            glob_error |= import.is_glob();
953
954            if let ImportKind::Single { source, ref decls, .. } = import.kind
955                && source.name == kw::SelfLower
956                // Silence `unresolved import` error if E0429 is already emitted
957                && let PendingDecl::Ready(None) = decls.value_ns.get()
958            {
959                continue;
960            }
961
962            if prev_root_id != NodeId::ZERO && prev_root_id != import.root_id && !errors.is_empty()
963            {
964                // In the case of a new import line, throw a diagnostic message
965                // for the previous line.
966                self.throw_unresolved_import_error(errors, glob_error);
967                errors = ::alloc::vec::Vec::new()vec![];
968            }
969            if seen_spans.insert(err.span) {
970                errors.push((*import, err));
971                prev_root_id = import.root_id;
972            }
973        }
974
975        if self.cstore().had_extern_crate_load_failure() {
976            self.tcx.sess.dcx().abort_if_errors();
977        }
978
979        if !errors.is_empty() {
980            self.throw_unresolved_import_error(errors, glob_error);
981            return;
982        }
983
984        for (import, _, _) in &indeterminate_imports {
985            let path = import_path_to_string(
986                &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
987                &import.kind,
988                import.span,
989            );
990            // FIXME: there should be a better way of doing this than
991            // formatting this as a string then checking for `::`
992            if path.contains("::") {
993                let err = UnresolvedImportError {
994                    span: import.span,
995                    label: None,
996                    note: None,
997                    suggestion: None,
998                    help: None,
999                    candidates: None,
1000                    segment: None,
1001                    module: None,
1002                    on_unknown_attr: import.on_unknown_attr.clone(),
1003                };
1004                errors.push((*import, err))
1005            }
1006        }
1007
1008        if !errors.is_empty() {
1009            self.throw_unresolved_import_error(errors, glob_error);
1010        }
1011    }
1012
1013    pub(crate) fn lint_reexports(&mut self, exported_ambiguities: FxHashSet<Decl<'ra>>) {
1014        for module in &self.local_modules {
1015            for (key, resolution) in self.resolutions(module.to_module()).iter() {
1016                let resolution = resolution.borrow_checked(self);
1017                let Some(binding) = resolution.best_decl() else { continue };
1018
1019                // Report "cannot reexport" errors for exotic cases involving macros 2.0
1020                // privacy bending or invariant-breaking code under deprecation lints.
1021                for decl in [resolution.non_glob_decl, resolution.glob_decl] {
1022                    if let Some(decl) = decl
1023                        && let DeclKind::Import { source_decl, import } = decl.kind
1024                        // FIXME: Do not check visibility-ambiguous imports for now. To check them
1025                        // properly we need to preserve all imports in ambiguous glob sets and
1026                        // check them all individually.
1027                        && decl.ambiguity_vis_max.get().is_none()
1028                    {
1029                        // The source entity is too private to be reexported
1030                        // with the given import declaration's visibility.
1031                        let ord = source_decl.vis().partial_cmp(decl.vis(), self.tcx);
1032                        if #[allow(non_exhaustive_omitted_patterns)] match ord {
    None | Some(Ordering::Less) => true,
    _ => false,
}matches!(ord, None | Some(Ordering::Less)) {
1033                            let ident = match import.kind {
1034                                ImportKind::Single { source, .. } => source,
1035                                _ => key.ident.orig(resolution.orig_ident_span),
1036                            };
1037                            if let Some(lint) =
1038                                self.report_cannot_reexport(import, source_decl, ident, key.ns)
1039                            {
1040                                self.lint_buffer.add_early_lint(lint);
1041                            }
1042                        }
1043                    }
1044                }
1045
1046                if let DeclKind::Import { import, .. } = binding.kind
1047                    && let Some((amb_binding, _)) = binding.ambiguity.get()
1048                    && binding.res() != Res::Err
1049                    && exported_ambiguities.contains(&binding)
1050                {
1051                    self.lint_buffer.buffer_lint(
1052                        AMBIGUOUS_GLOB_REEXPORTS,
1053                        import.root_id,
1054                        import.root_span,
1055                        diagnostics::AmbiguousGlobReexports {
1056                            name: key.ident.name.to_string(),
1057                            namespace: key.ns.descr().to_string(),
1058                            first_reexport: import.root_span,
1059                            duplicate_reexport: amb_binding.span,
1060                        },
1061                    );
1062                }
1063
1064                if let Some(glob_decl) = resolution.glob_decl
1065                    && resolution.non_glob_decl.is_some()
1066                {
1067                    if binding.res() != Res::Err
1068                        && glob_decl.res() != Res::Err
1069                        && let DeclKind::Import { import: glob_import, .. } = glob_decl.kind
1070                        && let Some(glob_import_def_id) = glob_import.def_id()
1071                        && self.effective_visibilities.is_exported(glob_import_def_id)
1072                        && glob_decl.vis().is_public()
1073                        && !binding.vis().is_public()
1074                    {
1075                        let binding_id = match binding.kind {
1076                            DeclKind::Def(res) => {
1077                                Some(self.def_id_to_node_id(res.def_id().expect_local()))
1078                            }
1079                            DeclKind::Import { import, .. } => import.id(),
1080                        };
1081                        if let Some(binding_id) = binding_id {
1082                            self.lint_buffer.buffer_lint(
1083                                HIDDEN_GLOB_REEXPORTS,
1084                                binding_id,
1085                                binding.span,
1086                                diagnostics::HiddenGlobReexports {
1087                                    name: key.ident.name.to_string(),
1088                                    namespace: key.ns.descr().to_owned(),
1089                                    glob_reexport: glob_decl.span,
1090                                    private_item: binding.span,
1091                                },
1092                            );
1093                        }
1094                    }
1095                }
1096
1097                if let DeclKind::Import { import, .. } = binding.kind
1098                    && let Some(binding_id) = import.id()
1099                    && let import_def_id = import.def_id().unwrap()
1100                    && self.effective_visibilities.is_exported(import_def_id)
1101                    && let Res::Def(reexported_kind, reexported_def_id) = binding.res()
1102                    && !#[allow(non_exhaustive_omitted_patterns)] match reexported_kind {
    DefKind::Ctor(..) => true,
    _ => false,
}matches!(reexported_kind, DefKind::Ctor(..))
1103                    && !reexported_def_id.is_local()
1104                    && self.tcx.is_private_dep(reexported_def_id.krate)
1105                {
1106                    self.lint_buffer.buffer_lint(
1107                        EXPORTED_PRIVATE_DEPENDENCIES,
1108                        binding_id,
1109                        binding.span,
1110                        crate::diagnostics::ReexportPrivateDependency {
1111                            name: key.ident.name,
1112                            kind: binding.res().descr(),
1113                            krate: self.tcx.crate_name(reexported_def_id.krate),
1114                        },
1115                    );
1116                }
1117            }
1118        }
1119    }
1120
1121    /// Attempts to resolve the given import, returning:
1122    /// - `0` means its resolution is determined.
1123    /// - Other values mean that indeterminate exists under certain namespaces.
1124    ///
1125    /// Meanwhile, if resolution is successful, its result is returned.
1126    fn resolve_import(&self, import: Import<'ra>) -> (Option<ImportResolution<'ra>>, usize) {
1127        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_resolve/src/imports.rs:1127",
                        "rustc_resolve::imports", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_resolve/src/imports.rs"),
                        ::tracing_core::__macro_support::Option::Some(1127u32),
                        ::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!(
1128            "(resolving import for module) resolving import `{}::{}` in `{}`",
1129            Segment::names_to_string(&import.module_path),
1130            import_kind_to_string(&import.kind),
1131            module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
1132        );
1133        let module = if let Some(module) = import.imported_module.get() {
1134            module
1135        } else {
1136            let path_res = self.cm().maybe_resolve_path(
1137                &import.module_path,
1138                None,
1139                &import.parent_scope,
1140                Some(import),
1141            );
1142
1143            match path_res {
1144                PathResult::Module(module) => module,
1145                PathResult::Indeterminate => return (None, 3),
1146                PathResult::NonModule(..) | PathResult::Failed { .. } => return (None, 0),
1147            }
1148        };
1149
1150        let (source, bindings) = match import.kind {
1151            ImportKind::Single { source, ref decls, .. } => (source, decls),
1152            ImportKind::Glob { .. } => {
1153                let import_resolution = ImportResolution {
1154                    imported_module: module,
1155                    kind: self.resolve_glob_import(import, module),
1156                };
1157                return (Some(import_resolution), 0);
1158            }
1159            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1160        };
1161
1162        let mut decls = PerNS::default();
1163        let mut indeterminate_count = 0;
1164        self.per_ns(|this, ns| {
1165            if bindings[ns].get() != PendingDecl::Pending {
1166                return;
1167            };
1168            let binding_result = this.cm().maybe_resolve_ident_in_module(
1169                module,
1170                source,
1171                ns,
1172                &import.parent_scope,
1173                Some(import),
1174            );
1175            let pending_decl = match binding_result {
1176                Ok(binding) => PendingDecl::Ready(Some(binding)),
1177                Err(Determinacy::Determined) => PendingDecl::Ready(None),
1178                Err(Determinacy::Undetermined) => {
1179                    indeterminate_count += 1;
1180                    PendingDecl::Pending
1181                }
1182            };
1183            decls[ns] = pending_decl;
1184        });
1185        let import_resolution =
1186            ImportResolution { imported_module: module, kind: ImportResolutionKind::Single(decls) };
1187
1188        (Some(import_resolution), indeterminate_count)
1189    }
1190
1191    /// Performs final import resolution, consistency checks and error reporting.
1192    ///
1193    /// Optionally returns an unresolved import error. This error is buffered and used to
1194    /// consolidate multiple unresolved import errors into a single diagnostic.
1195    fn finalize_import(&mut self, import: Import<'ra>) -> Option<UnresolvedImportError> {
1196        let ignore_decl = match &import.kind {
1197            ImportKind::Single { decls, .. } => decls[TypeNS].get().decl(),
1198            _ => None,
1199        };
1200        let ambiguity_errors_len = |errors: &Vec<AmbiguityError<'_>>| {
1201            errors.iter().filter(|error| error.warning.is_none()).count()
1202        };
1203        let prev_ambiguity_errors_len = ambiguity_errors_len(&self.ambiguity_errors);
1204        let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
1205
1206        // We'll provide more context to the privacy errors later, up to `len`.
1207        let privacy_errors_len = self.privacy_errors.len();
1208
1209        let path_res = self.cm_mut().resolve_path(
1210            &import.module_path,
1211            None,
1212            &import.parent_scope,
1213            Some(finalize),
1214            ignore_decl,
1215            Some(import),
1216        );
1217
1218        let no_ambiguity =
1219            ambiguity_errors_len(&self.ambiguity_errors) == prev_ambiguity_errors_len;
1220
1221        let module = match path_res {
1222            PathResult::Module(module) => {
1223                // Consistency checks, analogous to `finalize_macro_resolutions`.
1224                if let Some(initial_module) = import.imported_module.get() {
1225                    if module != initial_module && no_ambiguity && !self.issue_145575_hack_applied {
1226                        ::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");
1227                    }
1228                } else if self.privacy_errors.is_empty() {
1229                    self.dcx()
1230                        .create_err(CannotDetermineImportResolution { span: import.span })
1231                        .emit();
1232                }
1233
1234                module
1235            }
1236            PathResult::Failed {
1237                is_error_from_last_segment: false,
1238                span,
1239                segment,
1240                label,
1241                suggestion,
1242                help,
1243                module,
1244                error_implied_by_parse_error: _,
1245                message,
1246                note: _,
1247            } => {
1248                if no_ambiguity {
1249                    if !self.issue_145575_hack_applied {
1250                        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());
1251                    }
1252                    self.report_error(
1253                        span,
1254                        ResolutionError::FailedToResolve {
1255                            segment: segment.name,
1256                            label,
1257                            suggestion,
1258                            help,
1259                            module,
1260                            message,
1261                        },
1262                    );
1263                }
1264                return None;
1265            }
1266            PathResult::Failed {
1267                is_error_from_last_segment: true,
1268                span,
1269                label,
1270                suggestion,
1271                help,
1272                module,
1273                segment,
1274                note,
1275                ..
1276            } => {
1277                if no_ambiguity {
1278                    if !self.issue_145575_hack_applied {
1279                        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());
1280                    }
1281                    let module = if let Some(ModuleOrUniformRoot::Module(m)) = module {
1282                        m.opt_def_id()
1283                    } else {
1284                        None
1285                    };
1286                    let err = match self
1287                        .make_path_suggestion(import.module_path.clone(), &import.parent_scope)
1288                    {
1289                        Some((suggestion, note)) => UnresolvedImportError {
1290                            span,
1291                            label: None,
1292                            note,
1293                            suggestion: Some((
1294                                ::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))],
1295                                String::from("a similar path exists"),
1296                                Applicability::MaybeIncorrect,
1297                            )),
1298                            help: None,
1299                            candidates: None,
1300                            segment: Some(segment),
1301                            module,
1302                            on_unknown_attr: import.on_unknown_attr.clone(),
1303                        },
1304                        None => UnresolvedImportError {
1305                            span,
1306                            label: Some(label),
1307                            note,
1308                            suggestion,
1309                            help,
1310                            candidates: None,
1311                            segment: Some(segment),
1312                            module,
1313                            on_unknown_attr: import.on_unknown_attr.clone(),
1314                        },
1315                    };
1316                    return Some(err);
1317                }
1318                return None;
1319            }
1320            PathResult::NonModule(partial_res) => {
1321                if no_ambiguity && partial_res.full_res() != Some(Res::Err) {
1322                    // Check if there are no ambiguities and the result is not dummy.
1323                    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());
1324                }
1325                // The error was already reported earlier.
1326                return None;
1327            }
1328            PathResult::Indeterminate => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1329        };
1330
1331        let (ident, target, bindings, import_id) = match import.kind {
1332            ImportKind::Single { source, target, ref decls, id, .. } => (source, target, decls, id),
1333            ImportKind::Glob { ref max_vis, id, def_id } => {
1334                if import.module_path.len() <= 1 {
1335                    // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1336                    // 2 segments, so the `resolve_path` above won't trigger it.
1337                    let mut full_path = import.module_path.clone();
1338                    full_path.push(Segment::from_ident(Ident::dummy()));
1339                    self.lint_if_path_starts_with_module(finalize, &full_path, None);
1340                }
1341
1342                if let ModuleOrUniformRoot::Module(module) = module
1343                    && module == import.parent_scope.module
1344                {
1345                    // Importing a module into itself is not allowed.
1346                    return Some(UnresolvedImportError {
1347                        span: import.span,
1348                        label: Some(String::from("cannot glob-import a module into itself")),
1349                        note: None,
1350                        suggestion: None,
1351                        help: None,
1352                        candidates: None,
1353                        segment: None,
1354                        module: None,
1355                        on_unknown_attr: None,
1356                    });
1357                }
1358                if let Some(max_vis) = max_vis.get()
1359                    && import.vis.greater_than(max_vis, self.tcx)
1360                {
1361                    self.lint_buffer.buffer_lint(
1362                        UNUSED_IMPORTS,
1363                        id,
1364                        import.span,
1365                        crate::diagnostics::RedundantImportVisibility {
1366                            span: import.span,
1367                            help: (),
1368                            max_vis: max_vis.to_string(def_id, self.tcx),
1369                            import_vis: import.vis.to_string(def_id, self.tcx),
1370                        },
1371                    );
1372                }
1373                return None;
1374            }
1375            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1376        };
1377
1378        if self.privacy_errors.len() != privacy_errors_len {
1379            // Get the Res for the last element, so that we can point to alternative ways of
1380            // importing it if available.
1381            let mut path = import.module_path.clone();
1382            path.push(Segment::from_ident(ident));
1383            if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self
1384                .cm_mut()
1385                .resolve_path(&path, None, &import.parent_scope, Some(finalize), ignore_decl, None)
1386            {
1387                let res = module.res().map(|r| (r, ident));
1388                for error in &mut self.privacy_errors[privacy_errors_len..] {
1389                    error.outermost_res = res;
1390                }
1391            } else {
1392                // The final item is not a module (e.g., a struct, function, or macro).
1393                // Resolve it directly in the parent module to get its Res, so
1394                // `report_privacy_error()` can search for public re-export paths.
1395                for ns in [TypeNS, ValueNS, MacroNS] {
1396                    if let Ok(binding) = self.cm().resolve_ident_in_module(
1397                        module,
1398                        ident,
1399                        ns,
1400                        &import.parent_scope,
1401                        None,
1402                        ignore_decl,
1403                        None,
1404                    ) {
1405                        let res = binding.res();
1406                        for error in &mut self.privacy_errors[privacy_errors_len..] {
1407                            error.outermost_res = Some((res, ident));
1408                        }
1409                        break;
1410                    }
1411                }
1412            }
1413        }
1414
1415        let mut all_ns_err = true;
1416        self.per_ns_mut(|this, ns| {
1417            let binding = this.cm_mut().resolve_ident_in_module(
1418                module,
1419                ident,
1420                ns,
1421                &import.parent_scope,
1422                Some(Finalize {
1423                    report_private: false,
1424                    import: Some(import.summary()),
1425                    ..finalize
1426                }),
1427                bindings[ns].get().decl(),
1428                Some(import),
1429            );
1430
1431            match binding {
1432                Ok(binding) => {
1433                    // Consistency checks, analogous to `finalize_macro_resolutions`.
1434                    let initial_res = bindings[ns].get().decl().map(|binding| {
1435                        let initial_binding = binding.import_source();
1436                        all_ns_err = false;
1437                        if target.name == kw::Underscore
1438                            && initial_binding.is_extern_crate()
1439                            && !initial_binding.is_import()
1440                        {
1441                            let used = if import.module_path.is_empty() {
1442                                Used::Scope
1443                            } else {
1444                                Used::Other
1445                            };
1446                            this.record_use(ident, binding, used);
1447                        }
1448                        initial_binding.res()
1449                    });
1450                    let res = binding.res();
1451                    let has_ambiguity_error =
1452                        this.ambiguity_errors.iter().any(|error| error.warning.is_none());
1453                    if res == Res::Err || has_ambiguity_error {
1454                        this.dcx()
1455                            .span_delayed_bug(import.span, "some error happened for an import");
1456                        return;
1457                    }
1458                    if let Some(initial_res) = initial_res {
1459                        if res != initial_res && !this.issue_145575_hack_applied {
1460                            ::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");
1461                        }
1462                    } else if this.privacy_errors.is_empty() {
1463                        this.dcx()
1464                            .create_err(CannotDetermineImportResolution { span: import.span })
1465                            .emit();
1466                    }
1467                }
1468                Err(..) => {
1469                    // FIXME: This assert may fire if public glob is later shadowed by a private
1470                    // single import (see test `issue-55884-2.rs`). In theory single imports should
1471                    // always block globs, even if they are not yet resolved, so that this kind of
1472                    // self-inconsistent resolution never happens.
1473                    // Re-enable the assert when the issue is fixed.
1474                    // assert!(result[ns].get().is_err());
1475                }
1476            }
1477        });
1478
1479        if all_ns_err {
1480            let mut all_ns_failed = true;
1481            self.per_ns_mut(|this, ns| {
1482                let binding = this.cm_mut().resolve_ident_in_module(
1483                    module,
1484                    ident,
1485                    ns,
1486                    &import.parent_scope,
1487                    Some(finalize),
1488                    None,
1489                    None,
1490                );
1491                if binding.is_ok() {
1492                    all_ns_failed = false;
1493                }
1494            });
1495
1496            return if all_ns_failed {
1497                let names = match module {
1498                    ModuleOrUniformRoot::Module(module) => {
1499                        self.resolutions(module)
1500                            .iter()
1501                            .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1502                                if i.name == ident.name {
1503                                    return None;
1504                                } // Never suggest the same name
1505                                if i.name == kw::Underscore {
1506                                    return None;
1507                                } // `use _` is never valid
1508
1509                                let resolution = resolution.borrow(self);
1510                                if let Some(name_binding) = resolution.best_decl() {
1511                                    match name_binding.kind {
1512                                        DeclKind::Import { source_decl, .. } => {
1513                                            match source_decl.kind {
1514                                                // Never suggest names that previously could not
1515                                                // be resolved.
1516                                                DeclKind::Def(Res::Err) => None,
1517                                                _ => Some(i.name),
1518                                            }
1519                                        }
1520                                        _ => Some(i.name),
1521                                    }
1522                                } else if resolution.single_imports.is_empty() {
1523                                    None
1524                                } else {
1525                                    Some(i.name)
1526                                }
1527                            })
1528                            .collect()
1529                    }
1530                    _ => Vec::new(),
1531                };
1532
1533                let lev_suggestion =
1534                    find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
1535                        (
1536                            ::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())],
1537                            String::from("a similar name exists in the module"),
1538                            Applicability::MaybeIncorrect,
1539                        )
1540                    });
1541
1542                let (suggestion, note) =
1543                    match self.check_for_module_export_macro(import, module, ident) {
1544                        Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1545                        _ => (lev_suggestion, None),
1546                    };
1547
1548                // If importing of trait asscoiated items is enabled, an also find an
1549                // `Enum`, then note that inherent associated items cannot be imported.
1550                let note = if self.features.import_trait_associated_functions()
1551                    && let PathResult::Module(ModuleOrUniformRoot::Module(m)) = path_res
1552                    && let Some(Res::Def(DefKind::Enum, _)) = m.res()
1553                {
1554                    note.or(Some(
1555                        "cannot import inherent associated items, only trait associated items"
1556                            .to_string(),
1557                    ))
1558                } else {
1559                    note
1560                };
1561
1562                let label = match module {
1563                    ModuleOrUniformRoot::Module(module) => {
1564                        let module_str = module_to_string(module);
1565                        if let Some(module_str) = module_str {
1566                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no `{0}` in `{1}`", ident,
                module_str))
    })format!("no `{ident}` in `{module_str}`")
1567                        } else {
1568                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
    })format!("no `{ident}` in the root")
1569                        }
1570                    }
1571                    _ => {
1572                        if !ident.is_path_segment_keyword() {
1573                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no external crate `{0}`", ident))
    })format!("no external crate `{ident}`")
1574                        } else {
1575                            // HACK(eddyb) this shows up for `self` & `super`, which
1576                            // should work instead - for now keep the same error message.
1577                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
    })format!("no `{ident}` in the root")
1578                        }
1579                    }
1580                };
1581
1582                let parent_suggestion =
1583                    self.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true);
1584
1585                Some(UnresolvedImportError {
1586                    span: import.span,
1587                    label: Some(label),
1588                    note,
1589                    suggestion,
1590                    help: None,
1591                    candidates: if !parent_suggestion.is_empty() {
1592                        Some(parent_suggestion)
1593                    } else {
1594                        None
1595                    },
1596                    module: import.imported_module.get().and_then(|module| {
1597                        if let ModuleOrUniformRoot::Module(m) = module {
1598                            m.opt_def_id()
1599                        } else {
1600                            None
1601                        }
1602                    }),
1603                    segment: Some(ident),
1604                    on_unknown_attr: import.on_unknown_attr.clone(),
1605                })
1606            } else {
1607                // `resolve_ident_in_module` reported a privacy error.
1608                None
1609            };
1610        }
1611
1612        let mut reexport_error = None;
1613        let mut any_successful_reexport = false;
1614        self.per_ns(|this, ns| {
1615            let Some(binding) = bindings[ns].get().decl() else {
1616                return;
1617            };
1618
1619            if import.vis.greater_than(binding.vis(), this.tcx) {
1620                // In isolation, a declaration like this is not an error, but if *all* 1-3
1621                // declarations introduced by the import are more private than the import item's
1622                // nominal visibility, then it's an error.
1623                reexport_error = Some((ns, binding.import_source()));
1624            } else {
1625                any_successful_reexport = true;
1626            }
1627        });
1628
1629        if !any_successful_reexport {
1630            let (ns, binding) = reexport_error.unwrap();
1631            if let Some(lint) = self.report_cannot_reexport(import, binding, ident, ns) {
1632                self.lint_buffer.add_early_lint(lint);
1633            }
1634        }
1635
1636        if import.module_path.len() <= 1 {
1637            // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1638            // 2 segments, so the `resolve_path` above won't trigger it.
1639            let mut full_path = import.module_path.clone();
1640            full_path.push(Segment::from_ident(ident));
1641            self.per_ns_mut(|this, ns| {
1642                if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1643                    this.lint_if_path_starts_with_module(finalize, &full_path, Some(binding));
1644                }
1645            });
1646        }
1647
1648        // Record what this import resolves to for later uses in documentation,
1649        // this may resolve to either a value or a type, but for documentation
1650        // purposes it's good enough to just favor one over the other.
1651        self.per_ns_mut(|this, ns| {
1652            if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1653                this.owners.get_mut(&import_id).unwrap().import_res[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/a69a63265cfd9e006d43137f98301b8d274ad4c9/compiler/rustc_resolve/src/imports.rs:1657",
                        "rustc_resolve::imports", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/a69a63265cfd9e006d43137f98301b8d274ad4c9/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            let err = if crate_private_reexport {
1686                self.dcx().create_err(CannotBeReexportedCratePublicNS { span: import.span, ident })
1687            } else {
1688                self.dcx().create_err(CannotBeReexportedPrivateNS { span: import.span, ident })
1689            };
1690            err.emit();
1691        } else {
1692            let mut err = if crate_private_reexport {
1693                self.dcx().create_err(CannotBeReexportedCratePublic { span: import.span, ident })
1694            } else {
1695                self.dcx().create_err(CannotBeReexportedPrivate { span: import.span, ident })
1696            };
1697
1698            match decl.kind {
1699                // exclude decl_macro
1700                DeclKind::Def(Res::Def(DefKind::Macro(_), def_id))
1701                    if let SyntaxExtensionKind::MacroRules(mr) =
1702                        &self.get_macro_by_def_id(def_id).kind
1703                        && mr.is_macro_rules() =>
1704                {
1705                    err.subdiagnostic(ConsiderAddingMacroExport { span: decl.span });
1706                    err.subdiagnostic(ConsiderMarkingAsPubCrate { vis_span: import.vis_span });
1707                }
1708                _ => {
1709                    err.subdiagnostic(ConsiderMarkingAsPub { span: import.span, ident });
1710                }
1711            }
1712            err.emit();
1713        }
1714
1715        None
1716    }
1717
1718    pub(crate) fn check_for_redundant_imports(&mut self, import: Import<'ra>) -> bool {
1719        // This function is only called for single imports.
1720        let ImportKind::Single { source, target, ref decls, id, def_id, .. } = import.kind else {
1721            ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1722        };
1723
1724        // Skip if the import is of the form `use source as target` and source != target.
1725        if source != target {
1726            return false;
1727        }
1728
1729        // Skip if the import was produced by a macro.
1730        if import.parent_scope.expansion != LocalExpnId::ROOT {
1731            return false;
1732        }
1733
1734        // Skip if we are inside a named module (in contrast to an anonymous
1735        // module defined by a block).
1736        // Skip if the import is public or was used through non scope-based resolution,
1737        // e.g. through a module-relative path.
1738        if self.import_use_map.get(&import) == Some(&Used::Other)
1739            || self.effective_visibilities.is_exported(def_id)
1740        {
1741            return false;
1742        }
1743
1744        let mut is_redundant = true;
1745        let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1746        self.per_ns(|this, ns| {
1747            let binding = decls[ns].get().decl().map(|b| b.import_source());
1748            if is_redundant && let Some(binding) = binding {
1749                if binding.res() == Res::Err {
1750                    return;
1751                }
1752
1753                match this.cm().resolve_ident_in_scope_set(
1754                    target,
1755                    ScopeSet::All(ns),
1756                    &import.parent_scope,
1757                    None,
1758                    decls[ns].get().decl(),
1759                    None,
1760                ) {
1761                    Ok(other_binding) => {
1762                        is_redundant = binding.res() == other_binding.res()
1763                            && !other_binding.is_ambiguity_recursive();
1764                        if is_redundant {
1765                            redundant_span[ns] =
1766                                Some((other_binding.span, other_binding.is_import()));
1767                        }
1768                    }
1769                    Err(_) => is_redundant = false,
1770                }
1771            }
1772        });
1773
1774        if is_redundant && !redundant_span.is_empty() {
1775            let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1776            redundant_spans.sort();
1777            redundant_spans.dedup();
1778            self.lint_buffer.dyn_buffer_lint(
1779                REDUNDANT_IMPORTS,
1780                id,
1781                import.span,
1782                move |dcx, level| {
1783                    let ident = source;
1784                    let subs = redundant_spans
1785                        .into_iter()
1786                        .map(|(span, is_imported)| match (span.is_dummy(), is_imported) {
1787                            (false, true) => {
1788                                diagnostics::RedundantImportSub::ImportedHere { span, ident }
1789                            }
1790                            (false, false) => {
1791                                diagnostics::RedundantImportSub::DefinedHere { span, ident }
1792                            }
1793                            (true, true) => {
1794                                diagnostics::RedundantImportSub::ImportedPrelude { span, ident }
1795                            }
1796                            (true, false) => {
1797                                diagnostics::RedundantImportSub::DefinedPrelude { span, ident }
1798                            }
1799                        })
1800                        .collect();
1801                    diagnostics::RedundantImport { subs, ident }.into_diag(dcx, level)
1802                },
1803            );
1804            return true;
1805        }
1806
1807        false
1808    }
1809
1810    fn resolve_glob_import(
1811        &self,
1812        import: Import<'ra>,
1813        imported_module: ModuleOrUniformRoot<'ra>,
1814    ) -> ImportResolutionKind<'ra> {
1815        let import_bindings = match imported_module {
1816            ModuleOrUniformRoot::Module(module) if module != import.parent_scope.module => self
1817                .resolutions(module)
1818                .iter()
1819                .filter_map(|(key, resolution)| {
1820                    let res = resolution.borrow_checked(self);
1821                    let decl = res.determined_decl()?;
1822                    let mut key = *key;
1823                    let scope = match key.ident.ctxt.update_unchecked(|ctxt| {
1824                        ctxt.reverse_glob_adjust(module.expansion, import.span)
1825                    }) {
1826                        Some(Some(def)) => self.expn_def_scope(def),
1827                        Some(None) => import.parent_scope.module,
1828                        None => return None,
1829                    };
1830                    self.is_accessible_from(decl.vis(), scope).then_some((
1831                        decl,
1832                        key,
1833                        res.orig_ident_span,
1834                    ))
1835                })
1836                .collect::<Vec<_>>(),
1837
1838            // Errors are reported in `write_imports_resolutions`
1839            _ => ::alloc::vec::Vec::new()vec![],
1840        };
1841
1842        ImportResolutionKind::Glob(import_bindings)
1843    }
1844
1845    // Hack for the `rust_embed` regression observed in the crater run of #145108.
1846    fn rust_embed_hack(&self, module: LocalModule<'ra>, decl: Decl<'ra>) -> bool {
1847        // We are looking for this pattern:
1848        // ```rust
1849        // #[macro_use]
1850        // extern crate rust_embed_impl;
1851        // pub use rust_embed_impl::*;
1852        //
1853        // pub use RustEmbed as Embed;
1854        // ```
1855        if let DeclKind::Import { source_decl, import } = decl.kind
1856            // Check that `decl` is the re-export: "pub use RustEmbed as Embed;"
1857            && let ImportKind::Single { source, .. } = import.kind
1858            && source.name == sym::RustEmbed
1859            // make sure that the import points to the #[macro_use] import
1860            && let DeclKind::Import { import, .. } = source_decl.kind
1861            && #[allow(non_exhaustive_omitted_patterns)] match import.kind {
    ImportKind::MacroUse { .. } => true,
    _ => false,
}matches!(import.kind, ImportKind::MacroUse { .. })
1862            && self.macro_use_prelude.contains_key(&source.name) // and that the name actually exists in the macro_use_prelude
1863            // Then check that `RustEmbed` exists in the modules Macro namespace.
1864            && let Some(y_decl) = self
1865                .resolution(module.to_module(), BindingKey::new(IdentKey::new(source), MacroNS))
1866                .and_then(|res| res.best_decl())
1867            // which comes from "pub use rust_embed_impl::*"
1868            && y_decl.is_glob_import()
1869            && y_decl.vis().is_public()
1870        {
1871            return true;
1872        }
1873
1874        false
1875    }
1876
1877    // Miscellaneous post-processing, including recording re-exports,
1878    // reporting conflicts, and reporting unresolved imports.
1879    fn finalize_resolutions_in(
1880        &self,
1881        module: LocalModule<'ra>,
1882        module_children: &mut LocalDefIdMap<Vec<ModChild>>,
1883        ambig_module_children: &mut LocalDefIdMap<Vec<AmbigModChild>>,
1884    ) {
1885        // Since import resolution is finished, globs will not define any more names.
1886        *module.globs.borrow_mut_checked(self) = Vec::new();
1887
1888        let Some(def_id) = module.opt_def_id() else { return };
1889
1890        let mut children = Vec::new();
1891        let mut ambig_children = Vec::new();
1892
1893        module.to_module().for_each_child(self, |this, ident, orig_ident_span, _, decl| {
1894            let res = decl.res().expect_non_local();
1895            if res != def::Res::Err {
1896                let vis = if this.rust_embed_hack(module, decl) {
1897                    Visibility::Public
1898                } else {
1899                    decl.vis()
1900                };
1901                let ident = ident.orig(orig_ident_span);
1902                let child = |reexport_chain| ModChild { ident, res, vis, reexport_chain };
1903                if let Some((ambig_binding1, ambig_binding2)) = decl.descent_to_ambiguity() {
1904                    let main = child(ambig_binding1.reexport_chain());
1905                    let second = ModChild {
1906                        ident,
1907                        res: ambig_binding2.res().expect_non_local(),
1908                        vis: ambig_binding2.vis(),
1909                        reexport_chain: ambig_binding2.reexport_chain(),
1910                    };
1911                    ambig_children.push(AmbigModChild { main, second })
1912                } else {
1913                    children.push(child(decl.reexport_chain()));
1914                }
1915            }
1916        });
1917
1918        if !children.is_empty() {
1919            module_children.insert(def_id.expect_local(), children);
1920        }
1921        if !ambig_children.is_empty() {
1922            ambig_module_children.insert(def_id.expect_local(), ambig_children);
1923        }
1924    }
1925}
1926
1927pub(crate) fn import_path_to_string(
1928    names: &[Ident],
1929    import_kind: &ImportKind<'_>,
1930    span: Span,
1931) -> String {
1932    let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1933    let global = !names.is_empty() && names[0].name == kw::PathRoot;
1934    if let Some(pos) = pos {
1935        let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1936        names_to_string(names.iter().map(|ident| ident.name))
1937    } else {
1938        let names = if global { &names[1..] } else { names };
1939        if names.is_empty() {
1940            import_kind_to_string(import_kind)
1941        } else {
1942            ::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!(
1943                "{}::{}",
1944                names_to_string(names.iter().map(|ident| ident.name)),
1945                import_kind_to_string(import_kind),
1946            )
1947        }
1948    }
1949}
1950
1951fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1952    match import_kind {
1953        ImportKind::Single { source, .. } => source.to_string(),
1954        ImportKind::Glob { .. } => "*".to_string(),
1955        ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1956        ImportKind::MacroUse { .. } => "#[macro_use]".to_string(),
1957        ImportKind::MacroExport => "#[macro_export]".to_string(),
1958    }
1959}