|
| 1 | +from typing import Any, Collection, Dict, List, Optional, overload |
| 2 | + |
| 3 | +from ..language import Node, OperationType |
| 4 | +from ..pyutils import is_iterable |
| 5 | + |
| 6 | + |
| 7 | +__all__ = ["ast_to_dict"] |
| 8 | + |
| 9 | + |
| 10 | +@overload |
| 11 | +def ast_to_dict( |
| 12 | + node: Node, locations: bool = False, cache: Optional[Dict[Node, Any]] = None |
| 13 | +) -> Dict: |
| 14 | + ... |
| 15 | + |
| 16 | + |
| 17 | +@overload |
| 18 | +def ast_to_dict( |
| 19 | + node: Collection[Node], |
| 20 | + locations: bool = False, |
| 21 | + cache: Optional[Dict[Node, Any]] = None, |
| 22 | +) -> List[Node]: |
| 23 | + ... |
| 24 | + |
| 25 | + |
| 26 | +@overload |
| 27 | +def ast_to_dict( |
| 28 | + node: OperationType, |
| 29 | + locations: bool = False, |
| 30 | + cache: Optional[Dict[Node, Any]] = None, |
| 31 | +) -> str: |
| 32 | + ... |
| 33 | + |
| 34 | + |
| 35 | +def ast_to_dict( |
| 36 | + node: Any, locations: bool = False, cache: Optional[Dict[Node, Any]] = None |
| 37 | +) -> Any: |
| 38 | + """Convert a language AST to a nested Python dictionary. |
| 39 | +
|
| 40 | + Set `location` to True in order to get the locations as well. |
| 41 | + """ |
| 42 | + |
| 43 | + """Convert a node to a nested Python dictionary.""" |
| 44 | + if isinstance(node, Node): |
| 45 | + if cache is None: |
| 46 | + cache = {} |
| 47 | + elif node in cache: |
| 48 | + return cache[node] |
| 49 | + cache[node] = res = {} |
| 50 | + res.update( |
| 51 | + { |
| 52 | + key: ast_to_dict(getattr(node, key), locations, cache) |
| 53 | + for key in ("kind",) + node.keys[1:] |
| 54 | + } |
| 55 | + ) |
| 56 | + if locations: |
| 57 | + loc = node.loc |
| 58 | + if loc: |
| 59 | + res["loc"] = dict(start=loc.start, end=loc.end) |
| 60 | + return res |
| 61 | + if is_iterable(node): |
| 62 | + return [ast_to_dict(sub_node, locations, cache) for sub_node in node] |
| 63 | + if isinstance(node, OperationType): |
| 64 | + return node.value |
| 65 | + return node |
0 commit comments