| 1 | #!/usr/bin/env python3 |
| 2 | # |
| 3 | # SPDX-FileCopyrightText: Copyright 2026 Arm Limited and/or its affiliates <open-source-office@arm.com> |
| 4 | # |
| 5 | # SPDX-License-Identifier: Apache-2.0 |
| 6 | """Helpers for describing grammars as Python objects. |
| 7 | |
| 8 | This module provides a small expression system for writing grammar rules in a |
| 9 | readable Python form. It is intended only for documentation generation and name |
| 10 | validation. Rules are built from ``Expr`` objects: |
| 11 | |
| 12 | * ``Seq`` parses expressions in order. |
| 13 | * ``OneOf`` parses one expression from a set of alternatives. |
| 14 | * ``Optional`` parses an expression if it is present. |
| 15 | * ``OneOrMore`` parses repeated expressions. |
| 16 | * ``Literal`` parses a literal string. |
| 17 | * ``Doc`` attaches documentation to an expression without changing it. |
| 18 | * ``NaturalInt`` parses a positive integer. |
| 19 | * ``Pow2Int`` parses a natural integer that is a power of 2 (1, 2, 4, 8...) |
| 20 | * ``OperandType`` parses a data type descriptor (f32, i8, bf16...) |
| 21 | |
| 22 | ``Grammar`` is a local rule registry. Its ``rule`` decorator evaluates the |
| 23 | decorated function once, wraps the returned expression in a named ``Rule``, and |
| 24 | stores that rule for parsing and documentation generation. Only rules with a |
| 25 | title are included by ``render_markdown``. |
| 26 | |
| 27 | Parsing is position based. Every expression parses an input string |
| 28 | from a starting offset and returns either a ``ParseSuccess`` or ``ParseFailure``. |
| 29 | ``ParseSuccess.pos`` contains the end offset after a successful parse. |
| 30 | ``ParseSuccess.descriptions`` contains descriptions from parsed ``Doc`` nodes. |
| 31 | Alternatives use the longest successful parse. Equal-length successful |
| 32 | alternatives are invalid grammar. |
| 33 | |
| 34 | * ``ParseFailure.failures`` contains ``ParseExpectation`` entries with the input |
| 35 | offset and expected grammar fragment used for developer-facing diagnostics. |
| 36 | * ``Expr.parse_full`` converts partial parses into a failure that expects the |
| 37 | end of input. |
| 38 | * ``furthest_failure`` selects the most advanced failure position and combines |
| 39 | the expected fragments reported there. |
| 40 | """ |
| 41 | from abc import ABC |
| 42 | from abc import abstractmethod |
| 43 | from collections.abc import Callable |
| 44 | from collections.abc import Iterable |
| 45 | from collections.abc import Iterator |
| 46 | from dataclasses import dataclass |
| 47 | from dataclasses import field |
| 48 | from typing import TypeAlias |
| 49 | |
| 50 | |
| 51 | @dataclass(frozen=True) |
| 52 | class ParseExpectation: |
| 53 | """An expected grammar fragment at a failed input position.""" |
| 54 | |
| 55 | pos: int |
| 56 | expected: str |
| 57 | |
| 58 | |
| 59 | @dataclass(frozen=True) |
| 60 | class ParseSuccess: |
| 61 | pos: int |
| 62 | descriptions: list[tuple[int, str]] = field(default_factory=list) |
| 63 | |
| 64 | @property |
| 65 | def parsed_ok(self) -> bool: |
| 66 | return True |
| 67 | |
| 68 | def furthest_failure(self) -> None: |
| 69 | return None |
| 70 | |
| 71 | |
| 72 | @dataclass |
| 73 | class ParseFailure: |
| 74 | failures: list[ParseExpectation] |
| 75 | |
| 76 | @classmethod |
| 77 | def expected(cls, pos: int, expected: str) -> "ParseFailure": |
| 78 | return cls([ParseExpectation(pos, expected)]) |
| 79 | |
| 80 | @property |
| 81 | def parsed_ok(self) -> bool: |
| 82 | return False |
| 83 | |
| 84 | def furthest_failure(self) -> ParseExpectation | None: |
| 85 | if not self.failures: |
| 86 | return None |
| 87 | |
| 88 | max_pos = max(failure.pos for failure in self.failures) |
| 89 | expected = " | ".join( |
| 90 | dict.fromkeys( |
| 91 | failure.expected for failure in self.failures if failure.pos == max_pos |
| 92 | ) |
| 93 | ) |
| 94 | return ParseExpectation(max_pos, expected) |
| 95 | |
| 96 | |
| 97 | ParseResult: TypeAlias = ParseSuccess | ParseFailure |
| 98 | |
| 99 | |
| 100 | # ----------------------------------------------------------------------------- |
| 101 | # Grammar building blocks |
| 102 | # ----------------------------------------------------------------------------- |
| 103 | |
| 104 | |
| 105 | class Expr(ABC): |
| 106 | """Base class for grammar expressions.""" |
| 107 | |
| 108 | @property |
| 109 | def compound(self) -> bool: |
| 110 | """Whether this expression should be grouped when embedded.""" |
| 111 | return False |
| 112 | |
| 113 | def parse_full(self, text: str) -> ParseResult: |
| 114 | """Used for top level expressions to ensure that grammar fully parses a string""" |
| 115 | result = self.parse(text) |
| 116 | if result.parsed_ok and result.pos != len(text): |
| 117 | return ParseFailure.expected(result.pos, "end of input") |
| 118 | return result |
| 119 | |
| 120 | @abstractmethod |
| 121 | def parse(self, text: str, pos: int = 0) -> ParseResult: |
| 122 | """Parse this expression against ``text`` starting at ``pos``.""" |
| 123 | raise NotImplementedError |
| 124 | |
| 125 | @abstractmethod |
| 126 | def to_grammar(self) -> str: |
| 127 | """Render this expression as grammar documentation.""" |
| 128 | raise NotImplementedError |
| 129 | |
| 130 | def __str__(self) -> str: |
| 131 | return self.to_grammar() |
| 132 | |
| 133 | |
| 134 | class _CompoundExpr(Expr): |
| 135 | """Base class for grammar expressions that need grouping when embedded.""" |
| 136 | |
| 137 | @property |
| 138 | def compound(self) -> bool: |
| 139 | """Whether this expression should be grouped when embedded.""" |
| 140 | return True |
| 141 | |
| 142 | |
| 143 | class Seq(_CompoundExpr): |
| 144 | """A sequence of grammar expressions.""" |
| 145 | |
| 146 | def __init__(self, *items: Expr | str) -> None: |
| 147 | self.items = tuple(_as_expr(item) for item in items) |
| 148 | |
| 149 | def parse(self, text: str, pos: int = 0) -> ParseResult: |
| 150 | position = pos |
| 151 | descriptions: list[tuple[int, str]] = [] |
| 152 | for item in self.items: |
| 153 | result = item.parse(text, position) |
| 154 | if not result.parsed_ok: |
| 155 | return result |
| 156 | descriptions.extend(result.descriptions) |
| 157 | position = result.pos |
| 158 | |
| 159 | return ParseSuccess(position, descriptions) |
| 160 | |
| 161 | def to_grammar(self) -> str: |
| 162 | return " ".join( |
| 163 | f"({item.to_grammar()})" if item.compound else item.to_grammar() |
| 164 | for item in self.items |
| 165 | ) |
| 166 | |
| 167 | |
| 168 | class OneOf(_CompoundExpr): |
| 169 | """A choice between multiple grammar expressions.""" |
| 170 | |
| 171 | def __init__(self, *options: Expr | str) -> None: |
| 172 | self.options = tuple(_as_expr(option) for option in options) |
| 173 | |
| 174 | def parse(self, text: str, pos: int = 0) -> ParseResult: |
| 175 | parses: list[ParseSuccess] = [] |
| 176 | failures = [] |
| 177 | for option in self.options: |
| 178 | result = option.parse(text, pos) |
| 179 | if result.parsed_ok: |
| 180 | parses.append(result) |
| 181 | else: |
| 182 | failures.extend(result.failures) |
| 183 | |
| 184 | if parses: |
| 185 | best_pos = max(result.pos for result in parses) |
| 186 | best_parses = [result for result in parses if result.pos == best_pos] |
| 187 | assert len(best_parses) == 1, ( |
| 188 | "Ambiguous grammar alternatives consume the same input: " |
| 189 | f"{self.to_grammar()}" |
| 190 | ) |
| 191 | return best_parses[0] |
| 192 | |
| 193 | result = ParseFailure(failures) |
| 194 | failure = result.furthest_failure() |
| 195 | assert failure is not None |
| 196 | return ParseFailure.expected(failure.pos, failure.expected) |
| 197 | |
| 198 | def to_grammar(self) -> str: |
| 199 | return " | ".join(option.to_grammar() for option in self.options) |
| 200 | |
| 201 | |
| 202 | class Optional(Expr): |
| 203 | """An optional grammar expression.""" |
| 204 | |
| 205 | def __init__(self, expr: Expr | str) -> None: |
| 206 | self.expr = _as_expr(expr) |
| 207 | |
| 208 | def parse(self, text: str, pos: int = 0) -> ParseResult: |
| 209 | result = self.expr.parse(text, pos) |
| 210 | if result.parsed_ok: |
| 211 | assert result.pos != pos, "Optional expression parsed empty input" |
| 212 | return result |
| 213 | return ParseSuccess(pos) |
| 214 | |
| 215 | def to_grammar(self) -> str: |
| 216 | return f"[{self.expr.to_grammar()}]" |
| 217 | |
| 218 | |
| 219 | class OneOrMore(Expr): |
| 220 | """A grammar expression that must appear at least once.""" |
| 221 | |
| 222 | def __init__(self, expr: Expr | str) -> None: |
| 223 | self.expr = _as_expr(expr) |
| 224 | |
| 225 | def parse(self, text: str, pos: int = 0) -> ParseResult: |
| 226 | result = self.expr.parse(text, pos) |
| 227 | if not result.parsed_ok: |
| 228 | return result |
| 229 | |
| 230 | assert result.pos != pos, "Repeated expression parsed empty input" |
| 231 | position = result.pos |
| 232 | descriptions = list(result.descriptions) |
| 233 | while True: |
| 234 | result = self.expr.parse(text, position) |
| 235 | if not result.parsed_ok: |
| 236 | return ParseSuccess(position, descriptions) |
| 237 | assert result.pos != position, "Repeated expression parsed empty input" |
| 238 | descriptions.extend(result.descriptions) |
| 239 | position = result.pos |
| 240 | |
| 241 | def to_grammar(self) -> str: |
| 242 | if not self.expr.compound: |
| 243 | return f"{self.expr.to_grammar()}+" |
| 244 | return f"({self.expr.to_grammar()})+" |
| 245 | |
| 246 | |
| 247 | class Literal(Expr): |
| 248 | """A literal string in the grammar.""" |
| 249 | |
| 250 | def __init__(self, value: str) -> None: |
| 251 | self.value = value |
| 252 | |
| 253 | def parse(self, text: str, pos: int = 0) -> ParseResult: |
| 254 | if text.startswith(self.value, pos): |
| 255 | return ParseSuccess(pos + len(self.value)) |
| 256 | return ParseFailure.expected(pos, self.to_grammar()) |
| 257 | |
| 258 | def to_grammar(self) -> str: |
| 259 | return f'"{self.value}"' |
| 260 | |
| 261 | |
| 262 | class Doc(Expr): |
| 263 | """Documentation for a grammar expression.""" |
| 264 | |
| 265 | def __init__(self, expr: Expr | str, *, description: str) -> None: |
| 266 | self.expr = _as_expr(expr) |
| 267 | self.description = description |
| 268 | |
| 269 | @property |
| 270 | def compound(self) -> bool: |
| 271 | return self.expr.compound |
| 272 | |
| 273 | def parse(self, text: str, pos: int = 0) -> ParseResult: |
| 274 | result = self.expr.parse(text, pos) |
| 275 | if result.parsed_ok and result.pos != pos: |
| 276 | return ParseSuccess( |
| 277 | result.pos, |
| 278 | [(pos, self.description), *result.descriptions], |
| 279 | ) |
| 280 | return result |
| 281 | |
| 282 | def to_grammar(self) -> str: |
| 283 | return self.expr.to_grammar() |
| 284 | |
| 285 | |
| 286 | class NaturalInt(Expr): |
| 287 | """A positive integer literal.""" |
| 288 | |
| 289 | def parse(self, text: str, pos: int = 0) -> ParseResult: |
| 290 | return _parse_positive_integer(text, pos) |
| 291 | |
| 292 | def to_grammar(self) -> str: |
| 293 | return "@natural_int" |
| 294 | |
| 295 | |
| 296 | class Pow2Int(Expr): |
| 297 | """A power-of-two integer literal.""" |
| 298 | |
| 299 | def parse(self, text: str, pos: int = 0) -> ParseResult: |
| 300 | return _parse_positive_integer( |
| 301 | text, pos, lambda value: value > 0 and value & (value - 1) == 0 |
| 302 | ) |
| 303 | |
| 304 | def to_grammar(self) -> str: |
| 305 | return "@pow2_int" |
| 306 | |
| 307 | |
| 308 | class OperandType(Expr): |
| 309 | """A data type descriptor.""" |
| 310 | |
| 311 | def parse(self, text: str, pos: int = 0) -> ParseResult: |
| 312 | for base_type in ("bf", "f", "i", "u", "x"): |
| 313 | if text.startswith(base_type, pos): |
| 314 | result = _parse_positive_integer( |
| 315 | text, |
| 316 | pos + len(base_type), |
| 317 | lambda value: value > 0 and value & (value - 1) == 0, |
| 318 | ) |
| 319 | if result.parsed_ok: |
| 320 | return result |
| 321 | return ParseFailure.expected(pos, self.to_grammar()) |
| 322 | |
| 323 | return ParseFailure.expected(pos, self.to_grammar()) |
| 324 | |
| 325 | def to_grammar(self) -> str: |
| 326 | return "@operand_type" |
| 327 | |
| 328 | |
| 329 | # ----------------------------------------------------------------------------- |
| 330 | # Rule registration and documentation rendering |
| 331 | # ----------------------------------------------------------------------------- |
| 332 | |
| 333 | |
| 334 | class Rule(Expr): |
| 335 | """A named grammar rule with documentation.""" |
| 336 | |
| 337 | def __init__( |
| 338 | self, |
| 339 | name: str, |
| 340 | expr: Expr, |
| 341 | title: str | None, |
| 342 | description: str | None, |
| 343 | ) -> None: |
| 344 | self.name = name |
| 345 | self.expr = expr |
| 346 | self.title = title |
| 347 | self.description = description |
| 348 | |
| 349 | def parse(self, text: str, pos: int = 0) -> ParseResult: |
| 350 | return self.expr.parse(text, pos) |
| 351 | |
| 352 | def to_grammar(self) -> str: |
| 353 | return self.name |
| 354 | |
| 355 | def definition(self) -> str: |
| 356 | return f"{self.name} = {self.expr.to_grammar()}" |
| 357 | |
| 358 | def to_markdown(self) -> str: |
| 359 | lines = [ |
| 360 | f"### `{self.name}`", |
| 361 | "", |
| 362 | "```text", |
| 363 | self.definition(), |
| 364 | "```", |
| 365 | ] |
| 366 | if self.title: |
| 367 | lines.extend(("", self.title)) |
| 368 | if self.description: |
| 369 | lines.extend(("", self.description)) |
| 370 | return "\n".join(lines) |
| 371 | |
| 372 | |
| 373 | class Grammar: |
| 374 | """A local registry for grammar rules.""" |
| 375 | |
| 376 | def __init__(self) -> None: |
| 377 | self._rules: dict[str, Rule] = {} |
| 378 | |
| 379 | def rule( |
| 380 | self, |
| 381 | *, |
| 382 | title: str | None = None, |
| 383 | description: str | None = None, |
| 384 | name: str | None = None, |
| 385 | ) -> Callable[[Callable[[], Expr | str]], Rule]: |
| 386 | def decorate(fn: Callable[[], Expr | str]) -> Rule: |
| 387 | rule_name = name or fn.__name__ |
| 388 | if rule_name in self._rules: |
| 389 | raise ValueError(f"Grammar rule already registered: {rule_name}") |
| 390 | |
| 391 | rule = Rule(rule_name, _as_expr(fn()), title, description) |
| 392 | self._rules[rule_name] = rule |
| 393 | return rule |
| 394 | |
| 395 | return decorate |
| 396 | |
| 397 | def __iter__(self) -> Iterator[Rule]: |
| 398 | return iter(self.iter_rules()) |
| 399 | |
| 400 | def iter_rules(self) -> Iterable[Rule]: |
| 401 | return self._rules.values() |
| 402 | |
| 403 | def iter_documented_rules(self) -> Iterable[Rule]: |
| 404 | return (rule for rule in self.iter_rules() if rule.title) |
| 405 | |
| 406 | def to_grammar(self) -> str: |
| 407 | return "\n".join(rule.definition() for rule in reversed(self._rules.values())) |
| 408 | |
| 409 | def render_markdown(self) -> str: |
| 410 | return "\n\n".join(rule.to_markdown() for rule in self.iter_documented_rules()) |
| 411 | |
| 412 | |
| 413 | def _as_expr(value: Expr | str) -> Expr: |
| 414 | if isinstance(value, Expr): |
| 415 | return value |
| 416 | if isinstance(value, str): |
| 417 | return Literal(value) |
| 418 | raise TypeError(f"Expected grammar expression or string literal, got {type(value)}") |
| 419 | |
| 420 | |
| 421 | def _parse_positive_integer( |
| 422 | text: str, pos: int, predicate: Callable[[int], bool] | None = None |
| 423 | ) -> ParseResult: |
| 424 | expected = "@natural_int" if predicate is None else "@pow2_int" |
| 425 | if pos >= len(text) or not text[pos].isdigit() or text[pos] == "0": |
| 426 | return ParseFailure.expected(pos, expected) |
| 427 | |
| 428 | end = pos |
| 429 | while end < len(text) and text[end].isdigit(): |
| 430 | end += 1 |
| 431 | |
| 432 | value = int(text[pos:end]) |
| 433 | if predicate is None or predicate(value): |
| 434 | return ParseSuccess(end) |
| 435 | return ParseFailure.expected(pos, expected) |