Skip to content
Open
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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,13 @@ is in the [`1.0.0-rc.0`](#100-rc0---2026-05-26) entry below.
past the ceiling in a single allocation. Each raises the same catchable
`"resulting string too large"` error as `string.rep` and `..`, before the
result is built (#425).
- `os.time` normalises out-of-range date-table fields the way C `mktime` does
(e.g. `day = 0` is the last day of the previous month, `month = 13` is
January of the next year) instead of raising a `MatchError`.
Date-table fields are now validated like PUC-Lua's `os.time`: a field that
does not convert to an integer raises `field 'X' is not an integer`, and one
outside the C `int` range raises `field 'X' is out-of-bound` instead of
returning an integer beyond 64 bits.

## [1.0.2] - 2026-07-28

Expand Down
81 changes: 62 additions & 19 deletions lib/lua/vm/stdlib/os.ex
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ defmodule Lua.VM.Stdlib.Os do
alias Lua.VM.RuntimeError
alias Lua.VM.State
alias Lua.VM.Stdlib.Util
alias Lua.VM.Value

@impl true
def lib_name, do: "os"
Expand Down Expand Up @@ -96,15 +97,15 @@ defmodule Lua.VM.Stdlib.Os do
defp os_time([{:tref, _} = tref | _], state) do
data = State.get_table(state, tref).data

year = required_field(data, "year", "os.time")
month = required_field(data, "month", "os.time")
day = required_field(data, "day", "os.time")
hour = optional_field(data, "hour", 12)
min = optional_field(data, "min", 0)
sec = optional_field(data, "sec", 0)
year = date_field(data, "year", 1900, :required)
month = date_field(data, "month", 1, :required)
day = date_field(data, "day", 0, :required)
hour = date_field(data, "hour", 0, 12)
min = date_field(data, "min", 0, 0)
sec = date_field(data, "sec", 0, 0)

seconds =
naive_to_epoch(%{
date_fields_to_epoch(%{
year: year,
month: month,
day: day,
Expand Down Expand Up @@ -198,26 +199,68 @@ defmodule Lua.VM.Stdlib.Os do

## Helpers

defp required_field(data, key, fn_name) do
# Reads one date-table field the way PUC-Lua's `getfield` in loslib.c does:
# the value must convert to an integer (an integral float or a numeric
# string is accepted, anything else raises "not an integer"), and once the
# field's `delta` (1900 for year, 1 for month) is removed it must fit a C
# `int`, else "out-of-bound". The bound keeps the arithmetic in
# `date_fields_to_epoch/1` small: no field can push the result past 64 bits.
@c_int_min -2_147_483_648
@c_int_max 2_147_483_647

defp date_field(data, key, delta, default) do
case Map.get(data, key) do
n when is_number(n) ->
trunc(n)
nil when default == :required ->
raise RuntimeError, value: "field '#{key}' missing in date table for 'os.time'"

nil ->
default

value ->
n = field_integer(value, key)

_ ->
raise RuntimeError, value: "field '#{key}' missing in date table for '#{fn_name}'"
if n - delta < @c_int_min or n - delta > @c_int_max do
raise RuntimeError, value: "field '#{key}' is out-of-bound"
end

n
end
end

defp optional_field(data, key, default) do
case Map.get(data, key) do
n when is_number(n) -> trunc(n)
_ -> default
defp field_integer(n, _key) when is_integer(n), do: n

# A float converts only when it is integral and within the 64-bit range;
# NaN (`:nan`) and the huge values standing in for infinity do not.
defp field_integer(n, key) when is_float(n) do
if n == Float.floor(n) and n >= -9.223372036854776e18 and n < 9.223372036854776e18 do
trunc(n)
else
not_an_integer!(key)
end
end

defp naive_to_epoch(%{year: y, month: mo, day: d, hour: h, minute: mi, second: s}) do
{:ok, naive} = NaiveDateTime.new(y, mo, d, h, mi, s)
naive |> DateTime.from_naive!("Etc/UTC") |> DateTime.to_unix(:second)
defp field_integer(str, key) when is_binary(str) do
case Value.parse_number(str) do
nil -> not_an_integer!(key)
n -> field_integer(n, key)
end
end

defp field_integer(_other, key), do: not_an_integer!(key)

defp not_an_integer!(key), do: raise(RuntimeError, value: "field '#{key}' is not an integer")

# Lua 5.3 §6.9: date-table fields need not be within their valid ranges —
# C mktime normalises them (day = 0 is the last day of the previous month,
# month = 13 is January of the next year, hour = 25 rolls into the next day).
# Fold the month into the year, anchor on the 1st of that month, then add the
# remaining fields as a signed offset in seconds.
defp date_fields_to_epoch(%{year: y, month: mo, day: d, hour: h, minute: mi, second: s}) do
months = y * 12 + (mo - 1)
first_of_month = Date.new!(Integer.floor_div(months, 12), Integer.mod(months, 12) + 1, 1)
base = first_of_month |> DateTime.new!(~T[00:00:00], "Etc/UTC") |> DateTime.to_unix(:second)

base + (d - 1) * 86_400 + h * 3_600 + mi * 60 + s
end

defp strip_utc_flag("!" <> rest), do: {rest, true}
Expand Down
147 changes: 147 additions & 0 deletions test/lua/vm/stdlib/os_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -101,4 +101,151 @@ defmodule Lua.VM.Stdlib.OsTest do
end
end
end

# Lua 5.3 §6.9: date-table fields passed to os.time need not be within their
# valid ranges; they are normalised the way C mktime does.
describe "os.time field normalization" do
test "day = 0 is the last day of the previous month" do
assert normalize("year=2026, month=9, day=0") == {2026, 8, 31, 12, 0, 0}
assert normalize("year=2026, month=3, day=0") == {2026, 2, 28, 12, 0, 0}
assert normalize("year=2028, month=3, day=0") == {2028, 2, 29, 12, 0, 0}
end

test "day = 0 of month 1 rolls back into December of the previous year" do
assert normalize("year=2026, month=1, day=0") == {2025, 12, 31, 12, 0, 0}
end

test "month past December rolls into the next year" do
assert normalize("year=2026, month=13, day=1") == {2027, 1, 1, 12, 0, 0}
assert normalize("year=2026, month=12 + 1, day=0") == {2026, 12, 31, 12, 0, 0}
assert normalize("year=2026, month=14, day=1") == {2027, 2, 1, 12, 0, 0}
assert normalize("year=2026, month=24, day=1") == {2027, 12, 1, 12, 0, 0}
assert normalize("year=2026, month=25, day=0") == {2027, 12, 31, 12, 0, 0}
assert normalize("year=2026, month=25, day=1") == {2028, 1, 1, 12, 0, 0}
assert normalize("year=2026, month=100, day=1") == {2034, 4, 1, 12, 0, 0}
end

test "month below January rolls into the previous year" do
assert normalize("year=2026, month=0, day=1") == {2025, 12, 1, 12, 0, 0}
assert normalize("year=2026, month=-1, day=1") == {2025, 11, 1, 12, 0, 0}
assert normalize("year=2026, month=-13, day=1") == {2024, 11, 1, 12, 0, 0}
end

test "day past the end of the month overflows into the next month" do
assert normalize("year=2026, month=2, day=30") == {2026, 3, 2, 12, 0, 0}
assert normalize("year=2028, month=2, day=30") == {2028, 3, 1, 12, 0, 0}
assert normalize("year=2026, month=1, day=32") == {2026, 2, 1, 12, 0, 0}
assert normalize("year=2026, month=1, day=400") == {2027, 2, 4, 12, 0, 0}
end

test "negative day counts back across months and years" do
assert normalize("year=2026, month=1, day=-40") == {2025, 11, 21, 12, 0, 0}
end

test "time fields overflow and underflow across days" do
assert normalize("year=2026, month=12, day=31, hour=25") == {2027, 1, 1, 1, 0, 0}
assert normalize("year=2026, month=1, day=1, hour=0, min=0, sec=-10") == {2025, 12, 31, 23, 59, 50}
assert normalize("year=2026, month=1, day=1, hour=0, min=90") == {2026, 1, 1, 1, 30, 0}
end

test "in-range fields are unchanged" do
assert normalize("year=2000, month=1, day=1, hour=0, min=0, sec=0") == {2000, 1, 1, 0, 0, 0}
end
end

describe "os.time field validation" do
test "sec = 60 rolls into the next minute" do
assert normalize("year=2026, month=1, day=1, hour=0, min=0, sec=60") == {2026, 1, 1, 0, 1, 0}
end

test "years past 9999 are computed, not rejected" do
assert time_of("year=9999, month=13, day=1, hour=0") == 253_402_300_800
end

for field <- ~w(year month day hour min sec) do
test "#{field} beyond the C int range is out-of-bound" do
base = %{"year" => 2026, "month" => 1, "day" => 1, "hour" => 0, "min" => 0, "sec" => 0}

for huge <- ["2^31 + 2000", "2^40", "2^60", "-2^40", "-2^62", "math.maxinteger", "math.mininteger"] do
fields = base |> Map.put("#{unquote(field)}", huge) |> fields_to_lua()

assert {:error, msg} = time_error(fields)
assert msg =~ "field '#{unquote(field)}' is out-of-bound"
end
end
end

test "the C int boundary is inclusive, with the year and month offsets" do
# year is checked after subtracting 1900, month after subtracting 1.
assert {:ok, _} = time_error("year=2^31 - 1 + 1900, month=1, day=1")
assert {:error, msg} = time_error("year=2^31 + 1900, month=1, day=1")
assert msg =~ "field 'year' is out-of-bound"
assert {:ok, _} = time_error("year=-2^31 + 1900, month=1, day=1")
assert {:error, msg} = time_error("year=-2^31 + 1899, month=1, day=1")
assert msg =~ "field 'year' is out-of-bound"
assert {:ok, _} = time_error("year=2026, month=2^31, day=1")
assert {:error, msg} = time_error("year=2026, month=2^31 + 1, day=1")
assert msg =~ "field 'month' is out-of-bound"
assert {:ok, _} = time_error("year=2026, month=1, day=2^31 - 1")
assert {:error, msg} = time_error("year=2026, month=1, day=2^31")
assert msg =~ "field 'day' is out-of-bound"
end

test "results stay within 64 bits for the largest accepted fields" do
for fields <- [
"year=2^31 - 1 + 1900, month=2^31, day=2^31 - 1, hour=2^31 - 1, min=2^31 - 1, sec=2^31 - 1",
"year=-2^31 + 1900, month=-2^31 + 1, day=-2^31, hour=-2^31, min=-2^31, sec=-2^31"
] do
{[t], _} = Lua.eval!("return os.time({#{fields}})")
assert is_integer(t)
assert t >= -9_223_372_036_854_775_808 and t <= 9_223_372_036_854_775_807
end
end

test "fields with no integer representation raise 'not an integer'" do
for value <- ["1.5", "1/0", "-1/0", "0/0", "'x'", "{}", "true", "1e308"] do
assert {:error, msg} = time_error("year=2026, month=1, day=1, hour=#{value}")
assert msg =~ "field 'hour' is not an integer"
end

assert {:error, msg} = time_error("year=2026, month=1.5, day=1")
assert msg =~ "field 'month' is not an integer"
end

test "floats with an exact integer value and numeric strings are accepted" do
assert time_of("year=2026.0, month=1, day=1, hour=3.0") == time_of("year=2026, month=1, day=1, hour=3")
assert time_of("year=2026, month=1, day=1, hour='3'") == time_of("year=2026, month=1, day=1, hour=3")
assert time_of("year='2026', month='1', day='1'") == time_of("year=2026, month=1, day=1")
end

test "a missing required field still raises 'missing'" do
assert {:error, msg} = time_error("month=1, day=1")
assert msg =~ "field 'year' missing"
end
end

defp fields_to_lua(map), do: Enum.map_join(map, ", ", fn {k, v} -> "#{k}=#{v}" end)

defp time_of(fields) do
{[t], _} = Lua.eval!("return os.time({#{fields}})")
t
end

# Runs os.time under pcall so the Lua error message is available as a string.
defp time_error(fields) do
case Lua.eval!("return pcall(os.time, {#{fields}})") do
{[true, _], _} -> {:ok, nil}
{[false, msg], _} -> {:error, msg}
end
end

defp normalize(fields) do
code = """
local t = os.date("!*t", os.time({#{fields}}))
return t.year, t.month, t.day, t.hour, t.min, t.sec
"""

{[year, month, day, hour, min, sec], _} = Lua.eval!(code)
{year, month, day, hour, min, sec}
end
end
Loading