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
30 changes: 27 additions & 3 deletions .agents/plans/A5a-bitwise-suite-math-fmod.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
id: A5a
title: Add math.fmod for bitwise.lua bit32 verification
issue: null
pr: null
pr: 199
branch: feat/math-fmod
base: main
status: ready
status: review
direction: A
unlocks:
- bitwise.lua (final third — bit32.lshift verification block)
Expand Down Expand Up @@ -68,4 +68,28 @@ mix run --no-mix-exs -e 'Code.require_file("test/support/lua_test_case.ex"); Lua

## Discoveries

(populated during implementation)
- Lua 5.3 returns NaN for `math.fmod(x, 0.0)` when either argument is a
float. The BEAM has no NaN value, and the rest of this VM raises on
zero-divisor float arithmetic (`safe_divide` in
`lib/lua/vm/executor.ex:1690`). For consistency we raise `bad argument
#2 to 'math.fmod' (zero)` for both integer and float zero divisors.
Documented inline in `lib/lua/vm/stdlib/math.ex`.
- Integer `math.fmod(mininteger, -1)` is short-circuited to `0` to avoid
an overflow trap (matches the C implementation in `lmathlib.c`'s special
case for `d == -1`).
- Moved `bitwise.lua` from `@skipped_tests` to `@ready_tests` in
`test/lua53_suite_test.exs`, locking in the suite-count gain.
- No other math.* gaps surfaced while wiring fmod in. `math.modf` and
`math.atan2` are not exercised by `bitwise.lua`.

## What changed

- `lib/lua/vm/stdlib/math.ex` — added `math.fmod/2` with int/int, float,
zero-divisor, and `mininteger / -1` paths.
- `test/lua/vm/stdlib/math_test.exs` — added 8 tests covering each path.
- `test/lua53_suite_test.exs` — moved `bitwise.lua` from
`@skipped_tests` to `@ready_tests`.
- Suite delta: `mix test` 1394 → 1402 (8 new tests, 0 regressions);
ready Lua 5.3 suite files: 4 → 5.
- PR: #199.
- No follow-up issues required.
69 changes: 69 additions & 0 deletions lib/lua/vm/stdlib/math.ex
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ defmodule Lua.VM.Stdlib.Math do
- `math.cos(x)` - Returns the cosine of x (in radians)
- `math.exp(x)` - Returns e^x
- `math.floor(x)` - Returns the largest integer <= x
- `math.fmod(x, y)` - Returns the remainder of x/y rounded toward zero
- `math.log(x [, base])` - Returns the logarithm of x in the given base (default e)
- `math.max(x, ...)` - Returns the maximum value among arguments
- `math.min(x, ...)` - Returns the minimum value among arguments
Expand Down Expand Up @@ -51,6 +52,7 @@ defmodule Lua.VM.Stdlib.Math do
"cos" => {:native_func, &math_cos/2},
"exp" => {:native_func, &math_exp/2},
"floor" => {:native_func, &math_floor/2},
"fmod" => {:native_func, &math_fmod/2},
"log" => {:native_func, &math_log/2},
"max" => {:native_func, &math_max/2},
"min" => {:native_func, &math_min/2},
Expand Down Expand Up @@ -219,6 +221,73 @@ defmodule Lua.VM.Stdlib.Math do
raise ArgumentError.value_expected("math.floor", 1)
end

# math.fmod(x, y)
#
# Returns the remainder of the division of x by y that rounds the quotient
# toward zero (truncated division). Per Lua 5.3 §6.7:
#
# * If both x and y are integers, the result is an integer.
# * Otherwise the result is a float computed via C's fmod (matching
# `:math.fmod/2`).
# * For two integers, y == 0 raises "bad argument #2 ... (zero)".
# * The integer case y == -1 short-circuits to 0 to avoid overflow on
# `mininteger / -1` (matching the C implementation in lmathlib.c).
#
# Note: Lua 5.3 defines `math.fmod(x, 0.0)` as NaN for floats. The BEAM has
# no NaN value, so we raise instead — consistent with the rest of this VM,
# which raises on `0.0 / 0.0` and similar (see safe_divide/2 in
# Lua.VM.Executor).
defp math_fmod([x, y], _state) when is_integer(x) and is_integer(y) and y == 0 do
raise ArgumentError,
function_name: "math.fmod",
arg_num: 2,
details: "zero"
end

defp math_fmod([x, y], state) when is_integer(x) and is_integer(y) and y == -1 do
# Avoid overflow trap on mininteger / -1; remainder is always 0.
{[0], state}
end

defp math_fmod([x, y], state) when is_integer(x) and is_integer(y) do
{[Kernel.rem(x, y)], state}
end

defp math_fmod([x, y], _state) when is_number(x) and is_number(y) and y == 0 do
raise ArgumentError,
function_name: "math.fmod",
arg_num: 2,
details: "zero"
end

defp math_fmod([x, y], state) when is_number(x) and is_number(y) do
{[:math.fmod(x / 1, y / 1)], state}
end

defp math_fmod([x, y | _], _state) when is_number(x) do
raise ArgumentError,
function_name: "math.fmod",
arg_num: 2,
expected: "number",
got: Util.typeof(y)
end

defp math_fmod([x], _state) when is_number(x) do
raise ArgumentError.value_expected("math.fmod", 2)
end

defp math_fmod([x | _], _state) do
raise ArgumentError,
function_name: "math.fmod",
arg_num: 1,
expected: "number",
got: Util.typeof(x)
end

defp math_fmod([], _state) do
raise ArgumentError.value_expected("math.fmod", 1)
end

# math.log(x [, base])
defp math_log([x], state) when is_number(x) do
{[:math.log(x / 1)], state}
Expand Down
106 changes: 106 additions & 0 deletions test/lua/vm/stdlib/math_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ defmodule Lua.VM.Stdlib.MathTest do
alias Lua.Compiler
alias Lua.Parser
alias Lua.VM
alias Lua.VM.ArgumentError, as: LuaArgumentError
alias Lua.VM.State
alias Lua.VM.Stdlib

Expand Down Expand Up @@ -169,6 +170,111 @@ defmodule Lua.VM.Stdlib.MathTest do
VM.execute(proto, state)
end

test "math.fmod with two integers returns integer remainder (sign of dividend)" do
code = "return math.fmod(7, 3), math.fmod(-7, 3), math.fmod(7, -3), math.fmod(0, 5)"
assert {:ok, ast} = Parser.parse(code)
assert {:ok, proto} = Compiler.compile(ast, source: "test.lua")
state = Stdlib.install(State.new())

assert {:ok, [r1, r2, r3, r4], _state} = VM.execute(proto, state)
assert r1 === 1
assert r2 === -1
assert r3 === 1
assert r4 === 0
end

test "math.fmod with mixed int/float returns a float" do
code = "return math.fmod(7, 2.5), math.fmod(7.5, 2)"
assert {:ok, ast} = Parser.parse(code)
assert {:ok, proto} = Compiler.compile(ast, source: "test.lua")
state = Stdlib.install(State.new())

assert {:ok, [r1, r2], _state} = VM.execute(proto, state)
assert is_float(r1)
assert is_float(r2)
assert_in_delta r1, 2.0, 1.0e-9
assert_in_delta r2, 1.5, 1.0e-9
end

test "math.fmod with two floats returns a float matching :math.fmod/2" do
code = "return math.fmod(5.5, 2.0), math.fmod(-5.5, 2.0), math.fmod(5.5, -2.0)"
assert {:ok, ast} = Parser.parse(code)
assert {:ok, proto} = Compiler.compile(ast, source: "test.lua")
state = Stdlib.install(State.new())

assert {:ok, [r1, r2, r3], _state} = VM.execute(proto, state)
assert_in_delta r1, 1.5, 1.0e-9
assert_in_delta r2, -1.5, 1.0e-9
assert_in_delta r3, 1.5, 1.0e-9
end

test "math.fmod handles mininteger / -1 without overflow" do
code = "return math.fmod(math.mininteger, -1)"
assert {:ok, ast} = Parser.parse(code)
assert {:ok, proto} = Compiler.compile(ast, source: "test.lua")
state = Stdlib.install(State.new())

assert {:ok, [0], _state} = VM.execute(proto, state)
end

test "math.fmod with integer divisor of zero raises bad argument" do
code = "return math.fmod(5, 0)"
assert {:ok, ast} = Parser.parse(code)
assert {:ok, proto} = Compiler.compile(ast, source: "test.lua")
state = Stdlib.install(State.new())

assert_raise LuaArgumentError, ~r/bad argument #2 to 'math\.fmod' \(zero\)/, fn ->
VM.execute(proto, state)
end
end

test "math.fmod with float divisor of zero raises bad argument" do
# Lua 5.3 returns NaN here for floats, but BEAM has no NaN value, so we
# raise — consistent with other zero-divisor paths in this VM.
code = "return math.fmod(5.0, 0.0)"
assert {:ok, ast} = Parser.parse(code)
assert {:ok, proto} = Compiler.compile(ast, source: "test.lua")
state = Stdlib.install(State.new())

assert_raise LuaArgumentError, ~r/bad argument #2 to 'math\.fmod' \(zero\)/, fn ->
VM.execute(proto, state)
end
end

test "math.fmod rejects non-number arguments" do
assert {:ok, ast1} = Parser.parse("return math.fmod('x', 1)")
assert {:ok, proto1} = Compiler.compile(ast1, source: "test.lua")
state = Stdlib.install(State.new())

assert_raise LuaArgumentError, ~r/bad argument #1 to 'math\.fmod'/, fn ->
VM.execute(proto1, state)
end

assert {:ok, ast2} = Parser.parse("return math.fmod(1, 'x')")
assert {:ok, proto2} = Compiler.compile(ast2, source: "test.lua")

assert_raise LuaArgumentError, ~r/bad argument #2 to 'math\.fmod'/, fn ->
VM.execute(proto2, state)
end
end

test "math.fmod with too few arguments raises value expected" do
assert {:ok, ast0} = Parser.parse("return math.fmod()")
assert {:ok, proto0} = Compiler.compile(ast0, source: "test.lua")
state = Stdlib.install(State.new())

assert_raise LuaArgumentError, ~r/bad argument #1 to 'math\.fmod' \(value expected\)/, fn ->
VM.execute(proto0, state)
end

assert {:ok, ast1} = Parser.parse("return math.fmod(5)")
assert {:ok, proto1} = Compiler.compile(ast1, source: "test.lua")

assert_raise LuaArgumentError, ~r/bad argument #2 to 'math\.fmod' \(value expected\)/, fn ->
VM.execute(proto1, state)
end
end

test "math.random generates random numbers" do
code = """
math.randomseed(42)
Expand Down
2 changes: 1 addition & 1 deletion test/lua53_suite_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ defmodule Lua.Lua53SuiteTest do
|> Enum.sort()

# Tests that are ready to run (not skipped)
@ready_tests ["simple_test.lua", "api.lua", "code.lua", "vararg.lua"]
@ready_tests ["simple_test.lua", "api.lua", "bitwise.lua", "code.lua", "vararg.lua"]

# Tests that require features not yet implemented
# As we implement features, move tests from here to @ready_tests
Expand Down
Loading