diff --git a/lib/lua/vm/dispatcher.ex b/lib/lua/vm/dispatcher.ex index 2cd936e5..610388e0 100644 --- a/lib/lua/vm/dispatcher.ex +++ b/lib/lua/vm/dispatcher.ex @@ -30,6 +30,26 @@ defmodule Lua.VM.Dispatcher do alias Lua.VM.Table alias Lua.VM.Value + # Per-call depth check, inlined to a plain integer comparison so the + # call-dense recursive path does not pay a cross-module call on every + # Lua call/return. Returns the bumped depth, or raises a catchable + # "stack overflow" once the limit is hit. The `:infinity` head (the + # default) skips the comparison. + # + # This is one of three copies of the same logic: the authoritative + # `Lua.VM.State.next_call_depth!/1` and an identical private copy in + # `Lua.VM.Executor`. They are not compiler-checked against each other, + # so any change here must be mirrored in the other two. The shared + # semantics are pinned by `test/lua/vm/state_test.exs`. + @compile {:inline, next_call_depth!: 1} + + defp next_call_depth!(%State{call_depth: depth, max_call_depth: :infinity}), do: depth + 1 + defp next_call_depth!(%State{call_depth: depth, max_call_depth: max}) when depth < max, do: depth + 1 + + defp next_call_depth!(%State{call_stack: call_stack}) do + raise RuntimeError, value: "stack overflow", call_stack: call_stack + end + # Mirror of the interpreter's concat ceiling, inlined as a compile-time # constant so the binary-binary fast path stays a single comparison. See # `Lua.VM.Executor.concat_checked/2` for the rationale. @@ -582,12 +602,12 @@ defmodule Lua.VM.Dispatcher do {code, pc + 1, regs, upvalues, proto, cont, :discard, state.open_upvalues} call_info = Executor.dispatcher_call_info(proto, name_hint, 0) - State.check_call_depth!(state) + depth = next_call_depth!(state) state = %{ state | call_stack: [call_info | state.call_stack], - call_depth: state.call_depth + 1, + call_depth: depth, open_upvalues: %{} } @@ -605,8 +625,8 @@ defmodule Lua.VM.Dispatcher do {:lua_closure, _, _} = closure -> args = collect_args(regs, base + 1, arg_count) call_info = Executor.dispatcher_call_info(proto, name_hint, 0) - State.check_call_depth!(state) - state = %{state | call_stack: [call_info | state.call_stack], call_depth: state.call_depth + 1} + depth = next_call_depth!(state) + state = %{state | call_stack: [call_info | state.call_stack], call_depth: depth} {_results, state} = Executor.call_function(closure, args, state) state = %{state | call_stack: tl(state.call_stack), call_depth: state.call_depth - 1} dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames) @@ -635,12 +655,12 @@ defmodule Lua.VM.Dispatcher do {code, pc + 1, regs, upvalues, proto, cont, base, state.open_upvalues} call_info = Executor.dispatcher_call_info(proto, name_hint, 0) - State.check_call_depth!(state) + depth = next_call_depth!(state) state = %{ state | call_stack: [call_info | state.call_stack], - call_depth: state.call_depth + 1, + call_depth: depth, open_upvalues: %{} } @@ -658,8 +678,8 @@ defmodule Lua.VM.Dispatcher do {:lua_closure, _, _} = closure -> args = collect_args(regs, base + 1, arg_count) call_info = Executor.dispatcher_call_info(proto, name_hint, 0) - State.check_call_depth!(state) - state = %{state | call_stack: [call_info | state.call_stack], call_depth: state.call_depth + 1} + depth = next_call_depth!(state) + state = %{state | call_stack: [call_info | state.call_stack], call_depth: depth} {results, state} = Executor.call_function(closure, args, state) state = %{state | call_stack: tl(state.call_stack), call_depth: state.call_depth - 1} @@ -1039,12 +1059,12 @@ defmodule Lua.VM.Dispatcher do frame = {code, pc + 1, regs, upvalues, proto, cont, dest, state.open_upvalues} call_info = Executor.dispatcher_call_info(proto, name_hint, 0) - State.check_call_depth!(state) + depth = next_call_depth!(state) state = %{ state | call_stack: [call_info | state.call_stack], - call_depth: state.call_depth + 1, + call_depth: depth, open_upvalues: %{} } @@ -1062,8 +1082,8 @@ defmodule Lua.VM.Dispatcher do {:lua_closure, _, _} = closure -> args = collect_args(regs, base + 1, total_args) call_info = Executor.dispatcher_call_info(proto, name_hint, 0) - State.check_call_depth!(state) - state = %{state | call_stack: [call_info | state.call_stack], call_depth: state.call_depth + 1} + depth = next_call_depth!(state) + state = %{state | call_stack: [call_info | state.call_stack], call_depth: depth} {results, state} = Executor.call_function(closure, args, state) state = %{state | call_stack: tl(state.call_stack), call_depth: state.call_depth - 1} apply_multi_call_result(result_count, base, results, code, pc + 1, regs, upvalues, proto, state, cont, frames) diff --git a/lib/lua/vm/executor.ex b/lib/lua/vm/executor.ex index 70daa428..6697768a 100644 --- a/lib/lua/vm/executor.ex +++ b/lib/lua/vm/executor.ex @@ -967,8 +967,8 @@ defmodule Lua.VM.Executor do # without going through this branch. args = collect_args(regs, base + 1, total_args) call_info = %{source: proto.source, line: line, name: hint_name(name_hint), namewhat: hint_namewhat(name_hint)} - State.check_call_depth!(state) - state = %{state | call_stack: [call_info | state.call_stack], call_depth: state.call_depth + 1} + depth = next_call_depth!(state) + state = %{state | call_stack: [call_info | state.call_stack], call_depth: depth} {results, state} = Dispatcher.execute(callee_proto, args, callee_upvalues, state) state = %{state | call_stack: tl(state.call_stack), call_depth: state.call_depth - 1} continue_after_call(results, regs, rest, upvalues, proto, state, cont, frames, line, base, result_count) @@ -1005,12 +1005,12 @@ defmodule Lua.VM.Executor do call_info = %{source: proto.source, line: line, name: hint_name(name_hint), namewhat: hint_namewhat(name_hint)} - State.check_call_depth!(state) + depth = next_call_depth!(state) state = %{ state | call_stack: [call_info | state.call_stack], - call_depth: state.call_depth + 1, + call_depth: depth, open_upvalues: %{} } @@ -2175,6 +2175,25 @@ defmodule Lua.VM.Executor do raise RuntimeError, value: "resulting string too large" end + # Per-call depth check, inlined to a plain integer comparison so the + # call-dense recursive path does not pay a cross-module call on every + # Lua call/return. Returns the bumped depth, or raises a catchable + # "stack overflow" once the limit is hit. The `:infinity` head (the + # default) skips the comparison. + # + # This is one of three copies of the same logic: the authoritative + # `Lua.VM.State.next_call_depth!/1` and an identical private copy in + # `Lua.VM.Dispatcher`. They are not compiler-checked against each other, + # so any change here must be mirrored in the other two. The shared + # semantics are pinned by `test/lua/vm/state_test.exs`. + @compile {:inline, next_call_depth!: 1} + defp next_call_depth!(%State{call_depth: depth, max_call_depth: :infinity}), do: depth + 1 + defp next_call_depth!(%State{call_depth: depth, max_call_depth: max}) when depth < max, do: depth + 1 + + defp next_call_depth!(%State{call_stack: call_stack}) do + raise RuntimeError, value: "stack overflow", call_stack: call_stack + end + # ── Metamethod support ───────────────────────────────────────────────────── @metamethod_chain_limit 200 diff --git a/lib/lua/vm/state.ex b/lib/lua/vm/state.ex index cbd161f0..f4a5f42d 100644 --- a/lib/lua/vm/state.ex +++ b/lib/lua/vm/state.ex @@ -9,7 +9,7 @@ defmodule Lua.VM.State do # Call depth tracked as an O(1) counter that moves in lockstep # with `call_stack` — `length(call_stack)` would be O(depth) per # call. `max_call_depth` bounds it; `:infinity` (the default) - # means no limit. See `check_call_depth!/1`. + # means no limit. See `next_call_depth!/1`. call_depth: 0, max_call_depth: :infinity, metatables: %{}, @@ -55,21 +55,31 @@ defmodule Lua.VM.State do end @doc """ - Guards against unbounded recursion. + Returns the next call depth, guarding against unbounded recursion. - Raises a Lua `"stack overflow"` runtime error when the call depth has - reached `max_call_depth`. Call it immediately before pushing a frame - onto `call_stack`. - - No-op when depth is under the limit or when `max_call_depth` is - `:infinity` (the default). The clauses are ordered so both common cases - resolve in a single function-head match with no struct rebuild. - """ - @spec check_call_depth!(t()) :: :ok - def check_call_depth!(%__MODULE__{max_call_depth: :infinity}), do: :ok - def check_call_depth!(%__MODULE__{call_depth: depth, max_call_depth: max}) when depth < max, do: :ok + Call it immediately before pushing a frame onto `call_stack`: it both + enforces the limit and computes the incremented `call_depth` in a + single pass, so callers never read `call_depth` a second time to bump + it. - def check_call_depth!(%__MODULE__{call_stack: call_stack}) do + Raises a Lua `"stack overflow"` runtime error when the call depth has + already reached `max_call_depth`. When `max_call_depth` is `:infinity` + (the default) the limit comparison is skipped — the only work is the + integer increment. + + The hot call/return paths in `Lua.VM.Dispatcher` and `Lua.VM.Executor` + inline this same comparison directly rather than pay a cross-module + call on every Lua call. This function is the authoritative definition + those two private copies mirror, and the entry point for any other + caller. The copies are not compiler-checked against this one, so any + change to the limit logic here must be applied to all three; the direct + unit test in `test/lua/vm/state_test.exs` pins the shared semantics. + """ + @spec next_call_depth!(t()) :: pos_integer() + def next_call_depth!(%__MODULE__{call_depth: depth, max_call_depth: :infinity}), do: depth + 1 + def next_call_depth!(%__MODULE__{call_depth: depth, max_call_depth: max}) when depth < max, do: depth + 1 + + def next_call_depth!(%__MODULE__{call_stack: call_stack}) do raise Lua.VM.RuntimeError, value: "stack overflow", call_stack: call_stack end diff --git a/test/lua/vm/state_test.exs b/test/lua/vm/state_test.exs new file mode 100644 index 00000000..72e09645 --- /dev/null +++ b/test/lua/vm/state_test.exs @@ -0,0 +1,49 @@ +defmodule Lua.VM.StateTest do + @moduledoc """ + Pins the authoritative `State.next_call_depth!/1` and, by extension, the + shared semantics the inlined copies in `Lua.VM.Dispatcher` and + `Lua.VM.Executor` must match: the depth bumps by one under the limit, + `:infinity` skips the comparison, and reaching `max_call_depth` raises a + catchable Lua `"stack overflow"`. + """ + use ExUnit.Case, async: true + + alias Lua.VM.RuntimeError + alias Lua.VM.State + + describe "next_call_depth!/1" do + test "returns the incremented depth when under a finite limit" do + state = %State{call_depth: 3, max_call_depth: 10} + + assert State.next_call_depth!(state) == 4 + end + + test "returns the incremented depth when max_call_depth is :infinity" do + state = %State{call_depth: 41, max_call_depth: :infinity} + + assert State.next_call_depth!(state) == 42 + end + + test "skips the limit comparison for :infinity at depth 0 (the default)" do + assert State.next_call_depth!(%State{}) == 1 + end + + test "raises a catchable stack overflow once the depth reaches the limit" do + frames = [%{source: "chunk", line: 1, name: "f", namewhat: ""}] + state = %State{call_depth: 10, max_call_depth: 10, call_stack: frames} + + assert_raise RuntimeError, ~r/stack overflow/, fn -> + State.next_call_depth!(state) + end + end + + test "the raised error carries the stack-overflow value and the call stack" do + frames = [%{source: "chunk", line: 1, name: "f", namewhat: ""}] + state = %State{call_depth: 5, max_call_depth: 5, call_stack: frames} + + error = catch_error(State.next_call_depth!(state)) + + assert %RuntimeError{value: "stack overflow", call_stack: ^frames} = error + end + end +end