diff --git a/.agents/plans/A40-arith-name-hints.md b/.agents/plans/A40-arith-name-hints.md new file mode 100644 index 00000000..bc042797 --- /dev/null +++ b/.agents/plans/A40-arith-name-hints.md @@ -0,0 +1,193 @@ +--- +id: A40 +title: Thread name hints into arithmetic & bitwise type errors +issue: 252 +pr: 270 +branch: errors/arith-bitwise-hints +base: main +status: review +direction: A +unlocks: + - math.lua (reason narrowed) + - sort.lua (reason narrowed) + - errors.lua (reason narrowed) + - strings.lua (reason narrowed) +--- + +## Goal + +Append PUC-Lua-style `(global 'X')` / `(local 'X')` / `(upvalue 'X')` / +`(field 'X')` hints to arithmetic and bitwise type errors and to the +"number has no integer representation" error. This closes the +remaining half of #252 — the wording already aligns; only the trailing +hint suffix is missing. + +## Out of scope + +- Hints on `:concatenate` errors (separate raise path, much smaller + unlock for the suite). +- Hints on `:length`-on-non-string-table errors. +- Hints on metamethod-dispatch failures (`__add` value not callable). +- Audit of `bad argument #N to 'X' (T expected, got T)` wording — + the templates already match PUC-Lua. If a divergence surfaces + during testing, open a follow-up. +- Field-hint extraction across `:move` chains. We hint only when the + failing operand is *directly* a variable/property reference in the + AST. This matches PUC-Lua, which also tracks at the call site. + +## Success criteria + +- [ ] `mix test` passes with no regressions (baseline: 1955 passed, + 25 skipped). +- [ ] New pin tests in `test/lua/vm/error_format_test.exs` for each + of `{:global, :local, :upvalue, :field}` × `{arithmetic, + bitwise, integer-representation}`. +- [ ] At least one of `math.lua`, `sort.lua`, `errors.lua`, + `strings.lua` either passes fully or has its `:all` skip + narrowed to a smaller line range. +- [ ] `mix dialyzer` — no new errors. +- [ ] `mix format --check-formatted`. + +## Implementation notes + +### Approach: bake hints into the instruction tuple at codegen time + +This mirrors how `:get_field`, `:set_field`, `:call`, and `:self` +already carry hints (`lib/lua/compiler/instruction.ex`). The codegen +has a working `name_hint/2` resolver +(`lib/lua/compiler/codegen.ex:1641-1659`) that turns an `Expr.Var` or +`Expr.Property` AST node into `{:global|:local|:upvalue|:field, name}`. +The executor has `format_target_hint/1` +(`lib/lua/vm/executor.ex:1974-1991`) that renders those tuples into +` (field 'X')` suffixes. + +The work is to: + +1. Resolve the operand AST → hint tuple at codegen time and store it + in the instruction tuple alongside the register indices. +2. Match the new tuple shape in the executor; on the failure path, + forward the hint of the *failing* operand to the raise helper. +3. Append the formatted hint to the error message. + +### Files to modify + +#### `lib/lua/compiler/instruction.ex` + +Extend constructors with optional trailing `hint_a`/`hint_b` (or a +single `hint` for unary): + +- `add/subtract/multiply/divide/floor_divide/modulo/power` (binary) +- `negate` (unary) +- `bitwise_and/bitwise_or/bitwise_xor/shift_left/shift_right` (binary) +- `bitwise_not` (unary) + +All hints default to `nil`. + +#### `lib/lua/compiler/codegen.ex` + +At lines 910–966, the `left`/`right` AST nodes are in scope when the +binop/unop instruction is emitted. Call `name_hint(left, ctx)` / +`name_hint(right, ctx)` and pass to the `Instruction.*` constructor. +Apply only to arith/bitwise — comparison ops don't take this path. + +#### `lib/lua/vm/executor.ex` + +- Update each `do_execute([{:op, ...} | rest], ...)` pattern for the + 14 arith/bitwise opcodes to match the new tuple shape (binary ops + have both a fast int-int clause and a fallback clause; unary has a + single clause). +- Pass the operand hints through to the `safe_*` helpers. On the + `{:error, val}` path, select the hint corresponding to `val` + (whichever operand failed `to_number`) and forward to + `raise_arith_type_error`. +- `raise_arith_type_error/3` → arity 4 with `hint`; append + `format_target_hint(hint)` to the value string. Same pattern as + `raise_index_type_error/4` at line 1961. +- `to_integer!/3` and `float_to_integer!/2`: add a `hint` parameter + and append the formatted hint. Critical for `math.huge << 1` → + `"number has no integer representation (field 'huge')"`. Update all + callsites in `:bitwise_*` / `:shift_*` clauses to thread the + matching operand hint. + +#### `lib/lua/compiler/bytecode.ex` + +Line ~130 encodes instructions for `.luac` serialization. The new +tuple arity will break round-trip if any on-disk bytecode exists. +Strategy: strip hints on encode (they're debug info; missing-on-disk +is acceptable degradation). Implement by destructuring the new shape +and writing the same `{@op_X, dest, a, b}` form. + +#### Tests + +`test/lua/vm/error_format_test.exs` — pin each rendering: + +- `return foo + 1` (foo nil global) → `"attempt to perform + arithmetic on a nil value (global 'foo')"` +- `local x; return -x` → `"... (local 'x')"` +- `local t = {}; return t.x + 1` → `"... (field 'x')"` +- `function outer() local y; return function() return y + 1 end end` + via the returned closure → `"... (upvalue 'y')"` +- `return math.huge << 1` → `"number has no integer representation + (field 'huge')"` +- `local s = 'x'; return s << 1` → `"... (local 's')"` + +#### `test/lua53_skips.exs` + +After the implementation goes green, comment out the `:all` skip for +`math.lua`, `sort.lua`, `errors.lua`, and `strings.lua` one at a time +and run the suite. Narrow each to the smallest line range that still +fails for *non-wording* reasons. Update the `reason:` to describe the +narrowed cause. + +### Critical files (quick reference) + +- `lib/lua/vm/executor.ex` — arith patterns at 979–1135 (`:add` + through `:power`/`:negate`), bitwise at 1141–1216; helpers at 2269 + (arith raise), 2517–2562 (`to_integer!` / `float_to_integer!`), + format helpers at 1961 / 1974–1991. +- `lib/lua/compiler/codegen.ex` — emit sites at 910–966; + `name_hint/2` at 1641–1659. +- `lib/lua/compiler/instruction.ex` — constructors at 40–56. + +## Verification + +```bash +mix format +mix compile --warnings-as-errors +mix test +mix test test/lua/vm/error_format_test.exs +mix test test/lua/vm/arithmetic_test.exs +mix test test/lua/vm/bitwise_test.exs +mix dialyzer +``` + +Then, with skip ranges narrowed: + +```bash +mix test --include skip +``` + +Expected: math.lua / sort.lua / errors.lua / strings.lua either fully +pass or fail at a *narrower* line range (with a reason other than +"checkerror format mismatch"). + +## Risks + +- Tuple shape change ripples to every `:add`/`:subtract`/… match site. + Easy to miss a clause — exhaustive search for `{:op,` patterns in + the executor before declaring done. +- Bytecode round-trip: the bytecode encoder/decoder must agree on + arity. If both sides strip the hint, behaviour is identical to + in-memory execution minus the hint suffix on errors after a `luac` + reload. +- The suite skips may not narrow as much as hoped if non-wording + blockers remain (`math.huge` finite, `os.clock` missing, etc.). + That's still an honest closure of #252 — the wording half is done. + +## Discoveries + +(populated during implementation) + +## What changed + +(populated when PR opens) diff --git a/lib/lua/compiler/bytecode.ex b/lib/lua/compiler/bytecode.ex index 34627a40..ce666e0f 100644 --- a/lib/lua/compiler/bytecode.ex +++ b/lib/lua/compiler/bytecode.ex @@ -127,14 +127,19 @@ defmodule Lua.Compiler.Bytecode do defp encode({:get_field, dest, table_reg, name, name_hint}), do: {:ok, {@op_get_field, dest, table_reg, name, name_hint}} - defp encode({:add, dest, a, b}), do: {:ok, {@op_add, dest, a, b}} - defp encode({:subtract, dest, a, b}), do: {:ok, {@op_subtract, dest, a, b}} - defp encode({:multiply, dest, a, b}), do: {:ok, {@op_multiply, dest, a, b}} - defp encode({:divide, dest, a, b}), do: {:ok, {@op_divide, dest, a, b}} - defp encode({:floor_divide, dest, a, b}), do: {:ok, {@op_floor_divide, dest, a, b}} - defp encode({:modulo, dest, a, b}), do: {:ok, {@op_modulo, dest, a, b}} - defp encode({:power, dest, a, b}), do: {:ok, {@op_power, dest, a, b}} - defp encode({:negate, dest, src}), do: {:ok, {@op_negate, dest, src}} + # Arithmetic instructions carry per-operand hint tuples for error + # attribution. The v2 dispatcher threads them into + # `Executor.dispatcher_binop/7` / `dispatcher_unop/5` so on-disk + # bytecode preserves the hint suffix (e.g. `(local 'n')`) on + # arithmetic type errors. + defp encode({:add, dest, a, b, hint_a, hint_b}), do: {:ok, {@op_add, dest, a, b, hint_a, hint_b}} + defp encode({:subtract, dest, a, b, hint_a, hint_b}), do: {:ok, {@op_subtract, dest, a, b, hint_a, hint_b}} + defp encode({:multiply, dest, a, b, hint_a, hint_b}), do: {:ok, {@op_multiply, dest, a, b, hint_a, hint_b}} + defp encode({:divide, dest, a, b, hint_a, hint_b}), do: {:ok, {@op_divide, dest, a, b, hint_a, hint_b}} + defp encode({:floor_divide, dest, a, b, hint_a, hint_b}), do: {:ok, {@op_floor_divide, dest, a, b, hint_a, hint_b}} + defp encode({:modulo, dest, a, b, hint_a, hint_b}), do: {:ok, {@op_modulo, dest, a, b, hint_a, hint_b}} + defp encode({:power, dest, a, b, hint_a, hint_b}), do: {:ok, {@op_power, dest, a, b, hint_a, hint_b}} + defp encode({:negate, dest, src, hint}), do: {:ok, {@op_negate, dest, src, hint}} defp encode({:less_than, dest, a, b}), do: {:ok, {@op_less_than, dest, a, b}} defp encode({:less_equal, dest, a, b}), do: {:ok, {@op_less_equal, dest, a, b}} diff --git a/lib/lua/compiler/codegen.ex b/lib/lua/compiler/codegen.ex index 2e768318..6b6fe111 100644 --- a/lib/lua/compiler/codegen.ex +++ b/lib/lua/compiler/codegen.ex @@ -908,6 +908,14 @@ defmodule Lua.Compiler.Codegen do end defp gen_expr(%Expr.BinOp{op: op, left: left, right: right}, ctx) do + # Resolve operand origin hints before codegen consumes them so the + # executor can render PUC-Lua-style `(field 'huge')` / `(global 'x')` + # suffixes on arithmetic / bitwise type errors. Only meaningful for + # ops that can raise on operand type — comparisons and concat go + # through different raise paths. + hint_a = name_hint(left, ctx) + hint_b = name_hint(right, ctx) + # Generate code for left operand {left_instructions, left_reg, ctx} = gen_expr(left, ctx) @@ -921,18 +929,18 @@ defmodule Lua.Compiler.Codegen do # Generate the operation instruction operation_instruction = case op do - :add -> Instruction.add(dest_reg, left_reg, right_reg) - :sub -> Instruction.subtract(dest_reg, left_reg, right_reg) - :mul -> Instruction.multiply(dest_reg, left_reg, right_reg) - :div -> Instruction.divide(dest_reg, left_reg, right_reg) - :floordiv -> Instruction.floor_divide(dest_reg, left_reg, right_reg) - :mod -> Instruction.modulo(dest_reg, left_reg, right_reg) - :pow -> Instruction.power(dest_reg, left_reg, right_reg) - :band -> Instruction.bitwise_and(dest_reg, left_reg, right_reg) - :bor -> Instruction.bitwise_or(dest_reg, left_reg, right_reg) - :bxor -> Instruction.bitwise_xor(dest_reg, left_reg, right_reg) - :shl -> Instruction.shift_left(dest_reg, left_reg, right_reg) - :shr -> Instruction.shift_right(dest_reg, left_reg, right_reg) + :add -> Instruction.add(dest_reg, left_reg, right_reg, hint_a, hint_b) + :sub -> Instruction.subtract(dest_reg, left_reg, right_reg, hint_a, hint_b) + :mul -> Instruction.multiply(dest_reg, left_reg, right_reg, hint_a, hint_b) + :div -> Instruction.divide(dest_reg, left_reg, right_reg, hint_a, hint_b) + :floordiv -> Instruction.floor_divide(dest_reg, left_reg, right_reg, hint_a, hint_b) + :mod -> Instruction.modulo(dest_reg, left_reg, right_reg, hint_a, hint_b) + :pow -> Instruction.power(dest_reg, left_reg, right_reg, hint_a, hint_b) + :band -> Instruction.bitwise_and(dest_reg, left_reg, right_reg, hint_a, hint_b) + :bor -> Instruction.bitwise_or(dest_reg, left_reg, right_reg, hint_a, hint_b) + :bxor -> Instruction.bitwise_xor(dest_reg, left_reg, right_reg, hint_a, hint_b) + :shl -> Instruction.shift_left(dest_reg, left_reg, right_reg, hint_a, hint_b) + :shr -> Instruction.shift_right(dest_reg, left_reg, right_reg, hint_a, hint_b) :concat -> Instruction.concatenate(dest_reg, left_reg, right_reg) :eq -> Instruction.equal(dest_reg, left_reg, right_reg) :ne -> {:not_equal, dest_reg, left_reg, right_reg} @@ -947,6 +955,8 @@ defmodule Lua.Compiler.Codegen do end defp gen_expr(%Expr.UnOp{op: op, operand: operand}, ctx) do + hint = name_hint(operand, ctx) + # Generate code for operand {operand_instructions, operand_reg, ctx} = gen_expr(operand, ctx) @@ -957,10 +967,10 @@ defmodule Lua.Compiler.Codegen do # Generate the operation instruction operation_instruction = case op do - :neg -> Instruction.negate(dest_reg, operand_reg) + :neg -> Instruction.negate(dest_reg, operand_reg, hint) :not -> Instruction.logical_not(dest_reg, operand_reg) :len -> Instruction.length(dest_reg, operand_reg) - :bnot -> Instruction.bitwise_not(dest_reg, operand_reg) + :bnot -> Instruction.bitwise_not(dest_reg, operand_reg, hint) end {operand_instructions ++ [operation_instruction], dest_reg, ctx} diff --git a/lib/lua/compiler/instruction.ex b/lib/lua/compiler/instruction.ex index 5f86fe2f..ee9811bb 100644 --- a/lib/lua/compiler/instruction.ex +++ b/lib/lua/compiler/instruction.ex @@ -36,24 +36,37 @@ defmodule Lua.Compiler.Instruction do def set_field(table, name, value, name_hint \\ nil), do: {:set_field, table, name, value, name_hint} def set_list(table, start, count, offset), do: {:set_list, table, start, count, offset} - # Arithmetic - def add(dest, a, b), do: {:add, dest, a, b} - def subtract(dest, a, b), do: {:subtract, dest, a, b} - def multiply(dest, a, b), do: {:multiply, dest, a, b} - def divide(dest, a, b), do: {:divide, dest, a, b} - def floor_divide(dest, a, b), do: {:floor_divide, dest, a, b} - def modulo(dest, a, b), do: {:modulo, dest, a, b} - def power(dest, a, b), do: {:power, dest, a, b} - def negate(dest, source), do: {:negate, dest, source} + # Arithmetic. + # + # `hint_a` / `hint_b` carry the lexical origin of each operand + # (`{:global|:local|:upvalue|:field, name}` tuples produced by + # `Lua.Compiler.Codegen.name_hint/2`) so the executor can render + # PUC-Lua-style suffixes like `(field 'huge')` on type errors. `nil` + # means "no useful name" (e.g. expression operand). + def add(dest, a, b, hint_a \\ nil, hint_b \\ nil), do: {:add, dest, a, b, hint_a, hint_b} + def subtract(dest, a, b, hint_a \\ nil, hint_b \\ nil), do: {:subtract, dest, a, b, hint_a, hint_b} + def multiply(dest, a, b, hint_a \\ nil, hint_b \\ nil), do: {:multiply, dest, a, b, hint_a, hint_b} + def divide(dest, a, b, hint_a \\ nil, hint_b \\ nil), do: {:divide, dest, a, b, hint_a, hint_b} + + def floor_divide(dest, a, b, hint_a \\ nil, hint_b \\ nil), do: {:floor_divide, dest, a, b, hint_a, hint_b} + + def modulo(dest, a, b, hint_a \\ nil, hint_b \\ nil), do: {:modulo, dest, a, b, hint_a, hint_b} + def power(dest, a, b, hint_a \\ nil, hint_b \\ nil), do: {:power, dest, a, b, hint_a, hint_b} + def negate(dest, source, hint \\ nil), do: {:negate, dest, source, hint} def concatenate(dest, a, b), do: {:concatenate, dest, a, b} - # Bitwise - def bitwise_and(dest, a, b), do: {:bitwise_and, dest, a, b} - def bitwise_or(dest, a, b), do: {:bitwise_or, dest, a, b} - def bitwise_xor(dest, a, b), do: {:bitwise_xor, dest, a, b} - def shift_left(dest, a, b), do: {:shift_left, dest, a, b} - def shift_right(dest, a, b), do: {:shift_right, dest, a, b} - def bitwise_not(dest, source), do: {:bitwise_not, dest, source} + # Bitwise. Same hint convention as arithmetic. + def bitwise_and(dest, a, b, hint_a \\ nil, hint_b \\ nil), do: {:bitwise_and, dest, a, b, hint_a, hint_b} + + def bitwise_or(dest, a, b, hint_a \\ nil, hint_b \\ nil), do: {:bitwise_or, dest, a, b, hint_a, hint_b} + + def bitwise_xor(dest, a, b, hint_a \\ nil, hint_b \\ nil), do: {:bitwise_xor, dest, a, b, hint_a, hint_b} + + def shift_left(dest, a, b, hint_a \\ nil, hint_b \\ nil), do: {:shift_left, dest, a, b, hint_a, hint_b} + + def shift_right(dest, a, b, hint_a \\ nil, hint_b \\ nil), do: {:shift_right, dest, a, b, hint_a, hint_b} + + def bitwise_not(dest, source, hint \\ nil), do: {:bitwise_not, dest, source, hint} # Comparison def equal(dest, a, b), do: {:equal, dest, a, b} diff --git a/lib/lua/vm/dispatcher.ex b/lib/lua/vm/dispatcher.ex index b2c8eb4e..cac59a21 100644 --- a/lib/lua/vm/dispatcher.ex +++ b/lib/lua/vm/dispatcher.ex @@ -236,7 +236,7 @@ defmodule Lua.VM.Dispatcher do # when both operands are already numeric. The two `is_number` # guards inline directly in the case body. - {@op_add, dest, a, b} -> + {@op_add, dest, a, b, hint_a, hint_b} -> va = :erlang.element(a + 1, regs) vb = :erlang.element(b + 1, regs) @@ -252,12 +252,12 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames) true -> - {value, state} = Executor.dispatcher_binop(:add, va, vb, state, proto) + {value, state} = Executor.dispatcher_binop(:add, va, vb, state, proto, hint_a, hint_b) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames) end - {@op_subtract, dest, a, b} -> + {@op_subtract, dest, a, b, hint_a, hint_b} -> va = :erlang.element(a + 1, regs) vb = :erlang.element(b + 1, regs) @@ -273,12 +273,12 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames) true -> - {value, state} = Executor.dispatcher_binop(:subtract, va, vb, state, proto) + {value, state} = Executor.dispatcher_binop(:subtract, va, vb, state, proto, hint_a, hint_b) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames) end - {@op_multiply, dest, a, b} -> + {@op_multiply, dest, a, b, hint_a, hint_b} -> va = :erlang.element(a + 1, regs) vb = :erlang.element(b + 1, regs) @@ -294,66 +294,74 @@ defmodule Lua.VM.Dispatcher do dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames) true -> - {value, state} = Executor.dispatcher_binop(:multiply, va, vb, state, proto) + {value, state} = Executor.dispatcher_binop(:multiply, va, vb, state, proto, hint_a, hint_b) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames) end - {@op_divide, dest, a, b} -> + {@op_divide, dest, a, b, hint_a, hint_b} -> {value, state} = Executor.dispatcher_binop( :divide, :erlang.element(a + 1, regs), :erlang.element(b + 1, regs), state, - proto + proto, + hint_a, + hint_b ) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames) - {@op_floor_divide, dest, a, b} -> + {@op_floor_divide, dest, a, b, hint_a, hint_b} -> {value, state} = Executor.dispatcher_binop( :floor_divide, :erlang.element(a + 1, regs), :erlang.element(b + 1, regs), state, - proto + proto, + hint_a, + hint_b ) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames) - {@op_modulo, dest, a, b} -> + {@op_modulo, dest, a, b, hint_a, hint_b} -> {value, state} = Executor.dispatcher_binop( :modulo, :erlang.element(a + 1, regs), :erlang.element(b + 1, regs), state, - proto + proto, + hint_a, + hint_b ) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames) - {@op_power, dest, a, b} -> + {@op_power, dest, a, b, hint_a, hint_b} -> {value, state} = Executor.dispatcher_binop( :power, :erlang.element(a + 1, regs), :erlang.element(b + 1, regs), state, - proto + proto, + hint_a, + hint_b ) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames) - {@op_negate, dest, src} -> + {@op_negate, dest, src, hint} -> {value, state} = - Executor.dispatcher_unop(:negate, :erlang.element(src + 1, regs), state, proto) + Executor.dispatcher_unop(:negate, :erlang.element(src + 1, regs), state, proto, hint) regs = :erlang.setelement(dest + 1, regs, value) dispatch(code, pc + 1, regs, upvalues, proto, state, cont, frames) diff --git a/lib/lua/vm/executor.ex b/lib/lua/vm/executor.ex index 07491795..659d9425 100644 --- a/lib/lua/vm/executor.ex +++ b/lib/lua/vm/executor.ex @@ -202,39 +202,54 @@ defmodule Lua.VM.Executor do # process-dictionary bridge installed at the call boundary. @doc false - @spec dispatcher_binop(atom(), term(), term(), State.t(), term()) :: {term(), State.t()} - def dispatcher_binop(:add, a, b, state, proto) do - try_binary_metamethod("__add", a, b, state, fn -> safe_add(a, b, 0, proto.source) end) + @spec dispatcher_binop(atom(), term(), term(), State.t(), term(), term(), term()) :: + {term(), State.t()} + def dispatcher_binop(:add, a, b, state, proto, hint_a, hint_b) do + try_binary_metamethod("__add", a, b, state, fn -> + safe_add(a, b, 0, proto.source, hint_a, hint_b) + end) end - def dispatcher_binop(:subtract, a, b, state, proto) do - try_binary_metamethod("__sub", a, b, state, fn -> safe_subtract(a, b, 0, proto.source) end) + def dispatcher_binop(:subtract, a, b, state, proto, hint_a, hint_b) do + try_binary_metamethod("__sub", a, b, state, fn -> + safe_subtract(a, b, 0, proto.source, hint_a, hint_b) + end) end - def dispatcher_binop(:multiply, a, b, state, proto) do - try_binary_metamethod("__mul", a, b, state, fn -> safe_multiply(a, b, 0, proto.source) end) + def dispatcher_binop(:multiply, a, b, state, proto, hint_a, hint_b) do + try_binary_metamethod("__mul", a, b, state, fn -> + safe_multiply(a, b, 0, proto.source, hint_a, hint_b) + end) end - def dispatcher_binop(:divide, a, b, state, proto) do - try_binary_metamethod("__div", a, b, state, fn -> safe_divide(a, b, 0, proto.source) end) + def dispatcher_binop(:divide, a, b, state, proto, hint_a, hint_b) do + try_binary_metamethod("__div", a, b, state, fn -> + safe_divide(a, b, 0, proto.source, hint_a, hint_b) + end) end - def dispatcher_binop(:floor_divide, a, b, state, proto) do - try_binary_metamethod("__idiv", a, b, state, fn -> safe_floor_divide(a, b, 0, proto.source) end) + def dispatcher_binop(:floor_divide, a, b, state, proto, hint_a, hint_b) do + try_binary_metamethod("__idiv", a, b, state, fn -> + safe_floor_divide(a, b, 0, proto.source, hint_a, hint_b) + end) end - def dispatcher_binop(:modulo, a, b, state, proto) do - try_binary_metamethod("__mod", a, b, state, fn -> safe_modulo(a, b, 0, proto.source) end) + def dispatcher_binop(:modulo, a, b, state, proto, hint_a, hint_b) do + try_binary_metamethod("__mod", a, b, state, fn -> + safe_modulo(a, b, 0, proto.source, hint_a, hint_b) + end) end - def dispatcher_binop(:power, a, b, state, proto) do - try_binary_metamethod("__pow", a, b, state, fn -> safe_power(a, b, 0, proto.source) end) + def dispatcher_binop(:power, a, b, state, proto, hint_a, hint_b) do + try_binary_metamethod("__pow", a, b, state, fn -> + safe_power(a, b, 0, proto.source, hint_a, hint_b) + end) end @doc false - @spec dispatcher_unop(atom(), term(), State.t(), term()) :: {term(), State.t()} - def dispatcher_unop(:negate, val, state, proto) do - try_unary_metamethod("__unm", val, state, fn -> safe_negate(val, 0, proto.source) end) + @spec dispatcher_unop(atom(), term(), State.t(), term(), term()) :: {term(), State.t()} + def dispatcher_unop(:negate, val, state, proto, hint) do + try_unary_metamethod("__unm", val, state, fn -> safe_negate(val, 0, proto.source, hint) end) end @doc false @@ -976,14 +991,14 @@ defmodule Lua.VM.Executor do # for Lua 5.3 §3.4.1 wrap-around; mixed and float-only fall through to # native `+`/`-`/`*`. - defp do_execute([{:add, dest, a, b} | rest], regs, upvalues, proto, state, cont, frames, line) + defp do_execute([{:add, dest, a, b, _hint_a, _hint_b} | rest], regs, upvalues, proto, state, cont, frames, line) when is_integer(:erlang.element(a + 1, regs)) and is_integer(:erlang.element(b + 1, regs)) do sum = :erlang.element(a + 1, regs) + :erlang.element(b + 1, regs) regs = :erlang.setelement(dest + 1, regs, Numeric.to_signed_int64(sum)) do_execute(rest, regs, upvalues, proto, state, cont, frames, line) end - defp do_execute([{:add, dest, a, b} | rest], regs, upvalues, proto, state, cont, frames, line) do + defp do_execute([{:add, dest, a, b, hint_a, hint_b} | rest], regs, upvalues, proto, state, cont, frames, line) do val_a = elem(regs, a) val_b = elem(regs, b) @@ -994,21 +1009,23 @@ defmodule Lua.VM.Executor do src = proto.source {result, new_state} = - try_binary_metamethod("__add", val_a, val_b, state, fn -> safe_add(val_a, val_b, line, src) end) + try_binary_metamethod("__add", val_a, val_b, state, fn -> + safe_add(val_a, val_b, line, src, hint_a, hint_b) + end) regs = put_elem(regs, dest, result) do_execute(rest, regs, upvalues, proto, new_state, cont, frames, line) end end - defp do_execute([{:subtract, dest, a, b} | rest], regs, upvalues, proto, state, cont, frames, line) + defp do_execute([{:subtract, dest, a, b, _hint_a, _hint_b} | rest], regs, upvalues, proto, state, cont, frames, line) when is_integer(:erlang.element(a + 1, regs)) and is_integer(:erlang.element(b + 1, regs)) do diff = :erlang.element(a + 1, regs) - :erlang.element(b + 1, regs) regs = :erlang.setelement(dest + 1, regs, Numeric.to_signed_int64(diff)) do_execute(rest, regs, upvalues, proto, state, cont, frames, line) end - defp do_execute([{:subtract, dest, a, b} | rest], regs, upvalues, proto, state, cont, frames, line) do + defp do_execute([{:subtract, dest, a, b, hint_a, hint_b} | rest], regs, upvalues, proto, state, cont, frames, line) do val_a = elem(regs, a) val_b = elem(regs, b) @@ -1019,21 +1036,23 @@ defmodule Lua.VM.Executor do src = proto.source {result, new_state} = - try_binary_metamethod("__sub", val_a, val_b, state, fn -> safe_subtract(val_a, val_b, line, src) end) + try_binary_metamethod("__sub", val_a, val_b, state, fn -> + safe_subtract(val_a, val_b, line, src, hint_a, hint_b) + end) regs = put_elem(regs, dest, result) do_execute(rest, regs, upvalues, proto, new_state, cont, frames, line) end end - defp do_execute([{:multiply, dest, a, b} | rest], regs, upvalues, proto, state, cont, frames, line) + defp do_execute([{:multiply, dest, a, b, _hint_a, _hint_b} | rest], regs, upvalues, proto, state, cont, frames, line) when is_integer(:erlang.element(a + 1, regs)) and is_integer(:erlang.element(b + 1, regs)) do prod = :erlang.element(a + 1, regs) * :erlang.element(b + 1, regs) regs = :erlang.setelement(dest + 1, regs, Numeric.to_signed_int64(prod)) do_execute(rest, regs, upvalues, proto, state, cont, frames, line) end - defp do_execute([{:multiply, dest, a, b} | rest], regs, upvalues, proto, state, cont, frames, line) do + defp do_execute([{:multiply, dest, a, b, hint_a, hint_b} | rest], regs, upvalues, proto, state, cont, frames, line) do val_a = elem(regs, a) val_b = elem(regs, b) @@ -1044,58 +1063,66 @@ defmodule Lua.VM.Executor do src = proto.source {result, new_state} = - try_binary_metamethod("__mul", val_a, val_b, state, fn -> safe_multiply(val_a, val_b, line, src) end) + try_binary_metamethod("__mul", val_a, val_b, state, fn -> + safe_multiply(val_a, val_b, line, src, hint_a, hint_b) + end) regs = put_elem(regs, dest, result) do_execute(rest, regs, upvalues, proto, new_state, cont, frames, line) end end - defp do_execute([{:divide, dest, a, b} | rest], regs, upvalues, proto, state, cont, frames, line) do + defp do_execute([{:divide, dest, a, b, hint_a, hint_b} | rest], regs, upvalues, proto, state, cont, frames, line) do val_a = elem(regs, a) val_b = elem(regs, b) src = proto.source {result, new_state} = - try_binary_metamethod("__div", val_a, val_b, state, fn -> safe_divide(val_a, val_b, line, src) end) + try_binary_metamethod("__div", val_a, val_b, state, fn -> + safe_divide(val_a, val_b, line, src, hint_a, hint_b) + end) regs = put_elem(regs, dest, result) do_execute(rest, regs, upvalues, proto, new_state, cont, frames, line) end - defp do_execute([{:floor_divide, dest, a, b} | rest], regs, upvalues, proto, state, cont, frames, line) do + defp do_execute([{:floor_divide, dest, a, b, hint_a, hint_b} | rest], regs, upvalues, proto, state, cont, frames, line) do val_a = elem(regs, a) val_b = elem(regs, b) src = proto.source {result, new_state} = try_binary_metamethod("__idiv", val_a, val_b, state, fn -> - safe_floor_divide(val_a, val_b, line, src) + safe_floor_divide(val_a, val_b, line, src, hint_a, hint_b) end) regs = put_elem(regs, dest, result) do_execute(rest, regs, upvalues, proto, new_state, cont, frames, line) end - defp do_execute([{:modulo, dest, a, b} | rest], regs, upvalues, proto, state, cont, frames, line) do + defp do_execute([{:modulo, dest, a, b, hint_a, hint_b} | rest], regs, upvalues, proto, state, cont, frames, line) do val_a = elem(regs, a) val_b = elem(regs, b) src = proto.source {result, new_state} = - try_binary_metamethod("__mod", val_a, val_b, state, fn -> safe_modulo(val_a, val_b, line, src) end) + try_binary_metamethod("__mod", val_a, val_b, state, fn -> + safe_modulo(val_a, val_b, line, src, hint_a, hint_b) + end) regs = put_elem(regs, dest, result) do_execute(rest, regs, upvalues, proto, new_state, cont, frames, line) end - defp do_execute([{:power, dest, a, b} | rest], regs, upvalues, proto, state, cont, frames, line) do + defp do_execute([{:power, dest, a, b, hint_a, hint_b} | rest], regs, upvalues, proto, state, cont, frames, line) do val_a = elem(regs, a) val_b = elem(regs, b) src = proto.source {result, new_state} = - try_binary_metamethod("__pow", val_a, val_b, state, fn -> safe_power(val_a, val_b, line, src) end) + try_binary_metamethod("__pow", val_a, val_b, state, fn -> + safe_power(val_a, val_b, line, src, hint_a, hint_b) + end) regs = put_elem(regs, dest, result) do_execute(rest, regs, upvalues, proto, new_state, cont, frames, line) @@ -1138,83 +1165,87 @@ defmodule Lua.VM.Executor do # ── Bitwise operations ───────────────────────────────────────────────────── - defp do_execute([{:bitwise_and, dest, a, b} | rest], regs, upvalues, proto, state, cont, frames, line) do + defp do_execute([{:bitwise_and, dest, a, b, hint_a, hint_b} | rest], regs, upvalues, proto, state, cont, frames, line) do val_a = elem(regs, a) val_b = elem(regs, b) src = proto.source {result, new_state} = try_binary_metamethod("__band", val_a, val_b, state, fn -> - Numeric.to_signed_int64(Bitwise.band(to_integer!(val_a, line, src), to_integer!(val_b, line, src))) + Numeric.to_signed_int64( + Bitwise.band(to_integer!(val_a, line, src, hint_a), to_integer!(val_b, line, src, hint_b)) + ) end) regs = put_elem(regs, dest, result) do_execute(rest, regs, upvalues, proto, new_state, cont, frames, line) end - defp do_execute([{:bitwise_or, dest, a, b} | rest], regs, upvalues, proto, state, cont, frames, line) do + defp do_execute([{:bitwise_or, dest, a, b, hint_a, hint_b} | rest], regs, upvalues, proto, state, cont, frames, line) do val_a = elem(regs, a) val_b = elem(regs, b) src = proto.source {result, new_state} = try_binary_metamethod("__bor", val_a, val_b, state, fn -> - Numeric.to_signed_int64(Bitwise.bor(to_integer!(val_a, line, src), to_integer!(val_b, line, src))) + Numeric.to_signed_int64(Bitwise.bor(to_integer!(val_a, line, src, hint_a), to_integer!(val_b, line, src, hint_b))) end) regs = put_elem(regs, dest, result) do_execute(rest, regs, upvalues, proto, new_state, cont, frames, line) end - defp do_execute([{:bitwise_xor, dest, a, b} | rest], regs, upvalues, proto, state, cont, frames, line) do + defp do_execute([{:bitwise_xor, dest, a, b, hint_a, hint_b} | rest], regs, upvalues, proto, state, cont, frames, line) do val_a = elem(regs, a) val_b = elem(regs, b) src = proto.source {result, new_state} = try_binary_metamethod("__bxor", val_a, val_b, state, fn -> - Numeric.to_signed_int64(Bitwise.bxor(to_integer!(val_a, line, src), to_integer!(val_b, line, src))) + Numeric.to_signed_int64( + Bitwise.bxor(to_integer!(val_a, line, src, hint_a), to_integer!(val_b, line, src, hint_b)) + ) end) regs = put_elem(regs, dest, result) do_execute(rest, regs, upvalues, proto, new_state, cont, frames, line) end - defp do_execute([{:shift_left, dest, a, b} | rest], regs, upvalues, proto, state, cont, frames, line) do + defp do_execute([{:shift_left, dest, a, b, hint_a, hint_b} | rest], regs, upvalues, proto, state, cont, frames, line) do val_a = elem(regs, a) val_b = elem(regs, b) src = proto.source {result, new_state} = try_binary_metamethod("__shl", val_a, val_b, state, fn -> - lua_shift_left(to_integer!(val_a, line, src), to_integer!(val_b, line, src)) + lua_shift_left(to_integer!(val_a, line, src, hint_a), to_integer!(val_b, line, src, hint_b)) end) regs = put_elem(regs, dest, result) do_execute(rest, regs, upvalues, proto, new_state, cont, frames, line) end - defp do_execute([{:shift_right, dest, a, b} | rest], regs, upvalues, proto, state, cont, frames, line) do + defp do_execute([{:shift_right, dest, a, b, hint_a, hint_b} | rest], regs, upvalues, proto, state, cont, frames, line) do val_a = elem(regs, a) val_b = elem(regs, b) src = proto.source {result, new_state} = try_binary_metamethod("__shr", val_a, val_b, state, fn -> - lua_shift_right(to_integer!(val_a, line, src), to_integer!(val_b, line, src)) + lua_shift_right(to_integer!(val_a, line, src, hint_a), to_integer!(val_b, line, src, hint_b)) end) regs = put_elem(regs, dest, result) do_execute(rest, regs, upvalues, proto, new_state, cont, frames, line) end - defp do_execute([{:bitwise_not, dest, source} | rest], regs, upvalues, proto, state, cont, frames, line) do + defp do_execute([{:bitwise_not, dest, source, hint} | rest], regs, upvalues, proto, state, cont, frames, line) do val = elem(regs, source) src = proto.source {result, new_state} = try_unary_metamethod("__bnot", val, state, fn -> - Numeric.to_signed_int64(Bitwise.bnot(to_integer!(val, line, src))) + Numeric.to_signed_int64(Bitwise.bnot(to_integer!(val, line, src, hint))) end) regs = put_elem(regs, dest, result) @@ -1364,10 +1395,10 @@ defmodule Lua.VM.Executor do # ── Unary operations ─────────────────────────────────────────────────────── - defp do_execute([{:negate, dest, source} | rest], regs, upvalues, proto, state, cont, frames, line) do + defp do_execute([{:negate, dest, source, hint} | rest], regs, upvalues, proto, state, cont, frames, line) do val = elem(regs, source) src = proto.source - {result, new_state} = try_unary_metamethod("__unm", val, state, fn -> safe_negate(val, line, src) end) + {result, new_state} = try_unary_metamethod("__unm", val, state, fn -> safe_negate(val, line, src, hint) end) regs = put_elem(regs, dest, result) do_execute(rest, regs, upvalues, proto, new_state, cont, frames, line) end @@ -2239,36 +2270,41 @@ defmodule Lua.VM.Executor do # passed verbatim from the executor's threaded `line` and `proto.source`, # so they cost nothing on the success path beyond two register reads. - defp safe_add(a, b, line, source) do - with {:ok, na} <- to_number(a), - {:ok, nb} <- to_number(b) do - narrow_if_integer(na + nb) - else - {:error, val} -> raise_arith_type_error(val, line, source) - end + defp safe_add(a, b, line, source, hint_a, hint_b) do + na = number_or_arith_raise!(a, line, source, hint_a) + nb = number_or_arith_raise!(b, line, source, hint_b) + narrow_if_integer(na + nb) end - defp safe_subtract(a, b, line, source) do - with {:ok, na} <- to_number(a), - {:ok, nb} <- to_number(b) do - narrow_if_integer(na - nb) - else - {:error, val} -> raise_arith_type_error(val, line, source) - end + defp safe_subtract(a, b, line, source, hint_a, hint_b) do + na = number_or_arith_raise!(a, line, source, hint_a) + nb = number_or_arith_raise!(b, line, source, hint_b) + narrow_if_integer(na - nb) end - defp safe_multiply(a, b, line, source) do - with {:ok, na} <- to_number(a), - {:ok, nb} <- to_number(b) do - narrow_if_integer(na * nb) - else - {:error, val} -> raise_arith_type_error(val, line, source) + defp safe_multiply(a, b, line, source, hint_a, hint_b) do + na = number_or_arith_raise!(a, line, source, hint_a) + nb = number_or_arith_raise!(b, line, source, hint_b) + narrow_if_integer(na * nb) + end + + # Coerce a value to a number, or raise an arithmetic type error pointing + # at the failing operand. Per-operand hint lets the error suffix point + # to the originating variable / field (PUC-Lua mirrors this via debug + # info; we resolve at compile time and thread the hint through the + # instruction tuple). + defp number_or_arith_raise!(v, line, source, hint) do + case to_number(v) do + {:ok, n} -> n + {:error, val} -> raise_arith_type_error(val, line, source, hint) end end - defp raise_arith_type_error(val, line, source) do + defp raise_arith_type_error(val, line, source, hint) do raise TypeError, - value: "attempt to perform arithmetic on a #{Value.type_name(val)} value", + value: + "attempt to perform arithmetic on a #{Value.type_name(val)} value" <> + format_target_hint(hint), line: line, source: source, error_kind: :arithmetic_on_non_number, @@ -2289,20 +2325,18 @@ defmodule Lua.VM.Executor do # Arithmetic on `:nan` will surface a TypeError via `to_number/1`; that's # an accepted divergence from real IEEE 754, since the suite tests we # care about don't propagate NaN through further arithmetic. - defp safe_divide(a, b, line, source) do - with {:ok, na} <- to_number(a), - {:ok, nb} <- to_number(b) do - if nb == 0 or nb == 0.0 do - cond do - na == 0 or na == 0.0 -> :nan - na > 0 -> 1.0e308 - true -> -1.0e308 - end - else - na / nb + defp safe_divide(a, b, line, source, hint_a, hint_b) do + na = number_or_arith_raise!(a, line, source, hint_a) + nb = number_or_arith_raise!(b, line, source, hint_b) + + if nb == 0 or nb == 0.0 do + cond do + na == 0 or na == 0.0 -> :nan + na > 0 -> 1.0e308 + true -> -1.0e308 end else - {:error, val} -> raise_arith_type_error(val, line, source) + na / nb end end @@ -2316,52 +2350,48 @@ defmodule Lua.VM.Executor do # # An integer-zero divisor still raises — that's correct per spec, since # `//` between two integers is integer floor division. - defp safe_floor_divide(a, b, line, source) do - with {:ok, na} <- to_number(a), - {:ok, nb} <- to_number(b) do - cond do - is_integer(nb) and nb == 0 -> - raise RuntimeError, value: "attempt to perform 'n//0'", line: line, source: source + defp safe_floor_divide(a, b, line, source, hint_a, hint_b) do + na = number_or_arith_raise!(a, line, source, hint_a) + nb = number_or_arith_raise!(b, line, source, hint_b) - is_integer(na) and is_integer(nb) -> - Numeric.to_signed_int64(lua_idiv(na, nb)) + cond do + is_integer(nb) and nb == 0 -> + raise RuntimeError, value: "attempt to perform 'n//0'", line: line, source: source - is_float(nb) and nb == 0.0 -> - cond do - na == 0 or na == 0.0 -> :nan - na > 0 -> 1.0e308 - true -> -1.0e308 - end + is_integer(na) and is_integer(nb) -> + Numeric.to_signed_int64(lua_idiv(na, nb)) - true -> - Float.floor(na / nb) * 1.0 - end - else - {:error, val} -> raise_arith_type_error(val, line, source) + is_float(nb) and nb == 0.0 -> + cond do + na == 0 or na == 0.0 -> :nan + na > 0 -> 1.0e308 + true -> -1.0e308 + end + + true -> + Float.floor(na / nb) * 1.0 end end # Lua 5.3 §3.4.1: `a % b = a - floor(a/b)*b`. With a float zero divisor, # `a/0.0` is inf or nan, and `inf * 0.0 = nan`, so `a % 0.0` is always # `:nan` regardless of `a`. An integer-zero divisor still raises. - defp safe_modulo(a, b, line, source) do - with {:ok, na} <- to_number(a), - {:ok, nb} <- to_number(b) do - cond do - is_integer(nb) and nb == 0 -> - raise RuntimeError, value: "attempt to perform 'n%0'", line: line, source: source + defp safe_modulo(a, b, line, source, hint_a, hint_b) do + na = number_or_arith_raise!(a, line, source, hint_a) + nb = number_or_arith_raise!(b, line, source, hint_b) - is_integer(na) and is_integer(nb) -> - Numeric.to_signed_int64(na - lua_idiv(na, nb) * nb) + cond do + is_integer(nb) and nb == 0 -> + raise RuntimeError, value: "attempt to perform 'n%0'", line: line, source: source - is_float(nb) and nb == 0.0 -> - :nan + is_integer(na) and is_integer(nb) -> + Numeric.to_signed_int64(na - lua_idiv(na, nb) * nb) - true -> - na - Float.floor(na / nb) * nb - end - else - {:error, val} -> raise_arith_type_error(val, line, source) + is_float(nb) and nb == 0.0 -> + :nan + + true -> + na - Float.floor(na / nb) * nb end end @@ -2371,13 +2401,10 @@ defmodule Lua.VM.Executor do if r != 0 and Bitwise.bxor(r, b) < 0, do: q - 1, else: q end - defp safe_power(a, b, line, source) do - with {:ok, na} <- to_number(a), - {:ok, nb} <- to_number(b) do - pow_ieee(na, nb) - else - {:error, val} -> raise_arith_type_error(val, line, source) - end + defp safe_power(a, b, line, source, hint_a, hint_b) do + na = number_or_arith_raise!(a, line, source, hint_a) + nb = number_or_arith_raise!(b, line, source, hint_b) + pow_ieee(na, nb) end # `:math.pow` raises ArithmeticError on 0^(negative), inf ^ 0, etc. @@ -2391,13 +2418,13 @@ defmodule Lua.VM.Executor do ArithmeticError -> :nan end - defp safe_negate(a, line, source) do + defp safe_negate(a, line, source, hint) do case to_number(a) do {:ok, na} -> narrow_if_integer(-na) {:error, val} -> - raise_arith_type_error(val, line, source) + raise_arith_type_error(val, line, source, hint) end end @@ -2514,14 +2541,16 @@ defmodule Lua.VM.Executor do value_type: value_type(v) end - defp to_integer!(v, _line, _source) when is_integer(v), do: v - defp to_integer!(v, line, source) when is_float(v), do: float_to_integer!(v, line, source) + defp to_integer!(v, _line, _source, _hint) when is_integer(v), do: v + defp to_integer!(v, line, source, hint) when is_float(v), do: float_to_integer!(v, line, source, hint) - defp to_integer!(v, line, source) when is_binary(v) do + defp to_integer!(v, line, source, hint) when is_binary(v) do case Value.parse_number(v) do nil -> raise TypeError, - value: "attempt to perform bitwise operation on a string value", + value: + "attempt to perform bitwise operation on a string value" <> + format_target_hint(hint), line: line, source: source, error_kind: :bitwise_on_non_integer, @@ -2531,13 +2560,15 @@ defmodule Lua.VM.Executor do n n when is_float(n) -> - float_to_integer!(n, line, source) + float_to_integer!(n, line, source, hint) end end - defp to_integer!(v, line, source) do + defp to_integer!(v, line, source, hint) do raise TypeError, - value: "attempt to perform bitwise operation on a #{Value.type_name(v)} value", + value: + "attempt to perform bitwise operation on a #{Value.type_name(v)} value" <> + format_target_hint(hint), line: line, source: source, error_kind: :bitwise_on_non_integer, @@ -2546,14 +2577,14 @@ defmodule Lua.VM.Executor do # Per Lua 5.3 §3.4.3: a float converts to integer for bitwise ops only if # it represents an integer exactly and fits in the signed 64-bit range. - defp float_to_integer!(f, line, source) when is_float(f) do + defp float_to_integer!(f, line, source, hint) when is_float(f) do truncated = trunc(f) if f == truncated * 1.0 and Numeric.signed?(truncated) do truncated else raise TypeError, - value: "number has no integer representation", + value: "number has no integer representation" <> format_target_hint(hint), line: line, source: source, error_kind: :bitwise_on_non_integer, diff --git a/test/lua/vm/error_format_test.exs b/test/lua/vm/error_format_test.exs index b70382b6..1a70d7a0 100644 --- a/test/lua/vm/error_format_test.exs +++ b/test/lua/vm/error_format_test.exs @@ -87,4 +87,67 @@ defmodule Lua.VM.ErrorFormatTest do end end end + + # PUC-Lua appends `(global 'X')` / `(local 'X')` / `(upvalue 'X')` / + # `(field 'X')` to arithmetic and bitwise type errors when the failing + # operand's lexical origin is recoverable. We resolve at compile time + # and bake the hint into the instruction tuple — see codegen + # `name_hint/2` and `format_target_hint/1` in the executor. + describe "arithmetic type error carries operand hint" do + test "global operand surfaces (global 'X')" do + assert_raise LuaTypeError, + ~r/attempt to perform arithmetic on a nil value \(global 'foo'\)/, + fn -> run("return foo + 1") end + end + + test "local operand surfaces (local 'X')" do + assert_raise LuaTypeError, + ~r/attempt to perform arithmetic on a nil value \(local 'x'\)/, + fn -> run("local x; return x + 1") end + end + + test "field operand surfaces (field 'X')" do + assert_raise LuaTypeError, + ~r/attempt to perform arithmetic on a nil value \(field 'x'/, + fn -> run("local t = {}; return t.x + 1") end + end + + test "upvalue operand surfaces (upvalue 'X')" do + code = """ + local y + local function f() return y + 1 end + return f() + """ + + assert_raise LuaTypeError, + ~r/attempt to perform arithmetic on a nil value \(upvalue 'y'\)/, + fn -> run(code) end + end + + test "unary minus on a nil local surfaces the hint" do + assert_raise LuaTypeError, + ~r/attempt to perform arithmetic on a nil value \(local 'x'\)/, + fn -> run("local x; return -x") end + end + end + + describe "bitwise type error carries operand hint" do + test "shift on a string local surfaces (local 'X')" do + assert_raise LuaTypeError, + ~r/attempt to perform bitwise operation on a string value \(local 's'\)/, + fn -> run("local s = 'x'; return s << 1") end + end + + test "bnot on a nil global surfaces (global 'X')" do + assert_raise LuaTypeError, + ~r/attempt to perform bitwise operation on a nil value \(global 'foo'\)/, + fn -> run("return ~foo") end + end + + test "non-representable float through a field surfaces (field 'X')" do + assert_raise LuaTypeError, + ~r/number has no integer representation \(field 'huge'/, + fn -> run("return math.huge << 1") end + end + end end diff --git a/test/lua53_skips.exs b/test/lua53_skips.exs index f27d2513..3c722e0a 100644 --- a/test/lua53_skips.exs +++ b/test/lua53_skips.exs @@ -75,7 +75,8 @@ %{ lines: :all, category: :stdlib, - reason: "checkmessage/checksyntax/checkerr helpers expect PUC-Lua error message formats throughout", + reason: + "checkmessage/checksyntax expect PUC-Lua [string \"...\"]:N: prefixes on load() errors; many parse-error templates still differ", issue: nil } ], @@ -148,7 +149,8 @@ %{ lines: :all, category: :stdlib, - reason: "math.huge is finite (1.0e308) and many checkerror tests expect PUC-Lua-specific error messages", + reason: + "math.huge is a finite 1.0e308 stand-in so identities like math.huge + 1 == math.huge fail; not a wording issue", issue: nil } ], @@ -159,7 +161,7 @@ %{ lines: :all, category: :stdlib, - reason: "checkerror() expects PUC-Lua error message formats; os.clock not implemented", + reason: "times out (>30s) on the comparison-heavy section; os.clock not implemented", issue: nil } ], @@ -167,7 +169,7 @@ %{ lines: :all, category: :stdlib, - reason: "string.rep with large counts and checkerror format mismatches; pending finer triage", + reason: "times out (>30s) on string.rep with large counts; pending finer triage", issue: nil } ]