From 3676d2a17868e18765444b739c8ed9bec82d6bec Mon Sep 17 00:00:00 2001 From: Dave Lucia Date: Tue, 9 Jun 2026 13:29:44 -0700 Subject: [PATCH] fix(vm): return terse Lua error value from call_function, not terminal render (#336) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Lua.call_function/3 is a programmatic protected-call boundary, but its {:error, reason, _} surfaced the terminal-formatted error string — ANSI escape codes, the `at ::` header, the `Suggestion:` block, stack-trace frames, and a doubled `Lua runtime error: ... runtime error:` prefix — where a terse programmatic value was expected. Decouple the programmatic reason from the terminal render: - Extract the load-bearing §6.1 error_value/1 helper (formerly private in Lua.VM.Stdlib) into Lua.VM.ProtectedCall, the single source of truth for the Lua-facing error value at a protected-call boundary. pcall/xpcall now call it too. - do_call_function/3 carries the raw exception out of its rescue instead of a pre-rendered string. - call_function/3 projects that exception to the terse value via ProtectedCall.error_value/1 — exactly what pcall hands back: the source:line:-prefixed message for string errors, and raw table/number/ nil/false objects passed through verbatim (full pcall parity). - call_function!/3 keeps the rich render: it re-raises the original VM exception through Lua.RuntimeException (and now also populates :line/:source/:call_stack on the wrapper). reason may therefore now be a non-string Lua value, matching pcall. --- CHANGELOG.md | 11 ++ lib/lua.ex | 76 ++++++++----- lib/lua/vm/protected_call.ex | 18 +++ lib/lua/vm/stdlib.ex | 19 +--- test/lua/call_function_error_value_test.exs | 118 ++++++++++++++++++++ 5 files changed, 199 insertions(+), 43 deletions(-) create mode 100644 lib/lua/vm/protected_call.ex create mode 100644 test/lua/call_function_error_value_test.exs diff --git a/CHANGELOG.md b/CHANGELOG.md index d95ce8da..e49c0ef9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Fixed +- **`Lua.call_function/3` returns the terse Lua error value, not the terminal + render** (#336). Its `{:error, reason, _}` previously surfaced the + terminal-formatted error string — ANSI escape codes, the `at ::` + header, the `Suggestion:` block, stack-trace frames, and a doubled + `Lua runtime error: … runtime error:` prefix — where a programmatic value was + expected. `reason` is now exactly what `pcall` hands back (§6.1): the + `source:line:`-prefixed message for string errors, and the raw value + (table/number/`nil`/`false`) passed through verbatim for non-string error + objects. Note `reason` may therefore now be a non-string Lua value. The + raising variant `Lua.call_function!/3` is unchanged — it still raises a + `Lua.RuntimeException` carrying the rich formatted render. - **`pcall` passes the raised error value through as-is** (#334). Per Lua 5.3 §6.1, `error(value)` raises an arbitrary Lua value and `pcall` returns it verbatim as its second result — previously non-string values were diff --git a/lib/lua.ex b/lib/lua.ex index 5e3199e5..4f06e634 100644 --- a/lib/lua.ex +++ b/lib/lua.ex @@ -11,6 +11,7 @@ defmodule Lua do alias Lua.VM.Display alias Lua.VM.Executor alias Lua.VM.InternalError + alias Lua.VM.ProtectedCall alias Lua.VM.RuntimeError alias Lua.VM.State alias Lua.VM.Table @@ -729,41 +730,57 @@ defmodule Lua do """ @spec call_function(t(), term(), [term()]) :: {:ok, [term()], t()} | {:error, term(), t()} - def call_function(%__MODULE__{} = lua, %Display.Closure{ref: ref}, args) do - call_function(lua, ref, args) + def call_function(%__MODULE__{} = lua, name, args) do + finish_call(lua, resolve_and_call(lua, name, args)) end - def call_function(%__MODULE__{} = lua, %Display.NativeFunc{ref: ref}, args) do - call_function(lua, ref, args) + # `call_function/3` is a programmatic protected-call boundary. Its `:error` + # reason is the Lua-facing error value — exactly what `pcall` hands back via + # `ProtectedCall.error_value/1` (§6.1) — NOT the terminal-formatted render. + # The raising variant `call_function!/3` keeps the rich `ErrorFormatter` + # output by re-raising the original exception through `Lua.RuntimeException`. + defp finish_call(%__MODULE__{} = lua, {:ok, results, new_state}) do + {:ok, results, %{lua | state: new_state}} end - def call_function(%__MODULE__{state: state} = lua, func, args) when is_tuple(func) do - case do_call_function(func, args, state) do - {:ok, results, new_state} -> {:ok, results, %{lua | state: new_state}} - {:error, reason, new_state} -> {:error, reason, %{lua | state: new_state}} - end + defp finish_call(%__MODULE__{} = lua, {:error, e, new_state}) when is_exception(e) do + {:error, ProtectedCall.error_value(e), %{lua | state: new_state}} end - def call_function(%__MODULE__{} = lua, name, args) when is_function(name) do - {ref, lua} = encode!(lua, name) + defp finish_call(%__MODULE__{} = lua, {:error, reason, new_state}) do + {:error, reason, %{lua | state: new_state}} + end - case do_call_function(ref, args, lua.state) do - {:ok, results, new_state} -> {:ok, results, %{lua | state: new_state}} - {:error, reason, new_state} -> {:error, reason, %{lua | state: new_state}} - end + # Resolves `name`/`func` to a callable and invokes it under protection. + # Returns the raw `{:ok, results, new_state} | {:error, exception | reason, + # new_state}` (bare `Lua.VM.State`s); callers reattach the state to `lua`. + # On error the exception struct is carried out verbatim so each caller can + # project it differently (terse value vs. rich raise). + defp resolve_and_call(%__MODULE__{} = lua, %Display.Closure{ref: ref}, args) do + resolve_and_call(lua, ref, args) end - def call_function(%__MODULE__{} = lua, name, args) do + defp resolve_and_call(%__MODULE__{} = lua, %Display.NativeFunc{ref: ref}, args) do + resolve_and_call(lua, ref, args) + end + + defp resolve_and_call(%__MODULE__{state: state}, func, args) when is_tuple(func) do + do_call_function(func, args, state) + end + + defp resolve_and_call(%__MODULE__{} = lua, name, args) when is_function(name) do + {ref, lua} = encode!(lua, name) + do_call_function(ref, args, lua.state) + end + + defp resolve_and_call(%__MODULE__{} = lua, name, args) do keys = name |> List.wrap() |> Enum.map(&to_lua_key/1) func = do_get_nested(lua.state, keys) if func == nil or not is_tuple(func) do - {:error, "undefined function '#{inspect(func)}'", lua} + {:error, "undefined function '#{inspect(func)}'", lua.state} else - case do_call_function(func, args, lua.state) do - {:ok, results, new_state} -> {:ok, results, %{lua | state: new_state}} - {:error, reason, new_state} -> {:error, reason, %{lua | state: new_state}} - end + do_call_function(func, args, lua.state) end end @@ -771,7 +788,7 @@ defmodule Lua do {results, new_state} = fun.(args, state) {:ok, List.wrap(results), new_state} rescue - e -> {:error, Exception.message(e), recover_state(e, state)} + e -> {:error, e, recover_state(e, state)} end defp do_call_function({:lua_closure, proto, upvalues}, args, state) do @@ -789,7 +806,7 @@ defmodule Lua do {:ok, results, new_state} rescue - e -> {:error, Exception.message(e), recover_state(e, state)} + e -> {:error, e, recover_state(e, state)} end defp do_call_function({:compiled_closure, _, _} = closure, args, state) do @@ -798,7 +815,7 @@ defmodule Lua do {results, new_state} = Executor.call_function(closure, args, state) {:ok, results, new_state} rescue - e -> {:error, Exception.message(e), recover_state(e, state)} + e -> {:error, e, recover_state(e, state)} end defp do_call_function(other, _args, state) do @@ -829,9 +846,14 @@ defmodule Lua do """ @spec call_function!(t(), term(), [term()]) :: {[term()], t()} def call_function!(%__MODULE__{} = lua, func, args) do - case call_function(lua, func, args) do - {:ok, ret, lua} -> {ret, lua} - {:error, reason, lua} -> raise Lua.RuntimeException, {:lua_error, reason, lua.state} + # Unlike `call_function/3`, the raising variant keeps the rich + # `ErrorFormatter` render: re-raising the original VM exception through + # `Lua.RuntimeException` runs `Exception.message/1` (the terminal renderer) + # and copies its `:line` / `:source` / `:call_stack` onto the wrapper. + case resolve_and_call(lua, func, args) do + {:ok, ret, new_state} -> {ret, %{lua | state: new_state}} + {:error, e, _new_state} when is_exception(e) -> raise Lua.RuntimeException, e + {:error, reason, new_state} -> raise Lua.RuntimeException, {:lua_error, reason, new_state} end end diff --git a/lib/lua/vm/protected_call.ex b/lib/lua/vm/protected_call.ex new file mode 100644 index 00000000..dbb5681a --- /dev/null +++ b/lib/lua/vm/protected_call.ex @@ -0,0 +1,18 @@ +defmodule Lua.VM.ProtectedCall do + @moduledoc false + + # The Lua-facing error value handed back at a protected-call boundary + # (`pcall`/`xpcall`, and `Lua.call_function/3`), per §6.1: the raised value + # passes through verbatim. + # + # Clause ordering is load-bearing: + # 1. `error()`'s §6.1-prefixed string view (`RuntimeError.lua_value`). + # 2. Raw passthrough on KEY PRESENCE — `value: nil` (from `error()`) and + # `value: false` must match here so the boundary returns nil/false like + # PUC-Lua, never an `is_nil`-guarded fallthrough to clause 3. + # 3. `ArgumentError` (no `:value` field) and plain Elixir exceptions keep + # their message string. + def error_value(%{lua_value: lv}) when not is_nil(lv), do: lv + def error_value(%{value: value}), do: value + def error_value(e), do: Exception.message(e) +end diff --git a/lib/lua/vm/stdlib.ex b/lib/lua/vm/stdlib.ex index 7de9ab5d..b3a8e44a 100644 --- a/lib/lua/vm/stdlib.ex +++ b/lib/lua/vm/stdlib.ex @@ -10,6 +10,7 @@ defmodule Lua.VM.Stdlib do alias Lua.VM.AssertionError alias Lua.VM.Executor alias Lua.VM.Limits + alias Lua.VM.ProtectedCall alias Lua.VM.RuntimeError alias Lua.VM.State alias Lua.VM.Table @@ -239,7 +240,7 @@ defmodule Lua.VM.Stdlib do {[true | results], state} rescue e in [RuntimeError, AssertionError, TypeError, ArgumentError] -> - {[false, error_value(e)], State.unwind_to(state, e.state)} + {[false, ProtectedCall.error_value(e)], State.unwind_to(state, e.state)} e -> # Catch any other error @@ -259,7 +260,7 @@ defmodule Lua.VM.Stdlib do {[true | results], state} rescue e in [RuntimeError, AssertionError, TypeError, ArgumentError] -> - run_xpcall_handler(handler, error_value(e), State.unwind_to(state, e.state)) + run_xpcall_handler(handler, ProtectedCall.error_value(e), State.unwind_to(state, e.state)) e -> # Catch any other error @@ -278,20 +279,6 @@ defmodule Lua.VM.Stdlib do {[false, error_msg], State.unwind_to(state, raised_state(e))} end - # The Lua-facing error value handed back by pcall (and to xpcall's - # handler), per §6.1: the raised value passes through verbatim. - # - # Clause ordering is load-bearing: - # 1. `error()`'s §6.1-prefixed string view (`RuntimeError.lua_value`). - # 2. Raw passthrough on KEY PRESENCE — `value: nil` (from `error()`) and - # `value: false` must match here so pcall returns nil/false like - # PUC-Lua, never an `is_nil`-guarded fallthrough to clause 3. - # 3. `ArgumentError` (no `:value` field) and plain Elixir exceptions - # keep their message string. - defp error_value(%{lua_value: lv}) when not is_nil(lv), do: lv - defp error_value(%{value: value}), do: value - defp error_value(e), do: Exception.message(e) - # Raise-time state ferried out on VM exceptions; `nil` for anything else # (plain Elixir exceptions carry no Lua state). defp raised_state(%{state: %State{} = state}), do: state diff --git a/test/lua/call_function_error_value_test.exs b/test/lua/call_function_error_value_test.exs new file mode 100644 index 00000000..19e3ccd0 --- /dev/null +++ b/test/lua/call_function_error_value_test.exs @@ -0,0 +1,118 @@ +defmodule Lua.CallFunctionErrorValueTest do + @moduledoc """ + Pins the `Lua.call_function/3` protected-call boundary: its `{:error, + reason, _}` is the programmatic Lua error value — exactly what `pcall` + hands back (§6.1) — never the terminal-formatted render (ANSI, the + `at ::` header, the `Suggestion:` block, a stack trace, or a + doubled `Lua runtime error:` prefix). + + The raising variant `call_function!/3` is the opposite contract: it keeps + the rich `ErrorFormatter` render on the `Lua.RuntimeException` it raises. + """ + # async: false — one test toggles the global `:elixir` ANSI flag. + use ExUnit.Case, async: false + + defp fun!(code) do + {[ref], lua} = Lua.eval!(Lua.new(), "return #{code}", decode: false) + {ref, lua} + end + + describe "call_function/3 returns the terse Lua error value" do + test "a string error is not terminal-formatted" do + {ref, lua} = fun!("function() error('boom') end") + + assert {:error, reason, %Lua{}} = Lua.call_function(lua, ref, []) + + assert is_binary(reason) + assert reason =~ "boom" + refute reason =~ "\e[" + refute reason =~ "Suggestion" + refute reason =~ "Lua runtime error:" + refute reason =~ "runtime error:" + refute reason =~ "\n" + end + + test "a call-nil TypeError stays a terse one-line string" do + {ref, lua} = fun!("function() local f = nil; f() end") + + assert {:error, reason, %Lua{}} = Lua.call_function(lua, ref, []) + + assert is_binary(reason) + assert reason =~ "attempt to call a nil value" + refute reason =~ "\e[" + refute reason =~ "Suggestion" + refute reason =~ "\n" + end + + test "an index-nil TypeError stays a terse one-line string" do + {ref, lua} = fun!("function() local t = nil; return t.x end") + + assert {:error, reason, %Lua{}} = Lua.call_function(lua, ref, []) + + assert is_binary(reason) + assert reason =~ "attempt to index" + refute reason =~ "\e[" + refute reason =~ "\n" + end + end + + describe "call_function/3 passes non-string error objects through (pcall parity)" do + test "a table error object passes through verbatim" do + {ref, lua} = fun!("function() error({code = 1}) end") + + assert {:error, reason, %Lua{} = lua} = Lua.call_function(lua, ref, []) + assert Lua.decode!(lua, reason) == [{"code", 1}] + end + + test "a number error object passes through verbatim" do + {ref, lua} = fun!("function() error(42) end") + + assert {:error, 42, %Lua{}} = Lua.call_function(lua, ref, []) + end + + test "a nil error object passes through verbatim" do + {ref, lua} = fun!("function() error(nil) end") + + assert {:error, nil, %Lua{}} = Lua.call_function(lua, ref, []) + end + + test "a false error object passes through verbatim" do + {ref, lua} = fun!("function() error(false) end") + + assert {:error, false, %Lua{}} = Lua.call_function(lua, ref, []) + end + end + + describe "call_function/3 reason carries no ANSI even with a TTY attached" do + test "string error reason has no escape codes when ANSI is enabled" do + previous = Application.get_env(:elixir, :ansi_enabled) + Application.put_env(:elixir, :ansi_enabled, true) + on_exit(fn -> Application.put_env(:elixir, :ansi_enabled, previous) end) + + assert IO.ANSI.enabled?() + + {ref, lua} = fun!("function() error('boom') end") + assert {:error, reason, %Lua{}} = Lua.call_function(lua, ref, []) + + refute reason =~ "\e[" + end + end + + describe "call_function!/3 keeps the rich render" do + test "raises Lua.RuntimeException whose message carries the formatted render" do + {ref, lua} = fun!("function() error('boom') end") + + error = + assert_raise Lua.RuntimeException, fn -> + Lua.call_function!(lua, ref, []) + end + + message = Exception.message(error) + assert message =~ "Lua runtime error:" + assert message =~ "boom" + # The rich render includes the raw-message body that the terse + # programmatic reason deliberately omits. + assert message =~ "runtime error:" + end + end +end