From 98263b66f270260899f1c5bb26b853975bd7c885 Mon Sep 17 00:00:00 2001 From: Dave Lucia Date: Wed, 6 May 2026 15:46:12 -0700 Subject: [PATCH 1/4] chore(A16): start plan --- .agents/plans/A16-env-semantics.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.agents/plans/A16-env-semantics.md b/.agents/plans/A16-env-semantics.md index 1d444b2d..066a4145 100644 --- a/.agents/plans/A16-env-semantics.md +++ b/.agents/plans/A16-env-semantics.md @@ -5,7 +5,7 @@ issue: 186 pr: null branch: feat/env-semantics base: main -status: ready +status: in-progress direction: A unlocks: - events.lua From 441c6d41dafe76441d873624a7351076f5591fa4 Mon Sep 17 00:00:00 2001 From: Dave Lucia Date: Wed, 6 May 2026 16:19:42 -0700 Subject: [PATCH 2/4] feat(vm): implement Lua 5.3 _ENV semantics for global access Free names compile to _ENV. field access instead of bypassing table semantics via dedicated :get_global / :set_global opcodes. The chunk reserves register 0 for _ENV (initialised to _G via a new :load_env opcode); user-level _ENV reassignment redirects subsequent free-name reads and writes through the new environment table and its __index / __newindex metamethods. Globals storage moves from a flat state.globals map into the _G table's data field; State.get_global/2 and State.set_global/3 read and write _G directly. The host API (Lua.set! / Lua.get!) is unchanged. The _G metatable proxy that routed reads/writes back to state.globals is removed since _G itself is the storage. Closes #186 --- lib/lua.ex | 6 +- lib/lua/compiler/codegen.ex | 197 ++++++++++++++++++++----- lib/lua/compiler/instruction.ex | 7 + lib/lua/compiler/scope.ex | 147 +++++++++++++++--- lib/lua/vm/executor.ex | 14 +- lib/lua/vm/state.ex | 56 ++++++- lib/lua/vm/stdlib.ex | 74 +++------- test/lua/compiler/integration_test.exs | 41 ++--- test/lua/vm/env_semantics_test.exs | 33 ++--- 9 files changed, 408 insertions(+), 167 deletions(-) diff --git a/lib/lua.ex b/lib/lua.ex index 74ae0822..d5bc657e 100644 --- a/lib/lua.ex +++ b/lib/lua.ex @@ -281,7 +281,7 @@ defmodule Lua do defp do_set_nested(state, [first | rest], value) do # Get or allocate the table at the first key - case Map.get(state.globals, first) do + case State.get_global(state, first) do {:tref, _} = tref -> state = set_in_table(state, tref, rest, value) state @@ -363,11 +363,11 @@ defmodule Lua do end defp do_get_nested(state, [key]) do - Map.get(state.globals, key) + State.get_global(state, key) end defp do_get_nested(state, [first | rest]) do - case Map.get(state.globals, first) do + case State.get_global(state, first) do {:tref, _} = tref -> get_in_table(state, tref, rest) diff --git a/lib/lua/compiler/codegen.ex b/lib/lua/compiler/codegen.ex index c9544027..270a6a32 100644 --- a/lib/lua/compiler/codegen.ex +++ b/lib/lua/compiler/codegen.ex @@ -23,8 +23,18 @@ defmodule Lua.Compiler.Codegen do func_scope = scope_state.functions[:chunk] start_reg = func_scope.max_register - {instructions, ctx} = - gen_block(block, %{next_reg: start_reg, source: source, scope: scope_state, prototypes: []}) + {body_instructions, ctx} = + gen_block(block, %{ + next_reg: start_reg, + source: source, + scope: scope_state, + prototypes: [], + current_function: :chunk + }) + + # Plan A16: chunk-level `_ENV` is bound at register 0. Emit a `load_env` + # at the very start so it holds `_G` before user code runs. + instructions = [Instruction.load_env(0) | body_instructions] # Compute line range from block statements lines = compute_line_range(block) @@ -271,6 +281,13 @@ defmodule Lua.Compiler.Codegen do call_instr end + # Reserve register slots for all of the call's expanded + # results so subsequent temp-register allocations (e.g. + # `_ENV` loads when assigning to a free name) don't clobber + # them. The call writes results into [call_reg, call_reg + + # needed - 1]. + ctx = %{ctx | next_reg: max(ctx.next_reg, call_reg + max(needed, 1))} + {call_instr, call_reg, ctx} :vararg -> @@ -621,25 +638,26 @@ defmodule Lua.Compiler.Codegen do case name do [_single_name] -> # Per Lua 5.3: `function name(...) end` is sugar for `name = function(...) end`. - # Use the var_map entry resolved by scope analysis (local/upvalue/global). - store_instructions = + # Use the var_map entry resolved by scope analysis. + {store_instructions, ctx} = case Map.get(ctx.scope.var_map, {:func_decl_target, decl}) do {:register, local_reg} -> - if local_reg == closure_reg, do: [], else: [Instruction.move(local_reg, closure_reg)] + instrs = if local_reg == closure_reg, do: [], else: [Instruction.move(local_reg, closure_reg)] + {instrs, ctx} {:captured_local, local_reg} -> - [Instruction.set_open_upvalue(local_reg, closure_reg)] + {[Instruction.set_open_upvalue(local_reg, closure_reg)], ctx} {:upvalue, index} -> - [Instruction.set_upvalue(index, closure_reg)] + {[Instruction.set_upvalue(index, closure_reg)], ctx} - {:global, gname} -> - [Instruction.set_global(gname, closure_reg)] + {:env_field, env_ref, fname} -> + gen_env_field_set(env_ref, fname, closure_reg, ctx) nil -> - # Fallback: treat as global (shouldn't happen after scope analysis) - [single] = name - [Instruction.set_global(single, closure_reg)] + # Should never happen after scope analysis (single-name FuncDecl + # always populates {:func_decl_target, decl}). + raise "codegen: missing var_map entry for FuncDecl target #{inspect(name)}" end {closure_instructions ++ store_instructions, ctx} @@ -721,25 +739,39 @@ defmodule Lua.Compiler.Codegen do # Helpers for assignment target code generation defp gen_assign_target(%Expr.Var{} = target_var, value_reg, ctx) do - store_instructions = - case Map.get(ctx.scope.var_map, target_var) do - {:register, local_reg} -> - if local_reg == value_reg, do: [], else: [Instruction.move(local_reg, value_reg)] - - {:captured_local, local_reg} -> - [Instruction.set_open_upvalue(local_reg, value_reg)] + case Map.get(ctx.scope.var_map, target_var) do + {:register, local_reg} -> + instrs = if local_reg == value_reg, do: [], else: [Instruction.move(local_reg, value_reg)] + {instrs, ctx} + + {:captured_local, local_reg} -> + # Update both the register and any existing cell. The register is + # the source of truth before a closure has captured the local + # (set_open_upvalue is a no-op until a cell exists, per + # executor.ex). Emitting the move first ensures pre-capture writes + # are observed by the cell once a closure later captures this slot. + instrs = + if local_reg == value_reg do + [Instruction.set_open_upvalue(local_reg, value_reg)] + else + [ + Instruction.move(local_reg, value_reg), + Instruction.set_open_upvalue(local_reg, value_reg) + ] + end - {:upvalue, index} -> - [Instruction.set_upvalue(index, value_reg)] + {instrs, ctx} - {:global, name} -> - [Instruction.set_global(name, value_reg)] + {:upvalue, index} -> + {[Instruction.set_upvalue(index, value_reg)], ctx} - nil -> - [Instruction.set_global(target_var.name, value_reg)] - end + {:env_field, env_ref, name} -> + gen_env_field_set(env_ref, name, value_reg, ctx) - {store_instructions, ctx} + nil -> + # Should never happen after scope analysis. + raise "codegen: missing var_map entry for assign target #{inspect(target_var.name)}" + end end defp gen_assign_target(%Expr.Property{table: table_expr, field: field}, value_reg, ctx) do @@ -940,11 +972,9 @@ defmodule Lua.Compiler.Codegen do ctx = %{ctx | next_reg: reg + 1} {[Instruction.get_upvalue(reg, index)], reg, ctx} - {:global, name} -> - # Global variable - need to load it - reg = ctx.next_reg - ctx = %{ctx | next_reg: reg + 1} - {[Instruction.get_global(reg, name)], reg, ctx} + {:env_field, env_ref, name} -> + # Free name -> _ENV.name (Plan A16: Lua 5.3 _ENV semantics). + gen_env_field_get(env_ref, name, ctx) nil -> # Variable not in scope (shouldn't happen after scope resolution) @@ -1301,13 +1331,23 @@ defmodule Lua.Compiler.Codegen do # Look up a variable by name (not by AST node identity). # Used when we need to resolve a variable name that doesn't have a corresponding # scope-resolved Expr.Var node (e.g., FuncDecl table chain names). + # + # Note: this path operates on the chunk-level locals map. It only matches + # chunk-level locals (and chunk-level `_ENV` at register 0). This means for + # `function foo.bar()` where `foo` is an upvalue of an outer function, this + # path will fall through to `_ENV.foo`, which is the correct Lua 5.3 + # behaviour for a free name in a chunk. Pre-existing limitation: if `foo` + # is captured from a deeper enclosing scope, this won't walk the upvalue + # chain — `_ENV.foo` is used instead. Acceptable: all FuncDecl table-chain + # head names that aren't chunk-level locals are conventionally globals. defp gen_var_by_name(name, ctx) do case Map.get(ctx.scope.locals, name) do nil -> - # Not a local — treat as global - reg = ctx.next_reg - ctx = %{ctx | next_reg: reg + 1} - {[Instruction.get_global(reg, name)], reg, ctx} + # Not a chunk-level local — treat as `_ENV.name`. Resolve `_ENV` + # itself via the same chain as scope.ex so we use the right cell + # (chunk register 0, captured local, or upvalue). + env_ref = compute_env_var_ref_at_codegen(ctx) + gen_env_field_get(env_ref, name, ctx) local_reg -> if MapSet.member?(ctx.scope.captured_locals, name) do @@ -1321,6 +1361,88 @@ defmodule Lua.Compiler.Codegen do end end + # Resolve `_ENV` as a `var_ref` at codegen time. This is used by + # `gen_var_by_name`, which doesn't go through the AST tag path; it + # operates on the *current function's* scope (`ctx.scope.locals`). + # + # `gen_var_by_name` is only invoked from FuncDecl statement codegen at + # the top level of a chunk (or nested fn body), so the lookup happens + # against the function whose locals are reflected in `ctx.scope`. The + # chunk's `_ENV` is at register 0; nested functions hold `_ENV` as an + # upvalue. + defp compute_env_var_ref_at_codegen(ctx) do + case Map.get(ctx.scope.locals, "_ENV") do + nil -> + # No local _ENV — must be an upvalue. Find its index in the current + # function's upvalue_descriptors. Note: the scope resolver should + # have ensured this upvalue exists (any FuncDecl in a non-chunk + # function will have triggered ensure_upvalue when free names were + # resolved). If somehow the function has no free names elsewhere, + # we still need _ENV — fall back to looking at the current + # function's upvalues for a `_ENV` entry. + case current_function_env_upvalue_index(ctx) do + {:ok, index} -> {:upvalue, index} + :not_found -> raise "codegen: _ENV unreachable in gen_var_by_name (Plan A16)" + end + + reg -> + if MapSet.member?(ctx.scope.captured_locals, "_ENV") do + {:captured_local, reg} + else + {:register, reg} + end + end + end + + defp current_function_env_upvalue_index(ctx) do + # The codegen ctx doesn't expose the current function key directly, but + # we can look it up via ctx.scope.functions for the function we're + # currently generating. The chunk's locals map should always have + # `_ENV`, so this path is only hit for nested functions, where we'd + # have a `_ENV` upvalue allocated by scope resolution. If not, that's + # a scope-resolution bug. + func_scope = ctx.scope.functions[ctx.current_function] + + case Enum.find_index(func_scope.upvalue_descriptors, fn + {:parent_local, _, n} -> n == "_ENV" + {:parent_upvalue, _, n} -> n == "_ENV" + end) do + nil -> :not_found + idx -> {:ok, idx} + end + end + + # Emit a `_ENV` lookup followed by a `get_field` for `name`. + defp gen_env_field_get(env_ref, name, ctx) do + {load_instrs, env_reg, ctx} = gen_load_env(env_ref, ctx) + dest = ctx.next_reg + ctx = %{ctx | next_reg: dest + 1} + {load_instrs ++ [Instruction.get_field(dest, env_reg, name)], dest, ctx} + end + + # Emit a `_ENV` lookup followed by a `set_field` writing `value_reg` into + # `_ENV[name]`. + defp gen_env_field_set(env_ref, name, value_reg, ctx) do + {load_instrs, env_reg, ctx} = gen_load_env(env_ref, ctx) + {load_instrs ++ [Instruction.set_field(env_reg, name, value_reg)], ctx} + end + + # Load `_ENV` into a register based on its `var_ref`. Returns the + # instructions that produce `_ENV` and the register holding it. + defp gen_load_env({:register, reg}, ctx), do: {[], reg, ctx} + + defp gen_load_env({:captured_local, reg}, ctx) do + dest = ctx.next_reg + ctx = %{ctx | next_reg: dest + 1} + {[Instruction.get_open_upvalue(dest, reg)], dest, ctx} + end + + defp gen_load_env({:upvalue, index}, ctx) do + dest = ctx.next_reg + ctx = %{ctx | next_reg: dest + 1} + {[Instruction.get_upvalue(dest, index)], dest, ctx} + end + # Shared helper: generates a closure from a function node (Expr.Function, Statement.FuncDecl, etc.) # Returns {instructions, dest_reg, ctx} like gen_expr. defp gen_closure_from_node(node, ctx) do @@ -1335,7 +1457,8 @@ defmodule Lua.Compiler.Codegen do next_reg: max(func_scope.param_count, func_scope.max_register), source: ctx.source, scope: func_locals_scope, - prototypes: [] + prototypes: [], + current_function: func_key }) # Compute line range from function body diff --git a/lib/lua/compiler/instruction.ex b/lib/lua/compiler/instruction.ex index c2bbe35d..d4398f30 100644 --- a/lib/lua/compiler/instruction.ex +++ b/lib/lua/compiler/instruction.ex @@ -20,6 +20,13 @@ defmodule Lua.Compiler.Instruction do def get_global(dest, name), do: {:get_global, dest, name} def set_global(name, source), do: {:set_global, name, source} + # Loads the runtime `_G` table reference into `dest`. Emitted at the start + # of every chunk to bind `_ENV` as a chunk-level local. Plan A16 (Lua 5.3 + # `_ENV` semantics): free names compile to `_ENV.name` field access; the + # chunk's `_ENV` is initialised here and inherited by nested functions + # via the standard upvalue chain. + def load_env(dest), do: {:load_env, dest} + # Table operations def new_table(dest, array_hint \\ 0, hash_hint \\ 0), do: {:new_table, dest, array_hint, hash_hint} diff --git a/lib/lua/compiler/scope.ex b/lib/lua/compiler/scope.ex index 409f2ab9..f43e8a1e 100644 --- a/lib/lua/compiler/scope.ex +++ b/lib/lua/compiler/scope.ex @@ -14,7 +14,18 @@ defmodule Lua.Compiler.Scope do {:register, index :: non_neg_integer()} | {:captured_local, index :: non_neg_integer()} | {:upvalue, index :: non_neg_integer()} - | {:global, name :: binary()} + | {:env_field, env_var_ref :: env_var_ref(), name :: binary()} + + @typedoc """ + How `_ENV` itself is resolved at the use site of a free name. One of + `{:register, n}` (chunk-level), `{:captured_local, n}` (chunk-level + `_ENV` captured by a nested function), or `{:upvalue, n}` (most common + for nested functions). + """ + @type env_var_ref :: + {:register, index :: non_neg_integer()} + | {:captured_local, index :: non_neg_integer()} + | {:upvalue, index :: non_neg_integer()} defmodule FunctionScope do @moduledoc false @@ -58,8 +69,13 @@ defmodule Lua.Compiler.Scope do Resolves variable scopes in the AST. Returns a state containing: - - var_map: maps each Var node to {:register, n} | {:upvalue, n} | {:global, name} + - var_map: maps each Var node to {:register, n} | {:upvalue, n} | {:env_field, env_var_ref, name} - functions: maps each function node to its FunctionScope + + Plan A16 (Lua 5.3 `_ENV` semantics): the chunk reserves register 0 for + an implicit `_ENV` local, holding `_G`. Free names compile to + `_ENV.name` field access; nested functions capture `_ENV` via the + standard upvalue chain. """ @spec resolve(Chunk.t(), keyword()) :: {:ok, State.t()} | {:error, term()} def resolve(%Chunk{block: block}, _opts \\ []) do @@ -69,6 +85,28 @@ defmodule Lua.Compiler.Scope do func_scope = %FunctionScope{is_vararg: true} state = %{state | current_function: :chunk, functions: %{chunk: func_scope}} + # Bind `_ENV` as a chunk-level local at register 0. Codegen emits a + # `load_env` instruction at the start of the chunk to populate this + # register; user code (and any free-name reference resolved through + # `_ENV`) sees it as a normal local. User-level `_ENV = ...` rebinds + # this register and redirects subsequent free-name access. + # + # We mark `_ENV` as captured up-front so all chunk-level `_ENV` access + # routes through the open-upvalue cell. This keeps reads/writes + # consistent regardless of whether a nested function actually captures + # `_ENV` later in the chunk: the executor's open-upvalue mechanism + # falls back to direct register access until a cell is allocated. + state = %{ + state + | locals: %{"_ENV" => 0}, + next_register: 1, + captured_locals: MapSet.put(state.captured_locals, "_ENV") + } + + # Track max_register accordingly + func_scope = %{func_scope | max_register: 1} + state = %{state | functions: Map.put(state.functions, :chunk, func_scope)} + # Resolve the chunk body state = resolve_block(block, state) @@ -221,26 +259,32 @@ defmodule Lua.Compiler.Scope do # function-scope reference under the bare `decl` key). target_key = {:func_decl_target, decl} - state = - case Map.get(state.locals, single_name) do - nil -> - case find_upvalue(single_name, state.parent_scopes, state) do - {:ok, upvalue_index, state} -> - %{state | var_map: Map.put(state.var_map, target_key, {:upvalue, upvalue_index})} - - :not_found -> - %{state | var_map: Map.put(state.var_map, target_key, {:global, single_name})} - end - - reg -> - if MapSet.member?(state.captured_locals, single_name) do - %{state | var_map: Map.put(state.var_map, target_key, {:captured_local, reg})} - else - %{state | var_map: Map.put(state.var_map, target_key, {:register, reg})} - end - end + # Process the function body FIRST. The body may capture this scope's + # locals (including `_ENV`); processing it before tagging the assignment + # target ensures `state.captured_locals` is fully populated when we + # decide between `{:register, _}` vs `{:captured_local, _}` for the + # target (and for `_ENV` when the target is a free name). + state = resolve_function_scope(decl, all_params, body, state) - resolve_function_scope(decl, all_params, body, state) + case Map.get(state.locals, single_name) do + nil -> + case find_upvalue(single_name, state.parent_scopes, state) do + {:ok, upvalue_index, state} -> + %{state | var_map: Map.put(state.var_map, target_key, {:upvalue, upvalue_index})} + + :not_found -> + # Free name: compile as `_ENV.name = ...` + {env_ref, state} = resolve_env_ref(state) + %{state | var_map: Map.put(state.var_map, target_key, {:env_field, env_ref, single_name})} + end + + reg -> + if MapSet.member?(state.captured_locals, single_name) do + %{state | var_map: Map.put(state.var_map, target_key, {:captured_local, reg})} + else + %{state | var_map: Map.put(state.var_map, target_key, {:register, reg})} + end + end end defp resolve_statement(%Statement.FuncDecl{params: params, body: body, is_method: is_method} = decl, state) do @@ -318,7 +362,7 @@ defmodule Lua.Compiler.Scope do defp resolve_expr(%Expr.Nil{}, state), do: state defp resolve_expr(%Expr.Var{name: name} = var, state) do - # Check if this variable is a local, upvalue, or global + # Check if this variable is a local, upvalue, or free name (=> _ENV.name) case Map.get(state.locals, name) do nil -> # Not a local — check parent scopes for upvalue @@ -327,7 +371,9 @@ defmodule Lua.Compiler.Scope do %{state | var_map: Map.put(state.var_map, var, {:upvalue, upvalue_index})} :not_found -> - %{state | var_map: Map.put(state.var_map, var, {:global, name})} + # Free name: compile as `_ENV.name` + {env_ref, state} = resolve_env_ref(state) + %{state | var_map: Map.put(state.var_map, var, {:env_field, env_ref, name})} end reg -> @@ -395,6 +441,41 @@ defmodule Lua.Compiler.Scope do ensure_upvalue(name, state.current_function, parent_scopes, state) end + # Resolve `_ENV` as a `var_ref` (`{:register, n}` | `{:captured_local, n}` | + # `{:upvalue, n}`) usable for env-field access at the current scope. + # + # `_ENV` is bound as register 0 of the chunk and inherits to nested + # functions via the standard upvalue chain. This helper handles all three + # cases: chunk-level register, chunk-level captured-by-nested-fn, and + # nested-function upvalue. + defp resolve_env_ref(state) do + case Map.get(state.locals, "_ENV") do + nil -> + # Not a local in the current function — must be reachable as an + # upvalue (the chunk binds `_ENV` as a local at register 0; nested + # functions inherit through `find_upvalue`). + case find_upvalue("_ENV", state.parent_scopes, state) do + {:ok, upvalue_index, state} -> + {{:upvalue, upvalue_index}, state} + + :not_found -> + # Should never happen: the chunk always defines `_ENV`. + raise "Internal error: _ENV not found in scope chain (Plan A16)" + end + + reg -> + # Local `_ENV` (chunk register 0, or `local _ENV = ...` in an inner + # function). If a nested closure has captured this register, the + # current function reads it through the open-upvalue cell so writes + # remain visible. + if MapSet.member?(state.captured_locals, "_ENV") do + {{:captured_local, reg}, state} + else + {{:register, reg}, state} + end + end + end + # ensure_upvalue(name, for_function, parent_scopes, state) # Ensures that for_function has an upvalue for the variable `name`. # Walks up parent_scopes to find the variable, creating upvalue descriptors @@ -517,6 +598,26 @@ defmodule Lua.Compiler.Scope do state = %{state | functions: Map.put(state.functions, func_key, func_scope)} + # Plan A16: every nested function inherits `_ENV` as an upvalue. We + # eagerly resolve `_ENV` before the body is processed so codegen paths + # that need it (notably `gen_var_by_name` for FuncDecl table-chain + # heads) can rely on it being present, and so the upvalue index is + # known up-front. If the function shadows `_ENV` with a parameter or + # later `local _ENV = ...`, those local bindings still take precedence + # for free-name resolution, which is the correct Lua 5.3 behaviour. + state = + if Map.has_key?(state.locals, "_ENV") do + # `_ENV` is a parameter — no upvalue allocation needed at this entry + # point. Inner local rebinds will be handled by normal scope rules. + state + else + case find_upvalue("_ENV", state.parent_scopes, state) do + {:ok, _index, state} -> state + # Should not happen: chunk always defines `_ENV` as a local. + :not_found -> state + end + end + # Resolve the function body state = resolve_block(body, state) diff --git a/lib/lua/vm/executor.ex b/lib/lua/vm/executor.ex index c3b79d8a..8f45826a 100644 --- a/lib/lua/vm/executor.ex +++ b/lib/lua/vm/executor.ex @@ -264,7 +264,7 @@ defmodule Lua.VM.Executor do # ── get_global ───────────────────────────────────────────────────────────── defp do_execute([{:get_global, dest, name} | rest], regs, upvalues, proto, state, cont, frames, line) do - value = Map.get(state.globals, name, nil) + value = State.get_global(state, name) regs = put_elem(regs, dest, value) do_execute(rest, regs, upvalues, proto, state, cont, frames, line) end @@ -273,7 +273,17 @@ defmodule Lua.VM.Executor do defp do_execute([{:set_global, name, source} | rest], regs, upvalues, proto, state, cont, frames, line) do value = elem(regs, source) - state = %{state | globals: Map.put(state.globals, name, value)} + state = State.set_global(state, name, value) + do_execute(rest, regs, upvalues, proto, state, cont, frames, line) + end + + # ── load_env ─────────────────────────────────────────────────────────────── + # Loads the runtime `_G` table reference into `dest`. Plan A16 emits this + # at the start of every chunk so `_ENV` (a chunk-level local at register 0) + # is initialised before user code runs. + + defp do_execute([{:load_env, dest} | rest], regs, upvalues, proto, state, cont, frames, line) do + regs = put_elem(regs, dest, State.g_ref(state)) do_execute(rest, regs, upvalues, proto, state, cont, frames, line) end diff --git a/lib/lua/vm/state.ex b/lib/lua/vm/state.ex index 396eefba..72174177 100644 --- a/lib/lua/vm/state.ex +++ b/lib/lua/vm/state.ex @@ -5,8 +5,7 @@ defmodule Lua.VM.State do alias Lua.VM.Table - defstruct globals: %{}, - call_stack: [], + defstruct call_stack: [], metatables: %{}, upvalue_cells: %{}, open_upvalues: %{}, @@ -15,10 +14,14 @@ defmodule Lua.VM.State do userdata: %{}, userdata_next_id: 0, private: %{}, - multi_return_count: 0 + multi_return_count: 0, + # The `_G` table reference. Globals storage lives in this table's + # `data` map. Allocated by `new/0`. Plan A16: `_ENV` semantics + # require globals to be a real Lua table so `_ENV` reassignment + # can redirect global access. + g_ref: nil @type t :: %__MODULE__{ - globals: map(), call_stack: list(), metatables: map(), upvalue_cells: map(), @@ -27,23 +30,60 @@ defmodule Lua.VM.State do userdata: %{optional(non_neg_integer()) => term()}, userdata_next_id: non_neg_integer(), private: map(), - multi_return_count: non_neg_integer() + multi_return_count: non_neg_integer(), + g_ref: nil | {:tref, non_neg_integer()} } @doc """ Creates a new VM state. + + Allocates an empty `_G` table to hold globals. """ @spec new() :: t() def new do - %__MODULE__{} + state = %__MODULE__{} + {g_ref, state} = alloc_table(state) + %{state | g_ref: g_ref} end + @doc """ + Returns the `_G` table reference. + """ + @spec g_ref(t()) :: {:tref, non_neg_integer()} + def g_ref(%__MODULE__{g_ref: g_ref}), do: g_ref + @doc """ Sets a global variable in the VM state. + + Writes into the `_G` table's data map. Globals storage lives entirely + inside the `_G` table since Plan A16 (Lua 5.3 `_ENV` semantics). """ @spec set_global(t(), binary(), term()) :: t() - def set_global(%__MODULE__{} = state, name, value) when is_binary(name) do - %{state | globals: Map.put(state.globals, name, value)} + def set_global(%__MODULE__{g_ref: g_ref} = state, name, value) when is_binary(name) and not is_nil(g_ref) do + update_table(state, g_ref, fn table -> + %{table | data: Map.put(table.data, name, value)} + end) + end + + @doc """ + Reads a global variable from the VM state. Returns `nil` if unset. + """ + @spec get_global(t(), binary()) :: term() + def get_global(%__MODULE__{g_ref: g_ref} = state, name) when is_binary(name) and not is_nil(g_ref) do + table = get_table(state, g_ref) + Map.get(table.data, name) + end + + @doc """ + Returns the underlying globals data map (read-only convenience). + + Equivalent to `state._G.data`. Avoid using this for state mutation — + use `set_global/3` instead so that future invariants stay consistent. + """ + @spec globals(t()) :: map() + def globals(%__MODULE__{g_ref: g_ref} = state) when not is_nil(g_ref) do + table = get_table(state, g_ref) + table.data end @doc """ diff --git a/lib/lua/vm/stdlib.ex b/lib/lua/vm/stdlib.ex index b33d844a..f36f5a86 100644 --- a/lib/lua/vm/stdlib.ex +++ b/lib/lua/vm/stdlib.ex @@ -58,60 +58,34 @@ defmodule Lua.VM.Stdlib do state = module.install(state) name = module.lib_name() - case Map.get(state.globals, name) do + case State.get_global(state, name) do {:tref, _} = tref -> cache_module_result(state, name, tref) _ -> state end end - # Install _G global table as a proxy with __index/__newindex metamethods + # Install `_G` and `_ENV` globals. + # + # As of Plan A16 (Lua 5.3 `_ENV` semantics), the `_G` table itself is the + # storage for globals — its `data` map is what `State.set_global/3` and + # `State.get_global/2` read and write. The `_G` table is allocated by + # `State.new/0` and its tref is stored in `state.g_ref`. + # + # Here we just expose `_G` to Lua code under the names `_G` and `_ENV`. + # Top-level chunks see `_ENV` as a register holding `_G`; user code can + # reassign `_ENV` to redirect global access without affecting `_G` itself. defp install_global_g(state) do - # Create empty proxy table for _G - {g_ref, state} = State.alloc_table(state) - - # Create __index function that reads from globals - index_fn = - {:native_func, - fn [_table, key], st -> - value = Map.get(st.globals, key) - {[value], st} - end} - - # Create __newindex function that writes to globals - newindex_fn = - {:native_func, - fn [_table, key, value], st -> - st = %{st | globals: Map.put(st.globals, key, value)} - {[], st} - end} - - # Create metatable with __index and __newindex - mt_data = %{ - "__index" => index_fn, - "__newindex" => newindex_fn - } + g_ref = State.g_ref(state) - {mt_ref, state} = State.alloc_table(state, mt_data) - - # Set the metatable on the _G proxy - state = - State.update_table(state, g_ref, fn table -> - %{table | metatable: mt_ref} - end) - - # Set _G global (the proxy table itself is stored in the raw data for _G._G == _G) + # Expose _G to Lua under the name "_G" state = State.set_global(state, "_G", g_ref) - # _ENV is the environment table — equivalent to _G for top-level code - state = State.set_global(state, "_ENV", g_ref) - - # Store _G in the proxy's raw data so _G._G == _G works without hitting __index - state = - State.update_table(state, g_ref, fn table -> - %{table | data: Map.put(table.data, "_G", g_ref)} - end) - - state + # _ENV is also exposed at boot for backwards compatibility with code that + # references `_ENV` as a global. The compiler binds `_ENV` as a chunk-level + # local (register 0) at execute time, so this global is mostly for + # introspection; user-level `_ENV` reassignment goes to that local, not + # this global. + State.set_global(state, "_ENV", g_ref) end # Pre-load any stdlib table globals into package.loaded so that @@ -126,7 +100,7 @@ defmodule Lua.VM.Stdlib do modules = ["string", "math", "table", "debug"] Enum.reduce(modules, state, fn name, acc -> - case Map.get(acc.globals, name) do + case State.get_global(acc, name) do {:tref, _} = tref -> cache_module_result(acc, name, tref) _ -> acc end @@ -351,7 +325,7 @@ defmodule Lua.VM.Stdlib do # pairs(table) — returns next, table, nil defp lua_pairs([{:tref, _} = tref | _], state) do - next_func = Map.fetch!(state.globals, "next") + next_func = State.get_global(state, "next") {[next_func, tref, nil], state} end @@ -596,7 +570,7 @@ defmodule Lua.VM.Stdlib do # require(modname) — loads a Lua module defp lua_require([modname | _], state) when is_binary(modname) do # Get package table - {:tref, pkg_id} = Map.fetch!(state.globals, "package") + {:tref, pkg_id} = State.get_global(state, "package") package = Map.fetch!(state.tables, pkg_id) # Get package.loaded table @@ -688,7 +662,7 @@ defmodule Lua.VM.Stdlib do # Get the package.loaded table reference defp get_package_loaded_ref(state) do - with {:tref, pkg_id} <- Map.fetch!(state.globals, "package"), + with {:tref, pkg_id} <- State.get_global(state, "package"), package = Map.fetch!(state.tables, pkg_id), {:tref, _loaded_id} = loaded_ref <- Map.fetch!(package.data, "loaded") do loaded_ref @@ -760,7 +734,7 @@ defmodule Lua.VM.Stdlib do # Install global 'unpack' as alias for table.unpack defp install_unpack_alias(state) do - case Map.get(state.globals, "table") do + case State.get_global(state, "table") do {:tref, id} -> table = Map.fetch!(state.tables, id) diff --git a/test/lua/compiler/integration_test.exs b/test/lua/compiler/integration_test.exs index c26f34c6..bd5449e9 100644 --- a/test/lua/compiler/integration_test.exs +++ b/test/lua/compiler/integration_test.exs @@ -5,6 +5,7 @@ defmodule Lua.Compiler.IntegrationTest do alias Lua.Parser alias Lua.VM alias Lua.VM.AssertionError + alias Lua.VM.State alias Lua.VM.Stdlib alias Lua.VM.TypeError alias Lua.VM.Value @@ -370,7 +371,7 @@ defmodule Lua.Compiler.IntegrationTest do assert {:ok, results, state} = VM.execute(proto) assert results == [42] - assert state.globals["x"] == 42 + assert State.get_global(state, "x") == 42 end test "multiple global assignments" do @@ -381,8 +382,8 @@ defmodule Lua.Compiler.IntegrationTest do assert {:ok, results, state} = VM.execute(proto) assert results == [3] - assert state.globals["a"] == 1 - assert state.globals["b"] == 2 + assert State.get_global(state, "a") == 1 + assert State.get_global(state, "b") == 2 end test "reassign global variable" do @@ -966,7 +967,7 @@ defmodule Lua.Compiler.IntegrationTest do {[a + b], state} end} - state = %Lua.VM.State{globals: %{"add" => native_add}} + state = State.set_global(State.new(), "add", native_add) assert {:ok, results, _state} = VM.execute(proto, state) assert results == [7] @@ -1180,7 +1181,7 @@ defmodule Lua.Compiler.IntegrationTest do assert {:ok, proto} = Compiler.compile(ast) state = - VM.State.register_function(VM.State.new(), "double", fn [n], state -> {[n * 2], state} end) + State.register_function(State.new(), "double", fn [n], state -> {[n * 2], state} end) assert {:ok, [42], _state} = VM.execute(proto, state) end @@ -1192,7 +1193,7 @@ defmodule Lua.Compiler.IntegrationTest do assert {:ok, proto} = Compiler.compile(ast) state = - VM.State.register_function(VM.State.new(), "add", fn args, state -> + State.register_function(State.new(), "add", fn args, state -> {[Enum.sum(args)], state} end) @@ -1206,7 +1207,7 @@ defmodule Lua.Compiler.IntegrationTest do assert {:ok, proto} = Compiler.compile(ast) state = - VM.State.register_function(VM.State.new(), "get_answer", fn _args, state -> {[42], state} end) + State.register_function(State.new(), "get_answer", fn _args, state -> {[42], state} end) assert {:ok, [42], _state} = VM.execute(proto, state) end @@ -1221,8 +1222,8 @@ defmodule Lua.Compiler.IntegrationTest do assert {:ok, proto} = Compiler.compile(ast) state = - VM.State.register_function(VM.State.new(), "set_x", fn [val], state -> - {[], VM.State.set_global(state, "x", val)} + State.register_function(State.new(), "set_x", fn [val], state -> + {[], State.set_global(state, "x", val)} end) assert {:ok, [99], _state} = VM.execute(proto, state) @@ -1238,7 +1239,7 @@ defmodule Lua.Compiler.IntegrationTest do assert {:ok, proto} = Compiler.compile(ast) state = - VM.State.register_function(VM.State.new(), "get_field", fn [{:tref, id}, key], state -> + State.register_function(State.new(), "get_field", fn [{:tref, id}, key], state -> table = Map.fetch!(state.tables, id) {[Map.get(table.data, key)], state} end) @@ -1256,8 +1257,8 @@ defmodule Lua.Compiler.IntegrationTest do assert {:ok, proto} = Compiler.compile(ast) state = - VM.State.register_function(VM.State.new(), "make_table", fn _args, state -> - {tref, state} = VM.State.alloc_table(state, %{"x" => 100}) + State.register_function(State.new(), "make_table", fn _args, state -> + {tref, state} = State.alloc_table(state, %{"x" => 100}) {[tref], state} end) @@ -1292,7 +1293,7 @@ defmodule Lua.Compiler.IntegrationTest do describe "standard library" do setup do - state = Stdlib.install(VM.State.new()) + state = Stdlib.install(State.new()) {:ok, state: state} end @@ -1624,7 +1625,7 @@ defmodule Lua.Compiler.IntegrationTest do describe "generic for loops" do setup do - state = Stdlib.install(VM.State.new()) + state = Stdlib.install(State.new()) {:ok, state: state} end @@ -1704,9 +1705,9 @@ defmodule Lua.Compiler.IntegrationTest do describe "value encode/decode round-trip" do test "encode Elixir map as global, execute Lua, decode result" do # Encode an Elixir map into state as a global - state = Stdlib.install(VM.State.new()) + state = Stdlib.install(State.new()) {tref, state} = Value.encode(%{x: 10, y: 20}, state) - state = VM.State.set_global(state, "config", tref) + state = State.set_global(state, "config", tref) # Execute Lua code that reads from the encoded table code = "return config.x + config.y" @@ -1716,9 +1717,9 @@ defmodule Lua.Compiler.IntegrationTest do end test "encode list as global, iterate in Lua, decode result" do - state = Stdlib.install(VM.State.new()) + state = Stdlib.install(State.new()) {tref, state} = Value.encode([10, 20, 30], state) - state = VM.State.set_global(state, "items", tref) + state = State.set_global(state, "items", tref) code = """ local sum = 0 @@ -1734,7 +1735,7 @@ defmodule Lua.Compiler.IntegrationTest do end test "Lua produces table, decode to Elixir" do - state = Stdlib.install(VM.State.new()) + state = Stdlib.install(State.new()) code = """ local t = {a = 1, b = 2} @@ -2202,7 +2203,7 @@ defmodule Lua.Compiler.IntegrationTest do end test "break exits generic for loop", %{} do - state = Stdlib.install(VM.State.new()) + state = Stdlib.install(State.new()) code = """ local sum = 0 diff --git a/test/lua/vm/env_semantics_test.exs b/test/lua/vm/env_semantics_test.exs index f8ec6f97..9241c101 100644 --- a/test/lua/vm/env_semantics_test.exs +++ b/test/lua/vm/env_semantics_test.exs @@ -1,36 +1,26 @@ defmodule Lua.VM.EnvSemanticsTest do use ExUnit.Case, async: true - # Regression tests for Lua 5.3 _ENV semantics. + # Regression tests for Lua 5.3 `_ENV` semantics (Plan A16). # # In Lua 5.3, every "global" name reference is syntactic sugar for - # `_ENV.name`, where `_ENV` is an implicit upvalue in every function. A - # user may swap their environment with `_ENV = setmetatable({}, ...)` or + # `_ENV.name`, where `_ENV` is an implicit chunk-level local. A user + # may swap their environment with `_ENV = setmetatable({}, ...)` or # `local _ENV = ...`, and all subsequent free-name accesses go through # that table (and its metamethods). # - # This implementation does not currently honour that. Free names are - # resolved as `{:global, name}` at compile time and the VM reads/writes a - # flat `state.globals` map directly via `:get_global` / `:set_global` - # opcodes that bypass any user-controlled `_ENV`. `_G` is a metatable - # proxy whose `__index`/`__newindex` route to `state.globals`; `_ENV` is - # a one-time alias of `_G` set at stdlib install. - # - # These tests are tagged `:skip`. They must pass once Plan A16 - # (.agents/plans/A16-env-semantics.md) is implemented. Removing the - # skip tags is a success criterion of A16. - # - # Discovered while triaging suite test events.lua (Plan A8). The first - # failing assertion in events.lua is line 15: - # assert(X == 30 and _G.X == 20) - # which depends on this behaviour. + # In our implementation, the chunk reserves register 0 for `_ENV` and + # binds it to `_G` at startup via the `:load_env` opcode. Free names in + # the chunk compile to `_ENV.name` (`get_field`/`set_field` against + # register 0). Nested functions inherit `_ENV` via the standard upvalue + # chain, allocated eagerly during scope resolution so every function + # has access regardless of which free names it references. setup do %{lua: Lua.new(sandboxed: [])} end describe "_ENV reassignment redirects global access" do - @tag :skip test "global write after _ENV swap goes to new env, not _G", %{lua: lua} do code = """ X = 20 @@ -43,7 +33,6 @@ defmodule Lua.VM.EnvSemanticsTest do assert {[20, 30], _} = Lua.eval!(lua, code) end - @tag :skip test "setting key to nil in new _ENV falls through __index", %{lua: lua} do code = """ B = 30 @@ -60,7 +49,6 @@ defmodule Lua.VM.EnvSemanticsTest do assert {[false, 30], _} = Lua.eval!(lua, code) end - @tag :skip test "free name read consults new _ENV's __index", %{lua: lua} do code = """ _ENV = setmetatable({}, {__index = function(_, k) return "from-meta-" .. k end}) @@ -72,7 +60,6 @@ defmodule Lua.VM.EnvSemanticsTest do end describe "local _ENV scoping" do - @tag :skip test "local _ENV inside a function redirects only that function", %{lua: lua} do code = """ X = 1 @@ -92,8 +79,6 @@ defmodule Lua.VM.EnvSemanticsTest do describe "_G / _ENV identity at top level" do test "_G == _ENV before any user reassignment", %{lua: lua} do - # This already passes — included to pin the contract that the A16 - # implementation must not break. assert {[true], _} = Lua.eval!(lua, "return _G == _ENV") end end From b2c7ca59a1467959ed5840dd191fce1691014687 Mon Sep 17 00:00:00 2001 From: Dave Lucia Date: Wed, 6 May 2026 16:19:46 -0700 Subject: [PATCH 3/4] chore(A16): mark plan as review --- .agents/plans/A16-env-semantics.md | 92 +++++++++++++++++++++++++++++- 1 file changed, 90 insertions(+), 2 deletions(-) diff --git a/.agents/plans/A16-env-semantics.md b/.agents/plans/A16-env-semantics.md index 066a4145..c8f69b23 100644 --- a/.agents/plans/A16-env-semantics.md +++ b/.agents/plans/A16-env-semantics.md @@ -5,7 +5,7 @@ issue: 186 pr: null branch: feat/env-semantics base: main -status: in-progress +status: review direction: A unlocks: - events.lua @@ -137,4 +137,92 @@ mix test test/language/global_test.exs ## Discoveries -(populated during implementation) +### Storage migration: globals now live in `_G.data` + +Chose option 2 from the plan's "globals storage strategy" — moved global +storage out of the flat `state.globals` map and into the `_G` table's +`data` field. `State.new/0` now allocates `_G` up-front and stores its +tref in `state.g_ref`. New `State.get_global/2` and updated +`State.set_global/3` read/write `_G.data`. The `_G` metatable proxy +(`__index`/`__newindex` routing to `state.globals`) is gone — globals +are just real table fields now. + +This was cleaner than option 1 ("keep `state.globals` and sync with +`_G`") and avoids an ongoing sync-risk surface. Host API (`Lua.set!` / +`Lua.get!`) continues to work transparently because they now go through +`State.get_global`/`set_global`. + +### `_ENV` as a chunk-level local at register 0 + +The chunk reserves register 0 for `_ENV`. Codegen emits a new +`:load_env` opcode at the start of every chunk that copies +`state.g_ref` into register 0. User-level `_ENV = ...` becomes a normal +assignment to that local; nested functions inherit `_ENV` via the +existing upvalue chain. + +`_ENV` is unconditionally marked as a captured-local at the chunk +level. This guarantees that any later capture by a nested function +(which creates the open-upvalue cell) sees a consistent value, and that +chunk-level `_ENV` access always uses `get_open_upvalue` / +`set_open_upvalue` — which fall back to direct register I/O when no +cell exists yet. + +### `set_open_upvalue` no longer relies on a prior register write + +Previously, `gen_assign_target` for `{:captured_local, _}` emitted only +`set_open_upvalue` and relied on the (informal) invariant that the +register already held the value before the cell was created. That worked +for the existing call sites but broke under Plan A16 because chunk-level +`_ENV` is now captured-local from the very first instruction, before any +closure has run. Updated `gen_assign_target` to emit a `move` *and* the +`set_open_upvalue` so writes propagate regardless of cell-allocation +state. + +### Multi-target assignment to free names: register reservation fix + +In `Statement.Assign` codegen for `[a, b] = f()` (multi-return call), the +post-call `ctx.next_reg` only advanced past the *first* result register. +Old code emitted `set_global` per target, which doesn't allocate temp +registers — so it accidentally worked. New code emits `_ENV. = ...` +which loads `_ENV` into a temp register, and the temp allocation +clobbered subsequent call result registers. Fix: bump `ctx.next_reg` +past all the call's expanded result slots after `gen_expr(call, ctx)`. + +### FuncDecl target resolution moved after body resolution + +The `Statement.FuncDecl{name: [single_name]}` resolver used to tag the +target *before* recursing into the function body. Under A16 that +ordering was wrong: the body may capture `_ENV` from the chunk, and +`captured_locals` (and the `_ENV` upvalue chain in nested functions) is +only finalised after the body is processed. Now we resolve the body +first, then tag the target. This is a generalisation that doesn't change +behaviour for any non-`_ENV` case. + +### Eager `_ENV` upvalue allocation in every nested function + +`resolve_function_scope` now eagerly walks `find_upvalue("_ENV", ...)` +for every nested function it processes. This guarantees `_ENV` is +always available as an upvalue regardless of whether the function body +references any free name explicitly — required because the +`gen_var_by_name` path (used for FuncDecl table-chain heads like +`function obj.method`) needs to look up `_ENV` at codegen time without +re-walking the scope chain. + +### `:get_global` / `:set_global` opcodes are now vestigial + +Codegen no longer emits these instructions; all global access goes +through `_ENV` field access. The opcode handlers and constructors +remain in place (`Instruction.get_global/2`, `Instruction.set_global/2`, +the executor `do_execute` clauses) for forward-compatibility with any +external prototypes or hand-written instruction sequences. They could +be removed in a follow-up cleanup. + +### `_ENV` is no longer registered as a global + +`install_global_g/1` previously stored `_ENV` as a global aliasing +`_G`. With `_ENV` now living in chunk register 0, that global slot is +no longer the source of truth. We still set `state.globals["_ENV"] = +g_ref` at install time for backwards compatibility (so introspection +tools that read `_G._ENV` see something), but reading the global +`_ENV` is decoupled from the chunk-level `_ENV` that free-name access +consults. From 2a92c4d54272df617666f2395ee43f633027c624 Mon Sep 17 00:00:00 2001 From: Dave Lucia Date: Wed, 6 May 2026 16:21:24 -0700 Subject: [PATCH 4/4] chore(A16): record PR #197 and what-changed --- .agents/plans/A16-env-semantics.md | 65 +++++++++++++++++++++++++++++- 1 file changed, 64 insertions(+), 1 deletion(-) diff --git a/.agents/plans/A16-env-semantics.md b/.agents/plans/A16-env-semantics.md index c8f69b23..81478bde 100644 --- a/.agents/plans/A16-env-semantics.md +++ b/.agents/plans/A16-env-semantics.md @@ -2,7 +2,7 @@ id: A16 title: Implement Lua 5.3 _ENV semantics for global access issue: 186 -pr: null +pr: 197 branch: feat/env-semantics base: main status: review @@ -226,3 +226,66 @@ g_ref` at install time for backwards compatibility (so introspection tools that read `_G._ENV` see something), but reading the global `_ENV` is decoupled from the chunk-level `_ENV` that free-name access consults. + +## What changed + +PR: [#197](https://github.com/tv-labs/lua/pull/197) + +### Files touched + +- `lib/lua/vm/state.ex` — removed `globals: %{}` field; added `g_ref` + field; new `get_global/2` and `globals/1` helpers; `set_global/3` + rewrites to `_G.data`; `new/0` allocates `_G` up-front. +- `lib/lua/vm/stdlib.ex` — removed the `_G` metamethod proxy from + `install_global_g/1`; replaced internal `Map.get(state.globals, ...)` + reads with `State.get_global/2`. +- `lib/lua.ex` — `Lua.set!` / `Lua.get!` use `State.set_global` / + `State.get_global` instead of the removed `state.globals` map. +- `lib/lua/compiler/instruction.ex` — added `load_env(dest)` opcode + constructor. +- `lib/lua/vm/executor.ex` — added `:load_env` handler; `:get_global` / + `:set_global` handlers now route through `State.get_global` / + `State.set_global`. +- `lib/lua/compiler/scope.ex` — replaced `{:global, name}` var_ref + with `{:env_field, env_var_ref, name}`; chunk pre-registers `_ENV` + as a captured-local at register 0; nested functions eagerly resolve + `_ENV` as an upvalue; FuncDecl single-name target tagging moved + after function-body resolution; new `resolve_env_ref/1` helper. +- `lib/lua/compiler/codegen.ex` — new `gen_env_field_get/3`, + `gen_env_field_set/4`, `gen_load_env/2`, + `compute_env_var_ref_at_codegen/1`, + `current_function_env_upvalue_index/1` helpers; `gen_assign_target` + for `{:captured_local, _}` now also emits a `move` so writes + propagate before any cell exists; multi-target multi-return Assign + reserves call-result register slots in `ctx.next_reg`; chunk + `generate/3` prepends `:load_env 0`; codegen ctx now carries + `current_function`. +- `test/lua/vm/env_semantics_test.exs` — removed `:skip` tags; + refreshed module doc. +- `test/lua/compiler/integration_test.exs` — assertions on + `state.globals["x"]` now use `State.get_global(state, "x")`; one + literal `%Lua.VM.State{globals: ...}` constructor replaced with + `State.set_global(State.new(), ...)`. + +### Suite delta + +- `mix test`: 1382 → 1382 passing (no regressions). Skipped count + 36 → 32 (4 env-semantics tests un-skipped). +- `mix test --only lua53`: 29 tests, 0 failures (unchanged). +- Manually verified: `events.lua` now passes through line 19's + `_ENV`-dependent block (`X == 30 and _G.X == 20`, `B == false`, + `B == 30`). + +### Follow-up issues / plans + +- The `:get_global` / `:set_global` opcode handlers and constructors + are now vestigial (codegen no longer emits them). Removing them is + a small future cleanup. +- `gen_var_by_name`'s pre-existing limitation (doesn't walk the + upvalue chain for FuncDecl table-chain head names) is unchanged. + Free-name fallback now goes via `_ENV.`, which is correct Lua + 5.3 behaviour. +- Performance: globals access now involves an `_ENV` upvalue load + plus a `get_field` (table lookup) per global read/write, vs. the + previous direct map access. If this shows up in benchmarks, a + fast-path opcode for "unmodified `_ENV`" could be added.