diff --git a/pythonbpf/allocation_pass.py b/pythonbpf/allocation_pass.py index 9cae135..567e945 100644 --- a/pythonbpf/allocation_pass.py +++ b/pythonbpf/allocation_pass.py @@ -50,24 +50,20 @@ def handle_assign_allocation(compilation_context, builder, stmt, local_sym_tab): var_name = target.id - # Writes to @bpfglobal variables use the global symbol, not a stack - # slot. Requires Python's own `global` declaration; without it an - # assignment to a global's name would silently create a local that - # shadows it, which is exactly the bug class we refuse to compile. - if var_name in compilation_context.current_func_globals: - logger.debug(f"'{var_name}' is a declared global, no allocation needed") + # Already bound in this scope: a parameter, an earlier assignment, or a + # `global` declaration (whose slot is the GlobalVariable). No slot needed. + if var_name in local_sym_tab: + logger.debug(f"'{var_name}' already bound, no allocation needed") continue + + # Not declared `global`, yet named like one: in real Python this would + # create a shadowing local. Refuse rather than guess which was meant. if var_name in compilation_context.bpf_globals: raise SyntaxError( f"assignment to '{var_name}' shadows the BPF global of the same " f"name — add 'global {var_name}' to write to it" ) - # Skip if already allocated - if var_name in local_sym_tab: - logger.debug(f"Variable {var_name} already allocated, skipping") - continue - # Determine type and allocate based on rval if isinstance(rval, ast.Call): _allocate_for_call( diff --git a/pythonbpf/assign_pass.py b/pythonbpf/assign_pass.py index d00f433..5d931f7 100644 --- a/pythonbpf/assign_pass.py +++ b/pythonbpf/assign_pass.py @@ -113,33 +113,6 @@ def handle_variable_assignment( ): """Handle single named variable assignment.""" - # A name declared with `global` writes the @bpfglobal symbol directly: - # the plain `store i64 %v, ptr @counter` form of the C reference. - if ( - var_name not in local_sym_tab - and var_name in compilation_context.current_func_globals - ): - sym = compilation_context.bpf_globals[var_name] - val_result = eval_expr(func, compilation_context, builder, rval, local_sym_tab) - if val_result is None: - logger.error(f"Failed to evaluate value for global {var_name}") - return False - val, val_type = val_result - if isinstance(val_type, ir.IntType) and isinstance(sym.ir_type, ir.IntType): - # Same implicit widening/truncation rules as local assignments - if val_type.width < sym.ir_type.width: - val = builder.sext(val, sym.ir_type) - elif val_type.width > sym.ir_type.width: - val = builder.trunc(val, sym.ir_type) - elif val_type != sym.ir_type: - logger.error( - f"Type mismatch for global {var_name}: {val_type} vs {sym.ir_type}" - ) - return False - builder.store(val, sym.var) - logger.info(f"Stored to BPF global {var_name}") - return True - if var_name not in local_sym_tab: logger.error(f"Variable {var_name} not declared.") return False diff --git a/pythonbpf/context.py b/pythonbpf/context.py index 8ebd21b..21a252b 100644 --- a/pythonbpf/context.py +++ b/pythonbpf/context.py @@ -69,10 +69,6 @@ class CompilationContext: self.map_sym_tab: dict[str, "MapSymbol"] = {} self.bpf_globals: dict[str, "BpfGlobalSymbol"] = {} - # Names a `global` statement declared writable in the function whose - # body is currently being emitted; managed by process_func_body. - self.current_func_globals: set[str] = set() - # Helper management self.scratch_pool = ScratchPoolManager() @@ -86,4 +82,3 @@ class CompilationContext: """Reset state between functions if necessary, though new context per compile is preferred.""" self.scratch_pool.reset() self.current_func = None - self.current_func_globals = set() diff --git a/pythonbpf/functions/functions_pass.py b/pythonbpf/functions/functions_pass.py index 3519eb4..1982957 100644 --- a/pythonbpf/functions/functions_pass.py +++ b/pythonbpf/functions/functions_pass.py @@ -205,10 +205,8 @@ def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab): """ if isinstance(stmt.target, ast.Name): name = stmt.target.id - # Same resolution order as reads: local, then declared global. The two - # cannot both hold a name (a parameter may not be declared global, and - # an undeclared write to a global's name is refused), so this order is - # about giving the same answer as _handle_name_expr, not precedence. + # One table: a declared global is a local_sym_tab entry whose slot is + # the GlobalVariable, so it needs no separate branch. if name in local_sym_tab: slot = local_sym_tab[name].var slot_type = local_sym_tab[name].ir_type @@ -216,9 +214,6 @@ def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab): raise SyntaxError( f"cannot assign to '{name}': it is the context parameter" ) - elif name in compilation_context.current_func_globals: - sym = compilation_context.bpf_globals[name] - slot, slot_type = sym.var, sym.ir_type elif name in compilation_context.bpf_globals: raise SyntaxError( f"augmented assignment to '{name}' shadows the BPF global of " @@ -414,28 +409,6 @@ def process_func_body( local_sym_tab = {} - # Collect `global x` declarations. Python scoping rules apply: a declared - # name may be written anywhere in this function and always means the - # @bpfglobal, never a local. Undeclared writes to a global name are - # rejected in the allocation pass rather than silently shadowing. - declared_globals: set[str] = set() - param_names = {arg.arg for arg in func_node.args.args} - for node in ast.walk(func_node): - if isinstance(node, ast.Global): - for gname in node.names: - if gname in param_names: - # Python's own rule and wording. Without it the read path - # (local first) and the write path would resolve the same - # name to different storage. - raise SyntaxError(f"name '{gname}' is parameter and global") - if gname not in compilation_context.bpf_globals: - raise SyntaxError( - f"'global {gname}' in '{func_node.name}': no @bpfglobal " - f"named '{gname}' is declared" - ) - declared_globals.add(gname) - compilation_context.current_func_globals = declared_globals - # Add the context parameter (first function argument) to the local symbol table if func_node.args.args and len(func_node.args.args) > 0: context_arg = func_node.args.args[0] @@ -474,6 +447,26 @@ def process_func_body( local_sym_tab[context_name] = context_type logger.info(f"Added argument '{context_name}' to local symbol table") + # A `global x` statement binds x in this function's scope to the + # @bpfglobal's storage. It goes into local_sym_tab like any other name, + # flagged, so every read and write resolves it through the one table with + # no separate lookup order to get wrong. Python's rules apply: a parameter + # cannot be declared global, and the name must be a @bpfglobal. + for node in ast.walk(func_node): + if isinstance(node, ast.Global): + for gname in node.names: + if gname in local_sym_tab: + raise SyntaxError(f"name '{gname}' is parameter and global") + if gname not in compilation_context.bpf_globals: + raise SyntaxError( + f"'global {gname}' in '{func_node.name}': no @bpfglobal " + f"named '{gname}' is declared" + ) + sym = compilation_context.bpf_globals[gname] + local_sym_tab[gname] = LocalSymbol( + sym.var, sym.ir_type, None, declared_global=True + ) + # pre-allocate dynamic variables local_sym_tab = allocate_mem( compilation_context, @@ -500,8 +493,6 @@ def process_func_body( if not did_return: builder.ret(ir.Constant(ir.IntType(64), 0)) - compilation_context.current_func_globals = set() - def process_bpf_chunk(func_node, compilation_context, return_type): """Process a single BPF chunk (function) and emit corresponding LLVM IR.""" diff --git a/pythonbpf/local_symbol.py b/pythonbpf/local_symbol.py index ccef9d2..0abcec9 100644 --- a/pythonbpf/local_symbol.py +++ b/pythonbpf/local_symbol.py @@ -5,11 +5,20 @@ from typing import Any @dataclass class LocalSymbol: - var: ir.AllocaInstr + """One name visible in a BPF function's scope. + + `var` is the storage the name resolves to: an alloca for locals, the + GlobalVariable for a name brought in by a `global` statement, or None for + the context parameter (which arrives as func.args[0], not a slot). + """ + + var: ir.AllocaInstr | ir.GlobalVariable | None ir_type: ir.Type metadata: Any = None + declared_global: bool = False def __iter__(self): + # Three fields on purpose: several call sites tuple-unpack a symbol. yield self.var yield self.ir_type yield self.metadata