mirror of
https://github.com/varun-r-mallya/Python-BPF.git
synced 2026-12-06 01:48:35 +00:00
Core: Bind declared globals in local_sym_tab instead of a per-function set
A 'global x' statement is a fact about one function's scope, but it was
tracked as current_func_globals on the compilation-wide context -- per-function
state living at the wrong level, which had to be set before each body and
reset after, and which every read and write site then had to consult in a
specific order relative to local_sym_tab (the source of the parameter
collision fixed in f4ec12d).
The declaration now does what it means: it binds the name in local_sym_tab to
the @bpfglobal's storage, as a LocalSymbol whose var is the GlobalVariable and
whose declared_global flag records why. A GlobalVariable is a pointer to
storage exactly as an alloca is, so every existing path that loads from or
stores through a symbol's var works unchanged. That deletes the dedicated
global-store branch in handle_variable_assignment, the global branch in
handle_aug_assign, the allocation-pass skip, and the reset -- one table, one
lookup, no order to get wrong. Reads of an undeclared global (legal in Python)
still fall back to bpf_globals after local_sym_tab.
Python's rules fall out naturally: a parameter is already in the table when
the declarations are processed, so 'global ctx' on a parameter is detected by
the same membership check. LocalSymbol.__iter__ deliberately still yields
three fields, since several sites tuple-unpack a symbol.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BSDVsZH5NtoASyxB8FCtGU
This commit is contained in:
@ -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(
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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()
|
||||
|
||||
@ -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."""
|
||||
|
||||
@ -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
|
||||
|
||||
Reference in New Issue
Block a user