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.
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.
11 use self::ImportDirectiveSubclass::*;
13 use {AmbiguityError, CrateLint, Module, ModuleOrUniformRoot, PerNS};
14 use Namespace::{self, TypeNS, MacroNS};
15 use {NameBinding, NameBindingKind, ToNameBinding, PathResult, PrivacyError};
17 use {names_to_string, module_to_string};
18 use {resolve_error, ResolutionError};
20 use rustc_data_structures::ptr_key::PtrKey;
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::FxHashSet;
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::{MultiSpan, Span};
36 use std::cell::{Cell, RefCell};
37 use std::collections::BTreeMap;
41 /// Contains data for specific types of import directives.
42 #[derive(Clone, Debug)]
43 pub enum ImportDirectiveSubclass<'a> {
47 result: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
52 max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
53 // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
55 ExternCrate(Option<Name>),
59 /// One import directive.
60 #[derive(Debug,Clone)]
61 pub struct ImportDirective<'a> {
62 /// The id of the `extern crate`, `UseTree` etc that imported this `ImportDirective`.
64 /// In the case where the `ImportDirective` was expanded from a "nested" use tree,
65 /// this id is the id of the leaf tree. For example:
67 /// ```ignore (pacify the mercilous tidy)
68 /// use foo::bar::{a, b}
71 /// If this is the import directive for `foo::bar::a`, we would have the id of the `UseTree`
72 /// for `a` in this field.
75 /// The `id` of the "root" use-kind -- this is always the same as
76 /// `id` except in the case of "nested" use trees, in which case
77 /// it will be the `id` of the root use tree. e.g., in the example
78 /// from `id`, this would be the id of the `use foo::bar`
82 /// Span of this use tree.
85 /// Span of the *root* use tree (see `root_id`).
88 pub parent: Module<'a>,
89 pub module_path: Vec<Ident>,
90 /// The resolution of `module_path`.
91 pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>,
92 pub subclass: ImportDirectiveSubclass<'a>,
93 pub vis: Cell<ty::Visibility>,
97 /// Whether this import is a "canary" for the `uniform_paths` feature,
98 /// i.e. `use x::...;` results in an `use self::x as _;` canary.
99 /// This flag affects diagnostics: an error is reported if and only if
100 /// the import resolves successfully and an external crate with the same
101 /// name (`x` above) also exists; any resolution failures are ignored.
102 pub is_uniform_paths_canary: bool,
105 impl<'a> ImportDirective<'a> {
106 pub fn is_glob(&self) -> bool {
107 match self.subclass { ImportDirectiveSubclass::GlobImport { .. } => true, _ => false }
110 crate fn crate_lint(&self) -> CrateLint {
111 CrateLint::UsePath { root_id: self.root_id, root_span: self.root_span }
115 #[derive(Clone, Default, Debug)]
116 /// Records information about the resolution of a name in a namespace of a module.
117 pub struct NameResolution<'a> {
118 /// Single imports that may define the name in the namespace.
119 /// Import directives are arena-allocated, so it's ok to use pointers as keys.
120 single_imports: FxHashSet<PtrKey<'a, ImportDirective<'a>>>,
121 /// The least shadowable known binding for this name, or None if there are no known bindings.
122 pub binding: Option<&'a NameBinding<'a>>,
123 shadowed_glob: Option<&'a NameBinding<'a>>,
126 impl<'a> NameResolution<'a> {
127 // Returns the binding for the name if it is known or None if it not known.
128 fn binding(&self) -> Option<&'a NameBinding<'a>> {
129 self.binding.and_then(|binding| {
130 if !binding.is_glob_import() ||
131 self.single_imports.is_empty() { Some(binding) } else { None }
136 impl<'a, 'crateloader> Resolver<'a, 'crateloader> {
137 fn resolution(&self, module: Module<'a>, ident: Ident, ns: Namespace)
138 -> &'a RefCell<NameResolution<'a>> {
139 *module.resolutions.borrow_mut().entry((ident.modern(), ns))
140 .or_insert_with(|| self.arenas.alloc_name_resolution())
143 /// Attempts to resolve `ident` in namespaces `ns` of `module`.
144 /// Invariant: if `record_used` is `Some`, expansion and import resolution must be complete.
145 pub fn resolve_ident_in_module_unadjusted(&mut self,
146 module: ModuleOrUniformRoot<'a>,
149 restricted_shadowing: bool,
152 -> Result<&'a NameBinding<'a>, Determinacy> {
153 let module = match module {
154 ModuleOrUniformRoot::Module(module) => module,
155 ModuleOrUniformRoot::UniformRoot(root) => {
156 // HACK(eddyb): `resolve_path` uses `keywords::Invalid` to indicate
157 // paths of length 0, and currently these are relative `use` paths.
158 let can_be_relative = !ident.is_path_segment_keyword() &&
159 root == keywords::Invalid.name();
161 // Relative paths should only get here if the feature-gate is on.
162 assert!(self.session.rust_2018() &&
163 self.session.features_untracked().uniform_paths);
165 // Try first to resolve relatively.
166 let mut ctxt = ident.span.ctxt().modern();
167 let self_module = self.resolve_self(&mut ctxt, self.current_module);
169 let binding = self.resolve_ident_in_module_unadjusted(
170 ModuleOrUniformRoot::Module(self_module),
173 restricted_shadowing,
178 // FIXME(eddyb) This may give false negatives, specifically
179 // if a crate with the same name is found in `extern_prelude`,
180 // preventing the check below this one from returning `binding`
183 // That is, if there's no crate with the same name, `binding`
184 // is always returned, which is the result of doing the exact
185 // same lookup of `ident`, in the `self` module.
186 // But when a crate does exist, it will get chosen even when
187 // macro expansion could result in a success from the lookup
188 // in the `self` module, later on.
190 // NB. This is currently alleviated by the "ambiguity canaries"
191 // (see `is_uniform_paths_canary`) that get introduced for the
192 // maybe-relative imports handled here: if the false negative
193 // case were to arise, it would *also* cause an ambiguity error.
198 // Fall back to resolving to an external crate.
201 !ident.is_path_segment_keyword() &&
202 self.extern_prelude.contains(&ident.name)
204 // ... unless the crate name is not in the `extern_prelude`.
211 root != keywords::Extern.name() &&
213 ident.name == keywords::Crate.name() ||
214 ident.name == keywords::DollarCrate.name()
217 self.resolve_crate_root(ident)
220 !ident.is_path_segment_keyword() &&
221 self.extern_prelude.contains(&ident.name)
224 self.crate_loader.process_path_extern(ident.name, ident.span);
225 self.get_module(DefId { krate: crate_id, index: CRATE_DEF_INDEX })
227 return Err(Determined);
229 self.populate_module_if_necessary(crate_root);
230 let binding = (crate_root, ty::Visibility::Public,
231 ident.span, Mark::root()).to_name_binding(self.arenas);
236 self.populate_module_if_necessary(module);
238 let resolution = self.resolution(module, ident, ns)
240 .map_err(|_| Determined)?; // This happens when there is a cycle of imports
242 if let Some(binding) = resolution.binding {
243 if !restricted_shadowing && binding.expansion != Mark::root() {
244 if let NameBindingKind::Def(_, true) = binding.kind {
245 self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
251 if let Some(binding) = resolution.binding {
252 if let Some(shadowed_glob) = resolution.shadowed_glob {
253 // Forbid expanded shadowing to avoid time travel.
254 if restricted_shadowing &&
255 binding.expansion != Mark::root() &&
256 ns != MacroNS && // In MacroNS, `try_define` always forbids this shadowing
257 binding.def() != shadowed_glob.def() {
258 self.ambiguity_errors.push(AmbiguityError {
265 if self.record_use(ident, ns, binding) {
266 return Ok(self.dummy_binding);
268 if !self.is_accessible(binding.vis) {
269 self.privacy_errors.push(PrivacyError(path_span, ident.name, binding));
273 return resolution.binding.ok_or(Determined);
276 let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
277 // `extern crate` are always usable for backwards compatibility, see issue #37020.
278 let usable = this.is_accessible(binding.vis) || binding.is_extern_crate();
279 if usable { Ok(binding) } else { Err(Determined) }
282 // Items and single imports are not shadowable, if we have one, then it's determined.
283 if let Some(binding) = resolution.binding {
284 if !binding.is_glob_import() {
285 return check_usable(self, binding);
289 // --- From now on we either have a glob resolution or no resolution. ---
291 // Check if one of single imports can still define the name,
292 // if it can then our result is not determined and can be invalidated.
293 for single_import in &resolution.single_imports {
294 if !self.is_accessible(single_import.vis.get()) {
297 let module = unwrap_or!(single_import.imported_module.get(), return Err(Undetermined));
298 let ident = match single_import.subclass {
299 SingleImport { source, .. } => source,
302 match self.resolve_ident_in_module(module, ident, ns, false, path_span) {
303 Err(Determined) => continue,
305 if !self.is_accessible_from(binding.vis, single_import.parent) => continue,
306 Ok(_) | Err(Undetermined) => return Err(Undetermined),
310 // So we have a resolution that's from a glob import. This resolution is determined
311 // if it cannot be shadowed by some new item/import expanded from a macro.
312 // This happens either if there are no unexpanded macros, or expanded names cannot
313 // shadow globs (that happens in macro namespace or with restricted shadowing).
315 // Additionally, any macro in any module can plant names in the root module if it creates
316 // `macro_export` macros, so the root module effectively has unresolved invocations if any
317 // module has unresolved invocations.
318 // However, it causes resolution/expansion to stuck too often (#53144), so, to make
319 // progress, we have to ignore those potential unresolved invocations from other modules
320 // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
321 // shadowing is enabled, see `macro_expanded_macro_export_errors`).
322 let unexpanded_macros = !module.unresolved_invocations.borrow().is_empty();
323 if let Some(binding) = resolution.binding {
324 if !unexpanded_macros || ns == MacroNS || restricted_shadowing {
325 return check_usable(self, binding);
327 return Err(Undetermined);
331 // --- From now on we have no resolution. ---
333 // Now we are in situation when new item/import can appear only from a glob or a macro
334 // expansion. With restricted shadowing names from globs and macro expansions cannot
335 // shadow names from outer scopes, so we can freely fallback from module search to search
336 // in outer scopes. To continue search in outer scopes we have to lie a bit and return
337 // `Determined` to `resolve_lexical_macro_path_segment` even if the correct answer
338 // for in-module resolution could be `Undetermined`.
339 if restricted_shadowing {
340 return Err(Determined);
343 // Check if one of unexpanded macros can still define the name,
344 // if it can then our "no resolution" result is not determined and can be invalidated.
345 if unexpanded_macros {
346 return Err(Undetermined);
349 // Check if one of glob imports can still define the name,
350 // if it can then our "no resolution" result is not determined and can be invalidated.
351 for glob_import in module.globs.borrow().iter() {
352 if !self.is_accessible(glob_import.vis.get()) {
355 let module = match glob_import.imported_module.get() {
356 Some(ModuleOrUniformRoot::Module(module)) => module,
357 Some(ModuleOrUniformRoot::UniformRoot(_)) => continue,
358 None => return Err(Undetermined),
360 let (orig_current_module, mut ident) = (self.current_module, ident.modern());
361 match ident.span.glob_adjust(module.expansion, glob_import.span.ctxt().modern()) {
362 Some(Some(def)) => self.current_module = self.macro_def_scope(def),
366 let result = self.resolve_ident_in_module_unadjusted(
367 ModuleOrUniformRoot::Module(module),
374 self.current_module = orig_current_module;
377 Err(Determined) => continue,
379 if !self.is_accessible_from(binding.vis, glob_import.parent) => continue,
380 Ok(_) | Err(Undetermined) => return Err(Undetermined),
384 // No resolution and no one else can define the name - determinate error.
388 // Add an import directive to the current module.
389 pub fn add_import_directive(&mut self,
390 module_path: Vec<Ident>,
391 subclass: ImportDirectiveSubclass<'a>,
398 is_uniform_paths_canary: bool) {
399 let current_module = self.current_module;
400 let directive = self.arenas.alloc_import_directive(ImportDirective {
401 parent: current_module,
403 imported_module: Cell::new(None),
411 used: Cell::new(false),
412 is_uniform_paths_canary,
415 debug!("add_import_directive({:?})", directive);
417 self.indeterminate_imports.push(directive);
418 match directive.subclass {
419 SingleImport { target, type_ns_only, .. } => {
420 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
421 let mut resolution = this.resolution(current_module, target, ns).borrow_mut();
422 resolution.single_imports.insert(PtrKey(directive));
425 // We don't add prelude imports to the globs since they only affect lexical scopes,
426 // which are not relevant to import resolution.
427 GlobImport { is_prelude: true, .. } => {}
428 GlobImport { .. } => self.current_module.globs.borrow_mut().push(directive),
433 // Given a binding and an import directive that resolves to it,
434 // return the corresponding binding defined by the import directive.
435 pub fn import(&self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>)
436 -> &'a NameBinding<'a> {
437 let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) ||
438 // c.f. `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
439 !directive.is_glob() && binding.is_extern_crate() {
445 if let GlobImport { ref max_vis, .. } = directive.subclass {
446 if vis == directive.vis.get() || vis.is_at_least(max_vis.get(), self) {
451 self.arenas.alloc_name_binding(NameBinding {
452 kind: NameBindingKind::Import {
455 used: Cell::new(false),
457 span: directive.span,
459 expansion: directive.expansion,
463 crate fn check_reserved_macro_name(&self, ident: Ident, ns: Namespace) {
464 // Reserve some names that are not quite covered by the general check
465 // performed on `Resolver::builtin_attrs`.
467 (ident.name == "cfg" || ident.name == "cfg_attr" || ident.name == "derive") {
468 self.session.span_err(ident.span,
469 &format!("name `{}` is reserved in macro namespace", ident));
473 // Define the name or return the existing binding if there is a collision.
474 pub fn try_define(&mut self,
478 binding: &'a NameBinding<'a>)
479 -> Result<(), &'a NameBinding<'a>> {
480 self.check_reserved_macro_name(ident, ns);
481 self.update_resolution(module, ident, ns, |this, resolution| {
482 if let Some(old_binding) = resolution.binding {
483 if binding.is_glob_import() {
484 if !old_binding.is_glob_import() &&
485 !(ns == MacroNS && old_binding.expansion != Mark::root()) {
486 resolution.shadowed_glob = Some(binding);
487 } else if binding.def() != old_binding.def() {
488 resolution.binding = Some(this.ambiguity(old_binding, binding));
489 } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
490 // We are glob-importing the same item but with greater visibility.
491 resolution.binding = Some(binding);
493 } else if old_binding.is_glob_import() {
494 if ns == MacroNS && binding.expansion != Mark::root() &&
495 binding.def() != old_binding.def() {
496 resolution.binding = Some(this.ambiguity(binding, old_binding));
498 resolution.binding = Some(binding);
499 resolution.shadowed_glob = Some(old_binding);
501 } else if let (&NameBindingKind::Def(_, true), &NameBindingKind::Def(_, true)) =
502 (&old_binding.kind, &binding.kind) {
504 this.session.buffer_lint_with_diagnostic(
505 DUPLICATE_MACRO_EXPORTS,
508 &format!("a macro named `{}` has already been exported", ident),
509 BuiltinLintDiagnostics::DuplicatedMacroExports(
510 ident, old_binding.span, binding.span));
512 resolution.binding = Some(binding);
514 return Err(old_binding);
517 resolution.binding = Some(binding);
524 pub fn ambiguity(&self, b1: &'a NameBinding<'a>, b2: &'a NameBinding<'a>)
525 -> &'a NameBinding<'a> {
526 self.arenas.alloc_name_binding(NameBinding {
527 kind: NameBindingKind::Ambiguity { b1, b2 },
528 vis: if b1.vis.is_at_least(b2.vis, self) { b1.vis } else { b2.vis },
530 expansion: Mark::root(),
534 // Use `f` to mutate the resolution of the name in the module.
535 // If the resolution becomes a success, define it in the module's glob importers.
536 fn update_resolution<T, F>(&mut self, module: Module<'a>, ident: Ident, ns: Namespace, f: F)
538 where F: FnOnce(&mut Resolver<'a, 'crateloader>, &mut NameResolution<'a>) -> T
540 // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
541 // during which the resolution might end up getting re-defined via a glob cycle.
543 let resolution = &mut *self.resolution(module, ident, ns).borrow_mut();
544 let old_binding = resolution.binding();
546 let t = f(self, resolution);
548 match resolution.binding() {
549 _ if old_binding.is_some() => return t,
551 Some(binding) => match old_binding {
552 Some(old_binding) if ptr::eq(old_binding, binding) => return t,
558 // Define `binding` in `module`s glob importers.
559 for directive in module.glob_importers.borrow_mut().iter() {
560 let mut ident = ident.modern();
561 let scope = match ident.span.reverse_glob_adjust(module.expansion,
562 directive.span.ctxt().modern()) {
563 Some(Some(def)) => self.macro_def_scope(def),
564 Some(None) => directive.parent,
567 if self.is_accessible_from(binding.vis, scope) {
568 let imported_binding = self.import(binding, directive);
569 let _ = self.try_define(directive.parent, ident, ns, imported_binding);
576 // Define a "dummy" resolution containing a Def::Err as a placeholder for a
578 fn import_dummy_binding(&mut self, directive: &'a ImportDirective<'a>) {
579 if let SingleImport { target, .. } = directive.subclass {
580 let dummy_binding = self.dummy_binding;
581 let dummy_binding = self.import(dummy_binding, directive);
582 self.per_ns(|this, ns| {
583 let _ = this.try_define(directive.parent, target, ns, dummy_binding);
589 pub struct ImportResolver<'a, 'b: 'a, 'c: 'a + 'b> {
590 pub resolver: &'a mut Resolver<'b, 'c>,
593 impl<'a, 'b: 'a, 'c: 'a + 'b> ::std::ops::Deref for ImportResolver<'a, 'b, 'c> {
594 type Target = Resolver<'b, 'c>;
595 fn deref(&self) -> &Resolver<'b, 'c> {
600 impl<'a, 'b: 'a, 'c: 'a + 'b> ::std::ops::DerefMut for ImportResolver<'a, 'b, 'c> {
601 fn deref_mut(&mut self) -> &mut Resolver<'b, 'c> {
606 impl<'a, 'b: 'a, 'c: 'a + 'b> ty::DefIdTree for &'a ImportResolver<'a, 'b, 'c> {
607 fn parent(self, id: DefId) -> Option<DefId> {
608 self.resolver.parent(id)
612 impl<'a, 'b:'a, 'c: 'b> ImportResolver<'a, 'b, 'c> {
615 // This is a fixed-point algorithm. We resolve imports until our efforts
616 // are stymied by an unresolved import; then we bail out of the current
617 // module and continue. We terminate successfully once no more imports
618 // remain or unsuccessfully when no forward progress in resolving imports
621 /// Resolves all imports for the crate. This method performs the fixed-
623 pub fn resolve_imports(&mut self) {
624 let mut prev_num_indeterminates = self.indeterminate_imports.len() + 1;
625 while self.indeterminate_imports.len() < prev_num_indeterminates {
626 prev_num_indeterminates = self.indeterminate_imports.len();
627 for import in mem::replace(&mut self.indeterminate_imports, Vec::new()) {
628 match self.resolve_import(&import) {
629 true => self.determined_imports.push(import),
630 false => self.indeterminate_imports.push(import),
636 pub fn finalize_imports(&mut self) {
637 for module in self.arenas.local_modules().iter() {
638 self.finalize_resolutions_in(module);
641 struct UniformPathsCanaryResults<'a> {
643 module_scope: Option<&'a NameBinding<'a>>,
644 block_scopes: Vec<&'a NameBinding<'a>>,
647 // Collect all tripped `uniform_paths` canaries separately.
648 let mut uniform_paths_canaries: BTreeMap<
649 (Span, NodeId, Namespace),
650 UniformPathsCanaryResults,
653 let mut errors = false;
654 let mut seen_spans = FxHashSet();
655 let mut error_vec = Vec::new();
656 let mut prev_root_id: NodeId = NodeId::new(0);
657 for i in 0 .. self.determined_imports.len() {
658 let import = self.determined_imports[i];
659 let error = self.finalize_import(import);
661 // For a `#![feature(uniform_paths)]` `use self::x as _` canary,
662 // failure is ignored, while success may cause an ambiguity error.
663 if import.is_uniform_paths_canary {
668 let (name, result) = match import.subclass {
669 SingleImport { source, ref result, .. } => (source.name, result),
673 let has_explicit_self =
674 import.module_path.len() > 0 &&
675 import.module_path[0].name == keywords::SelfValue.name();
677 self.per_ns(|_, ns| {
678 if let Some(result) = result[ns].get().ok() {
680 uniform_paths_canaries.entry((import.span, import.id, ns))
681 .or_insert(UniformPathsCanaryResults {
684 block_scopes: vec![],
687 // All the canaries with the same `id` should have the same `name`.
688 assert_eq!(canary_results.name, name);
690 if has_explicit_self {
691 // There should only be one `self::x` (module-scoped) canary.
692 assert!(canary_results.module_scope.is_none());
693 canary_results.module_scope = Some(result);
695 canary_results.block_scopes.push(result);
699 } else if let Some((span, err)) = error {
702 if let SingleImport { source, ref result, .. } = import.subclass {
703 if source.name == "self" {
704 // Silence `unresolved import` error if E0429 is already emitted
705 match result.value_ns.get() {
706 Err(Determined) => continue,
712 // If the error is a single failed import then create a "fake" import
713 // resolution for it so that later resolve stages won't complain.
714 self.import_dummy_binding(import);
715 if prev_root_id.as_u32() != 0 &&
716 prev_root_id.as_u32() != import.root_id.as_u32() &&
717 !error_vec.is_empty(){
718 // in case of new import line, throw diagnostic message
719 // for previous line.
720 let mut empty_vec = vec![];
721 mem::swap(&mut empty_vec, &mut error_vec);
722 self.throw_unresolved_import_error(empty_vec, None);
724 if !seen_spans.contains(&span) {
725 let path = import_path_to_string(&import.module_path[..],
728 error_vec.push((span, path, err));
729 seen_spans.insert(span);
730 prev_root_id = import.root_id;
735 let uniform_paths_feature = self.session.features_untracked().uniform_paths;
736 for ((span, _, ns), results) in uniform_paths_canaries {
737 let name = results.name;
738 let external_crate = if ns == TypeNS && self.extern_prelude.contains(&name) {
740 self.crate_loader.process_path_extern(name, span);
741 Some(Def::Mod(DefId { krate: crate_id, index: CRATE_DEF_INDEX }))
746 // Currently imports can't resolve in non-module scopes,
747 // we only have canaries in them for future-proofing.
748 if external_crate.is_none() && results.module_scope.is_none() {
753 let mut all_results = external_crate.into_iter().chain(
754 results.module_scope.iter()
755 .chain(&results.block_scopes)
756 .map(|binding| binding.def())
758 let first = all_results.next().unwrap();
760 // An ambiguity requires more than one *distinct* possible resolution.
761 let possible_resultions =
762 1 + all_results.filter(|&def| def != first).count();
763 if possible_resultions <= 1 {
770 let msg = format!("`{}` import is ambiguous", name);
771 let mut err = self.session.struct_span_err(span, &msg);
772 let mut suggestion_choices = String::new();
773 if external_crate.is_some() {
774 write!(suggestion_choices, "`::{}`", name);
776 format!("can refer to external crate `::{}`", name));
778 if let Some(result) = results.module_scope {
779 if !suggestion_choices.is_empty() {
780 suggestion_choices.push_str(" or ");
782 write!(suggestion_choices, "`self::{}`", name);
783 if uniform_paths_feature {
784 err.span_label(result.span,
785 format!("can refer to `self::{}`", name));
787 err.span_label(result.span,
788 format!("may refer to `self::{}` in the future", name));
791 for result in results.block_scopes {
792 err.span_label(result.span,
793 format!("shadowed by block-scoped `{}`", name));
795 err.help(&format!("write {} explicitly instead", suggestion_choices));
796 if uniform_paths_feature {
797 err.note("relative `use` paths enabled by `#![feature(uniform_paths)]`");
799 err.note("in the future, `#![feature(uniform_paths)]` may become the default");
804 if !error_vec.is_empty() {
805 self.throw_unresolved_import_error(error_vec.clone(), None);
808 // Report unresolved imports only if no hard error was already reported
809 // to avoid generating multiple errors on the same import.
811 for import in &self.indeterminate_imports {
812 if import.is_uniform_paths_canary {
815 self.throw_unresolved_import_error(error_vec, Some(MultiSpan::from(import.span)));
821 fn throw_unresolved_import_error(&self, error_vec: Vec<(Span, String, String)>,
822 span: Option<MultiSpan>) {
823 let max_span_label_msg_count = 10; // upper limit on number of span_label message.
824 let (span,msg) = match error_vec.is_empty() {
825 true => (span.unwrap(), "unresolved import".to_string()),
827 let span = MultiSpan::from_spans(error_vec.clone().into_iter()
828 .map(|elem: (Span, String, String)| { elem.0 }
830 let path_vec: Vec<String> = error_vec.clone().into_iter()
831 .map(|elem: (Span, String, String)| { format!("`{}`", elem.1) }
833 let path = path_vec.join(", ");
834 let msg = format!("unresolved import{} {}",
835 if path_vec.len() > 1 { "s" } else { "" }, path);
839 let mut err = struct_span_err!(self.resolver.session, span, E0432, "{}", &msg);
840 for span_error in error_vec.into_iter().take(max_span_label_msg_count) {
841 err.span_label(span_error.0, span_error.2);
846 /// Attempts to resolve the given import, returning true if its resolution is determined.
847 /// If successful, the resolved bindings are written into the module.
848 fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool {
849 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
850 names_to_string(&directive.module_path[..]),
851 module_to_string(self.current_module).unwrap_or("???".to_string()));
853 self.current_module = directive.parent;
855 let module = if let Some(module) = directive.imported_module.get() {
858 let vis = directive.vis.get();
859 // For better failure detection, pretend that the import will not define any names
860 // while resolving its module path.
861 directive.vis.set(ty::Visibility::Invisible);
862 let result = self.resolve_path(
863 Some(if directive.is_uniform_paths_canary {
864 ModuleOrUniformRoot::Module(directive.parent)
866 ModuleOrUniformRoot::UniformRoot(keywords::Invalid.name())
868 &directive.module_path[..],
872 directive.crate_lint(),
874 directive.vis.set(vis);
877 PathResult::Module(module) => module,
878 PathResult::Indeterminate => return false,
883 directive.imported_module.set(Some(module));
884 let (source, target, result, type_ns_only) = match directive.subclass {
885 SingleImport { source, target, ref result, type_ns_only } =>
886 (source, target, result, type_ns_only),
887 GlobImport { .. } => {
888 self.resolve_glob_import(directive);
894 let mut indeterminate = false;
895 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
896 if let Err(Undetermined) = result[ns].get() {
897 result[ns].set(this.resolve_ident_in_module(module,
906 let parent = directive.parent;
907 match result[ns].get() {
908 Err(Undetermined) => indeterminate = true,
910 this.update_resolution(parent, target, ns, |_, resolution| {
911 resolution.single_imports.remove(&PtrKey(directive));
914 Ok(binding) if !binding.is_importable() => {
915 let msg = format!("`{}` is not directly importable", target);
916 struct_span_err!(this.session, directive.span, E0253, "{}", &msg)
917 .span_label(directive.span, "cannot be imported directly")
919 // Do not import this illegal binding. Import a dummy binding and pretend
920 // everything is fine
921 this.import_dummy_binding(directive);
924 let imported_binding = this.import(binding, directive);
925 let conflict = this.try_define(parent, target, ns, imported_binding);
926 if let Err(old_binding) = conflict {
927 this.report_conflict(parent, target, ns, imported_binding, old_binding);
936 // If appropriate, returns an error to report.
937 fn finalize_import(&mut self, directive: &'b ImportDirective<'b>) -> Option<(Span, String)> {
938 self.current_module = directive.parent;
939 let ImportDirective { ref module_path, span, .. } = *directive;
941 let module_result = self.resolve_path(
942 Some(if directive.is_uniform_paths_canary {
943 ModuleOrUniformRoot::Module(directive.parent)
945 ModuleOrUniformRoot::UniformRoot(keywords::Invalid.name())
951 directive.crate_lint(),
953 let module = match module_result {
954 PathResult::Module(module) => module,
955 PathResult::Failed(span, msg, false) => {
956 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
959 PathResult::Failed(span, msg, true) => {
960 let (mut self_path, mut self_result) = (module_path.clone(), None);
961 let is_special = |ident: Ident| ident.is_path_segment_keyword() &&
962 ident.name != keywords::CrateRoot.name();
963 if !self_path.is_empty() && !is_special(self_path[0]) &&
964 !(self_path.len() > 1 && is_special(self_path[1])) {
965 self_path[0].name = keywords::SelfValue.name();
966 self_result = Some(self.resolve_path(None, &self_path, None, false,
967 span, CrateLint::No));
969 return if let Some(PathResult::Module(..)) = self_result {
970 Some((span, format!("Did you mean `{}`?", names_to_string(&self_path[..]))))
978 let (ident, result, type_ns_only) = match directive.subclass {
979 SingleImport { source, ref result, type_ns_only, .. } => (source, result, type_ns_only),
980 GlobImport { is_prelude, ref max_vis } => {
981 if module_path.len() <= 1 {
982 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
983 // 2 segments, so the `resolve_path` above won't trigger it.
984 let mut full_path = module_path.clone();
985 full_path.push(keywords::Invalid.ident());
986 self.lint_if_path_starts_with_module(
987 directive.crate_lint(),
994 if let ModuleOrUniformRoot::Module(module) = module {
995 if module.def_id() == directive.parent.def_id() {
996 // Importing a module into itself is not allowed.
997 return Some((directive.span,
998 "Cannot glob-import a module into itself.".to_string()));
1002 max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
1003 !max_vis.get().is_at_least(directive.vis.get(), &*self) {
1004 let msg = "A non-empty glob must import something with the glob's visibility";
1005 self.session.span_err(directive.span, msg);
1009 _ => unreachable!(),
1012 // Do not record uses from canaries, to avoid interfering with other
1013 // diagnostics or suggestions that rely on some items not being used.
1014 let record_used = !directive.is_uniform_paths_canary;
1016 let mut all_ns_err = true;
1017 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
1018 if let Ok(binding) = result[ns].get() {
1020 if record_used && this.record_use(ident, ns, binding) {
1021 if let ModuleOrUniformRoot::Module(module) = module {
1022 this.resolution(module, ident, ns).borrow_mut().binding =
1023 Some(this.dummy_binding);
1030 let mut all_ns_failed = true;
1031 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
1032 match this.resolve_ident_in_module(module, ident, ns, record_used, span) {
1033 Ok(_) => all_ns_failed = false,
1038 return if all_ns_failed {
1039 let resolutions = match module {
1040 ModuleOrUniformRoot::Module(module) =>
1041 Some(module.resolutions.borrow()),
1042 ModuleOrUniformRoot::UniformRoot(_) => None,
1044 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
1045 let names = resolutions.filter_map(|(&(ref i, _), resolution)| {
1046 if *i == ident { return None; } // Never suggest the same name
1047 match *resolution.borrow() {
1048 NameResolution { binding: Some(name_binding), .. } => {
1049 match name_binding.kind {
1050 NameBindingKind::Import { binding, .. } => {
1051 match binding.kind {
1052 // Never suggest the name that has binding error
1053 // i.e. the name that cannot be previously resolved
1054 NameBindingKind::Def(Def::Err, _) => return None,
1061 NameResolution { ref single_imports, .. }
1062 if single_imports.is_empty() => None,
1066 let lev_suggestion =
1067 match find_best_match_for_name(names, &ident.as_str(), None) {
1068 Some(name) => format!(". Did you mean to use `{}`?", name),
1069 None => String::new(),
1071 let msg = match module {
1072 ModuleOrUniformRoot::Module(module) => {
1073 let module_str = module_to_string(module);
1074 if let Some(module_str) = module_str {
1075 format!("no `{}` in `{}`{}", ident, module_str, lev_suggestion)
1077 format!("no `{}` in the root{}", ident, lev_suggestion)
1080 ModuleOrUniformRoot::UniformRoot(_) => {
1081 if !ident.is_path_segment_keyword() {
1082 format!("no `{}` external crate{}", ident, lev_suggestion)
1084 // HACK(eddyb) this shows up for `self` & `super`, which
1085 // should work instead - for now keep the same error message.
1086 format!("no `{}` in the root{}", ident, lev_suggestion)
1092 // `resolve_ident_in_module` reported a privacy error.
1093 self.import_dummy_binding(directive);
1098 let mut reexport_error = None;
1099 let mut any_successful_reexport = false;
1100 self.per_ns(|this, ns| {
1101 if let Ok(binding) = result[ns].get() {
1102 let vis = directive.vis.get();
1103 if !binding.pseudo_vis().is_at_least(vis, &*this) {
1104 reexport_error = Some((ns, binding));
1106 any_successful_reexport = true;
1111 // All namespaces must be re-exported with extra visibility for an error to occur.
1112 if !any_successful_reexport {
1113 let (ns, binding) = reexport_error.unwrap();
1114 if ns == TypeNS && binding.is_extern_crate() {
1115 let msg = format!("extern crate `{}` is private, and cannot be \
1116 re-exported (error E0365), consider declaring with \
1119 self.session.buffer_lint(PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1123 } else if ns == TypeNS {
1124 struct_span_err!(self.session, directive.span, E0365,
1125 "`{}` is private, and cannot be re-exported", ident)
1126 .span_label(directive.span, format!("re-export of private `{}`", ident))
1127 .note(&format!("consider declaring type or module `{}` with `pub`", ident))
1130 let msg = format!("`{}` is private, and cannot be re-exported", ident);
1132 format!("consider marking `{}` as `pub` in the imported module", ident);
1133 struct_span_err!(self.session, directive.span, E0364, "{}", &msg)
1134 .span_note(directive.span, ¬e_msg)
1139 if module_path.len() <= 1 {
1140 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1141 // 2 segments, so the `resolve_path` above won't trigger it.
1142 let mut full_path = module_path.clone();
1143 full_path.push(ident);
1144 self.per_ns(|this, ns| {
1145 if let Ok(binding) = result[ns].get() {
1146 this.lint_if_path_starts_with_module(
1147 directive.crate_lint(),
1156 // Record what this import resolves to for later uses in documentation,
1157 // this may resolve to either a value or a type, but for documentation
1158 // purposes it's good enough to just favor one over the other.
1159 self.per_ns(|this, ns| if let Some(binding) = result[ns].get().ok() {
1160 let import = this.import_map.entry(directive.id).or_default();
1161 import[ns] = Some(PathResolution::new(binding.def()));
1164 debug!("(resolving single import) successfully resolved import");
1168 fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) {
1169 let module = match directive.imported_module.get().unwrap() {
1170 ModuleOrUniformRoot::Module(module) => module,
1171 ModuleOrUniformRoot::UniformRoot(_) => {
1172 self.session.span_err(directive.span,
1173 "cannot glob-import all possible crates");
1178 self.populate_module_if_necessary(module);
1180 if let Some(Def::Trait(_)) = module.def() {
1181 self.session.span_err(directive.span, "items in traits are not importable.");
1183 } else if module.def_id() == directive.parent.def_id() {
1185 } else if let GlobImport { is_prelude: true, .. } = directive.subclass {
1186 self.prelude = Some(module);
1190 // Add to module's glob_importers
1191 module.glob_importers.borrow_mut().push(directive);
1193 // Ensure that `resolutions` isn't borrowed during `try_define`,
1194 // since it might get updated via a glob cycle.
1195 let bindings = module.resolutions.borrow().iter().filter_map(|(&ident, resolution)| {
1196 resolution.borrow().binding().map(|binding| (ident, binding))
1197 }).collect::<Vec<_>>();
1198 for ((mut ident, ns), binding) in bindings {
1199 let scope = match ident.span.reverse_glob_adjust(module.expansion,
1200 directive.span.ctxt().modern()) {
1201 Some(Some(def)) => self.macro_def_scope(def),
1202 Some(None) => self.current_module,
1205 if self.is_accessible_from(binding.pseudo_vis(), scope) {
1206 let imported_binding = self.import(binding, directive);
1207 let _ = self.try_define(directive.parent, ident, ns, imported_binding);
1211 // Record the destination of this import
1212 self.record_def(directive.id, PathResolution::new(module.def().unwrap()));
1215 // Miscellaneous post-processing, including recording re-exports,
1216 // reporting conflicts, and reporting unresolved imports.
1217 fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1218 // Since import resolution is finished, globs will not define any more names.
1219 *module.globs.borrow_mut() = Vec::new();
1221 let mut reexports = Vec::new();
1223 for (&(ident, ns), resolution) in module.resolutions.borrow().iter() {
1224 let resolution = &mut *resolution.borrow_mut();
1225 let binding = match resolution.binding {
1226 Some(binding) => binding,
1230 // Don't reexport `uniform_path` canaries.
1231 let non_canary_import = match binding.kind {
1232 NameBindingKind::Import { directive, .. } => {
1233 !directive.is_uniform_paths_canary
1238 if non_canary_import || binding.is_macro_def() {
1239 let def = binding.def();
1240 if def != Def::Err {
1241 if !def.def_id().is_local() {
1242 self.cstore.export_macros_untracked(def.def_id().krate);
1244 reexports.push(Export {
1245 ident: ident.modern(),
1253 match binding.kind {
1254 NameBindingKind::Import { binding: orig_binding, directive, .. } => {
1255 if ns == TypeNS && orig_binding.is_variant() &&
1256 !orig_binding.vis.is_at_least(binding.vis, &*self) {
1257 let msg = match directive.subclass {
1258 ImportDirectiveSubclass::SingleImport { .. } => {
1259 format!("variant `{}` is private and cannot be re-exported",
1262 ImportDirectiveSubclass::GlobImport { .. } => {
1263 let msg = "enum is private and its variants \
1264 cannot be re-exported".to_owned();
1265 let error_id = (DiagnosticMessageId::ErrorId(0), // no code?!
1268 let fresh = self.session.one_time_diagnostics
1269 .borrow_mut().insert(error_id);
1275 ref s @ _ => bug!("unexpected import subclass {:?}", s)
1277 let mut err = self.session.struct_span_err(binding.span, &msg);
1279 let imported_module = match directive.imported_module.get() {
1280 Some(ModuleOrUniformRoot::Module(module)) => module,
1281 _ => bug!("module should exist"),
1283 let resolutions = imported_module.parent.expect("parent should exist")
1284 .resolutions.borrow();
1285 let enum_path_segment_index = directive.module_path.len() - 1;
1286 let enum_ident = directive.module_path[enum_path_segment_index];
1288 let enum_resolution = resolutions.get(&(enum_ident, TypeNS))
1289 .expect("resolution should exist");
1290 let enum_span = enum_resolution.borrow()
1291 .binding.expect("binding should exist")
1293 let enum_def_span = self.session.source_map().def_span(enum_span);
1294 let enum_def_snippet = self.session.source_map()
1295 .span_to_snippet(enum_def_span).expect("snippet should exist");
1296 // potentially need to strip extant `crate`/`pub(path)` for suggestion
1297 let after_vis_index = enum_def_snippet.find("enum")
1298 .expect("`enum` keyword should exist in snippet");
1299 let suggestion = format!("pub {}",
1300 &enum_def_snippet[after_vis_index..]);
1303 .diag_span_suggestion_once(&mut err,
1304 DiagnosticMessageId::ErrorId(0),
1306 "consider making the enum public",
1315 if reexports.len() > 0 {
1316 if let Some(def_id) = module.def_id() {
1317 self.export_map.insert(def_id, reexports);
1323 fn import_path_to_string(names: &[Ident],
1324 subclass: &ImportDirectiveSubclass,
1325 span: Span) -> String {
1326 let pos = names.iter()
1327 .position(|p| span == p.span && p.name != keywords::CrateRoot.name());
1328 let global = !names.is_empty() && names[0].name == keywords::CrateRoot.name();
1329 if let Some(pos) = pos {
1330 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1331 names_to_string(names)
1333 let names = if global { &names[1..] } else { names };
1334 if names.is_empty() {
1335 import_directive_subclass_to_string(subclass)
1338 names_to_string(names),
1339 import_directive_subclass_to_string(subclass))
1344 fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass) -> String {
1346 SingleImport { source, .. } => source.to_string(),
1347 GlobImport { .. } => "*".to_string(),
1348 ExternCrate(_) => "<extern crate>".to_string(),
1349 MacroUse => "#[macro_use]".to_string(),