diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ab5e30..dd61042 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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, diff --git a/guides/examples/chunks.livemd b/guides/examples/chunks.livemd index 8fd3617..9df6775 100644 --- a/guides/examples/chunks.livemd +++ b/guides/examples/chunks.livemd @@ -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)) ``` ``` +Failed to compile Lua! + Parse Error at line 1, column 11: diff --git a/lib/lua.ex b/lib/lua.ex index a1f4bcc..46936d3 100644 --- a/lib/lua.ex +++ b/lib/lua.ex @@ -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 @@ -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: - - - 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} -> @@ -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 @@ -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 @@ -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 ::` 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. @@ -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 value ( '')` + # 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 @@ -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 diff --git a/lib/lua/compiler_exception.ex b/lib/lua/compiler_exception.ex index ad26ad5..cdc80c7 100644 --- a/lib/lua/compiler_exception.ex +++ b/lib/lua/compiler_exception.ex @@ -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 diff --git a/lib/lua/vm/executor.ex b/lib/lua/vm/executor.ex index 92cd8cb..71536bc 100644 --- a/lib/lua/vm/executor.ex +++ b/lib/lua/vm/executor.ex @@ -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 value ( '')` 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), diff --git a/mix.exs b/mix.exs index 7910647..33cc32a 100644 --- a/mix.exs +++ b/mix.exs @@ -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" @@ -17,6 +20,9 @@ defmodule Lua.MixProject do Lua.Chunk, Lua.RuntimeException, Lua.CompilerException, + RuntimeError, + TypeError, + ArgumentError, Error, Eval ] @@ -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: [ diff --git a/test/lua/call_function_error_value_test.exs b/test/lua/call_function_error_value_test.exs index ed40431..da0035f 100644 --- a/test/lua/call_function_error_value_test.exs +++ b/test/lua/call_function_error_value_test.exs @@ -1,127 +1,150 @@ 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. + exception, _}` payload is the VM exception struct itself — a + `Lua.VM.RuntimeError`, `Lua.VM.TypeError`, or `Lua.VM.ArgumentError` — + carried out verbatim. The boundary does no rendering: callers own that by + calling `Exception.message/1`, and can pattern-match on the concrete struct + and its structured fields. The raw Lua value handed to `error()` (§6.1) is + preserved on the struct's `:value`, so pcall-parity data survives. + + The raising variant `call_function!/3` re-raises the same exception through + `Lua.RuntimeException`, keeping the rich `ErrorFormatter` render. """ - # async: false — one test toggles the global `:elixir` ANSI flag. - use ExUnit.Case, async: false + use ExUnit.Case, async: true + + alias Lua.VM.ArgumentError + alias Lua.VM.RuntimeError + alias Lua.VM.TypeError 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 + describe "call_function/3 returns the VM exception struct" do + test "error('boom') comes back as a RuntimeError carrying the raised value" do {ref, lua} = fun!("function() error('boom') end") - assert {:error, reason, %Lua{}} = Lua.call_function(lua, ref, []) + assert {:error, %RuntimeError{value: "boom"} = error, %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" + assert Exception.message(error) =~ "boom" end - test "a call-nil TypeError stays a terse one-line string" do + test "a call-nil failure comes back as a TypeError struct" do {ref, lua} = fun!("function() local f = nil; f() end") - assert {:error, reason, %Lua{}} = Lua.call_function(lua, ref, []) + assert {:error, %TypeError{error_kind: :call_nil} = error, %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" + assert Exception.message(error) =~ "attempt to call a nil value" end - test "an index-nil TypeError stays a terse one-line string" do + test "an index-nil failure comes back as a TypeError struct" do {ref, lua} = fun!("function() local t = nil; return t.x end") - assert {:error, reason, %Lua{}} = Lua.call_function(lua, ref, []) + assert {:error, %TypeError{error_kind: :index_non_table} = error, %Lua{}} = + Lua.call_function(lua, ref, []) - assert is_binary(reason) - assert reason =~ "attempt to index" - refute reason =~ "\e[" - refute reason =~ "\n" + assert Exception.message(error) =~ "attempt to index" end - test "a stdlib bad-argument ArgumentError stays a terse one-line string" do + test "a stdlib bad-argument failure comes back as an ArgumentError struct" do {ref, lua} = fun!(~S|function() for i in pairs("asdf") do end end|) - assert {:error, reason, %Lua{}} = Lua.call_function(lua, ref, []) + assert {:error, %ArgumentError{function_name: "pairs", arg_num: 1} = error, %Lua{}} = + Lua.call_function(lua, ref, []) - assert is_binary(reason) - assert reason =~ "bad argument #1 to 'pairs'" - assert reason =~ "table expected" - assert reason =~ "got string" - refute reason =~ "\e[" - refute reason =~ "at -no-source-" - refute reason =~ "\n" + message = Exception.message(error) + assert message =~ "bad argument #1 to 'pairs'" + assert message =~ "table expected" + assert message =~ "got string" 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") + describe "call_function/3 on a name that does not resolve to a function" do + test "an undefined name names what was looked up, not the resolved nil" do + {_, lua} = Lua.eval!(Lua.new(), "function foo() return 1 end") + + assert {:error, %TypeError{error_kind: :call_nil} = error, %Lua{}} = + Lua.call_function(lua, [:bar], []) - assert {:error, reason, %Lua{} = lua} = Lua.call_function(lua, ref, []) - assert Lua.decode!(lua, reason) == [{"code", 1}] + # Regression: previously reported the resolved value ("undefined + # function 'nil'"). It must name the requested global instead. + assert Exception.message(error) =~ "attempt to call a nil value (global 'bar')" end - test "a number error object passes through verbatim" do - {ref, lua} = fun!("function() error(42) end") + test "an existing non-function value reports its type, not 'undefined'" do + {_, lua} = Lua.eval!(Lua.new(), "x = 5") + + assert {:error, %TypeError{} = error, %Lua{}} = Lua.call_function(lua, [:x], []) - assert {:error, 42, %Lua{}} = Lua.call_function(lua, ref, []) + assert Exception.message(error) =~ "attempt to call a number value (global 'x')" end - test "a nil error object passes through verbatim" do - {ref, lua} = fun!("function() error(nil) end") + test "a nested path attributes to the final field" do + {_, lua} = Lua.eval!(Lua.new(), "t = {}") + + assert {:error, %TypeError{} = error, %Lua{}} = Lua.call_function(lua, [:t, :missing], []) - assert {:error, nil, %Lua{}} = Lua.call_function(lua, ref, []) + assert Exception.message(error) =~ "attempt to call a nil value (field 'missing')" end + end - test "a false error object passes through verbatim" do - {ref, lua} = fun!("function() error(false) end") + describe "call_function!/3 on an unresolved name keeps the rich render" do + test "raises with the location-less rich render and a suggestion" do + {_, lua} = Lua.eval!(Lua.new(), "function foo() return 1 end") + + error = + assert_raise Lua.RuntimeException, fn -> + Lua.call_function!(lua, [:bar], []) + end - assert {:error, false, %Lua{}} = Lua.call_function(lua, ref, []) + message = Exception.message(error) + assert message =~ "attempt to call a nil value (global 'bar')" + assert message =~ "Suggestion:" + # No Lua source position exists for a programmatic call, so no + # `at ::` header is rendered. + refute message =~ ~r/at \S+:\d+:/ + end + + test "the original TypeError carries the structured call-nil kind" do + {_, lua} = Lua.eval!(Lua.new(), "function foo() return 1 end") + + error = + assert_raise Lua.RuntimeException, fn -> + Lua.call_function!(lua, [:bar], []) + end + + assert %TypeError{error_kind: :call_nil} = error.original 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) + describe "call_function/3 preserves the raised Lua value on the struct (pcall parity)" do + test "a table error object is preserved on :value" do + {ref, lua} = fun!("function() error({code = 1}) end") - assert IO.ANSI.enabled?() + assert {:error, %RuntimeError{value: value}, %Lua{} = lua} = Lua.call_function(lua, ref, []) + assert Lua.decode!(lua, value) == [{"code", 1}] + end - {ref, lua} = fun!("function() error('boom') end") - assert {:error, reason, %Lua{}} = Lua.call_function(lua, ref, []) + test "a number error object is preserved on :value" do + {ref, lua} = fun!("function() error(42) end") - refute reason =~ "\e[" + assert {:error, %RuntimeError{value: 42}, %Lua{}} = Lua.call_function(lua, ref, []) end - test "ArgumentError 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) + test "a nil error object is preserved on :value" do + {ref, lua} = fun!("function() error(nil) end") - assert IO.ANSI.enabled?() + assert {:error, %RuntimeError{value: nil}, %Lua{}} = Lua.call_function(lua, ref, []) + end - {ref, lua} = fun!(~S|function() pairs("asdf") end|) - assert {:error, reason, %Lua{}} = Lua.call_function(lua, ref, []) + test "a false error object is preserved on :value" do + {ref, lua} = fun!("function() error(false) end") - refute reason =~ "\e[" + assert {:error, %RuntimeError{value: false}, %Lua{}} = Lua.call_function(lua, ref, []) end end @@ -152,7 +175,7 @@ defmodule Lua.CallFunctionErrorValueTest do Lua.call_function!(lua, ref, []) end - assert %Lua.VM.ArgumentError{ + assert %ArgumentError{ function_name: "pairs", arg_num: 1, expected: "table", @@ -168,7 +191,7 @@ defmodule Lua.CallFunctionErrorValueTest do Lua.call_function!(lua, ref, []) end - assert %Lua.VM.RuntimeError{value: "boom"} = error.original + assert %RuntimeError{value: "boom"} = error.original end test "TypeError passes through with error_kind for programmatic dispatch" do @@ -179,7 +202,7 @@ defmodule Lua.CallFunctionErrorValueTest do Lua.call_function!(lua, ref, []) end - assert %Lua.VM.TypeError{error_kind: :index_non_table} = error.original + assert %TypeError{error_kind: :index_non_table} = error.original end end diff --git a/test/lua/vm/pcall_state_preservation_test.exs b/test/lua/vm/pcall_state_preservation_test.exs index 326b6ec..8649c1c 100644 --- a/test/lua/vm/pcall_state_preservation_test.exs +++ b/test/lua/vm/pcall_state_preservation_test.exs @@ -521,8 +521,8 @@ defmodule Lua.VM.PcallStatePreservationTest do end """) - assert {:error, reason, lua} = Lua.call_function(lua, [:f], []) - assert reason =~ "boom" + assert {:error, %Lua.VM.RuntimeError{} = error, lua} = Lua.call_function(lua, [:f], []) + assert Exception.message(error) =~ "boom" assert Lua.get!(lua, [:x]) == 2 end diff --git a/test/lua_test.exs b/test/lua_test.exs index 7738e8e..21fd08a 100644 --- a/test/lua_test.exs +++ b/test/lua_test.exs @@ -174,31 +174,14 @@ defmodule LuaTest do end end - test "loading files with undefined functions returns an error" do - # Error message format differs from Luerl - Luerl raises CompilerException, - # new VM raises RuntimeException since undefined functions are a runtime error - # Original implementation: - # path = test_file("undefined_function") - # - # error = - # """ - # Failed to compile Lua! - # - # undefined function nil - # - # script line 1: () - # """ - # - # assert_raise Lua.CompilerException, error, fn -> - # Lua.load_file!(Lua.new(), path) - # end - # - # New VM implementation (raises RuntimeException instead): - # path = test_file("undefined_function") - # - # assert_raise Lua.RuntimeException, ~r/attempt to call a nil value/, fn -> - # Lua.load_file!(Lua.new(), path) - # end + test "loading a file that calls an undefined function raises a runtime error" do + # Calling an undefined function is a runtime error, not a compile error: + # the chunk compiles, then fails when the missing global resolves to nil. + path = test_file("undefined_function") + + assert_raise Lua.RuntimeException, ~r/attempt to call a nil value \(global 'bogus'\)/, fn -> + Lua.load_file!(Lua.new(), path) + end end test "it can load files with just comments" do @@ -347,22 +330,6 @@ defmodule LuaTest do assert match?({:tref, _}, Lua.unwrap(wrapped)) end - test "invalid functions raise" do - # The exact error message format differs from Luerl - # Original implementation: - # lua = Lua.new() - # - # error = """ - # Lua runtime error: undefined function nil - # - # script line 1: () - # """ - # - # assert_raise Lua.RuntimeException, error, fn -> - # Lua.eval!(lua, "bogus()") - # end - end - test "parsing errors raise" do # Original implementation used same regex pattern lua = Lua.new() @@ -489,20 +456,23 @@ defmodule LuaTest do end test "invalid strings raise Lua.CompilerException" do - # Original implementation (exact Luerl error message): - # message = """ - # Failed to compile Lua! - # - # Line 1: syntax error before: ';' - # """ - # - # assert_raise Lua.CompilerException, message, fn -> - # Lua.load_chunk!(Lua.new(), "local foo = ;") - # end + error = + assert_raise Lua.CompilerException, ~r/Failed to compile Lua/, fn -> + Lua.load_chunk!(Lua.new(), "local foo = ;") + end - assert_raise Lua.CompilerException, ~r/Failed to compile Lua/, fn -> - Lua.load_chunk!(Lua.new(), "local foo = ;") - end + # `parse_chunk/1` now hands back a `%Lua.CompilerException{}`; `load_chunk!/2` + # must re-raise it as-is. Regression guard: re-wrapping it via + # `raise Lua.CompilerException, formatted: exception` mangled the message + # into an inspected `{:formatted, %Lua.CompilerException{}}` tuple. + assert %Lua.CompilerException{errors: [msg]} = error + assert is_binary(msg) + assert msg =~ "Expected expression" + + message = Exception.message(error) + assert message =~ "Expected expression" + refute message =~ ":formatted" + refute message =~ "Lua.CompilerException" end test "chunks can be loaded multiple times" do @@ -692,25 +662,6 @@ defmodule LuaTest do Lua.eval!(lua, "return tables.map_table_with_state()") end end - - test "calling non-functions raises" do - # Error message format differs - # Original implementation: - # {_, lua} = - # Lua.eval!(""" - # foo = "bar" - # """) - # - # error = """ - # Lua runtime error: undefined function 'bar' - # - # - # """ - # - # assert_raise Lua.RuntimeException, error, fn -> - # Lua.call_function!(lua, :foo, []) - # end - end end describe "encode!/1 and decode!/1" do @@ -803,25 +754,6 @@ defmodule LuaTest do end describe "error messages" do - test "function doesn't exist" do - # Error message format differs from Luerl - # Original implementation: - # lua = Lua.new() - # - # error = """ - # Lua runtime error: undefined function nil - # - # script line 2: ("yuup") - # """ - # - # assert_raise Lua.RuntimeException, error, fn -> - # Lua.eval!(lua, """ - # local foo = 1 + 1 - # nope("yuup") - # """) - # end - end - test "missing quote" do # Original implementation (exact Luerl error messages): # error = """ @@ -863,91 +795,6 @@ defmodule LuaTest do end end - test "method that references property" do - # Requires setmetatable/__index - # Original implementation: - # lua = Lua.new() - # - # error = """ - # Lua runtime error: undefined function 'a' - # - # "a" with arguments ("b") - # ^--- self is incorrect for object with keys "name" - # - # - # script line 15 - # - # """ - # - # assert_raise Lua.RuntimeException, error, fn -> - # Lua.eval!(lua, """ - # Thing = {} - # Thing.__index = Thing - # - # function Thing.new(name) - # local self = setmetatable({}, Thing) - # self.name = name - # return self - # end - # - # function Thing:name() - # return self.name - # end - # - # local foo = Thing.new("a") - # foo:name("b") - # """) - # end - end - - test "function doesn't exist in nested function" do - # Error message format differs - # Original implementation: - # lua = Lua.new() - # - # error = """ - # Lua runtime error: undefined function nil - # - # script line 2: (\"dude\") - # script line 6: foo(2, \"dude\") - # script line 9: bar(1) - # """ - # - # assert_raise Lua.RuntimeException, error, fn -> - # Lua.eval!(lua, """ - # function foo(thing, name) - # doesnt_exist(name) - # end - # - # function bar(thing) - # foo(thing + 1, "dude") - # end - # - # bar(1) - # """) - # end - end - - test "api function that doesn't exist" do - # Error message format differs - # Original implementation: - # error = """ - # Lua runtime error: invalid index "nope" - # - # script line 5: thing() - # """ - # - # assert_raise Lua.RuntimeException, error, fn -> - # Lua.eval!(""" - # function thing() - # module.nope() - # end - # - # thing() - # """) - # end - end - test "erlang function called with the wrong arity" do defmodule Test do use Lua.API, scope: "test" @@ -1008,22 +855,6 @@ defmodule LuaTest do """) end end - - test "arithmetic exceptions are handled" do - # Division by zero handling differs in new VM - # Original implementation: - # error = """ - # Lua runtime error: bad arithmetic 5 / 0 - # - # - # """ - # - # assert_raise Lua.RuntimeException, error, fn -> - # lua = Lua.new() - # - # Lua.eval!(lua, "return 5 / 0") - # end - end end describe "set!/2 and get!/2" do diff --git a/test/test_helper.exs b/test/test_helper.exs index 81a9144..6b9c7da 100644 --- a/test/test_helper.exs +++ b/test/test_helper.exs @@ -1,8 +1,7 @@ # Error formatter output is gated on IO.ANSI.enabled?/0, which returns true # when stdout is a real TTY. Force it off so golden-snapshot tests are -# deterministic regardless of how the suite is launched. Tests that need -# ANSI on flip it locally and restore it via on_exit/1 (see -# test/lua/call_function_error_value_test.exs). +# deterministic regardless of how the suite is launched. A test that needs +# ANSI on should flip it locally and restore it via on_exit/1. Application.put_env(:elixir, :ansi_enabled, false) # `:differential` tests shell out to a reference `luac` and compare exact