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