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