From f5c4dece3eea346106af58308dc69b59570d7005 Mon Sep 17 00:00:00 2001 From: Pragyansh Chaturvedi Date: Thu, 3 Sep 2026 07:39:04 +0530 Subject: [PATCH] Core: Unify the Python-operator tables in expr/operators.py Operator knowledge was spread across three files: the binary-op table (an op_map dict rebuilt inline on every _handle_binary_op_impl call, then extracted to ir_ops.apply_binop for augmented assignment), COMPARISON_OPS in type_normalization.py, and the unary/boolean operators as isinstance chains in expr_pass.py. Anyone asking "which operators does PythonBPF support" had to read all three. They now live in one module. BINOP_METHODS and COMPARISON_OPS are the tables themselves; UNARY_OPS and BOOL_OPS list the operators whose lowering is structural (convert_to_bool, short-circuit control flow) so the registry is complete even where the emission stays in expr_pass. apply_binop moves here from ir_ops, which goes back to being purely about IR operations. No behaviour change: 133 passed, 19 xfailed before and after. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01BSDVsZH5NtoASyxB8FCtGU --- .claude/skills/ir-first-feature/SKILL.md | 4 ++ pythonbpf/expr/__init__.py | 3 +- pythonbpf/expr/expr_pass.py | 8 +++- pythonbpf/expr/ir_ops.py | 28 ------------ pythonbpf/expr/operators.py | 55 ++++++++++++++++++++++++ pythonbpf/expr/type_normalization.py | 13 +----- 6 files changed, 68 insertions(+), 43 deletions(-) create mode 100644 pythonbpf/expr/operators.py diff --git a/.claude/skills/ir-first-feature/SKILL.md b/.claude/skills/ir-first-feature/SKILL.md index 7372092..2fbf4f2 100644 --- a/.claude/skills/ir-first-feature/SKILL.md +++ b/.claude/skills/ir-first-feature/SKILL.md @@ -81,6 +81,10 @@ both use `apply_binop` for the operator table and `get_operand_value` for operan and let each handler resolve its own target and emit its own store. Two handlers calling one helper is the idiom; one handler manufacturing input for another is not. +The operator tables themselves — binary operators, comparisons, and the supported +unary/boolean operators — live in exactly one place, `expr/operators.py`. A new operator +is added there first; if it is not in that file, the compiler does not support it. + ## 6. Test at the right tier - Works now → `tests/passing_tests//`. diff --git a/pythonbpf/expr/__init__.py b/pythonbpf/expr/__init__.py index 7ab5f8d..5002113 100644 --- a/pythonbpf/expr/__init__.py +++ b/pythonbpf/expr/__init__.py @@ -1,6 +1,7 @@ from .expr_pass import eval_expr, handle_expr, get_operand_value from .type_normalization import convert_to_bool, get_base_type_and_depth -from .ir_ops import deref_to_depth, access_struct_field, apply_binop +from .ir_ops import deref_to_depth, access_struct_field +from .operators import apply_binop from .call_registry import CallHandlerRegistry from .vmlinux_registry import VmlinuxHandlerRegistry diff --git a/pythonbpf/expr/expr_pass.py b/pythonbpf/expr/expr_pass.py index a4854a6..48d5abc 100644 --- a/pythonbpf/expr/expr_pass.py +++ b/pythonbpf/expr/expr_pass.py @@ -6,7 +6,8 @@ from typing import Dict from pythonbpf.type_deducer import ctypes_to_ir, is_ctypes from .call_registry import CallHandlerRegistry -from .ir_ops import deref_to_depth, access_struct_field, apply_binop +from .ir_ops import deref_to_depth, access_struct_field +from .operators import apply_binop, UNARY_OPS, BOOL_OPS from .type_normalization import ( convert_to_bool, handle_comparator, @@ -375,7 +376,7 @@ def _handle_unary_op( local_sym_tab, ): """Handle ast.UnaryOp expressions.""" - if not isinstance(expr.op, ast.Not) and not isinstance(expr.op, ast.USub): + if not isinstance(expr.op, UNARY_OPS): logger.error("Only 'not' and '-' unary operators are supported") return None @@ -518,6 +519,9 @@ def _handle_boolean_op( ): """Handle `and` and `or` boolean operations.""" + if not isinstance(expr.op, BOOL_OPS): + logger.error(f"Unsupported boolean operator: {type(expr.op).__name__}") + return None if isinstance(expr.op, ast.And): return _handle_and_op(func, builder, expr, local_sym_tab, compilation_context) elif isinstance(expr.op, ast.Or): diff --git a/pythonbpf/expr/ir_ops.py b/pythonbpf/expr/ir_ops.py index d593f90..3f10d19 100644 --- a/pythonbpf/expr/ir_ops.py +++ b/pythonbpf/expr/ir_ops.py @@ -1,37 +1,9 @@ -import ast import logging from llvmlite import ir logger = logging.getLogger(__name__) -BINOP_METHODS = { - ast.Add: "add", - ast.Sub: "sub", - ast.Mult: "mul", - ast.Div: "sdiv", - ast.Mod: "srem", - ast.LShift: "shl", - ast.RShift: "lshr", - ast.BitOr: "or_", - ast.BitXor: "xor", - ast.BitAnd: "and_", - ast.FloorDiv: "udiv", -} - - -def apply_binop(builder, op, left, right): - """Emit the LLVM instruction for a Python binary operator. - - Shared by binary-op evaluation and augmented assignment so the operator - table exists exactly once. - """ - method = BINOP_METHODS.get(type(op)) - if method is None: - raise SyntaxError("Unsupported binary operation") - return getattr(builder, method)(left, right) - - def deref_to_depth(func, builder, val, target_depth): """Dereference a pointer to a certain depth.""" diff --git a/pythonbpf/expr/operators.py b/pythonbpf/expr/operators.py new file mode 100644 index 0000000..fb4cadd --- /dev/null +++ b/pythonbpf/expr/operators.py @@ -0,0 +1,55 @@ +"""Every Python operator PythonBPF understands, and the IR it maps to. + +This is the single registry. Binary operators map to IRBuilder method names, +comparisons map to icmp predicates, and the unary/boolean operators are listed +here even though their lowering is structural (they need convert_to_bool or +short-circuit control flow, so they live in expr_pass): if an operator is not +in this file, the compiler does not support it. Add new operators here first. +""" + +import ast + +# ast.BinOp.op class -> llvmlite IRBuilder method name. +# Shared by binary-op evaluation and augmented assignment. +BINOP_METHODS = { + ast.Add: "add", + ast.Sub: "sub", + ast.Mult: "mul", + ast.Div: "sdiv", + ast.Mod: "srem", + ast.LShift: "shl", + ast.RShift: "lshr", + ast.BitOr: "or_", + ast.BitXor: "xor", + ast.BitAnd: "and_", + ast.FloorDiv: "udiv", +} + +# ast.Compare op class -> icmp predicate string. +COMPARISON_OPS = { + ast.Eq: "==", + ast.NotEq: "!=", + ast.Lt: "<", + ast.LtE: "<=", + ast.Gt: ">", + ast.GtE: ">=", + ast.Is: "==", + ast.IsNot: "!=", +} + +# Lowered structurally in expr_pass (need convert_to_bool / control flow). +UNARY_OPS = (ast.Not, ast.USub) +BOOL_OPS = (ast.And, ast.Or) + + +def apply_binop(builder, op, left, right): + """Emit the LLVM instruction for a Python binary operator.""" + method = BINOP_METHODS.get(type(op)) + if method is None: + raise SyntaxError(f"Unsupported binary operation: {type(op).__name__}") + return getattr(builder, method)(left, right) + + +def comparison_predicate(op): + """icmp predicate for a Python comparison operator, or None if unsupported.""" + return COMPARISON_OPS.get(type(op)) diff --git a/pythonbpf/expr/type_normalization.py b/pythonbpf/expr/type_normalization.py index bb5e83b..edea422 100644 --- a/pythonbpf/expr/type_normalization.py +++ b/pythonbpf/expr/type_normalization.py @@ -1,21 +1,10 @@ import logging -import ast from llvmlite import ir from .ir_ops import deref_to_depth +from .operators import COMPARISON_OPS logger = logging.getLogger(__name__) -COMPARISON_OPS = { - ast.Eq: "==", - ast.NotEq: "!=", - ast.Lt: "<", - ast.LtE: "<=", - ast.Gt: ">", - ast.GtE: ">=", - ast.Is: "==", - ast.IsNot: "!=", -} - def get_base_type_and_depth(ir_type): """Get the base type for pointer types."""