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