Skip to content

Commit e07741e

Browse files
authored
Add as_group methods to AnyNodeRef (astral-sh#17048)
## Summary This PR adds `as_<group>` methods to `AnyNodeRef` to e.g. convert an `AnyNodeRef` to an `ExprRef`. I need this for go to definition where the fallback is to test if `AnyNodeRef` is an expression and then call `inferred_type` (listing this mapping at every call site where we need to convert `AnyNodeRef` to an `ExprRef` is a bit painful ;)) Split out from astral-sh#16901 ## Test Plan `cargo test`
1 parent 050f332 commit e07741e

File tree

2 files changed

+153
-0
lines changed

2 files changed

+153
-0
lines changed

crates/ruff_python_ast/generate.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -525,6 +525,23 @@ def write_anynoderef(out: list[str], ast: Ast) -> None:
525525
}
526526
""")
527527

528+
# `as_*` methods to convert from `AnyNodeRef` to e.g. `ExprRef`
529+
out.append(f"""
530+
impl<'a> AnyNodeRef<'a> {{
531+
pub fn as_{to_snake_case(group.ref_enum_ty)}(self) -> Option<{group.ref_enum_ty}<'a>> {{
532+
match self {{
533+
""")
534+
for node in group.nodes:
535+
out.append(
536+
f"Self::{node.name}(node) => Some({group.ref_enum_ty}::{node.variant}(node)),"
537+
)
538+
out.append("""
539+
_ => None,
540+
}
541+
}
542+
}
543+
""")
544+
528545
for node in ast.all_nodes:
529546
out.append(f"""
530547
impl<'a> From<&'a {node.ty}> for AnyNodeRef<'a> {{

crates/ruff_python_ast/src/generated.rs

Lines changed: 136 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)