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