Debian Codegraph @

src/graphql/language/visitor.py

raw
1 from copy import copy
2 from enum import Enum
3 from typing import (
4 Any,
5 Callable,
6 Collection,
7 Dict,
8 List,
9 NamedTuple,
10 Optional,
11 Tuple,
12 Union,
13 )
14
15 from ..pyutils import inspect, snake_to_camel
16 from . import ast
17 from .ast import QUERY_DOCUMENT_KEYS, Node
18
19 __all__ = [
20 "Visitor",
21 "ParallelVisitor",
22 "VisitorAction",
23 "visit",
24 "BREAK",
25 "SKIP",
26 "REMOVE",
27 "IDLE",
28 ]
29
30
31 class VisitorActionEnum(Enum):
32 """Special return values for the visitor methods.
33
34 You can also use the values of this enum directly.
35 """
36
37 BREAK = True
38 SKIP = False
39 REMOVE = Ellipsis
40
41
42 VisitorAction = Optional[VisitorActionEnum]
43
44 # Note that in GraphQL.js these are defined differently:
45 # BREAK = {}, SKIP = false, REMOVE = null, IDLE = undefined
46
47 BREAK = VisitorActionEnum.BREAK
48 SKIP = VisitorActionEnum.SKIP
49 REMOVE = VisitorActionEnum.REMOVE
50 IDLE = None
51
52 VisitorKeyMap = Dict[str, Tuple[str, ...]]
53
54
55 class EnterLeaveVisitor(NamedTuple):
56 """Visitor with functions for entering and leaving."""
57
58 enter: Optional[Callable[..., Optional[VisitorAction]]]
59 leave: Optional[Callable[..., Optional[VisitorAction]]]
60
61
62 class Visitor:
63 """Visitor that walks through an AST.
64
65 Visitors can define two generic methods "enter" and "leave". The former will be
66 called when a node is entered in the traversal, the latter is called after visiting
67 the node and its child nodes. These methods have the following signature::
68
69 def enter(self, node, key, parent, path, ancestors):
70 # The return value has the following meaning:
71 # IDLE (None): no action
72 # SKIP: skip visiting this node
73 # BREAK: stop visiting altogether
74 # REMOVE: delete this node
75 # any other value: replace this node with the returned value
76 return
77
78 def leave(self, node, key, parent, path, ancestors):
79 # The return value has the following meaning:
80 # IDLE (None) or SKIP: no action
81 # BREAK: stop visiting altogether
82 # REMOVE: delete this node
83 # any other value: replace this node with the returned value
84 return
85
86 The parameters have the following meaning:
87
88 :arg node: The current node being visiting.
89 :arg key: The index or key to this node from the parent node or Array.
90 :arg parent: the parent immediately above this node, which may be an Array.
91 :arg path: The key path to get to this node from the root node.
92 :arg ancestors: All nodes and Arrays visited before reaching parent
93 of this node. These correspond to array indices in ``path``.
94 Note: ancestors includes arrays which contain the parent of visited node.
95
96 You can also define node kind specific methods by suffixing them with an underscore
97 followed by the kind of the node to be visited. For instance, to visit ``field``
98 nodes, you would defined the methods ``enter_field()`` and/or ``leave_field()``,
99 with the same signature as above. If no kind specific method has been defined
100 for a given node, the generic method is called.
101 """
102
103 # Provide special return values as attributes
104 BREAK, SKIP, REMOVE, IDLE = BREAK, SKIP, REMOVE, IDLE
105
106 enter_leave_map: Dict[str, EnterLeaveVisitor]
107
108 def __init_subclass__(cls) -> None:
109 """Verify that all defined handlers are valid."""
110 super().__init_subclass__()
111 for attr, val in cls.__dict__.items():
112 if attr.startswith("_"):
113 continue
114 attr_kind = attr.split("_", 1)
115 if len(attr_kind) < 2:
116 kind: Optional[str] = None
117 else:
118 attr, kind = attr_kind
119 if attr in ("enter", "leave") and kind:
120 name = snake_to_camel(kind) + "Node"
121 node_cls = getattr(ast, name, None)
122 if (
123 not node_cls
124 or not isinstance(node_cls, type)
125 or not issubclass(node_cls, Node)
126 ):
127 raise TypeError(f"Invalid AST node kind: {kind}.")
128
129 def __init__(self) -> None:
130 self.enter_leave_map = {}
131
132 def get_enter_leave_for_kind(self, kind: str) -> EnterLeaveVisitor:
133 """Given a node kind, return the EnterLeaveVisitor for that kind."""
134 try:
135 return self.enter_leave_map[kind]
136 except KeyError:
137 enter_fn = getattr(self, f"enter_{kind}", None)
138 if not enter_fn:
139 enter_fn = getattr(self, "enter", None)
140 leave_fn = getattr(self, f"leave_{kind}", None)
141 if not leave_fn:
142 leave_fn = getattr(self, "leave", None)
143 enter_leave = EnterLeaveVisitor(enter_fn, leave_fn)
144 self.enter_leave_map[kind] = enter_leave
145 return enter_leave
146
147 def get_visit_fn(
148 self, kind: str, is_leaving: bool = False
149 ) -> Optional[Callable[..., Optional[VisitorAction]]]:
150 """Get the visit function for the given node kind and direction.
151
152 This deprecated compatibility helper delegates to
153 ``get_enter_leave_for_kind``; call ``get_enter_leave_for_kind`` directly
154 because ``get_visit_fn`` will be removed in v3.3.
155
156 .. deprecated:: 3.2
157 Please use ``get_enter_leave_for_kind`` instead. Will be removed in v3.3.
158 """
159 enter_leave = self.get_enter_leave_for_kind(kind)
160 return enter_leave.leave if is_leaving else enter_leave.enter
161
162
163 class Stack(NamedTuple):
164 """A stack for the visit function."""
165
166 in_array: bool
167 idx: int
168 keys: Tuple[Node, ...]
169 edits: List[Tuple[Union[int, str], Node]]
170 prev: Any # 'Stack' (python/mypy/issues/731)
171
172
173 def visit(
174 root: Node, visitor: Visitor, visitor_keys: Optional[VisitorKeyMap] = None
175 ) -> Any:
176 """Visit each node in an AST.
177
178 :func:`~.visit` will walk through an AST using a depth-first traversal, calling the
179 visitor's enter methods at each node in the traversal, and calling the leave methods
180 after visiting that node and all of its child nodes.
181
182 By returning different values from the enter and leave methods, the behavior of the
183 visitor can be altered, including skipping over a sub-tree of the AST (by returning
184 False), editing the AST by returning a value or None to remove the value, or to stop
185 the whole traversal by returning :data:`~.BREAK`.
186
187 When using :func:`~.visit` to edit an AST, the original AST will not be modified,
188 and a new version of the AST with the changes applied will be returned from the
189 visit function.
190
191 To customize the node attributes to be used for traversal, you can provide a
192 dictionary visitor_keys mapping node kinds to node attributes.
193 """
194 if not isinstance(root, Node):
195 raise TypeError(f"Not an AST Node: {inspect(root)}.")
196 if not isinstance(visitor, Visitor):
197 raise TypeError(f"Not an AST Visitor: {inspect(visitor)}.")
198 if visitor_keys is None:
199 visitor_keys = QUERY_DOCUMENT_KEYS
200
201 stack: Any = None
202 in_array = False
203 keys: Tuple[Node, ...] = (root,)
204 idx = -1
205 edits: List[Any] = []
206 node: Any = root
207 key: Any = None
208 parent: Any = None
209 path: List[Any] = []
210 path_append = path.append
211 path_pop = path.pop
212 ancestors: List[Any] = []
213 ancestors_append = ancestors.append
214 ancestors_pop = ancestors.pop
215
216 while True:
217 idx += 1
218 is_leaving = idx == len(keys)
219 is_edited = is_leaving and edits
220 if is_leaving:
221 key = path[-1] if ancestors else None
222 node = parent
223 parent = ancestors_pop() if ancestors else None
224 if is_edited:
225 if in_array:
226 node = list(node)
227 edit_offset = 0
228 for edit_key, edit_value in edits:
229 array_key = edit_key - edit_offset
230 if edit_value is REMOVE or edit_value is Ellipsis:
231 node.pop(array_key)
232 edit_offset += 1
233 else:
234 node[array_key] = edit_value
235 node = tuple(node)
236 else:
237 node = copy(node)
238 for edit_key, edit_value in edits:
239 setattr(node, edit_key, edit_value)
240 idx = stack.idx
241 keys = stack.keys
242 edits = stack.edits
243 in_array = stack.in_array
244 stack = stack.prev
245 elif parent:
246 if in_array:
247 key = idx
248 node = parent[key]
249 else:
250 key = keys[idx]
251 node = getattr(parent, key, None)
252 if node is None:
253 continue
254 path_append(key)
255
256 if isinstance(node, tuple):
257 result = None
258 else:
259 if not isinstance(node, Node):
260 raise TypeError(f"Invalid AST Node: {inspect(node)}.")
261 enter_leave = visitor.get_enter_leave_for_kind(node.kind)
262 visit_fn = enter_leave.leave if is_leaving else enter_leave.enter
263 if visit_fn:
264 result = visit_fn(node, key, parent, path, ancestors)
265
266 if result is BREAK or result is True:
267 break
268
269 if result is SKIP or result is False:
270 if not is_leaving:
271 path_pop()
272 continue
273
274 elif result is not None:
275 edits.append((key, result))
276 if not is_leaving:
277 if isinstance(result, Node):
278 node = result
279 else:
280 path_pop()
281 continue
282 else:
283 result = None
284
285 if result is None and is_edited:
286 edits.append((key, node))
287
288 if is_leaving:
289 if path:
290 path_pop()
291 else:
292 stack = Stack(in_array, idx, keys, edits, stack)
293 in_array = isinstance(node, tuple)
294 keys = node if in_array else visitor_keys.get(node.kind, ()) # type: ignore
295 idx = -1
296 edits = []
297 if parent:
298 ancestors_append(parent)
299 parent = node
300
301 if not stack:
302 break
303
304 if edits:
305 return edits[-1][1]
306
307 return root
308
309
310 class ParallelVisitor(Visitor):
311 """A Visitor which delegates to many visitors to run in parallel.
312
313 Each visitor will be visited for each node before moving on.
314
315 If a prior visitor edits a node, no following visitors will see that node.
316 """
317
318 def __init__(self, visitors: Collection[Visitor]):
319 """Create a new visitor from the given list of parallel visitors."""
320 super().__init__()
321 self.visitors = visitors
322 self.skipping: List[Any] = [None] * len(visitors)
323
324 def get_enter_leave_for_kind(self, kind: str) -> EnterLeaveVisitor:
325 """Given a node kind, return the EnterLeaveVisitor for that kind."""
326 try:
327 return self.enter_leave_map[kind]
328 except KeyError:
329 has_visitor = False
330 enter_list: List[Optional[Callable[..., Optional[VisitorAction]]]] = []
331 leave_list: List[Optional[Callable[..., Optional[VisitorAction]]]] = []
332 for visitor in self.visitors:
333 enter, leave = visitor.get_enter_leave_for_kind(kind)
334 if not has_visitor and (enter or leave):
335 has_visitor = True
336 enter_list.append(enter)
337 leave_list.append(leave)
338
339 if has_visitor:
340
341 def enter(node: Node, *args: Any) -> Optional[VisitorAction]:
342 skipping = self.skipping
343 for i, fn in enumerate(enter_list):
344 if not skipping[i]:
345 if fn:
346 result = fn(node, *args)
347 if result is SKIP or result is False:
348 skipping[i] = node
349 elif result is BREAK or result is True:
350 skipping[i] = BREAK
351 elif result is not None:
352 return result
353 return None
354
355 def leave(node: Node, *args: Any) -> Optional[VisitorAction]:
356 skipping = self.skipping
357 for i, fn in enumerate(leave_list):
358 if not skipping[i]:
359 if fn:
360 result = fn(node, *args)
361 if result is BREAK or result is True:
362 skipping[i] = BREAK
363 elif (
364 result is not None
365 and result is not SKIP
366 and result is not False
367 ):
368 return result
369 elif skipping[i] is node:
370 skipping[i] = None
371 return None
372
373 else:
374
375 enter = leave = None
376
377 enter_leave = EnterLeaveVisitor(enter, leave)
378 self.enter_leave_map[kind] = enter_leave
379 return enter_leave