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