116 lines
3.1 KiB
Python
116 lines
3.1 KiB
Python
class ParseError(Exception):
|
|
pass
|
|
|
|
|
|
class Num:
|
|
def __init__(self, value):
|
|
self.value = value
|
|
|
|
def __repr__(self):
|
|
return f"Num({self.value!r})"
|
|
|
|
def __eq__(self, other):
|
|
return isinstance(other, Num) and self.value == other.value
|
|
|
|
|
|
class BinOp:
|
|
def __init__(self, op: str, left, right):
|
|
self.op = op
|
|
self.left = left
|
|
self.right = right
|
|
|
|
def __repr__(self):
|
|
return f"BinOp({self.op!r}, {self.left!r}, {self.right!r})"
|
|
|
|
def __eq__(self, other):
|
|
return (isinstance(other, BinOp) and self.op == other.op
|
|
and self.left == other.left and self.right == other.right)
|
|
|
|
|
|
class Unary:
|
|
def __init__(self, op: str, operand):
|
|
self.op = op
|
|
self.operand = operand
|
|
|
|
def __repr__(self):
|
|
return f"Unary({self.op!r}, {self.operand!r})"
|
|
|
|
def __eq__(self, other):
|
|
return (isinstance(other, Unary) and self.op == other.op
|
|
and self.operand == other.operand)
|
|
|
|
|
|
class _Parser:
|
|
def __init__(self, tokens):
|
|
self._tokens = tokens
|
|
self._pos = 0
|
|
|
|
def _current(self):
|
|
return self._tokens[self._pos]
|
|
|
|
def _advance(self):
|
|
tok = self._tokens[self._pos]
|
|
if tok.kind != 'EOF':
|
|
self._pos += 1
|
|
return tok
|
|
|
|
def _expect(self, kind):
|
|
tok = self._current()
|
|
if tok.kind != kind:
|
|
raise ParseError(f"expected {kind}, got {tok!r}")
|
|
return self._advance()
|
|
|
|
def expr(self):
|
|
left = self._term()
|
|
while self._current().kind in ('PLUS', 'MINUS'):
|
|
op = self._advance().value
|
|
right = self._term()
|
|
left = BinOp(op, left, right)
|
|
return left
|
|
|
|
def _term(self):
|
|
left = self._unary()
|
|
while self._current().kind in ('STAR', 'SLASH'):
|
|
op = self._advance().value
|
|
right = self._unary()
|
|
left = BinOp(op, left, right)
|
|
return left
|
|
|
|
def _unary(self):
|
|
if self._current().kind == 'MINUS':
|
|
self._advance()
|
|
operand = self._unary()
|
|
return Unary('-', operand)
|
|
return self._primary()
|
|
|
|
def _primary(self):
|
|
tok = self._current()
|
|
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!r}")
|
|
|
|
|
|
def parse(tokens) -> object:
|
|
"""Parse a token list (from lexer.tokenize) into an AST.
|
|
|
|
Returns the root Node, one of:
|
|
Num(value) — numeric literal
|
|
BinOp(op, left, right) — binary + - * /
|
|
Unary(op, operand) — unary -
|
|
|
|
Raises ParseError on malformed input.
|
|
"""
|
|
if not tokens or (len(tokens) == 1 and tokens[0].kind == 'EOF'):
|
|
raise ParseError("empty input")
|
|
p = _Parser(tokens)
|
|
node = p.expr()
|
|
if p._current().kind != 'EOF':
|
|
raise ParseError(f"unexpected token after expression: {p._current()!r}")
|
|
return node
|