Core: Shadow a @bpfglobal with a local when a write has no global statement

Assigning a global's name without declaring it `global` was a compile
error. Python makes it a local instead: the name is local for the whole
function body, the global keeps its value, and only a `global` statement
writes through to it. Do that, so the same program means the same thing
in Python and in BPF.

Python's scoping is function-wide and static, which the compiler gets
for free: allocation runs as a pre-pass over the whole body, so a name
bound anywhere is in local_sym_tab before the first statement is
lowered, and reads resolve local-first. What does not come for free is
the read above the binding, which Python answers with UnboundLocalError
rather than the global's value. There is no runtime here in which to
raise that, so the local records where its binding ends and a read above
it is rejected, with the message Python would have given. Silence there
would load an uninitialised stack slot through a name the author
expected to be the global.

`counter += 1` without `global counter` stays an error for the same
reason: it binds a local and reads it in the same statement. Only its
message changes, from a shadowing refusal to the UnboundLocalError it
actually is.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Pragyansh Chaturvedi
2026-09-17 15:12:56 +05:30
parent 526f113a5a
commit 5948971469
5 changed files with 60 additions and 37 deletions

View File

@ -56,12 +56,14 @@ def handle_assign_allocation(compilation_context, builder, stmt, 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"
# Not declared `global`, yet named like one: Python creates a local
# that shadows the global for the whole function body, and leaves the
# global untouched. Do the same.
shadows_global = var_name in compilation_context.bpf_globals
if shadows_global:
logger.info(
f"'{var_name}' is assigned without a 'global' declaration, so it "
f"is a local shadowing the @bpfglobal of the same name"
)
# Determine type and allocate based on rval
@ -86,6 +88,14 @@ def handle_assign_allocation(compilation_context, builder, stmt, local_sym_tab):
f"Unsupported assignment value type for {var_name}: {type(rval).__name__}"
)
if shadows_global and var_name in local_sym_tab:
# Where the binding ends, so that a read above it is reported the
# way Python reports it. end_lineno, not lineno, so a read on a
# continuation line of a multi-line binding counts as above it too.
local_sym_tab[var_name].shadows_global_from = (
getattr(stmt, "end_lineno", None) or target.lineno
)
def _allocate_for_call(builder, var_name, rval, local_sym_tab, compilation_context):
"""Allocate memory for variable assigned from a call."""

View File

@ -28,9 +28,12 @@ def _handle_name_expr(
):
"""Handle ast.Name expressions."""
if expr.id in local_sym_tab:
var = local_sym_tab[expr.id].var
val = builder.load(var)
return val, local_sym_tab[expr.id].ir_type
sym = local_sym_tab[expr.id]
# A local that shadows a @bpfglobal is unreadable above its binding,
# exactly as in Python; for every other local this is a no-op.
sym.check_bound_at(expr.id, expr.lineno)
val = builder.load(sym.var)
return val, sym.ir_type
elif expr.id in compilation_context.bpf_globals:
# A @bpfglobal
sym = compilation_context.bpf_globals[expr.id]

View File

@ -208,6 +208,8 @@ def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab):
# 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:
# `x += v` reads x first, so it needs x to be bound already.
local_sym_tab[name].check_bound_at(name, stmt.lineno)
slot = local_sym_tab[name].var
slot_type = local_sym_tab[name].ir_type
if slot is None:
@ -215,9 +217,16 @@ def handle_aug_assign(func, compilation_context, builder, stmt, local_sym_tab):
f"cannot assign to '{name}': it is the context parameter"
)
elif name in compilation_context.bpf_globals:
# Binding x anywhere in the body makes it local throughout, so this
# statement reads an unbound local rather than the global. Python
# raises UnboundLocalError; there is no runtime here in which to do
# that, so the program is rejected.
raise SyntaxError(
f"augmented assignment to '{name}' shadows the BPF global of "
f"the same name — add 'global {name}' to write to it"
f"local variable '{name}' referenced before assignment: "
f"'{name} += ...' binds '{name}' as a local, which shadows the "
f"@bpfglobal of the same name, and reads it in the same "
f"statement (Python raises UnboundLocalError here). Add "
f"'global {name}' to update the global."
)
else:
raise SyntaxError(f"augmented assignment to undefined variable '{name}'")

View File

@ -30,10 +30,37 @@ class LocalSymbol(Symbol):
`declared_global` marks a name bound by a `global` statement: its var is
the @bpfglobal's GlobalVariable rather than an alloca.
`shadows_global_from` is set when this local's name is also the name of a
@bpfglobal and the function did not declare it `global`: Python makes such
a name a local for the whole body, shadowing the global, and the value is
the line where its first binding ends.
"""
metadata: Any = None
declared_global: bool = False
shadows_global_from: int | None = None
def check_bound_at(self, name: str, lineno: int) -> None:
"""Raise if `name` is read at `lineno` before its first binding.
Python's scoping is function-wide and static: assigning a name anywhere
in a body makes it local everywhere in that body, so a read above the
assignment is an UnboundLocalError rather than a read of the global.
There is no runtime in which to raise that, so a program in this shape
is rejected at compile time. The check applies only to locals that
shadow a @bpfglobal, where staying silent would otherwise load an
uninitialised slot from a name the author expected to be the global.
"""
if self.shadows_global_from is None or lineno > self.shadows_global_from:
return
raise SyntaxError(
f"local variable '{name}' referenced before assignment: the "
f"assignment on line {self.shadows_global_from} makes '{name}' a "
f"local that shadows the @bpfglobal of the same name (Python "
f"raises UnboundLocalError here). Add 'global {name}' if you meant "
f"the global."
)
def __iter__(self):
# Three fields on purpose: several call sites tuple-unpack a symbol.