| 1 |
from typing import Any, List |
| 2 |
from .ast import BaseNode, Node |
| 3 |
|
| 4 |
|
| 5 |
class Visitor: |
| 6 |
'''Read-only visitor pattern. |
| 7 |
|
| 8 |
Subclass this to gather information from an AST. |
| 9 |
To generally define which nodes not to descend in to, overload |
| 10 |
`generic_visit`. |
| 11 |
To handle specific node types, add methods like `visit_Pattern`. |
| 12 |
If you want to still descend into the children of the node, call |
| 13 |
`generic_visit` of the superclass. |
| 14 |
''' |
| 15 |
|
| 16 |
def visit(self, node: Any) -> None: |
| 17 |
if isinstance(node, list): |
| 18 |
for child in node: |
| 19 |
self.visit(child) |
| 20 |
return |
| 21 |
if not isinstance(node, BaseNode): |
| 22 |
return |
| 23 |
nodename = type(node).__name__ |
| 24 |
visit = getattr(self, f'visit_{nodename}', self.generic_visit) |
| 25 |
visit(node) |
| 26 |
|
| 27 |
def generic_visit(self, node: BaseNode) -> None: |
| 28 |
for propvalue in vars(node).values(): |
| 29 |
self.visit(propvalue) |
| 30 |
|
| 31 |
|
| 32 |
class Transformer(Visitor): |
| 33 |
'''In-place AST Transformer pattern. |
| 34 |
|
| 35 |
Subclass this to create an in-place modified variant |
| 36 |
of the given AST. |
| 37 |
If you need to keep the original AST around, pass |
| 38 |
a `node.clone()` to the transformer. |
| 39 |
''' |
| 40 |
|
| 41 |
def visit(self, node: Any) -> Any: |
| 42 |
if not isinstance(node, BaseNode): |
| 43 |
return node |
| 44 |
|
| 45 |
nodename = type(node).__name__ |
| 46 |
visit = getattr(self, f'visit_{nodename}', self.generic_visit) |
| 47 |
return visit(node) |
| 48 |
|
| 49 |
def generic_visit(self, node: Node) -> Node: # type: ignore |
| 50 |
for propname, propvalue in vars(node).items(): |
| 51 |
if isinstance(propvalue, list): |
| 52 |
new_vals: List[Any] = [] |
| 53 |
for child in propvalue: |
| 54 |
new_val = self.visit(child) |
| 55 |
if new_val is not None: |
| 56 |
new_vals.append(new_val) |
| 57 |
# in-place manipulation |
| 58 |
propvalue[:] = new_vals |
| 59 |
elif isinstance(propvalue, BaseNode): |
| 60 |
new_val = self.visit(propvalue) |
| 61 |
if new_val is None: |
| 62 |
delattr(node, propname) |
| 63 |
else: |
| 64 |
setattr(node, propname, new_val) |
| 65 |
return node |