93 lines
2.2 KiB
Python
93 lines
2.2 KiB
Python
from dataclasses import dataclass
|
|
from typing import Union
|
|
|
|
from calc.lexer import Token
|
|
|
|
|
|
class ParseError(Exception):
|
|
pass
|
|
|
|
|
|
@dataclass
|
|
class Num:
|
|
value: Union[int, float]
|
|
|
|
|
|
@dataclass
|
|
class BinOp:
|
|
op: str
|
|
left: object
|
|
right: object
|
|
|
|
|
|
@dataclass
|
|
class Unary:
|
|
op: str
|
|
operand: object
|
|
|
|
|
|
Node = Union[Num, BinOp, Unary]
|
|
|
|
|
|
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 and tok.kind != kind:
|
|
raise ParseError(f"expected {kind!r}, got {tok.kind!r} ({tok.value!r})")
|
|
self._pos += 1
|
|
return tok
|
|
|
|
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._consume().value
|
|
node = BinOp(op, node, self._term())
|
|
return node
|
|
|
|
def _term(self) -> Node:
|
|
node = self._unary()
|
|
while self._peek().kind in ('STAR', 'SLASH'):
|
|
op = self._consume().value
|
|
node = BinOp(op, node, self._unary())
|
|
return node
|
|
|
|
def _unary(self) -> Node:
|
|
if self._peek().kind == 'MINUS':
|
|
self._consume()
|
|
return Unary('-', self._unary())
|
|
return self._primary()
|
|
|
|
def _primary(self) -> Node:
|
|
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(f"unclosed parenthesis, got {self._peek().kind!r}")
|
|
self._consume()
|
|
return node
|
|
raise ParseError(f"unexpected token {tok.kind!r} ({tok.value!r})")
|
|
|
|
|
|
def parse(tokens: list) -> Node:
|
|
return _Parser(tokens).parse()
|