How do you rewrite a pattern recursively? #1566
-
I wrote two rules to transform Python's Here are rules in question.id: optional
language: Python
rule:
any:
- pattern:
context: 'arg: Optional[$TYPE]'
selector: generic_type
- pattern: Optional[$TYPE]
fix: $TYPE | None
---
id: unions
language: Python
rule:
pattern:
context: 'a: Union[$$$TYPES]'
selector: generic_type
rewriters:
- id: rewrite-unions
rule:
pattern: $TYPE
kind: type
fix: $TYPE
transform:
UNIONS:
rewrite:
rewriters:
- rewrite-unions
source: $$$TYPES
joinBy: " | "
fix: $UNIONS Let's say I have a type that looks like this in my codebase: results: Optional[Union[List[Union[str, dict]], str]] What I've observed is that
Is there any way to tell ast-grep to recurse into an already matched node and apply these fixes recursively without having to run it multiple times? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
Hi, sorry for the late reply.
Yes, it is possible but verbose. See the link See the rulerewriters:
- id: optional
language: Python
rule:
any:
- pattern:
context: 'arg: Optional[$TYPE]'
selector: generic_type
- pattern: Optional[$TYPE]
transform:
NT:
rewrite:
rewriters: [optional, unions]
source: $TYPE
fix: $NT | None
- id: unions
language: Python
rule:
pattern:
context: 'a: Union[$$$TYPES]'
selector: generic_type
transform:
UNIONS:
rewrite:
rewriters:
- rewrite-unions
source: $$$TYPES
joinBy: " | "
fix: $UNIONS
- id: rewrite-unions
rule:
pattern: $TYPE
kind: type
transform:
NT:
rewrite:
rewriters: [optional, unions]
source: $TYPE
fix: $NT
rule:
kind: type
pattern: $TPE
transform:
NEW_TYPE:
rewrite:
rewriters: [optional, unions]
source: $TPE
fix: $NEW_TYPE The trick here is to apply rewriters to inner types recursively. ![]() |
Beta Was this translation helpful? Give feedback.
Hi, sorry for the late reply.
Yes, it is possible but verbose.
See the link
See the rule