rustc_resolve: reduce rightwards drift with let..else 👉💨

This commit is contained in:
Yotam Ofek 2025-01-20 20:35:45 +00:00
parent cf91a93d09
commit ae87d005bc
4 changed files with 389 additions and 383 deletions

View File

@ -1038,14 +1038,16 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
if filter_fn(res) { if filter_fn(res) {
for derive in parent_scope.derives { for derive in parent_scope.derives {
let parent_scope = &ParentScope { derives: &[], ..*parent_scope }; let parent_scope = &ParentScope { derives: &[], ..*parent_scope };
if let Ok((Some(ext), _)) = this.resolve_macro_path( let Ok((Some(ext), _)) = this.resolve_macro_path(
derive, derive,
Some(MacroKind::Derive), Some(MacroKind::Derive),
parent_scope, parent_scope,
false, false,
false, false,
None, None,
) { ) else {
continue;
};
suggestions.extend( suggestions.extend(
ext.helper_attrs ext.helper_attrs
.iter() .iter()
@ -1054,7 +1056,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
} }
} }
} }
}
Scope::MacroRules(macro_rules_scope) => { Scope::MacroRules(macro_rules_scope) => {
if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() { if let MacroRulesScope::Binding(macro_rules_binding) = macro_rules_scope.get() {
let res = macro_rules_binding.binding.res(); let res = macro_rules_binding.binding.res();
@ -1362,8 +1363,11 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
// otherwise cause duplicate suggestions. // otherwise cause duplicate suggestions.
continue; continue;
} }
let crate_id = self.crate_loader(|c| c.maybe_process_path_extern(ident.name)); let Some(crate_id) = self.crate_loader(|c| c.maybe_process_path_extern(ident.name))
if let Some(crate_id) = crate_id { else {
continue;
};
let crate_def_id = crate_id.as_def_id(); let crate_def_id = crate_id.as_def_id();
let crate_root = self.expect_module(crate_def_id); let crate_root = self.expect_module(crate_def_id);
@ -1405,7 +1409,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
)); ));
} }
} }
}
suggestions suggestions
} }
@ -1500,7 +1503,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
}); });
} }
for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] { for ns in [Namespace::MacroNS, Namespace::TypeNS, Namespace::ValueNS] {
if let Ok(binding) = self.early_resolve_ident_in_lexical_scope( let Ok(binding) = self.early_resolve_ident_in_lexical_scope(
ident, ident,
ScopeSet::All(ns), ScopeSet::All(ns),
parent_scope, parent_scope,
@ -1508,11 +1511,12 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
false, false,
None, None,
None, None,
) { ) else {
continue;
};
let desc = match binding.res() { let desc = match binding.res() {
Res::Def(DefKind::Macro(MacroKind::Bang), _) => { Res::Def(DefKind::Macro(MacroKind::Bang), _) => "a function-like macro".to_string(),
"a function-like macro".to_string()
}
Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => { Res::Def(DefKind::Macro(MacroKind::Attr), _) | Res::NonMacroAttr(..) => {
format!("an attribute: `#[{ident}]`") format!("an attribute: `#[{ident}]`")
} }
@ -1556,7 +1560,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
return; return;
} }
} }
}
pub(crate) fn add_typo_suggestion( pub(crate) fn add_typo_suggestion(
&self, &self,
@ -1738,15 +1741,16 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
/// If the binding refers to a tuple struct constructor with fields, /// If the binding refers to a tuple struct constructor with fields,
/// returns the span of its fields. /// returns the span of its fields.
fn ctor_fields_span(&self, binding: NameBinding<'_>) -> Option<Span> { fn ctor_fields_span(&self, binding: NameBinding<'_>) -> Option<Span> {
if let NameBindingKind::Res(Res::Def( let NameBindingKind::Res(Res::Def(
DefKind::Ctor(CtorOf::Struct, CtorKind::Fn), DefKind::Ctor(CtorOf::Struct, CtorKind::Fn),
ctor_def_id, ctor_def_id,
)) = binding.kind )) = binding.kind
{ else {
return None;
};
let def_id = self.tcx.parent(ctor_def_id); let def_id = self.tcx.parent(ctor_def_id);
return self.field_idents(def_id)?.iter().map(|&f| f.span).reduce(Span::to); // None for `struct Foo()` self.field_idents(def_id)?.iter().map(|&f| f.span).reduce(Span::to) // None for `struct Foo()`
}
None
} }
fn report_privacy_error(&mut self, privacy_error: &PrivacyError<'ra>) { fn report_privacy_error(&mut self, privacy_error: &PrivacyError<'ra>) {
@ -2399,7 +2403,9 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
let binding_key = BindingKey::new(ident, MacroNS); let binding_key = BindingKey::new(ident, MacroNS);
let resolution = resolutions.get(&binding_key)?; let resolution = resolutions.get(&binding_key)?;
let binding = resolution.borrow().binding()?; let binding = resolution.borrow().binding()?;
if let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() { let Res::Def(DefKind::Macro(MacroKind::Bang), _) = binding.res() else {
return None;
};
let module_name = crate_module.kind.name().unwrap(); let module_name = crate_module.kind.name().unwrap();
let import_snippet = match import.kind { let import_snippet = match import.kind {
ImportKind::Single { source, target, .. } if source != target => { ImportKind::Single { source, target, .. } if source != target => {
@ -2451,11 +2457,8 @@ impl<'ra, 'tcx> Resolver<'ra, '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) =
self.tcx.sess, find_span_immediately_after_crate_name(self.tcx.sess, module_name, import.use_span);
module_name,
import.use_span,
);
debug!(has_nested, ?after_crate_name); debug!(has_nested, ?after_crate_name);
let source_map = self.tcx.sess.source_map(); let source_map = self.tcx.sess.source_map();
@ -2485,8 +2488,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
// Add a `};` to the end if nested, matching the `{` added at the start. // Add a `};` to the end if nested, matching the `{` added at the start.
if !has_nested { if !has_nested {
corrections corrections.push((source_map.end_point(after_crate_name), "};".to_string()));
.push((source_map.end_point(after_crate_name), "};".to_string()));
} }
} else { } else {
// If the root import is module-relative, add the import separately // If the root import is module-relative, add the import separately
@ -2502,12 +2504,14 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
String::from("a macro with this name exists at the root of the crate"), String::from("a macro with this name exists at the root of the crate"),
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
)); ));
Some((suggestion, Some("this could be because a macro annotated with `#[macro_export]` will be exported \ Some((
suggestion,
Some(
"this could be because a macro annotated with `#[macro_export]` will be exported \
at the root of the crate instead of the module where it is defined" at the root of the crate instead of the module where it is defined"
.to_string()))) .to_string(),
} else { ),
None ))
}
} }
/// Finds a cfg-ed out item inside `module` with the matching name. /// Finds a cfg-ed out item inside `module` with the matching name.

View File

@ -118,7 +118,9 @@ impl<'a, 'ra, 'tcx> EffectiveVisibilitiesVisitor<'a, 'ra, 'tcx> {
let resolutions = self.r.resolutions(module); let resolutions = self.r.resolutions(module);
for (_, name_resolution) in resolutions.borrow().iter() { for (_, name_resolution) in resolutions.borrow().iter() {
if let Some(mut binding) = name_resolution.borrow().binding() { let Some(mut binding) = name_resolution.borrow().binding() else {
continue;
};
// Set the given effective visibility level to `Level::Direct` and // Set the given effective visibility level to `Level::Direct` and
// sets the rest of the `use` chain to `Level::Reexported` until // sets the rest of the `use` chain to `Level::Reexported` until
// we hit the actual exported item. // we hit the actual exported item.
@ -151,7 +153,6 @@ impl<'a, 'ra, 'tcx> EffectiveVisibilitiesVisitor<'a, 'ra, 'tcx> {
} }
} }
} }
}
fn effective_vis_or_private(&mut self, parent_id: ParentId<'ra>) -> EffectiveVisibility { fn effective_vis_or_private(&mut self, parent_id: ParentId<'ra>) -> EffectiveVisibility {
// Private nodes are only added to the table for caching, they could be added or removed at // Private nodes are only added to the table for caching, they could be added or removed at

View File

@ -542,7 +542,8 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
// resolution for it so that later resolve stages won't complain. // resolution for it so that later resolve stages won't complain.
self.import_dummy_binding(*import, is_indeterminate); self.import_dummy_binding(*import, is_indeterminate);
if let Some(err) = unresolved_import_error { let Some(err) = unresolved_import_error else { continue };
glob_error |= import.is_glob(); glob_error |= import.is_glob();
if let ImportKind::Single { source, ref source_bindings, .. } = import.kind if let ImportKind::Single { source, ref source_bindings, .. } = import.kind
@ -553,9 +554,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
continue; continue;
} }
if prev_root_id != NodeId::ZERO if prev_root_id != NodeId::ZERO && prev_root_id != import.root_id && !errors.is_empty()
&& prev_root_id != import.root_id
&& !errors.is_empty()
{ {
// In the case of a new import line, throw a diagnostic message // In the case of a new import line, throw a diagnostic message
// for the previous line. // for the previous line.
@ -567,7 +566,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
prev_root_id = import.root_id; prev_root_id = import.root_id;
} }
} }
}
if !errors.is_empty() { if !errors.is_empty() {
self.throw_unresolved_import_error(errors, glob_error); self.throw_unresolved_import_error(errors, glob_error);
@ -607,7 +605,8 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
for (key, resolution) in self.resolutions(*module).borrow().iter() { for (key, resolution) in self.resolutions(*module).borrow().iter() {
let resolution = resolution.borrow(); let resolution = resolution.borrow();
if let Some(binding) = resolution.binding { let Some(binding) = resolution.binding else { continue };
if let NameBindingKind::Import { import, .. } = binding.kind if let NameBindingKind::Import { import, .. } = binding.kind
&& let Some((amb_binding, _)) = binding.ambiguity && let Some((amb_binding, _)) = binding.ambiguity
&& binding.res() != Res::Err && binding.res() != Res::Err
@ -664,7 +663,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
} }
} }
} }
}
fn throw_unresolved_import_error( fn throw_unresolved_import_error(
&mut self, &mut self,
@ -1242,7 +1240,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
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.per_ns(|this, ns| { self.per_ns(|this, ns| {
if let Ok(binding) = source_bindings[ns].get() { let Ok(binding) = source_bindings[ns].get() else {
return;
};
if !binding.vis.is_at_least(import.vis, this.tcx) { if !binding.vis.is_at_least(import.vis, this.tcx) {
reexport_error = Some((ns, binding)); reexport_error = Some((ns, binding));
if let ty::Visibility::Restricted(binding_def_id) = binding.vis if let ty::Visibility::Restricted(binding_def_id) = binding.vis
@ -1253,7 +1254,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
} else { } else {
any_successful_reexport = true; any_successful_reexport = true;
} }
}
}); });
// All namespaces must be re-exported with extra visibility for an error to occur. // All namespaces must be re-exported with extra visibility for an error to occur.
@ -1469,7 +1469,8 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
// 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() { let Some(def_id) = module.opt_def_id() else { return };
let mut children = Vec::new(); let mut children = Vec::new();
module.for_each_child(self, |this, ident, _, binding| { module.for_each_child(self, |this, ident, _, binding| {
@ -1492,7 +1493,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
self.module_children.insert(def_id.expect_local(), children); self.module_children.insert(def_id.expect_local(), children);
} }
} }
}
} }
fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String { fn import_path_to_string(names: &[Ident], import_kind: &ImportKind<'_>, span: Span) -> String {

View File

@ -1234,7 +1234,10 @@ impl<'ra: 'ast, 'ast, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'r
} }
fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) { fn visit_path_segment(&mut self, path_segment: &'ast PathSegment) {
if let Some(ref args) = path_segment.args { let Some(ref args) = path_segment.args else {
return;
};
match &**args { match &**args {
GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args), GenericArgs::AngleBracketed(..) => visit::walk_generic_args(self, args),
GenericArgs::Parenthesized(p_args) => { GenericArgs::Parenthesized(p_args) => {
@ -1283,7 +1286,6 @@ impl<'ra: 'ast, 'ast, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'r
GenericArgs::ParenthesizedElided(_) => {} GenericArgs::ParenthesizedElided(_) => {}
} }
} }
}
fn visit_where_predicate(&mut self, p: &'ast WherePredicate) { fn visit_where_predicate(&mut self, p: &'ast WherePredicate) {
debug!("visit_where_predicate {:?}", p); debug!("visit_where_predicate {:?}", p);
@ -3496,7 +3498,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
self.visit_ty(&qself.ty); self.visit_ty(&qself.ty);
} }
self.visit_path(&delegation.path, delegation.id); self.visit_path(&delegation.path, delegation.id);
if let Some(body) = &delegation.body { let Some(body) = &delegation.body else { return };
self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| { self.with_rib(ValueNS, RibKind::FnOrCoroutine, |this| {
// `PatBoundCtx` is not necessary in this context // `PatBoundCtx` is not necessary in this context
let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())]; let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];
@ -3511,7 +3513,6 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
this.visit_block(body); this.visit_block(body);
}); });
} }
}
fn resolve_params(&mut self, params: &'ast [Param]) { fn resolve_params(&mut self, params: &'ast [Param]) {
let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())]; let mut bindings = smallvec![(PatBoundCtx::Product, Default::default())];