Debian Codegraph @

src/graphql/utilities/ast_to_dict.py

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