""" AST evaluator for the calc expression language. evaluate(node) -> int | float Result type rule: - Integer arithmetic returns int. - Division (/) always uses true division; if the result is whole-valued (e.g. 4/2 == 2.0) it is coerced to int, otherwise returned as float. """ from calc.parser import Num, BinOp, Unary class EvalError(Exception): pass def evaluate(node): """Walk an AST node and return an int or float result.""" if isinstance(node, Num): return node.value if isinstance(node, Unary): val = evaluate(node.operand) if node.op == '-': return -val 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 binary operator: {node.op!r}") # Coerce whole-valued floats to int so "4/2" prints as "2" not "2.0" if isinstance(result, float) and result.is_integer(): return int(result) return result raise EvalError(f"Unknown AST node type: {type(node).__name__!r}")