]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/resolve_imports.rs
Rollup merge of #53413 - eddyb:featured-in-the-latest-edition, r=varkor
[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::{FxHashMap, 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::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                     let name = ident.name;
246                     // Forbid expanded shadowing to avoid time travel.
247                     if restricted_shadowing &&
248                        binding.expansion != Mark::root() &&
249                        ns != MacroNS && // In MacroNS, `try_define` always forbids this shadowing
250                        binding.def() != shadowed_glob.def() {
251                         self.ambiguity_errors.push(AmbiguityError {
252                             span: path_span,
253                             name,
254                             lexical: false,
255                             b1: binding,
256                             b2: shadowed_glob,
257                         });
258                     }
259                 }
260                 if self.record_use(ident, ns, binding, path_span) {
261                     return Ok(self.dummy_binding);
262                 }
263                 if !self.is_accessible(binding.vis) {
264                     self.privacy_errors.push(PrivacyError(path_span, ident.name, binding));
265                 }
266             }
267
268             return resolution.binding.ok_or(Determined);
269         }
270
271         let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
272             // `extern crate` are always usable for backwards compatibility, see issue #37020.
273             let usable = this.is_accessible(binding.vis) || binding.is_extern_crate();
274             if usable { Ok(binding) } else { Err(Determined) }
275         };
276
277         // Items and single imports are not shadowable, if we have one, then it's determined.
278         if let Some(binding) = resolution.binding {
279             if !binding.is_glob_import() {
280                 return check_usable(self, binding);
281             }
282         }
283
284         // --- From now on we either have a glob resolution or no resolution. ---
285
286         // Check if one of single imports can still define the name,
287         // if it can then our result is not determined and can be invalidated.
288         for single_import in &resolution.single_imports {
289             if !self.is_accessible(single_import.vis.get()) {
290                 continue;
291             }
292             let module = unwrap_or!(single_import.imported_module.get(), return Err(Undetermined));
293             let ident = match single_import.subclass {
294                 SingleImport { source, .. } => source,
295                 _ => unreachable!(),
296             };
297             match self.resolve_ident_in_module(module, ident, ns, false, path_span) {
298                 Err(Determined) => continue,
299                 Ok(_) | Err(Undetermined) => return Err(Undetermined),
300             }
301         }
302
303         // So we have a resolution that's from a glob import. This resolution is determined
304         // if it cannot be shadowed by some new item/import expanded from a macro.
305         // This happens either if there are no unexpanded macros, or expanded names cannot
306         // shadow globs (that happens in macro namespace or with restricted shadowing).
307         //
308         // Additionally, any macro in any module can plant names in the root module if it creates
309         // `macro_export` macros, so the root module effectively has unresolved invocations if any
310         // module has unresolved invocations.
311         // However, it causes resolution/expansion to stuck too often (#53144), so, to make
312         // progress, we have to ignore those potential unresolved invocations from other modules
313         // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
314         // shadowing is enabled, see `macro_expanded_macro_export_errors`).
315         let unexpanded_macros = !module.unresolved_invocations.borrow().is_empty();
316         if let Some(binding) = resolution.binding {
317             if !unexpanded_macros || ns == MacroNS || restricted_shadowing {
318                 return check_usable(self, binding);
319             } else {
320                 return Err(Undetermined);
321             }
322         }
323
324         // --- From now on we have no resolution. ---
325
326         // Now we are in situation when new item/import can appear only from a glob or a macro
327         // expansion. With restricted shadowing names from globs and macro expansions cannot
328         // shadow names from outer scopes, so we can freely fallback from module search to search
329         // in outer scopes. To continue search in outer scopes we have to lie a bit and return
330         // `Determined` to `resolve_lexical_macro_path_segment` even if the correct answer
331         // for in-module resolution could be `Undetermined`.
332         if restricted_shadowing {
333             return Err(Determined);
334         }
335
336         // Check if one of unexpanded macros can still define the name,
337         // if it can then our "no resolution" result is not determined and can be invalidated.
338         if unexpanded_macros {
339             return Err(Undetermined);
340         }
341
342         // Check if one of glob imports can still define the name,
343         // if it can then our "no resolution" result is not determined and can be invalidated.
344         for glob_import in module.globs.borrow().iter() {
345             if !self.is_accessible(glob_import.vis.get()) {
346                 continue
347             }
348             let module = match glob_import.imported_module.get() {
349                 Some(ModuleOrUniformRoot::Module(module)) => module,
350                 Some(ModuleOrUniformRoot::UniformRoot(_)) => continue,
351                 None => return Err(Undetermined),
352             };
353             let (orig_current_module, mut ident) = (self.current_module, ident.modern());
354             match ident.span.glob_adjust(module.expansion, glob_import.span.ctxt().modern()) {
355                 Some(Some(def)) => self.current_module = self.macro_def_scope(def),
356                 Some(None) => {}
357                 None => continue,
358             };
359             let result = self.resolve_ident_in_module_unadjusted(
360                 ModuleOrUniformRoot::Module(module),
361                 ident,
362                 ns,
363                 false,
364                 false,
365                 path_span,
366             );
367             self.current_module = orig_current_module;
368             match result {
369                 Err(Determined) => continue,
370                 Ok(_) | Err(Undetermined) => return Err(Undetermined),
371             }
372         }
373
374         // No resolution and no one else can define the name - determinate error.
375         Err(Determined)
376     }
377
378     // Add an import directive to the current module.
379     pub fn add_import_directive(&mut self,
380                                 module_path: Vec<Ident>,
381                                 subclass: ImportDirectiveSubclass<'a>,
382                                 span: Span,
383                                 id: NodeId,
384                                 root_span: Span,
385                                 root_id: NodeId,
386                                 vis: ty::Visibility,
387                                 expansion: Mark,
388                                 is_uniform_paths_canary: bool) {
389         let current_module = self.current_module;
390         let directive = self.arenas.alloc_import_directive(ImportDirective {
391             parent: current_module,
392             module_path,
393             imported_module: Cell::new(None),
394             subclass,
395             span,
396             id,
397             root_span,
398             root_id,
399             vis: Cell::new(vis),
400             expansion,
401             used: Cell::new(false),
402             is_uniform_paths_canary,
403         });
404
405         debug!("add_import_directive({:?})", directive);
406
407         self.indeterminate_imports.push(directive);
408         match directive.subclass {
409             SingleImport { target, type_ns_only, .. } => {
410                 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
411                     let mut resolution = this.resolution(current_module, target, ns).borrow_mut();
412                     resolution.single_imports.insert(PtrKey(directive));
413                 });
414             }
415             // We don't add prelude imports to the globs since they only affect lexical scopes,
416             // which are not relevant to import resolution.
417             GlobImport { is_prelude: true, .. } => {}
418             GlobImport { .. } => self.current_module.globs.borrow_mut().push(directive),
419             _ => unreachable!(),
420         }
421     }
422
423     // Given a binding and an import directive that resolves to it,
424     // return the corresponding binding defined by the import directive.
425     pub fn import(&self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>)
426                   -> &'a NameBinding<'a> {
427         let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) ||
428                      // c.f. `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
429                      !directive.is_glob() && binding.is_extern_crate() {
430             directive.vis.get()
431         } else {
432             binding.pseudo_vis()
433         };
434
435         if let GlobImport { ref max_vis, .. } = directive.subclass {
436             if vis == directive.vis.get() || vis.is_at_least(max_vis.get(), self) {
437                 max_vis.set(vis)
438             }
439         }
440
441         self.arenas.alloc_name_binding(NameBinding {
442             kind: NameBindingKind::Import {
443                 binding,
444                 directive,
445                 used: Cell::new(false),
446             },
447             span: directive.span,
448             vis,
449             expansion: directive.expansion,
450         })
451     }
452
453     // Define the name or return the existing binding if there is a collision.
454     pub fn try_define(&mut self,
455                       module: Module<'a>,
456                       ident: Ident,
457                       ns: Namespace,
458                       binding: &'a NameBinding<'a>)
459                       -> Result<(), &'a NameBinding<'a>> {
460         self.update_resolution(module, ident, ns, |this, resolution| {
461             if let Some(old_binding) = resolution.binding {
462                 if binding.is_glob_import() {
463                     if !old_binding.is_glob_import() &&
464                        !(ns == MacroNS && old_binding.expansion != Mark::root()) {
465                         resolution.shadowed_glob = Some(binding);
466                     } else if binding.def() != old_binding.def() {
467                         resolution.binding = Some(this.ambiguity(old_binding, binding));
468                     } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
469                         // We are glob-importing the same item but with greater visibility.
470                         resolution.binding = Some(binding);
471                     }
472                 } else if old_binding.is_glob_import() {
473                     if ns == MacroNS && binding.expansion != Mark::root() &&
474                        binding.def() != old_binding.def() {
475                         resolution.binding = Some(this.ambiguity(binding, old_binding));
476                     } else {
477                         resolution.binding = Some(binding);
478                         resolution.shadowed_glob = Some(old_binding);
479                     }
480                 } else if let (&NameBindingKind::Def(_, true), &NameBindingKind::Def(_, true)) =
481                         (&old_binding.kind, &binding.kind) {
482
483                     this.session.buffer_lint_with_diagnostic(
484                         DUPLICATE_MACRO_EXPORTS,
485                         CRATE_NODE_ID,
486                         binding.span,
487                         &format!("a macro named `{}` has already been exported", ident),
488                         BuiltinLintDiagnostics::DuplicatedMacroExports(
489                             ident, old_binding.span, binding.span));
490
491                     resolution.binding = Some(binding);
492                 } else {
493                     return Err(old_binding);
494                 }
495             } else {
496                 resolution.binding = Some(binding);
497             }
498
499             Ok(())
500         })
501     }
502
503     pub fn ambiguity(&self, b1: &'a NameBinding<'a>, b2: &'a NameBinding<'a>)
504                      -> &'a NameBinding<'a> {
505         self.arenas.alloc_name_binding(NameBinding {
506             kind: NameBindingKind::Ambiguity { b1, b2 },
507             vis: if b1.vis.is_at_least(b2.vis, self) { b1.vis } else { b2.vis },
508             span: b1.span,
509             expansion: Mark::root(),
510         })
511     }
512
513     // Use `f` to mutate the resolution of the name in the module.
514     // If the resolution becomes a success, define it in the module's glob importers.
515     fn update_resolution<T, F>(&mut self, module: Module<'a>, ident: Ident, ns: Namespace, f: F)
516                                -> T
517         where F: FnOnce(&mut Resolver<'a, 'crateloader>, &mut NameResolution<'a>) -> T
518     {
519         // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
520         // during which the resolution might end up getting re-defined via a glob cycle.
521         let (binding, t) = {
522             let resolution = &mut *self.resolution(module, ident, ns).borrow_mut();
523             let old_binding = resolution.binding();
524
525             let t = f(self, resolution);
526
527             match resolution.binding() {
528                 _ if old_binding.is_some() => return t,
529                 None => return t,
530                 Some(binding) => match old_binding {
531                     Some(old_binding) if ptr::eq(old_binding, binding) => return t,
532                     _ => (binding, t),
533                 }
534             }
535         };
536
537         // Define `binding` in `module`s glob importers.
538         for directive in module.glob_importers.borrow_mut().iter() {
539             let mut ident = ident.modern();
540             let scope = match ident.span.reverse_glob_adjust(module.expansion,
541                                                              directive.span.ctxt().modern()) {
542                 Some(Some(def)) => self.macro_def_scope(def),
543                 Some(None) => directive.parent,
544                 None => continue,
545             };
546             if self.is_accessible_from(binding.vis, scope) {
547                 let imported_binding = self.import(binding, directive);
548                 let _ = self.try_define(directive.parent, ident, ns, imported_binding);
549             }
550         }
551
552         t
553     }
554
555     // Define a "dummy" resolution containing a Def::Err as a placeholder for a
556     // failed resolution
557     fn import_dummy_binding(&mut self, directive: &'a ImportDirective<'a>) {
558         if let SingleImport { target, .. } = directive.subclass {
559             let dummy_binding = self.dummy_binding;
560             let dummy_binding = self.import(dummy_binding, directive);
561             self.per_ns(|this, ns| {
562                 let _ = this.try_define(directive.parent, target, ns, dummy_binding);
563             });
564         }
565     }
566 }
567
568 pub struct ImportResolver<'a, 'b: 'a, 'c: 'a + 'b> {
569     pub resolver: &'a mut Resolver<'b, 'c>,
570 }
571
572 impl<'a, 'b: 'a, 'c: 'a + 'b> ::std::ops::Deref for ImportResolver<'a, 'b, 'c> {
573     type Target = Resolver<'b, 'c>;
574     fn deref(&self) -> &Resolver<'b, 'c> {
575         self.resolver
576     }
577 }
578
579 impl<'a, 'b: 'a, 'c: 'a + 'b> ::std::ops::DerefMut for ImportResolver<'a, 'b, 'c> {
580     fn deref_mut(&mut self) -> &mut Resolver<'b, 'c> {
581         self.resolver
582     }
583 }
584
585 impl<'a, 'b: 'a, 'c: 'a + 'b> ty::DefIdTree for &'a ImportResolver<'a, 'b, 'c> {
586     fn parent(self, id: DefId) -> Option<DefId> {
587         self.resolver.parent(id)
588     }
589 }
590
591 impl<'a, 'b:'a, 'c: 'b> ImportResolver<'a, 'b, 'c> {
592     // Import resolution
593     //
594     // This is a fixed-point algorithm. We resolve imports until our efforts
595     // are stymied by an unresolved import; then we bail out of the current
596     // module and continue. We terminate successfully once no more imports
597     // remain or unsuccessfully when no forward progress in resolving imports
598     // is made.
599
600     /// Resolves all imports for the crate. This method performs the fixed-
601     /// point iteration.
602     pub fn resolve_imports(&mut self) {
603         let mut prev_num_indeterminates = self.indeterminate_imports.len() + 1;
604         while self.indeterminate_imports.len() < prev_num_indeterminates {
605             prev_num_indeterminates = self.indeterminate_imports.len();
606             for import in mem::replace(&mut self.indeterminate_imports, Vec::new()) {
607                 match self.resolve_import(&import) {
608                     true => self.determined_imports.push(import),
609                     false => self.indeterminate_imports.push(import),
610                 }
611             }
612         }
613     }
614
615     pub fn finalize_imports(&mut self) {
616         for module in self.arenas.local_modules().iter() {
617             self.finalize_resolutions_in(module);
618         }
619
620         #[derive(Default)]
621         struct UniformPathsCanaryResult {
622             module_scope: Option<Span>,
623             block_scopes: Vec<Span>,
624         }
625         // Collect all tripped `uniform_paths` canaries separately.
626         let mut uniform_paths_canaries: BTreeMap<
627             (Span, NodeId),
628             (Name, PerNS<UniformPathsCanaryResult>),
629         > = BTreeMap::new();
630
631         let mut errors = false;
632         let mut seen_spans = FxHashSet();
633         for i in 0 .. self.determined_imports.len() {
634             let import = self.determined_imports[i];
635             let error = self.finalize_import(import);
636
637             // For a `#![feature(uniform_paths)]` `use self::x as _` canary,
638             // failure is ignored, while success may cause an ambiguity error.
639             if import.is_uniform_paths_canary {
640                 if error.is_some() {
641                     continue;
642                 }
643
644                 let (name, result) = match import.subclass {
645                     SingleImport { source, ref result, .. } => (source.name, result),
646                     _ => bug!(),
647                 };
648
649                 let has_explicit_self =
650                     import.module_path.len() > 0 &&
651                     import.module_path[0].name == keywords::SelfValue.name();
652
653                 let (prev_name, canary_results) =
654                     uniform_paths_canaries.entry((import.span, import.id))
655                         .or_insert((name, PerNS::default()));
656
657                 // All the canaries with the same `id` should have the same `name`.
658                 assert_eq!(*prev_name, name);
659
660                 self.per_ns(|_, ns| {
661                     if let Some(result) = result[ns].get().ok() {
662                         if has_explicit_self {
663                             // There should only be one `self::x` (module-scoped) canary.
664                             assert_eq!(canary_results[ns].module_scope, None);
665                             canary_results[ns].module_scope = Some(result.span);
666                         } else {
667                             canary_results[ns].block_scopes.push(result.span);
668                         }
669                     }
670                 });
671             } else if let Some((span, err)) = error {
672                 errors = true;
673
674                 if let SingleImport { source, ref result, .. } = import.subclass {
675                     if source.name == "self" {
676                         // Silence `unresolved import` error if E0429 is already emitted
677                         match result.value_ns.get() {
678                             Err(Determined) => continue,
679                             _ => {},
680                         }
681                     }
682                 }
683
684                 // If the error is a single failed import then create a "fake" import
685                 // resolution for it so that later resolve stages won't complain.
686                 self.import_dummy_binding(import);
687                 if !seen_spans.contains(&span) {
688                     let path = import_path_to_string(&import.module_path[..],
689                                                      &import.subclass,
690                                                      span);
691                     let error = ResolutionError::UnresolvedImport(Some((span, &path, &err)));
692                     resolve_error(self.resolver, span, error);
693                     seen_spans.insert(span);
694                 }
695             }
696         }
697
698         for ((span, _), (name, results)) in uniform_paths_canaries {
699             self.per_ns(|this, ns| {
700                 let results = &results[ns];
701
702                 let has_external_crate =
703                     ns == TypeNS && this.extern_prelude.contains(&name);
704
705                 // An ambiguity requires more than one possible resolution.
706                 let possible_resultions =
707                     (has_external_crate as usize) +
708                     (results.module_scope.is_some() as usize) +
709                     (!results.block_scopes.is_empty() as usize);
710                 if possible_resultions <= 1 {
711                     return;
712                 }
713
714                 errors = true;
715
716                 // Special-case the error when `self::x` finds its own `use x;`.
717                 if has_external_crate &&
718                    results.module_scope == Some(span) &&
719                    results.block_scopes.is_empty() {
720                     let msg = format!("`{}` import is redundant", name);
721                     this.session.struct_span_err(span, &msg)
722                         .span_label(span,
723                             format!("refers to external crate `::{}`", name))
724                         .span_label(span,
725                             format!("defines `self::{}`, shadowing itself", name))
726                         .help(&format!("remove or write `::{}` explicitly instead", name))
727                         .note("relative `use` paths enabled by `#![feature(uniform_paths)]`")
728                         .emit();
729                     return;
730                 }
731
732                 let msg = format!("`{}` import is ambiguous", name);
733                 let mut err = this.session.struct_span_err(span, &msg);
734                 let mut suggestion_choices = String::new();
735                 if has_external_crate {
736                     write!(suggestion_choices, "`::{}`", name);
737                     err.span_label(span,
738                         format!("can refer to external crate `::{}`", name));
739                 }
740                 if let Some(span) = results.module_scope {
741                     if !suggestion_choices.is_empty() {
742                         suggestion_choices.push_str(" or ");
743                     }
744                     write!(suggestion_choices, "`self::{}`", name);
745                     err.span_label(span,
746                         format!("can refer to `self::{}`", name));
747                 }
748                 for &span in &results.block_scopes {
749                     err.span_label(span,
750                         format!("shadowed by block-scoped `{}`", name));
751                 }
752                 err.help(&format!("write {} explicitly instead", suggestion_choices));
753                 err.note("relative `use` paths enabled by `#![feature(uniform_paths)]`");
754                 err.emit();
755             });
756         }
757
758         // Report unresolved imports only if no hard error was already reported
759         // to avoid generating multiple errors on the same import.
760         if !errors {
761             for import in &self.indeterminate_imports {
762                 if import.is_uniform_paths_canary {
763                     continue;
764                 }
765
766                 let error = ResolutionError::UnresolvedImport(None);
767                 resolve_error(self.resolver, import.span, error);
768                 break;
769             }
770         }
771     }
772
773     /// Attempts to resolve the given import, returning true if its resolution is determined.
774     /// If successful, the resolved bindings are written into the module.
775     fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool {
776         debug!("(resolving import for module) resolving import `{}::...` in `{}`",
777                names_to_string(&directive.module_path[..]),
778                module_to_string(self.current_module).unwrap_or("???".to_string()));
779
780         self.current_module = directive.parent;
781
782         let module = if let Some(module) = directive.imported_module.get() {
783             module
784         } else {
785             let vis = directive.vis.get();
786             // For better failure detection, pretend that the import will not define any names
787             // while resolving its module path.
788             directive.vis.set(ty::Visibility::Invisible);
789             let result = self.resolve_path(
790                 Some(if directive.is_uniform_paths_canary {
791                     ModuleOrUniformRoot::Module(directive.parent)
792                 } else {
793                     ModuleOrUniformRoot::UniformRoot(keywords::Invalid.name())
794                 }),
795                 &directive.module_path[..],
796                 None,
797                 false,
798                 directive.span,
799                 directive.crate_lint(),
800             );
801             directive.vis.set(vis);
802
803             match result {
804                 PathResult::Module(module) => module,
805                 PathResult::Indeterminate => return false,
806                 _ => return true,
807             }
808         };
809
810         directive.imported_module.set(Some(module));
811         let (source, target, result, type_ns_only) = match directive.subclass {
812             SingleImport { source, target, ref result, type_ns_only } =>
813                 (source, target, result, type_ns_only),
814             GlobImport { .. } => {
815                 self.resolve_glob_import(directive);
816                 return true;
817             }
818             _ => unreachable!(),
819         };
820
821         let mut indeterminate = false;
822         self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
823             if let Err(Undetermined) = result[ns].get() {
824                 result[ns].set(this.resolve_ident_in_module(module,
825                                                             source,
826                                                             ns,
827                                                             false,
828                                                             directive.span));
829             } else {
830                 return
831             };
832
833             let parent = directive.parent;
834             match result[ns].get() {
835                 Err(Undetermined) => indeterminate = true,
836                 Err(Determined) => {
837                     this.update_resolution(parent, target, ns, |_, resolution| {
838                         resolution.single_imports.remove(&PtrKey(directive));
839                     });
840                 }
841                 Ok(binding) if !binding.is_importable() => {
842                     let msg = format!("`{}` is not directly importable", target);
843                     struct_span_err!(this.session, directive.span, E0253, "{}", &msg)
844                         .span_label(directive.span, "cannot be imported directly")
845                         .emit();
846                     // Do not import this illegal binding. Import a dummy binding and pretend
847                     // everything is fine
848                     this.import_dummy_binding(directive);
849                 }
850                 Ok(binding) => {
851                     let imported_binding = this.import(binding, directive);
852                     let conflict = this.try_define(parent, target, ns, imported_binding);
853                     if let Err(old_binding) = conflict {
854                         this.report_conflict(parent, target, ns, imported_binding, old_binding);
855                     }
856                 }
857             }
858         });
859
860         !indeterminate
861     }
862
863     // If appropriate, returns an error to report.
864     fn finalize_import(&mut self, directive: &'b ImportDirective<'b>) -> Option<(Span, String)> {
865         self.current_module = directive.parent;
866         let ImportDirective { ref module_path, span, .. } = *directive;
867
868         let module_result = self.resolve_path(
869             Some(if directive.is_uniform_paths_canary {
870                 ModuleOrUniformRoot::Module(directive.parent)
871             } else {
872                 ModuleOrUniformRoot::UniformRoot(keywords::Invalid.name())
873             }),
874             &module_path,
875             None,
876             true,
877             span,
878             directive.crate_lint(),
879         );
880         let module = match module_result {
881             PathResult::Module(module) => module,
882             PathResult::Failed(span, msg, false) => {
883                 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
884                 return None;
885             }
886             PathResult::Failed(span, msg, true) => {
887                 let (mut self_path, mut self_result) = (module_path.clone(), None);
888                 let is_special = |ident: Ident| ident.is_path_segment_keyword() &&
889                                                 ident.name != keywords::CrateRoot.name();
890                 if !self_path.is_empty() && !is_special(self_path[0]) &&
891                    !(self_path.len() > 1 && is_special(self_path[1])) {
892                     self_path[0].name = keywords::SelfValue.name();
893                     self_result = Some(self.resolve_path(None, &self_path, None, false,
894                                                          span, CrateLint::No));
895                 }
896                 return if let Some(PathResult::Module(..)) = self_result {
897                     Some((span, format!("Did you mean `{}`?", names_to_string(&self_path[..]))))
898                 } else {
899                     Some((span, msg))
900                 };
901             },
902             _ => return None,
903         };
904
905         let (ident, result, type_ns_only) = match directive.subclass {
906             SingleImport { source, ref result, type_ns_only, .. } => (source, result, type_ns_only),
907             GlobImport { is_prelude, ref max_vis } => {
908                 if module_path.len() <= 1 {
909                     // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
910                     // 2 segments, so the `resolve_path` above won't trigger it.
911                     let mut full_path = module_path.clone();
912                     full_path.push(keywords::Invalid.ident());
913                     self.lint_if_path_starts_with_module(
914                         directive.crate_lint(),
915                         &full_path,
916                         directive.span,
917                         None,
918                     );
919                 }
920
921                 if let ModuleOrUniformRoot::Module(module) = module {
922                     if module.def_id() == directive.parent.def_id() {
923                         // Importing a module into itself is not allowed.
924                         return Some((directive.span,
925                             "Cannot glob-import a module into itself.".to_string()));
926                     }
927                 }
928                 if !is_prelude &&
929                    max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
930                    !max_vis.get().is_at_least(directive.vis.get(), &*self) {
931                     let msg = "A non-empty glob must import something with the glob's visibility";
932                     self.session.span_err(directive.span, msg);
933                 }
934                 return None;
935             }
936             _ => unreachable!(),
937         };
938
939         let mut all_ns_err = true;
940         self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
941             if let Ok(binding) = result[ns].get() {
942                 all_ns_err = false;
943                 if this.record_use(ident, ns, binding, directive.span) {
944                     if let ModuleOrUniformRoot::Module(module) = module {
945                         this.resolution(module, ident, ns).borrow_mut().binding =
946                             Some(this.dummy_binding);
947                     }
948                 }
949             }
950         });
951
952         if all_ns_err {
953             let mut all_ns_failed = true;
954             self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
955                 match this.resolve_ident_in_module(module, ident, ns, true, span) {
956                     Ok(_) => all_ns_failed = false,
957                     _ => {}
958                 }
959             });
960
961             return if all_ns_failed {
962                 let resolutions = match module {
963                     ModuleOrUniformRoot::Module(module) =>
964                         Some(module.resolutions.borrow()),
965                     ModuleOrUniformRoot::UniformRoot(_) => None,
966                 };
967                 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
968                 let names = resolutions.filter_map(|(&(ref i, _), resolution)| {
969                     if *i == ident { return None; } // Never suggest the same name
970                     match *resolution.borrow() {
971                         NameResolution { binding: Some(name_binding), .. } => {
972                             match name_binding.kind {
973                                 NameBindingKind::Import { binding, .. } => {
974                                     match binding.kind {
975                                         // Never suggest the name that has binding error
976                                         // i.e. the name that cannot be previously resolved
977                                         NameBindingKind::Def(Def::Err, _) => return None,
978                                         _ => Some(&i.name),
979                                     }
980                                 },
981                                 _ => Some(&i.name),
982                             }
983                         },
984                         NameResolution { ref single_imports, .. }
985                             if single_imports.is_empty() => None,
986                         _ => Some(&i.name),
987                     }
988                 });
989                 let lev_suggestion =
990                     match find_best_match_for_name(names, &ident.as_str(), None) {
991                         Some(name) => format!(". Did you mean to use `{}`?", name),
992                         None => "".to_owned(),
993                     };
994                 let msg = match module {
995                     ModuleOrUniformRoot::Module(module) => {
996                         let module_str = module_to_string(module);
997                         if let Some(module_str) = module_str {
998                             format!("no `{}` in `{}`{}", ident, module_str, lev_suggestion)
999                         } else {
1000                             format!("no `{}` in the root{}", ident, lev_suggestion)
1001                         }
1002                     }
1003                     ModuleOrUniformRoot::UniformRoot(_) => {
1004                         if !ident.is_path_segment_keyword() {
1005                             format!("no `{}` external crate{}", ident, lev_suggestion)
1006                         } else {
1007                             // HACK(eddyb) this shows up for `self` & `super`, which
1008                             // should work instead - for now keep the same error message.
1009                             format!("no `{}` in the root{}", ident, lev_suggestion)
1010                         }
1011                     }
1012                 };
1013                 Some((span, msg))
1014             } else {
1015                 // `resolve_ident_in_module` reported a privacy error.
1016                 self.import_dummy_binding(directive);
1017                 None
1018             }
1019         }
1020
1021         let mut reexport_error = None;
1022         let mut any_successful_reexport = false;
1023         self.per_ns(|this, ns| {
1024             if let Ok(binding) = result[ns].get() {
1025                 let vis = directive.vis.get();
1026                 if !binding.pseudo_vis().is_at_least(vis, &*this) {
1027                     reexport_error = Some((ns, binding));
1028                 } else {
1029                     any_successful_reexport = true;
1030                 }
1031             }
1032         });
1033
1034         // All namespaces must be re-exported with extra visibility for an error to occur.
1035         if !any_successful_reexport {
1036             let (ns, binding) = reexport_error.unwrap();
1037             if ns == TypeNS && binding.is_extern_crate() {
1038                 let msg = format!("extern crate `{}` is private, and cannot be \
1039                                    re-exported (error E0365), consider declaring with \
1040                                    `pub`",
1041                                    ident);
1042                 self.session.buffer_lint(PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1043                                          directive.id,
1044                                          directive.span,
1045                                          &msg);
1046             } else if ns == TypeNS {
1047                 struct_span_err!(self.session, directive.span, E0365,
1048                                  "`{}` is private, and cannot be re-exported", ident)
1049                     .span_label(directive.span, format!("re-export of private `{}`", ident))
1050                     .note(&format!("consider declaring type or module `{}` with `pub`", ident))
1051                     .emit();
1052             } else {
1053                 let msg = format!("`{}` is private, and cannot be re-exported", ident);
1054                 let note_msg =
1055                     format!("consider marking `{}` as `pub` in the imported module", ident);
1056                 struct_span_err!(self.session, directive.span, E0364, "{}", &msg)
1057                     .span_note(directive.span, &note_msg)
1058                     .emit();
1059             }
1060         }
1061
1062         if module_path.len() <= 1 {
1063             // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1064             // 2 segments, so the `resolve_path` above won't trigger it.
1065             let mut full_path = module_path.clone();
1066             full_path.push(ident);
1067             self.per_ns(|this, ns| {
1068                 if let Ok(binding) = result[ns].get() {
1069                     this.lint_if_path_starts_with_module(
1070                         directive.crate_lint(),
1071                         &full_path,
1072                         directive.span,
1073                         Some(binding),
1074                     );
1075                 }
1076             });
1077         }
1078
1079         // Record what this import resolves to for later uses in documentation,
1080         // this may resolve to either a value or a type, but for documentation
1081         // purposes it's good enough to just favor one over the other.
1082         self.per_ns(|this, ns| if let Some(binding) = result[ns].get().ok() {
1083             let import = this.import_map.entry(directive.id).or_default();
1084             import[ns] = Some(PathResolution::new(binding.def()));
1085         });
1086
1087         debug!("(resolving single import) successfully resolved import");
1088         None
1089     }
1090
1091     fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) {
1092         let module = match directive.imported_module.get().unwrap() {
1093             ModuleOrUniformRoot::Module(module) => module,
1094             ModuleOrUniformRoot::UniformRoot(_) => {
1095                 self.session.span_err(directive.span,
1096                     "cannot glob-import all possible crates");
1097                 return;
1098             }
1099         };
1100
1101         self.populate_module_if_necessary(module);
1102
1103         if let Some(Def::Trait(_)) = module.def() {
1104             self.session.span_err(directive.span, "items in traits are not importable.");
1105             return;
1106         } else if module.def_id() == directive.parent.def_id()  {
1107             return;
1108         } else if let GlobImport { is_prelude: true, .. } = directive.subclass {
1109             self.prelude = Some(module);
1110             return;
1111         }
1112
1113         // Add to module's glob_importers
1114         module.glob_importers.borrow_mut().push(directive);
1115
1116         // Ensure that `resolutions` isn't borrowed during `try_define`,
1117         // since it might get updated via a glob cycle.
1118         let bindings = module.resolutions.borrow().iter().filter_map(|(&ident, resolution)| {
1119             resolution.borrow().binding().map(|binding| (ident, binding))
1120         }).collect::<Vec<_>>();
1121         for ((mut ident, ns), binding) in bindings {
1122             let scope = match ident.span.reverse_glob_adjust(module.expansion,
1123                                                              directive.span.ctxt().modern()) {
1124                 Some(Some(def)) => self.macro_def_scope(def),
1125                 Some(None) => self.current_module,
1126                 None => continue,
1127             };
1128             if self.is_accessible_from(binding.pseudo_vis(), scope) {
1129                 let imported_binding = self.import(binding, directive);
1130                 let _ = self.try_define(directive.parent, ident, ns, imported_binding);
1131             }
1132         }
1133
1134         // Record the destination of this import
1135         self.record_def(directive.id, PathResolution::new(module.def().unwrap()));
1136     }
1137
1138     // Miscellaneous post-processing, including recording re-exports,
1139     // reporting conflicts, and reporting unresolved imports.
1140     fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1141         // Since import resolution is finished, globs will not define any more names.
1142         *module.globs.borrow_mut() = Vec::new();
1143
1144         let mut reexports = Vec::new();
1145         let mut exported_macro_names = FxHashMap();
1146         if ptr::eq(module, self.graph_root) {
1147             let macro_exports = mem::replace(&mut self.macro_exports, Vec::new());
1148             for export in macro_exports.into_iter().rev() {
1149                 if let Some(later_span) = exported_macro_names.insert(export.ident.modern(),
1150                                                                       export.span) {
1151                     self.session.buffer_lint_with_diagnostic(
1152                         DUPLICATE_MACRO_EXPORTS,
1153                         CRATE_NODE_ID,
1154                         later_span,
1155                         &format!("a macro named `{}` has already been exported", export.ident),
1156                         BuiltinLintDiagnostics::DuplicatedMacroExports(
1157                             export.ident, export.span, later_span));
1158                 } else {
1159                     reexports.push(export);
1160                 }
1161             }
1162         }
1163
1164         for (&(ident, ns), resolution) in module.resolutions.borrow().iter() {
1165             let resolution = &mut *resolution.borrow_mut();
1166             let binding = match resolution.binding {
1167                 Some(binding) => binding,
1168                 None => continue,
1169             };
1170
1171             if binding.is_import() || binding.is_macro_def() {
1172                 let def = binding.def();
1173                 if def != Def::Err {
1174                     if !def.def_id().is_local() {
1175                         self.cstore.export_macros_untracked(def.def_id().krate);
1176                     }
1177                     if let Def::Macro(..) = def {
1178                         if let Some(&span) = exported_macro_names.get(&ident.modern()) {
1179                             let msg =
1180                                 format!("a macro named `{}` has already been exported", ident);
1181                             self.session.struct_span_err(span, &msg)
1182                                 .span_label(span, format!("`{}` already exported", ident))
1183                                 .span_note(binding.span, "previous macro export here")
1184                                 .emit();
1185                         }
1186                     }
1187                     reexports.push(Export {
1188                         ident: ident.modern(),
1189                         def: def,
1190                         span: binding.span,
1191                         vis: binding.vis,
1192                     });
1193                 }
1194             }
1195
1196             match binding.kind {
1197                 NameBindingKind::Import { binding: orig_binding, directive, .. } => {
1198                     if ns == TypeNS && orig_binding.is_variant() &&
1199                         !orig_binding.vis.is_at_least(binding.vis, &*self) {
1200                             let msg = match directive.subclass {
1201                                 ImportDirectiveSubclass::SingleImport { .. } => {
1202                                     format!("variant `{}` is private and cannot be re-exported",
1203                                             ident)
1204                                 },
1205                                 ImportDirectiveSubclass::GlobImport { .. } => {
1206                                     let msg = "enum is private and its variants \
1207                                                cannot be re-exported".to_owned();
1208                                     let error_id = (DiagnosticMessageId::ErrorId(0), // no code?!
1209                                                     Some(binding.span),
1210                                                     msg.clone());
1211                                     let fresh = self.session.one_time_diagnostics
1212                                         .borrow_mut().insert(error_id);
1213                                     if !fresh {
1214                                         continue;
1215                                     }
1216                                     msg
1217                                 },
1218                                 ref s @ _ => bug!("unexpected import subclass {:?}", s)
1219                             };
1220                             let mut err = self.session.struct_span_err(binding.span, &msg);
1221
1222                             let imported_module = match directive.imported_module.get() {
1223                                 Some(ModuleOrUniformRoot::Module(module)) => module,
1224                                 _ => bug!("module should exist"),
1225                             };
1226                             let resolutions = imported_module.parent.expect("parent should exist")
1227                                 .resolutions.borrow();
1228                             let enum_path_segment_index = directive.module_path.len() - 1;
1229                             let enum_ident = directive.module_path[enum_path_segment_index];
1230
1231                             let enum_resolution = resolutions.get(&(enum_ident, TypeNS))
1232                                 .expect("resolution should exist");
1233                             let enum_span = enum_resolution.borrow()
1234                                 .binding.expect("binding should exist")
1235                                 .span;
1236                             let enum_def_span = self.session.codemap().def_span(enum_span);
1237                             let enum_def_snippet = self.session.codemap()
1238                                 .span_to_snippet(enum_def_span).expect("snippet should exist");
1239                             // potentially need to strip extant `crate`/`pub(path)` for suggestion
1240                             let after_vis_index = enum_def_snippet.find("enum")
1241                                 .expect("`enum` keyword should exist in snippet");
1242                             let suggestion = format!("pub {}",
1243                                                      &enum_def_snippet[after_vis_index..]);
1244
1245                             self.session
1246                                 .diag_span_suggestion_once(&mut err,
1247                                                            DiagnosticMessageId::ErrorId(0),
1248                                                            enum_def_span,
1249                                                            "consider making the enum public",
1250                                                            suggestion);
1251                             err.emit();
1252                     }
1253                 }
1254                 _ => {}
1255             }
1256         }
1257
1258         if reexports.len() > 0 {
1259             if let Some(def_id) = module.def_id() {
1260                 self.export_map.insert(def_id, reexports);
1261             }
1262         }
1263     }
1264 }
1265
1266 fn import_path_to_string(names: &[Ident],
1267                          subclass: &ImportDirectiveSubclass,
1268                          span: Span) -> String {
1269     let pos = names.iter()
1270         .position(|p| span == p.span && p.name != keywords::CrateRoot.name());
1271     let global = !names.is_empty() && names[0].name == keywords::CrateRoot.name();
1272     if let Some(pos) = pos {
1273         let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1274         names_to_string(names)
1275     } else {
1276         let names = if global { &names[1..] } else { names };
1277         if names.is_empty() {
1278             import_directive_subclass_to_string(subclass)
1279         } else {
1280             format!("{}::{}",
1281                     names_to_string(names),
1282                     import_directive_subclass_to_string(subclass))
1283         }
1284     }
1285 }
1286
1287 fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass) -> String {
1288     match *subclass {
1289         SingleImport { source, .. } => source.to_string(),
1290         GlobImport { .. } => "*".to_string(),
1291         ExternCrate(_) => "<extern crate>".to_string(),
1292         MacroUse => "#[macro_use]".to_string(),
1293     }
1294 }