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