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
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,18 @@ is in the [`1.0.0-rc.0`](#100-rc0---2026-05-26) entry below.
shim that always returned `false` and was imported into every `use Lua.API`
module; the VM has no MFA references. Remove any `when is_mfa(value)` clauses
(they never matched).
- The public `{:error, _}`-returning APIs now hand back the exception struct
uniformly, instead of a pre-rendered message string, so callers own
rendering (`Exception.message/1`) and can pattern-match the concrete error.
- `Lua.call_function/3` returns `{:error, exception, lua}` where `exception`
is the VM struct (`Lua.VM.RuntimeError`, `Lua.VM.TypeError`,
`Lua.VM.ArgumentError`, …). The raised Lua value (`error(42)`, a table,
`nil`, `false`) is preserved on the struct's `:value`, matching what
`pcall` hands back inside Lua. Code matching on a string reason should
switch to the struct (or call `Exception.message/1` on it).
- `Lua.parse_chunk/1` returns `{:error, %Lua.CompilerException{}}` instead of
`{:error, [String.t()]}`. The formatted diagnostics are on the
exception's `:errors` field; `Exception.message/1` renders them.

### Changed
- `Lua.new/1`'s `:max_string_bytes` now accepts `:infinity` for no limit,
Expand Down
10 changes: 7 additions & 3 deletions guides/examples/chunks.livemd
Original file line number Diff line number Diff line change
Expand Up @@ -53,16 +53,20 @@ end

`Lua.parse_chunk/1` pre-parses a script so you can surface syntax errors
before ever running anything. It returns `{:ok, chunk}` on success and
`{:error, messages}` with human-readable diagnostics on failure.
`{:error, %Lua.CompilerException{}}` on failure. Call `Exception.message/1`
to render the human-readable diagnostics (or read the formatted list off the
exception's `:errors` field).

```elixir
{:error, [message]} = Lua.parse_chunk("return 1 +")
IO.puts(message)
{:error, error} = Lua.parse_chunk("return 1 +")
IO.puts(Exception.message(error))
```

<!-- livebook:{"output":true} -->

```
Failed to compile Lua!

Parse Error

at line 1, column 11:
Expand Down
101 changes: 67 additions & 34 deletions lib/lua.ex
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ 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 @@ -630,16 +629,17 @@ defmodule Lua do

iex> {:ok, %Lua.Chunk{}} = Lua.parse_chunk("local foo = 1")

Errors found during parsing will be returned as a list of formatted strings
Errors found during parsing are returned as a `Lua.CompilerException`. Call
`Exception.message/1` to render them, or read the formatted list off its
`:errors` field:

<!-- Old Luerl error format: Lua.parse_chunk("local foo =;") returned {:error, ["Line 1: syntax error before: ';'"]} -->

iex> {:error, [msg]} = Lua.parse_chunk("local foo =;")
iex> {:error, %Lua.CompilerException{} = error} = Lua.parse_chunk("local foo =;")
iex> [msg] = error.errors
iex> msg =~ "Expected expression"
true

"""
@spec parse_chunk(String.t()) :: {:ok, Lua.Chunk.t()} | {:error, [String.t()]}
@spec parse_chunk(String.t()) :: {:ok, Lua.Chunk.t()} | {:error, Lua.CompilerException.t()}
def parse_chunk(code) do
case Lua.Parser.parse(code) do
{:ok, ast} ->
Expand All @@ -648,11 +648,11 @@ defmodule Lua do
{:ok, %Lua.Chunk{prototype: proto}}

{:error, msg} ->
{:error, List.wrap(msg)}
{:error, Lua.CompilerException.exception(msg)}
end

{:error, msg} ->
{:error, List.wrap(msg)}
{:error, Lua.CompilerException.exception(msg)}
end
end

Expand All @@ -674,7 +674,7 @@ defmodule Lua do
def load_chunk!(%__MODULE__{} = lua, code) when is_binary(code) do
case parse_chunk(code) do
{:ok, chunk} -> {chunk, lua}
{:error, errors} -> raise Lua.CompilerException, formatted: errors
{:error, %Lua.CompilerException{} = exception} -> raise exception
end
end

Expand Down Expand Up @@ -707,46 +707,53 @@ defmodule Lua do

## Errors

When the function raises, `call_function/3` returns `{:error, reason, lua}`.
Unlike the raising `call_function!/3`, `reason` is the raw Lua-facing error
value — exactly what `pcall` would hand back — not a terminal-formatted
message. A non-string error value passes through verbatim:

iex> {[ref], lua} = Lua.eval!(Lua.new(), "return function() error(42) end", decode: false)
iex> {:error, reason, _lua} = Lua.call_function(lua, ref, [])
iex> reason
42

A string passed to `error` comes back with Lua's `source:line:` position
prefix as a single-line string (no ANSI, no `"Lua runtime error:"` header):
When the function raises, `call_function/3` returns `{:error, exception,
lua}`, where `exception` is the Lua VM exception struct — a
`Lua.VM.RuntimeError`, `Lua.VM.TypeError`, `Lua.VM.ArgumentError`, etc. Call
`Exception.message/1` yourself to render it; unlike the raising
`call_function!/3`, the boundary does *not* pre-render it (no ANSI, no
`at <source>:<line>:` header, no `Suggestion:` block).

iex> {[ref], lua} = Lua.eval!(Lua.new(), "return function() error('boom') end", decode: false)
iex> {:error, reason, _lua} = Lua.call_function(lua, ref, [])
iex> reason =~ "boom"
iex> {:error, exception, _lua} = Lua.call_function(lua, ref, [])
iex> Exception.message(exception) =~ "boom"
true

The raised Lua value is preserved on the struct — exactly what `pcall` hands
back inside Lua. `error(42)` carries `42` on the `RuntimeError`'s `:value`:

iex> {[ref], lua} = Lua.eval!(Lua.new(), "return function() error(42) end", decode: false)
iex> {:error, exception, _lua} = Lua.call_function(lua, ref, [])
iex> exception.value
42

"""
@spec call_function(t(), term(), [term()]) ::
{:ok, [term()], t()} | {:error, term(), t()}
{:ok, [term()], t()} | {:error, Exception.t(), t()}
def call_function(%__MODULE__{} = lua, name, args) do
finish_call(lua, resolve_and_call(lua, name, args))
end

# `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`.
# payload is the VM exception struct itself, carried out verbatim so callers
# own the rendering (`Exception.message/1`) and can pattern-match on the
# concrete error struct. In-Lua `pcall`/`xpcall` still project the raw §6.1
# value via `ProtectedCall.error_value/1`; this boundary deliberately does
# not. The raising variant `call_function!/3` re-raises the same exception
# through `Lua.RuntimeException` to get the rich `ErrorFormatter` render.
defp finish_call(%__MODULE__{} = lua, {:ok, results, new_state}) do
{:ok, results, %{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}}
{:error, e, %{lua | state: new_state}}
end

# Defensive: every `resolve_and_call/3` error path yields an exception today.
# If a bare Lua value ever reaches here, wrap it so the boundary's contract
# stays uniform — the `:error` payload is always an exception struct.
defp finish_call(%__MODULE__{} = lua, {:error, reason, new_state}) do
{:error, reason, %{lua | state: new_state}}
{:error, %RuntimeError{value: reason}, %{lua | state: new_state}}
end

# Resolves `name`/`func` to a callable and invokes it under protection.
Expand Down Expand Up @@ -775,10 +782,26 @@ defmodule Lua 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.state}
else
if is_tuple(func) do
do_call_function(func, args, lua.state)
else
# Report the *name that was looked up* — not the resolved `nil` — and
# reuse the VM's `attempt to call a <type> value (<namewhat> '<name>')`
# phrasing so the programmatic boundary matches an in-Lua call.
error = Executor.call_type_error(func, call_target_hint(name), lua.state)
{:error, error, lua.state}
end
end

# Derives a `format_target_hint/1` tag from the name passed to
# `call_function/3`. A bare name (`:foo` / `"foo"` / `[:foo]`) reads as a
# global; a nested path (`[:string, :lower]`) attributes to the final field,
# mirroring how Lua names the field it failed to resolve to a function.
defp call_target_hint(name) do
case List.wrap(name) do
[] -> nil
[single] -> {:global, to_string(single)}
segments -> {:field, to_string(List.last(segments))}
end
end

Expand Down Expand Up @@ -816,8 +839,18 @@ defmodule Lua do
e -> {:error, e, recover_state(e, state)}
end

# A resolved tuple that isn't one of the callable shapes above — e.g. a
# table or userdata reference. No name is available at this layer, so the
# error is reported by type without a name hint.
#
# This is one place the programmatic boundary does *not* mirror the in-Lua
# `:call` opcode: a table carrying a `__call` metamethod is reported as
# "attempt to call a table value" here rather than invoking the metamethod.
# `call_function/3` is a by-name function-call entry point, not a general
# value-application path, so callable tables are out of scope (and the prior
# implementation errored on them too).
defp do_call_function(other, _args, state) do
{:error, "undefined function '#{inspect(other)}'", state}
{:error, Executor.call_type_error(other, nil, state), state}
end

# This is a protected-call boundary like pcall: trapping the error
Expand Down
2 changes: 2 additions & 0 deletions lib/lua/compiler_exception.ex
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ defmodule Lua.CompilerException do
"""
alias Lua.Util

@type t :: %__MODULE__{}

defexception [:errors]

def exception(formatted: errors) when is_list(errors) do
Expand Down
31 changes: 31 additions & 0 deletions lib/lua/vm/executor.ex
Original file line number Diff line number Diff line change
Expand Up @@ -3022,6 +3022,37 @@ defmodule Lua.VM.Executor do
end
end

# Builds (does not raise) the `Lua.VM.TypeError` for an attempt to call a
# non-callable value, matching the wording the `:call` opcode raises inside
# the VM.
#
# Used by the programmatic `Lua.call_function/3` boundary, which resolves a
# name to a value itself and must report an uncallable value with the same
# `attempt to call a <type> value (<namewhat> '<name>')` phrasing, structured
# `:error_kind`, and suggestion the in-Lua path produces. Returned as a struct
# (not raised) so `Lua.call_function/3` can hand it to its protected-call
# boundary while `Lua.call_function!/3` re-raises it for the rich render.
#
# `name_hint` is a `format_target_hint/1` tag (e.g. `{:global, "bar"}`) or
# `nil` when no name is known.
@doc false
@spec call_type_error(term(), term(), State.t()) :: TypeError.t()
def call_type_error(value, name_hint, %State{} = state) do
{error_kind, value_type} =
case value do
nil -> {:call_nil, nil}
other -> {:call_non_function, value_type(other)}
end

TypeError.exception(
value: "attempt to call a #{Value.type_name(value)} value" <> format_target_hint(name_hint),
call_stack: state.call_stack,
error_kind: error_kind,
value_type: value_type,
state: state
)
end

defp raise_index_type_error(value, line, source, name_hint, state) do
raise TypeError,
value: "attempt to index a #{Value.type_name(value)} value" <> format_target_hint(name_hint),
Expand Down
23 changes: 22 additions & 1 deletion mix.exs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ defmodule Lua.MixProject do
use Mix.Project

alias Lua.Parser.Error
alias Lua.VM.ArgumentError
alias Lua.VM.RuntimeError
alias Lua.VM.TypeError
alias Mix.Tasks.Lua.Eval

@url "https://github.com/tv-labs/lua"
Expand All @@ -17,6 +20,9 @@ defmodule Lua.MixProject do
Lua.Chunk,
Lua.RuntimeException,
Lua.CompilerException,
RuntimeError,
TypeError,
ArgumentError,
Error,
Eval
]
Expand Down Expand Up @@ -53,9 +59,24 @@ defmodule Lua.MixProject do
source_ref: "v#{@version}",
# Render only the curated public surface; keep internals in source/IEx.
filter_modules: fn module, _meta -> module in @public_modules end,
# The public VM exception structs' moduledocs name internal plumbing
# (`Lua.VM.Executor`, `Lua.VM.ErrorFormatter`) that stays filtered.
# Render those references as plain code instead of autolinking to
# filtered pages, which errors under `--warnings-as-errors`.
skip_code_autolink_to: [
"Lua.VM.Executor.current_position/0",
"Lua.VM.ErrorFormatter.to_map/3"
],
groups_for_modules: [
Core: [Lua, Lua.API, Lua.Table, Lua.Chunk],
Errors: [Lua.RuntimeException, Lua.CompilerException, Error],
Errors: [
Lua.RuntimeException,
Lua.CompilerException,
RuntimeError,
TypeError,
ArgumentError,
Error
],
"Mix Tasks": [Eval]
],
extras: [
Expand Down
Loading
Loading