|
| 1 | +""" |
| 2 | +Evaluator for AST nodes generated by Parser. |
| 3 | +Evaluates math expressions with variable and function support. |
| 4 | +""" |
| 5 | + |
| 6 | +import math |
| 7 | +from typing import Dict, Any, Union |
| 8 | +from expression_parser.parser import ASTNode, NumberNode, VariableNode, UnaryOpNode, BinaryOpNode, FunctionCallNode |
| 9 | + |
| 10 | + |
| 11 | +class EvaluationError(Exception): |
| 12 | + pass |
| 13 | + |
| 14 | + |
| 15 | +class Evaluator: |
| 16 | + BUILTIN_FUNCTIONS = { |
| 17 | + "sin": math.sin, |
| 18 | + "cos": math.cos, |
| 19 | + "tan": math.tan, |
| 20 | + "asin": math.asin, |
| 21 | + "acos": math.acos, |
| 22 | + "atan": math.atan, |
| 23 | + "sqrt": math.sqrt, |
| 24 | + "abs": abs, |
| 25 | + "log": math.log, |
| 26 | + "exp": math.exp, |
| 27 | + "floor": math.floor, |
| 28 | + "ceil": math.ceil, |
| 29 | + "min": min, |
| 30 | + "max": max, |
| 31 | + } |
| 32 | + |
| 33 | + BUILTIN_CONSTANTS = { |
| 34 | + "pi": math.pi, |
| 35 | + "e": math.e, |
| 36 | + "tau": math.tau, |
| 37 | + } |
| 38 | + |
| 39 | + def __init__(self, variables: Dict[str, Union[int, float]] = None): |
| 40 | + self.variables = self.BUILTIN_CONSTANTS.copy() |
| 41 | + if variables: |
| 42 | + self.variables.update(variables) |
| 43 | + |
| 44 | + def evaluate(self, node: ASTNode) -> Union[int, float]: |
| 45 | + if isinstance(node, NumberNode): |
| 46 | + return node.value |
| 47 | + |
| 48 | + if isinstance(node, VariableNode): |
| 49 | + if node.name in self.variables: |
| 50 | + return self.variables[node.name] |
| 51 | + raise EvaluationError(f"Undefined variable or constant: '{node.name}'") |
| 52 | + |
| 53 | + if isinstance(node, UnaryOpNode): |
| 54 | + val = self.evaluate(node.operand) |
| 55 | + if node.operator == '+': |
| 56 | + return +val |
| 57 | + elif node.operator == '-': |
| 58 | + return -val |
| 59 | + raise EvaluationError(f"Unsupported unary operator: '{node.operator}'") |
| 60 | + |
| 61 | + if isinstance(node, BinaryOpNode): |
| 62 | + left_val = self.evaluate(node.left) |
| 63 | + right_val = self.evaluate(node.right) |
| 64 | + |
| 65 | + if node.operator == '+': |
| 66 | + return left_val + right_val |
| 67 | + elif node.operator == '-': |
| 68 | + return left_val - right_val |
| 69 | + elif node.operator == '*': |
| 70 | + return left_val * right_val |
| 71 | + elif node.operator == '/': |
| 72 | + if right_val == 0: |
| 73 | + raise EvaluationError("Division by zero") |
| 74 | + return left_val / right_val |
| 75 | + elif node.operator == '%': |
| 76 | + if right_val == 0: |
| 77 | + raise EvaluationError("Modulo by zero") |
| 78 | + return left_val % right_val |
| 79 | + elif node.operator in ('^', '**'): |
| 80 | + try: |
| 81 | + res = left_val ** right_val |
| 82 | + if isinstance(res, complex): |
| 83 | + raise EvaluationError("Complex numbers result not supported in real domain") |
| 84 | + return res |
| 85 | + except OverflowError: |
| 86 | + raise EvaluationError("Numerical overflow in exponentiation") |
| 87 | + |
| 88 | + raise EvaluationError(f"Unsupported binary operator: '{node.operator}'") |
| 89 | + |
| 90 | + if isinstance(node, FunctionCallNode): |
| 91 | + fn_name = node.name.lower() |
| 92 | + if fn_name not in self.BUILTIN_FUNCTIONS: |
| 93 | + raise EvaluationError(f"Unknown or unsupported function: '{node.name}'") |
| 94 | + |
| 95 | + args = [self.evaluate(arg) for arg in node.args] |
| 96 | + func = self.BUILTIN_FUNCTIONS[fn_name] |
| 97 | + |
| 98 | + try: |
| 99 | + result = func(*args) |
| 100 | + return result |
| 101 | + except TypeError as e: |
| 102 | + raise EvaluationError(f"Invalid arguments for function '{node.name}': {e}") |
| 103 | + except ValueError as e: |
| 104 | + raise EvaluationError(f"Mathematical domain error in function '{node.name}': {e}") |
| 105 | + |
| 106 | + raise EvaluationError(f"Unknown AST node type: {type(node).__name__}") |
| 107 | + |
| 108 | + |
| 109 | +def evaluate_expression(expression: str, variables: Dict[str, Union[int, float]] = None) -> Union[int, float]: |
| 110 | + """Helper function to tokenize, parse, and evaluate a math expression string.""" |
| 111 | + from expression_parser.tokenizer import Tokenizer |
| 112 | + from expression_parser.parser import Parser |
| 113 | + |
| 114 | + tokenizer = Tokenizer(expression) |
| 115 | + tokens = tokenizer.tokenize() |
| 116 | + parser = Parser(tokens) |
| 117 | + ast = parser.parse() |
| 118 | + evaluator = Evaluator(variables) |
| 119 | + return evaluator.evaluate(ast) |
0 commit comments