]> git.lizzy.rs Git - rust.git/blob - src/librustc_resolve/resolve_imports.rs
tests: prefer edition: directives to compile-flags:--edition.
[rust.git] / src / librustc_resolve / resolve_imports.rs
1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use self::ImportDirectiveSubclass::*;
12
13 use {AmbiguityError, CrateLint, Module, ModuleOrUniformRoot, PerNS};
14 use Namespace::{self, TypeNS, MacroNS, ValueNS};
15 use {NameBinding, NameBindingKind, ToNameBinding, PathResult, PrivacyError};
16 use Resolver;
17 use {names_to_string, module_to_string};
18 use {resolve_error, ResolutionError};
19
20 use rustc_data_structures::ptr_key::PtrKey;
21 use rustc::ty;
22 use rustc::lint::builtin::BuiltinLintDiagnostics;
23 use rustc::lint::builtin::{DUPLICATE_MACRO_EXPORTS, PUB_USE_OF_PRIVATE_EXTERN_CRATE};
24 use rustc::hir::def_id::{CRATE_DEF_INDEX, DefId};
25 use rustc::hir::def::*;
26 use rustc::session::DiagnosticMessageId;
27 use rustc::util::nodemap::{FxHashMap, FxHashSet};
28
29 use syntax::ast::{Ident, Name, NodeId, CRATE_NODE_ID};
30 use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
31 use syntax::ext::hygiene::Mark;
32 use syntax::symbol::keywords;
33 use syntax::util::lev_distance::find_best_match_for_name;
34 use syntax_pos::Span;
35
36 use std::cell::{Cell, RefCell};
37 use std::{mem, ptr};
38
39 /// Contains data for specific types of import directives.
40 #[derive(Clone, Debug)]
41 pub enum ImportDirectiveSubclass<'a> {
42     SingleImport {
43         target: Ident,
44         source: Ident,
45         result: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
46         type_ns_only: bool,
47     },
48     GlobImport {
49         is_prelude: bool,
50         max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
51         // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
52     },
53     ExternCrate(Option<Name>),
54     MacroUse,
55 }
56
57 /// One import directive.
58 #[derive(Debug,Clone)]
59 pub struct ImportDirective<'a> {
60     /// The id of the `extern crate`, `UseTree` etc that imported this `ImportDirective`.
61     ///
62     /// In the case where the `ImportDirective` was expanded from a "nested" use tree,
63     /// this id is the id of the leaf tree. For example:
64     ///
65     /// ```ignore (pacify the mercilous tidy)
66     /// use foo::bar::{a, b}
67     /// ```
68     ///
69     /// If this is the import directive for `foo::bar::a`, we would have the id of the `UseTree`
70     /// for `a` in this field.
71     pub id: NodeId,
72
73     /// The `id` of the "root" use-kind -- this is always the same as
74     /// `id` except in the case of "nested" use trees, in which case
75     /// it will be the `id` of the root use tree. e.g., in the example
76     /// from `id`, this would be the id of the `use foo::bar`
77     /// `UseTree` node.
78     pub root_id: NodeId,
79
80     /// Span of this use tree.
81     pub span: Span,
82
83     /// Span of the *root* use tree (see `root_id`).
84     pub root_span: Span,
85
86     pub parent: Module<'a>,
87     pub module_path: Vec<Ident>,
88     /// The resolution of `module_path`.
89     pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>,
90     pub subclass: ImportDirectiveSubclass<'a>,
91     pub vis: Cell<ty::Visibility>,
92     pub expansion: Mark,
93     pub used: Cell<bool>,
94
95     /// Whether this import is a "canary" for the `uniform_paths` feature,
96     /// i.e. `use x::...;` results in an `use self::x as _;` canary.
97     /// This flag affects diagnostics: an error is reported if and only if
98     /// the import resolves successfully and an external crate with the same
99     /// name (`x` above) also exists; any resolution failures are ignored.
100     pub is_uniform_paths_canary: bool,
101 }
102
103 impl<'a> ImportDirective<'a> {
104     pub fn is_glob(&self) -> bool {
105         match self.subclass { ImportDirectiveSubclass::GlobImport { .. } => true, _ => false }
106     }
107
108     crate fn crate_lint(&self) -> CrateLint {
109         CrateLint::UsePath { root_id: self.root_id, root_span: self.root_span }
110     }
111 }
112
113 #[derive(Clone, Default, Debug)]
114 /// Records information about the resolution of a name in a namespace of a module.
115 pub struct NameResolution<'a> {
116     /// Single imports that may define the name in the namespace.
117     /// Import directives are arena-allocated, so it's ok to use pointers as keys.
118     single_imports: FxHashSet<PtrKey<'a, ImportDirective<'a>>>,
119     /// The least shadowable known binding for this name, or None if there are no known bindings.
120     pub binding: Option<&'a NameBinding<'a>>,
121     shadowed_glob: Option<&'a NameBinding<'a>>,
122 }
123
124 impl<'a> NameResolution<'a> {
125     // Returns the binding for the name if it is known or None if it not known.
126     fn binding(&self) -> Option<&'a NameBinding<'a>> {
127         self.binding.and_then(|binding| {
128             if !binding.is_glob_import() ||
129                self.single_imports.is_empty() { Some(binding) } else { None }
130         })
131     }
132 }
133
134 impl<'a, 'crateloader> Resolver<'a, 'crateloader> {
135     fn resolution(&self, module: Module<'a>, ident: Ident, ns: Namespace)
136                   -> &'a RefCell<NameResolution<'a>> {
137         *module.resolutions.borrow_mut().entry((ident.modern(), ns))
138                .or_insert_with(|| self.arenas.alloc_name_resolution())
139     }
140
141     /// Attempts to resolve `ident` in namespaces `ns` of `module`.
142     /// Invariant: if `record_used` is `Some`, expansion and import resolution must be complete.
143     pub fn resolve_ident_in_module_unadjusted(&mut self,
144                                               module: ModuleOrUniformRoot<'a>,
145                                               ident: Ident,
146                                               ns: Namespace,
147                                               restricted_shadowing: bool,
148                                               record_used: bool,
149                                               path_span: Span)
150                                               -> Result<&'a NameBinding<'a>, Determinacy> {
151         let module = match module {
152             ModuleOrUniformRoot::Module(module) => module,
153             ModuleOrUniformRoot::UniformRoot(root) => {
154                 // HACK(eddyb): `resolve_path` uses `keywords::Invalid` to indicate
155                 // paths of length 0, and currently these are relative `use` paths.
156                 let can_be_relative = !ident.is_path_segment_keyword() &&
157                     root == keywords::Invalid.name();
158                 if can_be_relative {
159                     // Relative paths should only get here if the feature-gate is on.
160                     assert!(self.session.rust_2018() &&
161                             self.session.features_untracked().uniform_paths);
162
163                     // Try first to resolve relatively.
164                     let mut ctxt = ident.span.ctxt().modern();
165                     let self_module = self.resolve_self(&mut ctxt, self.current_module);
166
167                     let binding = self.resolve_ident_in_module_unadjusted(
168                         ModuleOrUniformRoot::Module(self_module),
169                         ident,
170                         ns,
171                         restricted_shadowing,
172                         record_used,
173                         path_span,
174                     );
175
176                     // FIXME(eddyb) This may give false negatives, specifically
177                     // if a crate with the same name is found in `extern_prelude`,
178                     // preventing the check below this one from returning `binding`
179                     // in all cases.
180                     //
181                     // That is, if there's no crate with the same name, `binding`
182                     // is always returned, which is the result of doing the exact
183                     // same lookup of `ident`, in the `self` module.
184                     // But when a crate does exist, it will get chosen even when
185                     // macro expansion could result in a success from the lookup
186                     // in the `self` module, later on.
187                     //
188                     // NB. This is currently alleviated by the "ambiguity canaries"
189                     // (see `is_uniform_paths_canary`) that get introduced for the
190                     // maybe-relative imports handled here: if the false negative
191                     // case were to arise, it would *also* cause an ambiguity error.
192                     if binding.is_ok() {
193                         return binding;
194                     }
195
196                     // Fall back to resolving to an external crate.
197                     if !(ns == TypeNS && self.extern_prelude.contains(&ident.name)) {
198                         // ... unless the crate name is not in the `extern_prelude`.
199                         return binding;
200                     }
201                 }
202
203                 let crate_root = if
204                     ns == TypeNS &&
205                     root != keywords::Extern.name() &&
206                     (
207                         ident.name == keywords::Crate.name() ||
208                         ident.name == keywords::DollarCrate.name()
209                     )
210                 {
211                     self.resolve_crate_root(ident)
212                 } else if ns == TypeNS && !ident.is_path_segment_keyword() {
213                     let crate_id =
214                         self.crate_loader.process_path_extern(ident.name, ident.span);
215                     self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX })
216                 } else {
217                     return Err(Determined);
218                 };
219                 self.populate_module_if_necessary(crate_root);
220                 let binding = (crate_root, ty::Visibility::Public,
221                                ident.span, Mark::root()).to_name_binding(self.arenas);
222                 return Ok(binding);
223             }
224         };
225
226         self.populate_module_if_necessary(module);
227
228         let resolution = self.resolution(module, ident, ns)
229             .try_borrow_mut()
230             .map_err(|_| Determined)?; // This happens when there is a cycle of imports
231
232         if let Some(binding) = resolution.binding {
233             if !restricted_shadowing && binding.expansion != Mark::root() {
234                 if let NameBindingKind::Def(_, true) = binding.kind {
235                     self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
236                 }
237             }
238         }
239
240         if record_used {
241             if let Some(binding) = resolution.binding {
242                 if let Some(shadowed_glob) = resolution.shadowed_glob {
243                     let name = ident.name;
244                     // Forbid expanded shadowing to avoid time travel.
245                     if restricted_shadowing &&
246                        binding.expansion != Mark::root() &&
247                        ns != MacroNS && // In MacroNS, `try_define` always forbids this shadowing
248                        binding.def() != shadowed_glob.def() {
249                         self.ambiguity_errors.push(AmbiguityError {
250                             span: path_span,
251                             name,
252                             lexical: false,
253                             b1: binding,
254                             b2: shadowed_glob,
255                         });
256                     }
257                 }
258                 if self.record_use(ident, ns, binding, path_span) {
259                     return Ok(self.dummy_binding);
260                 }
261                 if !self.is_accessible(binding.vis) {
262                     self.privacy_errors.push(PrivacyError(path_span, ident.name, binding));
263                 }
264             }
265
266             return resolution.binding.ok_or(Determined);
267         }
268
269         let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
270             // `extern crate` are always usable for backwards compatibility, see issue #37020.
271             let usable = this.is_accessible(binding.vis) || binding.is_extern_crate();
272             if usable { Ok(binding) } else { Err(Determined) }
273         };
274
275         // Items and single imports are not shadowable, if we have one, then it's determined.
276         if let Some(binding) = resolution.binding {
277             if !binding.is_glob_import() {
278                 return check_usable(self, binding);
279             }
280         }
281
282         // --- From now on we either have a glob resolution or no resolution. ---
283
284         // Check if one of single imports can still define the name,
285         // if it can then our result is not determined and can be invalidated.
286         for single_import in &resolution.single_imports {
287             if !self.is_accessible(single_import.vis.get()) {
288                 continue;
289             }
290             let module = unwrap_or!(single_import.imported_module.get(), return Err(Undetermined));
291             let ident = match single_import.subclass {
292                 SingleImport { source, .. } => source,
293                 _ => unreachable!(),
294             };
295             match self.resolve_ident_in_module(module, ident, ns, false, path_span) {
296                 Err(Determined) => continue,
297                 Ok(_) | Err(Undetermined) => return Err(Undetermined),
298             }
299         }
300
301         // So we have a resolution that's from a glob import. This resolution is determined
302         // if it cannot be shadowed by some new item/import expanded from a macro.
303         // This happens either if there are no unexpanded macros, or expanded names cannot
304         // shadow globs (that happens in macro namespace or with restricted shadowing).
305         //
306         // Additionally, any macro in any module can plant names in the root module if it creates
307         // `macro_export` macros, so the root module effectively has unresolved invocations if any
308         // module has unresolved invocations.
309         // However, it causes resolution/expansion to stuck too often (#53144), so, to make
310         // progress, we have to ignore those potential unresolved invocations from other modules
311         // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
312         // shadowing is enabled, see `macro_expanded_macro_export_errors`).
313         let unexpanded_macros = !module.unresolved_invocations.borrow().is_empty();
314         if let Some(binding) = resolution.binding {
315             if !unexpanded_macros || ns == MacroNS || restricted_shadowing {
316                 return check_usable(self, binding);
317             } else {
318                 return Err(Undetermined);
319             }
320         }
321
322         // --- From now on we have no resolution. ---
323
324         // Now we are in situation when new item/import can appear only from a glob or a macro
325         // expansion. With restricted shadowing names from globs and macro expansions cannot
326         // shadow names from outer scopes, so we can freely fallback from module search to search
327         // in outer scopes. To continue search in outer scopes we have to lie a bit and return
328         // `Determined` to `resolve_lexical_macro_path_segment` even if the correct answer
329         // for in-module resolution could be `Undetermined`.
330         if restricted_shadowing {
331             return Err(Determined);
332         }
333
334         // Check if one of unexpanded macros can still define the name,
335         // if it can then our "no resolution" result is not determined and can be invalidated.
336         if unexpanded_macros {
337             return Err(Undetermined);
338         }
339
340         // Check if one of glob imports can still define the name,
341         // if it can then our "no resolution" result is not determined and can be invalidated.
342         for glob_import in module.globs.borrow().iter() {
343             if !self.is_accessible(glob_import.vis.get()) {
344                 continue
345             }
346             let module = match glob_import.imported_module.get() {
347                 Some(ModuleOrUniformRoot::Module(module)) => module,
348                 Some(ModuleOrUniformRoot::UniformRoot(_)) => continue,
349                 None => return Err(Undetermined),
350             };
351             let (orig_current_module, mut ident) = (self.current_module, ident.modern());
352             match ident.span.glob_adjust(module.expansion, glob_import.span.ctxt().modern()) {
353                 Some(Some(def)) => self.current_module = self.macro_def_scope(def),
354                 Some(None) => {}
355                 None => continue,
356             };
357             let result = self.resolve_ident_in_module_unadjusted(
358                 ModuleOrUniformRoot::Module(module),
359                 ident,
360                 ns,
361                 false,
362                 false,
363                 path_span,
364             );
365             self.current_module = orig_current_module;
366             match result {
367                 Err(Determined) => continue,
368                 Ok(_) | Err(Undetermined) => return Err(Undetermined),
369             }
370         }
371
372         // No resolution and no one else can define the name - determinate error.
373         Err(Determined)
374     }
375
376     // Add an import directive to the current module.
377     pub fn add_import_directive(&mut self,
378                                 module_path: Vec<Ident>,
379                                 subclass: ImportDirectiveSubclass<'a>,
380                                 span: Span,
381                                 id: NodeId,
382                                 root_span: Span,
383                                 root_id: NodeId,
384                                 vis: ty::Visibility,
385                                 expansion: Mark,
386                                 is_uniform_paths_canary: bool) {
387         let current_module = self.current_module;
388         let directive = self.arenas.alloc_import_directive(ImportDirective {
389             parent: current_module,
390             module_path,
391             imported_module: Cell::new(None),
392             subclass,
393             span,
394             id,
395             root_span,
396             root_id,
397             vis: Cell::new(vis),
398             expansion,
399             used: Cell::new(false),
400             is_uniform_paths_canary,
401         });
402
403         debug!("add_import_directive({:?})", directive);
404
405         self.indeterminate_imports.push(directive);
406         match directive.subclass {
407             SingleImport { target, type_ns_only, .. } => {
408                 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
409                     let mut resolution = this.resolution(current_module, target, ns).borrow_mut();
410                     resolution.single_imports.insert(PtrKey(directive));
411                 });
412             }
413             // We don't add prelude imports to the globs since they only affect lexical scopes,
414             // which are not relevant to import resolution.
415             GlobImport { is_prelude: true, .. } => {}
416             GlobImport { .. } => self.current_module.globs.borrow_mut().push(directive),
417             _ => unreachable!(),
418         }
419     }
420
421     // Given a binding and an import directive that resolves to it,
422     // return the corresponding binding defined by the import directive.
423     pub fn import(&self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>)
424                   -> &'a NameBinding<'a> {
425         let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) ||
426                      // c.f. `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
427                      !directive.is_glob() && binding.is_extern_crate() {
428             directive.vis.get()
429         } else {
430             binding.pseudo_vis()
431         };
432
433         if let GlobImport { ref max_vis, .. } = directive.subclass {
434             if vis == directive.vis.get() || vis.is_at_least(max_vis.get(), self) {
435                 max_vis.set(vis)
436             }
437         }
438
439         self.arenas.alloc_name_binding(NameBinding {
440             kind: NameBindingKind::Import {
441                 binding,
442                 directive,
443                 used: Cell::new(false),
444             },
445             span: directive.span,
446             vis,
447             expansion: directive.expansion,
448         })
449     }
450
451     // Define the name or return the existing binding if there is a collision.
452     pub fn try_define(&mut self,
453                       module: Module<'a>,
454                       ident: Ident,
455                       ns: Namespace,
456                       binding: &'a NameBinding<'a>)
457                       -> Result<(), &'a NameBinding<'a>> {
458         self.update_resolution(module, ident, ns, |this, resolution| {
459             if let Some(old_binding) = resolution.binding {
460                 if binding.is_glob_import() {
461                     if !old_binding.is_glob_import() &&
462                        !(ns == MacroNS && old_binding.expansion != Mark::root()) {
463                         resolution.shadowed_glob = Some(binding);
464                     } else if binding.def() != old_binding.def() {
465                         resolution.binding = Some(this.ambiguity(old_binding, binding));
466                     } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
467                         // We are glob-importing the same item but with greater visibility.
468                         resolution.binding = Some(binding);
469                     }
470                 } else if old_binding.is_glob_import() {
471                     if ns == MacroNS && binding.expansion != Mark::root() &&
472                        binding.def() != old_binding.def() {
473                         resolution.binding = Some(this.ambiguity(binding, old_binding));
474                     } else {
475                         resolution.binding = Some(binding);
476                         resolution.shadowed_glob = Some(old_binding);
477                     }
478                 } else if let (&NameBindingKind::Def(_, true), &NameBindingKind::Def(_, true)) =
479                         (&old_binding.kind, &binding.kind) {
480
481                     this.session.buffer_lint_with_diagnostic(
482                         DUPLICATE_MACRO_EXPORTS,
483                         CRATE_NODE_ID,
484                         binding.span,
485                         &format!("a macro named `{}` has already been exported", ident),
486                         BuiltinLintDiagnostics::DuplicatedMacroExports(
487                             ident, old_binding.span, binding.span));
488
489                     resolution.binding = Some(binding);
490                 } else {
491                     return Err(old_binding);
492                 }
493             } else {
494                 resolution.binding = Some(binding);
495             }
496
497             Ok(())
498         })
499     }
500
501     pub fn ambiguity(&self, b1: &'a NameBinding<'a>, b2: &'a NameBinding<'a>)
502                      -> &'a NameBinding<'a> {
503         self.arenas.alloc_name_binding(NameBinding {
504             kind: NameBindingKind::Ambiguity { b1, b2 },
505             vis: if b1.vis.is_at_least(b2.vis, self) { b1.vis } else { b2.vis },
506             span: b1.span,
507             expansion: Mark::root(),
508         })
509     }
510
511     // Use `f` to mutate the resolution of the name in the module.
512     // If the resolution becomes a success, define it in the module's glob importers.
513     fn update_resolution<T, F>(&mut self, module: Module<'a>, ident: Ident, ns: Namespace, f: F)
514                                -> T
515         where F: FnOnce(&mut Resolver<'a, 'crateloader>, &mut NameResolution<'a>) -> T
516     {
517         // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
518         // during which the resolution might end up getting re-defined via a glob cycle.
519         let (binding, t) = {
520             let resolution = &mut *self.resolution(module, ident, ns).borrow_mut();
521             let old_binding = resolution.binding();
522
523             let t = f(self, resolution);
524
525             match resolution.binding() {
526                 _ if old_binding.is_some() => return t,
527                 None => return t,
528                 Some(binding) => match old_binding {
529                     Some(old_binding) if ptr::eq(old_binding, binding) => return t,
530                     _ => (binding, t),
531                 }
532             }
533         };
534
535         // Define `binding` in `module`s glob importers.
536         for directive in module.glob_importers.borrow_mut().iter() {
537             let mut ident = ident.modern();
538             let scope = match ident.span.reverse_glob_adjust(module.expansion,
539                                                              directive.span.ctxt().modern()) {
540                 Some(Some(def)) => self.macro_def_scope(def),
541                 Some(None) => directive.parent,
542                 None => continue,
543             };
544             if self.is_accessible_from(binding.vis, scope) {
545                 let imported_binding = self.import(binding, directive);
546                 let _ = self.try_define(directive.parent, ident, ns, imported_binding);
547             }
548         }
549
550         t
551     }
552
553     // Define a "dummy" resolution containing a Def::Err as a placeholder for a
554     // failed resolution
555     fn import_dummy_binding(&mut self, directive: &'a ImportDirective<'a>) {
556         if let SingleImport { target, .. } = directive.subclass {
557             let dummy_binding = self.dummy_binding;
558             let dummy_binding = self.import(dummy_binding, directive);
559             self.per_ns(|this, ns| {
560                 let _ = this.try_define(directive.parent, target, ns, dummy_binding);
561             });
562         }
563     }
564 }
565
566 pub struct ImportResolver<'a, 'b: 'a, 'c: 'a + 'b> {
567     pub resolver: &'a mut Resolver<'b, 'c>,
568 }
569
570 impl<'a, 'b: 'a, 'c: 'a + 'b> ::std::ops::Deref for ImportResolver<'a, 'b, 'c> {
571     type Target = Resolver<'b, 'c>;
572     fn deref(&self) -> &Resolver<'b, 'c> {
573         self.resolver
574     }
575 }
576
577 impl<'a, 'b: 'a, 'c: 'a + 'b> ::std::ops::DerefMut for ImportResolver<'a, 'b, 'c> {
578     fn deref_mut(&mut self) -> &mut Resolver<'b, 'c> {
579         self.resolver
580     }
581 }
582
583 impl<'a, 'b: 'a, 'c: 'a + 'b> ty::DefIdTree for &'a ImportResolver<'a, 'b, 'c> {
584     fn parent(self, id: DefId) -> Option<DefId> {
585         self.resolver.parent(id)
586     }
587 }
588
589 impl<'a, 'b:'a, 'c: 'b> ImportResolver<'a, 'b, 'c> {
590     // Import resolution
591     //
592     // This is a fixed-point algorithm. We resolve imports until our efforts
593     // are stymied by an unresolved import; then we bail out of the current
594     // module and continue. We terminate successfully once no more imports
595     // remain or unsuccessfully when no forward progress in resolving imports
596     // is made.
597
598     /// Resolves all imports for the crate. This method performs the fixed-
599     /// point iteration.
600     pub fn resolve_imports(&mut self) {
601         let mut prev_num_indeterminates = self.indeterminate_imports.len() + 1;
602         while self.indeterminate_imports.len() < prev_num_indeterminates {
603             prev_num_indeterminates = self.indeterminate_imports.len();
604             for import in mem::replace(&mut self.indeterminate_imports, Vec::new()) {
605                 match self.resolve_import(&import) {
606                     true => self.determined_imports.push(import),
607                     false => self.indeterminate_imports.push(import),
608                 }
609             }
610         }
611     }
612
613     pub fn finalize_imports(&mut self) {
614         for module in self.arenas.local_modules().iter() {
615             self.finalize_resolutions_in(module);
616         }
617
618         let mut errors = false;
619         let mut seen_spans = FxHashSet();
620         for i in 0 .. self.determined_imports.len() {
621             let import = self.determined_imports[i];
622             let error = self.finalize_import(import);
623
624             // For a `#![feature(uniform_paths)]` `use self::x as _` canary,
625             // failure is ignored, while success may cause an ambiguity error.
626             if import.is_uniform_paths_canary {
627                 let (name, result) = match import.subclass {
628                     SingleImport { source, ref result, .. } => {
629                         let type_ns = result[TypeNS].get().ok();
630                         let value_ns = result[ValueNS].get().ok();
631                         (source.name, type_ns.or(value_ns))
632                     }
633                     _ => bug!(),
634                 };
635
636                 if error.is_some() {
637                     continue;
638                 }
639
640                 let is_explicit_self =
641                     import.module_path.len() > 0 &&
642                     import.module_path[0].name == keywords::SelfValue.name();
643                 let extern_crate_exists = self.extern_prelude.contains(&name);
644
645                 // A successful `self::x` is ambiguous with an `x` external crate.
646                 if is_explicit_self && !extern_crate_exists {
647                     continue;
648                 }
649
650                 errors = true;
651
652                 let msg = format!("import from `{}` is ambiguous", name);
653                 let mut err = self.session.struct_span_err(import.span, &msg);
654                 if extern_crate_exists {
655                     err.span_label(import.span,
656                         format!("could refer to external crate `::{}`", name));
657                 }
658                 if let Some(result) = result {
659                     if is_explicit_self {
660                         err.span_label(result.span,
661                             format!("could also refer to `self::{}`", name));
662                     } else {
663                         err.span_label(result.span,
664                             format!("shadowed by block-scoped `{}`", name));
665                     }
666                 }
667                 err.help(&format!("write `::{0}` or `self::{0}` explicitly instead", name));
668                 err.note("relative `use` paths enabled by `#![feature(uniform_paths)]`");
669                 err.emit();
670             } else if let Some((span, err)) = error {
671                 errors = true;
672
673                 if let SingleImport { source, ref result, .. } = import.subclass {
674                     if source.name == "self" {
675                         // Silence `unresolved import` error if E0429 is already emitted
676                         match result.value_ns.get() {
677                             Err(Determined) => continue,
678                             _ => {},
679                         }
680                     }
681                 }
682
683                 // If the error is a single failed import then create a "fake" import
684                 // resolution for it so that later resolve stages won't complain.
685                 self.import_dummy_binding(import);
686                 if !seen_spans.contains(&span) {
687                     let path = import_path_to_string(&import.module_path[..],
688                                                      &import.subclass,
689                                                      span);
690                     let error = ResolutionError::UnresolvedImport(Some((span, &path, &err)));
691                     resolve_error(self.resolver, span, error);
692                     seen_spans.insert(span);
693                 }
694             }
695         }
696
697         // Report unresolved imports only if no hard error was already reported
698         // to avoid generating multiple errors on the same import.
699         if !errors {
700             for import in &self.indeterminate_imports {
701                 if import.is_uniform_paths_canary {
702                     continue;
703                 }
704
705                 let error = ResolutionError::UnresolvedImport(None);
706                 resolve_error(self.resolver, import.span, error);
707                 break;
708             }
709         }
710     }
711
712     /// Attempts to resolve the given import, returning true if its resolution is determined.
713     /// If successful, the resolved bindings are written into the module.
714     fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool {
715         debug!("(resolving import for module) resolving import `{}::...` in `{}`",
716                names_to_string(&directive.module_path[..]),
717                module_to_string(self.current_module).unwrap_or("???".to_string()));
718
719         self.current_module = directive.parent;
720
721         let module = if let Some(module) = directive.imported_module.get() {
722             module
723         } else {
724             let vis = directive.vis.get();
725             // For better failure detection, pretend that the import will not define any names
726             // while resolving its module path.
727             directive.vis.set(ty::Visibility::Invisible);
728             let result = self.resolve_path(
729                 Some(if directive.is_uniform_paths_canary {
730                     ModuleOrUniformRoot::Module(directive.parent)
731                 } else {
732                     ModuleOrUniformRoot::UniformRoot(keywords::Invalid.name())
733                 }),
734                 &directive.module_path[..],
735                 None,
736                 false,
737                 directive.span,
738                 directive.crate_lint(),
739             );
740             directive.vis.set(vis);
741
742             match result {
743                 PathResult::Module(module) => module,
744                 PathResult::Indeterminate => return false,
745                 _ => return true,
746             }
747         };
748
749         directive.imported_module.set(Some(module));
750         let (source, target, result, type_ns_only) = match directive.subclass {
751             SingleImport { source, target, ref result, type_ns_only } =>
752                 (source, target, result, type_ns_only),
753             GlobImport { .. } => {
754                 self.resolve_glob_import(directive);
755                 return true;
756             }
757             _ => unreachable!(),
758         };
759
760         let mut indeterminate = false;
761         self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
762             if let Err(Undetermined) = result[ns].get() {
763                 result[ns].set(this.resolve_ident_in_module(module,
764                                                             source,
765                                                             ns,
766                                                             false,
767                                                             directive.span));
768             } else {
769                 return
770             };
771
772             let parent = directive.parent;
773             match result[ns].get() {
774                 Err(Undetermined) => indeterminate = true,
775                 Err(Determined) => {
776                     this.update_resolution(parent, target, ns, |_, resolution| {
777                         resolution.single_imports.remove(&PtrKey(directive));
778                     });
779                 }
780                 Ok(binding) if !binding.is_importable() => {
781                     let msg = format!("`{}` is not directly importable", target);
782                     struct_span_err!(this.session, directive.span, E0253, "{}", &msg)
783                         .span_label(directive.span, "cannot be imported directly")
784                         .emit();
785                     // Do not import this illegal binding. Import a dummy binding and pretend
786                     // everything is fine
787                     this.import_dummy_binding(directive);
788                 }
789                 Ok(binding) => {
790                     let imported_binding = this.import(binding, directive);
791                     let conflict = this.try_define(parent, target, ns, imported_binding);
792                     if let Err(old_binding) = conflict {
793                         this.report_conflict(parent, target, ns, imported_binding, old_binding);
794                     }
795                 }
796             }
797         });
798
799         !indeterminate
800     }
801
802     // If appropriate, returns an error to report.
803     fn finalize_import(&mut self, directive: &'b ImportDirective<'b>) -> Option<(Span, String)> {
804         self.current_module = directive.parent;
805         let ImportDirective { ref module_path, span, .. } = *directive;
806
807         let module_result = self.resolve_path(
808             Some(if directive.is_uniform_paths_canary {
809                 ModuleOrUniformRoot::Module(directive.parent)
810             } else {
811                 ModuleOrUniformRoot::UniformRoot(keywords::Invalid.name())
812             }),
813             &module_path,
814             None,
815             true,
816             span,
817             directive.crate_lint(),
818         );
819         let module = match module_result {
820             PathResult::Module(module) => module,
821             PathResult::Failed(span, msg, false) => {
822                 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
823                 return None;
824             }
825             PathResult::Failed(span, msg, true) => {
826                 let (mut self_path, mut self_result) = (module_path.clone(), None);
827                 let is_special = |ident: Ident| ident.is_path_segment_keyword() &&
828                                                 ident.name != keywords::CrateRoot.name();
829                 if !self_path.is_empty() && !is_special(self_path[0]) &&
830                    !(self_path.len() > 1 && is_special(self_path[1])) {
831                     self_path[0].name = keywords::SelfValue.name();
832                     self_result = Some(self.resolve_path(None, &self_path, None, false,
833                                                          span, CrateLint::No));
834                 }
835                 return if let Some(PathResult::Module(..)) = self_result {
836                     Some((span, format!("Did you mean `{}`?", names_to_string(&self_path[..]))))
837                 } else {
838                     Some((span, msg))
839                 };
840             },
841             _ => return None,
842         };
843
844         let (ident, result, type_ns_only) = match directive.subclass {
845             SingleImport { source, ref result, type_ns_only, .. } => (source, result, type_ns_only),
846             GlobImport { is_prelude, ref max_vis } => {
847                 if module_path.len() <= 1 {
848                     // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
849                     // 2 segments, so the `resolve_path` above won't trigger it.
850                     let mut full_path = module_path.clone();
851                     full_path.push(keywords::Invalid.ident());
852                     self.lint_if_path_starts_with_module(
853                         directive.crate_lint(),
854                         &full_path,
855                         directive.span,
856                         None,
857                     );
858                 }
859
860                 if let ModuleOrUniformRoot::Module(module) = module {
861                     if module.def_id() == directive.parent.def_id() {
862                         // Importing a module into itself is not allowed.
863                         return Some((directive.span,
864                             "Cannot glob-import a module into itself.".to_string()));
865                     }
866                 }
867                 if !is_prelude &&
868                    max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
869                    !max_vis.get().is_at_least(directive.vis.get(), &*self) {
870                     let msg = "A non-empty glob must import something with the glob's visibility";
871                     self.session.span_err(directive.span, msg);
872                 }
873                 return None;
874             }
875             _ => unreachable!(),
876         };
877
878         let mut all_ns_err = true;
879         self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
880             if let Ok(binding) = result[ns].get() {
881                 all_ns_err = false;
882                 if this.record_use(ident, ns, binding, directive.span) {
883                     if let ModuleOrUniformRoot::Module(module) = module {
884                         this.resolution(module, ident, ns).borrow_mut().binding =
885                             Some(this.dummy_binding);
886                     }
887                 }
888             }
889         });
890
891         if all_ns_err {
892             let mut all_ns_failed = true;
893             self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
894                 match this.resolve_ident_in_module(module, ident, ns, true, span) {
895                     Ok(_) => all_ns_failed = false,
896                     _ => {}
897                 }
898             });
899
900             return if all_ns_failed {
901                 let resolutions = match module {
902                     ModuleOrUniformRoot::Module(module) =>
903                         Some(module.resolutions.borrow()),
904                     ModuleOrUniformRoot::UniformRoot(_) => None,
905                 };
906                 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
907                 let names = resolutions.filter_map(|(&(ref i, _), resolution)| {
908                     if *i == ident { return None; } // Never suggest the same name
909                     match *resolution.borrow() {
910                         NameResolution { binding: Some(name_binding), .. } => {
911                             match name_binding.kind {
912                                 NameBindingKind::Import { binding, .. } => {
913                                     match binding.kind {
914                                         // Never suggest the name that has binding error
915                                         // i.e. the name that cannot be previously resolved
916                                         NameBindingKind::Def(Def::Err, _) => return None,
917                                         _ => Some(&i.name),
918                                     }
919                                 },
920                                 _ => Some(&i.name),
921                             }
922                         },
923                         NameResolution { ref single_imports, .. }
924                             if single_imports.is_empty() => None,
925                         _ => Some(&i.name),
926                     }
927                 });
928                 let lev_suggestion =
929                     match find_best_match_for_name(names, &ident.as_str(), None) {
930                         Some(name) => format!(". Did you mean to use `{}`?", name),
931                         None => "".to_owned(),
932                     };
933                 let msg = match module {
934                     ModuleOrUniformRoot::Module(module) => {
935                         let module_str = module_to_string(module);
936                         if let Some(module_str) = module_str {
937                             format!("no `{}` in `{}`{}", ident, module_str, lev_suggestion)
938                         } else {
939                             format!("no `{}` in the root{}", ident, lev_suggestion)
940                         }
941                     }
942                     ModuleOrUniformRoot::UniformRoot(_) => {
943                         if !ident.is_path_segment_keyword() {
944                             format!("no `{}` external crate{}", ident, lev_suggestion)
945                         } else {
946                             // HACK(eddyb) this shows up for `self` & `super`, which
947                             // should work instead - for now keep the same error message.
948                             format!("no `{}` in the root{}", ident, lev_suggestion)
949                         }
950                     }
951                 };
952                 Some((span, msg))
953             } else {
954                 // `resolve_ident_in_module` reported a privacy error.
955                 self.import_dummy_binding(directive);
956                 None
957             }
958         }
959
960         let mut reexport_error = None;
961         let mut any_successful_reexport = false;
962         self.per_ns(|this, ns| {
963             if let Ok(binding) = result[ns].get() {
964                 let vis = directive.vis.get();
965                 if !binding.pseudo_vis().is_at_least(vis, &*this) {
966                     reexport_error = Some((ns, binding));
967                 } else {
968                     any_successful_reexport = true;
969                 }
970             }
971         });
972
973         // All namespaces must be re-exported with extra visibility for an error to occur.
974         if !any_successful_reexport {
975             let (ns, binding) = reexport_error.unwrap();
976             if ns == TypeNS && binding.is_extern_crate() {
977                 let msg = format!("extern crate `{}` is private, and cannot be \
978                                    re-exported (error E0365), consider declaring with \
979                                    `pub`",
980                                    ident);
981                 self.session.buffer_lint(PUB_USE_OF_PRIVATE_EXTERN_CRATE,
982                                          directive.id,
983                                          directive.span,
984                                          &msg);
985             } else if ns == TypeNS {
986                 struct_span_err!(self.session, directive.span, E0365,
987                                  "`{}` is private, and cannot be re-exported", ident)
988                     .span_label(directive.span, format!("re-export of private `{}`", ident))
989                     .note(&format!("consider declaring type or module `{}` with `pub`", ident))
990                     .emit();
991             } else {
992                 let msg = format!("`{}` is private, and cannot be re-exported", ident);
993                 let note_msg =
994                     format!("consider marking `{}` as `pub` in the imported module", ident);
995                 struct_span_err!(self.session, directive.span, E0364, "{}", &msg)
996                     .span_note(directive.span, &note_msg)
997                     .emit();
998             }
999         }
1000
1001         if module_path.len() <= 1 {
1002             // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1003             // 2 segments, so the `resolve_path` above won't trigger it.
1004             let mut full_path = module_path.clone();
1005             full_path.push(ident);
1006             self.per_ns(|this, ns| {
1007                 if let Ok(binding) = result[ns].get() {
1008                     this.lint_if_path_starts_with_module(
1009                         directive.crate_lint(),
1010                         &full_path,
1011                         directive.span,
1012                         Some(binding),
1013                     );
1014                 }
1015             });
1016         }
1017
1018         // Record what this import resolves to for later uses in documentation,
1019         // this may resolve to either a value or a type, but for documentation
1020         // purposes it's good enough to just favor one over the other.
1021         self.per_ns(|this, ns| if let Some(binding) = result[ns].get().ok() {
1022             let import = this.import_map.entry(directive.id).or_default();
1023             import[ns] = Some(PathResolution::new(binding.def()));
1024         });
1025
1026         debug!("(resolving single import) successfully resolved import");
1027         None
1028     }
1029
1030     fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) {
1031         let module = match directive.imported_module.get().unwrap() {
1032             ModuleOrUniformRoot::Module(module) => module,
1033             ModuleOrUniformRoot::UniformRoot(_) => {
1034                 self.session.span_err(directive.span,
1035                     "cannot glob-import all possible crates");
1036                 return;
1037             }
1038         };
1039
1040         self.populate_module_if_necessary(module);
1041
1042         if let Some(Def::Trait(_)) = module.def() {
1043             self.session.span_err(directive.span, "items in traits are not importable.");
1044             return;
1045         } else if module.def_id() == directive.parent.def_id()  {
1046             return;
1047         } else if let GlobImport { is_prelude: true, .. } = directive.subclass {
1048             self.prelude = Some(module);
1049             return;
1050         }
1051
1052         // Add to module's glob_importers
1053         module.glob_importers.borrow_mut().push(directive);
1054
1055         // Ensure that `resolutions` isn't borrowed during `try_define`,
1056         // since it might get updated via a glob cycle.
1057         let bindings = module.resolutions.borrow().iter().filter_map(|(&ident, resolution)| {
1058             resolution.borrow().binding().map(|binding| (ident, binding))
1059         }).collect::<Vec<_>>();
1060         for ((mut ident, ns), binding) in bindings {
1061             let scope = match ident.span.reverse_glob_adjust(module.expansion,
1062                                                              directive.span.ctxt().modern()) {
1063                 Some(Some(def)) => self.macro_def_scope(def),
1064                 Some(None) => self.current_module,
1065                 None => continue,
1066             };
1067             if self.is_accessible_from(binding.pseudo_vis(), scope) {
1068                 let imported_binding = self.import(binding, directive);
1069                 let _ = self.try_define(directive.parent, ident, ns, imported_binding);
1070             }
1071         }
1072
1073         // Record the destination of this import
1074         self.record_def(directive.id, PathResolution::new(module.def().unwrap()));
1075     }
1076
1077     // Miscellaneous post-processing, including recording re-exports,
1078     // reporting conflicts, and reporting unresolved imports.
1079     fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1080         // Since import resolution is finished, globs will not define any more names.
1081         *module.globs.borrow_mut() = Vec::new();
1082
1083         let mut reexports = Vec::new();
1084         let mut exported_macro_names = FxHashMap();
1085         if ptr::eq(module, self.graph_root) {
1086             let macro_exports = mem::replace(&mut self.macro_exports, Vec::new());
1087             for export in macro_exports.into_iter().rev() {
1088                 if let Some(later_span) = exported_macro_names.insert(export.ident.modern(),
1089                                                                       export.span) {
1090                     self.session.buffer_lint_with_diagnostic(
1091                         DUPLICATE_MACRO_EXPORTS,
1092                         CRATE_NODE_ID,
1093                         later_span,
1094                         &format!("a macro named `{}` has already been exported", export.ident),
1095                         BuiltinLintDiagnostics::DuplicatedMacroExports(
1096                             export.ident, export.span, later_span));
1097                 } else {
1098                     reexports.push(export);
1099                 }
1100             }
1101         }
1102
1103         for (&(ident, ns), resolution) in module.resolutions.borrow().iter() {
1104             let resolution = &mut *resolution.borrow_mut();
1105             let binding = match resolution.binding {
1106                 Some(binding) => binding,
1107                 None => continue,
1108             };
1109
1110             if binding.is_import() || binding.is_macro_def() {
1111                 let def = binding.def();
1112                 if def != Def::Err {
1113                     if !def.def_id().is_local() {
1114                         self.cstore.export_macros_untracked(def.def_id().krate);
1115                     }
1116                     if let Def::Macro(..) = def {
1117                         if let Some(&span) = exported_macro_names.get(&ident.modern()) {
1118                             let msg =
1119                                 format!("a macro named `{}` has already been exported", ident);
1120                             self.session.struct_span_err(span, &msg)
1121                                 .span_label(span, format!("`{}` already exported", ident))
1122                                 .span_note(binding.span, "previous macro export here")
1123                                 .emit();
1124                         }
1125                     }
1126                     reexports.push(Export {
1127                         ident: ident.modern(),
1128                         def: def,
1129                         span: binding.span,
1130                         vis: binding.vis,
1131                     });
1132                 }
1133             }
1134
1135             match binding.kind {
1136                 NameBindingKind::Import { binding: orig_binding, directive, .. } => {
1137                     if ns == TypeNS && orig_binding.is_variant() &&
1138                         !orig_binding.vis.is_at_least(binding.vis, &*self) {
1139                             let msg = match directive.subclass {
1140                                 ImportDirectiveSubclass::SingleImport { .. } => {
1141                                     format!("variant `{}` is private and cannot be re-exported",
1142                                             ident)
1143                                 },
1144                                 ImportDirectiveSubclass::GlobImport { .. } => {
1145                                     let msg = "enum is private and its variants \
1146                                                cannot be re-exported".to_owned();
1147                                     let error_id = (DiagnosticMessageId::ErrorId(0), // no code?!
1148                                                     Some(binding.span),
1149                                                     msg.clone());
1150                                     let fresh = self.session.one_time_diagnostics
1151                                         .borrow_mut().insert(error_id);
1152                                     if !fresh {
1153                                         continue;
1154                                     }
1155                                     msg
1156                                 },
1157                                 ref s @ _ => bug!("unexpected import subclass {:?}", s)
1158                             };
1159                             let mut err = self.session.struct_span_err(binding.span, &msg);
1160
1161                             let imported_module = match directive.imported_module.get() {
1162                                 Some(ModuleOrUniformRoot::Module(module)) => module,
1163                                 _ => bug!("module should exist"),
1164                             };
1165                             let resolutions = imported_module.parent.expect("parent should exist")
1166                                 .resolutions.borrow();
1167                             let enum_path_segment_index = directive.module_path.len() - 1;
1168                             let enum_ident = directive.module_path[enum_path_segment_index];
1169
1170                             let enum_resolution = resolutions.get(&(enum_ident, TypeNS))
1171                                 .expect("resolution should exist");
1172                             let enum_span = enum_resolution.borrow()
1173                                 .binding.expect("binding should exist")
1174                                 .span;
1175                             let enum_def_span = self.session.codemap().def_span(enum_span);
1176                             let enum_def_snippet = self.session.codemap()
1177                                 .span_to_snippet(enum_def_span).expect("snippet should exist");
1178                             // potentially need to strip extant `crate`/`pub(path)` for suggestion
1179                             let after_vis_index = enum_def_snippet.find("enum")
1180                                 .expect("`enum` keyword should exist in snippet");
1181                             let suggestion = format!("pub {}",
1182                                                      &enum_def_snippet[after_vis_index..]);
1183
1184                             self.session
1185                                 .diag_span_suggestion_once(&mut err,
1186                                                            DiagnosticMessageId::ErrorId(0),
1187                                                            enum_def_span,
1188                                                            "consider making the enum public",
1189                                                            suggestion);
1190                             err.emit();
1191                     }
1192                 }
1193                 _ => {}
1194             }
1195         }
1196
1197         if reexports.len() > 0 {
1198             if let Some(def_id) = module.def_id() {
1199                 self.export_map.insert(def_id, reexports);
1200             }
1201         }
1202     }
1203 }
1204
1205 fn import_path_to_string(names: &[Ident],
1206                          subclass: &ImportDirectiveSubclass,
1207                          span: Span) -> String {
1208     let pos = names.iter()
1209         .position(|p| span == p.span && p.name != keywords::CrateRoot.name());
1210     let global = !names.is_empty() && names[0].name == keywords::CrateRoot.name();
1211     if let Some(pos) = pos {
1212         let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1213         names_to_string(names)
1214     } else {
1215         let names = if global { &names[1..] } else { names };
1216         if names.is_empty() {
1217             import_directive_subclass_to_string(subclass)
1218         } else {
1219             format!("{}::{}",
1220                     names_to_string(names),
1221                     import_directive_subclass_to_string(subclass))
1222         }
1223     }
1224 }
1225
1226 fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass) -> String {
1227     match *subclass {
1228         SingleImport { source, .. } => source.to_string(),
1229         GlobImport { .. } => "*".to_string(),
1230         ExternCrate(_) => "<extern crate>".to_string(),
1231         MacroUse => "#[macro_use]".to_string(),
1232     }
1233 }