39 lines
1.2 KiB
Python
39 lines
1.2 KiB
Python
from calc.parser import Num, BinOp, Unary
|
|
|
|
|
|
class EvalError(Exception):
|
|
pass
|
|
|
|
|
|
def evaluate(node) -> 'int | float':
|
|
"""Walk an AST node and return the numeric result.
|
|
|
|
Result type rule: returns int for whole-valued results (including whole-valued
|
|
division), float for non-whole. Division by zero raises EvalError.
|
|
"""
|
|
if isinstance(node, Num):
|
|
return node.value
|
|
if isinstance(node, Unary):
|
|
v = evaluate(node.operand)
|
|
if node.op == '-':
|
|
return -v
|
|
raise EvalError(f"unknown unary op {node.op!r}")
|
|
if isinstance(node, BinOp):
|
|
left = evaluate(node.left)
|
|
right = evaluate(node.right)
|
|
if node.op == '+':
|
|
return left + right
|
|
if node.op == '-':
|
|
return left - right
|
|
if node.op == '*':
|
|
return left * right
|
|
if node.op == '/':
|
|
if right == 0:
|
|
raise EvalError("division by zero")
|
|
result = left / right
|
|
if isinstance(result, float) and result.is_integer():
|
|
return int(result)
|
|
return result
|
|
raise EvalError(f"unknown binary op {node.op!r}")
|
|
raise EvalError(f"unknown node type {type(node).__name__!r}")
|