Skip to content

Commit d7bfe86

Browse files
committed
Add handle_variable_assignment to assign_pass
1 parent 84ed27f commit d7bfe86

File tree

1 file changed

+54
-1
lines changed

1 file changed

+54
-1
lines changed

pythonbpf/assign_pass.py

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,57 @@
1+
import ast
2+
import logging
3+
from llvmlite import ir
4+
from pythonbpf.expr import eval_expr
5+
6+
logger = logging.getLogger(__name__)
7+
8+
19
def handle_variable_assignment(
210
func, module, builder, var_name, rval, local_sym_tab, map_sym_tab, structs_sym_tab
311
):
4-
pass
12+
"""Handle single named variable assignment."""
13+
14+
if var_name not in local_sym_tab:
15+
logger.error(f"Variable {var_name} not declared.")
16+
return False
17+
18+
var_ptr = local_sym_tab[var_name].var
19+
var_type = local_sym_tab[var_name].ir_type
20+
21+
# NOTE: Special case for struct initialization
22+
if isinstance(rval, ast.Call) and isinstance(rval.func, ast.Name):
23+
struct_name = rval.func.id
24+
if struct_name in structs_sym_tab and len(rval.args) == 0:
25+
struct_info = structs_sym_tab[struct_name]
26+
ir_struct = struct_info.ir_type
27+
28+
builder.store(ir.Constant(ir_struct, None), var_ptr)
29+
logger.info(f"Initialized struct {struct_name} for variable {var_name}")
30+
return True
31+
32+
val_result = eval_expr(
33+
func, module, builder, rval, local_sym_tab, map_sym_tab, structs_sym_tab
34+
)
35+
if val_result is None:
36+
logger.error(f"Failed to evaluate value for {var_name}")
37+
return False
38+
39+
val, val_type = val_result
40+
if val_type != var_type:
41+
if isinstance(val_type, ir.IntType) and isinstance(var_type, ir.IntType):
42+
# Allow implicit int widening
43+
if val_type.width < var_type.width:
44+
val = builder.sext(val, var_type)
45+
logger.info(f"Implicitly widened int for variable {var_name}")
46+
elif val_type.width > var_type.width:
47+
val = builder.trunc(val, var_type)
48+
logger.info(f"Implicitly truncated int for variable {var_name}")
49+
else:
50+
logger.error(
51+
f"Type mismatch for variable {var_name}: {val_type} vs {var_type}"
52+
)
53+
return False
54+
55+
builder.store(val, var_ptr)
56+
logger.info(f"Assigned value to variable {var_name}")
57+
return True

0 commit comments

Comments
 (0)