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
409 changes: 409 additions & 0 deletions .agents/plans/A48-pcall-error-value-passthrough.md

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- **`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
stringified (`error({code = 1})` came back as `"table: 0x..."`). Structured
error objects, numbers, booleans, and `nil` now survive `pcall`/`xpcall`,
and the `xpcall` message handler receives the untouched value. String
messages gain the reference `source:line:` position prefix (suppressed by
`error(msg, 0)`); note `pcall`'s second result may therefore now be a
non-string Lua value. Host-facing `Lua.VM.RuntimeError` rendering is
unchanged.
- **Protected calls no longer roll back heap effects** (#331). When a function
called via `pcall`/`xpcall` (or `Lua.call_function/3` from Elixir) raised an
error, mutations made before the error — global writes, table field updates,
Expand Down
18 changes: 16 additions & 2 deletions lib/lua/vm/executor.ex
Original file line number Diff line number Diff line change
Expand Up @@ -487,8 +487,22 @@ defmodule Lua.VM.Executor do
def dispatcher_call_function({:compiled_closure, _, _} = closure, args, state, _proto, _name_hint),
do: call_function(closure, args, state)

def dispatcher_call_function({:native_func, _} = nf, args, state, _proto, _name_hint),
do: call_function(nf, args, state)
def dispatcher_call_function({:native_func, _} = nf, args, state, proto, _name_hint) do
# The dispatcher strips per-instruction line info at encode time, so any
# position visible here is a stale snapshot from an outer executor frame.
# Publish `{nil, source}` for the duration of the native call: raise
# sites that read `current_position/0` (e.g. `error()`'s §6.1 position
# prefix) then omit the line rather than attribute a wrong one. Restored
# after the call so nested invocations don't leak.
prev_pos = Process.get(@position_key, @unset)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Process dictionary is really a hack. I think this was from a previous design choice made for performance that we need to revisit

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we will evaluate this later

set_position(nil, proto.source)

try do
call_function(nf, args, state)
after
restore_position(prev_pos)
end
end

def dispatcher_call_function(other, args, state, proto, name_hint) do
case get_metatable(other, state) do
Expand Down
10 changes: 9 additions & 1 deletion lib/lua/vm/runtime_error.ex
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,15 @@ defmodule Lua.VM.RuntimeError do
# (pcall/xpcall) can keep heap effects made before the error instead of
# rolling back to their entry snapshot. It is out-of-band metadata: it never
# participates in `message` and stays `nil` when no state was in scope.
#
# `:lua_value` is Lua-facing only: when `error()` raises a string message,
# it carries the §6.1 `source:line:`-prefixed view that `pcall`/`xpcall`
# hand back to Lua code. It is NEVER read by `message`, `to_map`,
# `format_message`, `raw_message`, or `stringify` — those keep reading the
# raw `:value`, so host-facing rendering (which adds its own
# `at source:line:` header) never doubles the location.
@derive {Inspect, except: [:state]}
defexception [:value, :source, :message, :call_stack, :line, :state]
defexception [:value, :lua_value, :source, :message, :call_stack, :line, :state]

@impl true
def exception(opts) do
Expand All @@ -37,6 +44,7 @@ defmodule Lua.VM.RuntimeError do

%__MODULE__{
value: value,
lua_value: Keyword.get(opts, :lua_value),
source: source,
message: message,
call_stack: call_stack,
Expand Down
56 changes: 46 additions & 10 deletions lib/lua/vm/stdlib.ex
Original file line number Diff line number Diff line change
Expand Up @@ -163,23 +163,51 @@ defmodule Lua.VM.Stdlib do
{[], state}
end

# error(message) — raises a Lua runtime error.
# error(message [, level]) — raises a Lua runtime error.
# The executor stashes the calling source position in the process dict
# before invoking native callbacks (see `Lua.VM.Executor.execute/5`), so
# this raise picks up `at <source>:<line>:` automatically. If the function
# is called outside a Lua execution (or from a context where no line was
# set), `current_position/0` returns `{nil, nil}` and the message just
# omits the location.
defp lua_error([message | _], state) do
#
# Per Lua 5.3 §6.1 the raised value passes through pcall/xpcall verbatim,
# and string messages gain a `source:line:` prefix unless `level == 0`.
# The prefixed view lives in `:lua_value` (Lua-facing only); `:value`
# stays raw so host rendering is untouched. Levels >= 2 (attribute to the
# caller's caller) need per-frame lines the call stack does not carry and
# are treated as level 1 for now.
defp lua_error([message | rest], state) do
{line, source} = Executor.current_position()
raise RuntimeError, value: message, line: line, source: source, state: state
level = error_level(rest)

raise RuntimeError,
value: message,
lua_value: position_prefixed(message, level, line, source),
line: line,
source: source,
state: state
end

defp lua_error([], state) do
{line, source} = Executor.current_position()
raise RuntimeError, value: nil, line: line, source: source, state: state
end

defp error_level([level | _]) when is_number(level), do: level
defp error_level(_), do: 1

# §6.1 position prefix: only string messages, only when `level ~= 0`, and
# only when the executor recorded a usable position. A `{nil, _}` position
# (native call inside a compiled closure — the dispatcher does not plumb
# per-call lines yet) omits the prefix rather than emit a wrong line.
defp position_prefixed(message, level, line, source)
when is_binary(message) and level != 0 and is_integer(line) and is_binary(source) do
"#{source}:#{line}: #{message}"
end

defp position_prefixed(message, _level, _line, _source), do: message

# assert(v [, message]) — raises if v is falsy
defp lua_assert([value | rest], state) do
if value == nil or value == false do
Expand Down Expand Up @@ -211,8 +239,7 @@ defmodule Lua.VM.Stdlib do
{[true | results], state}
rescue
e in [RuntimeError, AssertionError, TypeError, ArgumentError] ->
error_msg = extract_error_message(e)
{[false, error_msg], State.unwind_to(state, e.state)}
{[false, error_value(e)], State.unwind_to(state, e.state)}

e ->
# Catch any other error
Expand All @@ -232,7 +259,7 @@ defmodule Lua.VM.Stdlib do
{[true | results], state}
rescue
e in [RuntimeError, AssertionError, TypeError, ArgumentError] ->
run_xpcall_handler(handler, extract_error_message(e), State.unwind_to(state, e.state))
run_xpcall_handler(handler, error_value(e), State.unwind_to(state, e.state))

e ->
# Catch any other error
Expand All @@ -251,10 +278,19 @@ defmodule Lua.VM.Stdlib do
{[false, error_msg], State.unwind_to(state, raised_state(e))}
end

# Extract error message from exception
defp extract_error_message(%{value: value}) when is_binary(value), do: value
defp extract_error_message(%{value: value}) when not is_nil(value), do: Value.to_string(value)
defp extract_error_message(e), do: Exception.message(e)
# 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).
Expand Down
Loading
Loading