1 //! A bunch of methods and structures more or less related to resolving imports.
3 use crate::diagnostics::Suggestion;
4 use crate::Determinacy::{self, *};
5 use crate::Namespace::{self, MacroNS, TypeNS};
6 use crate::{module_to_string, names_to_string};
7 use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind};
8 use crate::{BindingKey, ModuleKind, ResolutionError, Resolver, Segment};
9 use crate::{Finalize, Module, ModuleOrUniformRoot, ParentScope, PerNS, ScopeSet, Weak};
10 use crate::{NameBinding, NameBindingKind, PathResult, PrivacyError, ToNameBinding};
12 use rustc_ast::NodeId;
13 use rustc_data_structures::fx::FxHashSet;
14 use rustc_data_structures::intern::Interned;
15 use rustc_errors::{pluralize, struct_span_err, Applicability, MultiSpan};
16 use rustc_hir::def::{self, PartialRes};
17 use rustc_hir::def_id::DefId;
18 use rustc_middle::metadata::ModChild;
19 use rustc_middle::span_bug;
21 use rustc_session::lint::builtin::{PUB_USE_OF_PRIVATE_EXTERN_CRATE, UNUSED_IMPORTS};
22 use rustc_session::lint::BuiltinLintDiagnostics;
23 use rustc_span::hygiene::LocalExpnId;
24 use rustc_span::lev_distance::find_best_match_for_name;
25 use rustc_span::symbol::{kw, Ident, Symbol};
33 type Res = def::Res<NodeId>;
35 /// Contains data for specific kinds of imports.
36 #[derive(Clone, Debug)]
37 pub enum ImportKind<'a> {
39 /// `source` in `use prefix::source as target`.
41 /// `target` in `use prefix::source as target`.
43 /// Bindings to which `source` refers to.
44 source_bindings: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
45 /// Bindings introduced by `target`.
46 target_bindings: PerNS<Cell<Option<&'a NameBinding<'a>>>>,
47 /// `true` for `...::{self [as target]}` imports, `false` otherwise.
49 /// Did this import result from a nested import? ie. `use foo::{bar, baz};`
51 /// Additional `NodeId`s allocated to a `ast::UseTree` for automatically generated `use` statement
52 /// (eg. implicit struct constructors)
53 additional_ids: (NodeId, NodeId),
57 max_vis: Cell<ty::Visibility>, // The visibility of the greatest re-export.
58 // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
61 source: Option<Symbol>,
68 #[derive(Debug, Clone)]
69 crate struct Import<'a> {
70 pub kind: ImportKind<'a>,
72 /// The ID of the `extern crate`, `UseTree` etc that imported this `Import`.
74 /// In the case where the `Import` was expanded from a "nested" use tree,
75 /// this id is the ID of the leaf tree. For example:
77 /// ```ignore (pacify the merciless tidy)
78 /// use foo::bar::{a, b}
81 /// If this is the import for `foo::bar::a`, we would have the ID of the `UseTree`
82 /// for `a` in this field.
85 /// The `id` of the "root" use-kind -- this is always the same as
86 /// `id` except in the case of "nested" use trees, in which case
87 /// it will be the `id` of the root use tree. e.g., in the example
88 /// from `id`, this would be the ID of the `use foo::bar`
92 /// Span of the entire use statement.
95 /// Span of the entire use statement with attributes.
96 pub use_span_with_attributes: Span,
98 /// Did the use statement have any attributes?
99 pub has_attributes: bool,
101 /// Span of this use tree.
104 /// Span of the *root* use tree (see `root_id`).
107 pub parent_scope: ParentScope<'a>,
108 pub module_path: Vec<Segment>,
109 /// The resolution of `module_path`.
110 pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>,
111 pub vis: Cell<ty::Visibility>,
112 pub used: Cell<bool>,
115 impl<'a> Import<'a> {
116 pub fn is_glob(&self) -> bool {
117 matches!(self.kind, ImportKind::Glob { .. })
120 pub fn is_nested(&self) -> bool {
122 ImportKind::Single { nested, .. } => nested,
128 #[derive(Clone, Default, Debug)]
129 /// Records information about the resolution of a name in a namespace of a module.
130 pub struct NameResolution<'a> {
131 /// Single imports that may define the name in the namespace.
132 /// Imports are arena-allocated, so it's ok to use pointers as keys.
133 single_imports: FxHashSet<Interned<'a, Import<'a>>>,
134 /// The least shadowable known binding for this name, or None if there are no known bindings.
135 pub binding: Option<&'a NameBinding<'a>>,
136 shadowed_glob: Option<&'a NameBinding<'a>>,
139 impl<'a> NameResolution<'a> {
140 // Returns the binding for the name if it is known or None if it not known.
141 pub(crate) fn binding(&self) -> Option<&'a NameBinding<'a>> {
142 self.binding.and_then(|binding| {
143 if !binding.is_glob_import() || self.single_imports.is_empty() {
151 crate fn add_single_import(&mut self, import: &'a Import<'a>) {
152 self.single_imports.insert(Interned::new_unchecked(import));
156 // Reexports of the form `pub use foo as bar;` where `foo` is `extern crate foo;`
157 // are permitted for backward-compatibility under a deprecation lint.
158 fn pub_use_of_private_extern_crate_hack(import: &Import<'_>, binding: &NameBinding<'_>) -> bool {
159 match (&import.kind, &binding.kind) {
161 ImportKind::Single { .. },
162 NameBindingKind::Import {
163 import: Import { kind: ImportKind::ExternCrate { .. }, .. },
166 ) => import.vis.get().is_public(),
171 impl<'a> Resolver<'a> {
172 crate fn resolve_ident_in_module_unadjusted(
174 module: ModuleOrUniformRoot<'a>,
177 parent_scope: &ParentScope<'a>,
178 finalize: Option<Span>,
179 ) -> Result<&'a NameBinding<'a>, Determinacy> {
180 self.resolve_ident_in_module_unadjusted_ext(
188 .map_err(|(determinacy, _)| determinacy)
191 /// Attempts to resolve `ident` in namespaces `ns` of `module`.
192 /// Invariant: if `finalize` is `Some`, expansion and import resolution must be complete.
193 crate fn resolve_ident_in_module_unadjusted_ext(
195 module: ModuleOrUniformRoot<'a>,
198 parent_scope: &ParentScope<'a>,
199 restricted_shadowing: bool,
200 finalize: Option<Span>,
201 ) -> Result<&'a NameBinding<'a>, (Determinacy, Weak)> {
202 let module = match module {
203 ModuleOrUniformRoot::Module(module) => module,
204 ModuleOrUniformRoot::CrateRootAndExternPrelude => {
205 assert!(!restricted_shadowing);
206 let binding = self.early_resolve_ident_in_lexical_scope(
208 ScopeSet::AbsolutePath(ns),
213 return binding.map_err(|determinacy| (determinacy, Weak::No));
215 ModuleOrUniformRoot::ExternPrelude => {
216 assert!(!restricted_shadowing);
217 return if ns != TypeNS {
218 Err((Determined, Weak::No))
219 } else if let Some(binding) = self.extern_prelude_get(ident, finalize.is_some()) {
221 } else if !self.graph_root.unexpanded_invocations.borrow().is_empty() {
222 // Macro-expanded `extern crate` items can add names to extern prelude.
223 Err((Undetermined, Weak::No))
225 Err((Determined, Weak::No))
228 ModuleOrUniformRoot::CurrentScope => {
229 assert!(!restricted_shadowing);
231 if ident.name == kw::Crate || ident.name == kw::DollarCrate {
232 let module = self.resolve_crate_root(ident);
234 (module, ty::Visibility::Public, module.span, LocalExpnId::ROOT)
235 .to_name_binding(self.arenas);
237 } else if ident.name == kw::Super || ident.name == kw::SelfLower {
238 // FIXME: Implement these with renaming requirements so that e.g.
239 // `use super;` doesn't work, but `use super as name;` does.
240 // Fall through here to get an error from `early_resolve_...`.
244 let scopes = ScopeSet::All(ns, true);
245 let binding = self.early_resolve_ident_in_lexical_scope(
252 return binding.map_err(|determinacy| (determinacy, Weak::No));
256 let key = self.new_key(ident, ns);
258 self.resolution(module, key).try_borrow_mut().map_err(|_| (Determined, Weak::No))?; // This happens when there is a cycle of imports.
260 if let Some(binding) = resolution.binding && let Some(path_span) = finalize {
261 if !restricted_shadowing && binding.expansion != LocalExpnId::ROOT {
262 if let NameBindingKind::Res(_, true) = binding.kind {
263 self.macro_expanded_macro_export_errors.insert((path_span, binding.span));
268 let check_usable = |this: &mut Self, binding: &'a NameBinding<'a>| {
269 if let Some(unusable_binding) = this.unusable_binding {
270 if ptr::eq(binding, unusable_binding) {
271 return Err((Determined, Weak::No));
274 let usable = this.is_accessible_from(binding.vis, parent_scope.module);
275 if usable { Ok(binding) } else { Err((Determined, Weak::No)) }
278 if let Some(path_span) = finalize {
281 .and_then(|binding| {
282 // If the primary binding is unusable, search further and return the shadowed glob
283 // binding if it exists. What we really want here is having two separate scopes in
284 // a module - one for non-globs and one for globs, but until that's done use this
285 // hack to avoid inconsistent resolution ICEs during import validation.
286 if let Some(unusable_binding) = self.unusable_binding {
287 if ptr::eq(binding, unusable_binding) {
288 return resolution.shadowed_glob;
293 .ok_or((Determined, Weak::No))
294 .and_then(|binding| {
295 if self.last_import_segment && check_usable(self, binding).is_err() {
296 Err((Determined, Weak::No))
298 self.record_use(ident, binding, restricted_shadowing);
300 if let Some(shadowed_glob) = resolution.shadowed_glob {
301 // Forbid expanded shadowing to avoid time travel.
302 if restricted_shadowing
303 && binding.expansion != LocalExpnId::ROOT
304 && binding.res() != shadowed_glob.res()
306 self.ambiguity_errors.push(AmbiguityError {
307 kind: AmbiguityKind::GlobVsExpanded,
311 misc1: AmbiguityErrorMisc::None,
312 misc2: AmbiguityErrorMisc::None,
317 if !self.is_accessible_from(binding.vis, parent_scope.module) {
318 self.privacy_errors.push(PrivacyError {
321 dedup_span: path_span,
330 // Items and single imports are not shadowable, if we have one, then it's determined.
331 if let Some(binding) = resolution.binding {
332 if !binding.is_glob_import() {
333 return check_usable(self, binding);
337 // --- From now on we either have a glob resolution or no resolution. ---
339 // Check if one of single imports can still define the name,
340 // if it can then our result is not determined and can be invalidated.
341 for single_import in &resolution.single_imports {
342 if !self.is_accessible_from(single_import.vis.get(), parent_scope.module) {
345 let Some(module) = single_import.imported_module.get() else {
346 return Err((Undetermined, Weak::No));
348 let ImportKind::Single { source: ident, .. } = single_import.kind else {
351 match self.resolve_ident_in_module(module, ident, ns, &single_import.parent_scope, None)
353 Err(Determined) => continue,
355 if !self.is_accessible_from(binding.vis, single_import.parent_scope.module) =>
359 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::No)),
363 // So we have a resolution that's from a glob import. This resolution is determined
364 // if it cannot be shadowed by some new item/import expanded from a macro.
365 // This happens either if there are no unexpanded macros, or expanded names cannot
366 // shadow globs (that happens in macro namespace or with restricted shadowing).
368 // Additionally, any macro in any module can plant names in the root module if it creates
369 // `macro_export` macros, so the root module effectively has unresolved invocations if any
370 // module has unresolved invocations.
371 // However, it causes resolution/expansion to stuck too often (#53144), so, to make
372 // progress, we have to ignore those potential unresolved invocations from other modules
373 // and prohibit access to macro-expanded `macro_export` macros instead (unless restricted
374 // shadowing is enabled, see `macro_expanded_macro_export_errors`).
375 let unexpanded_macros = !module.unexpanded_invocations.borrow().is_empty();
376 if let Some(binding) = resolution.binding {
377 if !unexpanded_macros || ns == MacroNS || restricted_shadowing {
378 return check_usable(self, binding);
380 return Err((Undetermined, Weak::No));
384 // --- From now on we have no resolution. ---
386 // Now we are in situation when new item/import can appear only from a glob or a macro
387 // expansion. With restricted shadowing names from globs and macro expansions cannot
388 // shadow names from outer scopes, so we can freely fallback from module search to search
389 // in outer scopes. For `early_resolve_ident_in_lexical_scope` to continue search in outer
390 // scopes we return `Undetermined` with `Weak::Yes`.
392 // Check if one of unexpanded macros can still define the name,
393 // if it can then our "no resolution" result is not determined and can be invalidated.
394 if unexpanded_macros {
395 return Err((Undetermined, Weak::Yes));
398 // Check if one of glob imports can still define the name,
399 // if it can then our "no resolution" result is not determined and can be invalidated.
400 for glob_import in module.globs.borrow().iter() {
401 if !self.is_accessible_from(glob_import.vis.get(), parent_scope.module) {
404 let module = match glob_import.imported_module.get() {
405 Some(ModuleOrUniformRoot::Module(module)) => module,
407 None => return Err((Undetermined, Weak::Yes)),
409 let tmp_parent_scope;
410 let (mut adjusted_parent_scope, mut ident) =
411 (parent_scope, ident.normalize_to_macros_2_0());
412 match ident.span.glob_adjust(module.expansion, glob_import.span) {
415 ParentScope { module: self.expn_def_scope(def), ..*parent_scope };
416 adjusted_parent_scope = &tmp_parent_scope;
421 let result = self.resolve_ident_in_module_unadjusted(
422 ModuleOrUniformRoot::Module(module),
425 adjusted_parent_scope,
430 Err(Determined) => continue,
432 if !self.is_accessible_from(binding.vis, glob_import.parent_scope.module) =>
436 Ok(_) | Err(Undetermined) => return Err((Undetermined, Weak::Yes)),
440 // No resolution and no one else can define the name - determinate error.
441 Err((Determined, Weak::No))
444 // Given a binding and an import that resolves to it,
445 // return the corresponding binding defined by the import.
448 binding: &'a NameBinding<'a>,
449 import: &'a Import<'a>,
450 ) -> &'a NameBinding<'a> {
451 let vis = if binding.vis.is_at_least(import.vis.get(), self)
452 || pub_use_of_private_extern_crate_hack(import, binding)
459 if let ImportKind::Glob { ref max_vis, .. } = import.kind {
460 if vis == import.vis.get() || vis.is_at_least(max_vis.get(), self) {
465 self.arenas.alloc_name_binding(NameBinding {
466 kind: NameBindingKind::Import { binding, import, used: Cell::new(false) },
470 expansion: import.parent_scope.expansion,
474 // Define the name or return the existing binding if there is a collision.
479 binding: &'a NameBinding<'a>,
480 ) -> Result<(), &'a NameBinding<'a>> {
481 let res = binding.res();
482 self.check_reserved_macro_name(key.ident, res);
483 self.set_binding_parent_module(binding, module);
484 self.update_resolution(module, key, |this, resolution| {
485 if let Some(old_binding) = resolution.binding {
487 // Do not override real bindings with `Res::Err`s from error recovery.
490 match (old_binding.is_glob_import(), binding.is_glob_import()) {
492 if res != old_binding.res() {
493 resolution.binding = Some(this.ambiguity(
494 AmbiguityKind::GlobVsGlob,
498 } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
499 // We are glob-importing the same item but with greater visibility.
500 resolution.binding = Some(binding);
503 (old_glob @ true, false) | (old_glob @ false, true) => {
504 let (glob_binding, nonglob_binding) =
505 if old_glob { (old_binding, binding) } else { (binding, old_binding) };
506 if glob_binding.res() != nonglob_binding.res()
508 && nonglob_binding.expansion != LocalExpnId::ROOT
510 resolution.binding = Some(this.ambiguity(
511 AmbiguityKind::GlobVsExpanded,
516 resolution.binding = Some(nonglob_binding);
518 resolution.shadowed_glob = Some(glob_binding);
521 return Err(old_binding);
525 resolution.binding = Some(binding);
535 primary_binding: &'a NameBinding<'a>,
536 secondary_binding: &'a NameBinding<'a>,
537 ) -> &'a NameBinding<'a> {
538 self.arenas.alloc_name_binding(NameBinding {
539 ambiguity: Some((secondary_binding, kind)),
540 ..primary_binding.clone()
544 // Use `f` to mutate the resolution of the name in the module.
545 // If the resolution becomes a success, define it in the module's glob importers.
546 fn update_resolution<T, F>(&mut self, module: Module<'a>, key: BindingKey, f: F) -> T
548 F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T,
550 // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
551 // during which the resolution might end up getting re-defined via a glob cycle.
553 let resolution = &mut *self.resolution(module, key).borrow_mut();
554 let old_binding = resolution.binding();
556 let t = f(self, resolution);
558 match resolution.binding() {
559 _ if old_binding.is_some() => return t,
561 Some(binding) => match old_binding {
562 Some(old_binding) if ptr::eq(old_binding, binding) => return t,
568 // Define `binding` in `module`s glob importers.
569 for import in module.glob_importers.borrow_mut().iter() {
570 let mut ident = key.ident;
571 let scope = match ident.span.reverse_glob_adjust(module.expansion, import.span) {
572 Some(Some(def)) => self.expn_def_scope(def),
573 Some(None) => import.parent_scope.module,
576 if self.is_accessible_from(binding.vis, scope) {
577 let imported_binding = self.import(binding, import);
578 let key = BindingKey { ident, ..key };
579 let _ = self.try_define(import.parent_scope.module, key, imported_binding);
586 // Define a "dummy" resolution containing a Res::Err as a placeholder for a
588 fn import_dummy_binding(&mut self, import: &'a Import<'a>) {
589 if let ImportKind::Single { target, .. } = import.kind {
590 let dummy_binding = self.dummy_binding;
591 let dummy_binding = self.import(dummy_binding, import);
592 self.per_ns(|this, ns| {
593 let key = this.new_key(target, ns);
594 let _ = this.try_define(import.parent_scope.module, key, dummy_binding);
596 // Consider erroneous imports used to avoid duplicate diagnostics.
597 self.record_use(target, dummy_binding, false);
602 /// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
603 /// import errors within the same use tree into a single diagnostic.
604 #[derive(Debug, Clone)]
605 struct UnresolvedImportError {
607 label: Option<String>,
609 suggestion: Option<Suggestion>,
612 pub struct ImportResolver<'a, 'b> {
613 pub r: &'a mut Resolver<'b>,
616 impl<'a, 'b> ty::DefIdTree for &'a ImportResolver<'a, 'b> {
617 fn parent(self, id: DefId) -> Option<DefId> {
622 impl<'a, 'b> ImportResolver<'a, 'b> {
625 // This is a fixed-point algorithm. We resolve imports until our efforts
626 // are stymied by an unresolved import; then we bail out of the current
627 // module and continue. We terminate successfully once no more imports
628 // remain or unsuccessfully when no forward progress in resolving imports
631 /// Resolves all imports for the crate. This method performs the fixed-
633 pub fn resolve_imports(&mut self) {
634 let mut prev_num_indeterminates = self.r.indeterminate_imports.len() + 1;
635 while self.r.indeterminate_imports.len() < prev_num_indeterminates {
636 prev_num_indeterminates = self.r.indeterminate_imports.len();
637 for import in mem::take(&mut self.r.indeterminate_imports) {
638 match self.resolve_import(&import) {
639 true => self.r.determined_imports.push(import),
640 false => self.r.indeterminate_imports.push(import),
646 pub fn finalize_imports(&mut self) {
647 for module in self.r.arenas.local_modules().iter() {
648 self.finalize_resolutions_in(module);
651 let mut seen_spans = FxHashSet::default();
652 let mut errors = vec![];
653 let mut prev_root_id: NodeId = NodeId::from_u32(0);
654 let determined_imports = mem::take(&mut self.r.determined_imports);
655 let indeterminate_imports = mem::take(&mut self.r.indeterminate_imports);
657 for (is_indeterminate, import) in determined_imports
660 .chain(indeterminate_imports.into_iter().map(|i| (true, i)))
662 if let Some(err) = self.finalize_import(import) {
663 if let ImportKind::Single { source, ref source_bindings, .. } = import.kind {
664 if source.name == kw::SelfLower {
665 // Silence `unresolved import` error if E0429 is already emitted
666 if let Err(Determined) = source_bindings.value_ns.get() {
672 // If the error is a single failed import then create a "fake" import
673 // resolution for it so that later resolve stages won't complain.
674 self.r.import_dummy_binding(import);
675 if prev_root_id.as_u32() != 0
676 && prev_root_id.as_u32() != import.root_id.as_u32()
677 && !errors.is_empty()
679 // In the case of a new import line, throw a diagnostic message
680 // for the previous line.
681 self.throw_unresolved_import_error(errors, None);
684 if seen_spans.insert(err.span) {
685 let path = import_path_to_string(
686 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
690 errors.push((path, err));
691 prev_root_id = import.root_id;
693 } else if is_indeterminate {
694 // Consider erroneous imports used to avoid duplicate diagnostics.
695 self.r.used_imports.insert(import.id);
696 let path = import_path_to_string(
697 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
701 let err = UnresolvedImportError {
707 if path.contains("::") {
708 errors.push((path, err))
713 if !errors.is_empty() {
714 self.throw_unresolved_import_error(errors, None);
718 fn throw_unresolved_import_error(
720 errors: Vec<(String, UnresolvedImportError)>,
721 span: Option<MultiSpan>,
723 /// Upper limit on the number of `span_label` messages.
724 const MAX_LABEL_COUNT: usize = 10;
726 let (span, msg) = if errors.is_empty() {
727 (span.unwrap(), "unresolved import".to_string())
729 let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
731 let paths = errors.iter().map(|(path, _)| format!("`{}`", path)).collect::<Vec<_>>();
733 let msg = format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);
738 let mut diag = struct_span_err!(self.r.session, span, E0432, "{}", &msg);
740 if let Some((_, UnresolvedImportError { note, .. })) = errors.iter().last() {
741 for message in note {
746 for (_, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
747 if let Some(label) = err.label {
748 diag.span_label(err.span, label);
751 if let Some((suggestions, msg, applicability)) = err.suggestion {
752 diag.multipart_suggestion(&msg, suggestions, applicability);
759 /// Attempts to resolve the given import, returning true if its resolution is determined.
760 /// If successful, the resolved bindings are written into the module.
761 fn resolve_import(&mut self, import: &'b Import<'b>) -> bool {
763 "(resolving import for module) resolving import `{}::...` in `{}`",
764 Segment::names_to_string(&import.module_path),
765 module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
768 let module = if let Some(module) = import.imported_module.get() {
771 // For better failure detection, pretend that the import will
772 // not define any names while resolving its module path.
773 let orig_vis = import.vis.replace(ty::Visibility::Invisible);
775 self.r.resolve_path(&import.module_path, None, &import.parent_scope, Finalize::No);
776 import.vis.set(orig_vis);
779 PathResult::Module(module) => module,
780 PathResult::Indeterminate => return false,
781 PathResult::NonModule(..) | PathResult::Failed { .. } => return true,
785 import.imported_module.set(Some(module));
786 let (source, target, source_bindings, target_bindings, type_ns_only) = match import.kind {
794 } => (source, target, source_bindings, target_bindings, type_ns_only),
795 ImportKind::Glob { .. } => {
796 self.resolve_glob_import(import);
802 let mut indeterminate = false;
803 self.r.per_ns(|this, ns| {
804 if !type_ns_only || ns == TypeNS {
805 if let Err(Undetermined) = source_bindings[ns].get() {
806 // For better failure detection, pretend that the import will
807 // not define any names while resolving its module path.
808 let orig_vis = import.vis.replace(ty::Visibility::Invisible);
809 let binding = this.resolve_ident_in_module(
813 &import.parent_scope,
816 import.vis.set(orig_vis);
817 source_bindings[ns].set(binding);
822 let parent = import.parent_scope.module;
823 match source_bindings[ns].get() {
824 Err(Undetermined) => indeterminate = true,
825 // Don't update the resolution, because it was never added.
826 Err(Determined) if target.name == kw::Underscore => {}
828 let key = this.new_key(target, ns);
829 this.update_resolution(parent, key, |_, resolution| {
830 resolution.single_imports.remove(&Interned::new_unchecked(import));
833 Ok(binding) if !binding.is_importable() => {
834 let msg = format!("`{}` is not directly importable", target);
835 struct_span_err!(this.session, import.span, E0253, "{}", &msg)
836 .span_label(import.span, "cannot be imported directly")
838 // Do not import this illegal binding. Import a dummy binding and pretend
839 // everything is fine
840 this.import_dummy_binding(import);
843 let imported_binding = this.import(binding, import);
844 target_bindings[ns].set(Some(imported_binding));
845 this.define(parent, target, ns, imported_binding);
854 /// Performs final import resolution, consistency checks and error reporting.
856 /// Optionally returns an unresolved import error. This error is buffered and used to
857 /// consolidate multiple unresolved import errors into a single diagnostic.
858 fn finalize_import(&mut self, import: &'b Import<'b>) -> Option<UnresolvedImportError> {
859 let orig_vis = import.vis.replace(ty::Visibility::Invisible);
860 let orig_unusable_binding = match &import.kind {
861 ImportKind::Single { target_bindings, .. } => {
862 Some(mem::replace(&mut self.r.unusable_binding, target_bindings[TypeNS].get()))
866 let prev_ambiguity_errors_len = self.r.ambiguity_errors.len();
867 let finalize = Finalize::UsePath {
868 root_id: import.root_id,
869 root_span: import.root_span,
870 path_span: import.span,
873 self.r.resolve_path(&import.module_path, None, &import.parent_scope, finalize);
874 let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len;
875 if let Some(orig_unusable_binding) = orig_unusable_binding {
876 self.r.unusable_binding = orig_unusable_binding;
878 import.vis.set(orig_vis);
879 if let PathResult::Failed { .. } | PathResult::NonModule(..) = path_res {
880 // Consider erroneous imports used to avoid duplicate diagnostics.
881 self.r.used_imports.insert(import.id);
883 let module = match path_res {
884 PathResult::Module(module) => {
885 // Consistency checks, analogous to `finalize_macro_resolutions`.
886 if let Some(initial_module) = import.imported_module.get() {
887 if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
888 span_bug!(import.span, "inconsistent resolution for an import");
890 } else if self.r.privacy_errors.is_empty() {
891 let msg = "cannot determine resolution for the import";
892 let msg_note = "import resolution is stuck, try simplifying other imports";
893 self.r.session.struct_span_err(import.span, msg).note(msg_note).emit();
898 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
900 assert!(import.imported_module.get().is_none());
902 .report_error(span, ResolutionError::FailedToResolve { label, suggestion });
906 PathResult::Failed { is_error_from_last_segment: true, span, label, suggestion } => {
908 assert!(import.imported_module.get().is_none());
909 let err = match self.make_path_suggestion(
911 import.module_path.clone(),
912 &import.parent_scope,
914 Some((suggestion, note)) => UnresolvedImportError {
919 vec![(span, Segment::names_to_string(&suggestion))],
920 String::from("a similar path exists"),
921 Applicability::MaybeIncorrect,
924 None => UnresolvedImportError {
935 PathResult::NonModule(_) => {
937 assert!(import.imported_module.get().is_none());
939 // The error was already reported earlier.
942 PathResult::Indeterminate => unreachable!(),
945 let (ident, target, source_bindings, target_bindings, type_ns_only) = match import.kind {
953 } => (source, target, source_bindings, target_bindings, type_ns_only),
954 ImportKind::Glob { is_prelude, ref max_vis } => {
955 if import.module_path.len() <= 1 {
956 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
957 // 2 segments, so the `resolve_path` above won't trigger it.
958 let mut full_path = import.module_path.clone();
959 full_path.push(Segment::from_ident(Ident::empty()));
960 self.r.lint_if_path_starts_with_module(finalize, &full_path, None);
963 if let ModuleOrUniformRoot::Module(module) = module {
964 if ptr::eq(module, import.parent_scope.module) {
965 // Importing a module into itself is not allowed.
966 return Some(UnresolvedImportError {
968 label: Some(String::from("cannot glob-import a module into itself")),
975 max_vis.get() != ty::Visibility::Invisible && // Allow empty globs.
976 !max_vis.get().is_at_least(import.vis.get(), &*self)
978 let msg = "glob import doesn't reexport anything because no candidate is public enough";
979 self.r.lint_buffer.buffer_lint(UNUSED_IMPORTS, import.id, import.span, msg);
986 let mut all_ns_err = true;
987 self.r.per_ns(|this, ns| {
988 if !type_ns_only || ns == TypeNS {
989 let orig_vis = import.vis.replace(ty::Visibility::Invisible);
990 let orig_unusable_binding =
991 mem::replace(&mut this.unusable_binding, target_bindings[ns].get());
992 let orig_last_import_segment = mem::replace(&mut this.last_import_segment, true);
993 let binding = this.resolve_ident_in_module(
997 &import.parent_scope,
1000 this.last_import_segment = orig_last_import_segment;
1001 this.unusable_binding = orig_unusable_binding;
1002 import.vis.set(orig_vis);
1006 // Consistency checks, analogous to `finalize_macro_resolutions`.
1007 let initial_res = source_bindings[ns].get().map(|initial_binding| {
1009 if let Some(target_binding) = target_bindings[ns].get() {
1010 if target.name == kw::Underscore
1011 && initial_binding.is_extern_crate()
1012 && !initial_binding.is_import()
1017 import.module_path.is_empty(),
1021 initial_binding.res()
1023 let res = binding.res();
1024 if let Ok(initial_res) = initial_res {
1025 if res != initial_res && this.ambiguity_errors.is_empty() {
1026 span_bug!(import.span, "inconsistent resolution for an import");
1028 } else if res != Res::Err
1029 && this.ambiguity_errors.is_empty()
1030 && this.privacy_errors.is_empty()
1032 let msg = "cannot determine resolution for the import";
1034 "import resolution is stuck, try simplifying other imports";
1035 this.session.struct_span_err(import.span, msg).note(msg_note).emit();
1039 // FIXME: This assert may fire if public glob is later shadowed by a private
1040 // single import (see test `issue-55884-2.rs`). In theory single imports should
1041 // always block globs, even if they are not yet resolved, so that this kind of
1042 // self-inconsistent resolution never happens.
1043 // Re-enable the assert when the issue is fixed.
1044 // assert!(result[ns].get().is_err());
1051 let mut all_ns_failed = true;
1052 self.r.per_ns(|this, ns| {
1053 if !type_ns_only || ns == TypeNS {
1054 let binding = this.resolve_ident_in_module(
1058 &import.parent_scope,
1061 if binding.is_ok() {
1062 all_ns_failed = false;
1067 return if all_ns_failed {
1068 let resolutions = match module {
1069 ModuleOrUniformRoot::Module(module) => {
1070 Some(self.r.resolutions(module).borrow())
1074 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
1075 let names = resolutions
1076 .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
1079 } // Never suggest the same name
1080 match *resolution.borrow() {
1081 NameResolution { binding: Some(name_binding), .. } => {
1082 match name_binding.kind {
1083 NameBindingKind::Import { binding, .. } => {
1084 match binding.kind {
1085 // Never suggest the name that has binding error
1086 // i.e., the name that cannot be previously resolved
1087 NameBindingKind::Res(Res::Err, _) => None,
1094 NameResolution { ref single_imports, .. }
1095 if single_imports.is_empty() =>
1102 .collect::<Vec<Symbol>>();
1104 let lev_suggestion =
1105 find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
1107 vec![(ident.span, suggestion.to_string())],
1108 String::from("a similar name exists in the module"),
1109 Applicability::MaybeIncorrect,
1113 let (suggestion, note) =
1114 match self.check_for_module_export_macro(import, module, ident) {
1115 Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
1116 _ => (lev_suggestion, Vec::new()),
1119 let label = match module {
1120 ModuleOrUniformRoot::Module(module) => {
1121 let module_str = module_to_string(module);
1122 if let Some(module_str) = module_str {
1123 format!("no `{}` in `{}`", ident, module_str)
1125 format!("no `{}` in the root", ident)
1129 if !ident.is_path_segment_keyword() {
1130 format!("no external crate `{}`", ident)
1132 // HACK(eddyb) this shows up for `self` & `super`, which
1133 // should work instead - for now keep the same error message.
1134 format!("no `{}` in the root", ident)
1139 Some(UnresolvedImportError {
1146 // `resolve_ident_in_module` reported a privacy error.
1147 self.r.import_dummy_binding(import);
1152 let mut reexport_error = None;
1153 let mut any_successful_reexport = false;
1154 let mut crate_private_reexport = false;
1155 self.r.per_ns(|this, ns| {
1156 if let Ok(binding) = source_bindings[ns].get() {
1157 let vis = import.vis.get();
1158 if !binding.vis.is_at_least(vis, &*this) {
1159 reexport_error = Some((ns, binding));
1160 if let ty::Visibility::Restricted(binding_def_id) = binding.vis {
1161 if binding_def_id.is_top_level_module() {
1162 crate_private_reexport = true;
1166 any_successful_reexport = true;
1171 // All namespaces must be re-exported with extra visibility for an error to occur.
1172 if !any_successful_reexport {
1173 let (ns, binding) = reexport_error.unwrap();
1174 if pub_use_of_private_extern_crate_hack(import, binding) {
1176 "extern crate `{}` is private, and cannot be \
1177 re-exported (error E0365), consider declaring with \
1181 self.r.lint_buffer.buffer_lint(
1182 PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1188 let error_msg = if crate_private_reexport {
1190 "`{}` is only public within the crate, and cannot be re-exported outside",
1194 format!("`{}` is private, and cannot be re-exported", ident)
1198 let label_msg = if crate_private_reexport {
1199 format!("re-export of crate public `{}`", ident)
1201 format!("re-export of private `{}`", ident)
1204 struct_span_err!(self.r.session, import.span, E0365, "{}", error_msg)
1205 .span_label(import.span, label_msg)
1206 .note(&format!("consider declaring type or module `{}` with `pub`", ident))
1210 format!("consider marking `{}` as `pub` in the imported module", ident);
1211 struct_span_err!(self.r.session, import.span, E0364, "{}", error_msg)
1212 .span_note(import.span, ¬e_msg)
1218 if import.module_path.len() <= 1 {
1219 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1220 // 2 segments, so the `resolve_path` above won't trigger it.
1221 let mut full_path = import.module_path.clone();
1222 full_path.push(Segment::from_ident(ident));
1223 self.r.per_ns(|this, ns| {
1224 if let Ok(binding) = source_bindings[ns].get() {
1225 this.lint_if_path_starts_with_module(finalize, &full_path, Some(binding));
1230 // Record what this import resolves to for later uses in documentation,
1231 // this may resolve to either a value or a type, but for documentation
1232 // purposes it's good enough to just favor one over the other.
1233 self.r.per_ns(|this, ns| {
1234 if let Ok(binding) = source_bindings[ns].get() {
1235 this.import_res_map.entry(import.id).or_default()[ns] = Some(binding.res());
1239 self.check_for_redundant_imports(ident, import, source_bindings, target_bindings, target);
1241 debug!("(resolving single import) successfully resolved import");
1245 fn check_for_redundant_imports(
1248 import: &'b Import<'b>,
1249 source_bindings: &PerNS<Cell<Result<&'b NameBinding<'b>, Determinacy>>>,
1250 target_bindings: &PerNS<Cell<Option<&'b NameBinding<'b>>>>,
1253 // Skip if the import was produced by a macro.
1254 if import.parent_scope.expansion != LocalExpnId::ROOT {
1258 // Skip if we are inside a named module (in contrast to an anonymous
1259 // module defined by a block).
1260 if let ModuleKind::Def(..) = import.parent_scope.module.kind {
1264 let mut is_redundant = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1266 let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1268 self.r.per_ns(|this, ns| {
1269 if let Ok(binding) = source_bindings[ns].get() {
1270 if binding.res() == Res::Err {
1274 let orig_unusable_binding =
1275 mem::replace(&mut this.unusable_binding, target_bindings[ns].get());
1277 match this.early_resolve_ident_in_lexical_scope(
1279 ScopeSet::All(ns, false),
1280 &import.parent_scope,
1284 Ok(other_binding) => {
1285 is_redundant[ns] = Some(
1286 binding.res() == other_binding.res() && !other_binding.is_ambiguity(),
1288 redundant_span[ns] = Some((other_binding.span, other_binding.is_import()));
1290 Err(_) => is_redundant[ns] = Some(false),
1293 this.unusable_binding = orig_unusable_binding;
1297 if !is_redundant.is_empty() && is_redundant.present_items().all(|is_redundant| is_redundant)
1299 let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1300 redundant_spans.sort();
1301 redundant_spans.dedup();
1302 self.r.lint_buffer.buffer_lint_with_diagnostic(
1306 &format!("the item `{}` is imported redundantly", ident),
1307 BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident),
1312 fn resolve_glob_import(&mut self, import: &'b Import<'b>) {
1313 let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else {
1314 self.r.session.span_err(import.span, "cannot glob-import all possible crates");
1318 if module.is_trait() {
1319 self.r.session.span_err(import.span, "items in traits are not importable");
1321 } else if ptr::eq(module, import.parent_scope.module) {
1323 } else if let ImportKind::Glob { is_prelude: true, .. } = import.kind {
1324 self.r.prelude = Some(module);
1328 // Add to module's glob_importers
1329 module.glob_importers.borrow_mut().push(import);
1331 // Ensure that `resolutions` isn't borrowed during `try_define`,
1332 // since it might get updated via a glob cycle.
1335 .resolutions(module)
1338 .filter_map(|(key, resolution)| {
1339 resolution.borrow().binding().map(|binding| (*key, binding))
1341 .collect::<Vec<_>>();
1342 for (mut key, binding) in bindings {
1343 let scope = match key.ident.span.reverse_glob_adjust(module.expansion, import.span) {
1344 Some(Some(def)) => self.r.expn_def_scope(def),
1345 Some(None) => import.parent_scope.module,
1348 if self.r.is_accessible_from(binding.vis, scope) {
1349 let imported_binding = self.r.import(binding, import);
1350 let _ = self.r.try_define(import.parent_scope.module, key, imported_binding);
1354 // Record the destination of this import
1355 self.r.record_partial_res(import.id, PartialRes::new(module.res().unwrap()));
1358 // Miscellaneous post-processing, including recording re-exports,
1359 // reporting conflicts, and reporting unresolved imports.
1360 fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1361 // Since import resolution is finished, globs will not define any more names.
1362 *module.globs.borrow_mut() = Vec::new();
1364 let mut reexports = Vec::new();
1366 module.for_each_child(self.r, |_, ident, _, binding| {
1367 // FIXME: Consider changing the binding inserted by `#[macro_export] macro_rules`
1368 // into the crate root to actual `NameBindingKind::Import`.
1369 if binding.is_import()
1370 || matches!(binding.kind, NameBindingKind::Res(_, _is_macro_export @ true))
1372 let res = binding.res().expect_non_local();
1373 // Ambiguous imports are treated as errors at this point and are
1374 // not exposed to other crates (see #36837 for more details).
1375 if res != def::Res::Err && !binding.is_ambiguity() {
1376 reexports.push(ModChild {
1387 if !reexports.is_empty() {
1388 if let Some(def_id) = module.opt_def_id() {
1389 // Call to `expect_local` should be fine because current
1390 // code is only called for local modules.
1391 self.r.reexport_map.insert(def_id.expect_local(), reexports);
1397 fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
1398 let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1399 let global = !names.is_empty() && names[0].name == kw::PathRoot;
1400 if let Some(pos) = pos {
1401 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1402 names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>())
1404 let names = if global { &names[1..] } else { names };
1405 if names.is_empty() {
1406 import_kind_to_string(import_kind)
1410 names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>()),
1411 import_kind_to_string(import_kind),
1417 fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1419 ImportKind::Single { source, .. } => source.to_string(),
1420 ImportKind::Glob { .. } => "*".to_string(),
1421 ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1422 ImportKind::MacroUse => "#[macro_use]".to_string(),