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, AmbiguityKind, AmbiguityErrorMisc};
14 use {CrateLint, Module, ModuleOrUniformRoot, PerNS, ScopeSet, Weak};
15 use Namespace::{self, TypeNS, MacroNS};
16 use {NameBinding, NameBindingKind, ToNameBinding, PathResult, PrivacyError};
17 use {Resolver, Segment};
18 use {names_to_string, module_to_string};
19 use {resolve_error, ResolutionError};
20 use macros::ParentScope;
22 use rustc_data_structures::ptr_key::PtrKey;
24 use rustc::lint::builtin::BuiltinLintDiagnostics;
25 use rustc::lint::builtin::{DUPLICATE_MACRO_EXPORTS, PUB_USE_OF_PRIVATE_EXTERN_CRATE};
26 use rustc::hir::def_id::{CrateNum, DefId};
27 use rustc::hir::def::*;
28 use rustc::session::DiagnosticMessageId;
29 use rustc::util::nodemap::FxHashSet;
31 use syntax::ast::{Ident, Name, NodeId, CRATE_NODE_ID};
32 use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
33 use syntax::ext::hygiene::Mark;
34 use syntax::symbol::keywords;
35 use syntax::util::lev_distance::find_best_match_for_name;
36 use syntax_pos::{MultiSpan, Span};
38 use std::cell::{Cell, RefCell};
41 /// Contains data for specific types of import directives.
42 #[derive(Clone, Debug)]
43 pub enum ImportDirectiveSubclass<'a> {
45 /// `source` in `use prefix::source as target`.
47 /// `target` in `use prefix::source as target`.
49 /// Bindings to which `source` refers to.
50 source_bindings: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
51 /// Bindings introduced by `target`.
52 target_bindings: PerNS<Cell<Option<&'a NameBinding<'a>>>>,
53 /// `true` for `...::{self [as target]}` imports, `false` otherwise.
58 max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
59 // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
68 /// One import directive.
69 #[derive(Debug,Clone)]
70 crate struct ImportDirective<'a> {
71 /// The id of the `extern crate`, `UseTree` etc that imported this `ImportDirective`.
73 /// In the case where the `ImportDirective` was expanded from a "nested" use tree,
74 /// this id is the id of the leaf tree. For example:
76 /// ```ignore (pacify the mercilous tidy)
77 /// use foo::bar::{a, b}
80 /// If this is the import directive for `foo::bar::a`, we would have the id of the `UseTree`
81 /// for `a` in this field.
84 /// The `id` of the "root" use-kind -- this is always the same as
85 /// `id` except in the case of "nested" use trees, in which case
86 /// it will be the `id` of the root use tree. e.g., in the example
87 /// from `id`, this would be the id of the `use foo::bar`
91 /// Span of this use tree.
94 /// Span of the *root* use tree (see `root_id`).
97 pub parent_scope: ParentScope<'a>,
98 pub module_path: Vec<Segment>,
99 /// The resolution of `module_path`.
100 pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>,
101 pub subclass: ImportDirectiveSubclass<'a>,
102 pub vis: Cell<ty::Visibility>,
103 pub used: Cell<bool>,
106 impl<'a> ImportDirective<'a> {
107 pub fn is_glob(&self) -> bool {
108 match self.subclass { ImportDirectiveSubclass::GlobImport { .. } => true, _ => false }
111 crate fn crate_lint(&self) -> CrateLint {
112 CrateLint::UsePath { root_id: self.root_id, root_span: self.root_span }
116 #[derive(Clone, Default, Debug)]
117 /// Records information about the resolution of a name in a namespace of a module.
118 pub struct NameResolution<'a> {
119 /// Single imports that may define the name in the namespace.
120 /// Import directives are arena-allocated, so it's ok to use pointers as keys.
121 single_imports: FxHashSet<PtrKey<'a, ImportDirective<'a>>>,
122 /// The least shadowable known binding for this name, or None if there are no known bindings.
123 pub binding: Option<&'a NameBinding<'a>>,
124 shadowed_glob: Option<&'a NameBinding<'a>>,
127 impl<'a> NameResolution<'a> {
128 // Returns the binding for the name if it is known or None if it not known.
129 fn binding(&self) -> Option<&'a NameBinding<'a>> {
130 self.binding.and_then(|binding| {
131 if !binding.is_glob_import() ||
132 self.single_imports.is_empty() { Some(binding) } else { None }
137 impl<'a, 'crateloader> Resolver<'a, 'crateloader> {
138 fn resolution(&self, module: Module<'a>, ident: Ident, ns: Namespace)
139 -> &'a RefCell<NameResolution<'a>> {
140 *module.resolutions.borrow_mut().entry((ident.modern(), ns))
141 .or_insert_with(|| self.arenas.alloc_name_resolution())
144 crate fn resolve_ident_in_module_unadjusted(
146 module: ModuleOrUniformRoot<'a>,
151 ) -> Result<&'a NameBinding<'a>, Determinacy> {
152 self.resolve_ident_in_module_unadjusted_ext(
153 module, ident, ns, None, false, record_used, path_span
154 ).map_err(|(determinacy, _)| determinacy)
157 /// Attempts to resolve `ident` in namespaces `ns` of `module`.
158 /// Invariant: if `record_used` is `Some`, expansion and import resolution must be complete.
159 crate fn resolve_ident_in_module_unadjusted_ext(
161 module: ModuleOrUniformRoot<'a>,
164 parent_scope: Option<&ParentScope<'a>>,
165 restricted_shadowing: bool,
168 ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
169 let module = match module {
170 ModuleOrUniformRoot::Module(module) => module,
171 ModuleOrUniformRoot::CrateRootAndExternPrelude => {
172 assert!(!restricted_shadowing);
173 let parent_scope = self.dummy_parent_scope();
174 let binding = self.early_resolve_ident_in_lexical_scope(
175 ident, ScopeSet::AbsolutePath(ns), &parent_scope,
176 record_used, record_used, path_span,
178 return binding.map_err(|determinacy| (determinacy, Weak::No));
180 ModuleOrUniformRoot::ExternPrelude => {
181 assert!(!restricted_shadowing);
182 return if ns != TypeNS {
183 Err((Determined, Weak::No))
184 } else if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
186 } else if !self.graph_root.unresolved_invocations.borrow().is_empty() {
187 // Macro-expanded `extern crate` items can add names to extern prelude.
188 Err((Undetermined, Weak::No))
190 Err((Determined, Weak::No))
193 ModuleOrUniformRoot::CurrentScope => {
194 assert!(!restricted_shadowing);
196 parent_scope.expect("no parent scope for a single-segment import");
199 if ident.name == keywords::Crate.name() ||
200 ident.name == keywords::DollarCrate.name() {
201 let module = self.resolve_crate_root(ident);
202 let binding = (module, ty::Visibility::Public,
203 module.span, Mark::root())
204 .to_name_binding(self.arenas);
206 } else if ident.name == keywords::Super.name() ||
207 ident.name == keywords::SelfLower.name() {
208 // FIXME: Implement these with renaming requirements so that e.g.
209 // `use super;` doesn't work, but `use super as name;` does.
210 // Fall through here to get an error from `early_resolve_...`.
214 let binding = self.early_resolve_ident_in_lexical_scope(
215 ident, ScopeSet::Import(ns), parent_scope, record_used, record_used, path_span
217 return binding.map_err(|determinacy| (determinacy, Weak::No));
221 self.populate_module_if_necessary(module);
223 let resolution = self.resolution(module, ident, ns)
225 .map_err(|_| (Determined, Weak::No))?; // This happens when there is a cycle of imports.
227 if let Some(binding) = resolution.binding {
228 if !restricted_shadowing && binding.expansion != Mark::root() {
229 if let NameBindingKind::Def(_, true) = binding.kind {
230 self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
235 let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
236 if let Some(blacklisted_binding) = this.blacklisted_binding {
237 if ptr::eq(binding, blacklisted_binding) {
238 return Err((Determined, Weak::No));
241 // `extern crate` are always usable for backwards compatibility, see issue #37020,
242 // remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`.
243 let usable = this.is_accessible(binding.vis) || binding.is_extern_crate();
244 if usable { Ok(binding) } else { Err((Determined, Weak::No)) }
248 return resolution.binding.ok_or((Determined, Weak::No)).and_then(|binding| {
249 if self.last_import_segment && check_usable(self, binding).is_err() {
250 Err((Determined, Weak::No))
252 self.record_use(ident, ns, binding, restricted_shadowing);
254 if let Some(shadowed_glob) = resolution.shadowed_glob {
255 // Forbid expanded shadowing to avoid time travel.
256 if restricted_shadowing &&
257 binding.expansion != Mark::root() &&
258 binding.def() != shadowed_glob.def() {
259 self.ambiguity_errors.push(AmbiguityError {
260 kind: AmbiguityKind::GlobVsExpanded,
264 misc1: AmbiguityErrorMisc::None,
265 misc2: AmbiguityErrorMisc::None,
270 if !self.is_accessible(binding.vis) &&
271 // Remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
272 !(self.last_import_segment && binding.is_extern_crate()) {
273 self.privacy_errors.push(PrivacyError(path_span, ident, binding));
281 // Items and single imports are not shadowable, if we have one, then it's determined.
282 if let Some(binding) = resolution.binding {
283 if !binding.is_glob_import() {
284 return check_usable(self, binding);
288 // --- From now on we either have a glob resolution or no resolution. ---
290 // Check if one of single imports can still define the name,
291 // if it can then our result is not determined and can be invalidated.
292 for single_import in &resolution.single_imports {
293 if !self.is_accessible(single_import.vis.get()) {
296 let module = unwrap_or!(single_import.imported_module.get(),
297 return Err((Undetermined, Weak::No)));
298 let ident = match single_import.subclass {
299 SingleImport { source, .. } => source,
302 match self.resolve_ident_in_module(module, ident, ns, Some(&single_import.parent_scope),
304 Err(Determined) => continue,
305 Ok(binding) if !self.is_accessible_from(
306 binding.vis, single_import.parent_scope.module
308 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::No)),
312 // So we have a resolution that's from a glob import. This resolution is determined
313 // if it cannot be shadowed by some new item/import expanded from a macro.
314 // This happens either if there are no unexpanded macros, or expanded names cannot
315 // shadow globs (that happens in macro namespace or with restricted shadowing).
317 // Additionally, any macro in any module can plant names in the root module if it creates
318 // `macro_export` macros, so the root module effectively has unresolved invocations if any
319 // module has unresolved invocations.
320 // However, it causes resolution/expansion to stuck too often (#53144), so, to make
321 // progress, we have to ignore those potential unresolved invocations from other modules
322 // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
323 // shadowing is enabled, see `macro_expanded_macro_export_errors`).
324 let unexpanded_macros = !module.unresolved_invocations.borrow().is_empty();
325 if let Some(binding) = resolution.binding {
326 if !unexpanded_macros || ns == MacroNS || restricted_shadowing {
327 return check_usable(self, binding);
329 return Err((Undetermined, Weak::No));
333 // --- From now on we have no resolution. ---
335 // Now we are in situation when new item/import can appear only from a glob or a macro
336 // expansion. With restricted shadowing names from globs and macro expansions cannot
337 // shadow names from outer scopes, so we can freely fallback from module search to search
338 // in outer scopes. For `early_resolve_ident_in_lexical_scope` to continue search in outer
339 // scopes we return `Undetermined` with `Weak::Yes`.
341 // Check if one of unexpanded macros can still define the name,
342 // if it can then our "no resolution" result is not determined and can be invalidated.
343 if unexpanded_macros {
344 return Err((Undetermined, Weak::Yes));
347 // Check if one of glob imports can still define the name,
348 // if it can then our "no resolution" result is not determined and can be invalidated.
349 for glob_import in module.globs.borrow().iter() {
350 if !self.is_accessible(glob_import.vis.get()) {
353 let module = match glob_import.imported_module.get() {
354 Some(ModuleOrUniformRoot::Module(module)) => module,
356 None => return Err((Undetermined, Weak::Yes)),
358 let (orig_current_module, mut ident) = (self.current_module, ident.modern());
359 match ident.span.glob_adjust(module.expansion, glob_import.span.ctxt().modern()) {
360 Some(Some(def)) => self.current_module = self.macro_def_scope(def),
364 let result = self.resolve_ident_in_module_unadjusted(
365 ModuleOrUniformRoot::Module(module),
371 self.current_module = orig_current_module;
374 Err(Determined) => continue,
375 Ok(binding) if !self.is_accessible_from(
376 binding.vis, glob_import.parent_scope.module
378 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::Yes)),
382 // No resolution and no one else can define the name - determinate error.
383 Err((Determined, Weak::No))
386 // Add an import directive to the current module.
387 pub fn add_import_directive(&mut self,
388 module_path: Vec<Segment>,
389 subclass: ImportDirectiveSubclass<'a>,
395 parent_scope: ParentScope<'a>) {
396 let current_module = parent_scope.module;
397 let directive = self.arenas.alloc_import_directive(ImportDirective {
400 imported_module: Cell::new(None),
407 used: Cell::new(false),
410 debug!("add_import_directive({:?})", directive);
412 self.indeterminate_imports.push(directive);
413 match directive.subclass {
414 SingleImport { target, type_ns_only, .. } => {
415 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
416 let mut resolution = this.resolution(current_module, target, ns).borrow_mut();
417 resolution.single_imports.insert(PtrKey(directive));
420 // We don't add prelude imports to the globs since they only affect lexical scopes,
421 // which are not relevant to import resolution.
422 GlobImport { is_prelude: true, .. } => {}
423 GlobImport { .. } => current_module.globs.borrow_mut().push(directive),
428 // Given a binding and an import directive that resolves to it,
429 // return the corresponding binding defined by the import directive.
430 crate fn import(&self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>)
431 -> &'a NameBinding<'a> {
432 let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) ||
433 // cf. `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
434 !directive.is_glob() && binding.is_extern_crate() {
440 if let GlobImport { ref max_vis, .. } = directive.subclass {
441 if vis == directive.vis.get() || vis.is_at_least(max_vis.get(), self) {
446 self.arenas.alloc_name_binding(NameBinding {
447 kind: NameBindingKind::Import {
450 used: Cell::new(false),
452 span: directive.span,
454 expansion: directive.parent_scope.expansion,
458 crate fn check_reserved_macro_name(&self, ident: Ident, ns: Namespace) {
459 // Reserve some names that are not quite covered by the general check
460 // performed on `Resolver::builtin_attrs`.
462 (ident.name == "cfg" || ident.name == "cfg_attr" || ident.name == "derive") {
463 self.session.span_err(ident.span,
464 &format!("name `{}` is reserved in macro namespace", ident));
468 // Define the name or return the existing binding if there is a collision.
469 pub fn try_define(&mut self,
473 binding: &'a NameBinding<'a>)
474 -> Result<(), &'a NameBinding<'a>> {
475 self.check_reserved_macro_name(ident, ns);
476 self.set_binding_parent_module(binding, module);
477 self.update_resolution(module, ident, ns, |this, resolution| {
478 if let Some(old_binding) = resolution.binding {
479 match (old_binding.is_glob_import(), binding.is_glob_import()) {
481 if binding.def() != old_binding.def() {
482 resolution.binding = Some(this.ambiguity(AmbiguityKind::GlobVsGlob,
483 old_binding, binding));
484 } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
485 // We are glob-importing the same item but with greater visibility.
486 resolution.binding = Some(binding);
489 (old_glob @ true, false) | (old_glob @ false, true) => {
490 let (glob_binding, nonglob_binding) = if old_glob {
491 (old_binding, binding)
493 (binding, old_binding)
495 if glob_binding.def() != nonglob_binding.def() &&
496 ns == MacroNS && nonglob_binding.expansion != Mark::root() {
497 resolution.binding = Some(this.ambiguity(AmbiguityKind::GlobVsExpanded,
498 nonglob_binding, glob_binding));
500 resolution.binding = Some(nonglob_binding);
501 resolution.shadowed_glob = Some(glob_binding);
505 if let (&NameBindingKind::Def(_, true), &NameBindingKind::Def(_, true)) =
506 (&old_binding.kind, &binding.kind) {
508 this.session.buffer_lint_with_diagnostic(
509 DUPLICATE_MACRO_EXPORTS,
512 &format!("a macro named `{}` has already been exported", ident),
513 BuiltinLintDiagnostics::DuplicatedMacroExports(
514 ident, old_binding.span, binding.span));
516 resolution.binding = Some(binding);
518 return Err(old_binding);
523 resolution.binding = Some(binding);
530 fn ambiguity(&self, kind: AmbiguityKind, b1: &'a NameBinding<'a>, b2: &'a NameBinding<'a>)
531 -> &'a NameBinding<'a> {
532 self.arenas.alloc_name_binding(NameBinding {
533 kind: NameBindingKind::Ambiguity { kind, b1, b2 },
534 vis: if b1.vis.is_at_least(b2.vis, self) { b1.vis } else { b2.vis },
536 expansion: Mark::root(),
540 // Use `f` to mutate the resolution of the name in the module.
541 // If the resolution becomes a success, define it in the module's glob importers.
542 fn update_resolution<T, F>(&mut self, module: Module<'a>, ident: Ident, ns: Namespace, f: F)
544 where F: FnOnce(&mut Resolver<'a, 'crateloader>, &mut NameResolution<'a>) -> T
546 // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
547 // during which the resolution might end up getting re-defined via a glob cycle.
549 let resolution = &mut *self.resolution(module, ident, ns).borrow_mut();
550 let old_binding = resolution.binding();
552 let t = f(self, resolution);
554 match resolution.binding() {
555 _ if old_binding.is_some() => return t,
557 Some(binding) => match old_binding {
558 Some(old_binding) if ptr::eq(old_binding, binding) => return t,
564 // Define `binding` in `module`s glob importers.
565 for directive in module.glob_importers.borrow_mut().iter() {
566 let mut ident = ident.modern();
567 let scope = match ident.span.reverse_glob_adjust(module.expansion,
568 directive.span.ctxt().modern()) {
569 Some(Some(def)) => self.macro_def_scope(def),
570 Some(None) => directive.parent_scope.module,
573 if self.is_accessible_from(binding.vis, scope) {
574 let imported_binding = self.import(binding, directive);
575 let _ = self.try_define(directive.parent_scope.module, ident, ns, imported_binding);
582 // Define a "dummy" resolution containing a Def::Err as a placeholder for a
584 fn import_dummy_binding(&mut self, directive: &'a ImportDirective<'a>) {
585 if let SingleImport { target, .. } = directive.subclass {
586 let dummy_binding = self.dummy_binding;
587 let dummy_binding = self.import(dummy_binding, directive);
588 self.per_ns(|this, ns| {
589 let _ = this.try_define(directive.parent_scope.module, target, ns, dummy_binding);
595 pub struct ImportResolver<'a, 'b: 'a, 'c: 'a + 'b> {
596 pub resolver: &'a mut Resolver<'b, 'c>,
599 impl<'a, 'b: 'a, 'c: 'a + 'b> ::std::ops::Deref for ImportResolver<'a, 'b, 'c> {
600 type Target = Resolver<'b, 'c>;
601 fn deref(&self) -> &Resolver<'b, 'c> {
606 impl<'a, 'b: 'a, 'c: 'a + 'b> ::std::ops::DerefMut for ImportResolver<'a, 'b, 'c> {
607 fn deref_mut(&mut self) -> &mut Resolver<'b, 'c> {
612 impl<'a, 'b: 'a, 'c: 'a + 'b> ty::DefIdTree for &'a ImportResolver<'a, 'b, 'c> {
613 fn parent(self, id: DefId) -> Option<DefId> {
614 self.resolver.parent(id)
618 impl<'a, 'b:'a, 'c: 'b> ImportResolver<'a, 'b, 'c> {
621 // This is a fixed-point algorithm. We resolve imports until our efforts
622 // are stymied by an unresolved import; then we bail out of the current
623 // module and continue. We terminate successfully once no more imports
624 // remain or unsuccessfully when no forward progress in resolving imports
627 /// Resolves all imports for the crate. This method performs the fixed-
629 pub fn resolve_imports(&mut self) {
630 let mut prev_num_indeterminates = self.indeterminate_imports.len() + 1;
631 while self.indeterminate_imports.len() < prev_num_indeterminates {
632 prev_num_indeterminates = self.indeterminate_imports.len();
633 for import in mem::replace(&mut self.indeterminate_imports, Vec::new()) {
634 match self.resolve_import(&import) {
635 true => self.determined_imports.push(import),
636 false => self.indeterminate_imports.push(import),
642 pub fn finalize_imports(&mut self) {
643 for module in self.arenas.local_modules().iter() {
644 self.finalize_resolutions_in(module);
647 let mut errors = false;
648 let mut seen_spans = FxHashSet::default();
649 let mut error_vec = Vec::new();
650 let mut prev_root_id: NodeId = NodeId::from_u32(0);
651 for i in 0 .. self.determined_imports.len() {
652 let import = self.determined_imports[i];
653 if let Some((span, err, note)) = self.finalize_import(import) {
656 if let SingleImport { source, ref source_bindings, .. } = import.subclass {
657 if source.name == "self" {
658 // Silence `unresolved import` error if E0429 is already emitted
659 if let Err(Determined) = source_bindings.value_ns.get() {
665 // If the error is a single failed import then create a "fake" import
666 // resolution for it so that later resolve stages won't complain.
667 self.import_dummy_binding(import);
668 if prev_root_id.as_u32() != 0 &&
669 prev_root_id.as_u32() != import.root_id.as_u32() &&
670 !error_vec.is_empty(){
671 // in case of new import line, throw diagnostic message
672 // for previous line.
673 let mut empty_vec = vec![];
674 mem::swap(&mut empty_vec, &mut error_vec);
675 self.throw_unresolved_import_error(empty_vec, None);
677 if !seen_spans.contains(&span) {
678 let path = import_path_to_string(
679 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
683 error_vec.push((span, path, err, note));
684 seen_spans.insert(span);
685 prev_root_id = import.root_id;
690 if !error_vec.is_empty() {
691 self.throw_unresolved_import_error(error_vec.clone(), None);
694 // Report unresolved imports only if no hard error was already reported
695 // to avoid generating multiple errors on the same import.
697 for import in &self.indeterminate_imports {
698 self.throw_unresolved_import_error(error_vec, Some(MultiSpan::from(import.span)));
704 fn throw_unresolved_import_error(
706 error_vec: Vec<(Span, String, String, Option<String>)>,
707 span: Option<MultiSpan>,
709 let max_span_label_msg_count = 10; // upper limit on number of span_label message.
710 let (span, msg, note) = if error_vec.is_empty() {
711 (span.unwrap(), "unresolved import".to_string(), None)
713 let span = MultiSpan::from_spans(
714 error_vec.clone().into_iter()
715 .map(|elem: (Span, String, String, Option<String>)| elem.0)
719 let note: Option<String> = error_vec.clone().into_iter()
720 .filter_map(|elem: (Span, String, String, Option<String>)| elem.3)
723 let path_vec: Vec<String> = error_vec.clone().into_iter()
724 .map(|elem: (Span, String, String, Option<String>)| format!("`{}`", elem.1))
726 let path = path_vec.join(", ");
728 "unresolved import{} {}",
729 if path_vec.len() > 1 { "s" } else { "" },
736 let mut err = struct_span_err!(self.resolver.session, span, E0432, "{}", &msg);
737 for span_error in error_vec.into_iter().take(max_span_label_msg_count) {
738 err.span_label(span_error.0, span_error.2);
740 if let Some(note) = note {
746 /// Attempts to resolve the given import, returning true if its resolution is determined.
747 /// If successful, the resolved bindings are written into the module.
748 fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool {
749 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
750 Segment::names_to_string(&directive.module_path),
751 module_to_string(self.current_module).unwrap_or_else(|| "???".to_string()));
753 self.current_module = directive.parent_scope.module;
755 let module = if let Some(module) = directive.imported_module.get() {
758 // For better failure detection, pretend that the import will
759 // not define any names while resolving its module path.
760 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
761 let path_res = self.resolve_path(
762 &directive.module_path,
764 &directive.parent_scope,
767 directive.crate_lint(),
769 directive.vis.set(orig_vis);
772 PathResult::Module(module) => module,
773 PathResult::Indeterminate => return false,
774 PathResult::NonModule(..) | PathResult::Failed(..) => return true,
778 directive.imported_module.set(Some(module));
779 let (source, target, source_bindings, target_bindings, type_ns_only) =
780 match directive.subclass {
781 SingleImport { source, target, ref source_bindings,
782 ref target_bindings, type_ns_only } =>
783 (source, target, source_bindings, target_bindings, type_ns_only),
784 GlobImport { .. } => {
785 self.resolve_glob_import(directive);
791 let mut indeterminate = false;
792 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
793 if let Err(Undetermined) = source_bindings[ns].get() {
794 // For better failure detection, pretend that the import will
795 // not define any names while resolving its module path.
796 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
797 let binding = this.resolve_ident_in_module(
798 module, source, ns, Some(&directive.parent_scope), false, directive.span
800 directive.vis.set(orig_vis);
802 source_bindings[ns].set(binding);
807 let parent = directive.parent_scope.module;
808 match source_bindings[ns].get() {
809 Err(Undetermined) => indeterminate = true,
811 this.update_resolution(parent, target, ns, |_, resolution| {
812 resolution.single_imports.remove(&PtrKey(directive));
815 Ok(binding) if !binding.is_importable() => {
816 let msg = format!("`{}` is not directly importable", target);
817 struct_span_err!(this.session, directive.span, E0253, "{}", &msg)
818 .span_label(directive.span, "cannot be imported directly")
820 // Do not import this illegal binding. Import a dummy binding and pretend
821 // everything is fine
822 this.import_dummy_binding(directive);
825 let imported_binding = this.import(binding, directive);
826 target_bindings[ns].set(Some(imported_binding));
827 let conflict = this.try_define(parent, target, ns, imported_binding);
828 if let Err(old_binding) = conflict {
829 this.report_conflict(parent, target, ns, imported_binding, old_binding);
838 // If appropriate, returns an error to report.
841 directive: &'b ImportDirective<'b>
842 ) -> Option<(Span, String, Option<String>)> {
843 self.current_module = directive.parent_scope.module;
845 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
846 let path_res = self.resolve_path(&directive.module_path, None, &directive.parent_scope,
847 true, directive.span, directive.crate_lint());
848 directive.vis.set(orig_vis);
849 let module = match path_res {
850 PathResult::Module(module) => {
851 // Consistency checks, analogous to `finalize_current_module_macro_resolutions`.
852 if let Some(initial_module) = directive.imported_module.get() {
853 if module != initial_module && self.ambiguity_errors.is_empty() {
854 span_bug!(directive.span, "inconsistent resolution for an import");
857 if self.privacy_errors.is_empty() {
858 let msg = "cannot determine resolution for the import";
859 let msg_note = "import resolution is stuck, try simplifying other imports";
860 self.session.struct_span_err(directive.span, msg).note(msg_note).emit();
866 PathResult::Failed(span, msg, false) => {
867 assert!(!self.ambiguity_errors.is_empty() ||
868 directive.imported_module.get().is_none());
869 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
872 PathResult::Failed(span, msg, true) => {
873 assert!(!self.ambiguity_errors.is_empty() ||
874 directive.imported_module.get().is_none());
875 return if let Some((suggested_path, note)) = self.make_path_suggestion(
876 span, directive.module_path.clone(), &directive.parent_scope
880 format!("did you mean `{}`?", Segment::names_to_string(&suggested_path)),
884 Some((span, msg, None))
887 PathResult::NonModule(path_res) if path_res.base_def() == Def::Err => {
888 // The error was already reported earlier.
889 assert!(!self.ambiguity_errors.is_empty() ||
890 directive.imported_module.get().is_none());
893 PathResult::Indeterminate | PathResult::NonModule(..) => unreachable!(),
896 let (ident, target, source_bindings, target_bindings, type_ns_only) =
897 match directive.subclass {
898 SingleImport { source, target, ref source_bindings,
899 ref target_bindings, type_ns_only } =>
900 (source, target, source_bindings, target_bindings, type_ns_only),
901 GlobImport { is_prelude, ref max_vis } => {
902 if directive.module_path.len() <= 1 {
903 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
904 // 2 segments, so the `resolve_path` above won't trigger it.
905 let mut full_path = directive.module_path.clone();
906 full_path.push(Segment::from_ident(keywords::Invalid.ident()));
907 self.lint_if_path_starts_with_module(
908 directive.crate_lint(),
915 if let ModuleOrUniformRoot::Module(module) = module {
916 if module.def_id() == directive.parent_scope.module.def_id() {
917 // Importing a module into itself is not allowed.
920 "Cannot glob-import a module into itself.".to_string(),
926 max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
927 !max_vis.get().is_at_least(directive.vis.get(), &*self) {
928 let msg = "A non-empty glob must import something with the glob's visibility";
929 self.session.span_err(directive.span, msg);
936 let mut all_ns_err = true;
937 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
938 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
939 let orig_blacklisted_binding =
940 mem::replace(&mut this.blacklisted_binding, target_bindings[ns].get());
941 let orig_last_import_segment = mem::replace(&mut this.last_import_segment, true);
942 let binding = this.resolve_ident_in_module(
943 module, ident, ns, Some(&directive.parent_scope), true, directive.span
945 this.last_import_segment = orig_last_import_segment;
946 this.blacklisted_binding = orig_blacklisted_binding;
947 directive.vis.set(orig_vis);
951 // Consistency checks, analogous to `finalize_current_module_macro_resolutions`.
952 let initial_def = source_bindings[ns].get().map(|initial_binding| {
954 if let Some(target_binding) = target_bindings[ns].get() {
955 if target.name == "_" &&
956 initial_binding.is_extern_crate() && !initial_binding.is_import() {
957 this.record_use(ident, ns, target_binding,
958 directive.module_path.is_empty());
961 initial_binding.def_ignoring_ambiguity()
963 let def = binding.def_ignoring_ambiguity();
964 if let Ok(initial_def) = initial_def {
965 if def != initial_def && this.ambiguity_errors.is_empty() {
966 span_bug!(directive.span, "inconsistent resolution for an import");
969 if def != Def::Err &&
970 this.ambiguity_errors.is_empty() && this.privacy_errors.is_empty() {
971 let msg = "cannot determine resolution for the import";
973 "import resolution is stuck, try simplifying other imports";
974 this.session.struct_span_err(directive.span, msg).note(msg_note).emit();
979 // FIXME: This assert may fire if public glob is later shadowed by a private
980 // single import (see test `issue-55884-2.rs`). In theory single imports should
981 // always block globs, even if they are not yet resolved, so that this kind of
982 // self-inconsistent resolution never happens.
983 // Reenable the assert when the issue is fixed.
984 // assert!(result[ns].get().is_err());
990 let mut all_ns_failed = true;
991 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
992 let binding = this.resolve_ident_in_module(
993 module, ident, ns, Some(&directive.parent_scope), true, directive.span
996 all_ns_failed = false;
1000 return if all_ns_failed {
1001 let resolutions = match module {
1002 ModuleOrUniformRoot::Module(module) => Some(module.resolutions.borrow()),
1005 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
1006 let names = resolutions.filter_map(|(&(ref i, _), resolution)| {
1007 if *i == ident { return None; } // Never suggest the same name
1008 match *resolution.borrow() {
1009 NameResolution { binding: Some(name_binding), .. } => {
1010 match name_binding.kind {
1011 NameBindingKind::Import { binding, .. } => {
1012 match binding.kind {
1013 // Never suggest the name that has binding error
1014 // i.e., the name that cannot be previously resolved
1015 NameBindingKind::Def(Def::Err, _) => return None,
1022 NameResolution { ref single_imports, .. }
1023 if single_imports.is_empty() => None,
1027 let lev_suggestion =
1028 match find_best_match_for_name(names, &ident.as_str(), None) {
1029 Some(name) => format!(". Did you mean to use `{}`?", name),
1030 None => String::new(),
1032 let msg = match module {
1033 ModuleOrUniformRoot::Module(module) => {
1034 let module_str = module_to_string(module);
1035 if let Some(module_str) = module_str {
1036 format!("no `{}` in `{}`{}", ident, module_str, lev_suggestion)
1038 format!("no `{}` in the root{}", ident, lev_suggestion)
1042 if !ident.is_path_segment_keyword() {
1043 format!("no `{}` external crate{}", ident, lev_suggestion)
1045 // HACK(eddyb) this shows up for `self` & `super`, which
1046 // should work instead - for now keep the same error message.
1047 format!("no `{}` in the root{}", ident, lev_suggestion)
1051 Some((directive.span, msg, None))
1053 // `resolve_ident_in_module` reported a privacy error.
1054 self.import_dummy_binding(directive);
1059 let mut reexport_error = None;
1060 let mut any_successful_reexport = false;
1061 self.per_ns(|this, ns| {
1062 if let Ok(binding) = source_bindings[ns].get() {
1063 let vis = directive.vis.get();
1064 if !binding.pseudo_vis().is_at_least(vis, &*this) {
1065 reexport_error = Some((ns, binding));
1067 any_successful_reexport = true;
1072 // All namespaces must be re-exported with extra visibility for an error to occur.
1073 if !any_successful_reexport {
1074 let (ns, binding) = reexport_error.unwrap();
1075 if ns == TypeNS && binding.is_extern_crate() {
1076 let msg = format!("extern crate `{}` is private, and cannot be \
1077 re-exported (error E0365), consider declaring with \
1080 self.session.buffer_lint(PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1084 } else if ns == TypeNS {
1085 struct_span_err!(self.session, directive.span, E0365,
1086 "`{}` is private, and cannot be re-exported", ident)
1087 .span_label(directive.span, format!("re-export of private `{}`", ident))
1088 .note(&format!("consider declaring type or module `{}` with `pub`", ident))
1091 let msg = format!("`{}` is private, and cannot be re-exported", ident);
1093 format!("consider marking `{}` as `pub` in the imported module", ident);
1094 struct_span_err!(self.session, directive.span, E0364, "{}", &msg)
1095 .span_note(directive.span, ¬e_msg)
1100 if directive.module_path.len() <= 1 {
1101 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1102 // 2 segments, so the `resolve_path` above won't trigger it.
1103 let mut full_path = directive.module_path.clone();
1104 full_path.push(Segment::from_ident(ident));
1105 self.per_ns(|this, ns| {
1106 if let Ok(binding) = source_bindings[ns].get() {
1107 this.lint_if_path_starts_with_module(
1108 directive.crate_lint(),
1117 // Record what this import resolves to for later uses in documentation,
1118 // this may resolve to either a value or a type, but for documentation
1119 // purposes it's good enough to just favor one over the other.
1120 self.per_ns(|this, ns| if let Some(binding) = source_bindings[ns].get().ok() {
1121 let mut def = binding.def();
1122 if let Def::Macro(def_id, _) = def {
1123 // `DefId`s from the "built-in macro crate" should not leak from resolve because
1124 // later stages are not ready to deal with them and produce lots of ICEs. Replace
1125 // them with `Def::Err` until some saner scheme is implemented for built-in macros.
1126 if def_id.krate == CrateNum::BuiltinMacros {
1127 this.session.span_err(directive.span, "cannot import a built-in macro");
1131 let import = this.import_map.entry(directive.id).or_default();
1132 import[ns] = Some(PathResolution::new(def));
1135 debug!("(resolving single import) successfully resolved import");
1139 fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) {
1140 let module = match directive.imported_module.get().unwrap() {
1141 ModuleOrUniformRoot::Module(module) => module,
1143 self.session.span_err(directive.span, "cannot glob-import all possible crates");
1148 self.populate_module_if_necessary(module);
1150 if let Some(Def::Trait(_)) = module.def() {
1151 self.session.span_err(directive.span, "items in traits are not importable.");
1153 } else if module.def_id() == directive.parent_scope.module.def_id() {
1155 } else if let GlobImport { is_prelude: true, .. } = directive.subclass {
1156 self.prelude = Some(module);
1160 // Add to module's glob_importers
1161 module.glob_importers.borrow_mut().push(directive);
1163 // Ensure that `resolutions` isn't borrowed during `try_define`,
1164 // since it might get updated via a glob cycle.
1165 let bindings = module.resolutions.borrow().iter().filter_map(|(&ident, resolution)| {
1166 resolution.borrow().binding().map(|binding| (ident, binding))
1167 }).collect::<Vec<_>>();
1168 for ((mut ident, ns), binding) in bindings {
1169 let scope = match ident.span.reverse_glob_adjust(module.expansion,
1170 directive.span.ctxt().modern()) {
1171 Some(Some(def)) => self.macro_def_scope(def),
1172 Some(None) => self.current_module,
1175 if self.is_accessible_from(binding.pseudo_vis(), scope) {
1176 let imported_binding = self.import(binding, directive);
1177 let _ = self.try_define(directive.parent_scope.module, ident, ns, imported_binding);
1181 // Record the destination of this import
1182 self.record_def(directive.id, PathResolution::new(module.def().unwrap()));
1185 // Miscellaneous post-processing, including recording re-exports,
1186 // reporting conflicts, and reporting unresolved imports.
1187 fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1188 // Since import resolution is finished, globs will not define any more names.
1189 *module.globs.borrow_mut() = Vec::new();
1191 let mut reexports = Vec::new();
1193 for (&(ident, ns), resolution) in module.resolutions.borrow().iter() {
1194 let resolution = &mut *resolution.borrow_mut();
1195 let binding = match resolution.binding {
1196 Some(binding) => binding,
1200 // Filter away "empty import canaries".
1201 let is_non_canary_import =
1202 binding.is_import() && binding.vis != ty::Visibility::Invisible;
1203 if is_non_canary_import || binding.is_macro_def() {
1204 let def = binding.def();
1205 if def != Def::Err {
1206 if let Some(def_id) = def.opt_def_id() {
1207 if !def_id.is_local() && def_id.krate != CrateNum::BuiltinMacros {
1208 self.cstore.export_macros_untracked(def_id.krate);
1211 reexports.push(Export {
1212 ident: ident.modern(),
1220 if let NameBindingKind::Import { binding: orig_binding, directive, .. } = binding.kind {
1221 if ns == TypeNS && orig_binding.is_variant() &&
1222 !orig_binding.vis.is_at_least(binding.vis, &*self) {
1223 let msg = match directive.subclass {
1224 ImportDirectiveSubclass::SingleImport { .. } => {
1225 format!("variant `{}` is private and cannot be re-exported",
1228 ImportDirectiveSubclass::GlobImport { .. } => {
1229 let msg = "enum is private and its variants \
1230 cannot be re-exported".to_owned();
1231 let error_id = (DiagnosticMessageId::ErrorId(0), // no code?!
1234 let fresh = self.session.one_time_diagnostics
1235 .borrow_mut().insert(error_id);
1241 ref s @ _ => bug!("unexpected import subclass {:?}", s)
1243 let mut err = self.session.struct_span_err(binding.span, &msg);
1245 let imported_module = match directive.imported_module.get() {
1246 Some(ModuleOrUniformRoot::Module(module)) => module,
1247 _ => bug!("module should exist"),
1249 let resolutions = imported_module.parent.expect("parent should exist")
1250 .resolutions.borrow();
1251 let enum_path_segment_index = directive.module_path.len() - 1;
1252 let enum_ident = directive.module_path[enum_path_segment_index].ident;
1254 let enum_resolution = resolutions.get(&(enum_ident, TypeNS))
1255 .expect("resolution should exist");
1256 let enum_span = enum_resolution.borrow()
1257 .binding.expect("binding should exist")
1259 let enum_def_span = self.session.source_map().def_span(enum_span);
1260 let enum_def_snippet = self.session.source_map()
1261 .span_to_snippet(enum_def_span).expect("snippet should exist");
1262 // potentially need to strip extant `crate`/`pub(path)` for suggestion
1263 let after_vis_index = enum_def_snippet.find("enum")
1264 .expect("`enum` keyword should exist in snippet");
1265 let suggestion = format!("pub {}",
1266 &enum_def_snippet[after_vis_index..]);
1269 .diag_span_suggestion_once(&mut err,
1270 DiagnosticMessageId::ErrorId(0),
1272 "consider making the enum public",
1279 if reexports.len() > 0 {
1280 if let Some(def_id) = module.def_id() {
1281 self.export_map.insert(def_id, reexports);
1287 fn import_path_to_string(names: &[Ident],
1288 subclass: &ImportDirectiveSubclass,
1289 span: Span) -> String {
1290 let pos = names.iter()
1291 .position(|p| span == p.span && p.name != keywords::PathRoot.name());
1292 let global = !names.is_empty() && names[0].name == keywords::PathRoot.name();
1293 if let Some(pos) = pos {
1294 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1295 names_to_string(names)
1297 let names = if global { &names[1..] } else { names };
1298 if names.is_empty() {
1299 import_directive_subclass_to_string(subclass)
1302 names_to_string(names),
1303 import_directive_subclass_to_string(subclass))
1308 fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass) -> String {
1310 SingleImport { source, .. } => source.to_string(),
1311 GlobImport { .. } => "*".to_string(),
1312 ExternCrate { .. } => "<extern crate>".to_string(),
1313 MacroUse => "#[macro_use]".to_string(),