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> Resolver<'a> {
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>, &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> {
596 pub resolver: &'a mut Resolver<'b>,
599 impl<'a, 'b: 'a> ::std::ops::Deref for ImportResolver<'a, 'b> {
600 type Target = Resolver<'b>;
601 fn deref(&self) -> &Resolver<'b> {
606 impl<'a, 'b: 'a> ::std::ops::DerefMut for ImportResolver<'a, 'b> {
607 fn deref_mut(&mut self) -> &mut Resolver<'b> {
612 impl<'a, 'b: 'a> ty::DefIdTree for &'a ImportResolver<'a, 'b> {
613 fn parent(self, id: DefId) -> Option<DefId> {
614 self.resolver.parent(id)
618 impl<'a, 'b:'a> ImportResolver<'a, 'b> {
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 prev_ambiguity_errors_len = self.ambiguity_errors.len();
847 let path_res = self.resolve_path(&directive.module_path, None, &directive.parent_scope,
848 true, directive.span, directive.crate_lint());
849 let no_ambiguity = self.ambiguity_errors.len() == prev_ambiguity_errors_len;
850 directive.vis.set(orig_vis);
851 let module = match path_res {
852 PathResult::Module(module) => {
853 // Consistency checks, analogous to `finalize_current_module_macro_resolutions`.
854 if let Some(initial_module) = directive.imported_module.get() {
855 if module != initial_module && no_ambiguity {
856 span_bug!(directive.span, "inconsistent resolution for an import");
859 if self.privacy_errors.is_empty() {
860 let msg = "cannot determine resolution for the import";
861 let msg_note = "import resolution is stuck, try simplifying other imports";
862 self.session.struct_span_err(directive.span, msg).note(msg_note).emit();
868 PathResult::Failed(span, msg, false) => {
870 assert!(directive.imported_module.get().is_none());
871 resolve_error(self, span, ResolutionError::FailedToResolve(&msg));
875 PathResult::Failed(span, msg, true) => {
877 assert!(directive.imported_module.get().is_none());
878 return Some(match self.make_path_suggestion(span, directive.module_path.clone(),
879 &directive.parent_scope) {
880 Some((suggestion, note)) => (
882 format!("did you mean `{}`?", Segment::names_to_string(&suggestion)),
885 None => (span, msg, None),
890 PathResult::NonModule(path_res) if path_res.base_def() == Def::Err => {
892 assert!(directive.imported_module.get().is_none());
894 // The error was already reported earlier.
897 PathResult::Indeterminate | PathResult::NonModule(..) => unreachable!(),
900 let (ident, target, source_bindings, target_bindings, type_ns_only) =
901 match directive.subclass {
902 SingleImport { source, target, ref source_bindings,
903 ref target_bindings, type_ns_only } =>
904 (source, target, source_bindings, target_bindings, type_ns_only),
905 GlobImport { is_prelude, ref max_vis } => {
906 if directive.module_path.len() <= 1 {
907 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
908 // 2 segments, so the `resolve_path` above won't trigger it.
909 let mut full_path = directive.module_path.clone();
910 full_path.push(Segment::from_ident(keywords::Invalid.ident()));
911 self.lint_if_path_starts_with_module(
912 directive.crate_lint(),
919 if let ModuleOrUniformRoot::Module(module) = module {
920 if module.def_id() == directive.parent_scope.module.def_id() {
921 // Importing a module into itself is not allowed.
924 "Cannot glob-import a module into itself.".to_string(),
930 max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
931 !max_vis.get().is_at_least(directive.vis.get(), &*self) {
932 let msg = "A non-empty glob must import something with the glob's visibility";
933 self.session.span_err(directive.span, msg);
940 let mut all_ns_err = true;
941 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
942 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
943 let orig_blacklisted_binding =
944 mem::replace(&mut this.blacklisted_binding, target_bindings[ns].get());
945 let orig_last_import_segment = mem::replace(&mut this.last_import_segment, true);
946 let binding = this.resolve_ident_in_module(
947 module, ident, ns, Some(&directive.parent_scope), true, directive.span
949 this.last_import_segment = orig_last_import_segment;
950 this.blacklisted_binding = orig_blacklisted_binding;
951 directive.vis.set(orig_vis);
955 // Consistency checks, analogous to `finalize_current_module_macro_resolutions`.
956 let initial_def = source_bindings[ns].get().map(|initial_binding| {
958 if let Some(target_binding) = target_bindings[ns].get() {
959 if target.name == "_" &&
960 initial_binding.is_extern_crate() && !initial_binding.is_import() {
961 this.record_use(ident, ns, target_binding,
962 directive.module_path.is_empty());
965 initial_binding.def_ignoring_ambiguity()
967 let def = binding.def_ignoring_ambiguity();
968 if let Ok(initial_def) = initial_def {
969 if def != initial_def && this.ambiguity_errors.is_empty() {
970 span_bug!(directive.span, "inconsistent resolution for an import");
973 if def != Def::Err &&
974 this.ambiguity_errors.is_empty() && this.privacy_errors.is_empty() {
975 let msg = "cannot determine resolution for the import";
977 "import resolution is stuck, try simplifying other imports";
978 this.session.struct_span_err(directive.span, msg).note(msg_note).emit();
983 // FIXME: This assert may fire if public glob is later shadowed by a private
984 // single import (see test `issue-55884-2.rs`). In theory single imports should
985 // always block globs, even if they are not yet resolved, so that this kind of
986 // self-inconsistent resolution never happens.
987 // Reenable the assert when the issue is fixed.
988 // assert!(result[ns].get().is_err());
994 let mut all_ns_failed = true;
995 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
996 let binding = this.resolve_ident_in_module(
997 module, ident, ns, Some(&directive.parent_scope), true, directive.span
1000 all_ns_failed = false;
1004 return if all_ns_failed {
1005 let resolutions = match module {
1006 ModuleOrUniformRoot::Module(module) => Some(module.resolutions.borrow()),
1009 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
1010 let names = resolutions.filter_map(|(&(ref i, _), resolution)| {
1011 if *i == ident { return None; } // Never suggest the same name
1012 match *resolution.borrow() {
1013 NameResolution { binding: Some(name_binding), .. } => {
1014 match name_binding.kind {
1015 NameBindingKind::Import { binding, .. } => {
1016 match binding.kind {
1017 // Never suggest the name that has binding error
1018 // i.e., the name that cannot be previously resolved
1019 NameBindingKind::Def(Def::Err, _) => return None,
1026 NameResolution { ref single_imports, .. }
1027 if single_imports.is_empty() => None,
1031 let lev_suggestion =
1032 match find_best_match_for_name(names, &ident.as_str(), None) {
1033 Some(name) => format!(". Did you mean to use `{}`?", name),
1034 None => String::new(),
1036 let msg = match module {
1037 ModuleOrUniformRoot::Module(module) => {
1038 let module_str = module_to_string(module);
1039 if let Some(module_str) = module_str {
1040 format!("no `{}` in `{}`{}", ident, module_str, lev_suggestion)
1042 format!("no `{}` in the root{}", ident, lev_suggestion)
1046 if !ident.is_path_segment_keyword() {
1047 format!("no `{}` external crate{}", ident, lev_suggestion)
1049 // HACK(eddyb) this shows up for `self` & `super`, which
1050 // should work instead - for now keep the same error message.
1051 format!("no `{}` in the root{}", ident, lev_suggestion)
1055 Some((directive.span, msg, None))
1057 // `resolve_ident_in_module` reported a privacy error.
1058 self.import_dummy_binding(directive);
1063 let mut reexport_error = None;
1064 let mut any_successful_reexport = false;
1065 self.per_ns(|this, ns| {
1066 if let Ok(binding) = source_bindings[ns].get() {
1067 let vis = directive.vis.get();
1068 if !binding.pseudo_vis().is_at_least(vis, &*this) {
1069 reexport_error = Some((ns, binding));
1071 any_successful_reexport = true;
1076 // All namespaces must be re-exported with extra visibility for an error to occur.
1077 if !any_successful_reexport {
1078 let (ns, binding) = reexport_error.unwrap();
1079 if ns == TypeNS && binding.is_extern_crate() {
1080 let msg = format!("extern crate `{}` is private, and cannot be \
1081 re-exported (error E0365), consider declaring with \
1084 self.session.buffer_lint(PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1088 } else if ns == TypeNS {
1089 struct_span_err!(self.session, directive.span, E0365,
1090 "`{}` is private, and cannot be re-exported", ident)
1091 .span_label(directive.span, format!("re-export of private `{}`", ident))
1092 .note(&format!("consider declaring type or module `{}` with `pub`", ident))
1095 let msg = format!("`{}` is private, and cannot be re-exported", ident);
1097 format!("consider marking `{}` as `pub` in the imported module", ident);
1098 struct_span_err!(self.session, directive.span, E0364, "{}", &msg)
1099 .span_note(directive.span, ¬e_msg)
1104 if directive.module_path.len() <= 1 {
1105 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1106 // 2 segments, so the `resolve_path` above won't trigger it.
1107 let mut full_path = directive.module_path.clone();
1108 full_path.push(Segment::from_ident(ident));
1109 self.per_ns(|this, ns| {
1110 if let Ok(binding) = source_bindings[ns].get() {
1111 this.lint_if_path_starts_with_module(
1112 directive.crate_lint(),
1121 // Record what this import resolves to for later uses in documentation,
1122 // this may resolve to either a value or a type, but for documentation
1123 // purposes it's good enough to just favor one over the other.
1124 self.per_ns(|this, ns| if let Some(binding) = source_bindings[ns].get().ok() {
1125 let mut def = binding.def();
1126 if let Def::Macro(def_id, _) = def {
1127 // `DefId`s from the "built-in macro crate" should not leak from resolve because
1128 // later stages are not ready to deal with them and produce lots of ICEs. Replace
1129 // them with `Def::Err` until some saner scheme is implemented for built-in macros.
1130 if def_id.krate == CrateNum::BuiltinMacros {
1131 this.session.span_err(directive.span, "cannot import a built-in macro");
1135 let import = this.import_map.entry(directive.id).or_default();
1136 import[ns] = Some(PathResolution::new(def));
1139 debug!("(resolving single import) successfully resolved import");
1143 fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) {
1144 let module = match directive.imported_module.get().unwrap() {
1145 ModuleOrUniformRoot::Module(module) => module,
1147 self.session.span_err(directive.span, "cannot glob-import all possible crates");
1152 self.populate_module_if_necessary(module);
1154 if let Some(Def::Trait(_)) = module.def() {
1155 self.session.span_err(directive.span, "items in traits are not importable.");
1157 } else if module.def_id() == directive.parent_scope.module.def_id() {
1159 } else if let GlobImport { is_prelude: true, .. } = directive.subclass {
1160 self.prelude = Some(module);
1164 // Add to module's glob_importers
1165 module.glob_importers.borrow_mut().push(directive);
1167 // Ensure that `resolutions` isn't borrowed during `try_define`,
1168 // since it might get updated via a glob cycle.
1169 let bindings = module.resolutions.borrow().iter().filter_map(|(&ident, resolution)| {
1170 resolution.borrow().binding().map(|binding| (ident, binding))
1171 }).collect::<Vec<_>>();
1172 for ((mut ident, ns), binding) in bindings {
1173 let scope = match ident.span.reverse_glob_adjust(module.expansion,
1174 directive.span.ctxt().modern()) {
1175 Some(Some(def)) => self.macro_def_scope(def),
1176 Some(None) => self.current_module,
1179 if self.is_accessible_from(binding.pseudo_vis(), scope) {
1180 let imported_binding = self.import(binding, directive);
1181 let _ = self.try_define(directive.parent_scope.module, ident, ns, imported_binding);
1185 // Record the destination of this import
1186 self.record_def(directive.id, PathResolution::new(module.def().unwrap()));
1189 // Miscellaneous post-processing, including recording re-exports,
1190 // reporting conflicts, and reporting unresolved imports.
1191 fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1192 // Since import resolution is finished, globs will not define any more names.
1193 *module.globs.borrow_mut() = Vec::new();
1195 let mut reexports = Vec::new();
1197 for (&(ident, ns), resolution) in module.resolutions.borrow().iter() {
1198 let resolution = &mut *resolution.borrow_mut();
1199 let binding = match resolution.binding {
1200 Some(binding) => binding,
1204 // Filter away "empty import canaries".
1205 let is_non_canary_import =
1206 binding.is_import() && binding.vis != ty::Visibility::Invisible;
1207 if is_non_canary_import || binding.is_macro_def() {
1208 let def = binding.def();
1209 if def != Def::Err {
1210 if let Some(def_id) = def.opt_def_id() {
1211 if !def_id.is_local() && def_id.krate != CrateNum::BuiltinMacros {
1212 self.cstore.export_macros_untracked(def_id.krate);
1215 reexports.push(Export {
1216 ident: ident.modern(),
1224 if let NameBindingKind::Import { binding: orig_binding, directive, .. } = binding.kind {
1225 if ns == TypeNS && orig_binding.is_variant() &&
1226 !orig_binding.vis.is_at_least(binding.vis, &*self) {
1227 let msg = match directive.subclass {
1228 ImportDirectiveSubclass::SingleImport { .. } => {
1229 format!("variant `{}` is private and cannot be re-exported",
1232 ImportDirectiveSubclass::GlobImport { .. } => {
1233 let msg = "enum is private and its variants \
1234 cannot be re-exported".to_owned();
1235 let error_id = (DiagnosticMessageId::ErrorId(0), // no code?!
1238 let fresh = self.session.one_time_diagnostics
1239 .borrow_mut().insert(error_id);
1245 ref s @ _ => bug!("unexpected import subclass {:?}", s)
1247 let mut err = self.session.struct_span_err(binding.span, &msg);
1249 let imported_module = match directive.imported_module.get() {
1250 Some(ModuleOrUniformRoot::Module(module)) => module,
1251 _ => bug!("module should exist"),
1253 let resolutions = imported_module.parent.expect("parent should exist")
1254 .resolutions.borrow();
1255 let enum_path_segment_index = directive.module_path.len() - 1;
1256 let enum_ident = directive.module_path[enum_path_segment_index].ident;
1258 let enum_resolution = resolutions.get(&(enum_ident, TypeNS))
1259 .expect("resolution should exist");
1260 let enum_span = enum_resolution.borrow()
1261 .binding.expect("binding should exist")
1263 let enum_def_span = self.session.source_map().def_span(enum_span);
1264 let enum_def_snippet = self.session.source_map()
1265 .span_to_snippet(enum_def_span).expect("snippet should exist");
1266 // potentially need to strip extant `crate`/`pub(path)` for suggestion
1267 let after_vis_index = enum_def_snippet.find("enum")
1268 .expect("`enum` keyword should exist in snippet");
1269 let suggestion = format!("pub {}",
1270 &enum_def_snippet[after_vis_index..]);
1273 .diag_span_suggestion_once(&mut err,
1274 DiagnosticMessageId::ErrorId(0),
1276 "consider making the enum public",
1283 if reexports.len() > 0 {
1284 if let Some(def_id) = module.def_id() {
1285 self.export_map.insert(def_id, reexports);
1291 fn import_path_to_string(names: &[Ident],
1292 subclass: &ImportDirectiveSubclass,
1293 span: Span) -> String {
1294 let pos = names.iter()
1295 .position(|p| span == p.span && p.name != keywords::PathRoot.name());
1296 let global = !names.is_empty() && names[0].name == keywords::PathRoot.name();
1297 if let Some(pos) = pos {
1298 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1299 names_to_string(names)
1301 let names = if global { &names[1..] } else { names };
1302 if names.is_empty() {
1303 import_directive_subclass_to_string(subclass)
1306 names_to_string(names),
1307 import_directive_subclass_to_string(subclass))
1312 fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass) -> String {
1314 SingleImport { source, .. } => source.to_string(),
1315 GlobImport { .. } => "*".to_string(),
1316 ExternCrate { .. } => "<extern crate>".to_string(),
1317 MacroUse => "#[macro_use]".to_string(),