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