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