Skip to main content

rustc_resolve/
imports.rs

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