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