37 lines
1.2 KiB
Python
37 lines
1.2 KiB
Python
from __future__ import annotations
|
|
from calc.parser import Node, Num, BinOp, Unary
|
|
|
|
|
|
class EvalError(Exception):
|
|
pass
|
|
|
|
|
|
def evaluate(node: Node) -> int | float:
|
|
"""Walk an AST and return its numeric value.
|
|
|
|
Uses true division (7/2 → 3.5). Division by zero raises EvalError.
|
|
Integer operands with integer-only operations (+ - *) return int;
|
|
any division always returns float. The CLI formats whole floats as int.
|
|
"""
|
|
if isinstance(node, Num):
|
|
return node.value
|
|
if isinstance(node, Unary):
|
|
if node.op == '-':
|
|
return -evaluate(node.operand)
|
|
raise EvalError(f"unknown unary operator: {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")
|
|
return left / right
|
|
raise EvalError(f"unknown binary operator: {node.op!r}")
|
|
raise EvalError(f"unknown node type: {type(node)!r}")
|