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