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