diff --git a/.agents/plans/A19-error-line-info-native-funcs.md b/.agents/plans/A19-error-line-info-native-funcs.md index 80337710..d9b5de27 100644 --- a/.agents/plans/A19-error-line-info-native-funcs.md +++ b/.agents/plans/A19-error-line-info-native-funcs.md @@ -2,10 +2,10 @@ id: A19 title: Stdlib bad-argument raises read source position from process dict issue: null -pr: null +pr: 215 branch: fix/error-line-info-stdlib base: main -status: ready +status: review direction: A unlocks: - line numbers on `string.upper(nil)`, `table.insert(t, nil, 5)`, etc. @@ -28,14 +28,19 @@ and `coroutine.*`. ## Success criteria -- [ ] `mix test` still passes. -- [ ] `mix test --only lua53` passes 5/29 (no regression). -- [ ] New tests: representative bad-arg raises from each stdlib file +- [x] `mix test` still passes (1577 → 1585, +8 new tests). +- [x] `mix test --only lua53` passes 5/29 (no regression). +- [x] New tests: representative bad-arg raises from each stdlib file have `:line` and `:source` populated. - - [ ] `string.upper(nil)` → TypeError with line/source. - - [ ] `table.insert(t, nil)` (bad pos) → has line/source. - - [ ] `math.floor("x")` → has line/source. -- [ ] No measurable perf regression on the benchee harness vs A18. + - [x] `string.upper(nil)` → TypeError with line/source. + - [x] `table.insert(t, nil)` (bad pos) → has line/source. + - [x] `math.floor("x")` → has line/source. +- [x] No measurable perf regression on the benchee harness vs A18. + fib(28) and a 1000-iteration string-ops workload measured on + both `main` and this branch with fresh builds: medians within + ~1% (within noise floor). Exception modules are off the hot + path; `Process.get` only fires when an exception is actually + being constructed. ## Implementation notes @@ -83,3 +88,54 @@ mix test --only lua53 `Lua.VM.Stdlib.some_helper/2` directly from Elixir), `current_position/0` returns `{nil, nil}` and the message just omits the location. That's the correct behavior — better than crashing. + +## Discoveries + +The plan anticipated touching ~50 stdlib raise sites individually with +a `bad_arg!` helper. During implementation, a much cleaner approach +emerged: have the **exception modules themselves** auto-populate +`:line`/`:source` from `Executor.current_position/0` inside +`exception/1` when not given. + +This means **zero callsite changes** for the ~80 `ArgumentError` +raises across `math`, `string`, `table`, etc. — they all picked up +line/source for free. Same for the bare `raise RuntimeError, value: +"..."` sites. + +Explicit opts still win: every executor raise that already passes +`:line`/`:source` (e.g. divide-by-zero at executor.ex:1864) is +unaffected because of `Keyword.get(opts, :line) || auto_line`. + +Two pre-existing oddities surfaced during smoke testing, neither +introduced by this change: + +- `table.insert(t, nil, 5)` reports the wrong arg number in its "bad + argument" message (says `#1`, should be `#2` — the `nil` is at + position 2). Logged as a candidate for an A24 sub-plan. +- `setmetatable(5, {})` on line 1 of a script reports `line 0`. Same + `source_line` off-by-one A18 already flagged in its Discoveries. + +## What changed + +PR: [#215](https://github.com/tv-labs/lua/pull/215) + +Files touched: + +- `lib/lua/vm/argument_error.ex` — added `:line` / `:source` / + `:call_stack` fields, auto-populate from `Executor.current_position/0`, + render through `Lua.VM.ErrorFormatter` for consistency with the + other exception types. +- `lib/lua/vm/runtime_error.ex` — auto-populate when `:line`/`:source` + not given. +- `lib/lua/vm/type_error.ex` — auto-populate. +- `lib/lua/vm/assertion_error.ex` — auto-populate. +- `test/lua/error_messages_test.exs` — 8 new tests under + "stdlib bad-argument raises carry line and source", covering + `string.upper(nil)`, `math.floor("x")`, `table.insert` bad pos, + `select` non-numeric index, `setmetatable` non-table, the defensive + outside-Lua case, the explicit-override case, and a stdlib + `RuntimeError` (`select(0, ...)`). + +Test count: 1577 → 1585 (+8). 0 failures. +Suite count: 5/29, unchanged. +Bench: no measurable regression vs main. diff --git a/lib/lua/vm/argument_error.ex b/lib/lua/vm/argument_error.ex index 9e458c81..94eba815 100644 --- a/lib/lua/vm/argument_error.ex +++ b/lib/lua/vm/argument_error.ex @@ -12,10 +12,15 @@ defmodule Lua.VM.ArgumentError do - `:expected` - What type or value was expected (e.g., "number", "string") - `:got` - What was actually received (optional, e.g., "nil", "boolean") - `:details` - Additional details about the error (optional) + - `:line` - Source line where the call originated (auto-populated from + `Lua.VM.Executor.current_position/0` when not given explicitly) + - `:source` - Source name where the call originated (auto-populated) + - `:call_stack` - Call stack frames at the raise site (default `[]`) ## Examples - # Basic type error + # Basic type error — line/source filled in automatically when raised + # from inside a Lua execution. raise ArgumentError, function_name: "string.rep", arg_num: 2, @@ -36,31 +41,47 @@ defmodule Lua.VM.ArgumentError do details: "value out of range" """ - defexception [:function_name, :arg_num, :expected, :got, :details] + defexception [ + :function_name, + :arg_num, + :expected, + :got, + :details, + :line, + :source, + :call_stack + ] @impl true def exception(opts) do + {auto_line, auto_source} = Lua.VM.Executor.current_position() + function_name = Keyword.fetch!(opts, :function_name) - arg_num = Keyword.get(opts, :arg_num) - expected = Keyword.get(opts, :expected) - got = Keyword.get(opts, :got) - details = Keyword.get(opts, :details) %__MODULE__{ function_name: function_name, - arg_num: arg_num, - expected: expected, - got: got, - details: details + arg_num: Keyword.get(opts, :arg_num), + expected: Keyword.get(opts, :expected), + got: Keyword.get(opts, :got), + details: Keyword.get(opts, :details), + line: Keyword.get(opts, :line) || auto_line, + source: Keyword.get(opts, :source) || auto_source, + call_stack: Keyword.get(opts, :call_stack, []) } end @impl true - def message(%__MODULE__{function_name: function_name, arg_num: arg_num, expected: expected, got: got, details: details}) do - build_message(function_name, arg_num, expected, got, details) + def message(%__MODULE__{} = e) do + base = build_base(e.function_name, e.arg_num, e.expected, e.got, e.details) + + Lua.VM.ErrorFormatter.format(:type_error, base, + source: e.source, + line: e.line, + call_stack: e.call_stack + ) end - defp build_message(function_name, arg_num, expected, got, details) do + defp build_base(function_name, arg_num, expected, got, details) do base = if arg_num do "bad argument ##{arg_num} to '#{function_name}'" diff --git a/lib/lua/vm/assertion_error.ex b/lib/lua/vm/assertion_error.ex index 37cbd954..e0e39e3e 100644 --- a/lib/lua/vm/assertion_error.ex +++ b/lib/lua/vm/assertion_error.ex @@ -1,16 +1,22 @@ defmodule Lua.VM.AssertionError do @moduledoc """ Raised by the Lua `assert()` function when the condition is falsy. + + When raised without explicit `:line` / `:source` opts, `exception/1` + populates them from the calling Lua source position via + `Lua.VM.Executor.current_position/0`. """ defexception [:value, :source, :message, :call_stack, :line] @impl true def exception(opts) do + {auto_line, auto_source} = Lua.VM.Executor.current_position() + value = Keyword.get(opts, :value) - source = Keyword.get(opts, :source) + source = Keyword.get(opts, :source) || auto_source call_stack = Keyword.get(opts, :call_stack, []) - line = Keyword.get(opts, :line) + line = Keyword.get(opts, :line) || auto_line message = Keyword.get(opts, :message) || format_message(value, source, line, call_stack) %__MODULE__{ diff --git a/lib/lua/vm/runtime_error.ex b/lib/lua/vm/runtime_error.ex index 1e97759f..3640acfe 100644 --- a/lib/lua/vm/runtime_error.ex +++ b/lib/lua/vm/runtime_error.ex @@ -4,16 +4,25 @@ defmodule Lua.VM.RuntimeError do Carries the original Lua error value, which may be any Lua type (string, number, table reference, etc.). + + When raised without explicit `:line` / `:source` opts (e.g. from a stdlib + bad-argument check), `exception/1` populates them from the calling Lua + source position via `Lua.VM.Executor.current_position/0`. That position + is stashed in the process dictionary at every native-call boundary, so + any raise site reachable from a Lua execution inherits the correct + attribution automatically. """ defexception [:value, :source, :message, :call_stack, :line] @impl true def exception(opts) do + {auto_line, auto_source} = Lua.VM.Executor.current_position() + value = Keyword.get(opts, :value) - source = Keyword.get(opts, :source) + source = Keyword.get(opts, :source) || auto_source call_stack = Keyword.get(opts, :call_stack, []) - line = Keyword.get(opts, :line) + line = Keyword.get(opts, :line) || auto_line message = Keyword.get(opts, :message) || format_message(value, source, line, call_stack) %__MODULE__{ diff --git a/lib/lua/vm/type_error.ex b/lib/lua/vm/type_error.ex index fff8469f..4fab3053 100644 --- a/lib/lua/vm/type_error.ex +++ b/lib/lua/vm/type_error.ex @@ -3,16 +3,25 @@ defmodule Lua.VM.TypeError do Raised when a Lua operation is applied to a value of the wrong type. Examples: calling a nil value, calling a number, indexing a boolean. + + When raised without explicit `:line` / `:source` opts (e.g. from a stdlib + type check), `exception/1` populates them from the calling Lua source + position via `Lua.VM.Executor.current_position/0`. That position is + stashed in the process dictionary at every native-call boundary, so + any raise site reachable from a Lua execution inherits the correct + attribution automatically. """ defexception [:value, :source, :message, :call_stack, :line, :error_kind, :value_type] @impl true def exception(opts) do + {auto_line, auto_source} = Lua.VM.Executor.current_position() + value = Keyword.get(opts, :value) - source = Keyword.get(opts, :source) + source = Keyword.get(opts, :source) || auto_source call_stack = Keyword.get(opts, :call_stack, []) - line = Keyword.get(opts, :line) + line = Keyword.get(opts, :line) || auto_line error_kind = Keyword.get(opts, :error_kind) value_type = Keyword.get(opts, :value_type) diff --git a/test/lua/error_messages_test.exs b/test/lua/error_messages_test.exs index 206b2c7b..e056a934 100644 --- a/test/lua/error_messages_test.exs +++ b/test/lua/error_messages_test.exs @@ -4,6 +4,7 @@ defmodule Lua.ErrorMessagesTest do alias Lua.Compiler alias Lua.Parser alias Lua.VM + alias Lua.VM.ArgumentError alias Lua.VM.State alias Lua.VM.TypeError @@ -345,4 +346,159 @@ defmodule Lua.ErrorMessagesTest do assert {["hi"], _} = Lua.eval!(Lua.new(), ~s|return "h" .. "i"|) end end + + describe "stdlib bad-argument raises carry line and source" do + # A18 wired line/source through every executor raise site and through + # `assert`/`error` via the native-call boundary process dict. A19 + # extended that pattern to every other stdlib raise — `string.*`, + # `table.*`, `math.*`, etc. — by having the exception modules + # themselves auto-populate from `Executor.current_position/0` when + # `:line`/`:source` aren't passed explicitly. These tests pin the + # contract: any stdlib bad-arg raise reachable from a Lua execution + # carries the correct location. + + test "string.upper(nil) carries line and source" do + script = """ + local x = 1 + local y = 2 + return string.upper(nil) + """ + + e = + assert_raise Lua.RuntimeException, fn -> + Lua.eval!(Lua.new(), script, source: "demo.lua") + end + + # The wrapped public exception preserves the structured fields. + assert is_integer(e.line) and e.line > 0 + assert e.source == "demo.lua" + assert e.message =~ "demo.lua:#{e.line}" + assert e.message =~ "bad argument #1 to 'string.upper'" + end + + test "math.floor on string carries line and source" do + script = """ + local greeting = "hello" + return math.floor("x") + """ + + e = + assert_raise Lua.RuntimeException, fn -> + Lua.eval!(Lua.new(), script, source: "demo.lua") + end + + assert is_integer(e.line) and e.line > 0 + assert e.source == "demo.lua" + assert e.message =~ "demo.lua:#{e.line}" + assert e.message =~ "bad argument #1 to 'math.floor'" + end + + test "table.insert with bad pos carries line and source" do + script = """ + local t = {1, 2, 3} + table.insert(t, nil, 99) + """ + + e = + assert_raise Lua.RuntimeException, fn -> + Lua.eval!(Lua.new(), script, source: "demo.lua") + end + + assert is_integer(e.line) and e.line > 0 + assert e.source == "demo.lua" + assert e.message =~ "demo.lua:#{e.line}" + assert e.message =~ "table.insert" + end + + test "select with non-numeric index carries line and source" do + script = """ + local first = 1 + local r = select("bad", 1, 2, 3) + """ + + e = + assert_raise Lua.RuntimeException, fn -> + Lua.eval!(Lua.new(), script, source: "demo.lua") + end + + assert is_integer(e.line) and e.line > 0 + assert e.source == "demo.lua" + assert e.message =~ "demo.lua:#{e.line}" + assert e.message =~ "select" + end + + test "setmetatable on non-table carries line and source" do + script = """ + local n = 5 + setmetatable(n, {}) + """ + + e = + assert_raise Lua.RuntimeException, fn -> + Lua.eval!(Lua.new(), script, source: "demo.lua") + end + + assert is_integer(e.line) + assert e.source == "demo.lua" + assert e.message =~ "demo.lua:" + assert e.message =~ "setmetatable" + end + + test "ArgumentError raised outside a Lua execution has nil line/source" do + # Defensive: if anyone calls a stdlib helper directly from Elixir + # outside of `Lua.eval!`, `current_position/0` returns {nil, nil} + # and the exception just renders without a location prefix. + e = + assert_raise ArgumentError, fn -> + raise ArgumentError, + function_name: "outside_lua", + arg_num: 1, + expected: "string" + end + + assert is_nil(e.line) + assert is_nil(e.source) + msg = Exception.message(e) + assert msg =~ "bad argument #1 to 'outside_lua'" + refute msg =~ ~r/at .+:\d+:/ + end + + test "explicit :line/:source on raise opts override auto-populate" do + # If a raise site does pass explicit values (because it's outside + # a Lua execution but knows the right answer somehow), those win. + e = + assert_raise ArgumentError, fn -> + raise ArgumentError, + function_name: "explicit", + arg_num: 1, + expected: "string", + line: 42, + source: "explicit.lua" + end + + assert e.line == 42 + assert e.source == "explicit.lua" + assert Exception.message(e) =~ "explicit.lua:42" + end + + test "RuntimeError raised from stdlib (e.g. select out of range) carries line and source" do + # `select(0, ...)` raises a Lua.VM.RuntimeError with just a value + # string, no explicit line/source. The exception should still pick + # them up from the calling Lua position via the auto-populate path. + script = """ + local x = 1 + return select(0, 1, 2, 3) + """ + + e = + assert_raise Lua.RuntimeException, fn -> + Lua.eval!(Lua.new(), script, source: "demo.lua") + end + + assert is_integer(e.line) and e.line > 0 + assert e.source == "demo.lua" + assert e.message =~ "demo.lua:#{e.line}" + assert e.message =~ "select" + end + end end