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