]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/resolve_imports.rs
Add test and fix dedup
[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     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: Option<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, note) = if errors.is_empty() {
760             (span.unwrap(), "unresolved import".to_string(), None)
761         } else {
762             let span = MultiSpan::from_spans(
763                 errors
764                     .iter()
765                     .map(|(_, err)| err.span)
766                     .collect(),
767             );
768
769             let note = errors
770                 .iter()
771                 .filter_map(|(_, err)| err.note.as_ref())
772                 .last();
773
774             let paths = errors
775                 .iter()
776                 .map(|(path, _)| format!("`{}`", path))
777                 .collect::<Vec<_>>();
778
779             let msg = format!(
780                 "unresolved import{} {}",
781                 if paths.len() > 1 { "s" } else { "" },
782                 paths.join(", "),
783             );
784
785             (span, msg, note)
786         };
787
788         let mut diag = struct_span_err!(self.resolver.session, span, E0432, "{}", &msg);
789
790         if let Some(note) = &note {
791             diag.note(note);
792         }
793
794         for (_, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
795             if let Some(label) = err.label {
796                 diag.span_label(err.span, label);
797             }
798
799             if let Some((span, msg, suggestion, applicability)) = err.suggestion {
800                 diag.span_suggestion(span, &msg, suggestion, applicability);
801             }
802         }
803
804         diag.emit();
805     }
806
807     /// Attempts to resolve the given import, returning true if its resolution is determined.
808     /// If successful, the resolved bindings are written into the module.
809     fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool {
810         debug!("(resolving import for module) resolving import `{}::...` in `{}`",
811                Segment::names_to_string(&directive.module_path),
812                module_to_string(self.current_module).unwrap_or_else(|| "???".to_string()));
813
814         self.current_module = directive.parent_scope.module;
815
816         let module = if let Some(module) = directive.imported_module.get() {
817             module
818         } else {
819             // For better failure detection, pretend that the import will
820             // not define any names while resolving its module path.
821             let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
822             let path_res = self.resolve_path(
823                 &directive.module_path,
824                 None,
825                 &directive.parent_scope,
826                 false,
827                 directive.span,
828                 directive.crate_lint(),
829             );
830             directive.vis.set(orig_vis);
831
832             match path_res {
833                 PathResult::Module(module) => module,
834                 PathResult::Indeterminate => return false,
835                 PathResult::NonModule(..) | PathResult::Failed { .. } => return true,
836             }
837         };
838
839         directive.imported_module.set(Some(module));
840         let (source, target, source_bindings, target_bindings, type_ns_only) =
841                 match directive.subclass {
842             SingleImport { source, target, ref source_bindings,
843                            ref target_bindings, type_ns_only, .. } =>
844                 (source, target, source_bindings, target_bindings, type_ns_only),
845             GlobImport { .. } => {
846                 self.resolve_glob_import(directive);
847                 return true;
848             }
849             _ => unreachable!(),
850         };
851
852         let mut indeterminate = false;
853         self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
854             if let Err(Undetermined) = source_bindings[ns].get() {
855                 // For better failure detection, pretend that the import will
856                 // not define any names while resolving its module path.
857                 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
858                 let binding = this.resolve_ident_in_module(
859                     module, source, ns, Some(&directive.parent_scope), false, directive.span
860                 );
861                 directive.vis.set(orig_vis);
862
863                 source_bindings[ns].set(binding);
864             } else {
865                 return
866             };
867
868             let parent = directive.parent_scope.module;
869             match source_bindings[ns].get() {
870                 Err(Undetermined) => indeterminate = true,
871                 Err(Determined) => {
872                     this.update_resolution(parent, target, ns, |_, resolution| {
873                         resolution.single_imports.remove(&PtrKey(directive));
874                     });
875                 }
876                 Ok(binding) if !binding.is_importable() => {
877                     let msg = format!("`{}` is not directly importable", target);
878                     struct_span_err!(this.session, directive.span, E0253, "{}", &msg)
879                         .span_label(directive.span, "cannot be imported directly")
880                         .emit();
881                     // Do not import this illegal binding. Import a dummy binding and pretend
882                     // everything is fine
883                     this.import_dummy_binding(directive);
884                 }
885                 Ok(binding) => {
886                     let imported_binding = this.import(binding, directive);
887                     target_bindings[ns].set(Some(imported_binding));
888                     this.define(parent, target, ns, imported_binding);
889                 }
890             }
891         });
892
893         !indeterminate
894     }
895
896     /// Performs final import resolution, consistency checks and error reporting.
897     ///
898     /// Optionally returns an unresolved import error. This error is buffered and used to
899     /// consolidate multiple unresolved import errors into a single diagnostic.
900     fn finalize_import(
901         &mut self,
902         directive: &'b ImportDirective<'b>
903     ) -> Option<UnresolvedImportError> {
904         self.current_module = directive.parent_scope.module;
905
906         let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
907         let prev_ambiguity_errors_len = self.ambiguity_errors.len();
908         let path_res = self.resolve_path(&directive.module_path, None, &directive.parent_scope,
909                                          true, directive.span, directive.crate_lint());
910         let no_ambiguity = self.ambiguity_errors.len() == prev_ambiguity_errors_len;
911         directive.vis.set(orig_vis);
912         let module = match path_res {
913             PathResult::Module(module) => {
914                 // Consistency checks, analogous to `finalize_current_module_macro_resolutions`.
915                 if let Some(initial_module) = directive.imported_module.get() {
916                     if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
917                         span_bug!(directive.span, "inconsistent resolution for an import");
918                     }
919                 } else {
920                     if self.privacy_errors.is_empty() {
921                         let msg = "cannot determine resolution for the import";
922                         let msg_note = "import resolution is stuck, try simplifying other imports";
923                         self.session.struct_span_err(directive.span, msg).note(msg_note).emit();
924                     }
925                 }
926
927                 module
928             }
929             PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
930                 if no_ambiguity {
931                     assert!(directive.imported_module.get().is_none());
932                     resolve_error(self, span, ResolutionError::FailedToResolve {
933                         label,
934                         suggestion,
935                     });
936                 }
937                 return None;
938             }
939             PathResult::Failed { is_error_from_last_segment: true, span, label, suggestion } => {
940                 if no_ambiguity {
941                     assert!(directive.imported_module.get().is_none());
942                     let err = match self.make_path_suggestion(
943                         span,
944                         directive.module_path.clone(),
945                         &directive.parent_scope,
946                     ) {
947                         Some((suggestion, note)) => {
948                             UnresolvedImportError {
949                                 span,
950                                 label: None,
951                                 note,
952                                 suggestion: Some((
953                                     span,
954                                     String::from("a similar path exists"),
955                                     Segment::names_to_string(&suggestion),
956                                     Applicability::MaybeIncorrect,
957                                 )),
958                             }
959                         }
960                         None => {
961                             UnresolvedImportError {
962                                 span,
963                                 label: Some(label),
964                                 note: None,
965                                 suggestion,
966                             }
967                         }
968                     };
969
970                     return Some(err);
971                 }
972                 return None;
973             }
974             PathResult::NonModule(path_res) if path_res.base_def() == Def::Err => {
975                 if no_ambiguity {
976                     assert!(directive.imported_module.get().is_none());
977                 }
978                 // The error was already reported earlier.
979                 return None;
980             }
981             PathResult::Indeterminate | PathResult::NonModule(..) => unreachable!(),
982         };
983
984         let (ident, target, source_bindings, target_bindings, type_ns_only) =
985                 match directive.subclass {
986             SingleImport { source, target, ref source_bindings,
987                            ref target_bindings, type_ns_only, .. } =>
988                 (source, target, source_bindings, target_bindings, type_ns_only),
989             GlobImport { is_prelude, ref max_vis } => {
990                 if directive.module_path.len() <= 1 {
991                     // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
992                     // 2 segments, so the `resolve_path` above won't trigger it.
993                     let mut full_path = directive.module_path.clone();
994                     full_path.push(Segment::from_ident(keywords::Invalid.ident()));
995                     self.lint_if_path_starts_with_module(
996                         directive.crate_lint(),
997                         &full_path,
998                         directive.span,
999                         None,
1000                     );
1001                 }
1002
1003                 if let ModuleOrUniformRoot::Module(module) = module {
1004                     if module.def_id() == directive.parent_scope.module.def_id() {
1005                         // Importing a module into itself is not allowed.
1006                         return Some(UnresolvedImportError {
1007                             span: directive.span,
1008                             label: Some(String::from("cannot glob-import a module into itself")),
1009                             note: None,
1010                             suggestion: None,
1011                         });
1012                     }
1013                 }
1014                 if !is_prelude &&
1015                    max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
1016                    !max_vis.get().is_at_least(directive.vis.get(), &*self) {
1017                     let msg = "A non-empty glob must import something with the glob's visibility";
1018                     self.session.span_err(directive.span, msg);
1019                 }
1020                 return None;
1021             }
1022             _ => unreachable!(),
1023         };
1024
1025         let mut all_ns_err = true;
1026         self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
1027             let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
1028             let orig_blacklisted_binding =
1029                 mem::replace(&mut this.blacklisted_binding, target_bindings[ns].get());
1030             let orig_last_import_segment = mem::replace(&mut this.last_import_segment, true);
1031             let binding = this.resolve_ident_in_module(
1032                 module, ident, ns, Some(&directive.parent_scope), true, directive.span
1033             );
1034             this.last_import_segment = orig_last_import_segment;
1035             this.blacklisted_binding = orig_blacklisted_binding;
1036             directive.vis.set(orig_vis);
1037
1038             match binding {
1039                 Ok(binding) => {
1040                     // Consistency checks, analogous to `finalize_current_module_macro_resolutions`.
1041                     let initial_def = source_bindings[ns].get().map(|initial_binding| {
1042                         all_ns_err = false;
1043                         if let Some(target_binding) = target_bindings[ns].get() {
1044                             if target.name == "_" &&
1045                                initial_binding.is_extern_crate() && !initial_binding.is_import() {
1046                                 this.record_use(ident, ns, target_binding,
1047                                                 directive.module_path.is_empty());
1048                             }
1049                         }
1050                         initial_binding.def()
1051                     });
1052                     let def = binding.def();
1053                     if let Ok(initial_def) = initial_def {
1054                         if def != initial_def && this.ambiguity_errors.is_empty() {
1055                             span_bug!(directive.span, "inconsistent resolution for an import");
1056                         }
1057                     } else {
1058                         if def != Def::Err &&
1059                            this.ambiguity_errors.is_empty() && this.privacy_errors.is_empty() {
1060                             let msg = "cannot determine resolution for the import";
1061                             let msg_note =
1062                                 "import resolution is stuck, try simplifying other imports";
1063                             this.session.struct_span_err(directive.span, msg).note(msg_note).emit();
1064                         }
1065                     }
1066                 }
1067                 Err(..) => {
1068                     // FIXME: This assert may fire if public glob is later shadowed by a private
1069                     // single import (see test `issue-55884-2.rs`). In theory single imports should
1070                     // always block globs, even if they are not yet resolved, so that this kind of
1071                     // self-inconsistent resolution never happens.
1072                     // Reenable the assert when the issue is fixed.
1073                     // assert!(result[ns].get().is_err());
1074                 }
1075             }
1076         });
1077
1078         if all_ns_err {
1079             let mut all_ns_failed = true;
1080             self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
1081                 let binding = this.resolve_ident_in_module(
1082                     module, ident, ns, Some(&directive.parent_scope), true, directive.span
1083                 );
1084                 if binding.is_ok() {
1085                     all_ns_failed = false;
1086                 }
1087             });
1088
1089             return if all_ns_failed {
1090                 let resolutions = match module {
1091                     ModuleOrUniformRoot::Module(module) => Some(module.resolutions.borrow()),
1092                     _ => None,
1093                 };
1094                 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
1095                 let names = resolutions.filter_map(|(&(ref i, _), resolution)| {
1096                     if *i == ident { return None; } // Never suggest the same name
1097                     match *resolution.borrow() {
1098                         NameResolution { binding: Some(name_binding), .. } => {
1099                             match name_binding.kind {
1100                                 NameBindingKind::Import { binding, .. } => {
1101                                     match binding.kind {
1102                                         // Never suggest the name that has binding error
1103                                         // i.e., the name that cannot be previously resolved
1104                                         NameBindingKind::Def(Def::Err, _) => return None,
1105                                         _ => Some(&i.name),
1106                                     }
1107                                 },
1108                                 _ => Some(&i.name),
1109                             }
1110                         },
1111                         NameResolution { ref single_imports, .. }
1112                             if single_imports.is_empty() => None,
1113                         _ => Some(&i.name),
1114                     }
1115                 });
1116
1117                 let lev_suggestion =
1118                     find_best_match_for_name(names, &ident.as_str(), None).map(|suggestion| {
1119                         (
1120                             ident.span,
1121                             String::from("a similar name exists in the module"),
1122                             suggestion.to_string(),
1123                             Applicability::MaybeIncorrect,
1124                         )
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                 Some(UnresolvedImportError {
1147                     span: directive.span,
1148                     label: Some(label),
1149                     note: None,
1150                     suggestion: lev_suggestion,
1151                 })
1152             } else {
1153                 // `resolve_ident_in_module` reported a privacy error.
1154                 self.import_dummy_binding(directive);
1155                 None
1156             }
1157         }
1158
1159         let mut reexport_error = None;
1160         let mut any_successful_reexport = false;
1161         self.per_ns(|this, ns| {
1162             if let Ok(binding) = source_bindings[ns].get() {
1163                 let vis = directive.vis.get();
1164                 if !binding.pseudo_vis().is_at_least(vis, &*this) {
1165                     reexport_error = Some((ns, binding));
1166                 } else {
1167                     any_successful_reexport = true;
1168                 }
1169             }
1170         });
1171
1172         // All namespaces must be re-exported with extra visibility for an error to occur.
1173         if !any_successful_reexport {
1174             let (ns, binding) = reexport_error.unwrap();
1175             if ns == TypeNS && binding.is_extern_crate() {
1176                 let msg = format!("extern crate `{}` is private, and cannot be \
1177                                    re-exported (error E0365), consider declaring with \
1178                                    `pub`",
1179                                    ident);
1180                 self.session.buffer_lint(PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1181                                          directive.id,
1182                                          directive.span,
1183                                          &msg);
1184             } else if ns == TypeNS {
1185                 struct_span_err!(self.session, directive.span, E0365,
1186                                  "`{}` is private, and cannot be re-exported", ident)
1187                     .span_label(directive.span, format!("re-export of private `{}`", ident))
1188                     .note(&format!("consider declaring type or module `{}` with `pub`", ident))
1189                     .emit();
1190             } else {
1191                 let msg = format!("`{}` is private, and cannot be re-exported", ident);
1192                 let note_msg =
1193                     format!("consider marking `{}` as `pub` in the imported module", ident);
1194                 struct_span_err!(self.session, directive.span, E0364, "{}", &msg)
1195                     .span_note(directive.span, &note_msg)
1196                     .emit();
1197             }
1198         }
1199
1200         if directive.module_path.len() <= 1 {
1201             // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1202             // 2 segments, so the `resolve_path` above won't trigger it.
1203             let mut full_path = directive.module_path.clone();
1204             full_path.push(Segment::from_ident(ident));
1205             self.per_ns(|this, ns| {
1206                 if let Ok(binding) = source_bindings[ns].get() {
1207                     this.lint_if_path_starts_with_module(
1208                         directive.crate_lint(),
1209                         &full_path,
1210                         directive.span,
1211                         Some(binding),
1212                     );
1213                 }
1214             });
1215         }
1216
1217         // Record what this import resolves to for later uses in documentation,
1218         // this may resolve to either a value or a type, but for documentation
1219         // purposes it's good enough to just favor one over the other.
1220         self.per_ns(|this, ns| if let Some(binding) = source_bindings[ns].get().ok() {
1221             let mut def = binding.def();
1222             if let Def::Macro(def_id, _) = def {
1223                 // `DefId`s from the "built-in macro crate" should not leak from resolve because
1224                 // later stages are not ready to deal with them and produce lots of ICEs. Replace
1225                 // them with `Def::Err` until some saner scheme is implemented for built-in macros.
1226                 if def_id.krate == CrateNum::BuiltinMacros {
1227                     this.session.span_err(directive.span, "cannot import a built-in macro");
1228                     def = Def::Err;
1229                 }
1230             }
1231             let import = this.import_map.entry(directive.id).or_default();
1232             import[ns] = Some(PathResolution::new(def));
1233         });
1234
1235         self.check_for_redundant_imports(
1236             ident,
1237             directive,
1238             source_bindings,
1239             target_bindings,
1240             target,
1241         );
1242
1243         debug!("(resolving single import) successfully resolved import");
1244         None
1245     }
1246
1247     fn check_for_redundant_imports(
1248         &mut self,
1249         ident: Ident,
1250         directive: &'b ImportDirective<'b>,
1251         source_bindings: &PerNS<Cell<Result<&'b NameBinding<'b>, Determinacy>>>,
1252         target_bindings: &PerNS<Cell<Option<&'b NameBinding<'b>>>>,
1253         target: Ident,
1254     ) {
1255         // Skip if the import was produced by a macro.
1256         if directive.parent_scope.expansion != Mark::root() {
1257             return;
1258         }
1259
1260         // Skip if we are inside a named module (in contrast to an anonymous
1261         // module defined by a block).
1262         if let ModuleKind::Def(_, _) = directive.parent_scope.module.kind {
1263             return;
1264         }
1265
1266         let mut is_redundant = PerNS {
1267             value_ns: None,
1268             type_ns: None,
1269             macro_ns: None,
1270         };
1271
1272         let mut redundant_span = PerNS {
1273             value_ns: None,
1274             type_ns: None,
1275             macro_ns: None,
1276         };
1277
1278         self.per_ns(|this, ns| if let Some(binding) = source_bindings[ns].get().ok() {
1279             if binding.def() == Def::Err {
1280                 return;
1281             }
1282
1283             let orig_blacklisted_binding = mem::replace(
1284                 &mut this.blacklisted_binding,
1285                 target_bindings[ns].get()
1286             );
1287
1288             match this.early_resolve_ident_in_lexical_scope(
1289                 target,
1290                 ScopeSet::Import(ns),
1291                 &directive.parent_scope,
1292                 false,
1293                 false,
1294                 directive.span,
1295             ) {
1296                 Ok(other_binding) => {
1297                     is_redundant[ns] = Some(
1298                         binding.def() == other_binding.def()
1299                         && !other_binding.is_ambiguity()
1300                     );
1301                     redundant_span[ns] =
1302                         Some((other_binding.span, other_binding.is_import()));
1303                 }
1304                 Err(_) => is_redundant[ns] = Some(false)
1305             }
1306
1307             this.blacklisted_binding = orig_blacklisted_binding;
1308         });
1309
1310         if !is_redundant.is_empty() &&
1311             is_redundant.present_items().all(|is_redundant| is_redundant)
1312         {
1313             let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1314             redundant_spans.sort();
1315             redundant_spans.dedup();
1316             self.session.buffer_lint_with_diagnostic(
1317                 UNUSED_IMPORTS,
1318                 directive.id,
1319                 directive.span,
1320                 &format!("the item `{}` is imported redundantly", ident),
1321                 BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident),
1322             );
1323         }
1324     }
1325
1326     fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) {
1327         let module = match directive.imported_module.get().unwrap() {
1328             ModuleOrUniformRoot::Module(module) => module,
1329             _ => {
1330                 self.session.span_err(directive.span, "cannot glob-import all possible crates");
1331                 return;
1332             }
1333         };
1334
1335         self.populate_module_if_necessary(module);
1336
1337         if module.is_trait() {
1338             self.session.span_err(directive.span, "items in traits are not importable.");
1339             return;
1340         } else if module.def_id() == directive.parent_scope.module.def_id()  {
1341             return;
1342         } else if let GlobImport { is_prelude: true, .. } = directive.subclass {
1343             self.prelude = Some(module);
1344             return;
1345         }
1346
1347         // Add to module's glob_importers
1348         module.glob_importers.borrow_mut().push(directive);
1349
1350         // Ensure that `resolutions` isn't borrowed during `try_define`,
1351         // since it might get updated via a glob cycle.
1352         let bindings = module.resolutions.borrow().iter().filter_map(|(&ident, resolution)| {
1353             resolution.borrow().binding().map(|binding| (ident, binding))
1354         }).collect::<Vec<_>>();
1355         for ((mut ident, ns), binding) in bindings {
1356             let scope = match ident.span.reverse_glob_adjust(module.expansion,
1357                                                              directive.span.ctxt().modern()) {
1358                 Some(Some(def)) => self.macro_def_scope(def),
1359                 Some(None) => self.current_module,
1360                 None => continue,
1361             };
1362             if self.is_accessible_from(binding.pseudo_vis(), scope) {
1363                 let imported_binding = self.import(binding, directive);
1364                 let _ = self.try_define(directive.parent_scope.module, ident, ns, imported_binding);
1365             }
1366         }
1367
1368         // Record the destination of this import
1369         self.record_def(directive.id, PathResolution::new(module.def().unwrap()));
1370     }
1371
1372     // Miscellaneous post-processing, including recording re-exports,
1373     // reporting conflicts, and reporting unresolved imports.
1374     fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1375         // Since import resolution is finished, globs will not define any more names.
1376         *module.globs.borrow_mut() = Vec::new();
1377
1378         let mut reexports = Vec::new();
1379
1380         for (&(ident, ns), resolution) in module.resolutions.borrow().iter() {
1381             let resolution = &mut *resolution.borrow_mut();
1382             let binding = match resolution.binding {
1383                 Some(binding) => binding,
1384                 None => continue,
1385             };
1386
1387             // Filter away ambiguous and gensymed imports. Gensymed imports
1388             // (e.g. implicitly injected `std`) cannot be properly encoded in metadata,
1389             // so they can cause name conflict errors downstream.
1390             let is_good_import = binding.is_import() && !binding.is_ambiguity() &&
1391                                  !(ident.name.is_gensymed() && ident.name != "_");
1392             if is_good_import || binding.is_macro_def() {
1393                 let def = binding.def();
1394                 if def != Def::Err {
1395                     if let Some(def_id) = def.opt_def_id() {
1396                         if !def_id.is_local() && def_id.krate != CrateNum::BuiltinMacros {
1397                             self.cstore.export_macros_untracked(def_id.krate);
1398                         }
1399                     }
1400                     reexports.push(Export {
1401                         ident: ident.modern(),
1402                         def: def,
1403                         span: binding.span,
1404                         vis: binding.vis,
1405                     });
1406                 }
1407             }
1408
1409             if let NameBindingKind::Import { binding: orig_binding, directive, .. } = binding.kind {
1410                 if ns == TypeNS && orig_binding.is_variant() &&
1411                     !orig_binding.vis.is_at_least(binding.vis, &*self) {
1412                         let msg = match directive.subclass {
1413                             ImportDirectiveSubclass::SingleImport { .. } => {
1414                                 format!("variant `{}` is private and cannot be re-exported",
1415                                         ident)
1416                             },
1417                             ImportDirectiveSubclass::GlobImport { .. } => {
1418                                 let msg = "enum is private and its variants \
1419                                            cannot be re-exported".to_owned();
1420                                 let error_id = (DiagnosticMessageId::ErrorId(0), // no code?!
1421                                                 Some(binding.span),
1422                                                 msg.clone());
1423                                 let fresh = self.session.one_time_diagnostics
1424                                     .borrow_mut().insert(error_id);
1425                                 if !fresh {
1426                                     continue;
1427                                 }
1428                                 msg
1429                             },
1430                             ref s @ _ => bug!("unexpected import subclass {:?}", s)
1431                         };
1432                         let mut err = self.session.struct_span_err(binding.span, &msg);
1433
1434                         let imported_module = match directive.imported_module.get() {
1435                             Some(ModuleOrUniformRoot::Module(module)) => module,
1436                             _ => bug!("module should exist"),
1437                         };
1438                         let resolutions = imported_module.parent.expect("parent should exist")
1439                             .resolutions.borrow();
1440                         let enum_path_segment_index = directive.module_path.len() - 1;
1441                         let enum_ident = directive.module_path[enum_path_segment_index].ident;
1442
1443                         let enum_resolution = resolutions.get(&(enum_ident, TypeNS))
1444                             .expect("resolution should exist");
1445                         let enum_span = enum_resolution.borrow()
1446                             .binding.expect("binding should exist")
1447                             .span;
1448                         let enum_def_span = self.session.source_map().def_span(enum_span);
1449                         let enum_def_snippet = self.session.source_map()
1450                             .span_to_snippet(enum_def_span).expect("snippet should exist");
1451                         // potentially need to strip extant `crate`/`pub(path)` for suggestion
1452                         let after_vis_index = enum_def_snippet.find("enum")
1453                             .expect("`enum` keyword should exist in snippet");
1454                         let suggestion = format!("pub {}",
1455                                                  &enum_def_snippet[after_vis_index..]);
1456
1457                         self.session
1458                             .diag_span_suggestion_once(&mut err,
1459                                                        DiagnosticMessageId::ErrorId(0),
1460                                                        enum_def_span,
1461                                                        "consider making the enum public",
1462                                                        suggestion);
1463                         err.emit();
1464                 }
1465             }
1466         }
1467
1468         if reexports.len() > 0 {
1469             if let Some(def_id) = module.def_id() {
1470                 self.export_map.insert(def_id, reexports);
1471             }
1472         }
1473     }
1474 }
1475
1476 fn import_path_to_string(names: &[Ident],
1477                          subclass: &ImportDirectiveSubclass<'_>,
1478                          span: Span) -> String {
1479     let pos = names.iter()
1480         .position(|p| span == p.span && p.name != keywords::PathRoot.name());
1481     let global = !names.is_empty() && names[0].name == keywords::PathRoot.name();
1482     if let Some(pos) = pos {
1483         let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1484         names_to_string(names)
1485     } else {
1486         let names = if global { &names[1..] } else { names };
1487         if names.is_empty() {
1488             import_directive_subclass_to_string(subclass)
1489         } else {
1490             format!("{}::{}",
1491                     names_to_string(names),
1492                     import_directive_subclass_to_string(subclass))
1493         }
1494     }
1495 }
1496
1497 fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass<'_>) -> String {
1498     match *subclass {
1499         SingleImport { source, .. } => source.to_string(),
1500         GlobImport { .. } => "*".to_string(),
1501         ExternCrate { .. } => "<extern crate>".to_string(),
1502         MacroUse => "#[macro_use]".to_string(),
1503     }
1504 }