Skip to main content

rustc_resolve/
imports.rs

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