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