mirror of
https://github.com/varun-r-mallya/Python-BPF.git
synced 2026-12-06 01:48:35 +00:00
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:
@ -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]
|
||||
|
||||
Reference in New Issue
Block a user