124 lines
3.0 KiB
Python
124 lines
3.0 KiB
Python
"""Recursive-descent parser for arithmetic expressions.
|
|
|
|
AST nodes:
|
|
Num(value) — numeric literal
|
|
BinOp(op, left, right) — binary op; op in {'+', '-', '*', '/'}
|
|
Unary(op, operand) — unary op; op == '-'
|
|
"""
|
|
from dataclasses import dataclass
|
|
from typing import Union
|
|
from .lexer import Token
|
|
|
|
|
|
class ParseError(Exception):
|
|
"""Raised on malformed input."""
|
|
|
|
|
|
@dataclass
|
|
class Num:
|
|
value: Union[int, float]
|
|
|
|
def __repr__(self):
|
|
return f"Num({self.value!r})"
|
|
|
|
|
|
@dataclass
|
|
class BinOp:
|
|
op: str
|
|
left: object
|
|
right: object
|
|
|
|
def __repr__(self):
|
|
return f"BinOp({self.op!r}, {self.left!r}, {self.right!r})"
|
|
|
|
|
|
@dataclass
|
|
class Unary:
|
|
op: str
|
|
operand: object
|
|
|
|
def __repr__(self):
|
|
return f"Unary({self.op!r}, {self.operand!r})"
|
|
|
|
|
|
_KIND_TO_OP = {
|
|
'PLUS': '+',
|
|
'MINUS': '-',
|
|
'STAR': '*',
|
|
'SLASH': '/',
|
|
}
|
|
|
|
|
|
class _Parser:
|
|
def __init__(self, tokens: list):
|
|
self._tokens = tokens
|
|
self._pos = 0
|
|
|
|
def _peek(self) -> Token:
|
|
return self._tokens[self._pos]
|
|
|
|
def _consume(self, kind: str = None) -> Token:
|
|
tok = self._tokens[self._pos]
|
|
if kind is not None and tok.kind != kind:
|
|
raise ParseError(f"expected {kind!r}, got {tok.kind!r}")
|
|
self._pos += 1
|
|
return tok
|
|
|
|
def parse(self):
|
|
if self._peek().kind == 'EOF':
|
|
raise ParseError("empty expression")
|
|
node = self._expr()
|
|
if self._peek().kind != 'EOF':
|
|
raise ParseError(f"unexpected token {self._peek().kind!r}")
|
|
return node
|
|
|
|
def _expr(self):
|
|
node = self._term()
|
|
while self._peek().kind in ('PLUS', 'MINUS'):
|
|
op = _KIND_TO_OP[self._consume().kind]
|
|
right = self._term()
|
|
node = BinOp(op, node, right)
|
|
return node
|
|
|
|
def _term(self):
|
|
node = self._unary()
|
|
while self._peek().kind in ('STAR', 'SLASH'):
|
|
op = _KIND_TO_OP[self._consume().kind]
|
|
right = self._unary()
|
|
node = BinOp(op, node, right)
|
|
return node
|
|
|
|
def _unary(self):
|
|
if self._peek().kind == 'MINUS':
|
|
self._consume()
|
|
return Unary('-', self._unary())
|
|
return self._primary()
|
|
|
|
def _primary(self):
|
|
tok = self._peek()
|
|
if tok.kind == 'NUMBER':
|
|
self._consume()
|
|
return Num(tok.value)
|
|
if tok.kind == 'LPAREN':
|
|
self._consume()
|
|
node = self._expr()
|
|
if self._peek().kind != 'RPAREN':
|
|
raise ParseError("unclosed parenthesis, expected ')'")
|
|
self._consume()
|
|
return node
|
|
if tok.kind == 'EOF':
|
|
raise ParseError("unexpected end of input")
|
|
raise ParseError(f"unexpected token {tok.kind!r}")
|
|
|
|
|
|
def parse(tokens: list):
|
|
"""Parse a token list into an AST.
|
|
|
|
Returns:
|
|
Num | BinOp | Unary — root node.
|
|
|
|
Raises:
|
|
ParseError: on any malformed input.
|
|
"""
|
|
return _Parser(tokens).parse()
|