1
Fork 0

rustc_resolve: flatten nested ifs

This commit is contained in:
Yotam Ofek 2025-01-20 17:41:03 +00:00
parent a93616acf3
commit cf91a93d09
5 changed files with 198 additions and 229 deletions

View file

@ -645,10 +645,10 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> {
let self_spans = items
.iter()
.filter_map(|(use_tree, _)| {
if let ast::UseTreeKind::Simple(..) = use_tree.kind {
if use_tree.ident().name == kw::SelfLower {
return Some(use_tree.span);
}
if let ast::UseTreeKind::Simple(..) = use_tree.kind
&& use_tree.ident().name == kw::SelfLower
{
return Some(use_tree.span);
}
None
@ -947,19 +947,19 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> {
let imported_binding = self.r.import(binding, import);
if parent == self.r.graph_root {
let ident = ident.normalize_to_macros_2_0();
if let Some(entry) = self.r.extern_prelude.get(&ident) {
if expansion != LocalExpnId::ROOT && orig_name.is_some() && !entry.is_import() {
self.r.dcx().emit_err(
errors::MacroExpandedExternCrateCannotShadowExternArguments {
span: item.span,
},
);
// `return` is intended to discard this binding because it's an
// unregistered ambiguity error which would result in a panic
// caused by inconsistency `path_res`
// more details: https://github.com/rust-lang/rust/pull/111761
return;
}
if let Some(entry) = self.r.extern_prelude.get(&ident)
&& expansion != LocalExpnId::ROOT
&& orig_name.is_some()
&& !entry.is_import()
{
self.r.dcx().emit_err(
errors::MacroExpandedExternCrateCannotShadowExternArguments { span: item.span },
);
// `return` is intended to discard this binding because it's an
// unregistered ambiguity error which would result in a panic
// caused by inconsistency `path_res`
// more details: https://github.com/rust-lang/rust/pull/111761
return;
}
let entry = self
.r
@ -1040,10 +1040,10 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> {
span: item.span,
});
}
if let ItemKind::ExternCrate(Some(orig_name)) = item.kind {
if orig_name == kw::SelfLower {
self.r.dcx().emit_err(errors::MacroUseExternCrateSelf { span: attr.span });
}
if let ItemKind::ExternCrate(Some(orig_name)) = item.kind
&& orig_name == kw::SelfLower
{
self.r.dcx().emit_err(errors::MacroUseExternCrateSelf { span: attr.span });
}
let ill_formed = |span| {
self.r.dcx().emit_err(errors::BadMacroImport { span });
@ -1179,14 +1179,12 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> {
return Some((MacroKind::Bang, item.ident, item.span));
} else if ast::attr::contains_name(&item.attrs, sym::proc_macro_attribute) {
return Some((MacroKind::Attr, item.ident, item.span));
} else if let Some(attr) = ast::attr::find_by_name(&item.attrs, sym::proc_macro_derive) {
if let Some(meta_item_inner) =
} else if let Some(attr) = ast::attr::find_by_name(&item.attrs, sym::proc_macro_derive)
&& let Some(meta_item_inner) =
attr.meta_item_list().and_then(|list| list.get(0).cloned())
{
if let Some(ident) = meta_item_inner.ident() {
return Some((MacroKind::Derive, ident, ident.span));
}
}
&& let Some(ident) = meta_item_inner.ident()
{
return Some((MacroKind::Derive, ident, ident.span));
}
None
}

View file

@ -225,10 +225,8 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
let (name, span) =
(ident.name, self.tcx.sess.source_map().guess_head_span(new_binding.span));
if let Some(s) = self.name_already_seen.get(&name) {
if s == &span {
return;
}
if self.name_already_seen.get(&name) == Some(&span) {
return;
}
let old_kind = match (ns, old_binding.module()) {
@ -380,20 +378,14 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
suggestion = Some(format!("self as {suggested_name}"))
}
ImportKind::Single { source, .. } => {
if let Some(pos) =
source.span.hi().0.checked_sub(binding_span.lo().0).map(|pos| pos as usize)
if let Some(pos) = source.span.hi().0.checked_sub(binding_span.lo().0)
&& let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(binding_span)
&& pos as usize <= snippet.len()
{
if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(binding_span) {
if pos <= snippet.len() {
span = binding_span
.with_lo(binding_span.lo() + BytePos(pos as u32))
.with_hi(
binding_span.hi()
- BytePos(if snippet.ends_with(';') { 1 } else { 0 }),
);
suggestion = Some(format!(" as {suggested_name}"));
}
}
span = binding_span.with_lo(binding_span.lo() + BytePos(pos)).with_hi(
binding_span.hi() - BytePos(if snippet.ends_with(';') { 1 } else { 0 }),
);
suggestion = Some(format!(" as {suggested_name}"));
}
}
ImportKind::ExternCrate { source, target, .. } => {
@ -510,13 +502,12 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
// If the first element of our path was actually resolved to an
// `ExternCrate` (also used for `crate::...`) then no need to issue a
// warning, this looks all good!
if let Some(binding) = second_binding {
if let NameBindingKind::Import { import, .. } = binding.kind {
// Careful: we still want to rewrite paths from renamed extern crates.
if let ImportKind::ExternCrate { source: None, .. } = import.kind {
return;
}
}
if let Some(binding) = second_binding
&& let NameBindingKind::Import { import, .. } = binding.kind
// Careful: we still want to rewrite paths from renamed extern crates.
&& let ImportKind::ExternCrate { source: None, .. } = import.kind
{
return;
}
let diag = BuiltinLintDiag::AbsPathWithModule(root_span);
@ -1215,12 +1206,11 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
}
// #90113: Do not count an inaccessible reexported item as a candidate.
if let NameBindingKind::Import { binding, .. } = name_binding.kind {
if this.is_accessible_from(binding.vis, parent_scope.module)
&& !this.is_accessible_from(name_binding.vis, parent_scope.module)
{
return;
}
if let NameBindingKind::Import { binding, .. } = name_binding.kind
&& this.is_accessible_from(binding.vis, parent_scope.module)
&& !this.is_accessible_from(name_binding.vis, parent_scope.module)
{
return;
}
let res = name_binding.res();
@ -1253,14 +1243,13 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
segms.push(ast::PathSegment::from_ident(ident));
let path = Path { span: name_binding.span, segments: segms, tokens: None };
if child_accessible {
if child_accessible
// Remove invisible match if exists
if let Some(idx) = candidates
&& let Some(idx) = candidates
.iter()
.position(|v: &ImportSuggestion| v.did == did && !v.accessible)
{
candidates.remove(idx);
}
{
candidates.remove(idx);
}
if candidates.iter().all(|v: &ImportSuggestion| v.did != did) {
@ -1545,19 +1534,19 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
macro_kind.descr_expected(),
),
};
if let crate::NameBindingKind::Import { import, .. } = binding.kind {
if !import.span.is_dummy() {
let note = errors::IdentImporterHereButItIsDesc {
span: import.span,
imported_ident: ident,
imported_ident_desc: &desc,
};
err.subdiagnostic(note);
// Silence the 'unused import' warning we might get,
// since this diagnostic already covers that import.
self.record_use(ident, binding, Used::Other);
return;
}
if let crate::NameBindingKind::Import { import, .. } = binding.kind
&& !import.span.is_dummy()
{
let note = errors::IdentImporterHereButItIsDesc {
span: import.span,
imported_ident: ident,
imported_ident_desc: &desc,
};
err.subdiagnostic(note);
// Silence the 'unused import' warning we might get,
// since this diagnostic already covers that import.
self.record_use(ident, binding, Used::Other);
return;
}
let note = errors::IdentInScopeButItIsDesc {
imported_ident: ident,
@ -2436,20 +2425,20 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
debug!(found_closing_brace, ?binding_span);
let mut removal_span = binding_span;
if found_closing_brace {
// If the binding span ended with a closing brace, as in the below example:
// ie. `use a::b::{c, d};`
// ^
// Then expand the span of characters to remove to include the previous
// binding's trailing comma.
// ie. `use a::b::{c, d};`
// ^^^
if let Some(previous_span) =
// If the binding span ended with a closing brace, as in the below example:
// ie. `use a::b::{c, d};`
// ^
// Then expand the span of characters to remove to include the previous
// binding's trailing comma.
// ie. `use a::b::{c, d};`
// ^^^
if found_closing_brace
&& let Some(previous_span) =
extend_span_to_previous_binding(self.tcx.sess, binding_span)
{
debug!(?previous_span);
removal_span = removal_span.with_lo(previous_span.lo());
}
{
debug!(?previous_span);
removal_span = removal_span.with_lo(previous_span.lo());
}
debug!(?removal_span);
@ -3064,16 +3053,16 @@ impl<'tcx> visit::Visitor<'tcx> for UsePlacementFinder {
fn search_for_any_use_in_items(items: &[P<ast::Item>]) -> Option<Span> {
for item in items {
if let ItemKind::Use(..) = item.kind {
if is_span_suitable_for_use_injection(item.span) {
let mut lo = item.span.lo();
for attr in &item.attrs {
if attr.span.eq_ctxt(item.span) {
lo = std::cmp::min(lo, attr.span.lo());
}
if let ItemKind::Use(..) = item.kind
&& is_span_suitable_for_use_injection(item.span)
{
let mut lo = item.span.lo();
for attr in &item.attrs {
if attr.span.eq_ctxt(item.span) {
lo = std::cmp::min(lo, attr.span.lo());
}
return Some(Span::new(lo, lo, item.span.ctxt(), item.span.parent()));
}
return Some(Span::new(lo, lo, item.span.ctxt(), item.span.parent()));
}
}
None

View file

@ -246,23 +246,21 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
// ---- end
// ```
// So we have to fall back to the module's parent during lexical resolution in this case.
if derive_fallback_lint_id.is_some() {
if let Some(parent) = module.parent {
// Inner module is inside the macro, parent module is outside of the macro.
if module.expansion != parent.expansion
&& module.expansion.is_descendant_of(parent.expansion)
{
// The macro is a proc macro derive
if let Some(def_id) = module.expansion.expn_data().macro_def_id {
let ext = &self.get_macro_by_def_id(def_id).ext;
if ext.builtin_name.is_none()
&& ext.macro_kind() == MacroKind::Derive
&& parent.expansion.outer_expn_is_descendant_of(*ctxt)
{
return Some((parent, derive_fallback_lint_id));
}
}
}
if derive_fallback_lint_id.is_some()
&& let Some(parent) = module.parent
// Inner module is inside the macro
&& module.expansion != parent.expansion
// Parent module is outside of the macro
&& module.expansion.is_descendant_of(parent.expansion)
// The macro is a proc macro derive
&& let Some(def_id) = module.expansion.expn_data().macro_def_id
{
let ext = &self.get_macro_by_def_id(def_id).ext;
if ext.builtin_name.is_none()
&& ext.macro_kind() == MacroKind::Derive
&& parent.expansion.outer_expn_is_descendant_of(*ctxt)
{
return Some((parent, derive_fallback_lint_id));
}
}
@ -593,8 +591,8 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
},
Scope::StdLibPrelude => {
let mut result = Err(Determinacy::Determined);
if let Some(prelude) = this.prelude {
if let Ok(binding) = this.resolve_ident_in_module_unadjusted(
if let Some(prelude) = this.prelude
&& let Ok(binding) = this.resolve_ident_in_module_unadjusted(
ModuleOrUniformRoot::Module(prelude),
ident,
ns,
@ -603,14 +601,13 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
None,
ignore_binding,
ignore_import,
) {
if matches!(use_prelude, UsePrelude::Yes)
|| this.is_builtin_macro(binding.res())
{
result = Ok((binding, Flags::MISC_FROM_PRELUDE));
}
}
)
&& (matches!(use_prelude, UsePrelude::Yes)
|| this.is_builtin_macro(binding.res()))
{
result = Ok((binding, Flags::MISC_FROM_PRELUDE));
}
result
}
Scope::BuiltinTypes => match this.builtin_types_bindings.get(&ident.name) {
@ -939,10 +936,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
};
// Items and single imports are not shadowable, if we have one, then it's determined.
if let Some(binding) = binding {
if !binding.is_glob_import() {
return check_usable(self, binding);
}
if let Some(binding) = binding
&& !binding.is_glob_import()
{
return check_usable(self, binding);
}
// --- From now on we either have a glob resolution or no resolution. ---
@ -1437,13 +1434,12 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
for (segment_idx, &Segment { ident, id, .. }) in path.iter().enumerate() {
debug!("resolve_path ident {} {:?} {:?}", segment_idx, ident, id);
let record_segment_res = |this: &mut Self, res| {
if finalize.is_some() {
if let Some(id) = id {
if !this.partial_res_map.contains_key(&id) {
assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id");
this.record_partial_res(id, PartialRes::new(res));
}
}
if finalize.is_some()
&& let Some(id) = id
&& !this.partial_res_map.contains_key(&id)
{
assert!(id != ast::DUMMY_NODE_ID, "Trying to resolve dummy id");
this.record_partial_res(id, PartialRes::new(res));
}
};
@ -1463,13 +1459,12 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
_ => None,
},
};
if let Some(self_module) = self_module {
if let Some(parent) = self_module.parent {
module = Some(ModuleOrUniformRoot::Module(
self.resolve_self(&mut ctxt, parent),
));
continue;
}
if let Some(self_module) = self_module
&& let Some(parent) = self_module.parent
{
module =
Some(ModuleOrUniformRoot::Module(self.resolve_self(&mut ctxt, parent)));
continue;
}
return PathResult::failed(
ident,
@ -1644,13 +1639,14 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
}
Err(Undetermined) => return PathResult::Indeterminate,
Err(Determined) => {
if let Some(ModuleOrUniformRoot::Module(module)) = module {
if opt_ns.is_some() && !module.is_normal() {
return PathResult::NonModule(PartialRes::with_unresolved_segments(
module.res().unwrap(),
path.len() - segment_idx,
));
}
if let Some(ModuleOrUniformRoot::Module(module)) = module
&& opt_ns.is_some()
&& !module.is_normal()
{
return PathResult::NonModule(PartialRes::with_unresolved_segments(
module.res().unwrap(),
path.len() - segment_idx,
));
}
return PathResult::failed(

View file

@ -287,12 +287,11 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
binding.vis
};
if let ImportKind::Glob { ref max_vis, .. } = import.kind {
if vis == import_vis
|| max_vis.get().is_none_or(|max_vis| vis.is_at_least(max_vis, self.tcx))
{
max_vis.set(Some(vis.expect_local()))
}
if let ImportKind::Glob { ref max_vis, .. } = import.kind
&& (vis == import_vis
|| max_vis.get().is_none_or(|max_vis| vis.is_at_least(max_vis, self.tcx)))
{
max_vis.set(Some(vis.expect_local()))
}
self.arenas.alloc_name_binding(NameBindingData {
@ -546,13 +545,12 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
if let Some(err) = unresolved_import_error {
glob_error |= import.is_glob();
if let ImportKind::Single { source, ref source_bindings, .. } = import.kind {
if source.name == kw::SelfLower {
// Silence `unresolved import` error if E0429 is already emitted
if let Err(Determined) = source_bindings.value_ns.get() {
continue;
}
}
if let ImportKind::Single { source, ref source_bindings, .. } = import.kind
&& source.name == kw::SelfLower
// Silence `unresolved import` error if E0429 is already emitted
&& let Err(Determined) = source_bindings.value_ns.get()
{
continue;
}
if prev_root_id != NodeId::ZERO
@ -1006,21 +1004,19 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
self.lint_if_path_starts_with_module(Some(finalize), &full_path, None);
}
if let ModuleOrUniformRoot::Module(module) = module {
if module == import.parent_scope.module {
// Importing a module into itself is not allowed.
return Some(UnresolvedImportError {
span: import.span,
label: Some(String::from(
"cannot glob-import a module into itself",
)),
note: None,
suggestion: None,
candidates: None,
segment: None,
module: None,
});
}
if let ModuleOrUniformRoot::Module(module) = module
&& module == import.parent_scope.module
{
// Importing a module into itself is not allowed.
return Some(UnresolvedImportError {
span: import.span,
label: Some(String::from("cannot glob-import a module into itself")),
note: None,
suggestion: None,
candidates: None,
segment: None,
module: None,
});
}
if !is_prelude
&& let Some(max_vis) = max_vis.get()
@ -1081,18 +1077,17 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
// Consistency checks, analogous to `finalize_macro_resolutions`.
let initial_res = source_bindings[ns].get().map(|initial_binding| {
all_ns_err = false;
if let Some(target_binding) = target_bindings[ns].get() {
if target.name == kw::Underscore
&& initial_binding.is_extern_crate()
&& !initial_binding.is_import()
{
let used = if import.module_path.is_empty() {
Used::Scope
} else {
Used::Other
};
this.record_use(ident, target_binding, used);
}
if let Some(target_binding) = target_bindings[ns].get()
&& target.name == kw::Underscore
&& initial_binding.is_extern_crate()
&& !initial_binding.is_import()
{
let used = if import.module_path.is_empty() {
Used::Scope
} else {
Used::Other
};
this.record_use(ident, target_binding, used);
}
initial_binding.res()
});
@ -1250,10 +1245,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
if let Ok(binding) = source_bindings[ns].get() {
if !binding.vis.is_at_least(import.vis, this.tcx) {
reexport_error = Some((ns, binding));
if let ty::Visibility::Restricted(binding_def_id) = binding.vis {
if binding_def_id.is_top_level_module() {
crate_private_reexport = true;
}
if let ty::Visibility::Restricted(binding_def_id) = binding.vis
&& binding_def_id.is_top_level_module()
{
crate_private_reexport = true;
}
} else {
any_successful_reexport = true;

View file

@ -468,16 +468,12 @@ impl<'a> PathSource<'a> {
{
"external crate"
}
ExprKind::Path(_, path) => {
let mut msg = "function";
if let Some(segment) = path.segments.iter().last() {
if let Some(c) = segment.ident.to_string().chars().next() {
if c.is_uppercase() {
msg = "function, tuple struct or tuple variant";
}
}
}
msg
ExprKind::Path(_, path)
if let Some(segment) = path.segments.last()
&& let Some(c) = segment.ident.to_string().chars().next()
&& c.is_uppercase() =>
{
"function, tuple struct or tuple variant"
}
_ => "function",
},
@ -1182,32 +1178,27 @@ impl<'ra: 'ast, 'ast, 'tcx> Visitor<'ast> for LateResolutionVisitor<'_, 'ast, 'r
// namespace first, and if that fails we try again in the value namespace. If
// resolution in the value namespace succeeds, we have an generic const argument on
// our hands.
if let TyKind::Path(None, ref path) = ty.kind {
if let TyKind::Path(None, ref path) = ty.kind
// We cannot disambiguate multi-segment paths right now as that requires type
// checking.
if path.is_potential_trivial_const_arg() {
let mut check_ns = |ns| {
self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
.is_some()
};
if !check_ns(TypeNS) && check_ns(ValueNS) {
self.resolve_anon_const_manual(
true,
AnonConstKind::ConstArg(IsRepeatExpr::No),
|this| {
this.smart_resolve_path(
ty.id,
&None,
path,
PathSource::Expr(None),
);
this.visit_path(path, ty.id);
},
);
&& path.is_potential_trivial_const_arg()
{
let mut check_ns = |ns| {
self.maybe_resolve_ident_in_lexical_scope(path.segments[0].ident, ns)
.is_some()
};
if !check_ns(TypeNS) && check_ns(ValueNS) {
self.resolve_anon_const_manual(
true,
AnonConstKind::ConstArg(IsRepeatExpr::No),
|this| {
this.smart_resolve_path(ty.id, &None, path, PathSource::Expr(None));
this.visit_path(path, ty.id);
},
);
self.diag_metadata.currently_processing_generic_args = prev;
return;
}
self.diag_metadata.currently_processing_generic_args = prev;
return;
}
}
@ -2460,12 +2451,12 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
for i in (0..self.label_ribs.len()).rev() {
let rib = &self.label_ribs[i];
if let RibKind::MacroDefinition(def) = rib.kind {
if let RibKind::MacroDefinition(def) = rib.kind
// If an invocation of this macro created `ident`, give up on `ident`
// and switch to `ident`'s source from the macro definition.
if def == self.r.macro_def(label.span.ctxt()) {
label.span.remove_mark();
}
&& def == self.r.macro_def(label.span.ctxt())
{
label.span.remove_mark();
}
let ident = label.normalize_to_macro_rules();