artifacts: add calculators/ — the 30 built calculators (5/variant) + machine-docs + git logs
This commit is contained in:
120
calculators/builder-adversary-deferred/run-03/calc/parser.py
Normal file
120
calculators/builder-adversary-deferred/run-03/calc/parser.py
Normal file
@ -0,0 +1,120 @@
|
||||
"""Recursive-descent parser for arithmetic expressions.
|
||||
|
||||
AST node shapes:
|
||||
Num(value) — a numeric literal; value is int or float
|
||||
BinOp(op, left, right) — binary op; op is one of '+', '-', '*', '/'
|
||||
Unary(op, operand) — unary minus; op is '-'
|
||||
|
||||
Grammar (precedence encoded by structure):
|
||||
expr = term ( ('+' | '-') term )*
|
||||
term = unary ( ('*' | '/') unary )*
|
||||
unary = '-' unary | primary
|
||||
primary= NUMBER | '(' expr ')'
|
||||
"""
|
||||
from __future__ import annotations
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Union
|
||||
from calc.lexer import Token
|
||||
|
||||
|
||||
class ParseError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
@dataclass
|
||||
class Num:
|
||||
value: Union[int, float]
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Num({self.value!r})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class BinOp:
|
||||
op: str
|
||||
left: "Node"
|
||||
right: "Node"
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"BinOp({self.op!r}, {self.left!r}, {self.right!r})"
|
||||
|
||||
|
||||
@dataclass
|
||||
class Unary:
|
||||
op: str
|
||||
operand: "Node"
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"Unary({self.op!r}, {self.operand!r})"
|
||||
|
||||
|
||||
Node = Union[Num, BinOp, Unary]
|
||||
|
||||
|
||||
class _Parser:
|
||||
def __init__(self, tokens: List[Token]) -> None:
|
||||
self._tokens = tokens
|
||||
self._pos = 0
|
||||
|
||||
def _peek(self) -> Token:
|
||||
return self._tokens[self._pos]
|
||||
|
||||
def _advance(self) -> Token:
|
||||
tok = self._tokens[self._pos]
|
||||
self._pos += 1
|
||||
return tok
|
||||
|
||||
def _expect(self, kind: str) -> Token:
|
||||
tok = self._peek()
|
||||
if tok.kind != kind:
|
||||
raise ParseError(f"expected {kind}, got {tok.kind!r} ({tok.value!r})")
|
||||
return self._advance()
|
||||
|
||||
def parse(self) -> Node:
|
||||
if self._peek().kind == "EOF":
|
||||
raise ParseError("empty input")
|
||||
node = self._expr()
|
||||
if self._peek().kind != "EOF":
|
||||
tok = self._peek()
|
||||
raise ParseError(f"unexpected token {tok.kind!r} ({tok.value!r})")
|
||||
return node
|
||||
|
||||
def _expr(self) -> Node:
|
||||
node = self._term()
|
||||
while self._peek().kind in ("PLUS", "MINUS"):
|
||||
op = self._advance().value
|
||||
right = self._term()
|
||||
node = BinOp(op, node, right)
|
||||
return node
|
||||
|
||||
def _term(self) -> Node:
|
||||
node = self._unary()
|
||||
while self._peek().kind in ("STAR", "SLASH"):
|
||||
op = self._advance().value
|
||||
right = self._unary()
|
||||
node = BinOp(op, node, right)
|
||||
return node
|
||||
|
||||
def _unary(self) -> Node:
|
||||
if self._peek().kind == "MINUS":
|
||||
op = self._advance().value
|
||||
operand = self._unary()
|
||||
return Unary(op, operand)
|
||||
return self._primary()
|
||||
|
||||
def _primary(self) -> Node:
|
||||
tok = self._peek()
|
||||
if tok.kind == "NUMBER":
|
||||
self._advance()
|
||||
return Num(tok.value)
|
||||
if tok.kind == "LPAREN":
|
||||
self._advance()
|
||||
node = self._expr()
|
||||
self._expect("RPAREN")
|
||||
return node
|
||||
raise ParseError(f"unexpected token {tok.kind!r} ({tok.value!r})")
|
||||
|
||||
|
||||
def parse(tokens: List[Token]) -> Node:
|
||||
"""Parse a token list (from lexer.tokenize) into an AST."""
|
||||
return _Parser(tokens).parse()
|
||||
Reference in New Issue
Block a user