From c0aa5616ab4842d2ecc1c586ad8eae2100752adf Mon Sep 17 00:00:00 2001 From: Dave Lucia Date: Thu, 26 Nov 2026 13:35:00 -0500 Subject: [PATCH 1/2] fix(compiler): keep captured locals fresh across loop iterations A write to a captured local that preceded the capturing closure in source order inside a loop compiled to a plain register move, missing the cell an earlier iteration's closure had opened. Loops and label blocks that contain functions are now resolved once to learn the captured names, then again with those names marked, so such writes go through the open upvalue. --- CHANGELOG.md | 5 + lib/lua/compiler/scope.ex | 72 ++++- test/language/loop_captured_local_test.exs | 302 +++++++++++++++++++++ 3 files changed, 377 insertions(+), 2 deletions(-) create mode 100644 test/language/loop_captured_local_test.exs diff --git a/CHANGELOG.md b/CHANGELOG.md index c26f0ca..200c5bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -55,6 +55,11 @@ is in the [`1.0.0-rc.0`](#100-rc0---2026-05-26) entry below. past the ceiling in a single allocation. Each raises the same catchable `"resulting string too large"` error as `string.rep` and `..`, before the result is built (#425). +- A local captured by a closure no longer goes stale when it is written inside + a `for`, `while`, `repeat` or `goto` loop before the closure is created: the + write now reaches the closure's cell, so the closure reads the new value like + PUC-Lua does (`local x; for i=1,2 do x=i; fns[i]=function() return x end end` + printed `1,1` instead of `1,2`). ## [1.0.2] - 2026-07-28 diff --git a/lib/lua/compiler/scope.ex b/lib/lua/compiler/scope.ex index 31a0b52..f87d38b 100644 --- a/lib/lua/compiler/scope.ex +++ b/lib/lua/compiler/scope.ex @@ -5,6 +5,7 @@ defmodule Lua.Compiler.Scope do alias Lua.AST.Chunk alias Lua.AST.Expr alias Lua.AST.Statement + alias Lua.AST.Walker @type var_ref :: {:register, index :: non_neg_integer()} @@ -49,6 +50,7 @@ defmodule Lua.Compiler.Scope do locals: %{}, parent_scopes: [], captured_locals: MapSet.new(), + loop_captures: nil, block_path: [], block_counter: 0 @@ -60,6 +62,7 @@ defmodule Lua.Compiler.Scope do locals: %{optional(binary()) => non_neg_integer()}, parent_scopes: [%{locals: map(), function: term()}], captured_locals: MapSet.t(), + loop_captures: nil | :trial | MapSet.t(), block_path: [non_neg_integer()], block_counter: non_neg_integer() } @@ -133,8 +136,68 @@ defmodule Lua.Compiler.Scope do {:ok, state} end - defp resolve_block(%Block{stmts: stmts}, state) do - Enum.reduce(stmts, state, &resolve_statement/2) + defp resolve_block(%Block{stmts: stmts} = block, state) do + resolve_stmts = fn state -> Enum.reduce(stmts, state, &resolve_block_statement/2) end + + # A block holding a label can be re-entered by a backward `goto`, so every + # captured name counts for the whole block, whichever local it names. + if Enum.any?(stmts, &match?(%Statement.Label{}, &1)) and contains_function?(block) do + with_loop_captures(state, :all, resolve_stmts) + else + resolve_stmts.(state) + end + end + + # A loop body runs more than once, so a local declared outside the loop can + # be written there before a closure later in the body (or in a later + # iteration) captures it. A plain register write made at that point would + # miss the cell the first closure opened. Which names get captured is only + # known after the body has been resolved, so a loop that contains a function + # is resolved once to find them and again with them already marked. + defp resolve_block_statement(%stmt_type{} = stmt, state) + when stmt_type in [Statement.While, Statement.Repeat, Statement.ForNum, Statement.ForIn] do + if contains_function?(stmt) do + with_loop_captures(state, {:visible, Map.keys(state.locals)}, &resolve_statement(stmt, &1)) + else + resolve_statement(stmt, state) + end + end + + defp resolve_block_statement(stmt, state), do: resolve_statement(stmt, state) + + # `scope` is `:all`, or `{:visible, names}`: the locals declared outside the + # loop. Locals declared inside the body get a fresh slot, and a closed cell, + # on every iteration, so they need no early marking. + defp with_loop_captures(%{loop_captures: :trial} = state, _scope, resolve), do: resolve.(state) + + defp with_loop_captures(%{loop_captures: nil} = state, scope, resolve) do + trial = resolve.(%{state | loop_captures: :trial}) + state = run_with_loop_captures(state, trial.captured_locals, scope, resolve) + %{state | loop_captures: nil} + end + + defp with_loop_captures(%{loop_captures: captures} = state, scope, resolve) do + state = run_with_loop_captures(state, captures, scope, resolve) + %{state | loop_captures: captures} + end + + defp run_with_loop_captures(state, captures, scope, resolve) do + marked = + case scope do + :all -> captures + {:visible, names} -> MapSet.intersection(captures, MapSet.new(names)) + end + + resolve.(%{state | loop_captures: captures, captured_locals: MapSet.union(state.captured_locals, marked)}) + end + + defp contains_function?(node) do + Walker.reduce(node, false, fn + %Expr.Function{}, _acc -> true + %Statement.FuncDecl{}, _acc -> true + %Statement.LocalFunc{}, _acc -> true + _node, acc -> acc + end) end # Per Lua 5.3 ยง3.3.4, each control-flow block (then/else, while/repeat @@ -682,6 +745,7 @@ defmodule Lua.Compiler.Scope do saved_function = state.current_function saved_parent_scopes = state.parent_scopes saved_captured_locals = state.captured_locals + saved_loop_captures = state.loop_captures # Push current scope onto parent_scopes for upvalue resolution parent_scope_entry = %{locals: state.locals, function: state.current_function} @@ -711,6 +775,9 @@ defmodule Lua.Compiler.Scope do # in a loop can then never reuse an open cell that a plain register # write to `_ENV` did not update. captured_locals: MapSet.new(["_ENV"]), + # A trial pass only collects captured names, so it never needs the + # nested function's own trial passes. + loop_captures: if(saved_loop_captures == :trial, do: :trial), block_path: [] } @@ -756,6 +823,7 @@ defmodule Lua.Compiler.Scope do current_function: saved_function, parent_scopes: saved_parent_scopes, captured_locals: MapSet.union(saved_captured_locals, newly_captured), + loop_captures: saved_loop_captures, block_path: saved_block_path } end diff --git a/test/language/loop_captured_local_test.exs b/test/language/loop_captured_local_test.exs new file mode 100644 index 0000000..c5e12db --- /dev/null +++ b/test/language/loop_captured_local_test.exs @@ -0,0 +1,302 @@ +defmodule Lua.Language.LoopCapturedLocalTest do + @moduledoc """ + A local declared outside a loop and written inside it before a closure + captures it must show the closure the latest value, as PUC-Lua does. + """ + use ExUnit.Case, async: true + + defp run(code), do: elem(Lua.eval!(Lua.new(sandboxed: []), code), 0) + + describe "write before the closure is created" do + test "numeric for" do + assert ["1,2"] = + run(~S""" + local x = 0 + local out = {} + for i = 1, 2 do + x = i + local g = function() return x end + out[i] = g() + end + return out[1] .. "," .. out[2] + """) + end + + test "numeric for inside a function" do + assert ["1,2"] = + run(~S""" + local function f() + local x = 0 + local out = {} + for i = 1, 2 do + x = i + local g = function() return x end + out[i] = g() + end + return out[1] .. "," .. out[2] + end + return f() + """) + end + + test "generic for" do + assert ["a,b"] = + run(~S""" + local x = "" + local out = {} + for i, v in ipairs({"a", "b"}) do + x = v + local g = function() return x end + out[i] = g() + end + return out[1] .. "," .. out[2] + """) + end + + test "while" do + assert ["1,2"] = + run(~S""" + local x, n = 0, 0 + local out = {} + while n < 2 do + n = n + 1 + x = n + local g = function() return x end + out[n] = g() + end + return out[1] .. "," .. out[2] + """) + end + + test "while, written in the condition" do + assert ["1,2"] = + run(~S""" + local x = 0 + local out = {} + local function bump() x = x + 1; return x <= 2 end + local n = 0 + while bump() do + n = n + 1 + local y = x + local g = function() return x + y * 0 end + out[n] = g() + end + return out[1] .. "," .. out[2] + """) + end + + test "repeat" do + assert ["1,2"] = + run(~S""" + local x, n = 0, 0 + local out = {} + repeat + n = n + 1 + x = n + local g = function() return x end + out[n] = g() + until n == 2 + return out[1] .. "," .. out[2] + """) + end + + test "goto loop" do + assert ["1,2"] = + run(~S""" + local x, n = 0, 0 + local out = {} + ::top:: + n = n + 1 + x = n + local g = function() return x end + out[n] = g() + if n < 2 then goto top end + return out[1] .. "," .. out[2] + """) + end + + test "goto loop where the local is declared before the label in the same block" do + assert ["1,2"] = + run(~S""" + local function f() + local n = 0 + local x = 0 + local out = {} + ::top:: + n = n + 1 + x = n + out[n] = (function() return x end)() + if n < 2 then goto top end + return out[1] .. "," .. out[2] + end + return f() + """) + end + + test "local declared in an outer loop body, written in an inner loop" do + assert ["1,2,3,4"] = + run(~S""" + local out = {} + for a = 1, 2 do + local x = 0 + for b = 1, 2 do + x = (a - 1) * 2 + b + local g = function() return x end + out[#out + 1] = g() + end + end + return table.concat(out, ",") + """) + end + end + + describe "write after the closure is created" do + test "numeric for" do + assert ["1,2"] = + run(~S""" + local x = 0 + local out = {} + for i = 1, 2 do + local g = function() return x end + x = i + out[i] = g() + end + return out[1] .. "," .. out[2] + """) + end + + test "generic for" do + assert ["a,b"] = + run(~S""" + local x = "" + local out = {} + for i, v in ipairs({"a", "b"}) do + local g = function() return x end + x = v + out[i] = g() + end + return out[1] .. "," .. out[2] + """) + end + + test "while" do + assert ["1,2"] = + run(~S""" + local x, n = 0, 0 + local out = {} + while n < 2 do + n = n + 1 + local g = function() return x end + x = n + out[n] = g() + end + return out[1] .. "," .. out[2] + """) + end + + test "repeat" do + assert ["1,2"] = + run(~S""" + local x, n = 0, 0 + local out = {} + repeat + n = n + 1 + local g = function() return x end + x = n + out[n] = g() + until n == 2 + return out[1] .. "," .. out[2] + """) + end + + test "goto loop" do + assert ["1,2"] = + run(~S""" + local x, n = 0, 0 + local out = {} + ::top:: + n = n + 1 + local g = function() return x end + x = n + out[n] = g() + if n < 2 then goto top end + return out[1] .. "," .. out[2] + """) + end + end + + describe "closures sharing and outliving the loop" do + test "a closure made in an earlier iteration sees later writes" do + assert ["3,3"] = + run(~S""" + local x = 0 + local fs = {} + for i = 1, 2 do + x = i + fs[i] = function() return x end + end + x = 3 + return fs[1]() .. "," .. fs[2]() + """) + end + + test "a closure can write the local the loop also writes" do + assert ["1,10,2,20"] = + run(~S""" + local x = 0 + local out = {} + for i = 1, 2 do + x = i + local set = function(v) x = v end + out[#out + 1] = x + set(i * 10) + out[#out + 1] = x + end + return table.concat(out, ",") + """) + end + + test "nested closures" do + assert ["1,2"] = + run(~S""" + local x = 0 + local out = {} + for i = 1, 2 do + x = i + local g = function() + return function() return x end + end + out[i] = g()() + end + return out[1] .. "," .. out[2] + """) + end + + test "nested closures, write between the two levels" do + assert ["1,2"] = + run(~S""" + local x = 0 + local out = {} + for i = 1, 2 do + local g = function() + x = i + return function() return x end + end + out[i] = g()() + end + return out[1] .. "," .. out[2] + """) + end + + test "a loop variable is still fresh for each iteration" do + assert ["1,2"] = + run(~S""" + local fs = {} + for i = 1, 2 do + fs[i] = function() return i end + end + return fs[1]() .. "," .. fs[2]() + """) + end + end +end From 398e8c9193d1a9a378a7e2563a55a6b2a34cc088 Mon Sep 17 00:00:00 2001 From: Dave Lucia Date: Thu, 26 Nov 2026 13:38:08 -0500 Subject: [PATCH 2/2] fix(compiler): write the register for function declarations to captured locals --- lib/lua/compiler/codegen.ex | 14 +++++++++++++- test/language/loop_captured_local_test.exs | 13 +++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/lib/lua/compiler/codegen.ex b/lib/lua/compiler/codegen.ex index a303fd5..7b787b5 100644 --- a/lib/lua/compiler/codegen.ex +++ b/lib/lua/compiler/codegen.ex @@ -776,7 +776,19 @@ defmodule Lua.Compiler.Codegen do {instrs, ctx} {:captured_local, local_reg} -> - {[Instruction.set_open_upvalue(local_reg, closure_reg)], ctx} + # Write the register as well: set_open_upvalue is a no-op until a + # cell exists, and a later closure captures the register's value. + instrs = + if local_reg == closure_reg do + [Instruction.set_open_upvalue(local_reg, closure_reg)] + else + [ + Instruction.move(local_reg, closure_reg), + Instruction.set_open_upvalue(local_reg, closure_reg) + ] + end + + {instrs, ctx} {:upvalue, index} -> {[Instruction.set_upvalue(index, closure_reg)], ctx} diff --git a/test/language/loop_captured_local_test.exs b/test/language/loop_captured_local_test.exs index c5e12db..4b6a8b5 100644 --- a/test/language/loop_captured_local_test.exs +++ b/test/language/loop_captured_local_test.exs @@ -299,4 +299,17 @@ defmodule Lua.Language.LoopCapturedLocalTest do """) end end + + describe "function declarations assigning a captured local" do + test "function f() in a loop before a closure captures f" do + assert run(""" + local f + for i = 1, 1 do + function f() return 42 end + local g = function() return f end + return g()() + end + """) == [42] + end + end end