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