"""Evaluator for arithmetic AST nodes produced by calc.parser.""" from calc.parser import Num, BinOp, Unary class EvalError(Exception): pass def evaluate(node) -> int | float: """Walk the AST and return the numeric result. Whole-valued floats are returned as int (e.g. 4/2 → 2, not 2.0). Division by zero raises EvalError. """ if isinstance(node, Num): return node.value if isinstance(node, Unary): operand = evaluate(node.operand) if node.op == "-": return -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 == "+": 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}") # Normalize: whole-valued float → int if isinstance(result, float) and result == int(result): return int(result) return result raise EvalError(f"unknown node type: {type(node).__name__}")