1 use ImportDirectiveSubclass::*;
3 use crate::{AmbiguityError, AmbiguityKind, AmbiguityErrorMisc};
4 use crate::{CrateLint, Module, ModuleOrUniformRoot, PerNS, ScopeSet, ParentScope, Weak};
5 use crate::Determinacy::{self, *};
6 use crate::Namespace::{self, TypeNS, MacroNS};
7 use crate::{NameBinding, NameBindingKind, ToNameBinding, PathResult, PrivacyError};
8 use crate::{Resolver, Segment};
9 use crate::{names_to_string, module_to_string};
10 use crate::{resolve_error, ResolutionError};
11 use crate::ModuleKind;
12 use crate::diagnostics::Suggestion;
14 use errors::Applicability;
16 use rustc_data_structures::ptr_key::PtrKey;
18 use rustc::lint::builtin::BuiltinLintDiagnostics;
19 use rustc::lint::builtin::{
20 DUPLICATE_MACRO_EXPORTS,
21 PUB_USE_OF_PRIVATE_EXTERN_CRATE,
24 use rustc::hir::def_id::DefId;
25 use rustc::hir::def::{self, PartialRes, Export};
26 use rustc::session::DiagnosticMessageId;
27 use rustc::util::nodemap::FxHashSet;
28 use rustc::{bug, span_bug};
30 use syntax::ast::{self, Ident, Name, NodeId, CRATE_NODE_ID};
31 use syntax::ext::hygiene::ExpnId;
32 use syntax::symbol::kw;
33 use syntax::util::lev_distance::find_best_match_for_name;
34 use syntax::{struct_span_err, unwrap_or};
35 use syntax_pos::{MultiSpan, Span};
39 use std::cell::{Cell, RefCell};
42 type Res = def::Res<NodeId>;
44 /// Contains data for specific types of import directives.
45 #[derive(Clone, Debug)]
46 pub enum ImportDirectiveSubclass<'a> {
48 /// `source` in `use prefix::source as target`.
50 /// `target` in `use prefix::source as target`.
52 /// Bindings to which `source` refers to.
53 source_bindings: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
54 /// Bindings introduced by `target`.
55 target_bindings: PerNS<Cell<Option<&'a NameBinding<'a>>>>,
56 /// `true` for `...::{self [as target]}` imports, `false` otherwise.
58 /// Did this import result from a nested import? ie. `use foo::{bar, baz};`
63 max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
64 // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
73 /// One import directive.
74 #[derive(Debug,Clone)]
75 crate struct ImportDirective<'a> {
76 /// The ID of the `extern crate`, `UseTree` etc that imported this `ImportDirective`.
78 /// In the case where the `ImportDirective` was expanded from a "nested" use tree,
79 /// this id is the ID of the leaf tree. For example:
81 /// ```ignore (pacify the mercilous tidy)
82 /// use foo::bar::{a, b}
85 /// If this is the import directive for `foo::bar::a`, we would have the ID of the `UseTree`
86 /// for `a` in this field.
89 /// The `id` of the "root" use-kind -- this is always the same as
90 /// `id` except in the case of "nested" use trees, in which case
91 /// it will be the `id` of the root use tree. e.g., in the example
92 /// from `id`, this would be the ID of the `use foo::bar`
96 /// Span of the entire use statement.
99 /// Span of the entire use statement with attributes.
100 pub use_span_with_attributes: Span,
102 /// Did the use statement have any attributes?
103 pub has_attributes: bool,
105 /// Span of this use tree.
108 /// Span of the *root* use tree (see `root_id`).
111 pub parent_scope: ParentScope<'a>,
112 pub module_path: Vec<Segment>,
113 /// The resolution of `module_path`.
114 pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>,
115 pub subclass: ImportDirectiveSubclass<'a>,
116 pub vis: Cell<ty::Visibility>,
117 pub used: Cell<bool>,
120 impl<'a> ImportDirective<'a> {
121 pub fn is_glob(&self) -> bool {
122 match self.subclass { ImportDirectiveSubclass::GlobImport { .. } => true, _ => false }
125 pub fn is_nested(&self) -> bool {
126 match self.subclass {
127 ImportDirectiveSubclass::SingleImport { nested, .. } => nested,
132 crate fn crate_lint(&self) -> CrateLint {
133 CrateLint::UsePath { root_id: self.root_id, root_span: self.root_span }
137 #[derive(Clone, Default, Debug)]
138 /// Records information about the resolution of a name in a namespace of a module.
139 pub struct NameResolution<'a> {
140 /// Single imports that may define the name in the namespace.
141 /// Import directives are arena-allocated, so it's ok to use pointers as keys.
142 single_imports: FxHashSet<PtrKey<'a, ImportDirective<'a>>>,
143 /// The least shadowable known binding for this name, or None if there are no known bindings.
144 pub binding: Option<&'a NameBinding<'a>>,
145 shadowed_glob: Option<&'a NameBinding<'a>>,
148 impl<'a> NameResolution<'a> {
149 // Returns the binding for the name if it is known or None if it not known.
150 pub(crate) fn binding(&self) -> Option<&'a NameBinding<'a>> {
151 self.binding.and_then(|binding| {
152 if !binding.is_glob_import() ||
153 self.single_imports.is_empty() { Some(binding) } else { None }
158 impl<'a> Resolver<'a> {
159 fn resolution(&self, module: Module<'a>, ident: Ident, ns: Namespace)
160 -> &'a RefCell<NameResolution<'a>> {
161 *module.resolutions.borrow_mut().entry((ident.modern(), ns))
162 .or_insert_with(|| self.arenas.alloc_name_resolution())
165 crate fn resolve_ident_in_module_unadjusted(
167 module: ModuleOrUniformRoot<'a>,
172 ) -> Result<&'a NameBinding<'a>, Determinacy> {
173 self.resolve_ident_in_module_unadjusted_ext(
174 module, ident, ns, None, false, record_used, path_span
175 ).map_err(|(determinacy, _)| determinacy)
178 /// Attempts to resolve `ident` in namespaces `ns` of `module`.
179 /// Invariant: if `record_used` is `Some`, expansion and import resolution must be complete.
180 crate fn resolve_ident_in_module_unadjusted_ext(
182 module: ModuleOrUniformRoot<'a>,
185 parent_scope: Option<&ParentScope<'a>>,
186 restricted_shadowing: bool,
189 ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
190 let module = match module {
191 ModuleOrUniformRoot::Module(module) => module,
192 ModuleOrUniformRoot::CrateRootAndExternPrelude => {
193 assert!(!restricted_shadowing);
194 let parent_scope = self.dummy_parent_scope();
195 let binding = self.early_resolve_ident_in_lexical_scope(
196 ident, ScopeSet::AbsolutePath(ns), &parent_scope,
197 record_used, record_used, path_span,
199 return binding.map_err(|determinacy| (determinacy, Weak::No));
201 ModuleOrUniformRoot::ExternPrelude => {
202 assert!(!restricted_shadowing);
203 return if ns != TypeNS {
204 Err((Determined, Weak::No))
205 } else if let Some(binding) = self.extern_prelude_get(ident, !record_used) {
207 } else if !self.graph_root.unresolved_invocations.borrow().is_empty() {
208 // Macro-expanded `extern crate` items can add names to extern prelude.
209 Err((Undetermined, Weak::No))
211 Err((Determined, Weak::No))
214 ModuleOrUniformRoot::CurrentScope => {
215 assert!(!restricted_shadowing);
217 parent_scope.expect("no parent scope for a single-segment import");
220 if ident.name == kw::Crate ||
221 ident.name == kw::DollarCrate {
222 let module = self.resolve_crate_root(ident);
223 let binding = (module, ty::Visibility::Public,
224 module.span, ExpnId::root())
225 .to_name_binding(self.arenas);
227 } else if ident.name == kw::Super ||
228 ident.name == kw::SelfLower {
229 // FIXME: Implement these with renaming requirements so that e.g.
230 // `use super;` doesn't work, but `use super as name;` does.
231 // Fall through here to get an error from `early_resolve_...`.
235 let binding = self.early_resolve_ident_in_lexical_scope(
236 ident, ScopeSet::Import(ns), parent_scope, record_used, record_used, path_span
238 return binding.map_err(|determinacy| (determinacy, Weak::No));
242 self.populate_module_if_necessary(module);
244 let resolution = self.resolution(module, ident, ns)
246 .map_err(|_| (Determined, Weak::No))?; // This happens when there is a cycle of imports.
248 if let Some(binding) = resolution.binding {
249 if !restricted_shadowing && binding.expansion != ExpnId::root() {
250 if let NameBindingKind::Res(_, true) = binding.kind {
251 self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
256 let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
257 if let Some(blacklisted_binding) = this.blacklisted_binding {
258 if ptr::eq(binding, blacklisted_binding) {
259 return Err((Determined, Weak::No));
262 // `extern crate` are always usable for backwards compatibility, see issue #37020,
263 // remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`.
264 let usable = this.is_accessible(binding.vis) || binding.is_extern_crate();
265 if usable { Ok(binding) } else { Err((Determined, Weak::No)) }
269 return resolution.binding.and_then(|binding| {
270 // If the primary binding is blacklisted, search further and return the shadowed
271 // glob binding if it exists. What we really want here is having two separate
272 // scopes in a module - one for non-globs and one for globs, but until that's done
273 // use this hack to avoid inconsistent resolution ICEs during import validation.
274 if let Some(blacklisted_binding) = self.blacklisted_binding {
275 if ptr::eq(binding, blacklisted_binding) {
276 return resolution.shadowed_glob;
280 }).ok_or((Determined, Weak::No)).and_then(|binding| {
281 if self.last_import_segment && check_usable(self, binding).is_err() {
282 Err((Determined, Weak::No))
284 self.record_use(ident, ns, binding, restricted_shadowing);
286 if let Some(shadowed_glob) = resolution.shadowed_glob {
287 // Forbid expanded shadowing to avoid time travel.
288 if restricted_shadowing &&
289 binding.expansion != ExpnId::root() &&
290 binding.res() != shadowed_glob.res() {
291 self.ambiguity_errors.push(AmbiguityError {
292 kind: AmbiguityKind::GlobVsExpanded,
296 misc1: AmbiguityErrorMisc::None,
297 misc2: AmbiguityErrorMisc::None,
302 if !self.is_accessible(binding.vis) &&
303 // Remove this together with `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
304 !(self.last_import_segment && binding.is_extern_crate()) {
305 self.privacy_errors.push(PrivacyError(path_span, ident, binding));
313 // Items and single imports are not shadowable, if we have one, then it's determined.
314 if let Some(binding) = resolution.binding {
315 if !binding.is_glob_import() {
316 return check_usable(self, binding);
320 // --- From now on we either have a glob resolution or no resolution. ---
322 // Check if one of single imports can still define the name,
323 // if it can then our result is not determined and can be invalidated.
324 for single_import in &resolution.single_imports {
325 if !self.is_accessible(single_import.vis.get()) {
328 let module = unwrap_or!(single_import.imported_module.get(),
329 return Err((Undetermined, Weak::No)));
330 let ident = match single_import.subclass {
331 SingleImport { source, .. } => source,
334 match self.resolve_ident_in_module(module, ident, ns, Some(&single_import.parent_scope),
336 Err(Determined) => continue,
337 Ok(binding) if !self.is_accessible_from(
338 binding.vis, single_import.parent_scope.module
340 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::No)),
344 // So we have a resolution that's from a glob import. This resolution is determined
345 // if it cannot be shadowed by some new item/import expanded from a macro.
346 // This happens either if there are no unexpanded macros, or expanded names cannot
347 // shadow globs (that happens in macro namespace or with restricted shadowing).
349 // Additionally, any macro in any module can plant names in the root module if it creates
350 // `macro_export` macros, so the root module effectively has unresolved invocations if any
351 // module has unresolved invocations.
352 // However, it causes resolution/expansion to stuck too often (#53144), so, to make
353 // progress, we have to ignore those potential unresolved invocations from other modules
354 // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
355 // shadowing is enabled, see `macro_expanded_macro_export_errors`).
356 let unexpanded_macros = !module.unresolved_invocations.borrow().is_empty();
357 if let Some(binding) = resolution.binding {
358 if !unexpanded_macros || ns == MacroNS || restricted_shadowing {
359 return check_usable(self, binding);
361 return Err((Undetermined, Weak::No));
365 // --- From now on we have no resolution. ---
367 // Now we are in situation when new item/import can appear only from a glob or a macro
368 // expansion. With restricted shadowing names from globs and macro expansions cannot
369 // shadow names from outer scopes, so we can freely fallback from module search to search
370 // in outer scopes. For `early_resolve_ident_in_lexical_scope` to continue search in outer
371 // scopes we return `Undetermined` with `Weak::Yes`.
373 // Check if one of unexpanded macros can still define the name,
374 // if it can then our "no resolution" result is not determined and can be invalidated.
375 if unexpanded_macros {
376 return Err((Undetermined, Weak::Yes));
379 // Check if one of glob imports can still define the name,
380 // if it can then our "no resolution" result is not determined and can be invalidated.
381 for glob_import in module.globs.borrow().iter() {
382 if !self.is_accessible(glob_import.vis.get()) {
385 let module = match glob_import.imported_module.get() {
386 Some(ModuleOrUniformRoot::Module(module)) => module,
388 None => return Err((Undetermined, Weak::Yes)),
390 let (orig_current_module, mut ident) = (self.current_module, ident.modern());
391 match ident.span.glob_adjust(module.expansion, glob_import.span) {
392 Some(Some(def)) => self.current_module = self.macro_def_scope(def),
396 let result = self.resolve_ident_in_module_unadjusted(
397 ModuleOrUniformRoot::Module(module),
403 self.current_module = orig_current_module;
406 Err(Determined) => continue,
407 Ok(binding) if !self.is_accessible_from(
408 binding.vis, glob_import.parent_scope.module
410 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::Yes)),
414 // No resolution and no one else can define the name - determinate error.
415 Err((Determined, Weak::No))
418 // Add an import directive to the current module.
419 pub fn add_import_directive(&mut self,
420 module_path: Vec<Segment>,
421 subclass: ImportDirectiveSubclass<'a>,
428 parent_scope: ParentScope<'a>) {
429 let current_module = parent_scope.module;
430 let directive = self.arenas.alloc_import_directive(ImportDirective {
433 imported_module: Cell::new(None),
438 use_span_with_attributes: item.span_with_attributes(),
439 has_attributes: !item.attrs.is_empty(),
443 used: Cell::new(false),
446 debug!("add_import_directive({:?})", directive);
448 self.indeterminate_imports.push(directive);
449 match directive.subclass {
450 SingleImport { target, type_ns_only, .. } => {
451 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
452 let mut resolution = this.resolution(current_module, target, ns).borrow_mut();
453 resolution.single_imports.insert(PtrKey(directive));
456 // We don't add prelude imports to the globs since they only affect lexical scopes,
457 // which are not relevant to import resolution.
458 GlobImport { is_prelude: true, .. } => {}
459 GlobImport { .. } => current_module.globs.borrow_mut().push(directive),
464 // Given a binding and an import directive that resolves to it,
465 // return the corresponding binding defined by the import directive.
466 crate fn import(&self, binding: &'a NameBinding<'a>, directive: &'a ImportDirective<'a>)
467 -> &'a NameBinding<'a> {
468 let vis = if binding.pseudo_vis().is_at_least(directive.vis.get(), self) ||
469 // cf. `PUB_USE_OF_PRIVATE_EXTERN_CRATE`
470 !directive.is_glob() && binding.is_extern_crate() {
476 if let GlobImport { ref max_vis, .. } = directive.subclass {
477 if vis == directive.vis.get() || vis.is_at_least(max_vis.get(), self) {
482 self.arenas.alloc_name_binding(NameBinding {
483 kind: NameBindingKind::Import {
486 used: Cell::new(false),
489 span: directive.span,
491 expansion: directive.parent_scope.expansion,
495 // Define the name or return the existing binding if there is a collision.
496 pub fn try_define(&mut self,
500 binding: &'a NameBinding<'a>)
501 -> Result<(), &'a NameBinding<'a>> {
502 let res = binding.res();
503 self.check_reserved_macro_name(ident, res);
504 self.set_binding_parent_module(binding, module);
505 self.update_resolution(module, ident, ns, |this, resolution| {
506 if let Some(old_binding) = resolution.binding {
508 // Do not override real bindings with `Res::Err`s from error recovery.
511 match (old_binding.is_glob_import(), binding.is_glob_import()) {
513 if res != old_binding.res() {
514 resolution.binding = Some(this.ambiguity(AmbiguityKind::GlobVsGlob,
515 old_binding, binding));
516 } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
517 // We are glob-importing the same item but with greater visibility.
518 resolution.binding = Some(binding);
521 (old_glob @ true, false) | (old_glob @ false, true) => {
522 let (glob_binding, nonglob_binding) = if old_glob {
523 (old_binding, binding)
525 (binding, old_binding)
527 if glob_binding.res() != nonglob_binding.res() &&
528 ns == MacroNS && nonglob_binding.expansion != ExpnId::root() {
529 resolution.binding = Some(this.ambiguity(AmbiguityKind::GlobVsExpanded,
530 nonglob_binding, glob_binding));
532 resolution.binding = Some(nonglob_binding);
534 resolution.shadowed_glob = Some(glob_binding);
537 if let (&NameBindingKind::Res(_, true), &NameBindingKind::Res(_, true)) =
538 (&old_binding.kind, &binding.kind) {
540 this.session.buffer_lint_with_diagnostic(
541 DUPLICATE_MACRO_EXPORTS,
544 &format!("a macro named `{}` has already been exported", ident),
545 BuiltinLintDiagnostics::DuplicatedMacroExports(
546 ident, old_binding.span, binding.span));
548 resolution.binding = Some(binding);
550 return Err(old_binding);
555 resolution.binding = Some(binding);
562 fn ambiguity(&self, kind: AmbiguityKind,
563 primary_binding: &'a NameBinding<'a>, secondary_binding: &'a NameBinding<'a>)
564 -> &'a NameBinding<'a> {
565 self.arenas.alloc_name_binding(NameBinding {
566 ambiguity: Some((secondary_binding, kind)),
567 ..primary_binding.clone()
571 // Use `f` to mutate the resolution of the name in the module.
572 // If the resolution becomes a success, define it in the module's glob importers.
573 fn update_resolution<T, F>(&mut self, module: Module<'a>, ident: Ident, ns: Namespace, f: F)
575 where F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T
577 // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
578 // during which the resolution might end up getting re-defined via a glob cycle.
580 let resolution = &mut *self.resolution(module, ident, ns).borrow_mut();
581 let old_binding = resolution.binding();
583 let t = f(self, resolution);
585 match resolution.binding() {
586 _ if old_binding.is_some() => return t,
588 Some(binding) => match old_binding {
589 Some(old_binding) if ptr::eq(old_binding, binding) => return t,
595 // Define `binding` in `module`s glob importers.
596 for directive in module.glob_importers.borrow_mut().iter() {
597 let mut ident = ident.modern();
598 let scope = match ident.span.reverse_glob_adjust(module.expansion, directive.span) {
599 Some(Some(def)) => self.macro_def_scope(def),
600 Some(None) => directive.parent_scope.module,
603 if self.is_accessible_from(binding.vis, scope) {
604 let imported_binding = self.import(binding, directive);
605 let _ = self.try_define(directive.parent_scope.module, ident, ns, imported_binding);
612 // Define a "dummy" resolution containing a Res::Err as a placeholder for a
614 fn import_dummy_binding(&mut self, directive: &'a ImportDirective<'a>) {
615 if let SingleImport { target, .. } = directive.subclass {
616 let dummy_binding = self.dummy_binding;
617 let dummy_binding = self.import(dummy_binding, directive);
618 self.per_ns(|this, ns| {
619 let _ = this.try_define(directive.parent_scope.module, target, ns, dummy_binding);
620 // Consider erroneous imports used to avoid duplicate diagnostics.
621 this.record_use(target, ns, dummy_binding, false);
627 /// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
628 /// import errors within the same use tree into a single diagnostic.
629 #[derive(Debug, Clone)]
630 struct UnresolvedImportError {
632 label: Option<String>,
634 suggestion: Option<Suggestion>,
637 pub struct ImportResolver<'a, 'b> {
638 pub resolver: &'a mut Resolver<'b>,
641 impl<'a, 'b> std::ops::Deref for ImportResolver<'a, 'b> {
642 type Target = Resolver<'b>;
643 fn deref(&self) -> &Resolver<'b> {
648 impl<'a, 'b> std::ops::DerefMut for ImportResolver<'a, 'b> {
649 fn deref_mut(&mut self) -> &mut Resolver<'b> {
654 impl<'a, 'b> ty::DefIdTree for &'a ImportResolver<'a, 'b> {
655 fn parent(self, id: DefId) -> Option<DefId> {
656 self.resolver.parent(id)
660 impl<'a, 'b> ImportResolver<'a, 'b> {
663 // This is a fixed-point algorithm. We resolve imports until our efforts
664 // are stymied by an unresolved import; then we bail out of the current
665 // module and continue. We terminate successfully once no more imports
666 // remain or unsuccessfully when no forward progress in resolving imports
669 /// Resolves all imports for the crate. This method performs the fixed-
671 pub fn resolve_imports(&mut self) {
672 let mut prev_num_indeterminates = self.indeterminate_imports.len() + 1;
673 while self.indeterminate_imports.len() < prev_num_indeterminates {
674 prev_num_indeterminates = self.indeterminate_imports.len();
675 for import in mem::take(&mut self.indeterminate_imports) {
676 match self.resolve_import(&import) {
677 true => self.determined_imports.push(import),
678 false => self.indeterminate_imports.push(import),
684 pub fn finalize_imports(&mut self) {
685 for module in self.arenas.local_modules().iter() {
686 self.finalize_resolutions_in(module);
689 let mut has_errors = false;
690 let mut seen_spans = FxHashSet::default();
691 let mut errors = vec![];
692 let mut prev_root_id: NodeId = NodeId::from_u32(0);
693 for i in 0 .. self.determined_imports.len() {
694 let import = self.determined_imports[i];
695 if let Some(err) = self.finalize_import(import) {
698 if let SingleImport { source, ref source_bindings, .. } = import.subclass {
699 if source.name == kw::SelfLower {
700 // Silence `unresolved import` error if E0429 is already emitted
701 if let Err(Determined) = source_bindings.value_ns.get() {
707 // If the error is a single failed import then create a "fake" import
708 // resolution for it so that later resolve stages won't complain.
709 self.import_dummy_binding(import);
710 if prev_root_id.as_u32() != 0
711 && prev_root_id.as_u32() != import.root_id.as_u32()
712 && !errors.is_empty() {
713 // In the case of a new import line, throw a diagnostic message
714 // for the previous line.
715 self.throw_unresolved_import_error(errors, None);
718 if !seen_spans.contains(&err.span) {
719 let path = import_path_to_string(
720 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
724 seen_spans.insert(err.span);
725 errors.push((path, err));
726 prev_root_id = import.root_id;
731 if !errors.is_empty() {
732 self.throw_unresolved_import_error(errors.clone(), None);
735 // Report unresolved imports only if no hard error was already reported
736 // to avoid generating multiple errors on the same import.
738 for import in &self.indeterminate_imports {
739 self.throw_unresolved_import_error(errors, Some(MultiSpan::from(import.span)));
745 fn throw_unresolved_import_error(
747 errors: Vec<(String, UnresolvedImportError)>,
748 span: Option<MultiSpan>,
750 /// Upper limit on the number of `span_label` messages.
751 const MAX_LABEL_COUNT: usize = 10;
753 let (span, msg) = if errors.is_empty() {
754 (span.unwrap(), "unresolved import".to_string())
756 let span = MultiSpan::from_spans(
759 .map(|(_, err)| err.span)
765 .map(|(path, _)| format!("`{}`", path))
766 .collect::<Vec<_>>();
769 "unresolved import{} {}",
770 if paths.len() > 1 { "s" } else { "" },
777 let mut diag = struct_span_err!(self.resolver.session, span, E0432, "{}", &msg);
779 if let Some((_, UnresolvedImportError { note, .. })) = errors.iter().last() {
780 for message in note {
785 for (_, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
786 if let Some(label) = err.label {
787 diag.span_label(err.span, label);
790 if let Some((suggestions, msg, applicability)) = err.suggestion {
791 diag.multipart_suggestion(&msg, suggestions, applicability);
798 /// Attempts to resolve the given import, returning true if its resolution is determined.
799 /// If successful, the resolved bindings are written into the module.
800 fn resolve_import(&mut self, directive: &'b ImportDirective<'b>) -> bool {
801 debug!("(resolving import for module) resolving import `{}::...` in `{}`",
802 Segment::names_to_string(&directive.module_path),
803 module_to_string(self.current_module).unwrap_or_else(|| "???".to_string()));
805 self.current_module = directive.parent_scope.module;
807 let module = if let Some(module) = directive.imported_module.get() {
810 // For better failure detection, pretend that the import will
811 // not define any names while resolving its module path.
812 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
813 let path_res = self.resolve_path(
814 &directive.module_path,
816 &directive.parent_scope,
819 directive.crate_lint(),
821 directive.vis.set(orig_vis);
824 PathResult::Module(module) => module,
825 PathResult::Indeterminate => return false,
826 PathResult::NonModule(..) | PathResult::Failed { .. } => return true,
830 directive.imported_module.set(Some(module));
831 let (source, target, source_bindings, target_bindings, type_ns_only) =
832 match directive.subclass {
833 SingleImport { source, target, ref source_bindings,
834 ref target_bindings, type_ns_only, .. } =>
835 (source, target, source_bindings, target_bindings, type_ns_only),
836 GlobImport { .. } => {
837 self.resolve_glob_import(directive);
843 let mut indeterminate = false;
844 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
845 if let Err(Undetermined) = source_bindings[ns].get() {
846 // For better failure detection, pretend that the import will
847 // not define any names while resolving its module path.
848 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
849 let binding = this.resolve_ident_in_module(
850 module, source, ns, Some(&directive.parent_scope), false, directive.span
852 directive.vis.set(orig_vis);
854 source_bindings[ns].set(binding);
859 let parent = directive.parent_scope.module;
860 match source_bindings[ns].get() {
861 Err(Undetermined) => indeterminate = true,
863 this.update_resolution(parent, target, ns, |_, resolution| {
864 resolution.single_imports.remove(&PtrKey(directive));
867 Ok(binding) if !binding.is_importable() => {
868 let msg = format!("`{}` is not directly importable", target);
869 struct_span_err!(this.session, directive.span, E0253, "{}", &msg)
870 .span_label(directive.span, "cannot be imported directly")
872 // Do not import this illegal binding. Import a dummy binding and pretend
873 // everything is fine
874 this.import_dummy_binding(directive);
877 let imported_binding = this.import(binding, directive);
878 target_bindings[ns].set(Some(imported_binding));
879 this.define(parent, target, ns, imported_binding);
887 /// Performs final import resolution, consistency checks and error reporting.
889 /// Optionally returns an unresolved import error. This error is buffered and used to
890 /// consolidate multiple unresolved import errors into a single diagnostic.
893 directive: &'b ImportDirective<'b>
894 ) -> Option<UnresolvedImportError> {
895 self.current_module = directive.parent_scope.module;
897 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
898 let prev_ambiguity_errors_len = self.ambiguity_errors.len();
899 let path_res = self.resolve_path(&directive.module_path, None, &directive.parent_scope,
900 true, directive.span, directive.crate_lint());
901 let no_ambiguity = self.ambiguity_errors.len() == prev_ambiguity_errors_len;
902 directive.vis.set(orig_vis);
903 let module = match path_res {
904 PathResult::Module(module) => {
905 // Consistency checks, analogous to `finalize_current_module_macro_resolutions`.
906 if let Some(initial_module) = directive.imported_module.get() {
907 if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
908 span_bug!(directive.span, "inconsistent resolution for an import");
911 if self.privacy_errors.is_empty() {
912 let msg = "cannot determine resolution for the import";
913 let msg_note = "import resolution is stuck, try simplifying other imports";
914 self.session.struct_span_err(directive.span, msg).note(msg_note).emit();
920 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
922 assert!(directive.imported_module.get().is_none());
923 resolve_error(self, span, ResolutionError::FailedToResolve {
930 PathResult::Failed { is_error_from_last_segment: true, span, label, suggestion } => {
932 assert!(directive.imported_module.get().is_none());
933 let err = match self.make_path_suggestion(
935 directive.module_path.clone(),
936 &directive.parent_scope,
938 Some((suggestion, note)) => {
939 UnresolvedImportError {
944 vec![(span, Segment::names_to_string(&suggestion))],
945 String::from("a similar path exists"),
946 Applicability::MaybeIncorrect,
951 UnresolvedImportError {
964 PathResult::NonModule(path_res) if path_res.base_res() == Res::Err => {
966 assert!(directive.imported_module.get().is_none());
968 // The error was already reported earlier.
971 PathResult::Indeterminate | PathResult::NonModule(..) => unreachable!(),
974 let (ident, target, source_bindings, target_bindings, type_ns_only) =
975 match directive.subclass {
976 SingleImport { source, target, ref source_bindings,
977 ref target_bindings, type_ns_only, .. } =>
978 (source, target, source_bindings, target_bindings, type_ns_only),
979 GlobImport { is_prelude, ref max_vis } => {
980 if directive.module_path.len() <= 1 {
981 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
982 // 2 segments, so the `resolve_path` above won't trigger it.
983 let mut full_path = directive.module_path.clone();
984 full_path.push(Segment::from_ident(Ident::invalid()));
985 self.lint_if_path_starts_with_module(
986 directive.crate_lint(),
993 if let ModuleOrUniformRoot::Module(module) = module {
994 if module.def_id() == directive.parent_scope.module.def_id() {
995 // Importing a module into itself is not allowed.
996 return Some(UnresolvedImportError {
997 span: directive.span,
998 label: Some(String::from("cannot glob-import a module into itself")),
1005 max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
1006 !max_vis.get().is_at_least(directive.vis.get(), &*self) {
1007 let msg = "A non-empty glob must import something with the glob's visibility";
1008 self.session.span_err(directive.span, msg);
1012 _ => unreachable!(),
1015 let mut all_ns_err = true;
1016 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
1017 let orig_vis = directive.vis.replace(ty::Visibility::Invisible);
1018 let orig_blacklisted_binding =
1019 mem::replace(&mut this.blacklisted_binding, target_bindings[ns].get());
1020 let orig_last_import_segment = mem::replace(&mut this.last_import_segment, true);
1021 let binding = this.resolve_ident_in_module(
1022 module, ident, ns, Some(&directive.parent_scope), true, directive.span
1024 this.last_import_segment = orig_last_import_segment;
1025 this.blacklisted_binding = orig_blacklisted_binding;
1026 directive.vis.set(orig_vis);
1030 // Consistency checks, analogous to `finalize_current_module_macro_resolutions`.
1031 let initial_res = source_bindings[ns].get().map(|initial_binding| {
1033 if let Some(target_binding) = target_bindings[ns].get() {
1034 // Note that as_str() de-gensyms the Symbol
1035 if target.name.as_str() == "_" &&
1036 initial_binding.is_extern_crate() && !initial_binding.is_import() {
1037 this.record_use(ident, ns, target_binding,
1038 directive.module_path.is_empty());
1041 initial_binding.res()
1043 let res = binding.res();
1044 if let Ok(initial_res) = initial_res {
1045 if res != initial_res && this.ambiguity_errors.is_empty() {
1046 span_bug!(directive.span, "inconsistent resolution for an import");
1049 if res != Res::Err &&
1050 this.ambiguity_errors.is_empty() && this.privacy_errors.is_empty() {
1051 let msg = "cannot determine resolution for the import";
1053 "import resolution is stuck, try simplifying other imports";
1054 this.session.struct_span_err(directive.span, msg).note(msg_note).emit();
1059 // FIXME: This assert may fire if public glob is later shadowed by a private
1060 // single import (see test `issue-55884-2.rs`). In theory single imports should
1061 // always block globs, even if they are not yet resolved, so that this kind of
1062 // self-inconsistent resolution never happens.
1063 // Reenable the assert when the issue is fixed.
1064 // assert!(result[ns].get().is_err());
1070 let mut all_ns_failed = true;
1071 self.per_ns(|this, ns| if !type_ns_only || ns == TypeNS {
1072 let binding = this.resolve_ident_in_module(
1073 module, ident, ns, Some(&directive.parent_scope), true, directive.span
1075 if binding.is_ok() {
1076 all_ns_failed = false;
1080 return if all_ns_failed {
1081 let resolutions = match module {
1082 ModuleOrUniformRoot::Module(module) => Some(module.resolutions.borrow()),
1085 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
1086 let names = resolutions.filter_map(|(&(ref i, _), resolution)| {
1087 if *i == ident { return None; } // Never suggest the same name
1088 match *resolution.borrow() {
1089 NameResolution { binding: Some(name_binding), .. } => {
1090 match name_binding.kind {
1091 NameBindingKind::Import { binding, .. } => {
1092 match binding.kind {
1093 // Never suggest the name that has binding error
1094 // i.e., the name that cannot be previously resolved
1095 NameBindingKind::Res(Res::Err, _) => return None,
1102 NameResolution { ref single_imports, .. }
1103 if single_imports.is_empty() => None,
1108 let lev_suggestion = find_best_match_for_name(names, &ident.as_str(), None)
1110 (vec![(ident.span, suggestion.to_string())],
1111 String::from("a similar name exists in the module"),
1112 Applicability::MaybeIncorrect)
1115 let (suggestion, note) = match self.check_for_module_export_macro(
1116 directive, module, ident,
1118 Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1119 _ => (lev_suggestion, Vec::new()),
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)
1142 Some(UnresolvedImportError {
1143 span: directive.span,
1149 // `resolve_ident_in_module` reported a privacy error.
1150 self.import_dummy_binding(directive);
1155 let mut reexport_error = None;
1156 let mut any_successful_reexport = false;
1157 self.per_ns(|this, ns| {
1158 if let Ok(binding) = source_bindings[ns].get() {
1159 let vis = directive.vis.get();
1160 if !binding.pseudo_vis().is_at_least(vis, &*this) {
1161 reexport_error = Some((ns, binding));
1163 any_successful_reexport = true;
1168 // All namespaces must be re-exported with extra visibility for an error to occur.
1169 if !any_successful_reexport {
1170 let (ns, binding) = reexport_error.unwrap();
1171 if ns == TypeNS && binding.is_extern_crate() {
1172 let msg = format!("extern crate `{}` is private, and cannot be \
1173 re-exported (error E0365), consider declaring with \
1176 self.session.buffer_lint(PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1180 } else if ns == TypeNS {
1181 struct_span_err!(self.session, directive.span, E0365,
1182 "`{}` is private, and cannot be re-exported", ident)
1183 .span_label(directive.span, format!("re-export of private `{}`", ident))
1184 .note(&format!("consider declaring type or module `{}` with `pub`", ident))
1187 let msg = format!("`{}` is private, and cannot be re-exported", ident);
1189 format!("consider marking `{}` as `pub` in the imported module", ident);
1190 struct_span_err!(self.session, directive.span, E0364, "{}", &msg)
1191 .span_note(directive.span, ¬e_msg)
1196 if directive.module_path.len() <= 1 {
1197 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1198 // 2 segments, so the `resolve_path` above won't trigger it.
1199 let mut full_path = directive.module_path.clone();
1200 full_path.push(Segment::from_ident(ident));
1201 self.per_ns(|this, ns| {
1202 if let Ok(binding) = source_bindings[ns].get() {
1203 this.lint_if_path_starts_with_module(
1204 directive.crate_lint(),
1213 // Record what this import resolves to for later uses in documentation,
1214 // this may resolve to either a value or a type, but for documentation
1215 // purposes it's good enough to just favor one over the other.
1216 self.per_ns(|this, ns| if let Some(binding) = source_bindings[ns].get().ok() {
1217 this.import_res_map.entry(directive.id).or_default()[ns] = Some(binding.res());
1220 self.check_for_redundant_imports(
1228 debug!("(resolving single import) successfully resolved import");
1232 fn check_for_redundant_imports(
1235 directive: &'b ImportDirective<'b>,
1236 source_bindings: &PerNS<Cell<Result<&'b NameBinding<'b>, Determinacy>>>,
1237 target_bindings: &PerNS<Cell<Option<&'b NameBinding<'b>>>>,
1240 // Skip if the import was produced by a macro.
1241 if directive.parent_scope.expansion != ExpnId::root() {
1245 // Skip if we are inside a named module (in contrast to an anonymous
1246 // module defined by a block).
1247 if let ModuleKind::Def(..) = directive.parent_scope.module.kind {
1251 let mut is_redundant = PerNS {
1257 let mut redundant_span = PerNS {
1263 self.per_ns(|this, ns| if let Some(binding) = source_bindings[ns].get().ok() {
1264 if binding.res() == Res::Err {
1268 let orig_blacklisted_binding = mem::replace(
1269 &mut this.blacklisted_binding,
1270 target_bindings[ns].get()
1273 match this.early_resolve_ident_in_lexical_scope(
1275 ScopeSet::Import(ns),
1276 &directive.parent_scope,
1281 Ok(other_binding) => {
1282 is_redundant[ns] = Some(
1283 binding.res() == other_binding.res()
1284 && !other_binding.is_ambiguity()
1286 redundant_span[ns] =
1287 Some((other_binding.span, other_binding.is_import()));
1289 Err(_) => is_redundant[ns] = Some(false)
1292 this.blacklisted_binding = orig_blacklisted_binding;
1295 if !is_redundant.is_empty() &&
1296 is_redundant.present_items().all(|is_redundant| is_redundant)
1298 let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1299 redundant_spans.sort();
1300 redundant_spans.dedup();
1301 self.session.buffer_lint_with_diagnostic(
1305 &format!("the item `{}` is imported redundantly", ident),
1306 BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident),
1311 fn resolve_glob_import(&mut self, directive: &'b ImportDirective<'b>) {
1312 let module = match directive.imported_module.get().unwrap() {
1313 ModuleOrUniformRoot::Module(module) => module,
1315 self.session.span_err(directive.span, "cannot glob-import all possible crates");
1320 self.populate_module_if_necessary(module);
1322 if module.is_trait() {
1323 self.session.span_err(directive.span, "items in traits are not importable.");
1325 } else if module.def_id() == directive.parent_scope.module.def_id() {
1327 } else if let GlobImport { is_prelude: true, .. } = directive.subclass {
1328 self.prelude = Some(module);
1332 // Add to module's glob_importers
1333 module.glob_importers.borrow_mut().push(directive);
1335 // Ensure that `resolutions` isn't borrowed during `try_define`,
1336 // since it might get updated via a glob cycle.
1337 let bindings = module.resolutions.borrow().iter().filter_map(|(&ident, resolution)| {
1338 resolution.borrow().binding().map(|binding| (ident, binding))
1339 }).collect::<Vec<_>>();
1340 for ((mut ident, ns), binding) in bindings {
1341 let scope = match ident.span.reverse_glob_adjust(module.expansion, directive.span) {
1342 Some(Some(def)) => self.macro_def_scope(def),
1343 Some(None) => self.current_module,
1346 if self.is_accessible_from(binding.pseudo_vis(), scope) {
1347 let imported_binding = self.import(binding, directive);
1348 let _ = self.try_define(directive.parent_scope.module, ident, ns, imported_binding);
1352 // Record the destination of this import
1353 self.record_partial_res(directive.id, PartialRes::new(module.res().unwrap()));
1356 // Miscellaneous post-processing, including recording re-exports,
1357 // reporting conflicts, and reporting unresolved imports.
1358 fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1359 // Since import resolution is finished, globs will not define any more names.
1360 *module.globs.borrow_mut() = Vec::new();
1362 let mut reexports = Vec::new();
1364 for (&(ident, ns), resolution) in module.resolutions.borrow().iter() {
1365 let resolution = &mut *resolution.borrow_mut();
1366 let binding = match resolution.binding {
1367 Some(binding) => binding,
1371 // Filter away ambiguous and gensymed imports. Gensymed imports
1372 // (e.g. implicitly injected `std`) cannot be properly encoded in metadata,
1373 // so they can cause name conflict errors downstream.
1374 let is_good_import = binding.is_import() && !binding.is_ambiguity() &&
1375 // Note that as_str() de-gensyms the Symbol
1376 !(ident.is_gensymed() && ident.name.as_str() != "_");
1377 if is_good_import || binding.is_macro_def() {
1378 let res = binding.res();
1379 if res != Res::Err {
1380 if let Some(def_id) = res.opt_def_id() {
1381 if !def_id.is_local() {
1382 self.cstore.export_macros_untracked(def_id.krate);
1385 reexports.push(Export {
1386 ident: ident.modern(),
1394 if let NameBindingKind::Import { binding: orig_binding, directive, .. } = binding.kind {
1395 if ns == TypeNS && orig_binding.is_variant() &&
1396 !orig_binding.vis.is_at_least(binding.vis, &*self) {
1397 let msg = match directive.subclass {
1398 ImportDirectiveSubclass::SingleImport { .. } => {
1399 format!("variant `{}` is private and cannot be re-exported",
1402 ImportDirectiveSubclass::GlobImport { .. } => {
1403 let msg = "enum is private and its variants \
1404 cannot be re-exported".to_owned();
1405 let error_id = (DiagnosticMessageId::ErrorId(0), // no code?!
1408 let fresh = self.session.one_time_diagnostics
1409 .borrow_mut().insert(error_id);
1415 ref s @ _ => bug!("unexpected import subclass {:?}", s)
1417 let mut err = self.session.struct_span_err(binding.span, &msg);
1419 let imported_module = match directive.imported_module.get() {
1420 Some(ModuleOrUniformRoot::Module(module)) => module,
1421 _ => bug!("module should exist"),
1423 let resolutions = imported_module.parent.expect("parent should exist")
1424 .resolutions.borrow();
1425 let enum_path_segment_index = directive.module_path.len() - 1;
1426 let enum_ident = directive.module_path[enum_path_segment_index].ident;
1428 let enum_resolution = resolutions.get(&(enum_ident, TypeNS))
1429 .expect("resolution should exist");
1430 let enum_span = enum_resolution.borrow()
1431 .binding.expect("binding should exist")
1433 let enum_def_span = self.session.source_map().def_span(enum_span);
1434 let enum_def_snippet = self.session.source_map()
1435 .span_to_snippet(enum_def_span).expect("snippet should exist");
1436 // potentially need to strip extant `crate`/`pub(path)` for suggestion
1437 let after_vis_index = enum_def_snippet.find("enum")
1438 .expect("`enum` keyword should exist in snippet");
1439 let suggestion = format!("pub {}",
1440 &enum_def_snippet[after_vis_index..]);
1443 .diag_span_suggestion_once(&mut err,
1444 DiagnosticMessageId::ErrorId(0),
1446 "consider making the enum public",
1453 if reexports.len() > 0 {
1454 if let Some(def_id) = module.def_id() {
1455 self.export_map.insert(def_id, reexports);
1461 fn import_path_to_string(names: &[Ident],
1462 subclass: &ImportDirectiveSubclass<'_>,
1463 span: Span) -> String {
1464 let pos = names.iter()
1465 .position(|p| span == p.span && p.name != kw::PathRoot);
1466 let global = !names.is_empty() && names[0].name == kw::PathRoot;
1467 if let Some(pos) = pos {
1468 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1469 names_to_string(names)
1471 let names = if global { &names[1..] } else { names };
1472 if names.is_empty() {
1473 import_directive_subclass_to_string(subclass)
1476 names_to_string(names),
1477 import_directive_subclass_to_string(subclass))
1482 fn import_directive_subclass_to_string(subclass: &ImportDirectiveSubclass<'_>) -> String {
1484 SingleImport { source, .. } => source.to_string(),
1485 GlobImport { .. } => "*".to_string(),
1486 ExternCrate { .. } => "<extern crate>".to_string(),
1487 MacroUse => "#[macro_use]".to_string(),