rustc_resolve/
imports.rs

1//! A bunch of methods and structures more or less related to resolving imports.
2
3use std::cell::Cell;
4use std::mem;
5
6use rustc_ast::NodeId;
7use rustc_data_structures::fx::{FxHashSet, FxIndexSet};
8use rustc_data_structures::intern::Interned;
9use rustc_errors::codes::*;
10use rustc_errors::{Applicability, MultiSpan, pluralize, struct_span_code_err};
11use rustc_hir::def::{self, DefKind, PartialRes};
12use rustc_hir::def_id::DefId;
13use rustc_middle::metadata::{ModChild, Reexport};
14use rustc_middle::{span_bug, ty};
15use rustc_session::lint::BuiltinLintDiag;
16use rustc_session::lint::builtin::{
17    AMBIGUOUS_GLOB_REEXPORTS, HIDDEN_GLOB_REEXPORTS, PUB_USE_OF_PRIVATE_EXTERN_CRATE,
18    REDUNDANT_IMPORTS, UNUSED_IMPORTS,
19};
20use rustc_session::parse::feature_err;
21use rustc_span::edit_distance::find_best_match_for_name;
22use rustc_span::hygiene::LocalExpnId;
23use rustc_span::{Ident, Span, Symbol, kw, sym};
24use smallvec::SmallVec;
25use tracing::debug;
26
27use crate::Determinacy::{self, *};
28use crate::Namespace::*;
29use crate::diagnostics::{DiagMode, Suggestion, import_candidates};
30use crate::errors::{
31    CannotBeReexportedCratePublic, CannotBeReexportedCratePublicNS, CannotBeReexportedPrivate,
32    CannotBeReexportedPrivateNS, CannotDetermineImportResolution, CannotGlobImportAllCrates,
33    ConsiderAddingMacroExport, ConsiderMarkingAsPub,
34};
35use crate::{
36    AmbiguityError, AmbiguityKind, BindingKey, Finalize, ImportSuggestion, Module,
37    ModuleOrUniformRoot, NameBinding, NameBindingData, NameBindingKind, ParentScope, PathResult,
38    PerNS, ResolutionError, Resolver, ScopeSet, Segment, Used, module_to_string, names_to_string,
39};
40
41type Res = def::Res<NodeId>;
42
43/// Contains data for specific kinds of imports.
44#[derive(Clone)]
45pub(crate) enum ImportKind<'ra> {
46    Single {
47        /// `source` in `use prefix::source as target`.
48        source: Ident,
49        /// `target` in `use prefix::source as target`.
50        /// It will directly use `source` when the format is `use prefix::source`.
51        target: Ident,
52        /// Bindings to which `source` refers to.
53        source_bindings: PerNS<Cell<Result<NameBinding<'ra>, Determinacy>>>,
54        /// Bindings introduced by `target`.
55        target_bindings: PerNS<Cell<Option<NameBinding<'ra>>>>,
56        /// `true` for `...::{self [as target]}` imports, `false` otherwise.
57        type_ns_only: bool,
58        /// Did this import result from a nested import? ie. `use foo::{bar, baz};`
59        nested: bool,
60        /// The ID of the `UseTree` that imported this `Import`.
61        ///
62        /// In the case where the `Import` was expanded from a "nested" use tree,
63        /// this id is the ID of the leaf tree. For example:
64        ///
65        /// ```ignore (pacify the merciless tidy)
66        /// use foo::bar::{a, b}
67        /// ```
68        ///
69        /// If this is the import for `foo::bar::a`, we would have the ID of the `UseTree`
70        /// for `a` in this field.
71        id: NodeId,
72    },
73    Glob {
74        is_prelude: bool,
75        // The visibility of the greatest re-export.
76        // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
77        max_vis: Cell<Option<ty::Visibility>>,
78        id: NodeId,
79    },
80    ExternCrate {
81        source: Option<Symbol>,
82        target: Ident,
83        id: NodeId,
84    },
85    MacroUse {
86        /// A field has been added indicating whether it should be reported as a lint,
87        /// addressing issue#119301.
88        warn_private: bool,
89    },
90    MacroExport,
91}
92
93/// Manually implement `Debug` for `ImportKind` because the `source/target_bindings`
94/// contain `Cell`s which can introduce infinite loops while printing.
95impl<'ra> std::fmt::Debug for ImportKind<'ra> {
96    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97        use ImportKind::*;
98        match self {
99            Single {
100                source,
101                target,
102                source_bindings,
103                target_bindings,
104                type_ns_only,
105                nested,
106                id,
107            } => f
108                .debug_struct("Single")
109                .field("source", source)
110                .field("target", target)
111                // Ignore the nested bindings to avoid an infinite loop while printing.
112                .field(
113                    "source_bindings",
114                    &source_bindings.clone().map(|b| b.into_inner().map(|_| format_args!(".."))),
115                )
116                .field(
117                    "target_bindings",
118                    &target_bindings.clone().map(|b| b.into_inner().map(|_| format_args!(".."))),
119                )
120                .field("type_ns_only", type_ns_only)
121                .field("nested", nested)
122                .field("id", id)
123                .finish(),
124            Glob { is_prelude, max_vis, id } => f
125                .debug_struct("Glob")
126                .field("is_prelude", is_prelude)
127                .field("max_vis", max_vis)
128                .field("id", id)
129                .finish(),
130            ExternCrate { source, target, id } => f
131                .debug_struct("ExternCrate")
132                .field("source", source)
133                .field("target", target)
134                .field("id", id)
135                .finish(),
136            MacroUse { .. } => f.debug_struct("MacroUse").finish(),
137            MacroExport => f.debug_struct("MacroExport").finish(),
138        }
139    }
140}
141
142/// One import.
143#[derive(Debug, Clone)]
144pub(crate) struct ImportData<'ra> {
145    pub kind: ImportKind<'ra>,
146
147    /// Node ID of the "root" use item -- this is always the same as `ImportKind`'s `id`
148    /// (if it exists) except in the case of "nested" use trees, in which case
149    /// it will be the ID of the root use tree. e.g., in the example
150    /// ```ignore (incomplete code)
151    /// use foo::bar::{a, b}
152    /// ```
153    /// this would be the ID of the `use foo::bar` `UseTree` node.
154    /// In case of imports without their own node ID it's the closest node that can be used,
155    /// for example, for reporting lints.
156    pub root_id: NodeId,
157
158    /// Span of the entire use statement.
159    pub use_span: Span,
160
161    /// Span of the entire use statement with attributes.
162    pub use_span_with_attributes: Span,
163
164    /// Did the use statement have any attributes?
165    pub has_attributes: bool,
166
167    /// Span of this use tree.
168    pub span: Span,
169
170    /// Span of the *root* use tree (see `root_id`).
171    pub root_span: Span,
172
173    pub parent_scope: ParentScope<'ra>,
174    pub module_path: Vec<Segment>,
175    /// The resolution of `module_path`.
176    pub imported_module: Cell<Option<ModuleOrUniformRoot<'ra>>>,
177    pub vis: ty::Visibility,
178}
179
180/// All imports are unique and allocated on a same arena,
181/// so we can use referential equality to compare them.
182pub(crate) type Import<'ra> = Interned<'ra, ImportData<'ra>>;
183
184// Allows us to use Interned without actually enforcing (via Hash/PartialEq/...) uniqueness of the
185// contained data.
186// FIXME: We may wish to actually have at least debug-level assertions that Interned's guarantees
187// are upheld.
188impl std::hash::Hash for ImportData<'_> {
189    fn hash<H>(&self, _: &mut H)
190    where
191        H: std::hash::Hasher,
192    {
193        unreachable!()
194    }
195}
196
197impl<'ra> ImportData<'ra> {
198    pub(crate) fn is_glob(&self) -> bool {
199        matches!(self.kind, ImportKind::Glob { .. })
200    }
201
202    pub(crate) fn is_nested(&self) -> bool {
203        match self.kind {
204            ImportKind::Single { nested, .. } => nested,
205            _ => false,
206        }
207    }
208
209    pub(crate) fn id(&self) -> Option<NodeId> {
210        match self.kind {
211            ImportKind::Single { id, .. }
212            | ImportKind::Glob { id, .. }
213            | ImportKind::ExternCrate { id, .. } => Some(id),
214            ImportKind::MacroUse { .. } | ImportKind::MacroExport => None,
215        }
216    }
217
218    fn simplify(&self, r: &Resolver<'_, '_>) -> Reexport {
219        let to_def_id = |id| r.local_def_id(id).to_def_id();
220        match self.kind {
221            ImportKind::Single { id, .. } => Reexport::Single(to_def_id(id)),
222            ImportKind::Glob { id, .. } => Reexport::Glob(to_def_id(id)),
223            ImportKind::ExternCrate { id, .. } => Reexport::ExternCrate(to_def_id(id)),
224            ImportKind::MacroUse { .. } => Reexport::MacroUse,
225            ImportKind::MacroExport => Reexport::MacroExport,
226        }
227    }
228}
229
230/// Records information about the resolution of a name in a namespace of a module.
231#[derive(Clone, Default, Debug)]
232pub(crate) struct NameResolution<'ra> {
233    /// Single imports that may define the name in the namespace.
234    /// Imports are arena-allocated, so it's ok to use pointers as keys.
235    pub single_imports: FxIndexSet<Import<'ra>>,
236    /// The least shadowable known binding for this name, or None if there are no known bindings.
237    pub binding: Option<NameBinding<'ra>>,
238    pub shadowed_glob: Option<NameBinding<'ra>>,
239}
240
241impl<'ra> NameResolution<'ra> {
242    /// Returns the binding for the name if it is known or None if it not known.
243    pub(crate) fn binding(&self) -> Option<NameBinding<'ra>> {
244        self.binding.and_then(|binding| {
245            if !binding.is_glob_import() || self.single_imports.is_empty() {
246                Some(binding)
247            } else {
248                None
249            }
250        })
251    }
252}
253
254/// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
255/// import errors within the same use tree into a single diagnostic.
256#[derive(Debug, Clone)]
257struct UnresolvedImportError {
258    span: Span,
259    label: Option<String>,
260    note: Option<String>,
261    suggestion: Option<Suggestion>,
262    candidates: Option<Vec<ImportSuggestion>>,
263    segment: Option<Symbol>,
264    /// comes from `PathRes::Failed { module }`
265    module: Option<DefId>,
266}
267
268// Reexports of the form `pub use foo as bar;` where `foo` is `extern crate foo;`
269// are permitted for backward-compatibility under a deprecation lint.
270fn pub_use_of_private_extern_crate_hack(
271    import: Import<'_>,
272    binding: NameBinding<'_>,
273) -> Option<NodeId> {
274    match (&import.kind, &binding.kind) {
275        (ImportKind::Single { .. }, NameBindingKind::Import { import: binding_import, .. })
276            if let ImportKind::ExternCrate { id, .. } = binding_import.kind
277                && import.vis.is_public() =>
278        {
279            Some(id)
280        }
281        _ => None,
282    }
283}
284
285impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
286    /// Given a binding and an import that resolves to it,
287    /// return the corresponding binding defined by the import.
288    pub(crate) fn import(
289        &self,
290        binding: NameBinding<'ra>,
291        import: Import<'ra>,
292    ) -> NameBinding<'ra> {
293        let import_vis = import.vis.to_def_id();
294        let vis = if binding.vis.is_at_least(import_vis, self.tcx)
295            || pub_use_of_private_extern_crate_hack(import, binding).is_some()
296        {
297            import_vis
298        } else {
299            binding.vis
300        };
301
302        if let ImportKind::Glob { ref max_vis, .. } = import.kind
303            && (vis == import_vis
304                || max_vis.get().is_none_or(|max_vis| vis.is_at_least(max_vis, self.tcx)))
305        {
306            max_vis.set(Some(vis.expect_local()))
307        }
308
309        self.arenas.alloc_name_binding(NameBindingData {
310            kind: NameBindingKind::Import { binding, import },
311            ambiguity: None,
312            warn_ambiguity: false,
313            span: import.span,
314            vis,
315            expansion: import.parent_scope.expansion,
316        })
317    }
318
319    /// Define the name or return the existing binding if there is a collision.
320    /// `update` indicates if the definition is a redefinition of an existing binding.
321    pub(crate) fn try_define(
322        &mut self,
323        module: Module<'ra>,
324        key: BindingKey,
325        binding: NameBinding<'ra>,
326        warn_ambiguity: bool,
327    ) -> Result<(), NameBinding<'ra>> {
328        let res = binding.res();
329        self.check_reserved_macro_name(key.ident, res);
330        self.set_binding_parent_module(binding, module);
331        self.update_resolution(module, key, warn_ambiguity, |this, resolution| {
332            if let Some(old_binding) = resolution.binding {
333                if res == Res::Err && old_binding.res() != Res::Err {
334                    // Do not override real bindings with `Res::Err`s from error recovery.
335                    return Ok(());
336                }
337                match (old_binding.is_glob_import(), binding.is_glob_import()) {
338                    (true, true) => {
339                        // FIXME: remove `!binding.is_ambiguity_recursive()` after delete the warning ambiguity.
340                        if !binding.is_ambiguity_recursive()
341                            && let NameBindingKind::Import { import: old_import, .. } =
342                                old_binding.kind
343                            && let NameBindingKind::Import { import, .. } = binding.kind
344                            && old_import == import
345                        {
346                            // We should replace the `old_binding` with `binding` regardless
347                            // of whether they has same resolution or not when they are
348                            // imported from the same glob-import statement.
349                            resolution.binding = Some(binding);
350                        } else if res != old_binding.res() {
351                            resolution.binding = Some(this.new_ambiguity_binding(
352                                AmbiguityKind::GlobVsGlob,
353                                old_binding,
354                                binding,
355                                warn_ambiguity,
356                            ));
357                        } else if !old_binding.vis.is_at_least(binding.vis, this.tcx) {
358                            // We are glob-importing the same item but with greater visibility.
359                            resolution.binding = Some(binding);
360                        } else if binding.is_ambiguity_recursive() {
361                            resolution.binding = Some(this.new_warn_ambiguity_binding(binding));
362                        }
363                    }
364                    (old_glob @ true, false) | (old_glob @ false, true) => {
365                        let (glob_binding, nonglob_binding) =
366                            if old_glob { (old_binding, binding) } else { (binding, old_binding) };
367                        if key.ns == MacroNS
368                            && nonglob_binding.expansion != LocalExpnId::ROOT
369                            && glob_binding.res() != nonglob_binding.res()
370                        {
371                            resolution.binding = Some(this.new_ambiguity_binding(
372                                AmbiguityKind::GlobVsExpanded,
373                                nonglob_binding,
374                                glob_binding,
375                                false,
376                            ));
377                        } else {
378                            resolution.binding = Some(nonglob_binding);
379                        }
380
381                        if let Some(old_shadowed_glob) = resolution.shadowed_glob {
382                            assert!(old_shadowed_glob.is_glob_import());
383                            if glob_binding.res() != old_shadowed_glob.res() {
384                                resolution.shadowed_glob = Some(this.new_ambiguity_binding(
385                                    AmbiguityKind::GlobVsGlob,
386                                    old_shadowed_glob,
387                                    glob_binding,
388                                    false,
389                                ));
390                            } else if !old_shadowed_glob.vis.is_at_least(binding.vis, this.tcx) {
391                                resolution.shadowed_glob = Some(glob_binding);
392                            }
393                        } else {
394                            resolution.shadowed_glob = Some(glob_binding);
395                        }
396                    }
397                    (false, false) => {
398                        return Err(old_binding);
399                    }
400                }
401            } else {
402                resolution.binding = Some(binding);
403            }
404
405            Ok(())
406        })
407    }
408
409    fn new_ambiguity_binding(
410        &self,
411        ambiguity_kind: AmbiguityKind,
412        primary_binding: NameBinding<'ra>,
413        secondary_binding: NameBinding<'ra>,
414        warn_ambiguity: bool,
415    ) -> NameBinding<'ra> {
416        let ambiguity = Some((secondary_binding, ambiguity_kind));
417        let data = NameBindingData { ambiguity, warn_ambiguity, ..*primary_binding };
418        self.arenas.alloc_name_binding(data)
419    }
420
421    fn new_warn_ambiguity_binding(&self, binding: NameBinding<'ra>) -> NameBinding<'ra> {
422        assert!(binding.is_ambiguity_recursive());
423        self.arenas.alloc_name_binding(NameBindingData { warn_ambiguity: true, ..*binding })
424    }
425
426    // Use `f` to mutate the resolution of the name in the module.
427    // If the resolution becomes a success, define it in the module's glob importers.
428    fn update_resolution<T, F>(
429        &mut self,
430        module: Module<'ra>,
431        key: BindingKey,
432        warn_ambiguity: bool,
433        f: F,
434    ) -> T
435    where
436        F: FnOnce(&mut Resolver<'ra, 'tcx>, &mut NameResolution<'ra>) -> T,
437    {
438        // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
439        // during which the resolution might end up getting re-defined via a glob cycle.
440        let (binding, t, warn_ambiguity) = {
441            let resolution = &mut *self.resolution(module, key).borrow_mut();
442            let old_binding = resolution.binding();
443
444            let t = f(self, resolution);
445
446            if let Some(binding) = resolution.binding()
447                && old_binding != Some(binding)
448            {
449                (binding, t, warn_ambiguity || old_binding.is_some())
450            } else {
451                return t;
452            }
453        };
454
455        let Ok(glob_importers) = module.glob_importers.try_borrow_mut() else {
456            return t;
457        };
458
459        // Define or update `binding` in `module`s glob importers.
460        for import in glob_importers.iter() {
461            let mut ident = key.ident;
462            let scope = match ident.span.reverse_glob_adjust(module.expansion, import.span) {
463                Some(Some(def)) => self.expn_def_scope(def),
464                Some(None) => import.parent_scope.module,
465                None => continue,
466            };
467            if self.is_accessible_from(binding.vis, scope) {
468                let imported_binding = self.import(binding, *import);
469                let key = BindingKey { ident, ..key };
470                let _ = self.try_define(
471                    import.parent_scope.module,
472                    key,
473                    imported_binding,
474                    warn_ambiguity,
475                );
476            }
477        }
478
479        t
480    }
481
482    // Define a dummy resolution containing a `Res::Err` as a placeholder for a failed
483    // or indeterminate resolution, also mark such failed imports as used to avoid duplicate diagnostics.
484    fn import_dummy_binding(&mut self, import: Import<'ra>, is_indeterminate: bool) {
485        if let ImportKind::Single { target, ref target_bindings, .. } = import.kind {
486            if !(is_indeterminate || target_bindings.iter().all(|binding| binding.get().is_none()))
487            {
488                return; // Has resolution, do not create the dummy binding
489            }
490            let dummy_binding = self.dummy_binding;
491            let dummy_binding = self.import(dummy_binding, import);
492            self.per_ns(|this, ns| {
493                let key = BindingKey::new(target, ns);
494                let _ = this.try_define(import.parent_scope.module, key, dummy_binding, false);
495                this.update_resolution(import.parent_scope.module, key, false, |_, resolution| {
496                    resolution.single_imports.swap_remove(&import);
497                })
498            });
499            self.record_use(target, dummy_binding, Used::Other);
500        } else if import.imported_module.get().is_none() {
501            self.import_use_map.insert(import, Used::Other);
502            if let Some(id) = import.id() {
503                self.used_imports.insert(id);
504            }
505        }
506    }
507
508    // Import resolution
509    //
510    // This is a fixed-point algorithm. We resolve imports until our efforts
511    // are stymied by an unresolved import; then we bail out of the current
512    // module and continue. We terminate successfully once no more imports
513    // remain or unsuccessfully when no forward progress in resolving imports
514    // is made.
515
516    /// Resolves all imports for the crate. This method performs the fixed-
517    /// point iteration.
518    pub(crate) fn resolve_imports(&mut self) {
519        let mut prev_indeterminate_count = usize::MAX;
520        let mut indeterminate_count = self.indeterminate_imports.len() * 3;
521        while indeterminate_count < prev_indeterminate_count {
522            prev_indeterminate_count = indeterminate_count;
523            indeterminate_count = 0;
524            for import in mem::take(&mut self.indeterminate_imports) {
525                let import_indeterminate_count = self.resolve_import(import);
526                indeterminate_count += import_indeterminate_count;
527                match import_indeterminate_count {
528                    0 => self.determined_imports.push(import),
529                    _ => self.indeterminate_imports.push(import),
530                }
531            }
532        }
533    }
534
535    pub(crate) fn finalize_imports(&mut self) {
536        for module in self.arenas.local_modules().iter() {
537            self.finalize_resolutions_in(*module);
538        }
539
540        let mut seen_spans = FxHashSet::default();
541        let mut errors = vec![];
542        let mut prev_root_id: NodeId = NodeId::ZERO;
543        let determined_imports = mem::take(&mut self.determined_imports);
544        let indeterminate_imports = mem::take(&mut self.indeterminate_imports);
545
546        let mut glob_error = false;
547        for (is_indeterminate, import) in determined_imports
548            .iter()
549            .map(|i| (false, i))
550            .chain(indeterminate_imports.iter().map(|i| (true, i)))
551        {
552            let unresolved_import_error = self.finalize_import(*import);
553            // If this import is unresolved then create a dummy import
554            // resolution for it so that later resolve stages won't complain.
555            self.import_dummy_binding(*import, is_indeterminate);
556
557            let Some(err) = unresolved_import_error else { continue };
558
559            glob_error |= import.is_glob();
560
561            if let ImportKind::Single { source, ref source_bindings, .. } = import.kind
562                && source.name == kw::SelfLower
563                // Silence `unresolved import` error if E0429 is already emitted
564                && let Err(Determined) = source_bindings.value_ns.get()
565            {
566                continue;
567            }
568
569            if prev_root_id != NodeId::ZERO && prev_root_id != import.root_id && !errors.is_empty()
570            {
571                // In the case of a new import line, throw a diagnostic message
572                // for the previous line.
573                self.throw_unresolved_import_error(errors, glob_error);
574                errors = vec![];
575            }
576            if seen_spans.insert(err.span) {
577                errors.push((*import, err));
578                prev_root_id = import.root_id;
579            }
580        }
581
582        if !errors.is_empty() {
583            self.throw_unresolved_import_error(errors, glob_error);
584            return;
585        }
586
587        for import in &indeterminate_imports {
588            let path = import_path_to_string(
589                &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
590                &import.kind,
591                import.span,
592            );
593            // FIXME: there should be a better way of doing this than
594            // formatting this as a string then checking for `::`
595            if path.contains("::") {
596                let err = UnresolvedImportError {
597                    span: import.span,
598                    label: None,
599                    note: None,
600                    suggestion: None,
601                    candidates: None,
602                    segment: None,
603                    module: None,
604                };
605                errors.push((*import, err))
606            }
607        }
608
609        self.throw_unresolved_import_error(errors, glob_error);
610    }
611
612    pub(crate) fn check_hidden_glob_reexports(
613        &mut self,
614        exported_ambiguities: FxHashSet<NameBinding<'ra>>,
615    ) {
616        for module in self.arenas.local_modules().iter() {
617            for (key, resolution) in self.resolutions(*module).borrow().iter() {
618                let resolution = resolution.borrow();
619
620                let Some(binding) = resolution.binding else { continue };
621
622                if let NameBindingKind::Import { import, .. } = binding.kind
623                    && let Some((amb_binding, _)) = binding.ambiguity
624                    && binding.res() != Res::Err
625                    && exported_ambiguities.contains(&binding)
626                {
627                    self.lint_buffer.buffer_lint(
628                        AMBIGUOUS_GLOB_REEXPORTS,
629                        import.root_id,
630                        import.root_span,
631                        BuiltinLintDiag::AmbiguousGlobReexports {
632                            name: key.ident.to_string(),
633                            namespace: key.ns.descr().to_string(),
634                            first_reexport_span: import.root_span,
635                            duplicate_reexport_span: amb_binding.span,
636                        },
637                    );
638                }
639
640                if let Some(glob_binding) = resolution.shadowed_glob {
641                    if binding.res() != Res::Err
642                        && glob_binding.res() != Res::Err
643                        && let NameBindingKind::Import { import: glob_import, .. } =
644                            glob_binding.kind
645                        && let Some(glob_import_id) = glob_import.id()
646                        && let glob_import_def_id = self.local_def_id(glob_import_id)
647                        && self.effective_visibilities.is_exported(glob_import_def_id)
648                        && glob_binding.vis.is_public()
649                        && !binding.vis.is_public()
650                    {
651                        let binding_id = match binding.kind {
652                            NameBindingKind::Res(res) => {
653                                Some(self.def_id_to_node_id(res.def_id().expect_local()))
654                            }
655                            NameBindingKind::Module(module) => {
656                                Some(self.def_id_to_node_id(module.def_id().expect_local()))
657                            }
658                            NameBindingKind::Import { import, .. } => import.id(),
659                        };
660                        if let Some(binding_id) = binding_id {
661                            self.lint_buffer.buffer_lint(
662                                HIDDEN_GLOB_REEXPORTS,
663                                binding_id,
664                                binding.span,
665                                BuiltinLintDiag::HiddenGlobReexports {
666                                    name: key.ident.name.to_string(),
667                                    namespace: key.ns.descr().to_owned(),
668                                    glob_reexport_span: glob_binding.span,
669                                    private_item_span: binding.span,
670                                },
671                            );
672                        }
673                    }
674                }
675            }
676        }
677    }
678
679    fn throw_unresolved_import_error(
680        &mut self,
681        mut errors: Vec<(Import<'_>, UnresolvedImportError)>,
682        glob_error: bool,
683    ) {
684        errors.retain(|(_import, err)| match err.module {
685            // Skip `use` errors for `use foo::Bar;` if `foo.rs` has unrecovered parse errors.
686            Some(def_id) if self.mods_with_parse_errors.contains(&def_id) => false,
687            _ => true,
688        });
689        if errors.is_empty() {
690            return;
691        }
692
693        /// Upper limit on the number of `span_label` messages.
694        const MAX_LABEL_COUNT: usize = 10;
695
696        let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
697        let paths = errors
698            .iter()
699            .map(|(import, err)| {
700                let path = import_path_to_string(
701                    &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
702                    &import.kind,
703                    err.span,
704                );
705                format!("`{path}`")
706            })
707            .collect::<Vec<_>>();
708        let msg = format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);
709
710        let mut diag = struct_span_code_err!(self.dcx(), span, E0432, "{msg}");
711
712        if let Some((_, UnresolvedImportError { note: Some(note), .. })) = errors.iter().last() {
713            diag.note(note.clone());
714        }
715
716        for (import, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
717            if let Some(label) = err.label {
718                diag.span_label(err.span, label);
719            }
720
721            if let Some((suggestions, msg, applicability)) = err.suggestion {
722                if suggestions.is_empty() {
723                    diag.help(msg);
724                    continue;
725                }
726                diag.multipart_suggestion(msg, suggestions, applicability);
727            }
728
729            if let Some(candidates) = &err.candidates {
730                match &import.kind {
731                    ImportKind::Single { nested: false, source, target, .. } => import_candidates(
732                        self.tcx,
733                        &mut diag,
734                        Some(err.span),
735                        candidates,
736                        DiagMode::Import { append: false, unresolved_import: true },
737                        (source != target)
738                            .then(|| format!(" as {target}"))
739                            .as_deref()
740                            .unwrap_or(""),
741                    ),
742                    ImportKind::Single { nested: true, source, target, .. } => {
743                        import_candidates(
744                            self.tcx,
745                            &mut diag,
746                            None,
747                            candidates,
748                            DiagMode::Normal,
749                            (source != target)
750                                .then(|| format!(" as {target}"))
751                                .as_deref()
752                                .unwrap_or(""),
753                        );
754                    }
755                    _ => {}
756                }
757            }
758
759            if matches!(import.kind, ImportKind::Single { .. })
760                && let Some(segment) = err.segment
761                && let Some(module) = err.module
762            {
763                self.find_cfg_stripped(&mut diag, &segment, module)
764            }
765        }
766
767        let guar = diag.emit();
768        if glob_error {
769            self.glob_error = Some(guar);
770        }
771    }
772
773    /// Attempts to resolve the given import, returning:
774    /// - `0` means its resolution is determined.
775    /// - Other values mean that indeterminate exists under certain namespaces.
776    ///
777    /// Meanwhile, if resolve successful, the resolved bindings are written
778    /// into the module.
779    fn resolve_import(&mut self, import: Import<'ra>) -> usize {
780        debug!(
781            "(resolving import for module) resolving import `{}::...` in `{}`",
782            Segment::names_to_string(&import.module_path),
783            module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
784        );
785        let module = if let Some(module) = import.imported_module.get() {
786            module
787        } else {
788            let path_res = self.maybe_resolve_path(
789                &import.module_path,
790                None,
791                &import.parent_scope,
792                Some(import),
793            );
794
795            match path_res {
796                PathResult::Module(module) => module,
797                PathResult::Indeterminate => return 3,
798                PathResult::NonModule(..) | PathResult::Failed { .. } => return 0,
799            }
800        };
801
802        import.imported_module.set(Some(module));
803        let (source, target, source_bindings, target_bindings, type_ns_only) = match import.kind {
804            ImportKind::Single {
805                source,
806                target,
807                ref source_bindings,
808                ref target_bindings,
809                type_ns_only,
810                ..
811            } => (source, target, source_bindings, target_bindings, type_ns_only),
812            ImportKind::Glob { .. } => {
813                self.resolve_glob_import(import);
814                return 0;
815            }
816            _ => unreachable!(),
817        };
818
819        let mut indeterminate_count = 0;
820        self.per_ns(|this, ns| {
821            if !type_ns_only || ns == TypeNS {
822                if let Err(Undetermined) = source_bindings[ns].get() {
823                    let binding = this.maybe_resolve_ident_in_module(
824                        module,
825                        source,
826                        ns,
827                        &import.parent_scope,
828                        Some(import),
829                    );
830                    source_bindings[ns].set(binding);
831                } else {
832                    return;
833                };
834
835                let parent = import.parent_scope.module;
836                match source_bindings[ns].get() {
837                    Ok(binding) => {
838                        if binding.is_assoc_item()
839                            && !this.tcx.features().import_trait_associated_functions()
840                        {
841                            feature_err(
842                                this.tcx.sess,
843                                sym::import_trait_associated_functions,
844                                import.span,
845                                "`use` associated items of traits is unstable",
846                            )
847                            .emit();
848                        }
849
850                        let imported_binding = this.import(binding, import);
851                        target_bindings[ns].set(Some(imported_binding));
852                        this.define(parent, target, ns, imported_binding);
853                    }
854                    Err(Determined) => {
855                        // Don't update the resolution for underscores, because it was never added.
856                        if target.name != kw::Underscore {
857                            let key = BindingKey::new(target, ns);
858                            this.update_resolution(parent, key, false, |_, resolution| {
859                                resolution.single_imports.swap_remove(&import);
860                            });
861                        }
862                    }
863                    Err(Undetermined) => indeterminate_count += 1,
864                }
865            }
866        });
867
868        indeterminate_count
869    }
870
871    /// Performs final import resolution, consistency checks and error reporting.
872    ///
873    /// Optionally returns an unresolved import error. This error is buffered and used to
874    /// consolidate multiple unresolved import errors into a single diagnostic.
875    fn finalize_import(&mut self, import: Import<'ra>) -> Option<UnresolvedImportError> {
876        let ignore_binding = match &import.kind {
877            ImportKind::Single { target_bindings, .. } => target_bindings[TypeNS].get(),
878            _ => None,
879        };
880        let ambiguity_errors_len =
881            |errors: &Vec<AmbiguityError<'_>>| errors.iter().filter(|error| !error.warning).count();
882        let prev_ambiguity_errors_len = ambiguity_errors_len(&self.ambiguity_errors);
883        let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
884
885        // We'll provide more context to the privacy errors later, up to `len`.
886        let privacy_errors_len = self.privacy_errors.len();
887
888        let path_res = self.resolve_path(
889            &import.module_path,
890            None,
891            &import.parent_scope,
892            Some(finalize),
893            ignore_binding,
894            Some(import),
895        );
896
897        let no_ambiguity =
898            ambiguity_errors_len(&self.ambiguity_errors) == prev_ambiguity_errors_len;
899
900        let module = match path_res {
901            PathResult::Module(module) => {
902                // Consistency checks, analogous to `finalize_macro_resolutions`.
903                if let Some(initial_module) = import.imported_module.get() {
904                    if module != initial_module && no_ambiguity {
905                        span_bug!(import.span, "inconsistent resolution for an import");
906                    }
907                } else if self.privacy_errors.is_empty() {
908                    self.dcx()
909                        .create_err(CannotDetermineImportResolution { span: import.span })
910                        .emit();
911                }
912
913                module
914            }
915            PathResult::Failed {
916                is_error_from_last_segment: false,
917                span,
918                segment_name,
919                label,
920                suggestion,
921                module,
922                error_implied_by_parse_error: _,
923            } => {
924                if no_ambiguity {
925                    assert!(import.imported_module.get().is_none());
926                    self.report_error(
927                        span,
928                        ResolutionError::FailedToResolve {
929                            segment: Some(segment_name),
930                            label,
931                            suggestion,
932                            module,
933                        },
934                    );
935                }
936                return None;
937            }
938            PathResult::Failed {
939                is_error_from_last_segment: true,
940                span,
941                label,
942                suggestion,
943                module,
944                segment_name,
945                ..
946            } => {
947                if no_ambiguity {
948                    assert!(import.imported_module.get().is_none());
949                    let module = if let Some(ModuleOrUniformRoot::Module(m)) = module {
950                        m.opt_def_id()
951                    } else {
952                        None
953                    };
954                    let err = match self
955                        .make_path_suggestion(import.module_path.clone(), &import.parent_scope)
956                    {
957                        Some((suggestion, note)) => UnresolvedImportError {
958                            span,
959                            label: None,
960                            note,
961                            suggestion: Some((
962                                vec![(span, Segment::names_to_string(&suggestion))],
963                                String::from("a similar path exists"),
964                                Applicability::MaybeIncorrect,
965                            )),
966                            candidates: None,
967                            segment: Some(segment_name),
968                            module,
969                        },
970                        None => UnresolvedImportError {
971                            span,
972                            label: Some(label),
973                            note: None,
974                            suggestion,
975                            candidates: None,
976                            segment: Some(segment_name),
977                            module,
978                        },
979                    };
980                    return Some(err);
981                }
982                return None;
983            }
984            PathResult::NonModule(partial_res) => {
985                if no_ambiguity && partial_res.full_res() != Some(Res::Err) {
986                    // Check if there are no ambiguities and the result is not dummy.
987                    assert!(import.imported_module.get().is_none());
988                }
989                // The error was already reported earlier.
990                return None;
991            }
992            PathResult::Indeterminate => unreachable!(),
993        };
994
995        let (ident, target, source_bindings, target_bindings, type_ns_only, import_id) =
996            match import.kind {
997                ImportKind::Single {
998                    source,
999                    target,
1000                    ref source_bindings,
1001                    ref target_bindings,
1002                    type_ns_only,
1003                    id,
1004                    ..
1005                } => (source, target, source_bindings, target_bindings, type_ns_only, id),
1006                ImportKind::Glob { is_prelude, ref max_vis, id } => {
1007                    if import.module_path.len() <= 1 {
1008                        // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1009                        // 2 segments, so the `resolve_path` above won't trigger it.
1010                        let mut full_path = import.module_path.clone();
1011                        full_path.push(Segment::from_ident(Ident::dummy()));
1012                        self.lint_if_path_starts_with_module(Some(finalize), &full_path, None);
1013                    }
1014
1015                    if let ModuleOrUniformRoot::Module(module) = module
1016                        && module == import.parent_scope.module
1017                    {
1018                        // Importing a module into itself is not allowed.
1019                        return Some(UnresolvedImportError {
1020                            span: import.span,
1021                            label: Some(String::from("cannot glob-import a module into itself")),
1022                            note: None,
1023                            suggestion: None,
1024                            candidates: None,
1025                            segment: None,
1026                            module: None,
1027                        });
1028                    }
1029                    if !is_prelude
1030                        && let Some(max_vis) = max_vis.get()
1031                        && !max_vis.is_at_least(import.vis, self.tcx)
1032                    {
1033                        let def_id = self.local_def_id(id);
1034                        self.lint_buffer.buffer_lint(
1035                            UNUSED_IMPORTS,
1036                            id,
1037                            import.span,
1038                            BuiltinLintDiag::RedundantImportVisibility {
1039                                max_vis: max_vis.to_string(def_id, self.tcx),
1040                                import_vis: import.vis.to_string(def_id, self.tcx),
1041                                span: import.span,
1042                            },
1043                        );
1044                    }
1045                    return None;
1046                }
1047                _ => unreachable!(),
1048            };
1049
1050        if self.privacy_errors.len() != privacy_errors_len {
1051            // Get the Res for the last element, so that we can point to alternative ways of
1052            // importing it if available.
1053            let mut path = import.module_path.clone();
1054            path.push(Segment::from_ident(ident));
1055            if let PathResult::Module(ModuleOrUniformRoot::Module(module)) = self.resolve_path(
1056                &path,
1057                None,
1058                &import.parent_scope,
1059                Some(finalize),
1060                ignore_binding,
1061                None,
1062            ) {
1063                let res = module.res().map(|r| (r, ident));
1064                for error in &mut self.privacy_errors[privacy_errors_len..] {
1065                    error.outermost_res = res;
1066                }
1067            }
1068        }
1069
1070        let mut all_ns_err = true;
1071        self.per_ns(|this, ns| {
1072            if !type_ns_only || ns == TypeNS {
1073                let binding = this.resolve_ident_in_module(
1074                    module,
1075                    ident,
1076                    ns,
1077                    &import.parent_scope,
1078                    Some(Finalize { report_private: false, ..finalize }),
1079                    target_bindings[ns].get(),
1080                    Some(import),
1081                );
1082
1083                match binding {
1084                    Ok(binding) => {
1085                        // Consistency checks, analogous to `finalize_macro_resolutions`.
1086                        let initial_res = source_bindings[ns].get().map(|initial_binding| {
1087                            all_ns_err = false;
1088                            if let Some(target_binding) = target_bindings[ns].get()
1089                                && target.name == kw::Underscore
1090                                && initial_binding.is_extern_crate()
1091                                && !initial_binding.is_import()
1092                            {
1093                                let used = if import.module_path.is_empty() {
1094                                    Used::Scope
1095                                } else {
1096                                    Used::Other
1097                                };
1098                                this.record_use(ident, target_binding, used);
1099                            }
1100                            initial_binding.res()
1101                        });
1102                        let res = binding.res();
1103                        let has_ambiguity_error =
1104                            this.ambiguity_errors.iter().any(|error| !error.warning);
1105                        if res == Res::Err || has_ambiguity_error {
1106                            this.dcx()
1107                                .span_delayed_bug(import.span, "some error happened for an import");
1108                            return;
1109                        }
1110                        if let Ok(initial_res) = initial_res {
1111                            if res != initial_res {
1112                                span_bug!(import.span, "inconsistent resolution for an import");
1113                            }
1114                        } else if this.privacy_errors.is_empty() {
1115                            this.dcx()
1116                                .create_err(CannotDetermineImportResolution { span: import.span })
1117                                .emit();
1118                        }
1119                    }
1120                    Err(..) => {
1121                        // FIXME: This assert may fire if public glob is later shadowed by a private
1122                        // single import (see test `issue-55884-2.rs`). In theory single imports should
1123                        // always block globs, even if they are not yet resolved, so that this kind of
1124                        // self-inconsistent resolution never happens.
1125                        // Re-enable the assert when the issue is fixed.
1126                        // assert!(result[ns].get().is_err());
1127                    }
1128                }
1129            }
1130        });
1131
1132        if all_ns_err {
1133            let mut all_ns_failed = true;
1134            self.per_ns(|this, ns| {
1135                if !type_ns_only || ns == TypeNS {
1136                    let binding = this.resolve_ident_in_module(
1137                        module,
1138                        ident,
1139                        ns,
1140                        &import.parent_scope,
1141                        Some(finalize),
1142                        None,
1143                        None,
1144                    );
1145                    if binding.is_ok() {
1146                        all_ns_failed = false;
1147                    }
1148                }
1149            });
1150
1151            return if all_ns_failed {
1152                let resolutions = match module {
1153                    ModuleOrUniformRoot::Module(module) => Some(self.resolutions(module).borrow()),
1154                    _ => None,
1155                };
1156                let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
1157                let names = resolutions
1158                    .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1159                        if i.name == ident.name {
1160                            return None;
1161                        } // Never suggest the same name
1162                        match *resolution.borrow() {
1163                            NameResolution { binding: Some(name_binding), .. } => {
1164                                match name_binding.kind {
1165                                    NameBindingKind::Import { binding, .. } => {
1166                                        match binding.kind {
1167                                            // Never suggest the name that has binding error
1168                                            // i.e., the name that cannot be previously resolved
1169                                            NameBindingKind::Res(Res::Err) => None,
1170                                            _ => Some(i.name),
1171                                        }
1172                                    }
1173                                    _ => Some(i.name),
1174                                }
1175                            }
1176                            NameResolution { ref single_imports, .. }
1177                                if single_imports.is_empty() =>
1178                            {
1179                                None
1180                            }
1181                            _ => Some(i.name),
1182                        }
1183                    })
1184                    .collect::<Vec<Symbol>>();
1185
1186                let lev_suggestion =
1187                    find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
1188                        (
1189                            vec![(ident.span, suggestion.to_string())],
1190                            String::from("a similar name exists in the module"),
1191                            Applicability::MaybeIncorrect,
1192                        )
1193                    });
1194
1195                let (suggestion, note) =
1196                    match self.check_for_module_export_macro(import, module, ident) {
1197                        Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1198                        _ => (lev_suggestion, None),
1199                    };
1200
1201                let label = match module {
1202                    ModuleOrUniformRoot::Module(module) => {
1203                        let module_str = module_to_string(module);
1204                        if let Some(module_str) = module_str {
1205                            format!("no `{ident}` in `{module_str}`")
1206                        } else {
1207                            format!("no `{ident}` in the root")
1208                        }
1209                    }
1210                    _ => {
1211                        if !ident.is_path_segment_keyword() {
1212                            format!("no external crate `{ident}`")
1213                        } else {
1214                            // HACK(eddyb) this shows up for `self` & `super`, which
1215                            // should work instead - for now keep the same error message.
1216                            format!("no `{ident}` in the root")
1217                        }
1218                    }
1219                };
1220
1221                let parent_suggestion =
1222                    self.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true);
1223
1224                Some(UnresolvedImportError {
1225                    span: import.span,
1226                    label: Some(label),
1227                    note,
1228                    suggestion,
1229                    candidates: if !parent_suggestion.is_empty() {
1230                        Some(parent_suggestion)
1231                    } else {
1232                        None
1233                    },
1234                    module: import.imported_module.get().and_then(|module| {
1235                        if let ModuleOrUniformRoot::Module(m) = module {
1236                            m.opt_def_id()
1237                        } else {
1238                            None
1239                        }
1240                    }),
1241                    segment: Some(ident.name),
1242                })
1243            } else {
1244                // `resolve_ident_in_module` reported a privacy error.
1245                None
1246            };
1247        }
1248
1249        let mut reexport_error = None;
1250        let mut any_successful_reexport = false;
1251        let mut crate_private_reexport = false;
1252        self.per_ns(|this, ns| {
1253            let Ok(binding) = source_bindings[ns].get() else {
1254                return;
1255            };
1256
1257            if !binding.vis.is_at_least(import.vis, this.tcx) {
1258                reexport_error = Some((ns, binding));
1259                if let ty::Visibility::Restricted(binding_def_id) = binding.vis
1260                    && binding_def_id.is_top_level_module()
1261                {
1262                    crate_private_reexport = true;
1263                }
1264            } else {
1265                any_successful_reexport = true;
1266            }
1267        });
1268
1269        // All namespaces must be re-exported with extra visibility for an error to occur.
1270        if !any_successful_reexport {
1271            let (ns, binding) = reexport_error.unwrap();
1272            if let Some(extern_crate_id) = pub_use_of_private_extern_crate_hack(import, binding) {
1273                self.lint_buffer.buffer_lint(
1274                    PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1275                    import_id,
1276                    import.span,
1277                    BuiltinLintDiag::PrivateExternCrateReexport {
1278                        source: ident,
1279                        extern_crate_span: self.tcx.source_span(self.local_def_id(extern_crate_id)),
1280                    },
1281                );
1282            } else if ns == TypeNS {
1283                let err = if crate_private_reexport {
1284                    self.dcx()
1285                        .create_err(CannotBeReexportedCratePublicNS { span: import.span, ident })
1286                } else {
1287                    self.dcx().create_err(CannotBeReexportedPrivateNS { span: import.span, ident })
1288                };
1289                err.emit();
1290            } else {
1291                let mut err = if crate_private_reexport {
1292                    self.dcx()
1293                        .create_err(CannotBeReexportedCratePublic { span: import.span, ident })
1294                } else {
1295                    self.dcx().create_err(CannotBeReexportedPrivate { span: import.span, ident })
1296                };
1297
1298                match binding.kind {
1299                        NameBindingKind::Res(Res::Def(DefKind::Macro(_), def_id))
1300                            // exclude decl_macro
1301                            if self.get_macro_by_def_id(def_id).macro_rules =>
1302                        {
1303                            err.subdiagnostic( ConsiderAddingMacroExport {
1304                                span: binding.span,
1305                            });
1306                        }
1307                        _ => {
1308                            err.subdiagnostic( ConsiderMarkingAsPub {
1309                                span: import.span,
1310                                ident,
1311                            });
1312                        }
1313                    }
1314                err.emit();
1315            }
1316        }
1317
1318        if import.module_path.len() <= 1 {
1319            // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1320            // 2 segments, so the `resolve_path` above won't trigger it.
1321            let mut full_path = import.module_path.clone();
1322            full_path.push(Segment::from_ident(ident));
1323            self.per_ns(|this, ns| {
1324                if let Ok(binding) = source_bindings[ns].get() {
1325                    this.lint_if_path_starts_with_module(Some(finalize), &full_path, Some(binding));
1326                }
1327            });
1328        }
1329
1330        // Record what this import resolves to for later uses in documentation,
1331        // this may resolve to either a value or a type, but for documentation
1332        // purposes it's good enough to just favor one over the other.
1333        self.per_ns(|this, ns| {
1334            if let Ok(binding) = source_bindings[ns].get() {
1335                this.import_res_map.entry(import_id).or_default()[ns] = Some(binding.res());
1336            }
1337        });
1338
1339        debug!("(resolving single import) successfully resolved import");
1340        None
1341    }
1342
1343    pub(crate) fn check_for_redundant_imports(&mut self, import: Import<'ra>) -> bool {
1344        // This function is only called for single imports.
1345        let ImportKind::Single {
1346            source, target, ref source_bindings, ref target_bindings, id, ..
1347        } = import.kind
1348        else {
1349            unreachable!()
1350        };
1351
1352        // Skip if the import is of the form `use source as target` and source != target.
1353        if source != target {
1354            return false;
1355        }
1356
1357        // Skip if the import was produced by a macro.
1358        if import.parent_scope.expansion != LocalExpnId::ROOT {
1359            return false;
1360        }
1361
1362        // Skip if we are inside a named module (in contrast to an anonymous
1363        // module defined by a block).
1364        // Skip if the import is public or was used through non scope-based resolution,
1365        // e.g. through a module-relative path.
1366        if self.import_use_map.get(&import) == Some(&Used::Other)
1367            || self.effective_visibilities.is_exported(self.local_def_id(id))
1368        {
1369            return false;
1370        }
1371
1372        let mut is_redundant = true;
1373        let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1374        self.per_ns(|this, ns| {
1375            if is_redundant && let Ok(binding) = source_bindings[ns].get() {
1376                if binding.res() == Res::Err {
1377                    return;
1378                }
1379
1380                match this.early_resolve_ident_in_lexical_scope(
1381                    target,
1382                    ScopeSet::All(ns),
1383                    &import.parent_scope,
1384                    None,
1385                    false,
1386                    target_bindings[ns].get(),
1387                    None,
1388                ) {
1389                    Ok(other_binding) => {
1390                        is_redundant = binding.res() == other_binding.res()
1391                            && !other_binding.is_ambiguity_recursive();
1392                        if is_redundant {
1393                            redundant_span[ns] =
1394                                Some((other_binding.span, other_binding.is_import()));
1395                        }
1396                    }
1397                    Err(_) => is_redundant = false,
1398                }
1399            }
1400        });
1401
1402        if is_redundant && !redundant_span.is_empty() {
1403            let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1404            redundant_spans.sort();
1405            redundant_spans.dedup();
1406            self.lint_buffer.buffer_lint(
1407                REDUNDANT_IMPORTS,
1408                id,
1409                import.span,
1410                BuiltinLintDiag::RedundantImport(redundant_spans, source),
1411            );
1412            return true;
1413        }
1414
1415        false
1416    }
1417
1418    fn resolve_glob_import(&mut self, import: Import<'ra>) {
1419        // This function is only called for glob imports.
1420        let ImportKind::Glob { id, is_prelude, .. } = import.kind else { unreachable!() };
1421
1422        let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else {
1423            self.dcx().emit_err(CannotGlobImportAllCrates { span: import.span });
1424            return;
1425        };
1426
1427        if module.is_trait() && !self.tcx.features().import_trait_associated_functions() {
1428            feature_err(
1429                self.tcx.sess,
1430                sym::import_trait_associated_functions,
1431                import.span,
1432                "`use` associated items of traits is unstable",
1433            )
1434            .emit();
1435        }
1436
1437        if module == import.parent_scope.module {
1438            return;
1439        } else if is_prelude {
1440            self.prelude = Some(module);
1441            return;
1442        }
1443
1444        // Add to module's glob_importers
1445        module.glob_importers.borrow_mut().push(import);
1446
1447        // Ensure that `resolutions` isn't borrowed during `try_define`,
1448        // since it might get updated via a glob cycle.
1449        let bindings = self
1450            .resolutions(module)
1451            .borrow()
1452            .iter()
1453            .filter_map(|(key, resolution)| {
1454                resolution.borrow().binding().map(|binding| (*key, binding))
1455            })
1456            .collect::<Vec<_>>();
1457        for (mut key, binding) in bindings {
1458            let scope = match key.ident.span.reverse_glob_adjust(module.expansion, import.span) {
1459                Some(Some(def)) => self.expn_def_scope(def),
1460                Some(None) => import.parent_scope.module,
1461                None => continue,
1462            };
1463            if self.is_accessible_from(binding.vis, scope) {
1464                let imported_binding = self.import(binding, import);
1465                let warn_ambiguity = self
1466                    .resolution(import.parent_scope.module, key)
1467                    .borrow()
1468                    .binding()
1469                    .is_some_and(|binding| binding.warn_ambiguity_recursive());
1470                let _ = self.try_define(
1471                    import.parent_scope.module,
1472                    key,
1473                    imported_binding,
1474                    warn_ambiguity,
1475                );
1476            }
1477        }
1478
1479        // Record the destination of this import
1480        self.record_partial_res(id, PartialRes::new(module.res().unwrap()));
1481    }
1482
1483    // Miscellaneous post-processing, including recording re-exports,
1484    // reporting conflicts, and reporting unresolved imports.
1485    fn finalize_resolutions_in(&mut self, module: Module<'ra>) {
1486        // Since import resolution is finished, globs will not define any more names.
1487        *module.globs.borrow_mut() = Vec::new();
1488
1489        let Some(def_id) = module.opt_def_id() else { return };
1490
1491        let mut children = Vec::new();
1492
1493        module.for_each_child(self, |this, ident, _, binding| {
1494            let res = binding.res().expect_non_local();
1495            let error_ambiguity = binding.is_ambiguity_recursive() && !binding.warn_ambiguity;
1496            if res != def::Res::Err && !error_ambiguity {
1497                let mut reexport_chain = SmallVec::new();
1498                let mut next_binding = binding;
1499                while let NameBindingKind::Import { binding, import, .. } = next_binding.kind {
1500                    reexport_chain.push(import.simplify(this));
1501                    next_binding = binding;
1502                }
1503
1504                children.push(ModChild { ident, res, vis: binding.vis, reexport_chain });
1505            }
1506        });
1507
1508        if !children.is_empty() {
1509            // Should be fine because this code is only called for local modules.
1510            self.module_children.insert(def_id.expect_local(), children);
1511        }
1512    }
1513}
1514
1515fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
1516    let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1517    let global = !names.is_empty() && names[0].name == kw::PathRoot;
1518    if let Some(pos) = pos {
1519        let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1520        names_to_string(names.iter().map(|ident| ident.name))
1521    } else {
1522        let names = if global { &names[1..] } else { names };
1523        if names.is_empty() {
1524            import_kind_to_string(import_kind)
1525        } else {
1526            format!(
1527                "{}::{}",
1528                names_to_string(names.iter().map(|ident| ident.name)),
1529                import_kind_to_string(import_kind),
1530            )
1531        }
1532    }
1533}
1534
1535fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1536    match import_kind {
1537        ImportKind::Single { source, .. } => source.to_string(),
1538        ImportKind::Glob { .. } => "*".to_string(),
1539        ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1540        ImportKind::MacroUse { .. } => "#[macro_use]".to_string(),
1541        ImportKind::MacroExport => "#[macro_export]".to_string(),
1542    }
1543}