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