Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <source>:<line>:`
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
Expand Down
76 changes: 49 additions & 27 deletions lib/lua.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -729,49 +730,65 @@ 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

defp do_call_function({:native_func, fun}, args, state) 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
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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

Expand Down
18 changes: 18 additions & 0 deletions lib/lua/vm/protected_call.ex
Original file line number Diff line number Diff line change
@@ -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
19 changes: 3 additions & 16 deletions lib/lua/vm/stdlib.ex
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down
118 changes: 118 additions & 0 deletions test/lua/call_function_error_value_test.exs
Original file line number Diff line number Diff line change
@@ -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 <source>:<line>:` 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
Loading