43 lines
1.2 KiB
Python
43 lines
1.2 KiB
Python
from calc.parser import Num, BinOp, Unary, Node
|
|
|
|
|
|
class EvalError(Exception):
|
|
pass
|
|
|
|
|
|
def evaluate(node: Node):
|
|
"""Walk the AST and return int | float.
|
|
|
|
Result type rule: if the result is mathematically an integer (no
|
|
fractional part), return int; otherwise return float.
|
|
"""
|
|
if isinstance(node, Num):
|
|
return node.value
|
|
if isinstance(node, Unary):
|
|
val = evaluate(node.operand)
|
|
if node.op == '-':
|
|
return _coerce(-val)
|
|
raise EvalError(f"unknown unary op {node.op!r}")
|
|
if isinstance(node, BinOp):
|
|
left = evaluate(node.left)
|
|
right = evaluate(node.right)
|
|
op = node.op
|
|
if op == '+':
|
|
return _coerce(left + right)
|
|
if op == '-':
|
|
return _coerce(left - right)
|
|
if op == '*':
|
|
return _coerce(left * right)
|
|
if op == '/':
|
|
if right == 0:
|
|
raise EvalError("division by zero")
|
|
return _coerce(left / right)
|
|
raise EvalError(f"unknown binary op {op!r}")
|
|
raise EvalError(f"unknown node type {type(node).__name__}")
|
|
|
|
|
|
def _coerce(value):
|
|
if isinstance(value, float) and value == int(value):
|
|
return int(value)
|
|
return value
|