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