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(import_decl)) => {
825                                if import_decl.is_assoc_item()
826                                    && !this.features.import_trait_associated_functions()
827                                {
828                                    feature_err(
829                                        this.tcx.sess,
830                                        sym::import_trait_associated_functions,
831                                        import.span,
832                                        "`use` associated items of traits is unstable",
833                                    )
834                                    .emit();
835                                }
836                                this.plant_decl_into_local_module(
837                                    IdentKey::new(*target),
838                                    target.span,
839                                    ns,
840                                    import_decl,
841                                );
842                                decls[ns].set(PendingDecl::Ready(Some(import_decl)), this);
843                            }
844                            PendingDecl::Ready(None) => {
845                                // Don't remove underscores from `single_imports`, they were never added.
846                                if target.name != kw::Underscore {
847                                    let key = BindingKey::new(IdentKey::new(*target), ns);
848                                    this.update_local_resolution(
849                                        import.parent_scope.module.expect_local(),
850                                        key,
851                                        target.span,
852                                        |_, resolution| {
853                                            resolution.single_imports.swap_remove(&import);
854                                        },
855                                    );
856                                }
857                                decls[ns].set(PendingDecl::Ready(None), this);
858                            }
859                            PendingDecl::Pending => {}
860                        }
861                    });
862                }
863                (ImportKind::Glob { id, .. }, ImportResolutionKind::Glob(imported_decls)) => {
864                    let ModuleOrUniformRoot::Module(module) = imported_module else {
865                        self.dcx().emit_err(CannotGlobImportAllCrates { span: import.span });
866                        continue;
867                    };
868
869                    if module.is_trait() && !self.features.import_trait_associated_functions() {
870                        feature_err(
871                            self.tcx.sess,
872                            sym::import_trait_associated_functions,
873                            import.span,
874                            "`use` associated items of traits is unstable",
875                        )
876                        .emit();
877                    }
878
879                    for (binding, key, orig_ident_span) in imported_decls {
880                        let import_decl = self.new_import_decl(binding, import);
881                        let _ = self
882                            .try_plant_decl_into_local_module(
883                                key.ident,
884                                orig_ident_span,
885                                key.ns,
886                                import_decl,
887                            )
888                            .expect("planting a glob cannot fail");
889                    }
890
891                    self.record_partial_res(*id, PartialRes::new(module.res().unwrap()));
892                }
893
894                // Something weird happened, which shouldn't have happened.
895                _ => {
    ::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"),
896            }
897        }
898    }
899
900    pub(crate) fn finalize_imports(&mut self) {
901        let mut module_children = Default::default();
902        let mut ambig_module_children = Default::default();
903        for module in &self.local_modules {
904            self.finalize_resolutions_in(*module, &mut module_children, &mut ambig_module_children);
905        }
906        self.module_children = module_children;
907        self.ambig_module_children = ambig_module_children;
908
909        let mut seen_spans = FxHashSet::default();
910        let mut errors = ::alloc::vec::Vec::new()vec![];
911        let mut prev_root_id: NodeId = NodeId::ZERO;
912        let determined_imports = mem::take(&mut self.determined_imports);
913        let indeterminate_imports = mem::take(&mut self.indeterminate_imports);
914
915        let mut glob_error = false;
916        for (is_indeterminate, import) in determined_imports
917            .iter()
918            .map(|i| (false, i))
919            .chain(indeterminate_imports.iter().map(|i| (true, i)))
920        {
921            let unresolved_import_error = self.finalize_import(*import);
922            // If this import is unresolved then create a dummy import
923            // resolution for it so that later resolve stages won't complain.
924            self.import_dummy_binding(*import, is_indeterminate);
925
926            let Some(err) = unresolved_import_error else { continue };
927
928            glob_error |= import.is_glob();
929
930            if let ImportKind::Single { source, ref decls, .. } = import.kind
931                && source.name == kw::SelfLower
932                // Silence `unresolved import` error if E0429 is already emitted
933                && let PendingDecl::Ready(None) = decls.value_ns.get()
934            {
935                continue;
936            }
937
938            if prev_root_id != NodeId::ZERO && prev_root_id != import.root_id && !errors.is_empty()
939            {
940                // In the case of a new import line, throw a diagnostic message
941                // for the previous line.
942                self.throw_unresolved_import_error(errors, glob_error);
943                errors = ::alloc::vec::Vec::new()vec![];
944            }
945            if seen_spans.insert(err.span) {
946                errors.push((*import, err));
947                prev_root_id = import.root_id;
948            }
949        }
950
951        if self.cstore().had_extern_crate_load_failure() {
952            self.tcx.sess.dcx().abort_if_errors();
953        }
954
955        if !errors.is_empty() {
956            self.throw_unresolved_import_error(errors, glob_error);
957            return;
958        }
959
960        for import in &indeterminate_imports {
961            let path = import_path_to_string(
962                &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
963                &import.kind,
964                import.span,
965            );
966            // FIXME: there should be a better way of doing this than
967            // formatting this as a string then checking for `::`
968            if path.contains("::") {
969                let err = UnresolvedImportError {
970                    span: import.span,
971                    label: None,
972                    note: None,
973                    suggestion: None,
974                    candidates: None,
975                    segment: None,
976                    module: None,
977                    on_unknown_attr: import.on_unknown_attr.clone(),
978                };
979                errors.push((*import, err))
980            }
981        }
982
983        if !errors.is_empty() {
984            self.throw_unresolved_import_error(errors, glob_error);
985        }
986    }
987
988    pub(crate) fn lint_reexports(&mut self, exported_ambiguities: FxHashSet<Decl<'ra>>) {
989        for module in &self.local_modules {
990            for (key, resolution) in self.resolutions(module.to_module()).borrow().iter() {
991                let resolution = resolution.borrow();
992                let Some(binding) = resolution.best_decl() else { continue };
993
994                // Report "cannot reexport" errors for exotic cases involving macros 2.0
995                // privacy bending or invariant-breaking code under deprecation lints.
996                for decl in [resolution.non_glob_decl, resolution.glob_decl] {
997                    if let Some(decl) = decl
998                        && let DeclKind::Import { source_decl, import } = decl.kind
999                        // FIXME: Do not check visibility-ambiguous imports for now. To check them
1000                        // properly we need to preserve all imports in ambiguous glob sets and
1001                        // check them all individually.
1002                        && decl.ambiguity_vis_max.get().is_none()
1003                    {
1004                        // The source entity is too private to be reexported
1005                        // with the given import declaration's visibility.
1006                        let ord = source_decl.vis().partial_cmp(decl.vis(), self.tcx);
1007                        if #[allow(non_exhaustive_omitted_patterns)] match ord {
    None | Some(Ordering::Less) => true,
    _ => false,
}matches!(ord, None | Some(Ordering::Less)) {
1008                            let ident = match import.kind {
1009                                ImportKind::Single { source, .. } => source,
1010                                _ => key.ident.orig(resolution.orig_ident_span),
1011                            };
1012                            if let Some(lint) =
1013                                self.report_cannot_reexport(import, source_decl, ident, key.ns)
1014                            {
1015                                self.lint_buffer.add_early_lint(lint);
1016                            }
1017                        }
1018                    }
1019                }
1020
1021                if let DeclKind::Import { import, .. } = binding.kind
1022                    && let Some((amb_binding, _)) = binding.ambiguity.get()
1023                    && binding.res() != Res::Err
1024                    && exported_ambiguities.contains(&binding)
1025                {
1026                    self.lint_buffer.buffer_lint(
1027                        AMBIGUOUS_GLOB_REEXPORTS,
1028                        import.root_id,
1029                        import.root_span,
1030                        diagnostics::AmbiguousGlobReexports {
1031                            name: key.ident.name.to_string(),
1032                            namespace: key.ns.descr().to_string(),
1033                            first_reexport: import.root_span,
1034                            duplicate_reexport: amb_binding.span,
1035                        },
1036                    );
1037                }
1038
1039                if let Some(glob_decl) = resolution.glob_decl
1040                    && resolution.non_glob_decl.is_some()
1041                {
1042                    if binding.res() != Res::Err
1043                        && glob_decl.res() != Res::Err
1044                        && let DeclKind::Import { import: glob_import, .. } = glob_decl.kind
1045                        && let Some(glob_import_def_id) = glob_import.def_id()
1046                        && self.effective_visibilities.is_exported(glob_import_def_id)
1047                        && glob_decl.vis().is_public()
1048                        && !binding.vis().is_public()
1049                    {
1050                        let binding_id = match binding.kind {
1051                            DeclKind::Def(res) => {
1052                                Some(self.def_id_to_node_id(res.def_id().expect_local()))
1053                            }
1054                            DeclKind::Import { import, .. } => import.id(),
1055                        };
1056                        if let Some(binding_id) = binding_id {
1057                            self.lint_buffer.buffer_lint(
1058                                HIDDEN_GLOB_REEXPORTS,
1059                                binding_id,
1060                                binding.span,
1061                                diagnostics::HiddenGlobReexports {
1062                                    name: key.ident.name.to_string(),
1063                                    namespace: key.ns.descr().to_owned(),
1064                                    glob_reexport: glob_decl.span,
1065                                    private_item: binding.span,
1066                                },
1067                            );
1068                        }
1069                    }
1070                }
1071
1072                if let DeclKind::Import { import, .. } = binding.kind
1073                    && let Some(binding_id) = import.id()
1074                    && let import_def_id = import.def_id().unwrap()
1075                    && self.effective_visibilities.is_exported(import_def_id)
1076                    && let Res::Def(reexported_kind, reexported_def_id) = binding.res()
1077                    && !#[allow(non_exhaustive_omitted_patterns)] match reexported_kind {
    DefKind::Ctor(..) => true,
    _ => false,
}matches!(reexported_kind, DefKind::Ctor(..))
1078                    && !reexported_def_id.is_local()
1079                    && self.tcx.is_private_dep(reexported_def_id.krate)
1080                {
1081                    self.lint_buffer.buffer_lint(
1082                        EXPORTED_PRIVATE_DEPENDENCIES,
1083                        binding_id,
1084                        binding.span,
1085                        crate::diagnostics::ReexportPrivateDependency {
1086                            name: key.ident.name,
1087                            kind: binding.res().descr(),
1088                            krate: self.tcx.crate_name(reexported_def_id.krate),
1089                        },
1090                    );
1091                }
1092            }
1093        }
1094    }
1095
1096    /// Attempts to resolve the given import, returning:
1097    /// - `0` means its resolution is determined.
1098    /// - Other values mean that indeterminate exists under certain namespaces.
1099    ///
1100    /// Meanwhile, if resolution is successful, its result is returned.
1101    fn resolve_import<'r>(
1102        mut self: CmResolver<'r, 'ra, 'tcx>,
1103        import: Import<'ra>,
1104    ) -> (Option<ImportResolution<'ra>>, usize) {
1105        {
    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:1105",
                        "rustc_resolve::imports", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/imports.rs"),
                        ::tracing_core::__macro_support::Option::Some(1105u32),
                        ::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!(
1106            "(resolving import for module) resolving import `{}::{}` in `{}`",
1107            Segment::names_to_string(&import.module_path),
1108            import_kind_to_string(&import.kind),
1109            module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
1110        );
1111        let module = if let Some(module) = import.imported_module.get() {
1112            module
1113        } else {
1114            let path_res = self.reborrow().maybe_resolve_path(
1115                &import.module_path,
1116                None,
1117                &import.parent_scope,
1118                Some(import),
1119            );
1120
1121            match path_res {
1122                PathResult::Module(module) => module,
1123                PathResult::Indeterminate => return (None, 3),
1124                PathResult::NonModule(..) | PathResult::Failed { .. } => return (None, 0),
1125            }
1126        };
1127
1128        let (source, bindings) = match import.kind {
1129            ImportKind::Single { source, ref decls, .. } => (source, decls),
1130            ImportKind::Glob { .. } => {
1131                let import_resolution = ImportResolution {
1132                    imported_module: module,
1133                    kind: self.resolve_glob_import(import, module),
1134                };
1135                return (Some(import_resolution), 0);
1136            }
1137            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1138        };
1139
1140        let mut import_decls = PerNS::default();
1141        let mut indeterminate_count = 0;
1142        self.per_ns_cm(|mut this, ns| {
1143            if bindings[ns].get() != PendingDecl::Pending {
1144                return;
1145            };
1146            let binding_result = this.reborrow().maybe_resolve_ident_in_module(
1147                module,
1148                source,
1149                ns,
1150                &import.parent_scope,
1151                Some(import),
1152            );
1153            let pending_decl = match binding_result {
1154                Ok(binding) => {
1155                    // We need the `target`, `source` can be extracted.
1156                    let import_decl = this.new_import_decl(binding, import);
1157                    PendingDecl::Ready(Some(import_decl))
1158                }
1159                Err(Determinacy::Determined) => PendingDecl::Ready(None),
1160                Err(Determinacy::Undetermined) => {
1161                    indeterminate_count += 1;
1162                    PendingDecl::Pending
1163                }
1164            };
1165            import_decls[ns] = pending_decl;
1166        });
1167        let import_resolution = ImportResolution {
1168            imported_module: module,
1169            kind: ImportResolutionKind::Single(import_decls),
1170        };
1171
1172        (Some(import_resolution), indeterminate_count)
1173    }
1174
1175    /// Performs final import resolution, consistency checks and error reporting.
1176    ///
1177    /// Optionally returns an unresolved import error. This error is buffered and used to
1178    /// consolidate multiple unresolved import errors into a single diagnostic.
1179    fn finalize_import(&mut self, import: Import<'ra>) -> Option<UnresolvedImportError> {
1180        let ignore_decl = match &import.kind {
1181            ImportKind::Single { decls, .. } => decls[TypeNS].get().decl(),
1182            _ => None,
1183        };
1184        let ambiguity_errors_len = |errors: &Vec<AmbiguityError<'_>>| {
1185            errors.iter().filter(|error| error.warning.is_none()).count()
1186        };
1187        let prev_ambiguity_errors_len = ambiguity_errors_len(&self.ambiguity_errors);
1188        let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
1189
1190        // We'll provide more context to the privacy errors later, up to `len`.
1191        let privacy_errors_len = self.privacy_errors.len();
1192
1193        let path_res = self.cm().resolve_path(
1194            &import.module_path,
1195            None,
1196            &import.parent_scope,
1197            Some(finalize),
1198            ignore_decl,
1199            Some(import),
1200        );
1201
1202        let no_ambiguity =
1203            ambiguity_errors_len(&self.ambiguity_errors) == prev_ambiguity_errors_len;
1204
1205        let module = match path_res {
1206            PathResult::Module(module) => {
1207                // Consistency checks, analogous to `finalize_macro_resolutions`.
1208                if let Some(initial_module) = import.imported_module.get() {
1209                    if module != initial_module && no_ambiguity && !self.issue_145575_hack_applied {
1210                        ::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");
1211                    }
1212                } else if self.privacy_errors.is_empty() {
1213                    self.dcx()
1214                        .create_err(CannotDetermineImportResolution { span: import.span })
1215                        .emit();
1216                }
1217
1218                module
1219            }
1220            PathResult::Failed {
1221                is_error_from_last_segment: false,
1222                span,
1223                segment,
1224                label,
1225                suggestion,
1226                module,
1227                error_implied_by_parse_error: _,
1228                message,
1229                note: _,
1230            } => {
1231                if no_ambiguity {
1232                    if !self.issue_145575_hack_applied {
1233                        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());
1234                    }
1235                    self.report_error(
1236                        span,
1237                        ResolutionError::FailedToResolve {
1238                            segment: segment.name,
1239                            label,
1240                            suggestion,
1241                            module,
1242                            message,
1243                        },
1244                    );
1245                }
1246                return None;
1247            }
1248            PathResult::Failed {
1249                is_error_from_last_segment: true,
1250                span,
1251                label,
1252                suggestion,
1253                module,
1254                segment,
1255                note,
1256                ..
1257            } => {
1258                if no_ambiguity {
1259                    if !self.issue_145575_hack_applied {
1260                        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());
1261                    }
1262                    let module = if let Some(ModuleOrUniformRoot::Module(m)) = module {
1263                        m.opt_def_id()
1264                    } else {
1265                        None
1266                    };
1267                    let err = match self
1268                        .make_path_suggestion(import.module_path.clone(), &import.parent_scope)
1269                    {
1270                        Some((suggestion, note)) => UnresolvedImportError {
1271                            span,
1272                            label: None,
1273                            note,
1274                            suggestion: Some((
1275                                ::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))],
1276                                String::from("a similar path exists"),
1277                                Applicability::MaybeIncorrect,
1278                            )),
1279                            candidates: None,
1280                            segment: Some(segment),
1281                            module,
1282                            on_unknown_attr: import.on_unknown_attr.clone(),
1283                        },
1284                        None => UnresolvedImportError {
1285                            span,
1286                            label: Some(label),
1287                            note,
1288                            suggestion,
1289                            candidates: None,
1290                            segment: Some(segment),
1291                            module,
1292                            on_unknown_attr: import.on_unknown_attr.clone(),
1293                        },
1294                    };
1295                    return Some(err);
1296                }
1297                return None;
1298            }
1299            PathResult::NonModule(partial_res) => {
1300                if no_ambiguity && partial_res.full_res() != Some(Res::Err) {
1301                    // Check if there are no ambiguities and the result is not dummy.
1302                    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());
1303                }
1304                // The error was already reported earlier.
1305                return None;
1306            }
1307            PathResult::Indeterminate => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1308        };
1309
1310        let (ident, target, bindings, import_id) = match import.kind {
1311            ImportKind::Single { source, target, ref decls, id, .. } => (source, target, decls, id),
1312            ImportKind::Glob { ref max_vis, id, def_id } => {
1313                if import.module_path.len() <= 1 {
1314                    // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1315                    // 2 segments, so the `resolve_path` above won't trigger it.
1316                    let mut full_path = import.module_path.clone();
1317                    full_path.push(Segment::from_ident(Ident::dummy()));
1318                    self.lint_if_path_starts_with_module(finalize, &full_path, None);
1319                }
1320
1321                if let ModuleOrUniformRoot::Module(module) = module
1322                    && module == import.parent_scope.module
1323                {
1324                    // Importing a module into itself is not allowed.
1325                    return Some(UnresolvedImportError {
1326                        span: import.span,
1327                        label: Some(String::from("cannot glob-import a module into itself")),
1328                        note: None,
1329                        suggestion: None,
1330                        candidates: None,
1331                        segment: None,
1332                        module: None,
1333                        on_unknown_attr: None,
1334                    });
1335                }
1336                if let Some(max_vis) = max_vis.get()
1337                    && import.vis.greater_than(max_vis, self.tcx)
1338                {
1339                    self.lint_buffer.buffer_lint(
1340                        UNUSED_IMPORTS,
1341                        id,
1342                        import.span,
1343                        crate::diagnostics::RedundantImportVisibility {
1344                            span: import.span,
1345                            help: (),
1346                            max_vis: max_vis.to_string(def_id, self.tcx),
1347                            import_vis: import.vis.to_string(def_id, self.tcx),
1348                        },
1349                    );
1350                }
1351                return None;
1352            }
1353            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1354        };
1355
1356        if self.privacy_errors.len() != privacy_errors_len {
1357            // Get the Res for the last element, so that we can point to alternative ways of
1358            // importing it if available.
1359            let mut path = import.module_path.clone();
1360            path.push(Segment::from_ident(ident));
1361            if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.cm().resolve_path(
1362                &path,
1363                None,
1364                &import.parent_scope,
1365                Some(finalize),
1366                ignore_decl,
1367                None,
1368            ) {
1369                let res = module.res().map(|r| (r, ident));
1370                for error in &mut self.privacy_errors[privacy_errors_len..] {
1371                    error.outermost_res = res;
1372                }
1373            } else {
1374                // The final item is not a module (e.g., a struct, function, or macro).
1375                // Resolve it directly in the parent module to get its Res, so
1376                // `report_privacy_error()` can search for public re-export paths.
1377                for ns in [TypeNS, ValueNS, MacroNS] {
1378                    if let Ok(binding) = self.cm().resolve_ident_in_module(
1379                        module,
1380                        ident,
1381                        ns,
1382                        &import.parent_scope,
1383                        None,
1384                        ignore_decl,
1385                        None,
1386                    ) {
1387                        let res = binding.res();
1388                        for error in &mut self.privacy_errors[privacy_errors_len..] {
1389                            error.outermost_res = Some((res, ident));
1390                        }
1391                        break;
1392                    }
1393                }
1394            }
1395        }
1396
1397        let mut all_ns_err = true;
1398        self.per_ns(|this, ns| {
1399            let binding = this.cm().resolve_ident_in_module(
1400                module,
1401                ident,
1402                ns,
1403                &import.parent_scope,
1404                Some(Finalize {
1405                    report_private: false,
1406                    import: Some(import.summary()),
1407                    ..finalize
1408                }),
1409                bindings[ns].get().decl(),
1410                Some(import),
1411            );
1412
1413            match binding {
1414                Ok(binding) => {
1415                    // Consistency checks, analogous to `finalize_macro_resolutions`.
1416                    let initial_res = bindings[ns].get().decl().map(|binding| {
1417                        let initial_binding = binding.import_source();
1418                        all_ns_err = false;
1419                        if target.name == kw::Underscore
1420                            && initial_binding.is_extern_crate()
1421                            && !initial_binding.is_import()
1422                        {
1423                            let used = if import.module_path.is_empty() {
1424                                Used::Scope
1425                            } else {
1426                                Used::Other
1427                            };
1428                            this.record_use(ident, binding, used);
1429                        }
1430                        initial_binding.res()
1431                    });
1432                    let res = binding.res();
1433                    let has_ambiguity_error =
1434                        this.ambiguity_errors.iter().any(|error| error.warning.is_none());
1435                    if res == Res::Err || has_ambiguity_error {
1436                        this.dcx()
1437                            .span_delayed_bug(import.span, "some error happened for an import");
1438                        return;
1439                    }
1440                    if let Some(initial_res) = initial_res {
1441                        if res != initial_res && !this.issue_145575_hack_applied {
1442                            ::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");
1443                        }
1444                    } else if this.privacy_errors.is_empty() {
1445                        this.dcx()
1446                            .create_err(CannotDetermineImportResolution { span: import.span })
1447                            .emit();
1448                    }
1449                }
1450                Err(..) => {
1451                    // FIXME: This assert may fire if public glob is later shadowed by a private
1452                    // single import (see test `issue-55884-2.rs`). In theory single imports should
1453                    // always block globs, even if they are not yet resolved, so that this kind of
1454                    // self-inconsistent resolution never happens.
1455                    // Re-enable the assert when the issue is fixed.
1456                    // assert!(result[ns].get().is_err());
1457                }
1458            }
1459        });
1460
1461        if all_ns_err {
1462            let mut all_ns_failed = true;
1463            self.per_ns(|this, ns| {
1464                let binding = this.cm().resolve_ident_in_module(
1465                    module,
1466                    ident,
1467                    ns,
1468                    &import.parent_scope,
1469                    Some(finalize),
1470                    None,
1471                    None,
1472                );
1473                if binding.is_ok() {
1474                    all_ns_failed = false;
1475                }
1476            });
1477
1478            return if all_ns_failed {
1479                let names = match module {
1480                    ModuleOrUniformRoot::Module(module) => {
1481                        self.resolutions(module)
1482                            .borrow()
1483                            .iter()
1484                            .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1485                                if i.name == ident.name {
1486                                    return None;
1487                                } // Never suggest the same name
1488                                if i.name == kw::Underscore {
1489                                    return None;
1490                                } // `use _` is never valid
1491
1492                                let resolution = resolution.borrow();
1493                                if let Some(name_binding) = resolution.best_decl() {
1494                                    match name_binding.kind {
1495                                        DeclKind::Import { source_decl, .. } => {
1496                                            match source_decl.kind {
1497                                                // Never suggest names that previously could not
1498                                                // be resolved.
1499                                                DeclKind::Def(Res::Err) => None,
1500                                                _ => Some(i.name),
1501                                            }
1502                                        }
1503                                        _ => Some(i.name),
1504                                    }
1505                                } else if resolution.single_imports.is_empty() {
1506                                    None
1507                                } else {
1508                                    Some(i.name)
1509                                }
1510                            })
1511                            .collect()
1512                    }
1513                    _ => Vec::new(),
1514                };
1515
1516                let lev_suggestion =
1517                    find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
1518                        (
1519                            ::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())],
1520                            String::from("a similar name exists in the module"),
1521                            Applicability::MaybeIncorrect,
1522                        )
1523                    });
1524
1525                let (suggestion, note) =
1526                    match self.check_for_module_export_macro(import, module, ident) {
1527                        Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1528                        _ => (lev_suggestion, None),
1529                    };
1530
1531                // If importing of trait asscoiated items is enabled, an also find an
1532                // `Enum`, then note that inherent associated items cannot be imported.
1533                let note = if self.features.import_trait_associated_functions()
1534                    && let PathResult::Module(ModuleOrUniformRoot::Module(m)) = path_res
1535                    && let Some(Res::Def(DefKind::Enum, _)) = m.res()
1536                {
1537                    note.or(Some(
1538                        "cannot import inherent associated items, only trait associated items"
1539                            .to_string(),
1540                    ))
1541                } else {
1542                    note
1543                };
1544
1545                let label = match module {
1546                    ModuleOrUniformRoot::Module(module) => {
1547                        let module_str = module_to_string(module);
1548                        if let Some(module_str) = module_str {
1549                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no `{0}` in `{1}`", ident,
                module_str))
    })format!("no `{ident}` in `{module_str}`")
1550                        } else {
1551                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
    })format!("no `{ident}` in the root")
1552                        }
1553                    }
1554                    _ => {
1555                        if !ident.is_path_segment_keyword() {
1556                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no external crate `{0}`", ident))
    })format!("no external crate `{ident}`")
1557                        } else {
1558                            // HACK(eddyb) this shows up for `self` & `super`, which
1559                            // should work instead - for now keep the same error message.
1560                            ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("no `{0}` in the root", ident))
    })format!("no `{ident}` in the root")
1561                        }
1562                    }
1563                };
1564
1565                let parent_suggestion =
1566                    self.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true);
1567
1568                Some(UnresolvedImportError {
1569                    span: import.span,
1570                    label: Some(label),
1571                    note,
1572                    suggestion,
1573                    candidates: if !parent_suggestion.is_empty() {
1574                        Some(parent_suggestion)
1575                    } else {
1576                        None
1577                    },
1578                    module: import.imported_module.get().and_then(|module| {
1579                        if let ModuleOrUniformRoot::Module(m) = module {
1580                            m.opt_def_id()
1581                        } else {
1582                            None
1583                        }
1584                    }),
1585                    segment: Some(ident),
1586                    on_unknown_attr: import.on_unknown_attr.clone(),
1587                })
1588            } else {
1589                // `resolve_ident_in_module` reported a privacy error.
1590                None
1591            };
1592        }
1593
1594        let mut reexport_error = None;
1595        let mut any_successful_reexport = false;
1596        self.per_ns(|this, ns| {
1597            let Some(binding) = bindings[ns].get().decl() else {
1598                return;
1599            };
1600
1601            if import.vis.greater_than(binding.vis(), this.tcx) {
1602                // In isolation, a declaration like this is not an error, but if *all* 1-3
1603                // declarations introduced by the import are more private than the import item's
1604                // nominal visibility, then it's an error.
1605                reexport_error = Some((ns, binding.import_source()));
1606            } else {
1607                any_successful_reexport = true;
1608            }
1609        });
1610
1611        if !any_successful_reexport {
1612            let (ns, binding) = reexport_error.unwrap();
1613            if let Some(lint) = self.report_cannot_reexport(import, binding, ident, ns) {
1614                self.lint_buffer.add_early_lint(lint);
1615            }
1616        }
1617
1618        if import.module_path.len() <= 1 {
1619            // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1620            // 2 segments, so the `resolve_path` above won't trigger it.
1621            let mut full_path = import.module_path.clone();
1622            full_path.push(Segment::from_ident(ident));
1623            self.per_ns(|this, ns| {
1624                if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1625                    this.lint_if_path_starts_with_module(finalize, &full_path, Some(binding));
1626                }
1627            });
1628        }
1629
1630        // Record what this import resolves to for later uses in documentation,
1631        // this may resolve to either a value or a type, but for documentation
1632        // purposes it's good enough to just favor one over the other.
1633        self.per_ns(|this, ns| {
1634            if let Some(binding) = bindings[ns].get().decl().map(|b| b.import_source()) {
1635                this.owners.get_mut(&import_id).unwrap().import_res[ns] = Some(binding.res());
1636            }
1637        });
1638
1639        {
    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:1639",
                        "rustc_resolve::imports", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_resolve/src/imports.rs"),
                        ::tracing_core::__macro_support::Option::Some(1639u32),
                        ::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");
1640        None
1641    }
1642
1643    fn report_cannot_reexport(
1644        &self,
1645        import: Import<'ra>,
1646        decl: Decl<'ra>,
1647        ident: Ident,
1648        ns: Namespace,
1649    ) -> Option<BufferedEarlyLint> {
1650        let crate_private_reexport = match decl.vis() {
1651            Visibility::Restricted(def_id) if def_id.is_top_level_module() => true,
1652            _ => false,
1653        };
1654
1655        if let Some(extern_crate_id) = pub_use_of_private_extern_crate_hack(import.summary(), decl)
1656        {
1657            let ImportKind::Single { id, .. } = import.kind else { ::core::panicking::panic("internal error: entered unreachable code")unreachable!() };
1658            let sugg = self.tcx.source_span(extern_crate_id).shrink_to_lo();
1659            let diagnostic = crate::diagnostics::PrivateExternCrateReexport { ident, sugg };
1660            return Some(BufferedEarlyLint {
1661                lint_id: LintId::of(PUB_USE_OF_PRIVATE_EXTERN_CRATE),
1662                node_id: id,
1663                span: Some(import.span.into()),
1664                diagnostic: diagnostic.into(),
1665            });
1666        } else if ns == TypeNS {
1667            let err = if crate_private_reexport {
1668                self.dcx().create_err(CannotBeReexportedCratePublicNS { span: import.span, ident })
1669            } else {
1670                self.dcx().create_err(CannotBeReexportedPrivateNS { span: import.span, ident })
1671            };
1672            err.emit();
1673        } else {
1674            let mut err = if crate_private_reexport {
1675                self.dcx().create_err(CannotBeReexportedCratePublic { span: import.span, ident })
1676            } else {
1677                self.dcx().create_err(CannotBeReexportedPrivate { span: import.span, ident })
1678            };
1679
1680            match decl.kind {
1681                // exclude decl_macro
1682                DeclKind::Def(Res::Def(DefKind::Macro(_), def_id))
1683                    if let SyntaxExtensionKind::MacroRules(mr) =
1684                        &self.get_macro_by_def_id(def_id).kind
1685                        && mr.is_macro_rules() =>
1686                {
1687                    err.subdiagnostic(ConsiderAddingMacroExport { span: decl.span });
1688                    err.subdiagnostic(ConsiderMarkingAsPubCrate { vis_span: import.vis_span });
1689                }
1690                _ => {
1691                    err.subdiagnostic(ConsiderMarkingAsPub { span: import.span, ident });
1692                }
1693            }
1694            err.emit();
1695        }
1696
1697        None
1698    }
1699
1700    pub(crate) fn check_for_redundant_imports(&mut self, import: Import<'ra>) -> bool {
1701        // This function is only called for single imports.
1702        let ImportKind::Single { source, target, ref decls, id, def_id, .. } = import.kind else {
1703            ::core::panicking::panic("internal error: entered unreachable code")unreachable!()
1704        };
1705
1706        // Skip if the import is of the form `use source as target` and source != target.
1707        if source != target {
1708            return false;
1709        }
1710
1711        // Skip if the import was produced by a macro.
1712        if import.parent_scope.expansion != LocalExpnId::ROOT {
1713            return false;
1714        }
1715
1716        // Skip if we are inside a named module (in contrast to an anonymous
1717        // module defined by a block).
1718        // Skip if the import is public or was used through non scope-based resolution,
1719        // e.g. through a module-relative path.
1720        if self.import_use_map.get(&import) == Some(&Used::Other)
1721            || self.effective_visibilities.is_exported(def_id)
1722        {
1723            return false;
1724        }
1725
1726        let mut is_redundant = true;
1727        let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1728        self.per_ns(|this, ns| {
1729            let binding = decls[ns].get().decl().map(|b| b.import_source());
1730            if is_redundant && let Some(binding) = binding {
1731                if binding.res() == Res::Err {
1732                    return;
1733                }
1734
1735                match this.cm().resolve_ident_in_scope_set(
1736                    target,
1737                    ScopeSet::All(ns),
1738                    &import.parent_scope,
1739                    None,
1740                    decls[ns].get().decl(),
1741                    None,
1742                ) {
1743                    Ok(other_binding) => {
1744                        is_redundant = binding.res() == other_binding.res()
1745                            && !other_binding.is_ambiguity_recursive();
1746                        if is_redundant {
1747                            redundant_span[ns] =
1748                                Some((other_binding.span, other_binding.is_import()));
1749                        }
1750                    }
1751                    Err(_) => is_redundant = false,
1752                }
1753            }
1754        });
1755
1756        if is_redundant && !redundant_span.is_empty() {
1757            let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1758            redundant_spans.sort();
1759            redundant_spans.dedup();
1760            self.lint_buffer.dyn_buffer_lint(
1761                REDUNDANT_IMPORTS,
1762                id,
1763                import.span,
1764                move |dcx, level| {
1765                    let ident = source;
1766                    let subs = redundant_spans
1767                        .into_iter()
1768                        .map(|(span, is_imported)| match (span.is_dummy(), is_imported) {
1769                            (false, true) => {
1770                                diagnostics::RedundantImportSub::ImportedHere { span, ident }
1771                            }
1772                            (false, false) => {
1773                                diagnostics::RedundantImportSub::DefinedHere { span, ident }
1774                            }
1775                            (true, true) => {
1776                                diagnostics::RedundantImportSub::ImportedPrelude { span, ident }
1777                            }
1778                            (true, false) => {
1779                                diagnostics::RedundantImportSub::DefinedPrelude { span, ident }
1780                            }
1781                        })
1782                        .collect();
1783                    diagnostics::RedundantImport { subs, ident }.into_diag(dcx, level)
1784                },
1785            );
1786            return true;
1787        }
1788
1789        false
1790    }
1791
1792    fn resolve_glob_import(
1793        &self,
1794        import: Import<'ra>,
1795        imported_module: ModuleOrUniformRoot<'ra>,
1796    ) -> ImportResolutionKind<'ra> {
1797        let import_bindings = match imported_module {
1798            ModuleOrUniformRoot::Module(module) if module != import.parent_scope.module => self
1799                .resolutions(module)
1800                .borrow()
1801                .iter()
1802                .filter_map(|(key, resolution)| {
1803                    let res = resolution.borrow();
1804                    let decl = res.determined_decl()?;
1805                    let mut key = *key;
1806                    let scope = match key.ident.ctxt.update_unchecked(|ctxt| {
1807                        ctxt.reverse_glob_adjust(module.expansion, import.span)
1808                    }) {
1809                        Some(Some(def)) => self.expn_def_scope(def),
1810                        Some(None) => import.parent_scope.module,
1811                        None => return None,
1812                    };
1813                    self.is_accessible_from(decl.vis(), scope).then_some((
1814                        decl,
1815                        key,
1816                        res.orig_ident_span,
1817                    ))
1818                })
1819                .collect::<Vec<_>>(),
1820
1821            // Errors are reported in `write_imports_resolutions`
1822            _ => ::alloc::vec::Vec::new()vec![],
1823        };
1824
1825        ImportResolutionKind::Glob(import_bindings)
1826    }
1827
1828    // Hack for the `rust_embed` regression observed in the crater run of #145108.
1829    fn rust_embed_hack(&self, module: LocalModule<'ra>, decl: Decl<'ra>) -> bool {
1830        // We are looking for this pattern:
1831        // ```rust
1832        // #[macro_use]
1833        // extern crate rust_embed_impl;
1834        // pub use rust_embed_impl::*;
1835        //
1836        // pub use RustEmbed as Embed;
1837        // ```
1838        if let DeclKind::Import { source_decl, import } = decl.kind
1839            // Check that `decl` is the re-export: "pub use RustEmbed as Embed;"
1840            && let ImportKind::Single { source, .. } = import.kind
1841            && source.name == sym::RustEmbed
1842            // make sure that the import points to the #[macro_use] import
1843            && let DeclKind::Import { import, .. } = source_decl.kind
1844            && #[allow(non_exhaustive_omitted_patterns)] match import.kind {
    ImportKind::MacroUse { .. } => true,
    _ => false,
}matches!(import.kind, ImportKind::MacroUse { .. })
1845            && self.macro_use_prelude.contains_key(&source.name) // and that the name actually exists in the macro_use_prelude
1846            // Then check that `RustEmbed` exists in the modules Macro namespace.
1847            && let Some(y_decl) = self
1848                .resolution(module.to_module(), BindingKey::new(IdentKey::new(source), MacroNS))
1849                .and_then(|res| res.best_decl())
1850            // which comes from "pub use rust_embed_impl::*"
1851            && y_decl.is_glob_import()
1852            && y_decl.vis().is_public()
1853        {
1854            return true;
1855        }
1856
1857        false
1858    }
1859
1860    // Miscellaneous post-processing, including recording re-exports,
1861    // reporting conflicts, and reporting unresolved imports.
1862    fn finalize_resolutions_in(
1863        &self,
1864        module: LocalModule<'ra>,
1865        module_children: &mut LocalDefIdMap<Vec<ModChild>>,
1866        ambig_module_children: &mut LocalDefIdMap<Vec<AmbigModChild>>,
1867    ) {
1868        // Since import resolution is finished, globs will not define any more names.
1869        *module.globs.borrow_mut(self) = Vec::new();
1870
1871        let Some(def_id) = module.opt_def_id() else { return };
1872
1873        let mut children = Vec::new();
1874        let mut ambig_children = Vec::new();
1875
1876        module.to_module().for_each_child(self, |this, ident, orig_ident_span, _, decl| {
1877            let res = decl.res().expect_non_local();
1878            if res != def::Res::Err {
1879                let vis = if this.rust_embed_hack(module, decl) {
1880                    Visibility::Public
1881                } else {
1882                    decl.vis()
1883                };
1884                let ident = ident.orig(orig_ident_span);
1885                let child = |reexport_chain| ModChild { ident, res, vis, reexport_chain };
1886                if let Some((ambig_binding1, ambig_binding2)) = decl.descent_to_ambiguity() {
1887                    let main = child(ambig_binding1.reexport_chain());
1888                    let second = ModChild {
1889                        ident,
1890                        res: ambig_binding2.res().expect_non_local(),
1891                        vis: ambig_binding2.vis(),
1892                        reexport_chain: ambig_binding2.reexport_chain(),
1893                    };
1894                    ambig_children.push(AmbigModChild { main, second })
1895                } else {
1896                    children.push(child(decl.reexport_chain()));
1897                }
1898            }
1899        });
1900
1901        if !children.is_empty() {
1902            module_children.insert(def_id.expect_local(), children);
1903        }
1904        if !ambig_children.is_empty() {
1905            ambig_module_children.insert(def_id.expect_local(), ambig_children);
1906        }
1907    }
1908}
1909
1910pub(crate) fn import_path_to_string(
1911    names: &[Ident],
1912    import_kind: &ImportKind<'_>,
1913    span: Span,
1914) -> String {
1915    let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1916    let global = !names.is_empty() && names[0].name == kw::PathRoot;
1917    if let Some(pos) = pos {
1918        let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1919        names_to_string(names.iter().map(|ident| ident.name))
1920    } else {
1921        let names = if global { &names[1..] } else { names };
1922        if names.is_empty() {
1923            import_kind_to_string(import_kind)
1924        } else {
1925            ::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!(
1926                "{}::{}",
1927                names_to_string(names.iter().map(|ident| ident.name)),
1928                import_kind_to_string(import_kind),
1929            )
1930        }
1931    }
1932}
1933
1934fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1935    match import_kind {
1936        ImportKind::Single { source, .. } => source.to_string(),
1937        ImportKind::Glob { .. } => "*".to_string(),
1938        ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1939        ImportKind::MacroUse { .. } => "#[macro_use]".to_string(),
1940        ImportKind::MacroExport => "#[macro_export]".to_string(),
1941    }
1942}