1
Fork 0

resolve: Remove ImportResolver

It's a trivial wrapper over `Resolver` that doesn't bring any benefits
This commit is contained in:
Vadim Petrochenkov 2023-02-22 21:20:54 +04:00
parent 3b4d6e0804
commit d275114bda
4 changed files with 87 additions and 103 deletions

View file

@ -29,7 +29,7 @@ use rustc_span::{BytePos, Span, SyntaxContext};
use thin_vec::ThinVec; use thin_vec::ThinVec;
use crate::errors as errs; use crate::errors as errs;
use crate::imports::{Import, ImportKind, ImportResolver}; use crate::imports::{Import, ImportKind};
use crate::late::{PatternSource, Rib}; use crate::late::{PatternSource, Rib};
use crate::path_names_to_string; use crate::path_names_to_string;
use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingError, Finalize}; use crate::{AmbiguityError, AmbiguityErrorMisc, AmbiguityKind, BindingError, Finalize};
@ -1888,15 +1888,13 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
(format!("use of undeclared crate or module `{}`", ident), suggestion) (format!("use of undeclared crate or module `{}`", ident), suggestion)
} }
} }
}
impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
/// Adds suggestions for a path that cannot be resolved. /// Adds suggestions for a path that cannot be resolved.
pub(crate) fn make_path_suggestion( pub(crate) fn make_path_suggestion(
&mut self, &mut self,
span: Span, span: Span,
mut path: Vec<Segment>, mut path: Vec<Segment>,
parent_scope: &ParentScope<'b>, parent_scope: &ParentScope<'a>,
) -> Option<(Vec<Segment>, Option<String>)> { ) -> Option<(Vec<Segment>, Option<String>)> {
debug!("make_path_suggestion: span={:?} path={:?}", span, path); debug!("make_path_suggestion: span={:?} path={:?}", span, path);
@ -1931,11 +1929,11 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
fn make_missing_self_suggestion( fn make_missing_self_suggestion(
&mut self, &mut self,
mut path: Vec<Segment>, mut path: Vec<Segment>,
parent_scope: &ParentScope<'b>, parent_scope: &ParentScope<'a>,
) -> Option<(Vec<Segment>, Option<String>)> { ) -> Option<(Vec<Segment>, Option<String>)> {
// Replace first ident with `self` and check if that is valid. // Replace first ident with `self` and check if that is valid.
path[0].ident.name = kw::SelfLower; path[0].ident.name = kw::SelfLower;
let result = self.r.maybe_resolve_path(&path, None, parent_scope); let result = self.maybe_resolve_path(&path, None, parent_scope);
debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result); debug!("make_missing_self_suggestion: path={:?} result={:?}", path, result);
if let PathResult::Module(..) = result { Some((path, None)) } else { None } if let PathResult::Module(..) = result { Some((path, None)) } else { None }
} }
@ -1950,11 +1948,11 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
fn make_missing_crate_suggestion( fn make_missing_crate_suggestion(
&mut self, &mut self,
mut path: Vec<Segment>, mut path: Vec<Segment>,
parent_scope: &ParentScope<'b>, parent_scope: &ParentScope<'a>,
) -> Option<(Vec<Segment>, Option<String>)> { ) -> Option<(Vec<Segment>, Option<String>)> {
// Replace first ident with `crate` and check if that is valid. // Replace first ident with `crate` and check if that is valid.
path[0].ident.name = kw::Crate; path[0].ident.name = kw::Crate;
let result = self.r.maybe_resolve_path(&path, None, parent_scope); let result = self.maybe_resolve_path(&path, None, parent_scope);
debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result); debug!("make_missing_crate_suggestion: path={:?} result={:?}", path, result);
if let PathResult::Module(..) = result { if let PathResult::Module(..) = result {
Some(( Some((
@ -1981,11 +1979,11 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
fn make_missing_super_suggestion( fn make_missing_super_suggestion(
&mut self, &mut self,
mut path: Vec<Segment>, mut path: Vec<Segment>,
parent_scope: &ParentScope<'b>, parent_scope: &ParentScope<'a>,
) -> Option<(Vec<Segment>, Option<String>)> { ) -> Option<(Vec<Segment>, Option<String>)> {
// Replace first ident with `crate` and check if that is valid. // Replace first ident with `crate` and check if that is valid.
path[0].ident.name = kw::Super; path[0].ident.name = kw::Super;
let result = self.r.maybe_resolve_path(&path, None, parent_scope); let result = self.maybe_resolve_path(&path, None, parent_scope);
debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result); debug!("make_missing_super_suggestion: path={:?} result={:?}", path, result);
if let PathResult::Module(..) = result { Some((path, None)) } else { None } if let PathResult::Module(..) = result { Some((path, None)) } else { None }
} }
@ -2003,7 +2001,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
fn make_external_crate_suggestion( fn make_external_crate_suggestion(
&mut self, &mut self,
mut path: Vec<Segment>, mut path: Vec<Segment>,
parent_scope: &ParentScope<'b>, parent_scope: &ParentScope<'a>,
) -> Option<(Vec<Segment>, Option<String>)> { ) -> Option<(Vec<Segment>, Option<String>)> {
if path[1].ident.span.is_rust_2015() { if path[1].ident.span.is_rust_2015() {
return None; return None;
@ -2013,13 +2011,13 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
// 1) some consistent ordering for emitted diagnostics, and // 1) some consistent ordering for emitted diagnostics, and
// 2) `std` suggestions before `core` suggestions. // 2) `std` suggestions before `core` suggestions.
let mut extern_crate_names = let mut extern_crate_names =
self.r.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>(); self.extern_prelude.iter().map(|(ident, _)| ident.name).collect::<Vec<_>>();
extern_crate_names.sort_by(|a, b| b.as_str().partial_cmp(a.as_str()).unwrap()); extern_crate_names.sort_by(|a, b| b.as_str().partial_cmp(a.as_str()).unwrap());
for name in extern_crate_names.into_iter() { for name in extern_crate_names.into_iter() {
// Replace first ident with a crate name and check if that is valid. // Replace first ident with a crate name and check if that is valid.
path[0].ident.name = name; path[0].ident.name = name;
let result = self.r.maybe_resolve_path(&path, None, parent_scope); let result = self.maybe_resolve_path(&path, None, parent_scope);
debug!( debug!(
"make_external_crate_suggestion: name={:?} path={:?} result={:?}", "make_external_crate_suggestion: name={:?} path={:?} result={:?}",
name, path, result name, path, result
@ -2046,8 +2044,8 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
/// ``` /// ```
pub(crate) fn check_for_module_export_macro( pub(crate) fn check_for_module_export_macro(
&mut self, &mut self,
import: &'b Import<'b>, import: &'a Import<'a>,
module: ModuleOrUniformRoot<'b>, module: ModuleOrUniformRoot<'a>,
ident: Ident, ident: Ident,
) -> Option<(Option<Suggestion>, Option<String>)> { ) -> Option<(Option<Suggestion>, Option<String>)> {
let ModuleOrUniformRoot::Module(mut crate_module) = module else { let ModuleOrUniformRoot::Module(mut crate_module) = module else {
@ -2064,8 +2062,8 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
return None; return None;
} }
let resolutions = self.r.resolutions(crate_module).borrow(); let resolutions = self.resolutions(crate_module).borrow();
let resolution = resolutions.get(&self.r.new_key(ident, MacroNS))?; let resolution = resolutions.get(&self.new_key(ident, MacroNS))?;
let binding = resolution.borrow().binding()?; let binding = resolution.borrow().binding()?;
if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() { if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() {
let module_name = crate_module.kind.name().unwrap(); let module_name = crate_module.kind.name().unwrap();
@ -2086,7 +2084,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
// ie. `use a::b::{c, d, e};` // ie. `use a::b::{c, d, e};`
// ^^^ // ^^^
let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding( let (found_closing_brace, binding_span) = find_span_of_binding_until_next_binding(
self.r.tcx.sess, self.tcx.sess,
import.span, import.span,
import.use_span, import.use_span,
); );
@ -2105,7 +2103,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
// ie. `use a::b::{c, d};` // ie. `use a::b::{c, d};`
// ^^^ // ^^^
if let Some(previous_span) = if let Some(previous_span) =
extend_span_to_previous_binding(self.r.tcx.sess, binding_span) extend_span_to_previous_binding(self.tcx.sess, binding_span)
{ {
debug!("check_for_module_export_macro: previous_span={:?}", previous_span); debug!("check_for_module_export_macro: previous_span={:?}", previous_span);
removal_span = removal_span.with_lo(previous_span.lo()); removal_span = removal_span.with_lo(previous_span.lo());
@ -2123,7 +2121,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
// or `use a::{b, c, d}};` // or `use a::{b, c, d}};`
// ^^^^^^^^^^^ // ^^^^^^^^^^^
let (has_nested, after_crate_name) = find_span_immediately_after_crate_name( let (has_nested, after_crate_name) = find_span_immediately_after_crate_name(
self.r.tcx.sess, self.tcx.sess,
module_name, module_name,
import.use_span, import.use_span,
); );
@ -2132,7 +2130,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
has_nested, after_crate_name has_nested, after_crate_name
); );
let source_map = self.r.tcx.sess.source_map(); let source_map = self.tcx.sess.source_map();
// Make sure this is actually crate-relative. // Make sure this is actually crate-relative.
let is_definitely_crate = import let is_definitely_crate = import

View file

@ -210,6 +210,17 @@ impl<'a> NameResolution<'a> {
} }
} }
/// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
/// import errors within the same use tree into a single diagnostic.
#[derive(Debug, Clone)]
struct UnresolvedImportError {
span: Span,
label: Option<String>,
note: Option<String>,
suggestion: Option<Suggestion>,
candidates: Option<Vec<ImportSuggestion>>,
}
// Reexports of the form `pub use foo as bar;` where `foo` is `extern crate foo;` // Reexports of the form `pub use foo as bar;` where `foo` is `extern crate foo;`
// are permitted for backward-compatibility under a deprecation lint. // are permitted for backward-compatibility under a deprecation lint.
fn pub_use_of_private_extern_crate_hack(import: &Import<'_>, binding: &NameBinding<'_>) -> bool { fn pub_use_of_private_extern_crate_hack(import: &Import<'_>, binding: &NameBinding<'_>) -> bool {
@ -392,24 +403,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
} }
} }
} }
}
/// An error that may be transformed into a diagnostic later. Used to combine multiple unresolved
/// import errors within the same use tree into a single diagnostic.
#[derive(Debug, Clone)]
struct UnresolvedImportError {
span: Span,
label: Option<String>,
note: Option<String>,
suggestion: Option<Suggestion>,
candidates: Option<Vec<ImportSuggestion>>,
}
pub(crate) struct ImportResolver<'a, 'b, 'tcx> {
pub r: &'a mut Resolver<'b, 'tcx>,
}
impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
// Import resolution // Import resolution
// //
// This is a fixed-point algorithm. We resolve imports until our efforts // This is a fixed-point algorithm. We resolve imports until our efforts
@ -421,28 +415,28 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
/// Resolves all imports for the crate. This method performs the fixed- /// Resolves all imports for the crate. This method performs the fixed-
/// point iteration. /// point iteration.
pub(crate) fn resolve_imports(&mut self) { pub(crate) fn resolve_imports(&mut self) {
let mut prev_num_indeterminates = self.r.indeterminate_imports.len() + 1; let mut prev_num_indeterminates = self.indeterminate_imports.len() + 1;
while self.r.indeterminate_imports.len() < prev_num_indeterminates { while self.indeterminate_imports.len() < prev_num_indeterminates {
prev_num_indeterminates = self.r.indeterminate_imports.len(); prev_num_indeterminates = self.indeterminate_imports.len();
for import in mem::take(&mut self.r.indeterminate_imports) { for import in mem::take(&mut self.indeterminate_imports) {
match self.resolve_import(&import) { match self.resolve_import(&import) {
true => self.r.determined_imports.push(import), true => self.determined_imports.push(import),
false => self.r.indeterminate_imports.push(import), false => self.indeterminate_imports.push(import),
} }
} }
} }
} }
pub(crate) fn finalize_imports(&mut self) { pub(crate) fn finalize_imports(&mut self) {
for module in self.r.arenas.local_modules().iter() { for module in self.arenas.local_modules().iter() {
self.finalize_resolutions_in(module); self.finalize_resolutions_in(module);
} }
let mut seen_spans = FxHashSet::default(); let mut seen_spans = FxHashSet::default();
let mut errors = vec![]; let mut errors = vec![];
let mut prev_root_id: NodeId = NodeId::from_u32(0); let mut prev_root_id: NodeId = NodeId::from_u32(0);
let determined_imports = mem::take(&mut self.r.determined_imports); let determined_imports = mem::take(&mut self.determined_imports);
let indeterminate_imports = mem::take(&mut self.r.indeterminate_imports); let indeterminate_imports = mem::take(&mut self.indeterminate_imports);
for (is_indeterminate, import) in determined_imports for (is_indeterminate, import) in determined_imports
.into_iter() .into_iter()
@ -453,7 +447,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
// If this import is unresolved then create a dummy import // If this import is unresolved then create a dummy import
// resolution for it so that later resolve stages won't complain. // resolution for it so that later resolve stages won't complain.
self.r.import_dummy_binding(import); self.import_dummy_binding(import);
if let Some(err) = unresolved_import_error { if let Some(err) = unresolved_import_error {
if let ImportKind::Single { source, ref source_bindings, .. } = import.kind { if let ImportKind::Single { source, ref source_bindings, .. } = import.kind {
@ -526,7 +520,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
.collect::<Vec<_>>(); .collect::<Vec<_>>();
let msg = format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),); let msg = format!("unresolved import{} {}", pluralize!(paths.len()), paths.join(", "),);
let mut diag = struct_span_err!(self.r.tcx.sess, span, E0432, "{}", &msg); let mut diag = struct_span_err!(self.tcx.sess, span, E0432, "{}", &msg);
if let Some((_, UnresolvedImportError { note: Some(note), .. })) = errors.iter().last() { if let Some((_, UnresolvedImportError { note: Some(note), .. })) = errors.iter().last() {
diag.note(note); diag.note(note);
@ -548,7 +542,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
if let Some(candidates) = &err.candidates { if let Some(candidates) = &err.candidates {
match &import.kind { match &import.kind {
ImportKind::Single { nested: false, source, target, .. } => import_candidates( ImportKind::Single { nested: false, source, target, .. } => import_candidates(
self.r.tcx, self.tcx,
&mut diag, &mut diag,
Some(err.span), Some(err.span),
&candidates, &candidates,
@ -560,7 +554,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
), ),
ImportKind::Single { nested: true, source, target, .. } => { ImportKind::Single { nested: true, source, target, .. } => {
import_candidates( import_candidates(
self.r.tcx, self.tcx,
&mut diag, &mut diag,
None, None,
&candidates, &candidates,
@ -581,7 +575,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
/// Attempts to resolve the given import, returning true if its resolution is determined. /// Attempts to resolve the given import, returning true if its resolution is determined.
/// If successful, the resolved bindings are written into the module. /// If successful, the resolved bindings are written into the module.
fn resolve_import(&mut self, import: &'b Import<'b>) -> bool { fn resolve_import(&mut self, import: &'a Import<'a>) -> bool {
debug!( debug!(
"(resolving import for module) resolving import `{}::...` in `{}`", "(resolving import for module) resolving import `{}::...` in `{}`",
Segment::names_to_string(&import.module_path), Segment::names_to_string(&import.module_path),
@ -594,8 +588,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
// For better failure detection, pretend that the import will // For better failure detection, pretend that the import will
// not define any names while resolving its module path. // not define any names while resolving its module path.
let orig_vis = import.vis.take(); let orig_vis = import.vis.take();
let path_res = let path_res = self.maybe_resolve_path(&import.module_path, None, &import.parent_scope);
self.r.maybe_resolve_path(&import.module_path, None, &import.parent_scope);
import.vis.set(orig_vis); import.vis.set(orig_vis);
match path_res { match path_res {
@ -623,7 +616,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
}; };
let mut indeterminate = false; let mut indeterminate = false;
self.r.per_ns(|this, ns| { self.per_ns(|this, ns| {
if !type_ns_only || ns == TypeNS { if !type_ns_only || ns == TypeNS {
if let Err(Undetermined) = source_bindings[ns].get() { if let Err(Undetermined) = source_bindings[ns].get() {
// For better failure detection, pretend that the import will // For better failure detection, pretend that the import will
@ -676,15 +669,15 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
/// ///
/// Optionally returns an unresolved import error. This error is buffered and used to /// Optionally returns an unresolved import error. This error is buffered and used to
/// consolidate multiple unresolved import errors into a single diagnostic. /// consolidate multiple unresolved import errors into a single diagnostic.
fn finalize_import(&mut self, import: &'b Import<'b>) -> Option<UnresolvedImportError> { fn finalize_import(&mut self, import: &'a Import<'a>) -> Option<UnresolvedImportError> {
let orig_vis = import.vis.take(); let orig_vis = import.vis.take();
let ignore_binding = match &import.kind { let ignore_binding = match &import.kind {
ImportKind::Single { target_bindings, .. } => target_bindings[TypeNS].get(), ImportKind::Single { target_bindings, .. } => target_bindings[TypeNS].get(),
_ => None, _ => None,
}; };
let prev_ambiguity_errors_len = self.r.ambiguity_errors.len(); let prev_ambiguity_errors_len = self.ambiguity_errors.len();
let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span); let finalize = Finalize::with_root_span(import.root_id, import.span, import.root_span);
let path_res = self.r.resolve_path( let path_res = self.resolve_path(
&import.module_path, &import.module_path,
None, None,
&import.parent_scope, &import.parent_scope,
@ -692,7 +685,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
ignore_binding, ignore_binding,
); );
let no_ambiguity = self.r.ambiguity_errors.len() == prev_ambiguity_errors_len; let no_ambiguity = self.ambiguity_errors.len() == prev_ambiguity_errors_len;
import.vis.set(orig_vis); import.vis.set(orig_vis);
let module = match path_res { let module = match path_res {
PathResult::Module(module) => { PathResult::Module(module) => {
@ -701,10 +694,10 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity { if !ModuleOrUniformRoot::same_def(module, initial_module) && no_ambiguity {
span_bug!(import.span, "inconsistent resolution for an import"); span_bug!(import.span, "inconsistent resolution for an import");
} }
} else if self.r.privacy_errors.is_empty() { } else if self.privacy_errors.is_empty() {
let msg = "cannot determine resolution for the import"; let msg = "cannot determine resolution for the import";
let msg_note = "import resolution is stuck, try simplifying other imports"; let msg_note = "import resolution is stuck, try simplifying other imports";
self.r.tcx.sess.struct_span_err(import.span, msg).note(msg_note).emit(); self.tcx.sess.struct_span_err(import.span, msg).note(msg_note).emit();
} }
module module
@ -712,8 +705,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => { PathResult::Failed { is_error_from_last_segment: false, span, label, suggestion } => {
if no_ambiguity { if no_ambiguity {
assert!(import.imported_module.get().is_none()); assert!(import.imported_module.get().is_none());
self.r self.report_error(span, ResolutionError::FailedToResolve { label, suggestion });
.report_error(span, ResolutionError::FailedToResolve { label, suggestion });
} }
return None; return None;
} }
@ -775,7 +767,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
// 2 segments, so the `resolve_path` above won't trigger it. // 2 segments, so the `resolve_path` above won't trigger it.
let mut full_path = import.module_path.clone(); let mut full_path = import.module_path.clone();
full_path.push(Segment::from_ident(Ident::empty())); full_path.push(Segment::from_ident(Ident::empty()));
self.r.lint_if_path_starts_with_module(Some(finalize), &full_path, None); self.lint_if_path_starts_with_module(Some(finalize), &full_path, None);
} }
if let ModuleOrUniformRoot::Module(module) = module { if let ModuleOrUniformRoot::Module(module) = module {
@ -794,10 +786,10 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
} }
if !is_prelude if !is_prelude
&& let Some(max_vis) = max_vis.get() && let Some(max_vis) = max_vis.get()
&& !max_vis.is_at_least(import.expect_vis(), &*self.r) && !max_vis.is_at_least(import.expect_vis(), &*self)
{ {
let msg = "glob import doesn't reexport anything because no candidate is public enough"; let msg = "glob import doesn't reexport anything because no candidate is public enough";
self.r.lint_buffer.buffer_lint(UNUSED_IMPORTS, id, import.span, msg); self.lint_buffer.buffer_lint(UNUSED_IMPORTS, id, import.span, msg);
} }
return None; return None;
} }
@ -805,7 +797,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
}; };
let mut all_ns_err = true; let mut all_ns_err = true;
self.r.per_ns(|this, ns| { self.per_ns(|this, ns| {
if !type_ns_only || ns == TypeNS { if !type_ns_only || ns == TypeNS {
let orig_vis = import.vis.take(); let orig_vis = import.vis.take();
let binding = this.resolve_ident_in_module( let binding = this.resolve_ident_in_module(
@ -874,7 +866,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
if all_ns_err { if all_ns_err {
let mut all_ns_failed = true; let mut all_ns_failed = true;
self.r.per_ns(|this, ns| { self.per_ns(|this, ns| {
if !type_ns_only || ns == TypeNS { if !type_ns_only || ns == TypeNS {
let binding = this.resolve_ident_in_module( let binding = this.resolve_ident_in_module(
module, module,
@ -892,9 +884,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
return if all_ns_failed { return if all_ns_failed {
let resolutions = match module { let resolutions = match module {
ModuleOrUniformRoot::Module(module) => { ModuleOrUniformRoot::Module(module) => Some(self.resolutions(module).borrow()),
Some(self.r.resolutions(module).borrow())
}
_ => None, _ => None,
}; };
let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter()); let resolutions = resolutions.as_ref().into_iter().flat_map(|r| r.iter());
@ -963,7 +953,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
}; };
let parent_suggestion = let parent_suggestion =
self.r.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true); self.lookup_import_candidates(ident, TypeNS, &import.parent_scope, |_| true);
Some(UnresolvedImportError { Some(UnresolvedImportError {
span: import.span, span: import.span,
@ -985,7 +975,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
let mut reexport_error = None; let mut reexport_error = None;
let mut any_successful_reexport = false; let mut any_successful_reexport = false;
let mut crate_private_reexport = false; let mut crate_private_reexport = false;
self.r.per_ns(|this, ns| { self.per_ns(|this, ns| {
if let Ok(binding) = source_bindings[ns].get() { if let Ok(binding) = source_bindings[ns].get() {
if !binding.vis.is_at_least(import.expect_vis(), &*this) { if !binding.vis.is_at_least(import.expect_vis(), &*this) {
reexport_error = Some((ns, binding)); reexport_error = Some((ns, binding));
@ -1010,7 +1000,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
`pub`", `pub`",
ident ident
); );
self.r.lint_buffer.buffer_lint( self.lint_buffer.buffer_lint(
PUB_USE_OF_PRIVATE_EXTERN_CRATE, PUB_USE_OF_PRIVATE_EXTERN_CRATE,
import_id, import_id,
import.span, import.span,
@ -1033,17 +1023,17 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
format!("re-export of private `{}`", ident) format!("re-export of private `{}`", ident)
}; };
struct_span_err!(self.r.tcx.sess, import.span, E0365, "{}", error_msg) struct_span_err!(self.tcx.sess, import.span, E0365, "{}", error_msg)
.span_label(import.span, label_msg) .span_label(import.span, label_msg)
.note(&format!("consider declaring type or module `{}` with `pub`", ident)) .note(&format!("consider declaring type or module `{}` with `pub`", ident))
.emit(); .emit();
} else { } else {
let mut err = let mut err =
struct_span_err!(self.r.tcx.sess, import.span, E0364, "{error_msg}"); struct_span_err!(self.tcx.sess, import.span, E0364, "{error_msg}");
match binding.kind { match binding.kind {
NameBindingKind::Res(Res::Def(DefKind::Macro(_), def_id)) NameBindingKind::Res(Res::Def(DefKind::Macro(_), def_id))
// exclude decl_macro // exclude decl_macro
if self.r.get_macro_by_def_id(def_id).macro_rules => if self.get_macro_by_def_id(def_id).macro_rules =>
{ {
err.span_help( err.span_help(
binding.span, binding.span,
@ -1069,7 +1059,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
// 2 segments, so the `resolve_path` above won't trigger it. // 2 segments, so the `resolve_path` above won't trigger it.
let mut full_path = import.module_path.clone(); let mut full_path = import.module_path.clone();
full_path.push(Segment::from_ident(ident)); full_path.push(Segment::from_ident(ident));
self.r.per_ns(|this, ns| { self.per_ns(|this, ns| {
if let Ok(binding) = source_bindings[ns].get() { if let Ok(binding) = source_bindings[ns].get() {
this.lint_if_path_starts_with_module(Some(finalize), &full_path, Some(binding)); this.lint_if_path_starts_with_module(Some(finalize), &full_path, Some(binding));
} }
@ -1079,7 +1069,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
// Record what this import resolves to for later uses in documentation, // Record what this import resolves to for later uses in documentation,
// this may resolve to either a value or a type, but for documentation // this may resolve to either a value or a type, but for documentation
// purposes it's good enough to just favor one over the other. // purposes it's good enough to just favor one over the other.
self.r.per_ns(|this, ns| { self.per_ns(|this, ns| {
if let Ok(binding) = source_bindings[ns].get() { if let Ok(binding) = source_bindings[ns].get() {
this.import_res_map.entry(import_id).or_default()[ns] = Some(binding.res()); this.import_res_map.entry(import_id).or_default()[ns] = Some(binding.res());
} }
@ -1094,9 +1084,9 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
fn check_for_redundant_imports( fn check_for_redundant_imports(
&mut self, &mut self,
ident: Ident, ident: Ident,
import: &'b Import<'b>, import: &'a Import<'a>,
source_bindings: &PerNS<Cell<Result<&'b NameBinding<'b>, Determinacy>>>, source_bindings: &PerNS<Cell<Result<&'a NameBinding<'a>, Determinacy>>>,
target_bindings: &PerNS<Cell<Option<&'b NameBinding<'b>>>>, target_bindings: &PerNS<Cell<Option<&'a NameBinding<'a>>>>,
target: Ident, target: Ident,
) { ) {
// This function is only called for single imports. // This function is only called for single imports.
@ -1117,7 +1107,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None }; let mut redundant_span = PerNS { value_ns: None, type_ns: None, macro_ns: None };
self.r.per_ns(|this, ns| { self.per_ns(|this, ns| {
if let Ok(binding) = source_bindings[ns].get() { if let Ok(binding) = source_bindings[ns].get() {
if binding.res() == Res::Err { if binding.res() == Res::Err {
return; return;
@ -1147,7 +1137,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
let mut redundant_spans: Vec<_> = redundant_span.present_items().collect(); let mut redundant_spans: Vec<_> = redundant_span.present_items().collect();
redundant_spans.sort(); redundant_spans.sort();
redundant_spans.dedup(); redundant_spans.dedup();
self.r.lint_buffer.buffer_lint_with_diagnostic( self.lint_buffer.buffer_lint_with_diagnostic(
UNUSED_IMPORTS, UNUSED_IMPORTS,
id, id,
import.span, import.span,
@ -1157,22 +1147,22 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
} }
} }
fn resolve_glob_import(&mut self, import: &'b Import<'b>) { fn resolve_glob_import(&mut self, import: &'a Import<'a>) {
// This function is only called for glob imports. // This function is only called for glob imports.
let ImportKind::Glob { id, is_prelude, .. } = import.kind else { unreachable!() }; let ImportKind::Glob { id, is_prelude, .. } = import.kind else { unreachable!() };
let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else { let ModuleOrUniformRoot::Module(module) = import.imported_module.get().unwrap() else {
self.r.tcx.sess.span_err(import.span, "cannot glob-import all possible crates"); self.tcx.sess.span_err(import.span, "cannot glob-import all possible crates");
return; return;
}; };
if module.is_trait() { if module.is_trait() {
self.r.tcx.sess.span_err(import.span, "items in traits are not importable"); self.tcx.sess.span_err(import.span, "items in traits are not importable");
return; return;
} else if ptr::eq(module, import.parent_scope.module) { } else if ptr::eq(module, import.parent_scope.module) {
return; return;
} else if is_prelude { } else if is_prelude {
self.r.prelude = Some(module); self.prelude = Some(module);
return; return;
} }
@ -1182,7 +1172,6 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
// Ensure that `resolutions` isn't borrowed during `try_define`, // Ensure that `resolutions` isn't borrowed during `try_define`,
// since it might get updated via a glob cycle. // since it might get updated via a glob cycle.
let bindings = self let bindings = self
.r
.resolutions(module) .resolutions(module)
.borrow() .borrow()
.iter() .iter()
@ -1192,30 +1181,30 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
.collect::<Vec<_>>(); .collect::<Vec<_>>();
for (mut key, binding) in bindings { for (mut key, binding) in bindings {
let scope = match key.ident.span.reverse_glob_adjust(module.expansion, import.span) { let scope = match key.ident.span.reverse_glob_adjust(module.expansion, import.span) {
Some(Some(def)) => self.r.expn_def_scope(def), Some(Some(def)) => self.expn_def_scope(def),
Some(None) => import.parent_scope.module, Some(None) => import.parent_scope.module,
None => continue, None => continue,
}; };
if self.r.is_accessible_from(binding.vis, scope) { if self.is_accessible_from(binding.vis, scope) {
let imported_binding = self.r.import(binding, import); let imported_binding = self.import(binding, import);
let _ = self.r.try_define(import.parent_scope.module, key, imported_binding); let _ = self.try_define(import.parent_scope.module, key, imported_binding);
} }
} }
// Record the destination of this import // Record the destination of this import
self.r.record_partial_res(id, PartialRes::new(module.res().unwrap())); self.record_partial_res(id, PartialRes::new(module.res().unwrap()));
} }
// Miscellaneous post-processing, including recording re-exports, // Miscellaneous post-processing, including recording re-exports,
// reporting conflicts, and reporting unresolved imports. // reporting conflicts, and reporting unresolved imports.
fn finalize_resolutions_in(&mut self, module: Module<'b>) { fn finalize_resolutions_in(&mut self, module: Module<'a>) {
// Since import resolution is finished, globs will not define any more names. // Since import resolution is finished, globs will not define any more names.
*module.globs.borrow_mut() = Vec::new(); *module.globs.borrow_mut() = Vec::new();
if let Some(def_id) = module.opt_def_id() { if let Some(def_id) = module.opt_def_id() {
let mut reexports = Vec::new(); let mut reexports = Vec::new();
module.for_each_child(self.r, |this, ident, _, binding| { module.for_each_child(self, |this, ident, _, binding| {
if let Some(res) = this.is_reexport(binding) { if let Some(res) = this.is_reexport(binding) {
reexports.push(ModChild { reexports.push(ModChild {
ident, ident,
@ -1230,7 +1219,7 @@ impl<'a, 'b, 'tcx> ImportResolver<'a, 'b, 'tcx> {
if !reexports.is_empty() { if !reexports.is_empty() {
// Call to `expect_local` should be fine because current // Call to `expect_local` should be fine because current
// code is only called for local modules. // code is only called for local modules.
self.r.reexport_map.insert(def_id.expect_local(), reexports); self.reexport_map.insert(def_id.expect_local(), reexports);
} }
} }
} }

View file

@ -57,7 +57,7 @@ use std::collections::BTreeSet;
use std::{fmt, ptr}; use std::{fmt, ptr};
use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion}; use diagnostics::{ImportSuggestion, LabelSuggestion, Suggestion};
use imports::{Import, ImportKind, ImportResolver, NameResolution}; use imports::{Import, ImportKind, NameResolution};
use late::{HasGenericParams, PathSource, PatternSource}; use late::{HasGenericParams, PathSource, PatternSource};
use macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef}; use macros::{MacroRulesBinding, MacroRulesScope, MacroRulesScopeRef};
@ -1486,9 +1486,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
/// Entry point to crate resolution. /// Entry point to crate resolution.
pub fn resolve_crate(&mut self, krate: &Crate) { pub fn resolve_crate(&mut self, krate: &Crate) {
self.tcx.sess.time("resolve_crate", || { self.tcx.sess.time("resolve_crate", || {
self.tcx self.tcx.sess.time("finalize_imports", || self.finalize_imports());
.sess
.time("finalize_imports", || ImportResolver { r: self }.finalize_imports());
self.tcx.sess.time("compute_effective_visibilities", || { self.tcx.sess.time("compute_effective_visibilities", || {
EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate) EffectiveVisibilitiesVisitor::compute_effective_visibilities(self, krate)
}); });

View file

@ -1,7 +1,6 @@
//! A bunch of methods and structures more or less related to resolving macros and //! A bunch of methods and structures more or less related to resolving macros and
//! interface provided by `Resolver` to macro expander. //! interface provided by `Resolver` to macro expander.
use crate::imports::ImportResolver;
use crate::Namespace::*; use crate::Namespace::*;
use crate::{BuiltinMacroState, Determinacy}; use crate::{BuiltinMacroState, Determinacy};
use crate::{DeriveData, Finalize, ParentScope, ResolutionError, Resolver, ScopeSet}; use crate::{DeriveData, Finalize, ParentScope, ResolutionError, Resolver, ScopeSet};
@ -233,7 +232,7 @@ impl<'a, 'tcx> ResolverExpand for Resolver<'a, 'tcx> {
} }
fn resolve_imports(&mut self) { fn resolve_imports(&mut self) {
ImportResolver { r: self }.resolve_imports() self.resolve_imports()
} }
fn resolve_macro_invocation( fn resolve_macro_invocation(