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