|
| 1 | +import ast |
| 2 | +from ...nucleoid.state import variable_state |
| 3 | + |
| 4 | +def expression_handler(node): |
| 5 | + """ |
| 6 | + Evaluates an AST node and returns its value based on the variable_state dictionary. |
| 7 | +
|
| 8 | + Args: |
| 9 | + node (ast.Node): The AST node to evaluate. |
| 10 | + variable_state (dict): A dictionary containing variable names and their values. |
| 11 | +
|
| 12 | + Returns: |
| 13 | + The evaluated value of the node. |
| 14 | +
|
| 15 | + Raises: |
| 16 | + NameError: If a variable is not defined in variable_state. |
| 17 | + NotImplementedError: If the node type or operation is not supported. |
| 18 | + """ |
| 19 | + if isinstance(node, ast.Name): |
| 20 | + if node.id in variable_state: |
| 21 | + return variable_state[node.id] |
| 22 | + else: |
| 23 | + raise NameError(f"Variable {node.id} is not defined") |
| 24 | + elif isinstance(node, ast.Constant): |
| 25 | + return node.value |
| 26 | + elif isinstance(node, ast.BinOp): |
| 27 | + left = expression_handler(node.left) |
| 28 | + right = expression_handler(node.right) |
| 29 | + if isinstance(node.op, ast.Add): |
| 30 | + return left + right |
| 31 | + elif isinstance(node.op, ast.Sub): |
| 32 | + return left - right |
| 33 | + elif isinstance(node.op, ast.Mult): |
| 34 | + return left * right |
| 35 | + elif isinstance(node.op, ast.Div): |
| 36 | + return left / right |
| 37 | + # Add more operators as needed |
| 38 | + else: |
| 39 | + raise NotImplementedError(f"Operator {node.op} not supported") |
| 40 | + elif isinstance(node, ast.Compare): |
| 41 | + left = expression_handler(node.left) |
| 42 | + right = expression_handler(node.comparators[0]) |
| 43 | + if isinstance(node.ops[0], ast.Eq): |
| 44 | + return left == right |
| 45 | + elif isinstance(node.ops[0], ast.NotEq): |
| 46 | + return left != right |
| 47 | + elif isinstance(node.ops[0], ast.Lt): |
| 48 | + return left < right |
| 49 | + elif isinstance(node.ops[0], ast.LtE): |
| 50 | + return left <= right |
| 51 | + elif isinstance(node.ops[0], ast.Gt): |
| 52 | + return left > right |
| 53 | + elif isinstance(node.ops[0], ast.GtE): |
| 54 | + return left >= right |
| 55 | + # Add more comparison operators as needed |
| 56 | + else: |
| 57 | + raise NotImplementedError(f"Comparison operator {node.ops[0]} not supported") |
| 58 | + else: |
| 59 | + raise NotImplementedError(f"Node type {type(node)} not supported") |
0 commit comments