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