Skip to main content

rustc_resolve/
imports.rs

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