rustc_resolve/
imports.rs

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