Spaces:
Sleeping
Sleeping
Download src/world_compiler/runtime/rules/predicate.py from defenestrate/learning-world-goliath: direct link, hf CLI and curl.
- Browser
- Download file 7.99 kB
-
https://huggingface.co/spaces/defenestrate/learning-world-goliath/resolve/main/src/world_compiler/runtime/rules/predicate.py
- Command line
-
hf download hf://spaces/defenestrate/learning-world-goliath/src/world_compiler/runtime/rules/predicate.py
-
curl -L -o predicate.py https://huggingface.co/spaces/defenestrate/learning-world-goliath/resolve/main/src/world_compiler/runtime/rules/predicate.py
7.99 kB
| """Restricted, deterministic predicate compilation and interpretation.""" | |
| import ast | |
| from dataclasses import dataclass, field | |
| from world_compiler.runtime.rules.symbols import RUNTIME_SYMBOLS | |
| type PredicateValue = int | float | str | bool | |
| _ALLOWED_NODE_TYPES: frozenset[type[ast.AST]] = frozenset( | |
| { | |
| ast.Expression, | |
| ast.BoolOp, | |
| ast.And, | |
| ast.Or, | |
| ast.UnaryOp, | |
| ast.Not, | |
| ast.Compare, | |
| ast.Eq, | |
| ast.NotEq, | |
| ast.Lt, | |
| ast.LtE, | |
| ast.Gt, | |
| ast.GtE, | |
| ast.Name, | |
| ast.Load, | |
| ast.Constant, | |
| ast.BinOp, | |
| ast.Add, | |
| ast.Sub, | |
| ast.Mult, | |
| ast.Div, | |
| } | |
| ) | |
| _ENV_VALUE_TYPES = frozenset({int, float, str, bool}) | |
| _ALLOWED_CONSTANT_TYPES = (bool, int, float, str) | |
| _NUMERIC_TYPES = (int, float) | |
| _MAX_EXPRESSION_LENGTH = 500 | |
| _MAX_AST_NODES = 100 | |
| class PredicateError(ValueError): | |
| """Raised when a predicate cannot be compiled or safely evaluated.""" | |
| class _AllowlistValidator(ast.NodeVisitor): | |
| def __init__(self, allowed_names: set[str]) -> None: | |
| self._allowed_names = allowed_names | |
| self.required_names: set[str] = set() | |
| def generic_visit(self, node: ast.AST) -> None: | |
| if type(node) not in _ALLOWED_NODE_TYPES: | |
| raise PredicateError( | |
| f"predicate node {type(node).__name__!r} is not allowed" | |
| ) | |
| super().generic_visit(node) | |
| def visit_Name(self, node: ast.Name) -> None: | |
| if node.id not in self._allowed_names: | |
| raise PredicateError(f"unknown predicate name {node.id!r}") | |
| self.required_names.add(node.id) | |
| self.generic_visit(node) | |
| def visit_Constant(self, node: ast.Constant) -> None: | |
| if not isinstance(node.value, _ALLOWED_CONSTANT_TYPES): | |
| raise PredicateError( | |
| f"predicate constant type {type(node.value).__name__!r} is not allowed" | |
| ) | |
| self.generic_visit(node) | |
| class CompiledPredicate: | |
| """A validated predicate tree that can only be recursively interpreted.""" | |
| expression: str | |
| _tree: ast.Expression = field(repr=False) | |
| _required_names: frozenset[str] = field(repr=False) | |
| def evaluate(self, env: dict[str, PredicateValue]) -> bool: | |
| """Interpret the predicate using a complete scalar environment.""" | |
| if type(env) is not dict: | |
| raise PredicateError("predicate environment must be a dict") | |
| try: | |
| missing = self._required_names.difference(env) | |
| if missing: | |
| names = ", ".join(sorted(missing)) | |
| raise PredicateError(f"missing predicate environment keys: {names}") | |
| values: dict[str, PredicateValue] = {} | |
| for name in self._required_names: | |
| value = env[name] | |
| symbol_spec = RUNTIME_SYMBOLS.get(name) | |
| if symbol_spec is not None and not _matches_symbol_type( | |
| value, symbol_spec.type | |
| ): | |
| raise PredicateError( | |
| f"predicate environment value for {name!r} does not match " | |
| f"runtime symbol type {symbol_spec.type.__name__!r}" | |
| ) | |
| if type(value) not in _ENV_VALUE_TYPES: | |
| raise PredicateError( | |
| f"predicate environment value for {name!r} has unsupported " | |
| f"type {type(value).__name__!r}" | |
| ) | |
| values[name] = value | |
| return bool(_interpret(self._tree.body, values)) | |
| except PredicateError: | |
| raise | |
| except ( | |
| ArithmeticError, | |
| MemoryError, | |
| RecursionError, | |
| TypeError, | |
| ValueError, | |
| ) as exc: | |
| raise PredicateError("predicate evaluation failed") from exc | |
| def compile_predicate(expr: str, world_variables: set[str]) -> CompiledPredicate: | |
| """Parse and validate a predicate against the closed v1 name catalog.""" | |
| if len(expr) > _MAX_EXPRESSION_LENGTH: | |
| raise PredicateError("predicate expression exceeds 500 characters") | |
| try: | |
| tree = ast.parse(expr, mode="eval") | |
| except (SyntaxError, ValueError) as exc: | |
| raise PredicateError("invalid predicate syntax") from exc | |
| allowed_names = set(world_variables) | RUNTIME_SYMBOLS.keys() | |
| validator = _AllowlistValidator(allowed_names) | |
| try: | |
| validator.visit(tree) | |
| except RecursionError as exc: | |
| raise PredicateError("predicate is too deeply nested") from exc | |
| if sum(1 for _ in ast.walk(tree)) > _MAX_AST_NODES: | |
| raise PredicateError("predicate expression exceeds 100 AST nodes") | |
| return CompiledPredicate(expr, tree, frozenset(validator.required_names)) | |
| def _interpret(node: ast.AST, env: dict[str, PredicateValue]): | |
| if isinstance(node, ast.Constant): | |
| return node.value | |
| if isinstance(node, ast.Name): | |
| return env[node.id] | |
| if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not): | |
| return not _interpret(node.operand, env) | |
| if isinstance(node, ast.BoolOp): | |
| if isinstance(node.op, ast.And): | |
| result = _interpret(node.values[0], env) | |
| for value in node.values[1:]: | |
| if not result: | |
| return result | |
| result = _interpret(value, env) | |
| return result | |
| if isinstance(node.op, ast.Or): | |
| result = _interpret(node.values[0], env) | |
| for value in node.values[1:]: | |
| if result: | |
| return result | |
| result = _interpret(value, env) | |
| return result | |
| if isinstance(node, ast.BinOp): | |
| left = _interpret(node.left, env) | |
| right = _interpret(node.right, env) | |
| if not _are_numeric(left, right): | |
| raise PredicateError("predicate arithmetic operands must be int or float") | |
| if isinstance(node.op, ast.Add): | |
| return left + right | |
| if isinstance(node.op, ast.Sub): | |
| return left - right | |
| if isinstance(node.op, ast.Mult): | |
| return left * right | |
| if isinstance(node.op, ast.Div): | |
| return left / right | |
| if isinstance(node, ast.Compare): | |
| left = _interpret(node.left, env) | |
| for operator, comparator in zip(node.ops, node.comparators, strict=True): | |
| right = _interpret(comparator, env) | |
| if not _compare(operator, left, right): | |
| return False | |
| left = right | |
| return True | |
| raise PredicateError( | |
| f"validated predicate node {type(node).__name__!r} cannot be interpreted" | |
| ) | |
| def _compare(operator: ast.cmpop, left, right) -> bool: | |
| if isinstance(operator, ast.Eq): | |
| return left == right | |
| if isinstance(operator, ast.NotEq): | |
| return left != right | |
| if isinstance(operator, ast.Lt): | |
| return left < right | |
| if isinstance(operator, ast.LtE): | |
| return left <= right | |
| if isinstance(operator, ast.Gt): | |
| return left > right | |
| if isinstance(operator, ast.GtE): | |
| return left >= right | |
| raise PredicateError( | |
| f"comparison operator {type(operator).__name__!r} is not allowed" | |
| ) | |
| def _matches_symbol_type(value: PredicateValue, expected_type: type) -> bool: | |
| return isinstance(value, expected_type) and not ( | |
| expected_type is int and isinstance(value, bool) | |
| ) | |
| def _are_numeric(left: PredicateValue, right: PredicateValue) -> bool: | |
| return ( | |
| isinstance(left, _NUMERIC_TYPES) | |
| and not isinstance(left, bool) | |
| and isinstance(right, _NUMERIC_TYPES) | |
| and not isinstance(right, bool) | |
| ) | |