Debian Codegraph @

pypy/interpreter/pyparser/tools/pegen/grammar.py

raw symbols SCIP
1 from __future__ import annotations
2
3 from abc import abstractmethod
4 from typing import (
5 TYPE_CHECKING,
6 AbstractSet,
7 Any,
8 Dict,
9 Iterable,
10 Iterator,
11 List,
12 Optional,
13 Set,
14 Tuple,
15 Union,
16 )
17
18 if TYPE_CHECKING:
19 from pegen.parser_generator import ParserGenerator
20
21
22 class GrammarError(Exception):
23 pass
24
25
26 class GrammarVisitor:
27 def visit(self, node: Any, *args: Any, **kwargs: Any) -> Any:
28 """Visit a node."""
29 method = "visit_" + node.__class__.__name__
30 visitor = getattr(self, method, self.generic_visit)
31 return visitor(node, *args, **kwargs)
32
33 def generic_visit(self, node: Iterable[Any], *args: Any, **kwargs: Any) -> None:
34 """Called if no explicit visitor function exists for a node."""
35 for value in node:
36 if isinstance(value, list):
37 for item in value:
38 self.visit(item, *args, **kwargs)
39 else:
40 self.visit(value, *args, **kwargs)
41
42
43 class Grammar:
44 def __init__(self, rules: Iterable[Rule], metas: Iterable[Tuple[str, Optional[str]]]):
45 self.rules = {rule.name: rule for rule in rules}
46 self.metas = dict(metas)
47
48 def __str__(self) -> str:
49 return "\n".join(str(rule) for name, rule in self.rules.items())
50
51 def __repr__(self) -> str:
52 lines = ["Grammar("]
53 lines.append(" [")
54 for rule in self.rules.values():
55 lines.append(f" {repr(rule)},")
56 lines.append(" ],")
57 lines.append(" {repr(list(self.metas.items()))}")
58 lines.append(")")
59 return "\n".join(lines)
60
61 def __iter__(self) -> Iterator[Rule]:
62 yield from self.rules.values()
63
64
65 # Global flag whether we want actions in __str__() -- default off.
66 SIMPLE_STR = True
67
68
69 class Rule:
70 def __init__(self, name: str, type: Optional[str], rhs: Rhs, memo: Optional[object] = None):
71 self.name = name
72 self.type = type
73 self.rhs = rhs
74 self.memo = bool(memo)
75 self.visited = False
76 self.nullable = False
77 self.left_recursive = False
78 self.leader = False
79
80 def is_loop(self) -> bool:
81 return self.name.startswith("_loop")
82
83 def is_gather(self) -> bool:
84 return self.name.startswith("_gather")
85
86 def __str__(self) -> str:
87 if SIMPLE_STR or self.type is None:
88 res = f"{self.name}: {self.rhs}"
89 else:
90 res = f"{self.name}[{self.type}]: {self.rhs}"
91 if len(res) < 88:
92 return res
93 lines = [res.split(":")[0] + ":"]
94 lines += [f" | {alt}" for alt in self.rhs.alts]
95 return "\n".join(lines)
96
97 def __repr__(self) -> str:
98 return f"Rule({self.name!r}, {self.type!r}, {self.rhs!r})"
99
100 def __iter__(self) -> Iterator[Rhs]:
101 yield self.rhs
102
103 def nullable_visit(self, rules: Dict[str, Rule]) -> bool:
104 if self.visited:
105 # A left-recursive rule is considered non-nullable.
106 return False
107 self.visited = True
108 self.nullable = self.rhs.nullable_visit(rules)
109 return self.nullable
110
111 def initial_names(self) -> AbstractSet[str]:
112 return self.rhs.initial_names()
113
114 def flatten(self) -> Rhs:
115 # If it's a single parenthesized group, flatten it.
116 rhs = self.rhs
117 if (
118 not self.is_loop()
119 and len(rhs.alts) == 1
120 and len(rhs.alts[0].items) == 1
121 and isinstance(rhs.alts[0].items[0].item, Group)
122 ):
123 rhs = rhs.alts[0].items[0].item.rhs
124 return rhs
125
126 def collect_todo(self, gen: ParserGenerator) -> None:
127 rhs = self.flatten()
128 rhs.collect_todo(gen)
129
130
131 class Leaf:
132 def __init__(self, value: str):
133 self.value = value
134
135 def __str__(self) -> str:
136 return self.value
137
138 def __iter__(self) -> Iterable[str]:
139 if False:
140 yield
141
142 @abstractmethod
143 def nullable_visit(self, rules: Dict[str, Rule]) -> bool:
144 raise NotImplementedError
145
146 @abstractmethod
147 def initial_names(self) -> AbstractSet[str]:
148 raise NotImplementedError
149
150
151 class NameLeaf(Leaf):
152 """The value is the name."""
153
154 def __str__(self) -> str:
155 if self.value == "ENDMARKER":
156 return "$"
157 return super().__str__()
158
159 def __repr__(self) -> str:
160 return f"NameLeaf({self.value!r})"
161
162 def nullable_visit(self, rules: Dict[str, Rule]) -> bool:
163 if self.value in rules:
164 return rules[self.value].nullable_visit(rules)
165 # Token or unknown; never empty.
166 return False
167
168 def initial_names(self) -> AbstractSet[str]:
169 return {self.value}
170
171
172 class StringLeaf(Leaf):
173 """The value is a string literal, including quotes."""
174
175 def __repr__(self) -> str:
176 return f"StringLeaf({self.value!r})"
177
178 def nullable_visit(self, rules: Dict[str, Rule]) -> bool:
179 # The string token '' is considered empty.
180 return not self.value
181
182 def initial_names(self) -> AbstractSet[str]:
183 return set()
184
185
186 class Rhs:
187 def __init__(self, alts: List[Alt]):
188 self.alts = alts
189 self.memo: Optional[Tuple[Optional[str], str]] = None
190
191 def __str__(self) -> str:
192 return " | ".join(str(alt) for alt in self.alts)
193
194 def __repr__(self) -> str:
195 return f"Rhs({self.alts!r})"
196
197 def __iter__(self) -> Iterator[List[Alt]]:
198 yield self.alts
199
200 def nullable_visit(self, rules: Dict[str, Rule]) -> bool:
201 for alt in self.alts:
202 if alt.nullable_visit(rules):
203 return True
204 return False
205
206 def initial_names(self) -> AbstractSet[str]:
207 names: Set[str] = set()
208 for alt in self.alts:
209 names |= alt.initial_names()
210 return names
211
212 def collect_todo(self, gen: ParserGenerator) -> None:
213 for alt in self.alts:
214 alt.collect_todo(gen)
215
216
217 class Alt:
218 def __init__(self, items: List[NamedItem], *, icut: int = -1, action: Optional[str] = None):
219 self.items = items
220 self.icut = icut
221 self.action = action
222
223 def __str__(self) -> str:
224 core = " ".join(str(item) for item in self.items)
225 if not SIMPLE_STR and self.action:
226 return f"{core} {{ {self.action} }}"
227 else:
228 return core
229
230 def __repr__(self) -> str:
231 args = [repr(self.items)]
232 if self.icut >= 0:
233 args.append(f"icut={self.icut}")
234 if self.action:
235 args.append(f"action={self.action!r}")
236 return f"Alt({', '.join(args)})"
237
238 def __iter__(self) -> Iterator[List[NamedItem]]:
239 yield self.items
240
241 def nullable_visit(self, rules: Dict[str, Rule]) -> bool:
242 for item in self.items:
243 if not item.nullable_visit(rules):
244 return False
245 return True
246
247 def initial_names(self) -> AbstractSet[str]:
248 names: Set[str] = set()
249 for item in self.items:
250 names |= item.initial_names()
251 if not item.nullable:
252 break
253 return names
254
255 def collect_todo(self, gen: ParserGenerator) -> None:
256 for item in self.items:
257 item.collect_todo(gen)
258
259
260 class NamedItem:
261 def __init__(self, name: Optional[str], item: Item, type: Optional[str] = None):
262 self.name = name
263 self.item = item
264 self.type = type
265 self.nullable = False
266
267 def __str__(self) -> str:
268 if not SIMPLE_STR and self.name:
269 return f"{self.name}={self.item}"
270 else:
271 return str(self.item)
272
273 def __repr__(self) -> str:
274 return f"NamedItem({self.name!r}, {self.item!r})"
275
276 def __iter__(self) -> Iterator[Item]:
277 yield self.item
278
279 def nullable_visit(self, rules: Dict[str, Rule]) -> bool:
280 self.nullable = self.item.nullable_visit(rules)
281 return self.nullable
282
283 def initial_names(self) -> AbstractSet[str]:
284 return self.item.initial_names()
285
286 def collect_todo(self, gen: ParserGenerator) -> None:
287 gen.callmakervisitor.visit(self.item)
288
289
290 class Forced:
291 def __init__(self, node: Plain):
292 self.node = node
293
294 def __str__(self) -> str:
295 return f"&&{self.node}"
296
297 def __iter__(self) -> Iterator[Plain]:
298 yield self.node
299
300 def nullable_visit(self, rules: Dict[str, Rule]) -> bool:
301 return True
302
303 def initial_names(self) -> AbstractSet[str]:
304 return set()
305
306
307 class Lookahead:
308 def __init__(self, node: Plain, sign: str):
309 self.node = node
310 self.sign = sign
311
312 def __str__(self) -> str:
313 return f"{self.sign}{self.node}"
314
315 def __iter__(self) -> Iterator[Plain]:
316 yield self.node
317
318 def nullable_visit(self, rules: Dict[str, Rule]) -> bool:
319 return True
320
321 def initial_names(self) -> AbstractSet[str]:
322 return set()
323
324
325 class PositiveLookahead(Lookahead):
326 def __init__(self, node: Plain):
327 super().__init__(node, "&")
328
329 def __repr__(self) -> str:
330 return f"PositiveLookahead({self.node!r})"
331
332
333 class NegativeLookahead(Lookahead):
334 def __init__(self, node: Plain):
335 super().__init__(node, "!")
336
337 def __repr__(self) -> str:
338 return f"NegativeLookahead({self.node!r})"
339
340
341 class Opt:
342 def __init__(self, node: Item):
343 self.node = node
344
345 def __str__(self) -> str:
346 s = str(self.node)
347 # TODO: Decide whether to use [X] or X? based on type of X
348 if " " in s:
349 return f"[{s}]"
350 else:
351 return f"{s}?"
352
353 def __repr__(self) -> str:
354 return f"Opt({self.node!r})"
355
356 def __iter__(self) -> Iterator[Item]:
357 yield self.node
358
359 def nullable_visit(self, rules: Dict[str, Rule]) -> bool:
360 return True
361
362 def initial_names(self) -> AbstractSet[str]:
363 return self.node.initial_names()
364
365
366 class Repeat:
367 """Shared base class for x* and x+."""
368
369 def __init__(self, node: Plain):
370 self.node = node
371 self.memo: Optional[Tuple[Optional[str], str]] = None
372
373 @abstractmethod
374 def nullable_visit(self, rules: Dict[str, Rule]) -> bool:
375 raise NotImplementedError
376
377 def __iter__(self) -> Iterator[Plain]:
378 yield self.node
379
380 def initial_names(self) -> AbstractSet[str]:
381 return self.node.initial_names()
382
383
384 class Repeat0(Repeat):
385 def __str__(self) -> str:
386 s = str(self.node)
387 # TODO: Decide whether to use (X)* or X* based on type of X
388 if " " in s:
389 return f"({s})*"
390 else:
391 return f"{s}*"
392
393 def __repr__(self) -> str:
394 return f"Repeat0({self.node!r})"
395
396 def nullable_visit(self, rules: Dict[str, Rule]) -> bool:
397 return True
398
399
400 class Repeat1(Repeat):
401 def __str__(self) -> str:
402 s = str(self.node)
403 # TODO: Decide whether to use (X)+ or X+ based on type of X
404 if " " in s:
405 return f"({s})+"
406 else:
407 return f"{s}+"
408
409 def __repr__(self) -> str:
410 return f"Repeat1({self.node!r})"
411
412 def nullable_visit(self, rules: Dict[str, Rule]) -> bool:
413 return False
414
415
416 class Gather(Repeat):
417 def __init__(self, separator: Plain, node: Plain):
418 self.separator = separator
419 self.node = node
420
421 def __str__(self) -> str:
422 return f"{self.separator!s}.{self.node!s}+"
423
424 def __repr__(self) -> str:
425 return f"Gather({self.separator!r}, {self.node!r})"
426
427 def nullable_visit(self, rules: Dict[str, Rule]) -> bool:
428 return False
429
430
431 class Group:
432 def __init__(self, rhs: Rhs):
433 self.rhs = rhs
434
435 def __str__(self) -> str:
436 return f"({self.rhs})"
437
438 def __repr__(self) -> str:
439 return f"Group({self.rhs!r})"
440
441 def __iter__(self) -> Iterator[Rhs]:
442 yield self.rhs
443
444 def nullable_visit(self, rules: Dict[str, Rule]) -> bool:
445 return self.rhs.nullable_visit(rules)
446
447 def initial_names(self) -> AbstractSet[str]:
448 return self.rhs.initial_names()
449
450
451 class Cut:
452 def __init__(self) -> None:
453 pass
454
455 def __repr__(self) -> str:
456 return f"Cut()"
457
458 def __str__(self) -> str:
459 return f"~"
460
461 def __iter__(self) -> Iterator[Tuple[str, str]]:
462 if False:
463 yield
464
465 def __eq__(self, other: object) -> bool:
466 if not isinstance(other, Cut):
467 return NotImplemented
468 return True
469
470 def nullable_visit(self, rules: Dict[str, Rule]) -> bool:
471 return True
472
473 def initial_names(self) -> AbstractSet[str]:
474 return set()
475
476
477 Plain = Union[Leaf, Group]
478 Item = Union[Plain, Opt, Repeat, Forced, Lookahead, Rhs, Cut]
479 RuleName = Tuple[str, str]
480 MetaTuple = Tuple[str, Optional[str]]
481 MetaList = List[MetaTuple]
482 RuleList = List[Rule]
483 NamedItemList = List[NamedItem]
484 LookaheadOrCut = Union[Lookahead, Forced, Cut]