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

@ -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}'")