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