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