Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 79 additions & 2 deletions .agents/plans/A8-events-suite.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
id: A8
title: Fix events.lua metamethod assertion
issue: 169
pr: null
pr: 203
branch: fix/events-suite
base: main
status: ready
status: review
direction: A
unlocks:
- events.lua
Expand Down Expand Up @@ -116,3 +116,80 @@ metamethod-only fix that would let events.lua pass.
A8 is set to **blocked** on A16. Once A16 lands, A8 can be reopened to
triage any remaining metamethod-specific failures in events.lua (if
any surface beyond the `_ENV` block).

### Re-triage post-A16: vararg metamethod calling convention bug

A16 (env semantics) merged. Re-running events.lua revealed a new first
failure at line 137: `assert(b+5 == b)`, where `b` has metatable
`{__add = function(...) cap = {[0]="add", ...}; return (...) end}`.

Reduced to a 5-line repro:

```lua
local t = {}
t.__add = function(...) print(select('#', ...)) end
local b = setmetatable({}, t)
local _ = b + 5
-- expected: prints 2; actual: prints 0
```

Root cause: `try_binary_metamethod`, `try_unary_metamethod`, and
`try_equality_metamethod` in `lib/lua/vm/executor.ex` invoked Lua
closure metamethods by hand, putting args into registers but **not**
populating `proto.varargs`. A metamethod declared `function(...)`
has `param_count == 0` and `is_vararg == true`, so it reads from
`varargs` (which was empty) instead of registers. Args were silently
dropped.

A second, separate bug surfaced in the same code path: for `'5' + b`
(string + metamethod-bearing table), the cond in
`try_binary_metamethod` looked up `__add` on the string metatable,
got `nil`, and stopped — it never tried `b`'s metatable. Per Lua 5.3
§2.4 the runtime must try the first operand's metamethod, and if
nil, try the second operand's.

### Fix

Replace the inlined closure invocation in all three helpers with a
delegation to `call_function/3`, which already sets up `varargs`
correctly. Refactor the metamethod lookup into a shared
`lookup_metamethod/3` helper that returns `nil` for missing entries,
and chain with `||` so the second operand is consulted when the first
operand's metatable lacks the metamethod. Net diff: -91 lines in
`lib/lua/vm/executor.ex`.

### Remaining gap: float division by zero

After the metamethod fix, events.lua advances from line 15 to line
156: `assert(a // (1/0) == a)`. The expression `1/0` raises
`"attempt to divide by zero"` instead of producing `inf` per Lua 5.3
§3.4.1. This is a stdlib-level semantics gap distinct from metamethod
dispatch.

Tracked as `.agents/plans/A8a-float-div-zero.md` (status: ready).
A8 ships the metamethod fix; events.lua remains skipped pending A8a.

## What changed

PR: #203

Files touched:

- `lib/lua/vm/executor.ex` — refactor `try_binary_metamethod`,
`try_unary_metamethod`, `try_equality_metamethod` to delegate to
`call_function/3` instead of inlining a closure invocation that
bypassed proto.varargs. Add `lookup_metamethod/3` so binary metamethod
lookup correctly falls through to the second operand. Net -91 lines.
- `test/lua/vm/events_metamethod_vararg_test.exs` (new) — 21 unit
tests pinning the calling convention for vararg-form metamethods
across all arithmetic, bitwise, unary, comparison, concat, and
equality cases, plus the events.lua factory pattern.

Suite delta: events.lua advances from first failure at line 15
(pre-A16) to line 156 (post-this-fix). Remains in `@skipped_tests`
pending A8a (float division by zero).

Test count delta: 1446 → 1467 passing (+21 new tests, 0 regressions).

Follow-up: `.agents/plans/A8a-float-div-zero.md` covers the remaining
`1/0` semantics gap blocking events.lua end-to-end.
88 changes: 88 additions & 0 deletions .agents/plans/A8a-float-div-zero.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
---
id: A8a
title: Float division by zero must yield ±inf, not raise
issue: null
pr: null
branch: fix/float-div-zero
base: main
status: ready
direction: A
unlocks:
- events.lua (line 156: `assert(a // (1/0) == a)`)
- any code path that relies on Lua 5.3 §3.4.1 float semantics
---

## Goal

Make `1/0`, `-1/0`, and `0/0` evaluate to `+inf`, `-inf`, and `nan`
respectively, per Lua 5.3 §3.4.1, instead of raising
`"attempt to divide by zero"`. Only `//` (floor div) and `%` (modulo)
should raise on integer-zero divisors; plain `/` is always float
division and never raises.

## Out of scope

- Changing the `//` or `%` behavior (those correctly raise on integer
zero in Lua 5.3 — confirm the integer/float branches separately).
- Implementing a full IEEE 754 float type. We only need values that
compare correctly with `math.huge` and propagate through subsequent
arithmetic the way the suite expects.

## Success criteria

- [ ] `1/0 == math.huge` (currently `math.huge` is `1.0e308`)
- [ ] `-1/0 == -math.huge`
- [ ] `0/0 ~= 0/0` (NaN inequality, the canonical NaN test)
- [ ] `math.huge + 1 == math.huge` survives (no overflow surprise)
- [ ] events.lua advances past line 156 (no regression at the metamethod fix)
- [ ] No regressions in `mix test`

## Implementation notes

Erlang's BIF `Float / 0.0` raises `:badarith`. We need to intercept
that in `safe_divide/2` (and likely `safe_floor_divide`'s float branch
plus modulo's float branch) and synthesize the right value.

Two viable representations:

1. **BEAM-native float infinity.** OTP 27 supports `:erlang.float/1`
producing infinity in some contexts but does NOT support `inf`
literals or `1.0/0.0` returning inf — `:badarith` is unconditional.
This rules it out without an NIF.
2. **Stay with finite stand-ins.** `math.huge = 1.0e308` already.
Have `1/0 -> 1.0e308`, `-1/0 -> -1.0e308`, `0/0 -> :nan` (a Lua
sentinel atom we'd need to plumb through comparison). The downside
is `1.0e308 + 1.0e308 == :infinity` won't hold without further
work, but the suite tests don't hit that.

Recommended: option 2 (finite stand-in), since it matches the existing
`math.huge` decision. Document the divergence from real IEEE 754.

## Verification

```bash
mix format
mix compile --warnings-as-errors
mix test
mix test --only lua53
```

Plus: re-run events.lua (currently skipped) and confirm it advances
past line 156. If events.lua passes end-to-end after this fix, move it
from `@skipped_tests` to `@ready_tests` in `test/lua53_suite_test.exs`.

## Risks

- NaN comparison rules are subtle. `nan != nan` is the IEEE rule but
Erlang's `==` doesn't honor that. May need a custom equality path.
- `math.huge + math.huge` overflows to `:infinity` atom in Erlang;
arithmetic on that raises. Could surface in suite code that does
inf arithmetic.

## Background

Discovered while shipping A8 (events.lua metamethod fix). With the
metamethod calling convention fixed, events.lua advances from line 15
to line 156. Line 156 is `assert(a // (1/0) == a)`, which fails because
`1/0` raises rather than producing `inf`. This is a stdlib-level Lua
semantics gap, distinct from metamethod dispatch.
157 changes: 33 additions & 124 deletions lib/lua/vm/executor.ex
Original file line number Diff line number Diff line change
Expand Up @@ -1489,146 +1489,55 @@ defmodule Lua.VM.Executor do
end

defp try_binary_metamethod(metamethod_name, a, b, state, default_fn) do
mt_a = get_metatable(a, state)
mt_b = get_metatable(b, state)

metamethod =
cond do
mt_a != nil ->
mt = Map.fetch!(state.tables, elem(mt_a, 1))
Map.get(mt.data, metamethod_name)

mt_b != nil ->
mt = Map.fetch!(state.tables, elem(mt_b, 1))
Map.get(mt.data, metamethod_name)

true ->
nil
end

case metamethod do
{:native_func, func} ->
{[result], new_state} = func.([a, b], state)
{result, new_state}

{:lua_closure, callee_proto, callee_upvalues} ->
args = [a, b]
initial_regs = List.to_tuple(args ++ List.duplicate(nil, 248))
saved_open_upvalues = state.open_upvalues
state = %{state | open_upvalues: %{}}

{results, _final_regs, new_state} =
do_execute(callee_proto.instructions, initial_regs, callee_upvalues, callee_proto, state, [], [], 0)

new_state = %{new_state | open_upvalues: saved_open_upvalues}

result =
case results do
[r | _] -> r
[] -> nil
end

{result, new_state}
lookup_metamethod(a, metamethod_name, state) ||
lookup_metamethod(b, metamethod_name, state)

nil ->
{default_fn.(), state}
invoke_metamethod(metamethod, [a, b], state, default_fn)
end

_ ->
{default_fn.(), state}
defp lookup_metamethod(value, name, state) do
case get_metatable(value, state) do
nil -> nil
{:tref, mt_id} -> Map.get(Map.fetch!(state.tables, mt_id).data, name)
end
end

defp try_unary_metamethod(metamethod_name, a, state, default_fn) do
mt = get_metatable(a, state)
metamethod = lookup_metamethod(a, metamethod_name, state)
invoke_metamethod(metamethod, [a], state, default_fn)
end

metamethod =
case mt do
nil ->
nil
defp try_equality_metamethod(a, b, state, default_fn) do
eq_a = lookup_metamethod(a, "__eq", state)
eq_b = lookup_metamethod(b, "__eq", state)

{:tref, mt_id} ->
mt_table = Map.fetch!(state.tables, mt_id)
Map.get(mt_table.data, metamethod_name)
end
if not is_nil(eq_a) and eq_a == eq_b do
invoke_metamethod(eq_a, [a, b], state, default_fn)
else
{default_fn.(), state}
end
end

# Invokes a metamethod (native or Lua closure) with the given args, falling
# back to default_fn when the metamethod is missing or unsupported. Delegates
# to call_function/3 so vararg metamethods receive operands through proto
# varargs rather than being silently dropped.
defp invoke_metamethod(metamethod, args, state, default_fn) do
case metamethod do
{:native_func, func} ->
{[result], new_state} = func.([a], state)
{result, new_state}

{:lua_closure, callee_proto, callee_upvalues} ->
args = [a]
initial_regs = List.to_tuple(args ++ List.duplicate(nil, 249))
saved_open_upvalues = state.open_upvalues
state = %{state | open_upvalues: %{}}

{results, _final_regs, new_state} =
do_execute(callee_proto.instructions, initial_regs, callee_upvalues, callee_proto, state, [], [], 0)

new_state = %{new_state | open_upvalues: saved_open_upvalues}

result =
case results do
[r | _] -> r
[] -> nil
end

{result, new_state}

nil ->
{default_fn.(), state}

_ ->
{default_fn.(), state}
end
end
{:native_func, _} = func ->
{results, new_state} = call_function(func, args, state)
{List.first(results), new_state}

defp try_equality_metamethod(a, b, state, default_fn) do
mt_a = get_metatable(a, state)
mt_b = get_metatable(b, state)

eq_a =
case mt_a do
nil -> nil
{:tref, mt_id} -> Map.get(Map.fetch!(state.tables, mt_id).data, "__eq")
end

eq_b =
case mt_b do
nil -> nil
{:tref, mt_id} -> Map.get(Map.fetch!(state.tables, mt_id).data, "__eq")
end

if not is_nil(eq_a) and eq_a == eq_b do
case eq_a do
{:native_func, func} ->
{[result], new_state} = func.([a, b], state)
{result, new_state}

{:lua_closure, callee_proto, callee_upvalues} ->
args = [a, b]
initial_regs = List.to_tuple(args ++ List.duplicate(nil, 248))
saved_open_upvalues = state.open_upvalues
state = %{state | open_upvalues: %{}}

{results, _final_regs, new_state} =
do_execute(callee_proto.instructions, initial_regs, callee_upvalues, callee_proto, state, [], [], 0)

new_state = %{new_state | open_upvalues: saved_open_upvalues}

result =
case results do
[r | _] -> r
[] -> nil
end

{result, new_state}
{:lua_closure, _, _} = func ->
{results, new_state} = call_function(func, args, state)
{List.first(results), new_state}

_ ->
{default_fn.(), state}
end
else
{default_fn.(), state}
_ ->
{default_fn.(), state}
end
end

Expand Down
Loading
Loading