rsnarsna
feat(alli-backend): Wave-1 standardization, standalone sys.env node & vault crypto, and DEC-014 security hardening
8628c98 Download language_core/nodes/nodes_oop.py from Rsnarsna/auto: direct link, hf CLI and curl.
- Browser
- Download file 9.59 kB
-
https://huggingface.co/spaces/Rsnarsna/auto/resolve/main/language_core/nodes/nodes_oop.py
- Command line
-
hf download hf://spaces/Rsnarsna/auto/language_core/nodes/nodes_oop.py
-
curl -L -o nodes_oop.py https://huggingface.co/spaces/Rsnarsna/auto/resolve/main/language_core/nodes/nodes_oop.py
9.59 kB
| """ | |
| ALLI Domain Nodes: Functions & Object-Oriented Programming (OOP). | |
| Covers: function.def, function.call, oop.class_def, oop.instance, oop.method_call. | |
| Strictly ZERO eval() — uses AST-whitelisted expression evaluation. | |
| """ | |
| import ast | |
| import operator | |
| from typing import Any, Dict, List, Tuple | |
| from language_core.nodes.loader import parse_safe_literal_or_json, register_domain_nodes | |
| _BIN_OPS = { | |
| ast.Add: operator.add, | |
| ast.Sub: operator.sub, | |
| ast.Mult: operator.mul, | |
| ast.Div: operator.truediv, | |
| ast.FloorDiv: operator.floordiv, | |
| ast.Mod: operator.mod, | |
| ast.Pow: operator.pow, | |
| } | |
| _UNARY_OPS = {ast.UAdd: operator.pos, ast.USub: operator.neg, ast.Not: operator.not_} | |
| _CMP_OPS = { | |
| ast.Eq: operator.eq, | |
| ast.NotEq: operator.ne, | |
| ast.Lt: operator.lt, | |
| ast.LtE: operator.le, | |
| ast.Gt: operator.gt, | |
| ast.GtE: operator.ge, | |
| ast.In: lambda a, b: a in b, | |
| ast.NotIn: lambda a, b: a not in b, | |
| } | |
| def _eval_ast_node(node: ast.AST, env: Dict[str, Any]) -> Any: | |
| if isinstance(node, ast.Constant): | |
| return node.value | |
| if isinstance(node, ast.Name): | |
| if node.id in env: | |
| return env[node.id] | |
| if node.id in ("True", "False", "None"): | |
| return {"True": True, "False": False, "None": None}[node.id] | |
| raise NameError(f"Identifier '{node.id}' not defined in safe expression scope.") | |
| if isinstance(node, ast.BinOp) and type(node.op) in _BIN_OPS: | |
| return _BIN_OPS[type(node.op)](_eval_ast_node(node.left, env), _eval_ast_node(node.right, env)) | |
| if isinstance(node, ast.UnaryOp) and type(node.op) in _UNARY_OPS: | |
| return _UNARY_OPS[type(node.op)](_eval_ast_node(node.operand, env)) | |
| if isinstance(node, ast.BoolOp): | |
| vals = [_eval_ast_node(v, env) for v in node.values] | |
| if isinstance(node.op, ast.And): | |
| res: Any = vals[0] | |
| for v in vals[1:]: | |
| res = res and v | |
| return res | |
| res = vals[0] | |
| for v in vals[1:]: | |
| res = res or v | |
| return res | |
| if isinstance(node, ast.Compare): | |
| left = _eval_ast_node(node.left, env) | |
| for op, comp in zip(node.ops, node.comparators): | |
| right = _eval_ast_node(comp, env) | |
| if type(op) not in _CMP_OPS or not _CMP_OPS[type(op)](left, right): | |
| return False | |
| left = right | |
| return True | |
| if isinstance(node, ast.IfExp): | |
| return _eval_ast_node(node.body if _eval_ast_node(node.test, env) else node.orelse, env) | |
| if isinstance(node, ast.List): | |
| return [_eval_ast_node(el, env) for el in node.elts] | |
| if isinstance(node, ast.Tuple): | |
| return tuple(_eval_ast_node(el, env) for el in node.elts) | |
| if isinstance(node, ast.Dict): | |
| return {_eval_ast_node(k, env): _eval_ast_node(v, env) for k, v in zip(node.keys, node.values) if k is not None} | |
| if isinstance(node, ast.Subscript): | |
| return _eval_ast_node(node.value, env)[_eval_ast_node(node.slice, env)] | |
| raise ValueError(f"Unsupported AST expression node: {type(node).__name__}") | |
| def _safe_eval_expr(expr_str: str, env: Dict[str, Any]) -> Any: | |
| tree = ast.parse(expr_str.strip(), mode="eval") | |
| return _eval_ast_node(tree.body, env) | |
| def _parse_class_attributes(raw_attrs: Any) -> Tuple[List[str], Dict[str, Any]]: | |
| if isinstance(raw_attrs, list): | |
| raw_str = ", ".join(str(a) for a in raw_attrs) | |
| else: | |
| raw_str = str(raw_attrs or "name, score") | |
| names: List[str] = [] | |
| defaults: Dict[str, Any] = {} | |
| try: | |
| mod = ast.parse(f"def _cls_attrs({raw_str}): pass") | |
| fn_args = mod.body[0].args # type: ignore[attr-defined] | |
| names = [a.arg for a in fn_args.args] | |
| offset = len(names) - len(fn_args.defaults) | |
| for idx, d_node in enumerate(fn_args.defaults): | |
| try: | |
| defaults[names[offset + idx]] = ast.literal_eval(d_node) | |
| except Exception: | |
| pass | |
| except SyntaxError: | |
| for tok in raw_str.split(","): | |
| part = tok.strip() | |
| if not part: | |
| continue | |
| k, sep, v = part.partition("=") | |
| attr_name = k.strip() | |
| if attr_name: | |
| names.append(attr_name) | |
| if sep: | |
| ok, parsed = parse_safe_literal_or_json(v.strip()) | |
| defaults[attr_name] = parsed if ok else v.strip().strip("'\"") | |
| return names or ["name", "score"], defaults | |
| def _exec_func_def(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]: | |
| fname = params.get("func_name") or params.get("function_name") or "my_func" | |
| ret_expr = str(params.get("return_expr") or params.get("body") or "x * 2") | |
| raw_params = str(params.get("params_list") or params.get("params") or "x") | |
| param_names = [p.strip().split("=")[0].strip() for p in raw_params.split(",") if p.strip()] or ["x"] | |
| ast.parse(ret_expr.strip(), mode="eval") | |
| def _safe_callable(*args: Any, **kwargs: Any) -> Any: | |
| env: Dict[str, Any] = {p: 0 for p in param_names} | |
| for idx, p in enumerate(param_names): | |
| if idx < len(args): | |
| env[p] = args[idx] | |
| env.update(kwargs) | |
| try: | |
| return _safe_eval_expr(ret_expr, env) | |
| except Exception: | |
| return env.get(param_names[0], 0) | |
| return {"callable_fn": _safe_callable, "func_ref": _safe_callable, "name": fname, "out": _safe_callable} | |
| def _exec_func_call(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]: | |
| arg = inputs.get("arg") | |
| if arg is None: | |
| arg = params.get("arg_val") | |
| if arg is None: | |
| arg = params.get("default_arg") | |
| if arg is None: | |
| arg = 5 | |
| fn = inputs.get("callable_fn") or inputs.get("func_in") | |
| res = fn(arg) if callable(fn) else 10 | |
| return {"result": res, "val": res, "out": res} | |
| def _exec_oop_class_def(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]: | |
| cname = str(params.get("class_name", "Student")).strip() or "Student" | |
| attrs, attr_defaults = _parse_class_attributes(params.get("attributes", "name, score")) | |
| doc = params.get("docstring", "") | |
| raw_methods = params.get("methods", "add_bonus") | |
| method_map: Dict[str, Dict[str, Any]] = {} | |
| if isinstance(raw_methods, list): | |
| for m in raw_methods: | |
| if isinstance(m, dict) and m.get("name"): | |
| method_map[str(m["name"])] = m | |
| cls_type = type( | |
| cname, | |
| (object,), | |
| { | |
| "__doc__": doc, | |
| "_attrs": attrs, | |
| "_attr_defaults": attr_defaults, | |
| "_methods": method_map, | |
| "__init__": lambda self, **kwargs: [setattr(self, k, v) for k, v in kwargs.items()], | |
| }, | |
| ) | |
| return {"class_ref": cls_type, "class_name": cname, "out": cls_type} | |
| def _exec_oop_instance(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]: | |
| attrs = ["name", "score"] | |
| attr_defaults: Dict[str, Any] = {} | |
| cls_obj = inputs.get("class_in") | |
| if cls_obj: | |
| if getattr(cls_obj, "_attrs", None): | |
| attrs = list(cls_obj._attrs) | |
| if getattr(cls_obj, "_attr_defaults", None): | |
| attr_defaults = dict(cls_obj._attr_defaults) | |
| has_a1 = inputs.get("arg_1") is not None or "arg_1_val" in params | |
| has_a2 = inputs.get("arg_2") is not None or "arg_2_val" in params | |
| a1 = inputs.get("arg_1") if inputs.get("arg_1") is not None else params.get("arg_1_val", attr_defaults.get(attrs[0], "Alice") if attrs else "Alice") | |
| a2 = inputs.get("arg_2") if inputs.get("arg_2") is not None else params.get("arg_2_val", attr_defaults.get(attrs[1], 85) if len(attrs) > 1 else 85) | |
| args = [a1, a2] | |
| inst: Dict[str, Any] = dict(attr_defaults) | |
| for idx, attr_name in enumerate(attrs): | |
| if idx == 0 and (has_a1 or attr_name not in attr_defaults): | |
| inst[attr_name] = args[0] | |
| elif idx == 1 and (has_a2 or attr_name not in attr_defaults): | |
| inst[attr_name] = args[1] | |
| elif idx < len(args) and attr_name not in inst: | |
| inst[attr_name] = args[idx] | |
| if "name" not in inst and not attr_defaults: | |
| inst["name"] = a1 | |
| if "score" not in inst and not attr_defaults: | |
| inst["score"] = a2 | |
| return {"instance": inst, "result": inst, "val": inst, "out": inst} | |
| def _exec_oop_method_call(inputs: Dict[str, Any], params: Dict[str, Any]) -> Dict[str, Any]: | |
| raw_inst = inputs.get("instance_in") | |
| inst = dict(raw_inst) if isinstance(raw_inst, dict) else (dict(vars(raw_inst)) if hasattr(raw_inst, "__dict__") else {}) | |
| attr = params.get("attribute_to_modify", "score") | |
| op = str(params.get("operation", "increment")).lower() | |
| arg_val = inputs.get("arg") if inputs.get("arg") is not None else params.get("default_arg", 15) | |
| if op == "increment": | |
| curr = inst.get(attr, 0) | |
| try: | |
| new_val = curr + arg_val | |
| except Exception: | |
| new_val = arg_val | |
| inst[attr] = new_val | |
| res = new_val | |
| elif op in ("set", "set_attr"): | |
| inst[attr] = arg_val | |
| res = arg_val | |
| elif op == "call_method": | |
| res = inst.get(attr, arg_val) | |
| else: | |
| res = inst.get(attr) | |
| return {"instance_out": inst, "result": res, "out": res} | |
| EXECUTORS = { | |
| "function.def": _exec_func_def, | |
| "function.call": _exec_func_call, | |
| "oop.class_def": _exec_oop_class_def, | |
| "oop.instance": _exec_oop_instance, | |
| "oop.method_call": _exec_oop_method_call, | |
| } | |
| def register_oop_nodes(registry: Any) -> None: | |
| register_domain_nodes(registry, "oop", EXECUTORS) | |