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