1 //! A bunch of methods and structures more or less related to resolving imports.
3 use crate::diagnostics::{import_candidates, DiagnosticMode, Suggestion};
4 use crate::Determinacy::{self, *};
5 use crate::Namespace::*;
6 use crate::{module_to_string, names_to_string, ImportSuggestion};
8 AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingKey, ModuleKind, ResolutionError,
11 use crate::{Finalize, Module, ModuleOrUniformRoot, ParentScope, PerNS, ScopeSet};
12 use crate::{NameBinding, NameBindingKind, PathResult};
14 use rustc_ast::NodeId;
15 use rustc_data_structures::fx::FxHashSet;
16 use rustc_data_structures::intern::Interned;
17 use rustc_errors::{pluralize, struct_span_err, Applicability, MultiSpan};
18 use rustc_hir::def::{self, DefKind, PartialRes};
19 use rustc_middle::metadata::ModChild;
20 use rustc_middle::span_bug;
22 use rustc_session::lint::builtin::{PUB_USE_OF_PRIVATE_EXTERN_CRATE, UNUSED_IMPORTS};
23 use rustc_session::lint::BuiltinLintDiagnostics;
24 use rustc_span::hygiene::LocalExpnId;
25 use rustc_span::lev_distance::find_best_match_for_name;
26 use rustc_span::symbol::{kw, Ident, Symbol};
32 type Res = def::Res<NodeId>;
34 /// Contains data for specific kinds of imports.
36 pub enum ImportKind<'a> {
38 /// `source` in `use prefix::source as target`.
40 /// `target` in `use prefix::source as target`.
42 /// Bindings to which `source` refers to.
43 source_bindings: PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
44 /// Bindings introduced by `target`.
45 target_bindings: PerNS<Cell<Option<&'a NameBinding<'a>>>>,
46 /// `true` for `...::{self [as target]}` imports, `false` otherwise.
48 /// Did this import result from a nested import? ie. `use foo::{bar, baz};`
50 /// The ID of the `UseTree` that imported this `Import`.
52 /// In the case where the `Import` was expanded from a "nested" use tree,
53 /// this id is the ID of the leaf tree. For example:
55 /// ```ignore (pacify the merciless tidy)
56 /// use foo::bar::{a, b}
59 /// If this is the import for `foo::bar::a`, we would have the ID of the `UseTree`
60 /// for `a` in this field.
65 // The visibility of the greatest re-export.
66 // n.b. `max_vis` is only used in `finalize_import` to check for re-export errors.
67 max_vis: Cell<Option<ty::Visibility>>,
71 source: Option<Symbol>,
79 /// Manually implement `Debug` for `ImportKind` because the `source/target_bindings`
80 /// contain `Cell`s which can introduce infinite loops while printing.
81 impl<'a> std::fmt::Debug for ImportKind<'a> {
82 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91 // Ignore the following to avoid an infinite loop while printing.
95 .debug_struct("Single")
96 .field("source", source)
97 .field("target", target)
98 .field("type_ns_only", type_ns_only)
99 .field("nested", nested)
101 .finish_non_exhaustive(),
102 Glob { ref is_prelude, ref max_vis, ref id } => f
103 .debug_struct("Glob")
104 .field("is_prelude", is_prelude)
105 .field("max_vis", max_vis)
108 ExternCrate { ref source, ref target, ref id } => f
109 .debug_struct("ExternCrate")
110 .field("source", source)
111 .field("target", target)
114 MacroUse => f.debug_struct("MacroUse").finish(),
115 MacroExport => f.debug_struct("MacroExport").finish(),
121 #[derive(Debug, Clone)]
122 pub(crate) struct Import<'a> {
123 pub kind: ImportKind<'a>,
125 /// Node ID of the "root" use item -- this is always the same as `ImportKind`'s `id`
126 /// (if it exists) except in the case of "nested" use trees, in which case
127 /// it will be the ID of the root use tree. e.g., in the example
128 /// ```ignore (incomplete code)
129 /// use foo::bar::{a, b}
131 /// this would be the ID of the `use foo::bar` `UseTree` node.
132 /// In case of imports without their own node ID it's the closest node that can be used,
133 /// for example, for reporting lints.
136 /// Span of the entire use statement.
139 /// Span of the entire use statement with attributes.
140 pub use_span_with_attributes: Span,
142 /// Did the use statement have any attributes?
143 pub has_attributes: bool,
145 /// Span of this use tree.
148 /// Span of the *root* use tree (see `root_id`).
151 pub parent_scope: ParentScope<'a>,
152 pub module_path: Vec<Segment>,
153 /// The resolution of `module_path`.
154 pub imported_module: Cell<Option<ModuleOrUniformRoot<'a>>>,
155 pub vis: Cell<Option<ty::Visibility>>,
156 pub used: Cell<bool>,
159 impl<'a> Import<'a> {
160 pub fn is_glob(&self) -> bool {
161 matches!(self.kind, ImportKind::Glob { .. })
164 pub fn is_nested(&self) -> bool {
166 ImportKind::Single { nested, .. } => nested,
171 pub(crate) fn expect_vis(&self) -> ty::Visibility {
172 self.vis.get().expect("encountered cleared import visibility")
175 pub(crate) fn id(&self) -> Option<NodeId> {
177 ImportKind::Single { id, .. }
178 | ImportKind::Glob { id, .. }
179 | ImportKind::ExternCrate { id, .. } => Some(id),
180 ImportKind::MacroUse | ImportKind::MacroExport => None,
185 /// Records information about the resolution of a name in a namespace of a module.
186 #[derive(Clone, Default, Debug)]
187 pub(crate) struct NameResolution<'a> {
188 /// Single imports that may define the name in the namespace.
189 /// Imports are arena-allocated, so it's ok to use pointers as keys.
190 pub single_imports: FxHashSet<Interned<'a, Import<'a>>>,
191 /// The least shadowable known binding for this name, or None if there are no known bindings.
192 pub binding: Option<&'a NameBinding<'a>>,
193 pub shadowed_glob: Option<&'a NameBinding<'a>>,
196 impl<'a> NameResolution<'a> {
197 /// Returns the binding for the name if it is known or None if it not known.
198 pub(crate) fn binding(&self) -> Option<&'a NameBinding<'a>> {
199 self.binding.and_then(|binding| {
200 if !binding.is_glob_import() || self.single_imports.is_empty() {
208 pub(crate) fn add_single_import(&mut self, import: &'a Import<'a>) {
209 self.single_imports.insert(Interned::new_unchecked(import));
213 // Reexports of the form `pub use foo as bar;` where `foo` is `extern crate foo;`
214 // are permitted for backward-compatibility under a deprecation lint.
215 fn pub_use_of_private_extern_crate_hack(import: &Import<'_>, binding: &NameBinding<'_>) -> bool {
216 match (&import.kind, &binding.kind) {
218 ImportKind::Single { .. },
219 NameBindingKind::Import {
220 import: Import { kind: ImportKind::ExternCrate { .. }, .. },
223 ) => import.expect_vis().is_public(),
228 impl<'a> Resolver<'a> {
229 /// Given a binding and an import that resolves to it,
230 /// return the corresponding binding defined by the import.
231 pub(crate) fn import(
233 binding: &'a NameBinding<'a>,
234 import: &'a Import<'a>,
235 ) -> &'a NameBinding<'a> {
236 let import_vis = import.expect_vis().to_def_id();
237 let vis = if binding.vis.is_at_least(import_vis, self)
238 || pub_use_of_private_extern_crate_hack(import, binding)
245 if let ImportKind::Glob { ref max_vis, .. } = import.kind {
247 || max_vis.get().map_or(true, |max_vis| vis.is_at_least(max_vis, self))
249 max_vis.set(Some(vis.expect_local()))
253 self.arenas.alloc_name_binding(NameBinding {
254 kind: NameBindingKind::Import { binding, import, used: Cell::new(false) },
258 expansion: import.parent_scope.expansion,
262 /// Define the name or return the existing binding if there is a collision.
263 pub(crate) fn try_define(
267 binding: &'a NameBinding<'a>,
268 ) -> Result<(), &'a NameBinding<'a>> {
269 let res = binding.res();
270 self.check_reserved_macro_name(key.ident, res);
271 self.set_binding_parent_module(binding, module);
272 self.update_resolution(module, key, |this, resolution| {
273 if let Some(old_binding) = resolution.binding {
274 if res == Res::Err && old_binding.res() != Res::Err {
275 // Do not override real bindings with `Res::Err`s from error recovery.
278 match (old_binding.is_glob_import(), binding.is_glob_import()) {
280 if res != old_binding.res() {
281 resolution.binding = Some(this.ambiguity(
282 AmbiguityKind::GlobVsGlob,
286 } else if !old_binding.vis.is_at_least(binding.vis, &*this) {
287 // We are glob-importing the same item but with greater visibility.
288 resolution.binding = Some(binding);
291 (old_glob @ true, false) | (old_glob @ false, true) => {
292 let (glob_binding, nonglob_binding) =
293 if old_glob { (old_binding, binding) } else { (binding, old_binding) };
294 if glob_binding.res() != nonglob_binding.res()
296 && nonglob_binding.expansion != LocalExpnId::ROOT
298 resolution.binding = Some(this.ambiguity(
299 AmbiguityKind::GlobVsExpanded,
304 resolution.binding = Some(nonglob_binding);
306 resolution.shadowed_glob = Some(glob_binding);
309 return Err(old_binding);
313 resolution.binding = Some(binding);
323 primary_binding: &'a NameBinding<'a>,
324 secondary_binding: &'a NameBinding<'a>,
325 ) -> &'a NameBinding<'a> {
326 self.arenas.alloc_name_binding(NameBinding {
327 ambiguity: Some((secondary_binding, kind)),
328 ..primary_binding.clone()
332 // Use `f` to mutate the resolution of the name in the module.
333 // If the resolution becomes a success, define it in the module's glob importers.
334 fn update_resolution<T, F>(&mut self, module: Module<'a>, key: BindingKey, f: F) -> T
336 F: FnOnce(&mut Resolver<'a>, &mut NameResolution<'a>) -> T,
338 // Ensure that `resolution` isn't borrowed when defining in the module's glob importers,
339 // during which the resolution might end up getting re-defined via a glob cycle.
341 let resolution = &mut *self.resolution(module, key).borrow_mut();
342 let old_binding = resolution.binding();
344 let t = f(self, resolution);
346 match resolution.binding() {
347 _ if old_binding.is_some() => return t,
349 Some(binding) => match old_binding {
350 Some(old_binding) if ptr::eq(old_binding, binding) => return t,
356 // Define `binding` in `module`s glob importers.
357 for import in module.glob_importers.borrow_mut().iter() {
358 let mut ident = key.ident;
359 let scope = match ident.span.reverse_glob_adjust(module.expansion, import.span) {
360 Some(Some(def)) => self.expn_def_scope(def),
361 Some(None) => import.parent_scope.module,
364 if self.is_accessible_from(binding.vis, scope) {
365 let imported_binding = self.import(binding, import);
366 let key = BindingKey { ident, ..key };
367 let _ = self.try_define(import.parent_scope.module, key, imported_binding);
374 // Define a dummy resolution containing a `Res::Err` as a placeholder for a failed resolution,
375 // also mark such failed imports as used to avoid duplicate diagnostics.
376 fn import_dummy_binding(&mut self, import: &'a Import<'a>) {
377 if let ImportKind::Single { target, ref target_bindings, .. } = import.kind {
378 if target_bindings.iter().any(|binding| binding.get().is_some()) {
379 return; // Has resolution, do not create the dummy binding
381 let dummy_binding = self.dummy_binding;
382 let dummy_binding = self.import(dummy_binding, import);
383 self.per_ns(|this, ns| {
384 let key = this.new_key(target, ns);
385 let _ = this.try_define(import.parent_scope.module, key, dummy_binding);
387 self.record_use(target, dummy_binding, false);
388 } else if import.imported_module.get().is_none() {
389 import.used.set(true);
390 if let Some(id) = import.id() {
391 self.used_imports.insert(id);
397 /// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
398 /// import errors within the same use tree into a single diagnostic.
399 #[derive(Debug, Clone)]
400 struct UnresolvedImportError {
402 label: Option<String>,
403 note: Option<String>,
404 suggestion: Option<Suggestion>,
405 candidates: Option<Vec<ImportSuggestion>>,
408 pub struct ImportResolver<'a, 'b> {
409 pub r: &'a mut Resolver<'b>,
412 impl<'a, 'b> ImportResolver<'a, 'b> {
415 // This is a fixed-point algorithm. We resolve imports until our efforts
416 // are stymied by an unresolved import; then we bail out of the current
417 // module and continue. We terminate successfully once no more imports
418 // remain or unsuccessfully when no forward progress in resolving imports
421 /// Resolves all imports for the crate. This method performs the fixed-
423 pub fn resolve_imports(&mut self) {
424 let mut prev_num_indeterminates = self.r.indeterminate_imports.len() + 1;
425 while self.r.indeterminate_imports.len() < prev_num_indeterminates {
426 prev_num_indeterminates = self.r.indeterminate_imports.len();
427 for import in mem::take(&mut self.r.indeterminate_imports) {
428 match self.resolve_import(&import) {
429 true => self.r.determined_imports.push(import),
430 false => self.r.indeterminate_imports.push(import),
436 pub fn finalize_imports(&mut self) {
437 for module in self.r.arenas.local_modules().iter() {
438 self.finalize_resolutions_in(module);
441 let mut seen_spans = FxHashSet::default();
442 let mut errors = vec![];
443 let mut prev_root_id: NodeId = NodeId::from_u32(0);
444 let determined_imports = mem::take(&mut self.r.determined_imports);
445 let indeterminate_imports = mem::take(&mut self.r.indeterminate_imports);
447 for (is_indeterminate, import) in determined_imports
450 .chain(indeterminate_imports.into_iter().map(|i| (true, i)))
452 let unresolved_import_error = self.finalize_import(import);
454 // If this import is unresolved then create a dummy import
455 // resolution for it so that later resolve stages won't complain.
456 self.r.import_dummy_binding(import);
458 if let Some(err) = unresolved_import_error {
459 if let ImportKind::Single { source, ref source_bindings, .. } = import.kind {
460 if source.name == kw::SelfLower {
461 // Silence `unresolved import` error if E0429 is already emitted
462 if let Err(Determined) = source_bindings.value_ns.get() {
468 if prev_root_id.as_u32() != 0
469 && prev_root_id.as_u32() != import.root_id.as_u32()
470 && !errors.is_empty()
472 // In the case of a new import line, throw a diagnostic message
473 // for the previous line.
474 self.throw_unresolved_import_error(errors);
477 if seen_spans.insert(err.span) {
478 errors.push((import, err));
479 prev_root_id = import.root_id;
481 } else if is_indeterminate {
482 let path = import_path_to_string(
483 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
487 let err = UnresolvedImportError {
494 // FIXME: there should be a better way of doing this than
495 // formatting this as a string then checking for `::`
496 if path.contains("::") {
497 errors.push((import, err))
502 if !errors.is_empty() {
503 self.throw_unresolved_import_error(errors);
507 fn throw_unresolved_import_error(&self, errors: Vec<(&Import<'_>, UnresolvedImportError)>) {
508 if errors.is_empty() {
512 /// Upper limit on the number of `span_label` messages.
513 const MAX_LABEL_COUNT: usize = 10;
515 let span = MultiSpan::from_spans(errors.iter().map(|(_, err)| err.span).collect());
518 .map(|(import, err)| {
519 let path = import_path_to_string(
520 &import.module_path.iter().map(|seg| seg.ident).collect::<Vec<_>>(),
526 .collect::<Vec<_>>();
527 let msg = format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);
529 let mut diag = struct_span_err!(self.r.session, span, E0432, "{}", &msg);
531 if let Some((_, UnresolvedImportError { note: Some(note), .. })) = errors.iter().last() {
535 for (import, err) in errors.into_iter().take(MAX_LABEL_COUNT) {
536 if let Some(label) = err.label {
537 diag.span_label(err.span, label);
540 if let Some((suggestions, msg, applicability)) = err.suggestion {
541 if suggestions.is_empty() {
545 diag.multipart_suggestion(&msg, suggestions, applicability);
548 if let Some(candidates) = &err.candidates {
550 ImportKind::Single { nested: false, source, target, .. } => import_candidates(
552 &self.r.untracked.source_span,
556 DiagnosticMode::Import,
558 .then(|| format!(" as {target}"))
562 ImportKind::Single { nested: true, source, target, .. } => {
565 &self.r.untracked.source_span,
569 DiagnosticMode::Normal,
571 .then(|| format!(" as {target}"))
584 /// Attempts to resolve the given import, returning true if its resolution is determined.
585 /// If successful, the resolved bindings are written into the module.
586 fn resolve_import(&mut self, import: &'b Import<'b>) -> bool {
588 "(resolving import for module) resolving import `{}::...` in `{}`",
589 Segment::names_to_string(&import.module_path),
590 module_to_string(import.parent_scope.module).unwrap_or_else(|| "???".to_string()),
593 let module = if let Some(module) = import.imported_module.get() {
596 // For better failure detection, pretend that the import will
597 // not define any names while resolving its module path.
598 let orig_vis = import.vis.take();
600 self.r.maybe_resolve_path(&import.module_path, None, &import.parent_scope);
601 import.vis.set(orig_vis);
604 PathResult::Module(module) => module,
605 PathResult::Indeterminate => return false,
606 PathResult::NonModule(..) | PathResult::Failed { .. } => return true,
610 import.imported_module.set(Some(module));
611 let (source, target, source_bindings, target_bindings, type_ns_only) = match import.kind {
619 } => (source, target, source_bindings, target_bindings, type_ns_only),
620 ImportKind::Glob { .. } => {
621 self.resolve_glob_import(import);
627 let mut indeterminate = false;
628 self.r.per_ns(|this, ns| {
629 if !type_ns_only || ns == TypeNS {
630 if let Err(Undetermined) = source_bindings[ns].get() {
631 // For better failure detection, pretend that the import will
632 // not define any names while resolving its module path.
633 let orig_vis = import.vis.take();
634 let binding = this.resolve_ident_in_module(
638 &import.parent_scope,
642 import.vis.set(orig_vis);
643 source_bindings[ns].set(binding);
648 let parent = import.parent_scope.module;
649 match source_bindings[ns].get() {
650 Err(Undetermined) => indeterminate = true,
651 // Don't update the resolution, because it was never added.
652 Err(Determined) if target.name == kw::Underscore => {}
653 Ok(binding) if binding.is_importable() => {
654 let imported_binding = this.import(binding, import);
655 target_bindings[ns].set(Some(imported_binding));
656 this.define(parent, target, ns, imported_binding);
658 source_binding @ (Ok(..) | Err(Determined)) => {
659 if source_binding.is_ok() {
660 let msg = format!("`{}` is not directly importable", target);
661 struct_span_err!(this.session, import.span, E0253, "{}", &msg)
662 .span_label(import.span, "cannot be imported directly")
665 let key = this.new_key(target, ns);
666 this.update_resolution(parent, key, |_, resolution| {
667 resolution.single_imports.remove(&Interned::new_unchecked(import));
677 /// Performs final import resolution, consistency checks and error reporting.
679 /// Optionally returns an unresolved import error. This error is buffered and used to
680 /// consolidate multiple unresolved import errors into a single diagnostic.
681 fn finalize_import(&mut self, import: &'b Import<'b>) -> Option<UnresolvedImportError> {
682 let orig_vis = import.vis.take();
683 let ignore_binding = match &import.kind {
684 ImportKind::Single { target_bindings, .. } => target_bindings[TypeNS].get(),
687 let prev_ambiguity_errors_len = self.r.ambiguity_errors.len();
688 let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
689 let path_res = self.r.resolve_path(
692 &import.parent_scope,
697 let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len;
698 import.vis.set(orig_vis);
699 let module = match path_res {
700 PathResult::Module(module) => {
701 // Consistency checks, analogous to `finalize_macro_resolutions`.
702 if let Some(initial_module) = import.imported_module.get() {
703 if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
704 span_bug!(import.span, "inconsistent resolution for an import");
706 } else if self.r.privacy_errors.is_empty() {
707 let msg = "cannot determine resolution for the import";
708 let msg_note = "import resolution is stuck, try simplifying other imports";
709 self.r.session.struct_span_err(import.span, msg).note(msg_note).emit();
714 PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
716 assert!(import.imported_module.get().is_none());
718 .report_error(span, ResolutionError::FailedToResolve { label, suggestion });
722 PathResult::Failed { is_error_from_last_segment: true, span, label, suggestion } => {
724 assert!(import.imported_module.get().is_none());
725 let err = match self.make_path_suggestion(
727 import.module_path.clone(),
728 &import.parent_scope,
730 Some((suggestion, note)) => UnresolvedImportError {
735 vec![(span, Segment::names_to_string(&suggestion))],
736 String::from("a similar path exists"),
737 Applicability::MaybeIncorrect,
741 None => UnresolvedImportError {
753 PathResult::NonModule(_) => {
755 assert!(import.imported_module.get().is_none());
757 // The error was already reported earlier.
760 PathResult::Indeterminate => unreachable!(),
763 let (ident, target, source_bindings, target_bindings, type_ns_only, import_id) =
773 } => (source, target, source_bindings, target_bindings, type_ns_only, id),
774 ImportKind::Glob { is_prelude, ref max_vis, id } => {
775 if import.module_path.len() <= 1 {
776 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
777 // 2 segments, so the `resolve_path` above won't trigger it.
778 let mut full_path = import.module_path.clone();
779 full_path.push(Segment::from_ident(Ident::empty()));
780 self.r.lint_if_path_starts_with_module(Some(finalize), &full_path, None);
783 if let ModuleOrUniformRoot::Module(module) = module {
784 if ptr::eq(module, import.parent_scope.module) {
785 // Importing a module into itself is not allowed.
786 return Some(UnresolvedImportError {
788 label: Some(String::from(
789 "cannot glob-import a module into itself",
798 && let Some(max_vis) = max_vis.get()
799 && !max_vis.is_at_least(import.expect_vis(), &*self.r)
801 let msg = "glob import doesn't reexport anything because no candidate is public enough";
802 self.r.lint_buffer.buffer_lint(UNUSED_IMPORTS, id, import.span, msg);
809 let mut all_ns_err = true;
810 self.r.per_ns(|this, ns| {
811 if !type_ns_only || ns == TypeNS {
812 let orig_vis = import.vis.take();
813 let binding = this.resolve_ident_in_module(
817 &import.parent_scope,
818 Some(Finalize { report_private: false, ..finalize }),
819 target_bindings[ns].get(),
821 import.vis.set(orig_vis);
825 // Consistency checks, analogous to `finalize_macro_resolutions`.
826 let initial_binding = source_bindings[ns].get().map(|initial_binding| {
828 if let Some(target_binding) = target_bindings[ns].get() {
829 if target.name == kw::Underscore
830 && initial_binding.is_extern_crate()
831 && !initial_binding.is_import()
836 import.module_path.is_empty(),
842 let res = binding.res();
843 if let Ok(initial_binding) = initial_binding {
844 let initial_res = initial_binding.res();
845 if res != initial_res && this.ambiguity_errors.is_empty() {
846 this.ambiguity_errors.push(AmbiguityError {
847 kind: AmbiguityKind::Import,
851 misc1: AmbiguityErrorMisc::None,
852 misc2: AmbiguityErrorMisc::None,
855 } else if res != Res::Err
856 && this.ambiguity_errors.is_empty()
857 && this.privacy_errors.is_empty()
859 let msg = "cannot determine resolution for the import";
861 "import resolution is stuck, try simplifying other imports";
862 this.session.struct_span_err(import.span, msg).note(msg_note).emit();
866 // FIXME: This assert may fire if public glob is later shadowed by a private
867 // single import (see test `issue-55884-2.rs`). In theory single imports should
868 // always block globs, even if they are not yet resolved, so that this kind of
869 // self-inconsistent resolution never happens.
870 // Re-enable the assert when the issue is fixed.
871 // assert!(result[ns].get().is_err());
878 let mut all_ns_failed = true;
879 self.r.per_ns(|this, ns| {
880 if !type_ns_only || ns == TypeNS {
881 let binding = this.resolve_ident_in_module(
885 &import.parent_scope,
890 all_ns_failed = false;
895 return if all_ns_failed {
896 let resolutions = match module {
897 ModuleOrUniformRoot::Module(module) => {
898 Some(self.r.resolutions(module).borrow())
902 let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
903 let names = resolutions
904 .filter_map(|(BindingKey { ident: i, .. }, resolution)| {
905 if i.name == ident.name {
907 } // Never suggest the same name
908 match *resolution.borrow() {
909 NameResolution { binding: Some(name_binding), .. } => {
910 match name_binding.kind {
911 NameBindingKind::Import { binding, .. } => {
913 // Never suggest the name that has binding error
914 // i.e., the name that cannot be previously resolved
915 NameBindingKind::Res(Res::Err) => None,
922 NameResolution { ref single_imports, .. }
923 if single_imports.is_empty() =>
930 .collect::<Vec<Symbol>>();
933 find_best_match_for_name(&names, ident.name, None).map(|suggestion| {
935 vec![(ident.span, suggestion.to_string())],
936 String::from("a similar name exists in the module"),
937 Applicability::MaybeIncorrect,
941 let (suggestion, note) =
942 match self.check_for_module_export_macro(import, module, ident) {
943 Some((suggestion, note)) => (suggestion.or(lev_suggestion), note),
944 _ => (lev_suggestion, None),
947 let label = match module {
948 ModuleOrUniformRoot::Module(module) => {
949 let module_str = module_to_string(module);
950 if let Some(module_str) = module_str {
951 format!("no `{}` in `{}`", ident, module_str)
953 format!("no `{}` in the root", ident)
957 if !ident.is_path_segment_keyword() {
958 format!("no external crate `{}`", ident)
960 // HACK(eddyb) this shows up for `self` & `super`, which
961 // should work instead - for now keep the same error message.
962 format!("no `{}` in the root", ident)
967 let parent_suggestion =
968 self.r.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true);
970 Some(UnresolvedImportError {
975 candidates: if !parent_suggestion.is_empty() {
976 Some(parent_suggestion)
982 // `resolve_ident_in_module` reported a privacy error.
987 let mut reexport_error = None;
988 let mut any_successful_reexport = false;
989 let mut crate_private_reexport = false;
990 self.r.per_ns(|this, ns| {
991 if let Ok(binding) = source_bindings[ns].get() {
992 if !binding.vis.is_at_least(import.expect_vis(), &*this) {
993 reexport_error = Some((ns, binding));
994 if let ty::Visibility::Restricted(binding_def_id) = binding.vis {
995 if binding_def_id.is_top_level_module() {
996 crate_private_reexport = true;
1000 any_successful_reexport = true;
1005 // All namespaces must be re-exported with extra visibility for an error to occur.
1006 if !any_successful_reexport {
1007 let (ns, binding) = reexport_error.unwrap();
1008 if pub_use_of_private_extern_crate_hack(import, binding) {
1010 "extern crate `{}` is private, and cannot be \
1011 re-exported (error E0365), consider declaring with \
1015 self.r.lint_buffer.buffer_lint(
1016 PUB_USE_OF_PRIVATE_EXTERN_CRATE,
1022 let error_msg = if crate_private_reexport {
1024 "`{}` is only public within the crate, and cannot be re-exported outside",
1028 format!("`{}` is private, and cannot be re-exported", ident)
1032 let label_msg = if crate_private_reexport {
1033 format!("re-export of crate public `{}`", ident)
1035 format!("re-export of private `{}`", ident)
1038 struct_span_err!(self.r.session, import.span, E0365, "{}", error_msg)
1039 .span_label(import.span, label_msg)
1040 .note(&format!("consider declaring type or module `{}` with `pub`", ident))
1044 struct_span_err!(self.r.session, import.span, E0364, "{error_msg}");
1045 match binding.kind {
1046 NameBindingKind::Res(Res::Def(DefKind::Macro(_), def_id))
1047 // exclude decl_macro
1048 if self.r.get_macro_by_def_id(def_id).macro_rules =>
1052 "consider adding a `#[macro_export]` to the macro in the imported module",
1059 "consider marking `{ident}` as `pub` in the imported module"
1069 if import.module_path.len() <= 1 {
1070 // HACK(eddyb) `lint_if_path_starts_with_module` needs at least
1071 // 2 segments, so the `resolve_path` above won't trigger it.
1072 let mut full_path = import.module_path.clone();
1073 full_path.push(Segment::from_ident(ident));
1074 self.r.per_ns(|this, ns| {
1075 if let Ok(binding) = source_bindings[ns].get() {
1076 this.lint_if_path_starts_with_module(Some(finalize), &full_path, Some(binding));
1081 // Record what this import resolves to for later uses in documentation,
1082 // this may resolve to either a value or a type, but for documentation
1083 // purposes it's good enough to just favor one over the other.
1084 self.r.per_ns(|this, ns| {
1085 if let Ok(binding) = source_bindings[ns].get() {
1086 this.import_res_map.entry(import_id).or_default()[ns] = Some(binding.res());
1090 self.check_for_redundant_imports(ident, import, source_bindings, target_bindings, target);
1092 debug!("(resolving single import) successfully resolved import");
1096 fn check_for_redundant_imports(
1099 import: &'b Import<'b>,
1100 source_bindings: &PerNS<Cell<Result<&'b NameBinding<'b>, Determinacy>>>,
1101 target_bindings: &PerNS<Cell<Option<&'b NameBinding<'b>>>>,
1104 // This function is only called for single imports.
1105 let ImportKind::Single { id, .. } = import.kind else { unreachable!() };
1107 // Skip if the import was produced by a macro.
1108 if import.parent_scope.expansion != LocalExpnId::ROOT {
1112 // Skip if we are inside a named module (in contrast to an anonymous
1113 // module defined by a block).
1114 if let ModuleKind::Def(..) = import.parent_scope.module.kind {
1118 let mut is_redundant = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1120 let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
1122 self.r.per_ns(|this, ns| {
1123 if let Ok(binding) = source_bindings[ns].get() {
1124 if binding.res() == Res::Err {
1128 match this.early_resolve_ident_in_lexical_scope(
1130 ScopeSet::All(ns, false),
1131 &import.parent_scope,
1134 target_bindings[ns].get(),
1136 Ok(other_binding) => {
1137 is_redundant[ns] = Some(
1138 binding.res() == other_binding.res() && !other_binding.is_ambiguity(),
1140 redundant_span[ns] = Some((other_binding.span, other_binding.is_import()));
1142 Err(_) => is_redundant[ns] = Some(false),
1147 if !is_redundant.is_empty() && is_redundant.present_items().all(|is_redundant| is_redundant)
1149 let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
1150 redundant_spans.sort();
1151 redundant_spans.dedup();
1152 self.r.lint_buffer.buffer_lint_with_diagnostic(
1156 &format!("the item `{}` is imported redundantly", ident),
1157 BuiltinLintDiagnostics::RedundantImport(redundant_spans, ident),
1162 fn resolve_glob_import(&mut self, import: &'b Import<'b>) {
1163 // This function is only called for glob imports.
1164 let ImportKind::Glob { id, is_prelude, .. } = import.kind else { unreachable!() };
1166 let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else {
1167 self.r.session.span_err(import.span, "cannot glob-import all possible crates");
1171 if module.is_trait() {
1172 self.r.session.span_err(import.span, "items in traits are not importable");
1174 } else if ptr::eq(module, import.parent_scope.module) {
1176 } else if is_prelude {
1177 self.r.prelude = Some(module);
1181 // Add to module's glob_importers
1182 module.glob_importers.borrow_mut().push(import);
1184 // Ensure that `resolutions` isn't borrowed during `try_define`,
1185 // since it might get updated via a glob cycle.
1188 .resolutions(module)
1191 .filter_map(|(key, resolution)| {
1192 resolution.borrow().binding().map(|binding| (*key, binding))
1194 .collect::<Vec<_>>();
1195 for (mut key, binding) in bindings {
1196 let scope = match key.ident.span.reverse_glob_adjust(module.expansion, import.span) {
1197 Some(Some(def)) => self.r.expn_def_scope(def),
1198 Some(None) => import.parent_scope.module,
1201 if self.r.is_accessible_from(binding.vis, scope) {
1202 let imported_binding = self.r.import(binding, import);
1203 let _ = self.r.try_define(import.parent_scope.module, key, imported_binding);
1207 // Record the destination of this import
1208 self.r.record_partial_res(id, PartialRes::new(module.res().unwrap()));
1211 // Miscellaneous post-processing, including recording re-exports,
1212 // reporting conflicts, and reporting unresolved imports.
1213 fn finalize_resolutions_in(&mut self, module: Module<'b>) {
1214 // Since import resolution is finished, globs will not define any more names.
1215 *module.globs.borrow_mut() = Vec::new();
1217 if let Some(def_id) = module.opt_def_id() {
1218 let mut reexports = Vec::new();
1220 module.for_each_child(self.r, |this, ident, _, binding| {
1221 if let Some(res) = this.is_reexport(binding) {
1222 reexports.push(ModChild {
1232 if !reexports.is_empty() {
1233 // Call to `expect_local` should be fine because current
1234 // code is only called for local modules.
1235 self.r.reexport_map.insert(def_id.expect_local(), reexports);
1241 fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {
1242 let pos = names.iter().position(|p| span == p.span && p.name != kw::PathRoot);
1243 let global = !names.is_empty() && names[0].name == kw::PathRoot;
1244 if let Some(pos) = pos {
1245 let names = if global { &names[1..pos + 1] } else { &names[..pos + 1] };
1246 names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>())
1248 let names = if global { &names[1..] } else { names };
1249 if names.is_empty() {
1250 import_kind_to_string(import_kind)
1254 names_to_string(&names.iter().map(|ident| ident.name).collect::<Vec<_>>()),
1255 import_kind_to_string(import_kind),
1261 fn import_kind_to_string(import_kind: &ImportKind<'_>) -> String {
1263 ImportKind::Single { source, .. } => source.to_string(),
1264 ImportKind::Glob { .. } => "*".to_string(),
1265 ImportKind::ExternCrate { .. } => "<extern crate>".to_string(),
1266 ImportKind::MacroUse => "#[macro_use]".to_string(),
1267 ImportKind::MacroExport => "#[macro_export]".to_string(),