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::mem;
4
5use rustc_ast::NodeId;
6use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
7use rustc_data_structures::intern::Interned;
8use rustc_errors::codes::*;
9use rustc_errors::{Applicability, MultiSpan, pluralize, struct_span_code_err};
10use rustc_hir::def::{self, DefKind, PartialRes};
11use rustc_hir::def_id::{DefId, LocalDefIdMap};
12use rustc_middle::metadata::{AmbigModChild, ModChild, Reexport};
13use rustc_middle::span_bug;
14use rustc_middle::ty::Visibility;
15use rustc_session::lint::BuiltinLintDiag;
16use rustc_session::lint::builtin::{
17    AMBIGUOUS_GLOB_REEXPORTS, EXPORTED_PRIVATE_DEPENDENCIES, HIDDEN_GLOB_REEXPORTS,
18    PUB_USE_OF_PRIVATE_EXTERN_CRATE, REDUNDANT_IMPORTS, UNUSED_IMPORTS,
19};
20use rustc_session::parse::feature_err;
21use rustc_span::edit_distance::find_best_match_for_name;
22use rustc_span::hygiene::LocalExpnId;
23use rustc_span::{Ident, Span, Symbol, kw, sym};
24use tracing::debug;
25
26use crate::Namespace::{self, *};
27use crate::diagnostics::{DiagMode, Suggestion, import_candidates};
28use crate::errors::{
29    CannotBeReexportedCratePublic, CannotBeReexportedCratePublicNS, CannotBeReexportedPrivate,
30    CannotBeReexportedPrivateNS, CannotDetermineImportResolution, CannotGlobImportAllCrates,
31    ConsiderAddingMacroExport, ConsiderMarkingAsPub, ConsiderMarkingAsPubCrate,
32};
33use crate::ref_mut::CmCell;
34use crate::{
35    AmbiguityError, BindingKey, CmResolver, Decl, DeclData, DeclKind, Determinacy, Finalize,
36    IdentKey, ImportSuggestion, Module, ModuleOrUniformRoot, ParentScope, PathResult, PerNS,
37    ResolutionError, Resolver, ScopeSet, Segment, Used, module_to_string, names_to_string,
38};
39
40type Res = def::Res<NodeId>;
41
42/// A potential import declaration in the process of being planted into a module.
43/// Also used for lazily planting names from `--extern` flags to extern prelude.
44#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for PendingDecl<'ra> {
    #[inline]
    fn clone(&self) -> PendingDecl<'ra> {
        let _: ::core::clone::AssertParamIsClone<Option<Decl<'ra>>>;
        *self
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::marker::Copy for PendingDecl<'ra> { }Copy, #[automatically_derived]
impl<'ra> ::core::default::Default for PendingDecl<'ra> {
    #[inline]
    fn default() -> PendingDecl<'ra> { Self::Pending }
}Default, #[automatically_derived]
impl<'ra> ::core::cmp::PartialEq for PendingDecl<'ra> {
    #[inline]
    fn eq(&self, other: &PendingDecl<'ra>) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (PendingDecl::Ready(__self_0), PendingDecl::Ready(__arg1_0))
                    => __self_0 == __arg1_0,
                _ => true,
            }
    }
}PartialEq)]
45pub(crate) enum PendingDecl<'ra> {
46    Ready(Option<Decl<'ra>>),
47    #[default]
48    Pending,
49}
50
51impl<'ra> PendingDecl<'ra> {
52    pub(crate) fn decl(self) -> Option<Decl<'ra>> {
53        match self {
54            PendingDecl::Ready(decl) => decl,
55            PendingDecl::Pending => None,
56        }
57    }
58}
59
60/// Contains data for specific kinds of imports.
61#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for ImportKind<'ra> {
    #[inline]
    fn clone(&self) -> ImportKind<'ra> {
        match self {
            ImportKind::Single {
                source: __self_0,
                target: __self_1,
                decls: __self_2,
                type_ns_only: __self_3,
                nested: __self_4,
                id: __self_5 } =>
                ImportKind::Single {
                    source: ::core::clone::Clone::clone(__self_0),
                    target: ::core::clone::Clone::clone(__self_1),
                    decls: ::core::clone::Clone::clone(__self_2),
                    type_ns_only: ::core::clone::Clone::clone(__self_3),
                    nested: ::core::clone::Clone::clone(__self_4),
                    id: ::core::clone::Clone::clone(__self_5),
                },
            ImportKind::Glob { max_vis: __self_0, id: __self_1 } =>
                ImportKind::Glob {
                    max_vis: ::core::clone::Clone::clone(__self_0),
                    id: ::core::clone::Clone::clone(__self_1),
                },
            ImportKind::ExternCrate {
                source: __self_0, target: __self_1, id: __self_2 } =>
                ImportKind::ExternCrate {
                    source: ::core::clone::Clone::clone(__self_0),
                    target: ::core::clone::Clone::clone(__self_1),
                    id: ::core::clone::Clone::clone(__self_2),
                },
            ImportKind::MacroUse { warn_private: __self_0 } =>
                ImportKind::MacroUse {
                    warn_private: ::core::clone::Clone::clone(__self_0),
                },
            ImportKind::MacroExport => ImportKind::MacroExport,
        }
    }
}Clone)]
62pub(crate) enum ImportKind<'ra> {
63    Single {
64        /// `source` in `use prefix::source as target`.
65        source: Ident,
66        /// `target` in `use prefix::source as target`.
67        /// It will directly use `source` when the format is `use prefix::source`.
68        target: Ident,
69        /// Name declarations introduced by the import.
70        decls: PerNS<CmCell<PendingDecl<'ra>>>,
71        /// `true` for `...::{self [as target]}` imports, `false` otherwise.
72        type_ns_only: bool,
73        /// Did this import result from a nested import? ie. `use foo::{bar, baz};`
74        nested: bool,
75        /// The ID of the `UseTree` that imported this `Import`.
76        ///
77        /// In the case where the `Import` was expanded from a "nested" use tree,
78        /// this id is the ID of the leaf tree. For example:
79        ///
80        /// ```ignore (pacify the merciless tidy)
81        /// use foo::bar::{a, b}
82        /// ```
83        ///
84        /// If this is the import for `foo::bar::a`, we would have the ID of the `UseTree`
85        /// for `a` in this field.
86        id: NodeId,
87    },
88    Glob {
89        // The visibility of the greatest re-export.
90        // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
91        max_vis: CmCell<Option<Visibility>>,
92        id: NodeId,
93    },
94    ExternCrate {
95        source: Option<Symbol>,
96        target: Ident,
97        id: NodeId,
98    },
99    MacroUse {
100        /// A field has been added indicating whether it should be reported as a lint,
101        /// addressing issue#119301.
102        warn_private: bool,
103    },
104    MacroExport,
105}
106
107/// Manually implement `Debug` for `ImportKind` because the `source/target_bindings`
108/// contain `Cell`s which can introduce infinite loops while printing.
109impl<'ra> std::fmt::Debug for ImportKind<'ra> {
110    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111        use ImportKind::*;
112        match self {
113            Single { source, target, decls, type_ns_only, nested, id, .. } => f
114                .debug_struct("Single")
115                .field("source", source)
116                .field("target", target)
117                // Ignore the nested bindings to avoid an infinite loop while printing.
118                .field(
119                    "decls",
120                    &decls.clone().map(|b| b.into_inner().decl().map(|_| format_args!("..")format_args!(".."))),
121                )
122                .field("type_ns_only", type_ns_only)
123                .field("nested", nested)
124                .field("id", id)
125                .finish(),
126            Glob { max_vis, id } => {
127                f.debug_struct("Glob").field("max_vis", max_vis).field("id", id).finish()
128            }
129            ExternCrate { source, target, id } => f
130                .debug_struct("ExternCrate")
131                .field("source", source)
132                .field("target", target)
133                .field("id", id)
134                .finish(),
135            MacroUse { warn_private } => {
136                f.debug_struct("MacroUse").field("warn_private", warn_private).finish()
137            }
138            MacroExport => f.debug_struct("MacroExport").finish(),
139        }
140    }
141}
142
143/// One import.
144#[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"];
        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];
        ::core::fmt::Formatter::debug_struct_fields_finish(f, "ImportData",
            names, values)
    }
}Debug, #[automatically_derived]
impl<'ra> ::core::clone::Clone for ImportData<'ra> {
    #[inline]
    fn clone(&self) -> ImportData<'ra> {
        ImportData {
            kind: ::core::clone::Clone::clone(&self.kind),
            root_id: ::core::clone::Clone::clone(&self.root_id),
            use_span: ::core::clone::Clone::clone(&self.use_span),
            use_span_with_attributes: ::core::clone::Clone::clone(&self.use_span_with_attributes),
            has_attributes: ::core::clone::Clone::clone(&self.has_attributes),
            span: ::core::clone::Clone::clone(&self.span),
            root_span: ::core::clone::Clone::clone(&self.root_span),
            parent_scope: ::core::clone::Clone::clone(&self.parent_scope),
            module_path: ::core::clone::Clone::clone(&self.module_path),
            imported_module: ::core::clone::Clone::clone(&self.imported_module),
            vis: ::core::clone::Clone::clone(&self.vis),
            vis_span: ::core::clone::Clone::clone(&self.vis_span),
        }
    }
}Clone)]
145pub(crate) struct ImportData<'ra> {
146    pub kind: ImportKind<'ra>,
147
148    /// Node ID of the "root" use item -- this is always the same as `ImportKind`'s `id`
149    /// (if it exists) except in the case of "nested" use trees, in which case
150    /// it will be the ID of the root use tree. e.g., in the example
151    /// ```ignore (incomplete code)
152    /// use foo::bar::{a, b}
153    /// ```
154    /// this would be the ID of the `use foo::bar` `UseTree` node.
155    /// In case of imports without their own node ID it's the closest node that can be used,
156    /// for example, for reporting lints.
157    pub root_id: NodeId,
158
159    /// Span of the entire use statement.
160    pub use_span: Span,
161
162    /// Span of the entire use statement with attributes.
163    pub use_span_with_attributes: Span,
164
165    /// Did the use statement have any attributes?
166    pub has_attributes: bool,
167
168    /// Span of this use tree.
169    pub span: Span,
170
171    /// Span of the *root* use tree (see `root_id`).
172    pub root_span: Span,
173
174    pub parent_scope: ParentScope<'ra>,
175    pub module_path: Vec<Segment>,
176    /// The resolution of `module_path`:
177    ///
178    /// | `module_path` | `imported_module` | remark |
179    /// |-|-|-|
180    /// |`use prefix::foo`| `ModuleOrUniformRoot::Module(prefix)`         | - |
181    /// |`use ::foo`      | `ModuleOrUniformRoot::ExternPrelude`          | 2018+ editions |
182    /// |`use ::foo`      | `ModuleOrUniformRoot::ModuleAndExternPrelude` | a special case in 2015 edition |
183    /// |`use foo`        | `ModuleOrUniformRoot::CurrentScope`           | - |
184    pub imported_module: CmCell<Option<ModuleOrUniformRoot<'ra>>>,
185    pub vis: Visibility,
186
187    /// Span of the visibility.
188    pub vis_span: Span,
189}
190
191/// All imports are unique and allocated on a same arena,
192/// so we can use referential equality to compare them.
193pub(crate) type Import<'ra> = Interned<'ra, ImportData<'ra>>;
194
195// Allows us to use Interned without actually enforcing (via Hash/PartialEq/...) uniqueness of the
196// contained data.
197// FIXME: We may wish to actually have at least debug-level assertions that Interned's guarantees
198// are upheld.
199impl std::hash::Hash for ImportData<'_> {
200    fn hash<H>(&self, _: &mut H)
201    where
202        H: std::hash::Hasher,
203    {
204        ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
205    }
206}
207
208impl<'ra> ImportData<'ra> {
209    pub(crate) fn is_glob(&self) -> bool {
210        #[allow(non_exhaustive_omitted_patterns)] match self.kind {
    ImportKind::Glob { .. } => true,
    _ => false,
}matches!(self.kind, ImportKind::Glob { .. })
211    }
212
213    pub(crate) fn is_nested(&self) -> bool {
214        match self.kind {
215            ImportKind::Single { nested, .. } => nested,
216            _ => false,
217        }
218    }
219
220    pub(crate) fn id(&self) -> Option<NodeId> {
221        match self.kind {
222            ImportKind::Single { id, .. }
223            | ImportKind::Glob { id, .. }
224            | ImportKind::ExternCrate { id, .. } => Some(id),
225            ImportKind::MacroUse { .. } | ImportKind::MacroExport => None,
226        }
227    }
228
229    pub(crate) fn simplify(&self, r: &Resolver<'_, '_>) -> Reexport {
230        let to_def_id = |id| r.local_def_id(id).to_def_id();
231        match self.kind {
232            ImportKind::Single { id, .. } => Reexport::Single(to_def_id(id)),
233            ImportKind::Glob { id, .. } => Reexport::Glob(to_def_id(id)),
234            ImportKind::ExternCrate { id, .. } => Reexport::ExternCrate(to_def_id(id)),
235            ImportKind::MacroUse { .. } => Reexport::MacroUse,
236            ImportKind::MacroExport => Reexport::MacroExport,
237        }
238    }
239}
240
241/// Records information about the resolution of a name in a namespace of a module.
242#[derive(#[automatically_derived]
impl<'ra> ::core::clone::Clone for NameResolution<'ra> {
    #[inline]
    fn clone(&self) -> NameResolution<'ra> {
        NameResolution {
            single_imports: ::core::clone::Clone::clone(&self.single_imports),
            non_glob_decl: ::core::clone::Clone::clone(&self.non_glob_decl),
            glob_decl: ::core::clone::Clone::clone(&self.glob_decl),
            orig_ident_span: ::core::clone::Clone::clone(&self.orig_ident_span),
        }
    }
}Clone, #[automatically_derived]
impl<'ra> ::core::fmt::Debug for NameResolution<'ra> {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field4_finish(f,
            "NameResolution", "single_imports", &self.single_imports,
            "non_glob_decl", &self.non_glob_decl, "glob_decl",
            &self.glob_decl, "orig_ident_span", &&self.orig_ident_span)
    }
}Debug)]
243pub(crate) struct NameResolution<'ra> {
244    /// Single imports that may define the name in the namespace.
245    /// Imports are arena-allocated, so it's ok to use pointers as keys.
246    pub single_imports: FxIndexSet<Import<'ra>>,
247    /// The non-glob declaration for this name, if it is known to exist.
248    pub non_glob_decl: Option<Decl<'ra>> = None,
249    /// The glob declaration for this name, if it is known to exist.
250    pub glob_decl: Option<Decl<'ra>> = None,
251    pub orig_ident_span: Span,
252}
253
254impl<'ra> NameResolution<'ra> {
255    pub(crate) fn new(orig_ident_span: Span) -> Self {
256        NameResolution { single_imports: FxIndexSet::default(), orig_ident_span, .. }
257    }
258
259    /// Returns the binding for the name if it is known or None if it not known.
260    pub(crate) fn binding(&self) -> Option<Decl<'ra>> {
261        self.best_decl().and_then(|binding| {
262            if !binding.is_glob_import() || self.single_imports.is_empty() {
263                Some(binding)
264            } else {
265                None
266            }
267        })
268    }
269
270    pub(crate) fn best_decl(&self) -> Option<Decl<'ra>> {
271        self.non_glob_decl.or(self.glob_decl)
272    }
273}
274
275/// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
276/// import errors within the same use tree into a single diagnostic.
277#[derive(#[automatically_derived]
impl ::core::fmt::Debug for UnresolvedImportError {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        let names: &'static _ =
            &["span", "label", "note", "suggestion", "candidates", "segment",
                        "module"];
        let values: &[&dyn ::core::fmt::Debug] =
            &[&self.span, &self.label, &self.note, &self.suggestion,
                        &self.candidates, &self.segment, &&self.module];
        ::core::fmt::Formatter::debug_struct_fields_finish(f,
            "UnresolvedImportError", names, values)
    }
}Debug, #[automatically_derived]
impl ::core::clone::Clone for UnresolvedImportError {
    #[inline]
    fn clone(&self) -> UnresolvedImportError {
        UnresolvedImportError {
            span: ::core::clone::Clone::clone(&self.span),
            label: ::core::clone::Clone::clone(&self.label),
            note: ::core::clone::Clone::clone(&self.note),
            suggestion: ::core::clone::Clone::clone(&self.suggestion),
            candidates: ::core::clone::Clone::clone(&self.candidates),
            segment: ::core::clone::Clone::clone(&self.segment),
            module: ::core::clone::Clone::clone(&self.module),
        }
    }
}Clone)]
278struct UnresolvedImportError {
279    span: Span,
280    label: Option<String>,
281    note: Option<String>,
282    suggestion: Option<Suggestion>,
283    candidates: Option<Vec<ImportSuggestion>>,
284    segment: Option<Symbol>,
285    /// comes from `PathRes::Failed { module }`
286    module: Option<DefId>,
287}
288
289// Reexports of the form `pub use foo as bar;` where `foo` is `extern crate foo;`
290// are permitted for backward-compatibility under a deprecation lint.
291fn pub_use_of_private_extern_crate_hack(import: Import<'_>, decl: Decl<'_>) -> Option<NodeId> {
292    match (&import.kind, &decl.kind) {
293        (ImportKind::Single { .. }, DeclKind::Import { import: decl_import, .. })
294            if let ImportKind::ExternCrate { id, .. } = decl_import.kind
295                && import.vis.is_public() =>
296        {
297            Some(id)
298        }
299        _ => None,
300    }
301}
302
303/// Removes identical import layers from two declarations.
304fn remove_same_import<'ra>(d1: Decl<'ra>, d2: Decl<'ra>) -> (Decl<'ra>, Decl<'ra>) {
305    if let DeclKind::Import { import: import1, source_decl: d1_next } = d1.kind
306        && let DeclKind::Import { import: import2, source_decl: d2_next } = d2.kind
307        && import1 == import2
308    {
309        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);
310        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);
311        if d1.ambiguity.get() != d2.ambiguity.get() {
312            if !d1.ambiguity.get().is_some() {
    ::core::panicking::panic("assertion failed: d1.ambiguity.get().is_some()")
};assert!(d1.ambiguity.get().is_some());
313            if !d2.ambiguity.get().is_none() {
    ::core::panicking::panic("assertion failed: d2.ambiguity.get().is_none()")
};assert!(d2.ambiguity.get().is_none());
314        }
315        // Visibility of the new import declaration may be different,
316        // because it already incorporates the visibility of the source binding.
317        // `warn_ambiguity` of a re-fetched glob can also change in both directions.
318        remove_same_import(d1_next, d2_next)
319    } else {
320        (d1, d2)
321    }
322}
323
324impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
325    /// Given an import and the declaration that it points to,
326    /// create the corresponding import declaration.
327    pub(crate) fn new_import_decl(&self, decl: Decl<'ra>, import: Import<'ra>) -> Decl<'ra> {
328        let import_vis = import.vis.to_def_id();
329        let vis = if decl.vis().is_at_least(import_vis, self.tcx)
330            || pub_use_of_private_extern_crate_hack(import, decl).is_some()
331        {
332            import_vis
333        } else {
334            decl.vis()
335        };
336
337        if let ImportKind::Glob { ref max_vis, .. } = import.kind
338            && (vis == import_vis
339                || max_vis.get().is_none_or(|max_vis| vis.is_at_least(max_vis, self.tcx)))
340        {
341            max_vis.set_unchecked(Some(vis.expect_local()))
342        }
343
344        self.arenas.alloc_decl(DeclData {
345            kind: DeclKind::Import { source_decl: decl, import },
346            ambiguity: CmCell::new(None),
347            warn_ambiguity: CmCell::new(false),
348            span: import.span,
349            vis: CmCell::new(vis),
350            expansion: import.parent_scope.expansion,
351            parent_module: Some(import.parent_scope.module),
352        })
353    }
354
355    /// If `glob_decl` attempts to overwrite `old_glob_decl` in a module,
356    /// decide which one to keep.
357    fn select_glob_decl(
358        &self,
359        old_glob_decl: Decl<'ra>,
360        glob_decl: Decl<'ra>,
361        warn_ambiguity: bool,
362    ) -> Decl<'ra> {
363        if !glob_decl.is_glob_import() {
    ::core::panicking::panic("assertion failed: glob_decl.is_glob_import()")
};assert!(glob_decl.is_glob_import());
364        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());
365        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);
366        // `best_decl` with a given key in a module may be overwritten in a
367        // number of cases (all of them can be seen below in the `match` in `try_define_local`),
368        // all these overwrites will be re-fetched by glob imports importing
369        // from that module without generating new ambiguities.
370        // - A glob decl is overwritten by a non-glob decl arriving later.
371        // - A glob decl is overwritten by its clone after setting ambiguity in it.
372        //   FIXME: avoid this by removing `warn_ambiguity`, or by triggering glob re-fetch
373        //   with the same decl in some way.
374        // - A glob decl is overwritten by a glob decl with larger visibility.
375        //   FIXME: avoid this by updating this visibility in place.
376        // - A glob decl is overwritten by a glob decl re-fetching an
377        //   overwritten decl from other module (the recursive case).
378        // Here we are detecting all such re-fetches and overwrite old decls
379        // with the re-fetched decls.
380        // This is probably incorrect in corner cases, and the outdated decls still get
381        // propagated to other places and get stuck there, but that's what we have at the moment.
382        let (old_deep_decl, deep_decl) = remove_same_import(old_glob_decl, glob_decl);
383        if deep_decl != glob_decl {
384            // Some import layers have been removed, need to overwrite.
385            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);
386            // FIXME: reenable the asserts when `warn_ambiguity` is removed (#149195).
387            // assert_ne!(old_deep_decl, deep_decl);
388            // assert!(old_deep_decl.is_glob_import());
389            // FIXME: reenable the assert when visibility is updated in place.
390            // assert!(!deep_decl.is_glob_import());
391            if old_glob_decl.ambiguity.get().is_some() && glob_decl.ambiguity.get().is_none() {
392                // Do not lose glob ambiguities when re-fetching the glob.
393                glob_decl.ambiguity.set_unchecked(old_glob_decl.ambiguity.get());
394            }
395            if glob_decl.is_ambiguity_recursive() {
396                glob_decl.warn_ambiguity.set_unchecked(true);
397            }
398            glob_decl
399        } else if glob_decl.res() != old_glob_decl.res() {
400            old_glob_decl.ambiguity.set_unchecked(Some(glob_decl));
401            old_glob_decl.warn_ambiguity.set_unchecked(warn_ambiguity);
402            if warn_ambiguity {
403                old_glob_decl
404            } else {
405                // Need a fresh decl so other glob imports importing it could re-fetch it
406                // and set their own `warn_ambiguity` to true.
407                // FIXME: remove this when `warn_ambiguity` is removed (#149195).
408                self.arenas.alloc_decl((*old_glob_decl).clone())
409            }
410        } else if !old_glob_decl.vis().is_at_least(glob_decl.vis(), self.tcx) {
411            // We are glob-importing the same item but with greater visibility.
412            // FIXME: Update visibility in place, but without regressions
413            // (#152004, #151124, #152347).
414            glob_decl
415        } else if glob_decl.is_ambiguity_recursive() && !old_glob_decl.is_ambiguity_recursive() {
416            // Overwriting a non-ambiguous glob import with an ambiguous glob import.
417            old_glob_decl.ambiguity.set_unchecked(Some(glob_decl));
418            old_glob_decl.warn_ambiguity.set_unchecked(true);
419            old_glob_decl
420        } else {
421            old_glob_decl
422        }
423    }
424
425    /// Attempt to put the declaration with the given name and namespace into the module,
426    /// and return existing declaration if there is a collision.
427    pub(crate) fn try_plant_decl_into_local_module(
428        &mut self,
429        ident: IdentKey,
430        orig_ident_span: Span,
431        ns: Namespace,
432        decl: Decl<'ra>,
433        warn_ambiguity: bool,
434    ) -> Result<(), Decl<'ra>> {
435        let module = decl.parent_module.unwrap();
436        let res = decl.res();
437        self.check_reserved_macro_name(ident.name, orig_ident_span, res);
438        // Even if underscore names cannot be looked up, we still need to add them to modules,
439        // because they can be fetched by glob imports from those modules, and bring traits
440        // into scope both directly and through glob imports.
441        let key = BindingKey::new_disambiguated(ident, ns, || {
442            module.underscore_disambiguator.update_unchecked(|d| d + 1);
443            module.underscore_disambiguator.get()
444        });
445        self.update_local_resolution(
446            module,
447            key,
448            orig_ident_span,
449            warn_ambiguity,
450            |this, resolution| {
451                if let Some(old_decl) = resolution.best_decl() {
452                    match (&decl, &old_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!(decl, old_decl);
453                    if !!decl.warn_ambiguity.get() {
    ::core::panicking::panic("assertion failed: !decl.warn_ambiguity.get()")
};assert!(!decl.warn_ambiguity.get());
454                    if res == Res::Err && old_decl.res() != Res::Err {
455                        // Do not override real declarations with `Res::Err`s from error recovery.
456                        return Ok(());
457                    }
458                    match (old_decl.is_glob_import(), decl.is_glob_import()) {
459                        (true, true) => {
460                            resolution.glob_decl =
461                                Some(this.select_glob_decl(old_decl, decl, warn_ambiguity));
462                        }
463                        (old_glob @ true, false) | (old_glob @ false, true) => {
464                            let (glob_decl, non_glob_decl) =
465                                if old_glob { (old_decl, decl) } else { (decl, old_decl) };
466                            resolution.non_glob_decl = Some(non_glob_decl);
467                            if let Some(old_glob_decl) = resolution.glob_decl
468                                && old_glob_decl != glob_decl
469                            {
470                                resolution.glob_decl =
471                                    Some(this.select_glob_decl(old_glob_decl, glob_decl, false));
472                            } else {
473                                resolution.glob_decl = Some(glob_decl);
474                            }
475                        }
476                        (false, false) => {
477                            return Err(old_decl);
478                        }
479                    }
480                } else {
481                    if decl.is_glob_import() {
482                        resolution.glob_decl = Some(decl);
483                    } else {
484                        resolution.non_glob_decl = Some(decl);
485                    }
486                }
487
488                Ok(())
489            },
490        )
491    }
492
493    // Use `f` to mutate the resolution of the name in the module.
494    // If the resolution becomes a success, define it in the module's glob importers.
495    fn update_local_resolution<T, F>(
496        &mut self,
497        module: Module<'ra>,
498        key: BindingKey,
499        orig_ident_span: Span,
500        warn_ambiguity: bool,
501        f: F,
502    ) -> T
503    where
504        F: FnOnce(&Resolver<'ra, 'tcx>, &mut NameResolution<'ra>) -> T,
505    {
506        // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
507        // during which the resolution might end up getting re-defined via a glob cycle.
508        let (binding, t, warn_ambiguity) = {
509            let resolution = &mut *self
510                .resolution_or_default(module, key, orig_ident_span)
511                .borrow_mut_unchecked();
512            let old_decl = resolution.binding();
513
514            let t = f(self, resolution);
515
516            if let Some(binding) = resolution.binding()
517                && old_decl != Some(binding)
518            {
519                (binding, t, warn_ambiguity || old_decl.is_some())
520            } else {
521                return t;
522            }
523        };
524
525        let Ok(glob_importers) = module.glob_importers.try_borrow_mut_unchecked() else {
526            return t;
527        };
528
529        // Define or update `binding` in `module`s glob importers.
530        for import in glob_importers.iter() {
531            let mut ident = key.ident;
532            let scope = match ident
533                .ctxt
534                .update_unchecked(|ctxt| ctxt.reverse_glob_adjust(module.expansion, import.span))
535            {
536                Some(Some(def)) => self.expn_def_scope(def),
537                Some(None) => import.parent_scope.module,
538                None => continue,
539            };
540            if self.is_accessible_from(binding.vis(), scope) {
541                let import_decl = self.new_import_decl(binding, *import);
542                let _ = self.try_plant_decl_into_local_module(
543                    ident,
544                    orig_ident_span,
545                    key.ns,
546                    import_decl,
547                    warn_ambiguity,
548                );
549            }
550        }
551
552        t
553    }
554
555    // Define a dummy resolution containing a `Res::Err` as a placeholder for a failed
556    // or indeterminate resolution, also mark such failed imports as used to avoid duplicate diagnostics.
557    fn import_dummy_binding(&mut self, import: Import<'ra>, is_indeterminate: bool) {
558        if let ImportKind::Single { target, ref decls, .. } = import.kind {
559            if !(is_indeterminate || decls.iter().all(|d| d.get().decl().is_none())) {
560                return; // Has resolution, do not create the dummy binding
561            }
562            let dummy_decl = self.dummy_decl;
563            let dummy_decl = self.new_import_decl(dummy_decl, import);
564            self.per_ns(|this, ns| {
565                let module = import.parent_scope.module;
566                let ident = IdentKey::new(target);
567                let _ = this.try_plant_decl_into_local_module(
568                    ident,
569                    target.span,
570                    ns,
571                    dummy_decl,
572                    false,
573                );
574                // Don't remove underscores from `single_imports`, they were never added.
575                if target.name != kw::Underscore {
576                    let key = BindingKey::new(ident, ns);
577                    this.update_local_resolution(
578                        module,
579                        key,
580                        target.span,
581                        false,
582                        |_, resolution| {
583                            resolution.single_imports.swap_remove(&import);
584                        },
585                    )
586                }
587            });
588            self.record_use(target, dummy_decl, Used::Other);
589        } else if import.imported_module.get().is_none() {
590            self.import_use_map.insert(import, Used::Other);
591            if let Some(id) = import.id() {
592                self.used_imports.insert(id);
593            }
594        }
595    }
596
597    // Import resolution
598    //
599    // This is a fixed-point algorithm. We resolve imports until our efforts
600    // are stymied by an unresolved import; then we bail out of the current
601    // module and continue. We terminate successfully once no more imports
602    // remain or unsuccessfully when no forward progress in resolving imports
603    // is made.
604
605    /// Resolves all imports for the crate. This method performs the fixed-
606    /// point iteration.
607    pub(crate) fn resolve_imports(&mut self) {
608        let mut prev_indeterminate_count = usize::MAX;
609        let mut indeterminate_count = self.indeterminate_imports.len() * 3;
610        while indeterminate_count < prev_indeterminate_count {
611            prev_indeterminate_count = indeterminate_count;
612            indeterminate_count = 0;
613            self.assert_speculative = true;
614            for import in mem::take(&mut self.indeterminate_imports) {
615                let import_indeterminate_count = self.cm().resolve_import(import);
616                indeterminate_count += import_indeterminate_count;
617                match import_indeterminate_count {
618                    0 => self.determined_imports.push(import),
619                    _ => self.indeterminate_imports.push(import),
620                }
621            }
622            self.assert_speculative = false;
623        }
624    }
625
626    pub(crate) fn finalize_imports(&mut self) {
627        let mut module_children = Default::default();
628        let mut ambig_module_children = Default::default();
629        for module in &self.local_modules {
630            self.finalize_resolutions_in(*module, &mut module_children, &mut ambig_module_children);
631        }
632        self.module_children = module_children;
633        self.ambig_module_children = ambig_module_children;
634
635        let mut seen_spans = FxHashSet::default();
636        let mut errors = ::alloc::vec::Vec::new()vec![];
637        let mut prev_root_id: NodeId = NodeId::ZERO;
638        let determined_imports = mem::take(&mut self.determined_imports);
639        let indeterminate_imports = mem::take(&mut self.indeterminate_imports);
640
641        let mut glob_error = false;
642        for (is_indeterminate, import) in determined_imports
643            .iter()
644            .map(|i| (false, i))
645            .chain(indeterminate_imports.iter().map(|i| (true, i)))
646        {
647            let unresolved_import_error = self.finalize_import(*import);
648            // If this import is unresolved then create a dummy import
649            // resolution for it so that later resolve stages won't complain.
650            self.import_dummy_binding(*import, is_indeterminate);
651
652            let Some(err) = unresolved_import_error else { continue };
653
654            glob_error |= import.is_glob();
655
656            if let ImportKind::Single { source, ref decls, .. } = import.kind
657                && source.name == kw::SelfLower
658                // Silence `unresolved import` error if E0429 is already emitted
659                && let PendingDecl::Ready(None) = decls.value_ns.get()
660            {
661                continue;
662            }
663
664            if prev_root_id != NodeId::ZERO && prev_root_id != import.root_id && !errors.is_empty()
665            {
666                // In the case of a new import line, throw a diagnostic message
667                // for the previous line.
668                self.throw_unresolved_import_error(errors, glob_error);
669                errors = ::alloc::vec::Vec::new()vec![];
670            }
671            if seen_spans.insert(err.span) {
672                errors.push((*import, err));
673                prev_root_id = import.root_id;
674            }
675        }
676
677        if !errors.is_empty() {
678            self.throw_unresolved_import_error(errors, glob_error);
679            return;
680        }
681
682        for import in &indeterminate_imports {
683            let path = import_path_to_string(
684                &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
685                &import.kind,
686                import.span,
687            );
688            // FIXME: there should be a better way of doing this than
689            // formatting this as a string then checking for `::`
690            if path.contains("::") {
691                let err = UnresolvedImportError {
692                    span: import.span,
693                    label: None,
694                    note: None,
695                    suggestion: None,
696                    candidates: None,
697                    segment: None,
698                    module: None,
699                };
700                errors.push((*import, err))
701            }
702        }
703
704        if !errors.is_empty() {
705            self.throw_unresolved_import_error(errors, glob_error);
706        }
707    }
708
709    pub(crate) fn lint_reexports(&mut self, exported_ambiguities: FxHashSet<Decl<'ra>>) {
710        for module in &self.local_modules {
711            for (key, resolution) in self.resolutions(*module).borrow().iter() {
712                let resolution = resolution.borrow();
713                let Some(binding) = resolution.best_decl() else { continue };
714
715                if let DeclKind::Import { import, .. } = binding.kind
716                    && let Some(amb_binding) = binding.ambiguity.get()
717                    && binding.res() != Res::Err
718                    && exported_ambiguities.contains(&binding)
719                {
720                    self.lint_buffer.buffer_lint(
721                        AMBIGUOUS_GLOB_REEXPORTS,
722                        import.root_id,
723                        import.root_span,
724                        BuiltinLintDiag::AmbiguousGlobReexports {
725                            name: key.ident.name.to_string(),
726                            namespace: key.ns.descr().to_string(),
727                            first_reexport_span: import.root_span,
728                            duplicate_reexport_span: amb_binding.span,
729                        },
730                    );
731                }
732
733                if let Some(glob_decl) = resolution.glob_decl
734                    && resolution.non_glob_decl.is_some()
735                {
736                    if binding.res() != Res::Err
737                        && glob_decl.res() != Res::Err
738                        && let DeclKind::Import { import: glob_import, .. } = glob_decl.kind
739                        && let Some(glob_import_id) = glob_import.id()
740                        && let glob_import_def_id = self.local_def_id(glob_import_id)
741                        && self.effective_visibilities.is_exported(glob_import_def_id)
742                        && glob_decl.vis().is_public()
743                        && !binding.vis().is_public()
744                    {
745                        let binding_id = match binding.kind {
746                            DeclKind::Def(res) => {
747                                Some(self.def_id_to_node_id(res.def_id().expect_local()))
748                            }
749                            DeclKind::Import { import, .. } => import.id(),
750                        };
751                        if let Some(binding_id) = binding_id {
752                            self.lint_buffer.buffer_lint(
753                                HIDDEN_GLOB_REEXPORTS,
754                                binding_id,
755                                binding.span,
756                                BuiltinLintDiag::HiddenGlobReexports {
757                                    name: key.ident.name.to_string(),
758                                    namespace: key.ns.descr().to_owned(),
759                                    glob_reexport_span: glob_decl.span,
760                                    private_item_span: binding.span,
761                                },
762                            );
763                        }
764                    }
765                }
766
767                if let DeclKind::Import { import, .. } = binding.kind
768                    && let Some(binding_id) = import.id()
769                    && let import_def_id = self.local_def_id(binding_id)
770                    && self.effective_visibilities.is_exported(import_def_id)
771                    && let Res::Def(reexported_kind, reexported_def_id) = binding.res()
772                    && !#[allow(non_exhaustive_omitted_patterns)] match reexported_kind {
    DefKind::Ctor(..) => true,
    _ => false,
}matches!(reexported_kind, DefKind::Ctor(..))
773                    && !reexported_def_id.is_local()
774                    && self.tcx.is_private_dep(reexported_def_id.krate)
775                {
776                    self.lint_buffer.buffer_lint(
777                        EXPORTED_PRIVATE_DEPENDENCIES,
778                        binding_id,
779                        binding.span,
780                        crate::errors::ReexportPrivateDependency {
781                            name: key.ident.name,
782                            kind: binding.res().descr(),
783                            krate: self.tcx.crate_name(reexported_def_id.krate),
784                        },
785                    );
786                }
787            }
788        }
789    }
790
791    fn throw_unresolved_import_error(
792        &mut self,
793        mut errors: Vec<(Import<'_>, UnresolvedImportError)>,
794        glob_error: bool,
795    ) {
796        errors.retain(|(_import, err)| match err.module {
797            // Skip `use` errors for `use foo::Bar;` if `foo.rs` has unrecovered parse errors.
798            Some(def_id) if self.mods_with_parse_errors.contains(&def_id) => false,
799            // If we've encountered something like `use _;`, we've already emitted an error stating
800            // that `_` is not a valid identifier, so we ignore that resolve error.
801            _ => err.segment != Some(kw::Underscore),
802        });
803        if errors.is_empty() {
804            self.tcx.dcx().delayed_bug("expected a parse or \"`_` can't be an identifier\" error");
805            return;
806        }
807
808        let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
809
810        let paths = errors
811            .iter()
812            .map(|(import, err)| {
813                let path = import_path_to_string(
814                    &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
815                    &import.kind,
816                    err.span,
817                );
818                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", path))
    })format!("`{path}`")
819            })
820            .collect::<Vec<_>>();
821        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("unresolved import{0} {1}",
                if paths.len() == 1 { "" } else { "s" }, paths.join(", ")))
    })format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);
822
823        let mut diag = {
    self.dcx().struct_span_err(span,
            ::alloc::__export::must_use({
                    ::alloc::fmt::format(format_args!("{0}", msg))
                })).with_code(E0432)
}struct_span_code_err!(self.dcx(), span, E0432, "{msg}");
824
825        if let Some((_, UnresolvedImportError { note: Some(note), .. })) = errors.iter().last() {
826            diag.note(note.clone());
827        }
828
829        /// Upper limit on the number of `span_label` messages.
830        const MAX_LABEL_COUNT: usize = 10;
831
832        for (import, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
833            if let Some(label) = err.label {
834                diag.span_label(err.span, label);
835            }
836
837            if let Some((suggestions, msg, applicability)) = err.suggestion {
838                if suggestions.is_empty() {
839                    diag.help(msg);
840                    continue;
841                }
842                diag.multipart_suggestion(msg, suggestions, applicability);
843            }
844
845            if let Some(candidates) = &err.candidates {
846                match &import.kind {
847                    ImportKind::Single { nested: false, source, target, .. } => import_candidates(
848                        self.tcx,
849                        &mut diag,
850                        Some(err.span),
851                        candidates,
852                        DiagMode::Import { append: false, unresolved_import: true },
853                        (source != target)
854                            .then(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" as {0}", target))
    })format!(" as {target}"))
855                            .as_deref()
856                            .unwrap_or(""),
857                    ),
858                    ImportKind::Single { nested: true, source, target, .. } => {
859                        import_candidates(
860                            self.tcx,
861                            &mut diag,
862                            None,
863                            candidates,
864                            DiagMode::Normal,
865                            (source != target)
866                                .then(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" as {0}", target))
    })format!(" as {target}"))
867                                .as_deref()
868                                .unwrap_or(""),
869                        );
870                    }
871                    _ => {}
872                }
873            }
874
875            if #[allow(non_exhaustive_omitted_patterns)] match import.kind {
    ImportKind::Single { .. } => true,
    _ => false,
}matches!(import.kind, ImportKind::Single { .. })
876                && let Some(segment) = err.segment
877                && let Some(module) = err.module
878            {
879                self.find_cfg_stripped(&mut diag, &segment, module)
880            }
881        }
882
883        let guar = diag.emit();
884        if glob_error {
885            self.glob_error = Some(guar);
886        }
887    }
888
889    /// Attempts to resolve the given import, returning:
890    /// - `0` means its resolution is determined.
891    /// - Other values mean that indeterminate exists under certain namespaces.
892    ///
893    /// Meanwhile, if resolve successful, the resolved bindings are written
894    /// into the module.
895    fn resolve_import<'r>(mut self: CmResolver<'r, 'ra, 'tcx>, import: Import<'ra>) -> usize {
896        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/imports.rs:896",
                        "rustc_resolve::imports", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/imports.rs"),
                        ::tracing_core::__macro_support::Option::Some(896u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::imports"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("(resolving import for module) resolving import `{0}::...` in `{1}`",
                                                    Segment::names_to_string(&import.module_path),
                                                    module_to_string(import.parent_scope.module).unwrap_or_else(||
                                                            "???".to_string())) as &dyn Value))])
            });
    } else { ; }
};debug!(
897            "(resolving import for module) resolving import `{}::...` in `{}`",
898            Segment::names_to_string(&import.module_path),
899            module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
900        );
901        let module = if let Some(module) = import.imported_module.get() {
902            module
903        } else {
904            let path_res = self.reborrow().maybe_resolve_path(
905                &import.module_path,
906                None,
907                &import.parent_scope,
908                Some(import),
909            );
910
911            match path_res {
912                PathResult::Module(module) => module,
913                PathResult::Indeterminate => return 3,
914                PathResult::NonModule(..) | PathResult::Failed { .. } => return 0,
915            }
916        };
917
918        import.imported_module.set_unchecked(Some(module));
919        let (source, target, bindings, type_ns_only) = match import.kind {
920            ImportKind::Single { source, target, ref decls, type_ns_only, .. } => {
921                (source, target, decls, type_ns_only)
922            }
923            ImportKind::Glob { .. } => {
924                self.get_mut_unchecked().resolve_glob_import(import);
925                return 0;
926            }
927            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
928        };
929
930        let mut indeterminate_count = 0;
931        self.per_ns_cm(|mut this, ns| {
932            if !type_ns_only || ns == TypeNS {
933                if bindings[ns].get() != PendingDecl::Pending {
934                    return;
935                };
936                let binding_result = this.reborrow().maybe_resolve_ident_in_module(
937                    module,
938                    source,
939                    ns,
940                    &import.parent_scope,
941                    Some(import),
942                );
943                let parent = import.parent_scope.module;
944                let binding = match binding_result {
945                    Ok(binding) => {
946                        if binding.is_assoc_item()
947                            && !this.tcx.features().import_trait_associated_functions()
948                        {
949                            feature_err(
950                                this.tcx.sess,
951                                sym::import_trait_associated_functions,
952                                import.span,
953                                "`use` associated items of traits is unstable",
954                            )
955                            .emit();
956                        }
957                        // We need the `target`, `source` can be extracted.
958                        let import_decl = this.new_import_decl(binding, import);
959                        this.get_mut_unchecked().plant_decl_into_local_module(
960                            IdentKey::new(target),
961                            target.span,
962                            ns,
963                            import_decl,
964                        );
965                        PendingDecl::Ready(Some(import_decl))
966                    }
967                    Err(Determinacy::Determined) => {
968                        // Don't remove underscores from `single_imports`, they were never added.
969                        if target.name != kw::Underscore {
970                            let key = BindingKey::new(IdentKey::new(target), ns);
971                            this.get_mut_unchecked().update_local_resolution(
972                                parent,
973                                key,
974                                target.span,
975                                false,
976                                |_, resolution| {
977                                    resolution.single_imports.swap_remove(&import);
978                                },
979                            );
980                        }
981                        PendingDecl::Ready(None)
982                    }
983                    Err(Determinacy::Undetermined) => {
984                        indeterminate_count += 1;
985                        PendingDecl::Pending
986                    }
987                };
988                bindings[ns].set_unchecked(binding);
989            }
990        });
991
992        indeterminate_count
993    }
994
995    /// Performs final import resolution, consistency checks and error reporting.
996    ///
997    /// Optionally returns an unresolved import error. This error is buffered and used to
998    /// consolidate multiple unresolved import errors into a single diagnostic.
999    fn finalize_import(&mut self, import: Import<'ra>) -> Option<UnresolvedImportError> {
1000        let ignore_decl = match &import.kind {
1001            ImportKind::Single { decls, .. } => decls[TypeNS].get().decl(),
1002            _ => None,
1003        };
1004        let ambiguity_errors_len = |errors: &Vec<AmbiguityError<'_>>| {
1005            errors.iter().filter(|error| error.warning.is_none()).count()
1006        };
1007        let prev_ambiguity_errors_len = ambiguity_errors_len(&self.ambiguity_errors);
1008        let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
1009
1010        // We'll provide more context to the privacy errors later, up to `len`.
1011        let privacy_errors_len = self.privacy_errors.len();
1012
1013        let path_res = self.cm().resolve_path(
1014            &import.module_path,
1015            None,
1016            &import.parent_scope,
1017            Some(finalize),
1018            ignore_decl,
1019            Some(import),
1020        );
1021
1022        let no_ambiguity =
1023            ambiguity_errors_len(&self.ambiguity_errors) == prev_ambiguity_errors_len;
1024
1025        let module = match path_res {
1026            PathResult::Module(module) => {
1027                // Consistency checks, analogous to `finalize_macro_resolutions`.
1028                if let Some(initial_module) = import.imported_module.get() {
1029                    if module != initial_module && no_ambiguity && !self.issue_145575_hack_applied {
1030                        ::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");
1031                    }
1032                } else if self.privacy_errors.is_empty() {
1033                    self.dcx()
1034                        .create_err(CannotDetermineImportResolution { span: import.span })
1035                        .emit();
1036                }
1037
1038                module
1039            }
1040            PathResult::Failed {
1041                is_error_from_last_segment: false,
1042                span,
1043                segment_name,
1044                label,
1045                suggestion,
1046                module,
1047                error_implied_by_parse_error: _,
1048                message,
1049            } => {
1050                if no_ambiguity {
1051                    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());
1052                    self.report_error(
1053                        span,
1054                        ResolutionError::FailedToResolve {
1055                            segment: segment_name,
1056                            label,
1057                            suggestion,
1058                            module,
1059                            message,
1060                        },
1061                    );
1062                }
1063                return None;
1064            }
1065            PathResult::Failed {
1066                is_error_from_last_segment: true,
1067                span,
1068                label,
1069                suggestion,
1070                module,
1071                segment_name,
1072                ..
1073            } => {
1074                if no_ambiguity {
1075                    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());
1076                    let module = if let Some(ModuleOrUniformRoot::Module(m)) = module {
1077                        m.opt_def_id()
1078                    } else {
1079                        None
1080                    };
1081                    let err = match self
1082                        .make_path_suggestion(import.module_path.clone(), &import.parent_scope)
1083                    {
1084                        Some((suggestion, note)) => UnresolvedImportError {
1085                            span,
1086                            label: None,
1087                            note,
1088                            suggestion: Some((
1089                                ::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))],
1090                                String::from("a similar path exists"),
1091                                Applicability::MaybeIncorrect,
1092                            )),
1093                            candidates: None,
1094                            segment: Some(segment_name),
1095                            module,
1096                        },
1097                        None => UnresolvedImportError {
1098                            span,
1099                            label: Some(label),
1100                            note: None,
1101                            suggestion,
1102                            candidates: None,
1103                            segment: Some(segment_name),
1104                            module,
1105                        },
1106                    };
1107                    return Some(err);
1108                }
1109                return None;
1110            }
1111            PathResult::NonModule(partial_res) => {
1112                if no_ambiguity && partial_res.full_res() != Some(Res::Err) {
1113                    // Check if there are no ambiguities and the result is not dummy.
1114                    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());
1115                }
1116                // The error was already reported earlier.
1117                return None;
1118            }
1119            PathResult::Indeterminate => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1120        };
1121
1122        let (ident, target, bindings, type_ns_only, import_id) = match import.kind {
1123            ImportKind::Single { source, target, ref decls, type_ns_only, id, .. } => {
1124                (source, target, decls, type_ns_only, id)
1125            }
1126            ImportKind::Glob { ref max_vis, id } => {
1127                if import.module_path.len() <= 1 {
1128                    // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1129                    // 2 segments, so the `resolve_path` above won't trigger it.
1130                    let mut full_path = import.module_path.clone();
1131                    full_path.push(Segment::from_ident(Ident::dummy()));
1132                    self.lint_if_path_starts_with_module(finalize, &full_path, None);
1133                }
1134
1135                if let ModuleOrUniformRoot::Module(module) = module
1136                    && module == import.parent_scope.module
1137                {
1138                    // Importing a module into itself is not allowed.
1139                    return Some(UnresolvedImportError {
1140                        span: import.span,
1141                        label: Some(String::from("cannot glob-import a module into itself")),
1142                        note: None,
1143                        suggestion: None,
1144                        candidates: None,
1145                        segment: None,
1146                        module: None,
1147                    });
1148                }
1149                if let Some(max_vis) = max_vis.get()
1150                    && !max_vis.is_at_least(import.vis, self.tcx)
1151                {
1152                    let def_id = self.local_def_id(id);
1153                    self.lint_buffer.buffer_lint(
1154                        UNUSED_IMPORTS,
1155                        id,
1156                        import.span,
1157                        crate::errors::RedundantImportVisibility {
1158                            span: import.span,
1159                            help: (),
1160                            max_vis: max_vis.to_string(def_id, self.tcx),
1161                            import_vis: import.vis.to_string(def_id, self.tcx),
1162                        },
1163                    );
1164                }
1165                return None;
1166            }
1167            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1168        };
1169
1170        if self.privacy_errors.len() != privacy_errors_len {
1171            // Get the Res for the last element, so that we can point to alternative ways of
1172            // importing it if available.
1173            let mut path = import.module_path.clone();
1174            path.push(Segment::from_ident(ident));
1175            if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.cm().resolve_path(
1176                &path,
1177                None,
1178                &import.parent_scope,
1179                Some(finalize),
1180                ignore_decl,
1181                None,
1182            ) {
1183                let res = module.res().map(|r| (r, ident));
1184                for error in &mut self.privacy_errors[privacy_errors_len..] {
1185                    error.outermost_res = res;
1186                }
1187            }
1188        }
1189
1190        let mut all_ns_err = true;
1191        self.per_ns(|this, ns| {
1192            if !type_ns_only || ns == TypeNS {
1193                let binding = this.cm().resolve_ident_in_module(
1194                    module,
1195                    ident,
1196                    ns,
1197                    &import.parent_scope,
1198                    Some(Finalize {
1199                        report_private: false,
1200                        import_vis: Some(import.vis),
1201                        ..finalize
1202                    }),
1203                    bindings[ns].get().decl(),
1204                    Some(import),
1205                );
1206
1207                match binding {
1208                    Ok(binding) => {
1209                        // Consistency checks, analogous to `finalize_macro_resolutions`.
1210                        let initial_res = bindings[ns].get().decl().map(|binding| {
1211                            let initial_binding = binding.import_source();
1212                            all_ns_err = false;
1213                            if target.name == kw::Underscore
1214                                && initial_binding.is_extern_crate()
1215                                && !initial_binding.is_import()
1216                            {
1217                                let used = if import.module_path.is_empty() {
1218                                    Used::Scope
1219                                } else {
1220                                    Used::Other
1221                                };
1222                                this.record_use(ident, binding, used);
1223                            }
1224                            initial_binding.res()
1225                        });
1226                        let res = binding.res();
1227                        let has_ambiguity_error =
1228                            this.ambiguity_errors.iter().any(|error| error.warning.is_none());
1229                        if res == Res::Err || has_ambiguity_error {
1230                            this.dcx()
1231                                .span_delayed_bug(import.span, "some error happened for an import");
1232                            return;
1233                        }
1234                        if let Some(initial_res) = initial_res {
1235                            if res != initial_res && !this.issue_145575_hack_applied {
1236                                ::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");
1237                            }
1238                        } else if this.privacy_errors.is_empty() {
1239                            this.dcx()
1240                                .create_err(CannotDetermineImportResolution { span: import.span })
1241                                .emit();
1242                        }
1243                    }
1244                    Err(..) => {
1245                        // FIXME: This assert may fire if public glob is later shadowed by a private
1246                        // single import (see test `issue-55884-2.rs`). In theory single imports should
1247                        // always block globs, even if they are not yet resolved, so that this kind of
1248                        // self-inconsistent resolution never happens.
1249                        // Re-enable the assert when the issue is fixed.
1250                        // assert!(result[ns].get().is_err());
1251                    }
1252                }
1253            }
1254        });
1255
1256        if all_ns_err {
1257            let mut all_ns_failed = true;
1258            self.per_ns(|this, ns| {
1259                if !type_ns_only || ns == TypeNS {
1260                    let binding = this.cm().resolve_ident_in_module(
1261                        module,
1262                        ident,
1263                        ns,
1264                        &import.parent_scope,
1265                        Some(finalize),
1266                        None,
1267                        None,
1268                    );
1269                    if binding.is_ok() {
1270                        all_ns_failed = false;
1271                    }
1272                }
1273            });
1274
1275            return if all_ns_failed {
1276                let names = match module {
1277                    ModuleOrUniformRoot::Module(module) => {
1278                        self.resolutions(module)
1279                            .borrow()
1280                            .iter()
1281                            .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1282                                if i.name == ident.name {
1283                                    return None;
1284                                } // Never suggest the same name
1285
1286                                let resolution = resolution.borrow();
1287                                if let Some(name_binding) = resolution.best_decl() {
1288                                    match name_binding.kind {
1289                                        DeclKind::Import { source_decl, .. } => {
1290                                            match source_decl.kind {
1291                                                // Never suggest names that previously could not
1292                                                // be resolved.
1293                                                DeclKind::Def(Res::Err) => None,
1294                                                _ => Some(i.name),
1295                                            }
1296                                        }
1297                                        _ => Some(i.name),
1298                                    }
1299                                } else if resolution.single_imports.is_empty() {
1300                                    None
1301                                } else {
1302                                    Some(i.name)
1303                                }
1304                            })
1305                            .collect()
1306                    }
1307                    _ => Vec::new(),
1308                };
1309
1310                let lev_suggestion =
1311                    find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
1312                        (
1313                            ::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())],
1314                            String::from("a similar name exists in the module"),
1315                            Applicability::MaybeIncorrect,
1316                        )
1317                    });
1318
1319                let (suggestion, note) =
1320                    match self.check_for_module_export_macro(import, module, ident) {
1321                        Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1322                        _ => (lev_suggestion, None),
1323                    };
1324
1325                let label = match module {
1326                    ModuleOrUniformRoot::Module(module) => {
1327                        let module_str = module_to_string(module);
1328                        if let Some(module_str) = module_str {
1329                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no `{0}` in `{1}`", ident,
                module_str))
    })format!("no `{ident}` in `{module_str}`")
1330                        } else {
1331                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
    })format!("no `{ident}` in the root")
1332                        }
1333                    }
1334                    _ => {
1335                        if !ident.is_path_segment_keyword() {
1336                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no external crate `{0}`", ident))
    })format!("no external crate `{ident}`")
1337                        } else {
1338                            // HACK(eddyb) this shows up for `self` & `super`, which
1339                            // should work instead - for now keep the same error message.
1340                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
    })format!("no `{ident}` in the root")
1341                        }
1342                    }
1343                };
1344
1345                let parent_suggestion =
1346                    self.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true);
1347
1348                Some(UnresolvedImportError {
1349                    span: import.span,
1350                    label: Some(label),
1351                    note,
1352                    suggestion,
1353                    candidates: if !parent_suggestion.is_empty() {
1354                        Some(parent_suggestion)
1355                    } else {
1356                        None
1357                    },
1358                    module: import.imported_module.get().and_then(|module| {
1359                        if let ModuleOrUniformRoot::Module(m) = module {
1360                            m.opt_def_id()
1361                        } else {
1362                            None
1363                        }
1364                    }),
1365                    segment: Some(ident.name),
1366                })
1367            } else {
1368                // `resolve_ident_in_module` reported a privacy error.
1369                None
1370            };
1371        }
1372
1373        let mut reexport_error = None;
1374        let mut any_successful_reexport = false;
1375        let mut crate_private_reexport = false;
1376        self.per_ns(|this, ns| {
1377            let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) else {
1378                return;
1379            };
1380
1381            if !binding.vis().is_at_least(import.vis, this.tcx) {
1382                reexport_error = Some((ns, binding));
1383                if let Visibility::Restricted(binding_def_id) = binding.vis()
1384                    && binding_def_id.is_top_level_module()
1385                {
1386                    crate_private_reexport = true;
1387                }
1388            } else {
1389                any_successful_reexport = true;
1390            }
1391        });
1392
1393        // All namespaces must be re-exported with extra visibility for an error to occur.
1394        if !any_successful_reexport {
1395            let (ns, binding) = reexport_error.unwrap();
1396            if let Some(extern_crate_id) = pub_use_of_private_extern_crate_hack(import, binding) {
1397                let extern_crate_sp = self.tcx.source_span(self.local_def_id(extern_crate_id));
1398                self.lint_buffer.buffer_lint(
1399                    PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1400                    import_id,
1401                    import.span,
1402                    crate::errors::PrivateExternCrateReexport {
1403                        ident,
1404                        sugg: extern_crate_sp.shrink_to_lo(),
1405                    },
1406                );
1407            } else if ns == TypeNS {
1408                let err = if crate_private_reexport {
1409                    self.dcx()
1410                        .create_err(CannotBeReexportedCratePublicNS { span: import.span, ident })
1411                } else {
1412                    self.dcx().create_err(CannotBeReexportedPrivateNS { span: import.span, ident })
1413                };
1414                err.emit();
1415            } else {
1416                let mut err = if crate_private_reexport {
1417                    self.dcx()
1418                        .create_err(CannotBeReexportedCratePublic { span: import.span, ident })
1419                } else {
1420                    self.dcx().create_err(CannotBeReexportedPrivate { span: import.span, ident })
1421                };
1422
1423                match binding.kind {
1424                        DeclKind::Def(Res::Def(DefKind::Macro(_), def_id))
1425                            // exclude decl_macro
1426                            if self.get_macro_by_def_id(def_id).macro_rules =>
1427                        {
1428                            err.subdiagnostic( ConsiderAddingMacroExport {
1429                                span: binding.span,
1430                            });
1431                            err.subdiagnostic( ConsiderMarkingAsPubCrate {
1432                                vis_span: import.vis_span,
1433                            });
1434                        }
1435                        _ => {
1436                            err.subdiagnostic( ConsiderMarkingAsPub {
1437                                span: import.span,
1438                                ident,
1439                            });
1440                        }
1441                    }
1442                err.emit();
1443            }
1444        }
1445
1446        if import.module_path.len() <= 1 {
1447            // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1448            // 2 segments, so the `resolve_path` above won't trigger it.
1449            let mut full_path = import.module_path.clone();
1450            full_path.push(Segment::from_ident(ident));
1451            self.per_ns(|this, ns| {
1452                if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1453                    this.lint_if_path_starts_with_module(finalize, &full_path, Some(binding));
1454                }
1455            });
1456        }
1457
1458        // Record what this import resolves to for later uses in documentation,
1459        // this may resolve to either a value or a type, but for documentation
1460        // purposes it's good enough to just favor one over the other.
1461        self.per_ns(|this, ns| {
1462            if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1463                this.import_res_map.entry(import_id).or_default()[ns] = Some(binding.res());
1464            }
1465        });
1466
1467        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_resolve/src/imports.rs:1467",
                        "rustc_resolve::imports", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/imports.rs"),
                        ::tracing_core::__macro_support::Option::Some(1467u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_resolve::imports"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("(resolving single import) successfully resolved import")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("(resolving single import) successfully resolved import");
1468        None
1469    }
1470
1471    pub(crate) fn check_for_redundant_imports(&mut self, import: Import<'ra>) -> bool {
1472        // This function is only called for single imports.
1473        let ImportKind::Single { source, target, ref decls, id, .. } = import.kind else {
1474            ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1475        };
1476
1477        // Skip if the import is of the form `use source as target` and source != target.
1478        if source != target {
1479            return false;
1480        }
1481
1482        // Skip if the import was produced by a macro.
1483        if import.parent_scope.expansion != LocalExpnId::ROOT {
1484            return false;
1485        }
1486
1487        // Skip if we are inside a named module (in contrast to an anonymous
1488        // module defined by a block).
1489        // Skip if the import is public or was used through non scope-based resolution,
1490        // e.g. through a module-relative path.
1491        if self.import_use_map.get(&import) == Some(&Used::Other)
1492            || self.effective_visibilities.is_exported(self.local_def_id(id))
1493        {
1494            return false;
1495        }
1496
1497        let mut is_redundant = true;
1498        let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1499        self.per_ns(|this, ns| {
1500            let binding = decls[ns].get().decl().map(|b| b.import_source());
1501            if is_redundant && let Some(binding) = binding {
1502                if binding.res() == Res::Err {
1503                    return;
1504                }
1505
1506                match this.cm().resolve_ident_in_scope_set(
1507                    target,
1508                    ScopeSet::All(ns),
1509                    &import.parent_scope,
1510                    None,
1511                    decls[ns].get().decl(),
1512                    None,
1513                ) {
1514                    Ok(other_binding) => {
1515                        is_redundant = binding.res() == other_binding.res()
1516                            && !other_binding.is_ambiguity_recursive();
1517                        if is_redundant {
1518                            redundant_span[ns] =
1519                                Some((other_binding.span, other_binding.is_import()));
1520                        }
1521                    }
1522                    Err(_) => is_redundant = false,
1523                }
1524            }
1525        });
1526
1527        if is_redundant && !redundant_span.is_empty() {
1528            let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1529            redundant_spans.sort();
1530            redundant_spans.dedup();
1531            self.lint_buffer.buffer_lint(
1532                REDUNDANT_IMPORTS,
1533                id,
1534                import.span,
1535                BuiltinLintDiag::RedundantImport(redundant_spans, source),
1536            );
1537            return true;
1538        }
1539
1540        false
1541    }
1542
1543    fn resolve_glob_import(&mut self, import: Import<'ra>) {
1544        // This function is only called for glob imports.
1545        let ImportKind::Glob { id, .. } = import.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
1546
1547        let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else {
1548            self.dcx().emit_err(CannotGlobImportAllCrates { span: import.span });
1549            return;
1550        };
1551
1552        if module.is_trait() && !self.tcx.features().import_trait_associated_functions() {
1553            feature_err(
1554                self.tcx.sess,
1555                sym::import_trait_associated_functions,
1556                import.span,
1557                "`use` associated items of traits is unstable",
1558            )
1559            .emit();
1560        }
1561
1562        if module == import.parent_scope.module {
1563            return;
1564        }
1565
1566        // Add to module's glob_importers
1567        module.glob_importers.borrow_mut_unchecked().push(import);
1568
1569        // Ensure that `resolutions` isn't borrowed during `try_define`,
1570        // since it might get updated via a glob cycle.
1571        let bindings = self
1572            .resolutions(module)
1573            .borrow()
1574            .iter()
1575            .filter_map(|(key, resolution)| {
1576                let resolution = resolution.borrow();
1577                resolution.binding().map(|binding| (*key, binding, resolution.orig_ident_span))
1578            })
1579            .collect::<Vec<_>>();
1580        for (mut key, binding, orig_ident_span) in bindings {
1581            let scope =
1582                match key.ident.ctxt.update_unchecked(|ctxt| {
1583                    ctxt.reverse_glob_adjust(module.expansion, import.span)
1584                }) {
1585                    Some(Some(def)) => self.expn_def_scope(def),
1586                    Some(None) => import.parent_scope.module,
1587                    None => continue,
1588                };
1589            if self.is_accessible_from(binding.vis(), scope) {
1590                let import_decl = self.new_import_decl(binding, import);
1591                let warn_ambiguity = self
1592                    .resolution(import.parent_scope.module, key)
1593                    .and_then(|r| r.binding())
1594                    .is_some_and(|binding| binding.warn_ambiguity_recursive());
1595                let _ = self.try_plant_decl_into_local_module(
1596                    key.ident,
1597                    orig_ident_span,
1598                    key.ns,
1599                    import_decl,
1600                    warn_ambiguity,
1601                );
1602            }
1603        }
1604
1605        // Record the destination of this import
1606        self.record_partial_res(id, PartialRes::new(module.res().unwrap()));
1607    }
1608
1609    // Miscellaneous post-processing, including recording re-exports,
1610    // reporting conflicts, and reporting unresolved imports.
1611    fn finalize_resolutions_in(
1612        &self,
1613        module: Module<'ra>,
1614        module_children: &mut LocalDefIdMap<Vec<ModChild>>,
1615        ambig_module_children: &mut LocalDefIdMap<Vec<AmbigModChild>>,
1616    ) {
1617        // Since import resolution is finished, globs will not define any more names.
1618        *module.globs.borrow_mut(self) = Vec::new();
1619
1620        let Some(def_id) = module.opt_def_id() else { return };
1621
1622        let mut children = Vec::new();
1623        let mut ambig_children = Vec::new();
1624
1625        module.for_each_child(self, |this, ident, orig_ident_span, _, binding| {
1626            let res = binding.res().expect_non_local();
1627            if res != def::Res::Err {
1628                let ident = ident.orig(orig_ident_span);
1629                let child =
1630                    |reexport_chain| ModChild { ident, res, vis: binding.vis(), reexport_chain };
1631                if let Some((ambig_binding1, ambig_binding2)) = binding.descent_to_ambiguity() {
1632                    let main = child(ambig_binding1.reexport_chain(this));
1633                    let second = ModChild {
1634                        ident,
1635                        res: ambig_binding2.res().expect_non_local(),
1636                        vis: ambig_binding2.vis(),
1637                        reexport_chain: ambig_binding2.reexport_chain(this),
1638                    };
1639                    ambig_children.push(AmbigModChild { main, second })
1640                } else {
1641                    children.push(child(binding.reexport_chain(this)));
1642                }
1643            }
1644        });
1645
1646        if !children.is_empty() {
1647            module_children.insert(def_id.expect_local(), children);
1648        }
1649        if !ambig_children.is_empty() {
1650            ambig_module_children.insert(def_id.expect_local(), ambig_children);
1651        }
1652    }
1653}
1654
1655fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
1656    let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1657    let global = !names.is_empty() && names[0].name == kw::PathRoot;
1658    if let Some(pos) = pos {
1659        let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1660        names_to_string(names.iter().map(|ident| ident.name))
1661    } else {
1662        let names = if global { &names[1..] } else { names };
1663        if names.is_empty() {
1664            import_kind_to_string(import_kind)
1665        } else {
1666            ::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!(
1667                "{}::{}",
1668                names_to_string(names.iter().map(|ident| ident.name)),
1669                import_kind_to_string(import_kind),
1670            )
1671        }
1672    }
1673}
1674
1675fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1676    match import_kind {
1677        ImportKind::Single { source, .. } => source.to_string(),
1678        ImportKind::Glob { .. } => "*".to_string(),
1679        ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1680        ImportKind::MacroUse { .. } => "#[macro_use]".to_string(),
1681        ImportKind::MacroExport => "#[macro_export]".to_string(),
1682    }
1683}