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