Debian Codegraph @

src/globus_sdk/scopes/_graph_parser.py

raw
1 from __future__ import annotations
2
3 import dataclasses
4 import sys
5 import typing as t
6 from collections import defaultdict, deque
7
8 from .errors import ScopeCycleError, ScopeParseError
9
10 SPECIAL_CHARACTERS = set("[]* ")
11 SPECIAL_TOKENS = set("[]*")
12
13
14 class ScopeGraph:
15 def __init__(self) -> None:
16 self.top_level_scopes: set[tuple[str, bool]] = set()
17 self.nodes: set[str] = set()
18 self.edges: set[tuple[str, str, bool]] = set()
19 self.adjacency_matrix: dict[str, set[tuple[str, str, bool]]] = defaultdict(set)
20
21 def breadth_first_walk(self) -> t.Iterator[tuple[str, bool]]:
22 """
23 Do a BFS across the forest, returning nodes (as tuples) in BFS order.
24
25 For inspection of the graph after parsing.
26 """
27 bfs_queue: t.Deque[tuple[str, bool]] = deque(self.top_level_scopes)
28
29 while bfs_queue:
30 yield (current := bfs_queue.popleft())
31
32 edges = self.adjacency_matrix[current[0]]
33 for _, dest, optional in edges:
34 bfs_queue.append((dest, optional))
35
36 def add_edge(self, src: str, dest: str, optional: bool) -> None:
37 self.edges.add((src, dest, optional))
38 self.adjacency_matrix[src].add((src, dest, optional))
39
40 def _normalize_optionals(self) -> None:
41 to_remove: set[tuple[str, str, bool]] = set()
42 for edge in self.edges:
43 src, dest, optional = edge
44 if not optional:
45 continue
46 # The current edge is optional; see if it's superseded by required edge
47 required_variant = (src, dest, False)
48 if required_variant in self.edges:
49 to_remove.add(edge)
50 self.edges = self.edges - to_remove
51 for edge in to_remove:
52 src, _, _ = edge
53 self.adjacency_matrix[src].remove(edge)
54
55 def _check_cycles(self) -> None:
56 # explore the graph using an iterative Depth-First Search
57 # as we explore the graph, keep track of paths of ancestry being explored
58 # if we ever find a back-edge along one of those paths of ancestry, that
59 # means that there must be a cycle
60
61 # start from the top-level nodes (which we know to be the roots of this
62 # forest-shaped graph)
63 # we will track this as the set of paths to continue to branch and explore in a
64 # stack and pop from it until it is empty, thus implementing DFS
65 #
66 # conceptually, the paths could be implemented as `list[str]`, which would
67 # preserve the order in which we encountered each node. Using a set is a
68 # micro-optimization which makes checks faster, since we only care to detect
69 # *that* there was a cycle, not what the shape of that cycle was
70 paths_to_explore: list[tuple[set[str], str]] = [
71 ({node}, node) for node, _ in self.top_level_scopes
72 ]
73
74 while paths_to_explore:
75 path, terminus = paths_to_explore.pop()
76
77 # get out-edges from the last node in the path
78 children = self.adjacency_matrix[terminus]
79
80 # if the node was a leaf, no children, we are done exploring this path
81 if not children:
82 continue
83
84 # for each child edge, do two basic things:
85 # - check if we found a back-edge (cycle!)
86 # - create a new path to explore, with the child node as its current
87 # terminus
88 for edge in children:
89 _, dest, _ = edge
90 if dest in path:
91 raise ScopeCycleError(f"A cycle was found involving '{dest}'")
92 paths_to_explore.append((path.union((dest,)), dest))
93
94 def __str__(self) -> str:
95 lines = ["digraph scopes {", ' rankdir="LR";', ""]
96 for node, optional in self.top_level_scopes:
97 lines.append(f" {'*' if optional else ''}{node}")
98 lines.append("")
99
100 # do two passes to put all non-optional edges first
101 for source, dest, optional in self.edges:
102 if optional:
103 continue
104 lines.append(f" {source} -> {dest};")
105 for source, dest, optional in self.edges:
106 if not optional:
107 continue
108 lines.append(f' {source} -> {dest} [ label = "optional" ];')
109 lines.append("")
110 lines.append("}")
111 return "\n".join(lines)
112
113 @classmethod
114 def parse(cls, scopes: str) -> ScopeGraph:
115 trees = ScopeTreeNode.parse(scopes)
116 graph = cls._convert_trees(trees)
117 graph._normalize_optionals()
118 graph._check_cycles()
119 return graph
120
121 @classmethod
122 def _convert_trees(cls, trees: list[ScopeTreeNode]) -> ScopeGraph:
123 graph = ScopeGraph()
124 node_queue: t.Deque[ScopeTreeNode] = deque()
125
126 for tree_node in trees:
127 node_queue.append(tree_node)
128 graph.top_level_scopes.add((tree_node.scope_string, tree_node.optional))
129
130 while node_queue:
131 tree_node = node_queue.pop()
132 scope_string = tree_node.scope_string
133 graph.nodes.add(scope_string)
134 for dep in tree_node.dependencies:
135 node_queue.append(dep)
136 graph.add_edge(scope_string, dep.scope_string, dep.optional)
137
138 return graph
139
140
141 # pass slots=True on 3.10+
142 # it's not strictly necessary, but it improves performance
143 if sys.version_info >= (3, 10):
144 _add_dataclass_kwargs: dict[str, bool] = {"slots": True}
145 else:
146 _add_dataclass_kwargs: dict[str, bool] = {}
147
148
149 @dataclasses.dataclass(**_add_dataclass_kwargs)
150 class ScopeTreeNode:
151 #
152 # This is an intermediate representation for scope parsing.
153 #
154 scope_string: str
155 optional: bool
156 dependencies: list[ScopeTreeNode] = dataclasses.field(default_factory=list)
157
158 def add_dependency(self, subtree: ScopeTreeNode) -> None:
159 self.dependencies.append(subtree)
160
161 @staticmethod
162 def parse(scope_string: str) -> list[ScopeTreeNode]:
163 tokens = _tokenize(scope_string)
164 return _parse_tokens(tokens)
165
166
167 def _tokenize(scope_string: str) -> list[str]:
168 tokens: list[str] = []
169 start = 0
170 for idx, current_char, next_char in _peek_enumerate(scope_string):
171 if current_char not in SPECIAL_CHARACTERS:
172 continue
173 _reject_bad_adjacent_characters(current_char, next_char)
174
175 if start != idx:
176 tokens.append(scope_string[start:idx])
177 start = idx + 1
178
179 if current_char in SPECIAL_TOKENS:
180 tokens.append(current_char)
181 elif current_char == " ":
182 pass
183 else:
184 raise NotImplementedError
185 remainder = scope_string[start:].strip()
186 if remainder:
187 tokens.append(remainder)
188 return tokens
189
190
191 def _reject_bad_adjacent_characters(current_char: str, next_char: str | None) -> None:
192 """Given a pair of adjacent characters during tokenization, raise
193 appropriate errors if they are not valid."""
194 if next_char is None:
195 return
196
197 if (current_char, next_char) == ("*", " "):
198 raise ScopeParseError("'*' must not be followed by a space")
199 elif current_char == "]" and next_char not in (" ", "]"):
200 raise ScopeParseError("']' may only be followed by a space or ']'")
201 elif (current_char, next_char) == (" ", "["):
202 raise ScopeParseError("'[' cannot have a preceding space")
203
204
205 def _parse_tokens(tokens: list[str]) -> list[ScopeTreeNode]:
206 # value to return
207 ret: list[ScopeTreeNode] = []
208 # track whether or not the current scope is optional (has a preceding *)
209 current_optional = False
210 # keep a stack of "parents", each time we enter a `[` context, push the last scope
211 # and each time we exit via a `]`, pop from the stack
212 parents: list[ScopeTreeNode] = []
213 # track the current (or, by similar terminology, "last") complete scope seen
214 current_scope: ScopeTreeNode | None = None
215
216 for _, token, next_token in _peek_enumerate(tokens):
217 _reject_bad_adjacent_tokens(token, next_token)
218
219 if token == "*":
220 current_optional = True
221 elif token == "[":
222 if not current_scope:
223 raise ScopeParseError("found '[' without a preceding scope string")
224
225 parents.append(current_scope)
226 elif token == "]":
227 if not parents:
228 raise ScopeParseError("found ']' with no matching '[' preceding it")
229 parents.pop()
230 else:
231 current_scope = ScopeTreeNode(token, optional=current_optional)
232 current_optional = False
233 if parents:
234 parents[-1].add_dependency(current_scope)
235 else:
236 ret.append(current_scope)
237 if parents:
238 raise ScopeParseError("unclosed brackets, missing ']'")
239
240 return ret
241
242
243 def _reject_bad_adjacent_tokens(current_token: str, next_token: str | None) -> None:
244 """
245 Given a pair of tokens from parsing, raise appropriate errors if they are
246 not a valid sequence.
247 """
248 if current_token == "*":
249 if next_token is None:
250 raise ScopeParseError("ended in optional marker")
251 elif next_token in SPECIAL_TOKENS:
252 raise ScopeParseError(
253 "a scope string must always follow an optional marker"
254 )
255 elif (current_token, next_token) == ("[", None):
256 raise ScopeParseError("ended in left bracket")
257 elif (current_token, next_token) == ("[", "]"):
258 raise ScopeParseError("found empty brackets")
259 elif (current_token, next_token) == ("[", "["):
260 raise ScopeParseError("found double left-bracket")
261
262
263 def _peek_enumerate(data: str | list[str]) -> t.Iterator[tuple[int, str, str | None]]:
264 """
265 An iterator producing (index, character, next_char)
266 or else producing (index, str, next_str)
267
268 (Depending on whether or not the input is a string or list of strings)
269 """
270 if not data:
271 return
272
273 prev: str = data[0]
274 for idx, c in enumerate(data[1:]):
275 yield (idx, prev, c)
276 prev = c
277
278 yield (len(data) - 1, prev, None)