| 1 | from typing import Optional |
| 2 | |
| 3 | from pegen import grammar |
| 4 | from pegen.grammar import ( |
| 5 | Alt, |
| 6 | GrammarVisitor, |
| 7 | Rule, |
| 8 | Rhs, |
| 9 | ) |
| 10 | |
| 11 | |
| 12 | class ValidationError(Exception): |
| 13 | pass |
| 14 | |
| 15 | |
| 16 | class GrammarValidator(GrammarVisitor): |
| 17 | def __init__(self, grammar: grammar.Grammar) -> None: |
| 18 | self.grammar = grammar |
| 19 | self.rulename: Optional[str] = None |
| 20 | |
| 21 | def validate_rule(self, rulename: str, node: Rule) -> None: |
| 22 | self.rulename = rulename |
| 23 | self.visit(node) |
| 24 | self.rulename = None |
| 25 | |
| 26 | |
| 27 | class SubRuleValidator(GrammarValidator): |
| 28 | def visit_Rhs(self, node: Rhs) -> None: |
| 29 | for index, alt in enumerate(node.alts): |
| 30 | alts_to_consider = node.alts[index + 1 :] |
| 31 | for other_alt in alts_to_consider: |
| 32 | self.check_intersection(alt, other_alt) |
| 33 | |
| 34 | def check_intersection(self, first_alt: Alt, second_alt: Alt) -> None: |
| 35 | if str(second_alt).startswith(str(first_alt)): |
| 36 | raise ValidationError( |
| 37 | f"In {self.rulename} there is an alternative that will " |
| 38 | f"never be visited:\n{second_alt}" |
| 39 | ) |
| 40 | |
| 41 | |
| 42 | def validate_grammar(the_grammar: grammar.Grammar) -> None: |
| 43 | for validator_cls in GrammarValidator.__subclasses__(): |
| 44 | validator = validator_cls(the_grammar) |
| 45 | for rule_name, rule in the_grammar.rules.items(): |
| 46 | validator.validate_rule(rule_name, rule) |