1 use ImportDirectiveSubclass::*;
3 use crate::{AmbiguityError, AmbiguityKind, AmbiguityErrorMisc};
4 use crate::{CrateLint, Module, ModuleOrUniformRoot, PerNS, ScopeSet, Weak};
5 use crate::Namespace::{self, TypeNS, MacroNS};
6 use crate::{NameBinding, NameBindingKind, ToNameBinding, PathResult, PrivacyError};
7 use crate::{Resolver, Segment};
8 use crate::{names_to_string, module_to_string};
9 use crate::{resolve_error, ResolutionError, Suggestion};
10 use crate::macros::ParentScope;
12 use errors::Applicability;
14 use rustc_data_structures::ptr_key::PtrKey;
16 use rustc::lint::builtin::BuiltinLintDiagnostics;
17 use rustc::lint::builtin::{DUPLICATE_MACRO_EXPORTS, PUB_USE_OF_PRIVATE_EXTERN_CRATE};
18 use rustc::hir::def_id::{CrateNum, DefId};
19 use rustc::hir::def::*;
20 use rustc::session::DiagnosticMessageId;
21 use rustc::util::nodemap::FxHashSet;
22 use rustc::{bug, span_bug};
24 use syntax::ast::{self, Ident, Name, NodeId, CRATE_NODE_ID};
25 use syntax::ext::base::Determinacy::{self, Determined, Undetermined};
26 use syntax::ext::hygiene::Mark;
27 use syntax::symbol::keywords;
28 use syntax::util::lev_distance::find_best_match_for_name;
29 use syntax::{struct_span_err, unwrap_or};
30 use syntax_pos::{MultiSpan, Span};
34 use std::cell::{Cell, RefCell};
37 /// Contains data for specific types of import directives.
38 #[derive(Clone, Debug)]
39 pub enum ImportDirectiveSubclass<'a> {
41 /// `source` in `use prefix::source as target`.
43 /// `target` in `use prefix::source as target`.
45 /// Bindings to which `source` refers to.
46 source_bindings: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
47 /// Bindings introduced by `target`.
48 target_bindings: PerNS<Cell<Option<&'a NameBinding<'a>>>>,
49 /// `true` for `...::{self [as target]}` imports, `false` otherwise.
51 /// Did this import result from a nested import? ie. `use foo::{bar, baz};`
56 max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
57 // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
66 /// One import directive.
67 #[derive(Debug,Clone)]
68 crate struct ImportDirective<'a> {
69 /// The ID of the `extern crate`, `UseTree` etc that imported this `ImportDirective`.
71 /// In the case where the `ImportDirective` was expanded from a "nested" use tree,
72 /// this id is the ID of the leaf tree. For example:
74 /// ```ignore (pacify the mercilous tidy)
75 /// use foo::bar::{a, b}
78 /// If this is the import directive for `foo::bar::a`, we would have the ID of the `UseTree`
79 /// for `a` in this field.
82 /// The `id` of the "root" use-kind -- this is always the same as
83 /// `id` except in the case of "nested" use trees, in which case
84 /// it will be the `id` of the root use tree. e.g., in the example
85 /// from `id`, this would be the ID of the `use foo::bar`
89 /// Span of the entire use statement.
92 /// Span of the entire use statement with attributes.
93 pub use_span_with_attributes: Span,
95 /// Did the use statement have any attributes?
96 pub has_attributes: bool,
98 /// Span of this use tree.
101 /// Span of the *root* use tree (see `root_id`).
104 pub parent_scope: ParentScope<'a>,
105 pub module_path: Vec<Segment>,
106 /// The resolution of `module_path`.
107 pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>,
108 pub subclass: ImportDirectiveSubclass<'a>,
109 pub vis: Cell<ty::Visibility>,
110 pub used: Cell<bool>,
113 impl<'a> ImportDirective<'a> {
114 pub fn is_glob(&self) -> bool {
115 match self.subclass { ImportDirectiveSubclass::GlobImport { .. } => true, _ => false }
118 pub fn is_nested(&self) -> bool {
119 match self.subclass {
120 ImportDirectiveSubclass::SingleImport { nested, .. } => nested,
125 crate fn crate_lint(&self) -> CrateLint {
126 CrateLint::UsePath { root_id: self.root_id, root_span: self.root_span }
130 #[derive(Clone, Default, Debug)]
131 /// Records information about the resolution of a name in a namespace of a module.
132 pub struct NameResolution<'a> {
133 /// Single imports that may define the name in the namespace.
134 /// Import directives are arena-allocated, so it's ok to use pointers as keys.
135 single_imports: FxHashSet<PtrKey<'a, ImportDirective<'a>>>,
136 /// The least shadowable known binding for this name, or None if there are no known bindings.
137 pub binding: Option<&'a NameBinding<'a>>,
138 shadowed_glob: Option<&'a NameBinding<'a>>,
141 impl<'a> NameResolution<'a> {
142 // Returns the binding for the name if it is known or None if it not known.
143 fn binding(&self) -> Option<&'a NameBinding<'a>> {
144 self.binding.and_then(|binding| {
145 if !binding.is_glob_import() ||
146 self.single_imports.is_empty() { Some(binding) } else { None }
151 impl<'a> Resolver<'a> {
152 fn resolution(&self, module: Module<'a>, ident: Ident, ns: Namespace)
153 -> &'a RefCell<NameResolution<'a>> {
154 *module.resolutions.borrow_mut().entry((ident.modern(), ns))
155 .or_insert_with(|| self.arenas.alloc_name_resolution())
158 crate fn resolve_ident_in_module_unadjusted(
160 module: ModuleOrUniformRoot<'a>,
165 ) -> Result<&'a NameBinding<'a>, Determinacy> {
166 self.resolve_ident_in_module_unadjusted_ext(
167 module, ident, ns, None, false, record_used, path_span
168 ).map_err(|(determinacy, _)| determinacy)
171 /// Attempts to resolve `ident` in namespaces `ns` of `module`.
172 /// Invariant: if `record_used` is `Some`, expansion and import resolution must be complete.
173 crate fn resolve_ident_in_module_unadjusted_ext(
175 module: ModuleOrUniformRoot<'a>,
178 parent_scope: Option<&ParentScope<'a>>,
179 restricted_shadowing: bool,
182 ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
183 let module = match module {
184 ModuleOrUniformRoot::Module(module) => module,
185 ModuleOrUniformRoot::CrateRootAndExternPrelude => {
186 assert!(!restricted_shadowing);
187 let parent_scope = self.dummy_parent_scope();
188 let binding = self.early_resolve_ident_in_lexical_scope(
189 ident, ScopeSet::AbsolutePath(ns), &parent_scope,
190 record_used, record_used, path_span,
192 return binding.map_err(|determinacy| (determinacy, Weak::No));
194 ModuleOrUniformRoot::ExternPrelude => {
195 assert!(!restricted_shadowing);
196 return if ns != TypeNS {
197 Err((Determined, Weak::No))
198 } else if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
200 } else if !self.graph_root.unresolved_invocations.borrow().is_empty() {
201 // Macro-expanded `extern crate` items can add names to extern prelude.
202 Err((Undetermined, Weak::No))
204 Err((Determined, Weak::No))
207 ModuleOrUniformRoot::CurrentScope => {
208 assert!(!restricted_shadowing);
210 parent_scope.expect("no parent scope for a single-segment import");
213 if ident.name == keywords::Crate.name() ||
214 ident.name == keywords::DollarCrate.name() {
215 let module = self.resolve_crate_root(ident);
216 let binding = (module, ty::Visibility::Public,
217 module.span, Mark::root())
218 .to_name_binding(self.arenas);
220 } else if ident.name == keywords::Super.name() ||
221 ident.name == keywords::SelfLower.name() {
222 // FIXME: Implement these with renaming requirements so that e.g.
223 // `use super;` doesn't work, but `use super as name;` does.
224 // Fall through here to get an error from `early_resolve_...`.
228 let binding = self.early_resolve_ident_in_lexical_scope(
229 ident, ScopeSet::Import(ns), parent_scope, record_used, record_used, path_span
231 return binding.map_err(|determinacy| (determinacy, Weak::No));
235 self.populate_module_if_necessary(module);
237 let resolution = self.resolution(module, ident, ns)
239 .map_err(|_| (Determined, Weak::No))?; // This happens when there is a cycle of imports.
241 if let Some(binding) = resolution.binding {
242 if !restricted_shadowing && binding.expansion != Mark::root() {
243 if let NameBindingKind::Def(_, true) = binding.kind {
244 self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
249 let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
250 if let Some(blacklisted_binding) = this.blacklisted_binding {
251 if ptr::eq(binding, blacklisted_binding) {
252 return Err((Determined, Weak::No));
255 // `extern crate` are always usable for backwards compatibility, see issue #37020,
256 // remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`.
257 let usable = this.is_accessible(binding.vis) || binding.is_extern_crate();
258 if usable { Ok(binding) } else { Err((Determined, Weak::No)) }
262 return resolution.binding.and_then(|binding| {
263 // If the primary binding is blacklisted, search further and return the shadowed
264 // glob binding if it exists. What we really want here is having two separate
265 // scopes in a module - one for non-globs and one for globs, but until that's done
266 // use this hack to avoid inconsistent resolution ICEs during import validation.
267 if let Some(blacklisted_binding) = self.blacklisted_binding {
268 if ptr::eq(binding, blacklisted_binding) {
269 return resolution.shadowed_glob;
273 }).ok_or((Determined, Weak::No)).and_then(|binding| {
274 if self.last_import_segment && check_usable(self, binding).is_err() {
275 Err((Determined, Weak::No))
277 self.record_use(ident, ns, binding, restricted_shadowing);
279 if let Some(shadowed_glob) = resolution.shadowed_glob {
280 // Forbid expanded shadowing to avoid time travel.
281 if restricted_shadowing &&
282 binding.expansion != Mark::root() &&
283 binding.def() != shadowed_glob.def() {
284 self.ambiguity_errors.push(AmbiguityError {
285 kind: AmbiguityKind::GlobVsExpanded,
289 misc1: AmbiguityErrorMisc::None,
290 misc2: AmbiguityErrorMisc::None,
295 if !self.is_accessible(binding.vis) &&
296 // Remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
297 !(self.last_import_segment && binding.is_extern_crate()) {
298 self.privacy_errors.push(PrivacyError(path_span, ident, binding));
306 // Items and single imports are not shadowable, if we have one, then it's determined.
307 if let Some(binding) = resolution.binding {
308 if !binding.is_glob_import() {
309 return check_usable(self, binding);
313 // --- From now on we either have a glob resolution or no resolution. ---
315 // Check if one of single imports can still define the name,
316 // if it can then our result is not determined and can be invalidated.
317 for single_import in &resolution.single_imports {
318 if !self.is_accessible(single_import.vis.get()) {
321 let module = unwrap_or!(single_import.imported_module.get(),
322 return Err((Undetermined, Weak::No)));
323 let ident = match single_import.subclass {
324 SingleImport { source, .. } => source,
327 match self.resolve_ident_in_module(module, ident, ns, Some(&single_import.parent_scope),
329 Err(Determined) => continue,
330 Ok(binding) if !self.is_accessible_from(
331 binding.vis, single_import.parent_scope.module
333 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::No)),
337 // So we have a resolution that's from a glob import. This resolution is determined
338 // if it cannot be shadowed by some new item/import expanded from a macro.
339 // This happens either if there are no unexpanded macros, or expanded names cannot
340 // shadow globs (that happens in macro namespace or with restricted shadowing).
342 // Additionally, any macro in any module can plant names in the root module if it creates
343 // `macro_export` macros, so the root module effectively has unresolved invocations if any
344 // module has unresolved invocations.
345 // However, it causes resolution/expansion to stuck too often (#53144), so, to make
346 // progress, we have to ignore those potential unresolved invocations from other modules
347 // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
348 // shadowing is enabled, see `macro_expanded_macro_export_errors`).
349 let unexpanded_macros = !module.unresolved_invocations.borrow().is_empty();
350 if let Some(binding) = resolution.binding {
351 if !unexpanded_macros || ns == MacroNS || restricted_shadowing {
352 return check_usable(self, binding);
354 return Err((Undetermined, Weak::No));
358 // --- From now on we have no resolution. ---
360 // Now we are in situation when new item/import can appear only from a glob or a macro
361 // expansion. With restricted shadowing names from globs and macro expansions cannot
362 // shadow names from outer scopes, so we can freely fallback from module search to search
363 // in outer scopes. For `early_resolve_ident_in_lexical_scope` to continue search in outer
364 // scopes we return `Undetermined` with `Weak::Yes`.
366 // Check if one of unexpanded macros can still define the name,
367 // if it can then our "no resolution" result is not determined and can be invalidated.
368 if unexpanded_macros {
369 return Err((Undetermined, Weak::Yes));
372 // Check if one of glob imports can still define the name,
373 // if it can then our "no resolution" result is not determined and can be invalidated.
374 for glob_import in module.globs.borrow().iter() {
375 if !self.is_accessible(glob_import.vis.get()) {
378 let module = match glob_import.imported_module.get() {
379 Some(ModuleOrUniformRoot::Module(module)) => module,
381 None => return Err((Undetermined, Weak::Yes)),
383 let (orig_current_module, mut ident) = (self.current_module, ident.modern());
384 match ident.span.glob_adjust(module.expansion, glob_import.span.ctxt().modern()) {
385 Some(Some(def)) => self.current_module = self.macro_def_scope(def),
389 let result = self.resolve_ident_in_module_unadjusted(
390 ModuleOrUniformRoot::Module(module),
396 self.current_module = orig_current_module;
399 Err(Determined) => continue,
400 Ok(binding) if !self.is_accessible_from(
401 binding.vis, glob_import.parent_scope.module
403 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::Yes)),
407 // No resolution and no one else can define the name - determinate error.
408 Err((Determined, Weak::No))
411 // Add an import directive to the current module.
412 pub fn add_import_directive(&mut self,
413 module_path: Vec<Segment>,
414 subclass: ImportDirectiveSubclass<'a>,
421 parent_scope: ParentScope<'a>) {
422 let current_module = parent_scope.module;
423 let directive = self.arenas.alloc_import_directive(ImportDirective {
426 imported_module: Cell::new(None),
431 use_span_with_attributes: item.span_with_attributes(),
432 has_attributes: !item.attrs.is_empty(),
436 used: Cell::new(false),
439 debug!("add_import_directive({:?})", directive);
441 self.indeterminate_imports.push(directive);
442 match directive.subclass {
443 SingleImport { target, type_ns_only, .. } => {
444 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
445 let mut resolution = this.resolution(current_module, target, ns).borrow_mut();
446 resolution.single_imports.insert(PtrKey(directive));
449 // We don't add prelude imports to the globs since they only affect lexical scopes,
450 // which are not relevant to import resolution.
451 GlobImport { is_prelude: true, .. } => {}
452 GlobImport { .. } => current_module.globs.borrow_mut().push(directive),
457 // Given a binding and an import directive that resolves to it,
458 // return the corresponding binding defined by the import directive.
459 crate fn import(&self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>)
460 -> &'a NameBinding<'a> {
461 let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) ||
462 // cf. `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
463 !directive.is_glob() && binding.is_extern_crate() {
469 if let GlobImport { ref max_vis, .. } = directive.subclass {
470 if vis == directive.vis.get() || vis.is_at_least(max_vis.get(), self) {
475 self.arenas.alloc_name_binding(NameBinding {
476 kind: NameBindingKind::Import {
479 used: Cell::new(false),
482 span: directive.span,
484 expansion: directive.parent_scope.expansion,
488 crate fn check_reserved_macro_name(&self, ident: Ident, ns: Namespace) {
489 // Reserve some names that are not quite covered by the general check
490 // performed on `Resolver::builtin_attrs`.
492 (ident.name == "cfg" || ident.name == "cfg_attr" || ident.name == "derive") {
493 self.session.span_err(ident.span,
494 &format!("name `{}` is reserved in macro namespace", ident));
498 // Define the name or return the existing binding if there is a collision.
499 pub fn try_define(&mut self,
503 binding: &'a NameBinding<'a>)
504 -> Result<(), &'a NameBinding<'a>> {
505 self.check_reserved_macro_name(ident, ns);
506 self.set_binding_parent_module(binding, module);
507 self.update_resolution(module, ident, ns, |this, resolution| {
508 if let Some(old_binding) = resolution.binding {
509 if binding.def() == Def::Err {
510 // Do not override real bindings with `Def::Err`s from error recovery.
513 match (old_binding.is_glob_import(), binding.is_glob_import()) {
515 if binding.def() != old_binding.def() {
516 resolution.binding = Some(this.ambiguity(AmbiguityKind::GlobVsGlob,
517 old_binding, binding));
518 } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
519 // We are glob-importing the same item but with greater visibility.
520 resolution.binding = Some(binding);
523 (old_glob @ true, false) | (old_glob @ false, true) => {
524 let (glob_binding, nonglob_binding) = if old_glob {
525 (old_binding, binding)
527 (binding, old_binding)
529 if glob_binding.def() != nonglob_binding.def() &&
530 ns == MacroNS && nonglob_binding.expansion != Mark::root() {
531 resolution.binding = Some(this.ambiguity(AmbiguityKind::GlobVsExpanded,
532 nonglob_binding, glob_binding));
534 resolution.binding = Some(nonglob_binding);
536 resolution.shadowed_glob = Some(glob_binding);
539 if let (&NameBindingKind::Def(_, true), &NameBindingKind::Def(_, true)) =
540 (&old_binding.kind, &binding.kind) {
542 this.session.buffer_lint_with_diagnostic(
543 DUPLICATE_MACRO_EXPORTS,
546 &format!("a macro named `{}` has already been exported", ident),
547 BuiltinLintDiagnostics::DuplicatedMacroExports(
548 ident, old_binding.span, binding.span));
550 resolution.binding = Some(binding);
552 return Err(old_binding);
557 resolution.binding = Some(binding);
564 fn ambiguity(&self, kind: AmbiguityKind,
565 primary_binding: &'a NameBinding<'a>, secondary_binding: &'a NameBinding<'a>)
566 -> &'a NameBinding<'a> {
567 self.arenas.alloc_name_binding(NameBinding {
568 ambiguity: Some((secondary_binding, kind)),
569 ..primary_binding.clone()
573 // Use `f` to mutate the resolution of the name in the module.
574 // If the resolution becomes a success, define it in the module's glob importers.
575 fn update_resolution<T, F>(&mut self, module: Module<'a>, ident: Ident, ns: Namespace, f: F)
577 where F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T
579 // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
580 // during which the resolution might end up getting re-defined via a glob cycle.
582 let resolution = &mut *self.resolution(module, ident, ns).borrow_mut();
583 let old_binding = resolution.binding();
585 let t = f(self, resolution);
587 match resolution.binding() {
588 _ if old_binding.is_some() => return t,
590 Some(binding) => match old_binding {
591 Some(old_binding) if ptr::eq(old_binding, binding) => return t,
597 // Define `binding` in `module`s glob importers.
598 for directive in module.glob_importers.borrow_mut().iter() {
599 let mut ident = ident.modern();
600 let scope = match ident.span.reverse_glob_adjust(module.expansion,
601 directive.span.ctxt().modern()) {
602 Some(Some(def)) => self.macro_def_scope(def),
603 Some(None) => directive.parent_scope.module,
606 if self.is_accessible_from(binding.vis, scope) {
607 let imported_binding = self.import(binding, directive);
608 let _ = self.try_define(directive.parent_scope.module, ident, ns, imported_binding);
615 // Define a "dummy" resolution containing a Def::Err as a placeholder for a
617 fn import_dummy_binding(&mut self, directive: &'a ImportDirective<'a>) {
618 if let SingleImport { target, .. } = directive.subclass {
619 let dummy_binding = self.dummy_binding;
620 let dummy_binding = self.import(dummy_binding, directive);
621 self.per_ns(|this, ns| {
622 let _ = this.try_define(directive.parent_scope.module, target, ns, dummy_binding);
628 /// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
629 /// import errors within the same use tree into a single diagnostic.
630 #[derive(Debug, Clone)]
631 struct UnresolvedImportError {
633 label: Option<String>,
634 note: Option<String>,
635 suggestion: Option<Suggestion>,
638 pub struct ImportResolver<'a, 'b: 'a> {
639 pub resolver: &'a mut Resolver<'b>,
642 impl<'a, 'b: 'a> std::ops::Deref for ImportResolver<'a, 'b> {
643 type Target = Resolver<'b>;
644 fn deref(&self) -> &Resolver<'b> {
649 impl<'a, 'b: 'a> std::ops::DerefMut for ImportResolver<'a, 'b> {
650 fn deref_mut(&mut self) -> &mut Resolver<'b> {
655 impl<'a, 'b: 'a> ty::DefIdTree for &'a ImportResolver<'a, 'b> {
656 fn parent(self, id: DefId) -> Option<DefId> {
657 self.resolver.parent(id)
661 impl<'a, 'b:'a> ImportResolver<'a, 'b> {
664 // This is a fixed-point algorithm. We resolve imports until our efforts
665 // are stymied by an unresolved import; then we bail out of the current
666 // module and continue. We terminate successfully once no more imports
667 // remain or unsuccessfully when no forward progress in resolving imports
670 /// Resolves all imports for the crate. This method performs the fixed-
672 pub fn resolve_imports(&mut self) {
673 let mut prev_num_indeterminates = self.indeterminate_imports.len() + 1;
674 while self.indeterminate_imports.len() < prev_num_indeterminates {
675 prev_num_indeterminates = self.indeterminate_imports.len();
676 for import in mem::replace(&mut self.indeterminate_imports, Vec::new()) {
677 match self.resolve_import(&import) {
678 true => self.determined_imports.push(import),
679 false => self.indeterminate_imports.push(import),
685 pub fn finalize_imports(&mut self) {
686 for module in self.arenas.local_modules().iter() {
687 self.finalize_resolutions_in(module);
690 let mut has_errors = false;
691 let mut seen_spans = FxHashSet::default();
692 let mut errors = vec![];
693 let mut prev_root_id: NodeId = NodeId::from_u32(0);
694 for i in 0 .. self.determined_imports.len() {
695 let import = self.determined_imports[i];
696 if let Some(err) = self.finalize_import(import) {
699 if let SingleImport { source, ref source_bindings, .. } = import.subclass {
700 if source.name == "self" {
701 // Silence `unresolved import` error if E0429 is already emitted
702 if let Err(Determined) = source_bindings.value_ns.get() {
708 // If the error is a single failed import then create a "fake" import
709 // resolution for it so that later resolve stages won't complain.
710 self.import_dummy_binding(import);
711 if prev_root_id.as_u32() != 0
712 && prev_root_id.as_u32() != import.root_id.as_u32()
713 && !errors.is_empty() {
714 // In the case of a new import line, throw a diagnostic message
715 // for the previous line.
716 self.throw_unresolved_import_error(errors, None);
719 if !seen_spans.contains(&err.span) {
720 let path = import_path_to_string(
721 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
725 seen_spans.insert(err.span);
726 errors.push((path, err));
727 prev_root_id = import.root_id;
732 if !errors.is_empty() {
733 self.throw_unresolved_import_error(errors.clone(), None);
736 // Report unresolved imports only if no hard error was already reported
737 // to avoid generating multiple errors on the same import.
739 for import in &self.indeterminate_imports {
740 self.throw_unresolved_import_error(errors, Some(MultiSpan::from(import.span)));
746 fn throw_unresolved_import_error(
748 errors: Vec<(String, UnresolvedImportError)>,
749 span: Option<MultiSpan>,
751 /// Upper limit on the number of `span_label` messages.
752 const MAX_LABEL_COUNT: usize = 10;
754 let (span, msg, note) = if errors.is_empty() {
755 (span.unwrap(), "unresolved import".to_string(), None)
757 let span = MultiSpan::from_spans(
760 .map(|(_, err)| err.span)
766 .filter_map(|(_, err)| err.note.as_ref())
771 .map(|(path, _)| format!("`{}`", path))
772 .collect::<Vec<_>>();
775 "unresolved import{} {}",
776 if paths.len() > 1 { "s" } else { "" },
783 let mut diag = struct_span_err!(self.resolver.session, span, E0432, "{}", &msg);
785 if let Some(note) = ¬e {
789 for (_, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
790 if let Some(label) = err.label {
791 diag.span_label(err.span, label);
794 if let Some((span, msg, suggestion, applicability)) = err.suggestion {
795 diag.span_suggestion(span, &msg, suggestion, applicability);
802 /// Attempts to resolve the given import, returning true if its resolution is determined.
803 /// If successful, the resolved bindings are written into the module.
804 fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool {
805 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
806 Segment::names_to_string(&directive.module_path),
807 module_to_string(self.current_module).unwrap_or_else(|| "???".to_string()));
809 self.current_module = directive.parent_scope.module;
811 let module = if let Some(module) = directive.imported_module.get() {
814 // For better failure detection, pretend that the import will
815 // not define any names while resolving its module path.
816 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
817 let path_res = self.resolve_path(
818 &directive.module_path,
820 &directive.parent_scope,
823 directive.crate_lint(),
825 directive.vis.set(orig_vis);
828 PathResult::Module(module) => module,
829 PathResult::Indeterminate => return false,
830 PathResult::NonModule(..) | PathResult::Failed { .. } => return true,
834 directive.imported_module.set(Some(module));
835 let (source, target, source_bindings, target_bindings, type_ns_only) =
836 match directive.subclass {
837 SingleImport { source, target, ref source_bindings,
838 ref target_bindings, type_ns_only, .. } =>
839 (source, target, source_bindings, target_bindings, type_ns_only),
840 GlobImport { .. } => {
841 self.resolve_glob_import(directive);
847 let mut indeterminate = false;
848 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
849 if let Err(Undetermined) = source_bindings[ns].get() {
850 // For better failure detection, pretend that the import will
851 // not define any names while resolving its module path.
852 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
853 let binding = this.resolve_ident_in_module(
854 module, source, ns, Some(&directive.parent_scope), false, directive.span
856 directive.vis.set(orig_vis);
858 source_bindings[ns].set(binding);
863 let parent = directive.parent_scope.module;
864 match source_bindings[ns].get() {
865 Err(Undetermined) => indeterminate = true,
867 this.update_resolution(parent, target, ns, |_, resolution| {
868 resolution.single_imports.remove(&PtrKey(directive));
871 Ok(binding) if !binding.is_importable() => {
872 let msg = format!("`{}` is not directly importable", target);
873 struct_span_err!(this.session, directive.span, E0253, "{}", &msg)
874 .span_label(directive.span, "cannot be imported directly")
876 // Do not import this illegal binding. Import a dummy binding and pretend
877 // everything is fine
878 this.import_dummy_binding(directive);
881 let imported_binding = this.import(binding, directive);
882 target_bindings[ns].set(Some(imported_binding));
883 this.define(parent, target, ns, imported_binding);
891 /// Performs final import resolution, consistency checks and error reporting.
893 /// Optionally returns an unresolved import error. This error is buffered and used to
894 /// consolidate multiple unresolved import errors into a single diagnostic.
897 directive: &'b ImportDirective<'b>
898 ) -> Option<UnresolvedImportError> {
899 self.current_module = directive.parent_scope.module;
901 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
902 let prev_ambiguity_errors_len = self.ambiguity_errors.len();
903 let path_res = self.resolve_path(&directive.module_path, None, &directive.parent_scope,
904 true, directive.span, directive.crate_lint());
905 let no_ambiguity = self.ambiguity_errors.len() == prev_ambiguity_errors_len;
906 directive.vis.set(orig_vis);
907 let module = match path_res {
908 PathResult::Module(module) => {
909 // Consistency checks, analogous to `finalize_current_module_macro_resolutions`.
910 if let Some(initial_module) = directive.imported_module.get() {
911 if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
912 span_bug!(directive.span, "inconsistent resolution for an import");
915 if self.privacy_errors.is_empty() {
916 let msg = "cannot determine resolution for the import";
917 let msg_note = "import resolution is stuck, try simplifying other imports";
918 self.session.struct_span_err(directive.span, msg).note(msg_note).emit();
924 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
926 assert!(directive.imported_module.get().is_none());
927 resolve_error(self, span, ResolutionError::FailedToResolve {
934 PathResult::Failed { is_error_from_last_segment: true, span, label, suggestion } => {
936 assert!(directive.imported_module.get().is_none());
937 let err = match self.make_path_suggestion(
939 directive.module_path.clone(),
940 &directive.parent_scope,
942 Some((suggestion, note)) => {
943 UnresolvedImportError {
949 String::from("a similar path exists"),
950 Segment::names_to_string(&suggestion),
951 Applicability::MaybeIncorrect,
956 UnresolvedImportError {
969 PathResult::NonModule(path_res) if path_res.base_def() == Def::Err => {
971 assert!(directive.imported_module.get().is_none());
973 // The error was already reported earlier.
976 PathResult::Indeterminate | PathResult::NonModule(..) => unreachable!(),
979 let (ident, target, source_bindings, target_bindings, type_ns_only) =
980 match directive.subclass {
981 SingleImport { source, target, ref source_bindings,
982 ref target_bindings, type_ns_only, .. } =>
983 (source, target, source_bindings, target_bindings, type_ns_only),
984 GlobImport { is_prelude, ref max_vis } => {
985 if directive.module_path.len() <= 1 {
986 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
987 // 2 segments, so the `resolve_path` above won't trigger it.
988 let mut full_path = directive.module_path.clone();
989 full_path.push(Segment::from_ident(keywords::Invalid.ident()));
990 self.lint_if_path_starts_with_module(
991 directive.crate_lint(),
998 if let ModuleOrUniformRoot::Module(module) = module {
999 if module.def_id() == directive.parent_scope.module.def_id() {
1000 // Importing a module into itself is not allowed.
1001 return Some(UnresolvedImportError {
1002 span: directive.span,
1003 label: Some(String::from("cannot glob-import a module into itself")),
1010 max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
1011 !max_vis.get().is_at_least(directive.vis.get(), &*self) {
1012 let msg = "A non-empty glob must import something with the glob's visibility";
1013 self.session.span_err(directive.span, msg);
1017 _ => unreachable!(),
1020 let mut all_ns_err = true;
1021 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
1022 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
1023 let orig_blacklisted_binding =
1024 mem::replace(&mut this.blacklisted_binding, target_bindings[ns].get());
1025 let orig_last_import_segment = mem::replace(&mut this.last_import_segment, true);
1026 let binding = this.resolve_ident_in_module(
1027 module, ident, ns, Some(&directive.parent_scope), true, directive.span
1029 this.last_import_segment = orig_last_import_segment;
1030 this.blacklisted_binding = orig_blacklisted_binding;
1031 directive.vis.set(orig_vis);
1035 // Consistency checks, analogous to `finalize_current_module_macro_resolutions`.
1036 let initial_def = source_bindings[ns].get().map(|initial_binding| {
1038 if let Some(target_binding) = target_bindings[ns].get() {
1039 if target.name == "_" &&
1040 initial_binding.is_extern_crate() && !initial_binding.is_import() {
1041 this.record_use(ident, ns, target_binding,
1042 directive.module_path.is_empty());
1045 initial_binding.def()
1047 let def = binding.def();
1048 if let Ok(initial_def) = initial_def {
1049 if def != initial_def && this.ambiguity_errors.is_empty() {
1050 span_bug!(directive.span, "inconsistent resolution for an import");
1053 if def != Def::Err &&
1054 this.ambiguity_errors.is_empty() && this.privacy_errors.is_empty() {
1055 let msg = "cannot determine resolution for the import";
1057 "import resolution is stuck, try simplifying other imports";
1058 this.session.struct_span_err(directive.span, msg).note(msg_note).emit();
1063 // FIXME: This assert may fire if public glob is later shadowed by a private
1064 // single import (see test `issue-55884-2.rs`). In theory single imports should
1065 // always block globs, even if they are not yet resolved, so that this kind of
1066 // self-inconsistent resolution never happens.
1067 // Reenable the assert when the issue is fixed.
1068 // assert!(result[ns].get().is_err());
1074 let mut all_ns_failed = true;
1075 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
1076 let binding = this.resolve_ident_in_module(
1077 module, ident, ns, Some(&directive.parent_scope), true, directive.span
1079 if binding.is_ok() {
1080 all_ns_failed = false;
1084 return if all_ns_failed {
1085 let resolutions = match module {
1086 ModuleOrUniformRoot::Module(module) => Some(module.resolutions.borrow()),
1089 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
1090 let names = resolutions.filter_map(|(&(ref i, _), resolution)| {
1091 if *i == ident { return None; } // Never suggest the same name
1092 match *resolution.borrow() {
1093 NameResolution { binding: Some(name_binding), .. } => {
1094 match name_binding.kind {
1095 NameBindingKind::Import { binding, .. } => {
1096 match binding.kind {
1097 // Never suggest the name that has binding error
1098 // i.e., the name that cannot be previously resolved
1099 NameBindingKind::Def(Def::Err, _) => return None,
1106 NameResolution { ref single_imports, .. }
1107 if single_imports.is_empty() => None,
1112 let lev_suggestion =
1113 find_best_match_for_name(names, &ident.as_str(), None).map(|suggestion| {
1116 String::from("a similar name exists in the module"),
1117 suggestion.to_string(),
1118 Applicability::MaybeIncorrect,
1122 let label = match module {
1123 ModuleOrUniformRoot::Module(module) => {
1124 let module_str = module_to_string(module);
1125 if let Some(module_str) = module_str {
1126 format!("no `{}` in `{}`", ident, module_str)
1128 format!("no `{}` in the root", ident)
1132 if !ident.is_path_segment_keyword() {
1133 format!("no `{}` external crate", ident)
1135 // HACK(eddyb) this shows up for `self` & `super`, which
1136 // should work instead - for now keep the same error message.
1137 format!("no `{}` in the root", ident)
1141 Some(UnresolvedImportError {
1142 span: directive.span,
1145 suggestion: lev_suggestion,
1148 // `resolve_ident_in_module` reported a privacy error.
1149 self.import_dummy_binding(directive);
1154 let mut reexport_error = None;
1155 let mut any_successful_reexport = false;
1156 self.per_ns(|this, ns| {
1157 if let Ok(binding) = source_bindings[ns].get() {
1158 let vis = directive.vis.get();
1159 if !binding.pseudo_vis().is_at_least(vis, &*this) {
1160 reexport_error = Some((ns, binding));
1162 any_successful_reexport = true;
1167 // All namespaces must be re-exported with extra visibility for an error to occur.
1168 if !any_successful_reexport {
1169 let (ns, binding) = reexport_error.unwrap();
1170 if ns == TypeNS && binding.is_extern_crate() {
1171 let msg = format!("extern crate `{}` is private, and cannot be \
1172 re-exported (error E0365), consider declaring with \
1175 self.session.buffer_lint(PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1179 } else if ns == TypeNS {
1180 struct_span_err!(self.session, directive.span, E0365,
1181 "`{}` is private, and cannot be re-exported", ident)
1182 .span_label(directive.span, format!("re-export of private `{}`", ident))
1183 .note(&format!("consider declaring type or module `{}` with `pub`", ident))
1186 let msg = format!("`{}` is private, and cannot be re-exported", ident);
1188 format!("consider marking `{}` as `pub` in the imported module", ident);
1189 struct_span_err!(self.session, directive.span, E0364, "{}", &msg)
1190 .span_note(directive.span, ¬e_msg)
1195 if directive.module_path.len() <= 1 {
1196 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1197 // 2 segments, so the `resolve_path` above won't trigger it.
1198 let mut full_path = directive.module_path.clone();
1199 full_path.push(Segment::from_ident(ident));
1200 self.per_ns(|this, ns| {
1201 if let Ok(binding) = source_bindings[ns].get() {
1202 this.lint_if_path_starts_with_module(
1203 directive.crate_lint(),
1212 // Record what this import resolves to for later uses in documentation,
1213 // this may resolve to either a value or a type, but for documentation
1214 // purposes it's good enough to just favor one over the other.
1215 self.per_ns(|this, ns| if let Some(binding) = source_bindings[ns].get().ok() {
1216 let mut def = binding.def();
1217 if let Def::Macro(def_id, _) = def {
1218 // `DefId`s from the "built-in macro crate" should not leak from resolve because
1219 // later stages are not ready to deal with them and produce lots of ICEs. Replace
1220 // them with `Def::Err` until some saner scheme is implemented for built-in macros.
1221 if def_id.krate == CrateNum::BuiltinMacros {
1222 this.session.span_err(directive.span, "cannot import a built-in macro");
1226 let import = this.import_map.entry(directive.id).or_default();
1227 import[ns] = Some(PathResolution::new(def));
1230 debug!("(resolving single import) successfully resolved import");
1234 fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) {
1235 let module = match directive.imported_module.get().unwrap() {
1236 ModuleOrUniformRoot::Module(module) => module,
1238 self.session.span_err(directive.span, "cannot glob-import all possible crates");
1243 self.populate_module_if_necessary(module);
1245 if let Some(Def::Trait(_)) = module.def() {
1246 self.session.span_err(directive.span, "items in traits are not importable.");
1248 } else if module.def_id() == directive.parent_scope.module.def_id() {
1250 } else if let GlobImport { is_prelude: true, .. } = directive.subclass {
1251 self.prelude = Some(module);
1255 // Add to module's glob_importers
1256 module.glob_importers.borrow_mut().push(directive);
1258 // Ensure that `resolutions` isn't borrowed during `try_define`,
1259 // since it might get updated via a glob cycle.
1260 let bindings = module.resolutions.borrow().iter().filter_map(|(&ident, resolution)| {
1261 resolution.borrow().binding().map(|binding| (ident, binding))
1262 }).collect::<Vec<_>>();
1263 for ((mut ident, ns), binding) in bindings {
1264 let scope = match ident.span.reverse_glob_adjust(module.expansion,
1265 directive.span.ctxt().modern()) {
1266 Some(Some(def)) => self.macro_def_scope(def),
1267 Some(None) => self.current_module,
1270 if self.is_accessible_from(binding.pseudo_vis(), scope) {
1271 let imported_binding = self.import(binding, directive);
1272 let _ = self.try_define(directive.parent_scope.module, ident, ns, imported_binding);
1276 // Record the destination of this import
1277 self.record_def(directive.id, PathResolution::new(module.def().unwrap()));
1280 // Miscellaneous post-processing, including recording re-exports,
1281 // reporting conflicts, and reporting unresolved imports.
1282 fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1283 // Since import resolution is finished, globs will not define any more names.
1284 *module.globs.borrow_mut() = Vec::new();
1286 let mut reexports = Vec::new();
1288 for (&(ident, ns), resolution) in module.resolutions.borrow().iter() {
1289 let resolution = &mut *resolution.borrow_mut();
1290 let binding = match resolution.binding {
1291 Some(binding) => binding,
1295 // Filter away ambiguous and gensymed imports. Gensymed imports
1296 // (e.g. implicitly injected `std`) cannot be properly encoded in metadata,
1297 // so they can cause name conflict errors downstream.
1298 let is_good_import = binding.is_import() && !binding.is_ambiguity() &&
1299 !(ident.name.is_gensymed() && ident.name != "_");
1300 if is_good_import || binding.is_macro_def() {
1301 let def = binding.def();
1302 if def != Def::Err {
1303 if let Some(def_id) = def.opt_def_id() {
1304 if !def_id.is_local() && def_id.krate != CrateNum::BuiltinMacros {
1305 self.cstore.export_macros_untracked(def_id.krate);
1308 reexports.push(Export {
1309 ident: ident.modern(),
1317 if let NameBindingKind::Import { binding: orig_binding, directive, .. } = binding.kind {
1318 if ns == TypeNS && orig_binding.is_variant() &&
1319 !orig_binding.vis.is_at_least(binding.vis, &*self) {
1320 let msg = match directive.subclass {
1321 ImportDirectiveSubclass::SingleImport { .. } => {
1322 format!("variant `{}` is private and cannot be re-exported",
1325 ImportDirectiveSubclass::GlobImport { .. } => {
1326 let msg = "enum is private and its variants \
1327 cannot be re-exported".to_owned();
1328 let error_id = (DiagnosticMessageId::ErrorId(0), // no code?!
1331 let fresh = self.session.one_time_diagnostics
1332 .borrow_mut().insert(error_id);
1338 ref s @ _ => bug!("unexpected import subclass {:?}", s)
1340 let mut err = self.session.struct_span_err(binding.span, &msg);
1342 let imported_module = match directive.imported_module.get() {
1343 Some(ModuleOrUniformRoot::Module(module)) => module,
1344 _ => bug!("module should exist"),
1346 let resolutions = imported_module.parent.expect("parent should exist")
1347 .resolutions.borrow();
1348 let enum_path_segment_index = directive.module_path.len() - 1;
1349 let enum_ident = directive.module_path[enum_path_segment_index].ident;
1351 let enum_resolution = resolutions.get(&(enum_ident, TypeNS))
1352 .expect("resolution should exist");
1353 let enum_span = enum_resolution.borrow()
1354 .binding.expect("binding should exist")
1356 let enum_def_span = self.session.source_map().def_span(enum_span);
1357 let enum_def_snippet = self.session.source_map()
1358 .span_to_snippet(enum_def_span).expect("snippet should exist");
1359 // potentially need to strip extant `crate`/`pub(path)` for suggestion
1360 let after_vis_index = enum_def_snippet.find("enum")
1361 .expect("`enum` keyword should exist in snippet");
1362 let suggestion = format!("pub {}",
1363 &enum_def_snippet[after_vis_index..]);
1366 .diag_span_suggestion_once(&mut err,
1367 DiagnosticMessageId::ErrorId(0),
1369 "consider making the enum public",
1376 if reexports.len() > 0 {
1377 if let Some(def_id) = module.def_id() {
1378 self.export_map.insert(def_id, reexports);
1384 fn import_path_to_string(names: &[Ident],
1385 subclass: &ImportDirectiveSubclass<'_>,
1386 span: Span) -> String {
1387 let pos = names.iter()
1388 .position(|p| span == p.span && p.name != keywords::PathRoot.name());
1389 let global = !names.is_empty() && names[0].name == keywords::PathRoot.name();
1390 if let Some(pos) = pos {
1391 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1392 names_to_string(names)
1394 let names = if global { &names[1..] } else { names };
1395 if names.is_empty() {
1396 import_directive_subclass_to_string(subclass)
1399 names_to_string(names),
1400 import_directive_subclass_to_string(subclass))
1405 fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass<'_>) -> String {
1407 SingleImport { source, .. } => source.to_string(),
1408 GlobImport { .. } => "*".to_string(),
1409 ExternCrate { .. } => "<extern crate>".to_string(),
1410 MacroUse => "#[macro_use]".to_string(),