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