|
| 1 | +"""Deterministic arithmetic formula evaluation without eval().""" |
| 2 | + |
| 3 | +import ast |
| 4 | +import operator |
| 5 | +from typing import Mapping |
| 6 | + |
| 7 | + |
| 8 | +class FormulaEngine: |
| 9 | + """Safe arithmetic evaluator backed by Python's AST.""" |
| 10 | + |
| 11 | + _binary_operators = { |
| 12 | + ast.Add: operator.add, |
| 13 | + ast.Sub: operator.sub, |
| 14 | + ast.Mult: operator.mul, |
| 15 | + ast.Div: operator.truediv, |
| 16 | + } |
| 17 | + _unary_operators = { |
| 18 | + ast.UAdd: operator.pos, |
| 19 | + ast.USub: operator.neg, |
| 20 | + } |
| 21 | + |
| 22 | + def evaluate(self, formula: str, values: Mapping[str, float]) -> float: |
| 23 | + parsed = ast.parse(formula, mode="eval") |
| 24 | + return float(self._evaluate_node(parsed.body, values)) |
| 25 | + |
| 26 | + def _evaluate_node(self, node: ast.AST, values: Mapping[str, float]) -> float: |
| 27 | + if isinstance(node, ast.BinOp): |
| 28 | + return self._evaluate_binary(node, values) |
| 29 | + if isinstance(node, ast.UnaryOp) and type(node.op) in self._unary_operators: |
| 30 | + operand = self._evaluate_node(node.operand, values) |
| 31 | + return self._unary_operators[type(node.op)](operand) |
| 32 | + if isinstance(node, ast.Name): |
| 33 | + if node.id not in values: |
| 34 | + raise KeyError(f"Missing value for concept '{node.id}'") |
| 35 | + return float(values[node.id]) |
| 36 | + if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)): |
| 37 | + return float(node.value) |
| 38 | + if isinstance(node, ast.Num): |
| 39 | + return float(node.n) |
| 40 | + raise ValueError(f"Unsupported formula node: {ast.dump(node)}") |
| 41 | + |
| 42 | + def _evaluate_binary(self, node: ast.BinOp, values: Mapping[str, float]) -> float: |
| 43 | + operator_type = type(node.op) |
| 44 | + if operator_type not in self._binary_operators: |
| 45 | + raise ValueError(f"Unsupported operator: {operator_type.__name__}") |
| 46 | + left = self._evaluate_node(node.left, values) |
| 47 | + right = self._evaluate_node(node.right, values) |
| 48 | + if operator_type is ast.Div and right == 0: |
| 49 | + raise ZeroDivisionError("Division by zero in formula evaluation") |
| 50 | + return self._binary_operators[operator_type](left, right) |
0 commit comments