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            if !d2.ambiguity.get().is_none() {
    ::core::panicking::panic("assertion failed: d2.ambiguity.get().is_none()")
};assert!(d2.ambiguity.get().is_none());
386        }
387        // Visibility of the new import declaration may be different,
388        // because it already incorporates the visibility of the source binding.
389        // `warn_ambiguity` of a re-fetched glob can also change in both directions.
390        remove_same_import(d1_next, d2_next)
391    } else {
392        (d1, d2)
393    }
394}
395
396impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
397    pub(crate) fn import_decl_vis(&self, decl: Decl<'ra>, import: ImportSummary) -> Visibility {
398        self.import_decl_vis_ext(decl, import, false)
399    }
400
401    pub(crate) fn import_decl_vis_ext(
402        &self,
403        decl: Decl<'ra>,
404        import: ImportSummary,
405        min: bool,
406    ) -> Visibility {
407        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));
408        let decl_vis = if min { decl.min_vis() } else { decl.vis() };
409        let ord = decl_vis.partial_cmp(import.vis, self.tcx);
410        let extern_crate_hack = pub_use_of_private_extern_crate_hack(import, decl).is_some();
411        if ord == Some(Ordering::Less)
412            && decl_vis.is_accessible_from(import.nearest_parent_mod, self.tcx)
413            && !extern_crate_hack
414        {
415            // Imported declaration is less visible than the import, but is still visible
416            // from the current module, use the declaration's visibility.
417            decl_vis.expect_local()
418        } else {
419            // Good case - imported declaration is more visible than the import, or the same,
420            // use the import's visibility.
421            //
422            // Bad case - imported declaration is too private for the current module.
423            // It doesn't matter what visibility we choose here (except in the `PRIVATE_MACRO_USE`
424            // and `PUB_USE_OF_PRIVATE_EXTERN_CRATE` cases), because an error will be reported.
425            // Use import visibility to keep the all declaration visibilities in a module ordered.
426            if !min
427                && #[allow(non_exhaustive_omitted_patterns)] match ord {
    None | Some(Ordering::Less) => true,
    _ => false,
}matches!(ord, None | Some(Ordering::Less))
428                && !extern_crate_hack
429                && !import.priv_macro_use
430            {
431                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);
432                self.dcx().span_delayed_bug(import.span, msg);
433            }
434            import.vis
435        }
436    }
437
438    /// Given an import and the declaration that it points to,
439    /// create the corresponding import declaration.
440    pub(crate) fn new_import_decl(&self, decl: Decl<'ra>, import: Import<'ra>) -> Decl<'ra> {
441        let vis = self.import_decl_vis(decl, import.summary());
442
443        if let ImportKind::Glob { ref max_vis, .. } = import.kind
444            && (vis == import.vis
445                || max_vis.get().is_none_or(|max_vis| vis.greater_than(max_vis, self.tcx)))
446        {
447            max_vis.set_unchecked(Some(vis))
448        }
449
450        self.arenas.alloc_decl(DeclData {
451            kind: DeclKind::Import { source_decl: decl, import },
452            ambiguity: CmCell::new(None),
453            warn_ambiguity: CmCell::new(false),
454            span: import.span,
455            initial_vis: vis.to_def_id(),
456            ambiguity_vis_max: CmCell::new(None),
457            ambiguity_vis_min: CmCell::new(None),
458            expansion: import.parent_scope.expansion,
459            parent_module: Some(import.parent_scope.module),
460        })
461    }
462
463    /// If `glob_decl` attempts to overwrite `old_glob_decl` in a module,
464    /// decide which one to keep.
465    fn select_glob_decl(
466        &self,
467        old_glob_decl: Decl<'ra>,
468        glob_decl: Decl<'ra>,
469        warn_ambiguity: bool,
470    ) -> Decl<'ra> {
471        if !glob_decl.is_glob_import() {
    ::core::panicking::panic("assertion failed: glob_decl.is_glob_import()")
};assert!(glob_decl.is_glob_import());
472        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());
473        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);
474        // `best_decl` with a given key in a module may be overwritten in a
475        // number of cases (all of them can be seen below in the `match` in `try_define_local`),
476        // all these overwrites will be re-fetched by glob imports importing
477        // from that module without generating new ambiguities.
478        // - A glob decl is overwritten by a non-glob decl arriving later.
479        // - A glob decl is overwritten by its clone after setting ambiguity in it.
480        //   FIXME: avoid this by removing `warn_ambiguity`, or by triggering glob re-fetch
481        //   with the same decl in some way.
482        // - A glob decl is overwritten by a glob decl re-fetching an
483        //   overwritten decl from other module (the recursive case).
484        // Here we are detecting all such re-fetches and overwrite old decls
485        // with the re-fetched decls.
486        // This is probably incorrect in corner cases, and the outdated decls still get
487        // propagated to other places and get stuck there, but that's what we have at the moment.
488        let (old_deep_decl, deep_decl) = remove_same_import(old_glob_decl, glob_decl);
489        if deep_decl != glob_decl {
490            // Some import layers have been removed, need to overwrite.
491            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);
492            // FIXME: reenable the asserts when `warn_ambiguity` is removed (#149195).
493            // assert_ne!(old_deep_decl, deep_decl);
494            // assert!(old_deep_decl.is_glob_import());
495            if !!deep_decl.is_glob_import() {
    ::core::panicking::panic("assertion failed: !deep_decl.is_glob_import()")
};assert!(!deep_decl.is_glob_import());
496            if old_glob_decl.ambiguity.get().is_some() && glob_decl.ambiguity.get().is_none() {
497                // Do not lose glob ambiguities when re-fetching the glob.
498                glob_decl.ambiguity.set_unchecked(old_glob_decl.ambiguity.get());
499            }
500            if glob_decl.is_ambiguity_recursive() {
501                glob_decl.warn_ambiguity.set_unchecked(true);
502            }
503            glob_decl
504        } else if glob_decl.res() != old_glob_decl.res() {
505            old_glob_decl.ambiguity.set_unchecked(Some(glob_decl));
506            old_glob_decl.warn_ambiguity.set_unchecked(warn_ambiguity);
507            if warn_ambiguity {
508                old_glob_decl
509            } else {
510                // Need a fresh decl so other glob imports importing it could re-fetch it
511                // and set their own `warn_ambiguity` to true.
512                // FIXME: remove this when `warn_ambiguity` is removed (#149195).
513                self.arenas.alloc_decl((*old_glob_decl).clone())
514            }
515        } else if let old_vis = old_glob_decl.vis()
516            && let vis = glob_decl.vis()
517            && old_vis != vis
518        {
519            // We are glob-importing the same item but with a different visibility.
520            // All visibilities here are ordered because all of them are ancestors of `module`.
521            if vis.greater_than(old_vis, self.tcx) {
522                old_glob_decl.ambiguity_vis_max.set_unchecked(Some(glob_decl));
523            } else if let old_min_vis = old_glob_decl.min_vis()
524                && old_min_vis != vis
525                && old_min_vis.greater_than(vis, self.tcx)
526            {
527                old_glob_decl.ambiguity_vis_min.set_unchecked(Some(glob_decl));
528            }
529            old_glob_decl
530        } else if glob_decl.is_ambiguity_recursive() && !old_glob_decl.is_ambiguity_recursive() {
531            // Overwriting a non-ambiguous glob import with an ambiguous glob import.
532            old_glob_decl.ambiguity.set_unchecked(Some(glob_decl));
533            old_glob_decl.warn_ambiguity.set_unchecked(true);
534            old_glob_decl
535        } else {
536            old_glob_decl
537        }
538    }
539
540    /// Attempt to put the declaration with the given name and namespace into the module,
541    /// and return existing declaration if there is a collision.
542    pub(crate) fn try_plant_decl_into_local_module(
543        &mut self,
544        ident: IdentKey,
545        orig_ident_span: Span,
546        ns: Namespace,
547        decl: Decl<'ra>,
548        warn_ambiguity: bool,
549    ) -> Result<(), Decl<'ra>> {
550        if !!decl.warn_ambiguity.get() {
    ::core::panicking::panic("assertion failed: !decl.warn_ambiguity.get()")
};assert!(!decl.warn_ambiguity.get());
551        if !decl.ambiguity.get().is_none() {
    ::core::panicking::panic("assertion failed: decl.ambiguity.get().is_none()")
};assert!(decl.ambiguity.get().is_none());
552        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());
553        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());
554        let module = decl.parent_module.unwrap().expect_local();
555        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()));
556        let res = decl.res();
557        self.check_reserved_macro_name(ident.name, orig_ident_span, res);
558        // Even if underscore names cannot be looked up, we still need to add them to modules,
559        // because they can be fetched by glob imports from those modules, and bring traits
560        // into scope both directly and through glob imports.
561        let key = BindingKey::new_disambiguated(ident, ns, || {
562            module.underscore_disambiguator.update_unchecked(|d| d + 1);
563            module.underscore_disambiguator.get()
564        });
565        self.update_local_resolution(
566            module,
567            key,
568            orig_ident_span,
569            warn_ambiguity,
570            |this, resolution| {
571                if decl.is_glob_import() {
572                    resolution.glob_decl = Some(match resolution.glob_decl {
573                        Some(old_decl) => this.select_glob_decl(
574                            old_decl,
575                            decl,
576                            warn_ambiguity && resolution.non_glob_decl.is_none(),
577                        ),
578                        None => decl,
579                    })
580                } else {
581                    resolution.non_glob_decl = Some(match resolution.non_glob_decl {
582                        Some(old_decl) => return Err(old_decl),
583                        None => decl,
584                    })
585                }
586
587                Ok(())
588            },
589        )
590    }
591
592    // Use `f` to mutate the resolution of the name in the module.
593    // If the resolution becomes a success, define it in the module's glob importers.
594    fn update_local_resolution<T, F>(
595        &mut self,
596        module: LocalModule<'ra>,
597        key: BindingKey,
598        orig_ident_span: Span,
599        warn_ambiguity: bool,
600        f: F,
601    ) -> T
602    where
603        F: FnOnce(&Resolver<'ra, 'tcx>, &mut NameResolution<'ra>) -> T,
604    {
605        // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
606        // during which the resolution might end up getting re-defined via a glob cycle.
607        let (binding, t, warn_ambiguity) = {
608            let resolution = &mut *self
609                .resolution_or_default(module.to_module(), key, orig_ident_span)
610                .borrow_mut_unchecked();
611            let old_decl = resolution.determined_decl();
612            let old_vis = old_decl.map(|d| d.vis());
613
614            let t = f(self, resolution);
615
616            if let Some(binding) = resolution.determined_decl()
617                && (old_decl != Some(binding) || old_vis != Some(binding.vis()))
618            {
619                (binding, t, warn_ambiguity || old_decl.is_some())
620            } else {
621                return t;
622            }
623        };
624
625        let Ok(glob_importers) = module.glob_importers.try_borrow_mut_unchecked() else {
626            return t;
627        };
628
629        // Define or update `binding` in `module`s glob importers.
630        for import in glob_importers.iter() {
631            let mut ident = key.ident;
632            let scope = match ident
633                .ctxt
634                .update_unchecked(|ctxt| ctxt.reverse_glob_adjust(module.expansion, import.span))
635            {
636                Some(Some(def)) => self.expn_def_scope(def),
637                Some(None) => import.parent_scope.module,
638                None => continue,
639            };
640            if self.is_accessible_from(binding.vis(), scope) {
641                let import_decl = self.new_import_decl(binding, *import);
642                self.try_plant_decl_into_local_module(
643                    ident,
644                    orig_ident_span,
645                    key.ns,
646                    import_decl,
647                    warn_ambiguity,
648                )
649                .expect("planting a glob cannot fail");
650            }
651        }
652
653        t
654    }
655
656    // Define a dummy resolution containing a `Res::Err` as a placeholder for a failed
657    // or indeterminate resolution, also mark such failed imports as used to avoid duplicate diagnostics.
658    fn import_dummy_binding(&mut self, import: Import<'ra>, is_indeterminate: bool) {
659        if let ImportKind::Single { target, ref decls, .. } = import.kind {
660            if !(is_indeterminate || decls.iter().all(|d| d.get().decl().is_none())) {
661                return; // Has resolution, do not create the dummy binding
662            }
663            let dummy_decl = self.dummy_decl;
664            let dummy_decl = self.new_import_decl(dummy_decl, import);
665            self.per_ns(|this, ns| {
666                let ident = IdentKey::new(target);
667                // This can fail, dummies are inserted only in non-occupied slots.
668                let _ = this.try_plant_decl_into_local_module(
669                    ident,
670                    target.span,
671                    ns,
672                    dummy_decl,
673                    false,
674                );
675                // Don't remove underscores from `single_imports`, they were never added.
676                if target.name != kw::Underscore {
677                    let key = BindingKey::new(ident, ns);
678                    this.update_local_resolution(
679                        import.parent_scope.module.expect_local(),
680                        key,
681                        target.span,
682                        false,
683                        |_, resolution| {
684                            resolution.single_imports.swap_remove(&import);
685                        },
686                    )
687                }
688            });
689            self.record_use(target, dummy_decl, Used::Other);
690        } else if import.imported_module.get().is_none() {
691            self.import_use_map.insert(import, Used::Other);
692            if let Some(id) = import.id() {
693                self.used_imports.insert(id);
694            }
695        }
696    }
697
698    // Import resolution
699    //
700    // This is a fixed-point algorithm. We resolve imports until our efforts
701    // are stymied by an unresolved import; then we bail out of the current
702    // module and continue. We terminate successfully once no more imports
703    // remain or unsuccessfully when no forward progress in resolving imports
704    // is made.
705
706    /// Resolves all imports for the crate. This method performs the fixed-
707    /// point iteration.
708    pub(crate) fn resolve_imports(&mut self) {
709        let mut prev_indeterminate_count = usize::MAX;
710        let mut indeterminate_count = self.indeterminate_imports.len() * 3;
711        while indeterminate_count < prev_indeterminate_count {
712            prev_indeterminate_count = indeterminate_count;
713            indeterminate_count = 0;
714            self.assert_speculative = true;
715            for import in mem::take(&mut self.indeterminate_imports) {
716                let import_indeterminate_count = self.cm().resolve_import(import);
717                indeterminate_count += import_indeterminate_count;
718                match import_indeterminate_count {
719                    0 => self.determined_imports.push(import),
720                    _ => self.indeterminate_imports.push(import),
721                }
722            }
723            self.assert_speculative = false;
724        }
725    }
726
727    pub(crate) fn finalize_imports(&mut self) {
728        let mut module_children = Default::default();
729        let mut ambig_module_children = Default::default();
730        for module in &self.local_modules {
731            self.finalize_resolutions_in(*module, &mut module_children, &mut ambig_module_children);
732        }
733        self.module_children = module_children;
734        self.ambig_module_children = ambig_module_children;
735
736        let mut seen_spans = FxHashSet::default();
737        let mut errors = ::alloc::vec::Vec::new()vec![];
738        let mut prev_root_id: NodeId = NodeId::ZERO;
739        let determined_imports = mem::take(&mut self.determined_imports);
740        let indeterminate_imports = mem::take(&mut self.indeterminate_imports);
741
742        let mut glob_error = false;
743        for (is_indeterminate, import) in determined_imports
744            .iter()
745            .map(|i| (false, i))
746            .chain(indeterminate_imports.iter().map(|i| (true, i)))
747        {
748            let unresolved_import_error = self.finalize_import(*import);
749            // If this import is unresolved then create a dummy import
750            // resolution for it so that later resolve stages won't complain.
751            self.import_dummy_binding(*import, is_indeterminate);
752
753            let Some(err) = unresolved_import_error else { continue };
754
755            glob_error |= import.is_glob();
756
757            if let ImportKind::Single { source, ref decls, .. } = import.kind
758                && source.name == kw::SelfLower
759                // Silence `unresolved import` error if E0429 is already emitted
760                && let PendingDecl::Ready(None) = decls.value_ns.get()
761            {
762                continue;
763            }
764
765            if prev_root_id != NodeId::ZERO && prev_root_id != import.root_id && !errors.is_empty()
766            {
767                // In the case of a new import line, throw a diagnostic message
768                // for the previous line.
769                self.throw_unresolved_import_error(errors, glob_error);
770                errors = ::alloc::vec::Vec::new()vec![];
771            }
772            if seen_spans.insert(err.span) {
773                errors.push((*import, err));
774                prev_root_id = import.root_id;
775            }
776        }
777
778        if self.cstore().had_extern_crate_load_failure() {
779            self.tcx.sess.dcx().abort_if_errors();
780        }
781
782        if !errors.is_empty() {
783            self.throw_unresolved_import_error(errors, glob_error);
784            return;
785        }
786
787        for import in &indeterminate_imports {
788            let path = import_path_to_string(
789                &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
790                &import.kind,
791                import.span,
792            );
793            // FIXME: there should be a better way of doing this than
794            // formatting this as a string then checking for `::`
795            if path.contains("::") {
796                let err = UnresolvedImportError {
797                    span: import.span,
798                    label: None,
799                    note: None,
800                    suggestion: None,
801                    candidates: None,
802                    segment: None,
803                    module: None,
804                    on_unknown_attr: import.on_unknown_attr.clone(),
805                };
806                errors.push((*import, err))
807            }
808        }
809
810        if !errors.is_empty() {
811            self.throw_unresolved_import_error(errors, glob_error);
812        }
813    }
814
815    pub(crate) fn lint_reexports(&mut self, exported_ambiguities: FxHashSet<Decl<'ra>>) {
816        for module in &self.local_modules {
817            for (key, resolution) in self.resolutions(module.to_module()).borrow().iter() {
818                let resolution = resolution.borrow();
819                let Some(binding) = resolution.best_decl() else { continue };
820
821                // Report "cannot reexport" errors for exotic cases involving macros 2.0
822                // privacy bending or invariant-breaking code under deprecation lints.
823                for decl in [resolution.non_glob_decl, resolution.glob_decl] {
824                    if let Some(decl) = decl
825                        && let DeclKind::Import { source_decl, import } = decl.kind
826                        // FIXME: Do not check visibility-ambiguous imports for now. To check them
827                        // properly we need to preserve all imports in ambiguous glob sets and
828                        // check them all individually.
829                        && decl.ambiguity_vis_max.get().is_none()
830                    {
831                        // The source entity is too private to be reexported
832                        // with the given import declaration's visibility.
833                        let ord = source_decl.vis().partial_cmp(decl.vis(), self.tcx);
834                        if #[allow(non_exhaustive_omitted_patterns)] match ord {
    None | Some(Ordering::Less) => true,
    _ => false,
}matches!(ord, None | Some(Ordering::Less)) {
835                            let ident = match import.kind {
836                                ImportKind::Single { source, .. } => source,
837                                _ => key.ident.orig(resolution.orig_ident_span),
838                            };
839                            if let Some(lint) =
840                                self.report_cannot_reexport(import, source_decl, ident, key.ns)
841                            {
842                                self.lint_buffer.add_early_lint(lint);
843                            }
844                        }
845                    }
846                }
847
848                if let DeclKind::Import { import, .. } = binding.kind
849                    && let Some(amb_binding) = binding.ambiguity.get()
850                    && binding.res() != Res::Err
851                    && exported_ambiguities.contains(&binding)
852                {
853                    self.lint_buffer.buffer_lint(
854                        AMBIGUOUS_GLOB_REEXPORTS,
855                        import.root_id,
856                        import.root_span,
857                        errors::AmbiguousGlobReexports {
858                            name: key.ident.name.to_string(),
859                            namespace: key.ns.descr().to_string(),
860                            first_reexport: import.root_span,
861                            duplicate_reexport: amb_binding.span,
862                        },
863                    );
864                }
865
866                if let Some(glob_decl) = resolution.glob_decl
867                    && resolution.non_glob_decl.is_some()
868                {
869                    if binding.res() != Res::Err
870                        && glob_decl.res() != Res::Err
871                        && let DeclKind::Import { import: glob_import, .. } = glob_decl.kind
872                        && let Some(glob_import_def_id) = glob_import.def_id()
873                        && self.effective_visibilities.is_exported(glob_import_def_id)
874                        && glob_decl.vis().is_public()
875                        && !binding.vis().is_public()
876                    {
877                        let binding_id = match binding.kind {
878                            DeclKind::Def(res) => {
879                                Some(self.def_id_to_node_id(res.def_id().expect_local()))
880                            }
881                            DeclKind::Import { import, .. } => import.id(),
882                        };
883                        if let Some(binding_id) = binding_id {
884                            self.lint_buffer.buffer_lint(
885                                HIDDEN_GLOB_REEXPORTS,
886                                binding_id,
887                                binding.span,
888                                errors::HiddenGlobReexports {
889                                    name: key.ident.name.to_string(),
890                                    namespace: key.ns.descr().to_owned(),
891                                    glob_reexport: glob_decl.span,
892                                    private_item: binding.span,
893                                },
894                            );
895                        }
896                    }
897                }
898
899                if let DeclKind::Import { import, .. } = binding.kind
900                    && let Some(binding_id) = import.id()
901                    && let import_def_id = import.def_id().unwrap()
902                    && self.effective_visibilities.is_exported(import_def_id)
903                    && let Res::Def(reexported_kind, reexported_def_id) = binding.res()
904                    && !#[allow(non_exhaustive_omitted_patterns)] match reexported_kind {
    DefKind::Ctor(..) => true,
    _ => false,
}matches!(reexported_kind, DefKind::Ctor(..))
905                    && !reexported_def_id.is_local()
906                    && self.tcx.is_private_dep(reexported_def_id.krate)
907                {
908                    self.lint_buffer.buffer_lint(
909                        EXPORTED_PRIVATE_DEPENDENCIES,
910                        binding_id,
911                        binding.span,
912                        crate::errors::ReexportPrivateDependency {
913                            name: key.ident.name,
914                            kind: binding.res().descr(),
915                            krate: self.tcx.crate_name(reexported_def_id.krate),
916                        },
917                    );
918                }
919            }
920        }
921    }
922
923    fn throw_unresolved_import_error(
924        &mut self,
925        mut errors: Vec<(Import<'_>, UnresolvedImportError)>,
926        glob_error: bool,
927    ) {
928        errors.retain(|(_import, err)| match err.module {
929            // Skip `use` errors for `use foo::Bar;` if `foo.rs` has unrecovered parse errors.
930            Some(def_id) if self.mods_with_parse_errors.contains(&def_id) => false,
931            // If we've encountered something like `use _;`, we've already emitted an error stating
932            // that `_` is not a valid identifier, so we ignore that resolve error.
933            _ => err.segment != Some(kw::Underscore),
934        });
935        if errors.is_empty() {
936            self.tcx.dcx().delayed_bug("expected a parse or \"`_` can't be an identifier\" error");
937            return;
938        }
939
940        let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
941
942        let paths = errors
943            .iter()
944            .map(|(import, err)| {
945                let path = import_path_to_string(
946                    &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
947                    &import.kind,
948                    err.span,
949                );
950                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}`", path))
    })format!("`{path}`")
951            })
952            .collect::<Vec<_>>();
953        let default_message =
954            ::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(", "),);
955        let (message, label, notes) =
956            // Feature gating for `on_unknown_attr` happens initialization of the field
957            if let Some(directive) = errors[0].1.on_unknown_attr.as_ref().map(|a| &a.directive) {
958                let this = errors.iter().map(|(_import, err)| {
959
960                    // Is this unwrap_or reachable?
961                    err.segment.unwrap_or(kw::Underscore)
962                }).join(", ");
963
964                let args = FormatArgs {
965                    this,
966                    ..
967                };
968                let CustomDiagnostic { message, label, notes, .. } = directive.eval(None, &args);
969
970                (message, label, notes)
971            } else {
972                (None, None, Vec::new())
973            };
974        let has_custom_message = message.is_some();
975        let message = message.as_deref().unwrap_or(default_message.as_str());
976
977        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}");
978        if has_custom_message {
979            diag.note(default_message);
980        }
981
982        if !notes.is_empty() {
983            for note in notes {
984                diag.note(note);
985            }
986        } else if let Some((_, UnresolvedImportError { note: Some(note), .. })) =
987            errors.iter().last()
988        {
989            diag.note(note.clone());
990        }
991
992        /// Upper limit on the number of `span_label` messages.
993        const MAX_LABEL_COUNT: usize = 10;
994
995        for (import, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
996            if let Some(label) = &label {
997                diag.span_label(err.span, label.clone());
998            } else if let Some(label) = &err.label {
999                diag.span_label(err.span, label.clone());
1000            }
1001
1002            if let Some((suggestions, msg, applicability)) = err.suggestion {
1003                if suggestions.is_empty() {
1004                    diag.help(msg);
1005                    continue;
1006                }
1007                diag.multipart_suggestion(msg, suggestions, applicability);
1008            }
1009
1010            if let Some(candidates) = &err.candidates {
1011                match &import.kind {
1012                    ImportKind::Single { nested: false, source, target, .. } => import_candidates(
1013                        self.tcx,
1014                        &mut diag,
1015                        Some(err.span),
1016                        candidates,
1017                        DiagMode::Import { append: false, unresolved_import: true },
1018                        (source != target)
1019                            .then(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" as {0}", target))
    })format!(" as {target}"))
1020                            .as_deref()
1021                            .unwrap_or(""),
1022                    ),
1023                    ImportKind::Single { nested: true, source, target, .. } => {
1024                        import_candidates(
1025                            self.tcx,
1026                            &mut diag,
1027                            None,
1028                            candidates,
1029                            DiagMode::Normal,
1030                            (source != target)
1031                                .then(|| ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!(" as {0}", target))
    })format!(" as {target}"))
1032                                .as_deref()
1033                                .unwrap_or(""),
1034                        );
1035                    }
1036                    _ => {}
1037                }
1038            }
1039
1040            if #[allow(non_exhaustive_omitted_patterns)] match import.kind {
    ImportKind::Single { .. } => true,
    _ => false,
}matches!(import.kind, ImportKind::Single { .. })
1041                && let Some(segment) = err.segment
1042                && let Some(module) = err.module
1043            {
1044                self.find_cfg_stripped(&mut diag, &segment, module)
1045            }
1046        }
1047
1048        let guar = diag.emit();
1049        if glob_error {
1050            self.glob_error = Some(guar);
1051        }
1052    }
1053
1054    /// Attempts to resolve the given import, returning:
1055    /// - `0` means its resolution is determined.
1056    /// - Other values mean that indeterminate exists under certain namespaces.
1057    ///
1058    /// Meanwhile, if resolve successful, the resolved bindings are written
1059    /// into the module.
1060    fn resolve_import<'r>(mut self: CmResolver<'r, 'ra, 'tcx>, import: Import<'ra>) -> usize {
1061        {
    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:1061",
                        "rustc_resolve::imports", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/imports.rs"),
                        ::tracing_core::__macro_support::Option::Some(1061u32),
                        ::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!(
1062            "(resolving import for module) resolving import `{}::...` in `{}`",
1063            Segment::names_to_string(&import.module_path),
1064            module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
1065        );
1066        let module = if let Some(module) = import.imported_module.get() {
1067            module
1068        } else {
1069            let path_res = self.reborrow().maybe_resolve_path(
1070                &import.module_path,
1071                None,
1072                &import.parent_scope,
1073                Some(import),
1074            );
1075
1076            match path_res {
1077                PathResult::Module(module) => module,
1078                PathResult::Indeterminate => return 3,
1079                PathResult::NonModule(..) | PathResult::Failed { .. } => return 0,
1080            }
1081        };
1082
1083        import.imported_module.set_unchecked(Some(module));
1084        let (source, target, bindings) = match import.kind {
1085            ImportKind::Single { source, target, ref decls, .. } => (source, target, decls),
1086            ImportKind::Glob { .. } => {
1087                self.get_mut_unchecked().resolve_glob_import(import);
1088                return 0;
1089            }
1090            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1091        };
1092
1093        let mut indeterminate_count = 0;
1094        self.per_ns_cm(|mut this, ns| {
1095            if bindings[ns].get() != PendingDecl::Pending {
1096                return;
1097            };
1098            let binding_result = this.reborrow().maybe_resolve_ident_in_module(
1099                module,
1100                source,
1101                ns,
1102                &import.parent_scope,
1103                Some(import),
1104            );
1105            let parent = import.parent_scope.module;
1106            let binding = match binding_result {
1107                Ok(binding) => {
1108                    if binding.is_assoc_item()
1109                        && !this.tcx.features().import_trait_associated_functions()
1110                    {
1111                        feature_err(
1112                            this.tcx.sess,
1113                            sym::import_trait_associated_functions,
1114                            import.span,
1115                            "`use` associated items of traits is unstable",
1116                        )
1117                        .emit();
1118                    }
1119                    // We need the `target`, `source` can be extracted.
1120                    let import_decl = this.new_import_decl(binding, import);
1121                    this.get_mut_unchecked().plant_decl_into_local_module(
1122                        IdentKey::new(target),
1123                        target.span,
1124                        ns,
1125                        import_decl,
1126                    );
1127                    PendingDecl::Ready(Some(import_decl))
1128                }
1129                Err(Determinacy::Determined) => {
1130                    // Don't remove underscores from `single_imports`, they were never added.
1131                    if target.name != kw::Underscore {
1132                        let key = BindingKey::new(IdentKey::new(target), ns);
1133                        this.get_mut_unchecked().update_local_resolution(
1134                            parent.expect_local(),
1135                            key,
1136                            target.span,
1137                            false,
1138                            |_, resolution| {
1139                                resolution.single_imports.swap_remove(&import);
1140                            },
1141                        );
1142                    }
1143                    PendingDecl::Ready(None)
1144                }
1145                Err(Determinacy::Undetermined) => {
1146                    indeterminate_count += 1;
1147                    PendingDecl::Pending
1148                }
1149            };
1150            bindings[ns].set_unchecked(binding);
1151        });
1152
1153        indeterminate_count
1154    }
1155
1156    /// Performs final import resolution, consistency checks and error reporting.
1157    ///
1158    /// Optionally returns an unresolved import error. This error is buffered and used to
1159    /// consolidate multiple unresolved import errors into a single diagnostic.
1160    fn finalize_import(&mut self, import: Import<'ra>) -> Option<UnresolvedImportError> {
1161        let ignore_decl = match &import.kind {
1162            ImportKind::Single { decls, .. } => decls[TypeNS].get().decl(),
1163            _ => None,
1164        };
1165        let ambiguity_errors_len = |errors: &Vec<AmbiguityError<'_>>| {
1166            errors.iter().filter(|error| error.warning.is_none()).count()
1167        };
1168        let prev_ambiguity_errors_len = ambiguity_errors_len(&self.ambiguity_errors);
1169        let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
1170
1171        // We'll provide more context to the privacy errors later, up to `len`.
1172        let privacy_errors_len = self.privacy_errors.len();
1173
1174        let path_res = self.cm().resolve_path(
1175            &import.module_path,
1176            None,
1177            &import.parent_scope,
1178            Some(finalize),
1179            ignore_decl,
1180            Some(import),
1181        );
1182
1183        let no_ambiguity =
1184            ambiguity_errors_len(&self.ambiguity_errors) == prev_ambiguity_errors_len;
1185
1186        let module = match path_res {
1187            PathResult::Module(module) => {
1188                // Consistency checks, analogous to `finalize_macro_resolutions`.
1189                if let Some(initial_module) = import.imported_module.get() {
1190                    if module != initial_module && no_ambiguity && !self.issue_145575_hack_applied {
1191                        ::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");
1192                    }
1193                } else if self.privacy_errors.is_empty() {
1194                    self.dcx()
1195                        .create_err(CannotDetermineImportResolution { span: import.span })
1196                        .emit();
1197                }
1198
1199                module
1200            }
1201            PathResult::Failed {
1202                is_error_from_last_segment: false,
1203                span,
1204                segment_name,
1205                label,
1206                suggestion,
1207                module,
1208                error_implied_by_parse_error: _,
1209                message,
1210                note: _,
1211            } => {
1212                if no_ambiguity {
1213                    if !self.issue_145575_hack_applied {
1214                        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());
1215                    }
1216                    self.report_error(
1217                        span,
1218                        ResolutionError::FailedToResolve {
1219                            segment: segment_name,
1220                            label,
1221                            suggestion,
1222                            module,
1223                            message,
1224                        },
1225                    );
1226                }
1227                return None;
1228            }
1229            PathResult::Failed {
1230                is_error_from_last_segment: true,
1231                span,
1232                label,
1233                suggestion,
1234                module,
1235                segment_name,
1236                note,
1237                ..
1238            } => {
1239                if no_ambiguity {
1240                    if !self.issue_145575_hack_applied {
1241                        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());
1242                    }
1243                    let module = if let Some(ModuleOrUniformRoot::Module(m)) = module {
1244                        m.opt_def_id()
1245                    } else {
1246                        None
1247                    };
1248                    let err = match self
1249                        .make_path_suggestion(import.module_path.clone(), &import.parent_scope)
1250                    {
1251                        Some((suggestion, note)) => UnresolvedImportError {
1252                            span,
1253                            label: None,
1254                            note,
1255                            suggestion: Some((
1256                                ::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))],
1257                                String::from("a similar path exists"),
1258                                Applicability::MaybeIncorrect,
1259                            )),
1260                            candidates: None,
1261                            segment: Some(segment_name),
1262                            module,
1263                            on_unknown_attr: import.on_unknown_attr.clone(),
1264                        },
1265                        None => UnresolvedImportError {
1266                            span,
1267                            label: Some(label),
1268                            note,
1269                            suggestion,
1270                            candidates: None,
1271                            segment: Some(segment_name),
1272                            module,
1273                            on_unknown_attr: import.on_unknown_attr.clone(),
1274                        },
1275                    };
1276                    return Some(err);
1277                }
1278                return None;
1279            }
1280            PathResult::NonModule(partial_res) => {
1281                if no_ambiguity && partial_res.full_res() != Some(Res::Err) {
1282                    // Check if there are no ambiguities and the result is not dummy.
1283                    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());
1284                }
1285                // The error was already reported earlier.
1286                return None;
1287            }
1288            PathResult::Indeterminate => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1289        };
1290
1291        let (ident, target, bindings, import_id) = match import.kind {
1292            ImportKind::Single { source, target, ref decls, id, .. } => (source, target, decls, id),
1293            ImportKind::Glob { ref max_vis, id, def_id } => {
1294                if import.module_path.len() <= 1 {
1295                    // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1296                    // 2 segments, so the `resolve_path` above won't trigger it.
1297                    let mut full_path = import.module_path.clone();
1298                    full_path.push(Segment::from_ident(Ident::dummy()));
1299                    self.lint_if_path_starts_with_module(finalize, &full_path, None);
1300                }
1301
1302                if let ModuleOrUniformRoot::Module(module) = module
1303                    && module == import.parent_scope.module
1304                {
1305                    // Importing a module into itself is not allowed.
1306                    return Some(UnresolvedImportError {
1307                        span: import.span,
1308                        label: Some(String::from("cannot glob-import a module into itself")),
1309                        note: None,
1310                        suggestion: None,
1311                        candidates: None,
1312                        segment: None,
1313                        module: None,
1314                        on_unknown_attr: None,
1315                    });
1316                }
1317                if let Some(max_vis) = max_vis.get()
1318                    && import.vis.greater_than(max_vis, self.tcx)
1319                {
1320                    self.lint_buffer.buffer_lint(
1321                        UNUSED_IMPORTS,
1322                        id,
1323                        import.span,
1324                        crate::errors::RedundantImportVisibility {
1325                            span: import.span,
1326                            help: (),
1327                            max_vis: max_vis.to_string(def_id, self.tcx),
1328                            import_vis: import.vis.to_string(def_id, self.tcx),
1329                        },
1330                    );
1331                }
1332                return None;
1333            }
1334            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1335        };
1336
1337        if self.privacy_errors.len() != privacy_errors_len {
1338            // Get the Res for the last element, so that we can point to alternative ways of
1339            // importing it if available.
1340            let mut path = import.module_path.clone();
1341            path.push(Segment::from_ident(ident));
1342            if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.cm().resolve_path(
1343                &path,
1344                None,
1345                &import.parent_scope,
1346                Some(finalize),
1347                ignore_decl,
1348                None,
1349            ) {
1350                let res = module.res().map(|r| (r, ident));
1351                for error in &mut self.privacy_errors[privacy_errors_len..] {
1352                    error.outermost_res = res;
1353                }
1354            } else {
1355                // The final item is not a module (e.g., a struct, function, or macro).
1356                // Resolve it directly in the parent module to get its Res, so
1357                // `report_privacy_error()` can search for public re-export paths.
1358                for ns in [TypeNS, ValueNS, MacroNS] {
1359                    if let Ok(binding) = self.cm().resolve_ident_in_module(
1360                        module,
1361                        ident,
1362                        ns,
1363                        &import.parent_scope,
1364                        None,
1365                        ignore_decl,
1366                        None,
1367                    ) {
1368                        let res = binding.res();
1369                        for error in &mut self.privacy_errors[privacy_errors_len..] {
1370                            error.outermost_res = Some((res, ident));
1371                        }
1372                        break;
1373                    }
1374                }
1375            }
1376        }
1377
1378        let mut all_ns_err = true;
1379        self.per_ns(|this, ns| {
1380            let binding = this.cm().resolve_ident_in_module(
1381                module,
1382                ident,
1383                ns,
1384                &import.parent_scope,
1385                Some(Finalize {
1386                    report_private: false,
1387                    import: Some(import.summary()),
1388                    ..finalize
1389                }),
1390                bindings[ns].get().decl(),
1391                Some(import),
1392            );
1393
1394            match binding {
1395                Ok(binding) => {
1396                    // Consistency checks, analogous to `finalize_macro_resolutions`.
1397                    let initial_res = bindings[ns].get().decl().map(|binding| {
1398                        let initial_binding = binding.import_source();
1399                        all_ns_err = false;
1400                        if target.name == kw::Underscore
1401                            && initial_binding.is_extern_crate()
1402                            && !initial_binding.is_import()
1403                        {
1404                            let used = if import.module_path.is_empty() {
1405                                Used::Scope
1406                            } else {
1407                                Used::Other
1408                            };
1409                            this.record_use(ident, binding, used);
1410                        }
1411                        initial_binding.res()
1412                    });
1413                    let res = binding.res();
1414                    let has_ambiguity_error =
1415                        this.ambiguity_errors.iter().any(|error| error.warning.is_none());
1416                    if res == Res::Err || has_ambiguity_error {
1417                        this.dcx()
1418                            .span_delayed_bug(import.span, "some error happened for an import");
1419                        return;
1420                    }
1421                    if let Some(initial_res) = initial_res {
1422                        if res != initial_res && !this.issue_145575_hack_applied {
1423                            ::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");
1424                        }
1425                    } else if this.privacy_errors.is_empty() {
1426                        this.dcx()
1427                            .create_err(CannotDetermineImportResolution { span: import.span })
1428                            .emit();
1429                    }
1430                }
1431                Err(..) => {
1432                    // FIXME: This assert may fire if public glob is later shadowed by a private
1433                    // single import (see test `issue-55884-2.rs`). In theory single imports should
1434                    // always block globs, even if they are not yet resolved, so that this kind of
1435                    // self-inconsistent resolution never happens.
1436                    // Re-enable the assert when the issue is fixed.
1437                    // assert!(result[ns].get().is_err());
1438                }
1439            }
1440        });
1441
1442        if all_ns_err {
1443            let mut all_ns_failed = true;
1444            self.per_ns(|this, ns| {
1445                let binding = this.cm().resolve_ident_in_module(
1446                    module,
1447                    ident,
1448                    ns,
1449                    &import.parent_scope,
1450                    Some(finalize),
1451                    None,
1452                    None,
1453                );
1454                if binding.is_ok() {
1455                    all_ns_failed = false;
1456                }
1457            });
1458
1459            return if all_ns_failed {
1460                let names = match module {
1461                    ModuleOrUniformRoot::Module(module) => {
1462                        self.resolutions(module)
1463                            .borrow()
1464                            .iter()
1465                            .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1466                                if i.name == ident.name {
1467                                    return None;
1468                                } // Never suggest the same name
1469                                if i.name == kw::Underscore {
1470                                    return None;
1471                                } // `use _` is never valid
1472
1473                                let resolution = resolution.borrow();
1474                                if let Some(name_binding) = resolution.best_decl() {
1475                                    match name_binding.kind {
1476                                        DeclKind::Import { source_decl, .. } => {
1477                                            match source_decl.kind {
1478                                                // Never suggest names that previously could not
1479                                                // be resolved.
1480                                                DeclKind::Def(Res::Err) => None,
1481                                                _ => Some(i.name),
1482                                            }
1483                                        }
1484                                        _ => Some(i.name),
1485                                    }
1486                                } else if resolution.single_imports.is_empty() {
1487                                    None
1488                                } else {
1489                                    Some(i.name)
1490                                }
1491                            })
1492                            .collect()
1493                    }
1494                    _ => Vec::new(),
1495                };
1496
1497                let lev_suggestion =
1498                    find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
1499                        (
1500                            ::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())],
1501                            String::from("a similar name exists in the module"),
1502                            Applicability::MaybeIncorrect,
1503                        )
1504                    });
1505
1506                let (suggestion, note) =
1507                    match self.check_for_module_export_macro(import, module, ident) {
1508                        Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1509                        _ => (lev_suggestion, None),
1510                    };
1511
1512                // If importing of trait asscoiated items is enabled, an also find an
1513                // `Enum`, then note that inherent associated items cannot be imported.
1514                let note = if self.tcx.features().import_trait_associated_functions()
1515                    && let PathResult::Module(ModuleOrUniformRoot::Module(m)) = path_res
1516                    && let Some(Res::Def(DefKind::Enum, _)) = m.res()
1517                {
1518                    note.or(Some(
1519                        "cannot import inherent associated items, only trait associated items"
1520                            .to_string(),
1521                    ))
1522                } else {
1523                    note
1524                };
1525
1526                let label = match module {
1527                    ModuleOrUniformRoot::Module(module) => {
1528                        let module_str = module_to_string(module);
1529                        if let Some(module_str) = module_str {
1530                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no `{0}` in `{1}`", ident,
                module_str))
    })format!("no `{ident}` in `{module_str}`")
1531                        } else {
1532                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
    })format!("no `{ident}` in the root")
1533                        }
1534                    }
1535                    _ => {
1536                        if !ident.is_path_segment_keyword() {
1537                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no external crate `{0}`", ident))
    })format!("no external crate `{ident}`")
1538                        } else {
1539                            // HACK(eddyb) this shows up for `self` & `super`, which
1540                            // should work instead - for now keep the same error message.
1541                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
    })format!("no `{ident}` in the root")
1542                        }
1543                    }
1544                };
1545
1546                let parent_suggestion =
1547                    self.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true);
1548
1549                Some(UnresolvedImportError {
1550                    span: import.span,
1551                    label: Some(label),
1552                    note,
1553                    suggestion,
1554                    candidates: if !parent_suggestion.is_empty() {
1555                        Some(parent_suggestion)
1556                    } else {
1557                        None
1558                    },
1559                    module: import.imported_module.get().and_then(|module| {
1560                        if let ModuleOrUniformRoot::Module(m) = module {
1561                            m.opt_def_id()
1562                        } else {
1563                            None
1564                        }
1565                    }),
1566                    segment: Some(ident.name),
1567                    on_unknown_attr: import.on_unknown_attr.clone(),
1568                })
1569            } else {
1570                // `resolve_ident_in_module` reported a privacy error.
1571                None
1572            };
1573        }
1574
1575        let mut reexport_error = None;
1576        let mut any_successful_reexport = false;
1577        self.per_ns(|this, ns| {
1578            let Some(binding) = bindings[ns].get().decl() else {
1579                return;
1580            };
1581
1582            if import.vis.greater_than(binding.vis(), this.tcx) {
1583                // In isolation, a declaration like this is not an error, but if *all* 1-3
1584                // declarations introduced by the import are more private than the import item's
1585                // nominal visibility, then it's an error.
1586                reexport_error = Some((ns, binding.import_source()));
1587            } else {
1588                any_successful_reexport = true;
1589            }
1590        });
1591
1592        if !any_successful_reexport {
1593            let (ns, binding) = reexport_error.unwrap();
1594            if let Some(lint) = self.report_cannot_reexport(import, binding, ident, ns) {
1595                self.lint_buffer.add_early_lint(lint);
1596            }
1597        }
1598
1599        if import.module_path.len() <= 1 {
1600            // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1601            // 2 segments, so the `resolve_path` above won't trigger it.
1602            let mut full_path = import.module_path.clone();
1603            full_path.push(Segment::from_ident(ident));
1604            self.per_ns(|this, ns| {
1605                if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1606                    this.lint_if_path_starts_with_module(finalize, &full_path, Some(binding));
1607                }
1608            });
1609        }
1610
1611        // Record what this import resolves to for later uses in documentation,
1612        // this may resolve to either a value or a type, but for documentation
1613        // purposes it's good enough to just favor one over the other.
1614        self.per_ns(|this, ns| {
1615            if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1616                this.import_res_map.entry(import_id).or_default()[ns] = Some(binding.res());
1617            }
1618        });
1619
1620        {
    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:1620",
                        "rustc_resolve::imports", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/imports.rs"),
                        ::tracing_core::__macro_support::Option::Some(1620u32),
                        ::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");
1621        None
1622    }
1623
1624    fn report_cannot_reexport(
1625        &self,
1626        import: Import<'ra>,
1627        decl: Decl<'ra>,
1628        ident: Ident,
1629        ns: Namespace,
1630    ) -> Option<BufferedEarlyLint> {
1631        let crate_private_reexport = match decl.vis() {
1632            Visibility::Restricted(def_id) if def_id.is_top_level_module() => true,
1633            _ => false,
1634        };
1635
1636        if let Some(extern_crate_id) = pub_use_of_private_extern_crate_hack(import.summary(), decl)
1637        {
1638            let ImportKind::Single { id, .. } = import.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
1639            let sugg = self.tcx.source_span(extern_crate_id).shrink_to_lo();
1640            let diagnostic = crate::errors::PrivateExternCrateReexport { ident, sugg };
1641            return Some(BufferedEarlyLint {
1642                lint_id: LintId::of(PUB_USE_OF_PRIVATE_EXTERN_CRATE),
1643                node_id: id,
1644                span: Some(import.span.into()),
1645                diagnostic: diagnostic.into(),
1646            });
1647        } else if ns == TypeNS {
1648            let err = if crate_private_reexport {
1649                self.dcx().create_err(CannotBeReexportedCratePublicNS { span: import.span, ident })
1650            } else {
1651                self.dcx().create_err(CannotBeReexportedPrivateNS { span: import.span, ident })
1652            };
1653            err.emit();
1654        } else {
1655            let mut err = if crate_private_reexport {
1656                self.dcx().create_err(CannotBeReexportedCratePublic { span: import.span, ident })
1657            } else {
1658                self.dcx().create_err(CannotBeReexportedPrivate { span: import.span, ident })
1659            };
1660
1661            match decl.kind {
1662                // exclude decl_macro
1663                DeclKind::Def(Res::Def(DefKind::Macro(_), def_id))
1664                    if let SyntaxExtensionKind::MacroRules(mr) =
1665                        &self.get_macro_by_def_id(def_id).kind
1666                        && mr.is_macro_rules() =>
1667                {
1668                    err.subdiagnostic(ConsiderAddingMacroExport { span: decl.span });
1669                    err.subdiagnostic(ConsiderMarkingAsPubCrate { vis_span: import.vis_span });
1670                }
1671                _ => {
1672                    err.subdiagnostic(ConsiderMarkingAsPub { span: import.span, ident });
1673                }
1674            }
1675            err.emit();
1676        }
1677
1678        None
1679    }
1680
1681    pub(crate) fn check_for_redundant_imports(&mut self, import: Import<'ra>) -> bool {
1682        // This function is only called for single imports.
1683        let ImportKind::Single { source, target, ref decls, id, def_id, .. } = import.kind else {
1684            ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1685        };
1686
1687        // Skip if the import is of the form `use source as target` and source != target.
1688        if source != target {
1689            return false;
1690        }
1691
1692        // Skip if the import was produced by a macro.
1693        if import.parent_scope.expansion != LocalExpnId::ROOT {
1694            return false;
1695        }
1696
1697        // Skip if we are inside a named module (in contrast to an anonymous
1698        // module defined by a block).
1699        // Skip if the import is public or was used through non scope-based resolution,
1700        // e.g. through a module-relative path.
1701        if self.import_use_map.get(&import) == Some(&Used::Other)
1702            || self.effective_visibilities.is_exported(def_id)
1703        {
1704            return false;
1705        }
1706
1707        let mut is_redundant = true;
1708        let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1709        self.per_ns(|this, ns| {
1710            let binding = decls[ns].get().decl().map(|b| b.import_source());
1711            if is_redundant && let Some(binding) = binding {
1712                if binding.res() == Res::Err {
1713                    return;
1714                }
1715
1716                match this.cm().resolve_ident_in_scope_set(
1717                    target,
1718                    ScopeSet::All(ns),
1719                    &import.parent_scope,
1720                    None,
1721                    decls[ns].get().decl(),
1722                    None,
1723                ) {
1724                    Ok(other_binding) => {
1725                        is_redundant = binding.res() == other_binding.res()
1726                            && !other_binding.is_ambiguity_recursive();
1727                        if is_redundant {
1728                            redundant_span[ns] =
1729                                Some((other_binding.span, other_binding.is_import()));
1730                        }
1731                    }
1732                    Err(_) => is_redundant = false,
1733                }
1734            }
1735        });
1736
1737        if is_redundant && !redundant_span.is_empty() {
1738            let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1739            redundant_spans.sort();
1740            redundant_spans.dedup();
1741            self.lint_buffer.dyn_buffer_lint(
1742                REDUNDANT_IMPORTS,
1743                id,
1744                import.span,
1745                move |dcx, level| {
1746                    let ident = source;
1747                    let subs = redundant_spans
1748                        .into_iter()
1749                        .map(|(span, is_imported)| match (span.is_dummy(), is_imported) {
1750                            (false, true) => {
1751                                errors::RedundantImportSub::ImportedHere { span, ident }
1752                            }
1753                            (false, false) => {
1754                                errors::RedundantImportSub::DefinedHere { span, ident }
1755                            }
1756                            (true, true) => {
1757                                errors::RedundantImportSub::ImportedPrelude { span, ident }
1758                            }
1759                            (true, false) => {
1760                                errors::RedundantImportSub::DefinedPrelude { span, ident }
1761                            }
1762                        })
1763                        .collect();
1764                    errors::RedundantImport { subs, ident }.into_diag(dcx, level)
1765                },
1766            );
1767            return true;
1768        }
1769
1770        false
1771    }
1772
1773    fn resolve_glob_import(&mut self, import: Import<'ra>) {
1774        // This function is only called for glob imports.
1775        let ImportKind::Glob { id, .. } = import.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
1776
1777        let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else {
1778            self.dcx().emit_err(CannotGlobImportAllCrates { span: import.span });
1779            return;
1780        };
1781
1782        if module.is_trait() && !self.tcx.features().import_trait_associated_functions() {
1783            feature_err(
1784                self.tcx.sess,
1785                sym::import_trait_associated_functions,
1786                import.span,
1787                "`use` associated items of traits is unstable",
1788            )
1789            .emit();
1790        }
1791
1792        if module == import.parent_scope.module {
1793            return;
1794        }
1795
1796        // Add to module's glob_importers
1797        if module.is_local() {
1798            module.glob_importers.borrow_mut_unchecked().push(import);
1799        }
1800
1801        // Ensure that `resolutions` isn't borrowed during `try_define`,
1802        // since it might get updated via a glob cycle.
1803        let bindings = self
1804            .resolutions(module)
1805            .borrow()
1806            .iter()
1807            .filter_map(|(key, resolution)| {
1808                let resolution = resolution.borrow();
1809                resolution.determined_decl().map(|decl| (*key, decl, resolution.orig_ident_span))
1810            })
1811            .collect::<Vec<_>>();
1812        for (mut key, binding, orig_ident_span) in bindings {
1813            let scope =
1814                match key.ident.ctxt.update_unchecked(|ctxt| {
1815                    ctxt.reverse_glob_adjust(module.expansion, import.span)
1816                }) {
1817                    Some(Some(def)) => self.expn_def_scope(def),
1818                    Some(None) => import.parent_scope.module,
1819                    None => continue,
1820                };
1821            if self.is_accessible_from(binding.vis(), scope) {
1822                let import_decl = self.new_import_decl(binding, import);
1823                let warn_ambiguity = self
1824                    .resolution(import.parent_scope.module, key)
1825                    .and_then(|r| r.determined_decl())
1826                    .is_some_and(|binding| binding.warn_ambiguity_recursive());
1827                self.try_plant_decl_into_local_module(
1828                    key.ident,
1829                    orig_ident_span,
1830                    key.ns,
1831                    import_decl,
1832                    warn_ambiguity,
1833                )
1834                .expect("planting a glob cannot fail");
1835            }
1836        }
1837
1838        // Record the destination of this import
1839        self.record_partial_res(id, PartialRes::new(module.res().unwrap()));
1840    }
1841
1842    // Miscellaneous post-processing, including recording re-exports,
1843    // reporting conflicts, and reporting unresolved imports.
1844    fn finalize_resolutions_in(
1845        &self,
1846        module: LocalModule<'ra>,
1847        module_children: &mut LocalDefIdMap<Vec<ModChild>>,
1848        ambig_module_children: &mut LocalDefIdMap<Vec<AmbigModChild>>,
1849    ) {
1850        // Since import resolution is finished, globs will not define any more names.
1851        *module.globs.borrow_mut(self) = Vec::new();
1852
1853        let Some(def_id) = module.opt_def_id() else { return };
1854
1855        let mut children = Vec::new();
1856        let mut ambig_children = Vec::new();
1857
1858        module.to_module().for_each_child(self, |_this, ident, orig_ident_span, _, binding| {
1859            let res = binding.res().expect_non_local();
1860            if res != def::Res::Err {
1861                let ident = ident.orig(orig_ident_span);
1862                let child =
1863                    |reexport_chain| ModChild { ident, res, vis: binding.vis(), reexport_chain };
1864                if let Some((ambig_binding1, ambig_binding2)) = binding.descent_to_ambiguity() {
1865                    let main = child(ambig_binding1.reexport_chain());
1866                    let second = ModChild {
1867                        ident,
1868                        res: ambig_binding2.res().expect_non_local(),
1869                        vis: ambig_binding2.vis(),
1870                        reexport_chain: ambig_binding2.reexport_chain(),
1871                    };
1872                    ambig_children.push(AmbigModChild { main, second })
1873                } else {
1874                    children.push(child(binding.reexport_chain()));
1875                }
1876            }
1877        });
1878
1879        if !children.is_empty() {
1880            module_children.insert(def_id.expect_local(), children);
1881        }
1882        if !ambig_children.is_empty() {
1883            ambig_module_children.insert(def_id.expect_local(), ambig_children);
1884        }
1885    }
1886}
1887
1888fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
1889    let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1890    let global = !names.is_empty() && names[0].name == kw::PathRoot;
1891    if let Some(pos) = pos {
1892        let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1893        names_to_string(names.iter().map(|ident| ident.name))
1894    } else {
1895        let names = if global { &names[1..] } else { names };
1896        if names.is_empty() {
1897            import_kind_to_string(import_kind)
1898        } else {
1899            ::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!(
1900                "{}::{}",
1901                names_to_string(names.iter().map(|ident| ident.name)),
1902                import_kind_to_string(import_kind),
1903            )
1904        }
1905    }
1906}
1907
1908fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1909    match import_kind {
1910        ImportKind::Single { source, .. } => source.to_string(),
1911        ImportKind::Glob { .. } => "*".to_string(),
1912        ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1913        ImportKind::MacroUse { .. } => "#[macro_use]".to_string(),
1914        ImportKind::MacroExport => "#[macro_export]".to_string(),
1915    }
1916}