38 lines
1.1 KiB
Python
38 lines
1.1 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.
|
|
|
|
Returns int for whole-valued results, float otherwise.
|
|
Raises EvalError on division by zero.
|
|
"""
|
|
if isinstance(node, Num):
|
|
return node.value
|
|
if isinstance(node, Unary):
|
|
return -evaluate(node.operand)
|
|
if isinstance(node, BinOp):
|
|
left = evaluate(node.left)
|
|
right = evaluate(node.right)
|
|
if node.op == '+':
|
|
result = left + right
|
|
elif node.op == '-':
|
|
result = left - right
|
|
elif node.op == '*':
|
|
result = left * right
|
|
elif node.op == '/':
|
|
if right == 0:
|
|
raise EvalError("division by zero")
|
|
result = left / right
|
|
else:
|
|
raise EvalError(f"unknown operator {node.op!r}")
|
|
# Return int when the result is whole-valued
|
|
if isinstance(result, float) and result.is_integer():
|
|
return int(result)
|
|
return result
|
|
raise EvalError(f"unknown node type {type(node)!r}")
|