Files
rosetta/compat/luajit.lua
T
4DBug 8baa1f1388 ws-cleanup: compat math.clamp through math.min / math.max (LuaJIT)
The branchy compat clamp spawned side traces in hot loops: ~3.5x slower than min(max(x, lo), hi) in a
microbenchmark (NaN still passes through, as in Luau). MPEG-1 320x240 to rgba on LuaJIT (tuned traces):
2.92 -> 2.13 ms/frame.
2026-10-31 11:30:29 -05:00

657 lines
21 KiB
Lua

-- compat/luajit.lua: the Luau standard library pieces formats-luau uses, for LuaJIT 2.1 (plain luajit and LÖVE).
-- tools/build.py copies this file to build/luajit/formats/_compat.lua, and every built module starts with
-- local __compat = require("formats._compat") local buffer, bit32, utf8, typeof, type, __iter = ...
-- on its first line (so line numbers match the source). Nothing here is installed as a global; the table/math/string
-- additions (table.create, math.clamp, string.split, ...) are added to the standard libraries only where missing.
--
-- Semantics follow Luau (checked by tests/compat.luau under both runtimes):
-- bit32 unsigned 32-bit results; shift counts outside -31..31 give 0; extract/replace/countlz/countrz/byteswap
-- (fractional operands: see the bit32 section).
-- buffer fixed-size byte arrays on FFI memory, little-endian, zero-filled; out-of-bounds access throws
-- "buffer access out of bounds" like Luau. A buffer is a table { p = uint8_t*, n = length } with a
-- private metatable: typeof(b) and the injected type(b) return "buffer".
-- __iter Luau's generalized iteration (`for k, v in t do`): build.py rewrites such loops to
-- `for k, v in __iter(t) do`. Functions pass through; arrays iterate with ipairs (JIT-compiled) when the
-- table has no keys past #t, anything else with next.
-- LuaJIT-only extensions (not in Luau; host/love uses them when present): buffer.toffi(b) -> uint8_t* (valid while b
-- is alive), buffer.fromffi(ptr, n) -> a new buffer with a copy of n bytes.
local ffi = require("ffi")
local bit = require("bit")
local floor = math.floor
local rawtype, getmetatable, setmetatable, select, error, pairs, ipairs, next = type, getmetatable, setmetatable, select, error, pairs, ipairs, next
local TWO32 = 4294967296
local M = {}
-- ---------------------------------------------------------------------------------------------------- bit32
-- LuaJIT's bit.* take any number in +-2^51 (reduced mod 2^32) and return a signed int32; Luau returns the uint32.
-- Performance (inflate, pinned to one core): the sign fix written inline as `if r < 0 then r = r + 2^32 end` runs
-- about 45% faster than `r % 2^32`; operands are passed to bit.* as they are (no truncation step).
-- Divergence from Luau: a fractional operand is rounded by bit.tobit where Luau truncates it. The library never
-- passes fractions to bit32 (tests/compat.luau checks integers only).
do
local band, bor, bxor, bnot, lshift, rshift, arshift, bswap =
bit.band, bit.bor, bit.bxor, bit.bnot, bit.lshift, bit.rshift, bit.arshift, bit.bswap
local B = {}
-- the 2- and 3-argument forms are the hot ones: no varargs on that path
function B.band(a, b, c, d, ...)
local r
if b == nil then
if a == nil then return TWO32 - 1 end
r = band(a, -1)
else
r = band(a, b)
if c ~= nil then
r = band(r, c)
if d ~= nil then
r = band(r, d)
for i = 1, select("#", ...) do r = band(r, (select(i, ...))) end
end
end
end
if r < 0 then r = r + TWO32 end
return r
end
function B.bor(a, b, c, d, ...)
local r
if b == nil then
if a == nil then return 0 end
r = band(a, -1)
else
r = bor(a, b)
if c ~= nil then
r = bor(r, c)
if d ~= nil then
r = bor(r, d)
for i = 1, select("#", ...) do r = bor(r, (select(i, ...))) end
end
end
end
if r < 0 then r = r + TWO32 end
return r
end
function B.bxor(a, b, c, d, e, f, g, h, ...)
local r
if b == nil then
if a == nil then return 0 end
r = band(a, -1)
else
r = bxor(a, b)
if c ~= nil then
r = bxor(r, c)
if d ~= nil then
r = bxor(r, d)
if e ~= nil then
r = bxor(r, e)
if f ~= nil then
r = bxor(r, f)
if g ~= nil then
r = bxor(r, g)
if h ~= nil then
r = bxor(r, h)
for i = 1, select("#", ...) do r = bxor(r, (select(i, ...))) end
end
end
end
end
end
end
end
if r < 0 then r = r + TWO32 end
return r
end
function B.btest(...)
return B.band(...) ~= 0
end
function B.bnot(a)
local r = bnot(a)
if r < 0 then r = r + TWO32 end
return r
end
function B.lshift(a, n)
if n >= 32 or n <= -32 then return 0 end
local r
if n < 0 then r = rshift(a, -n) else r = lshift(a, n) end
if r < 0 then r = r + TWO32 end
return r
end
function B.rshift(a, n)
if n >= 32 or n <= -32 then return 0 end
local r
if n < 0 then r = lshift(a, -n) else r = rshift(a, n) end
if r < 0 then r = r + TWO32 end
return r
end
function B.arshift(a, n)
if n <= -32 then return 0 end
if n >= 32 then n = 31 end
local r
if n < 0 then r = lshift(a, -n) else r = arshift(a, n) end
if r < 0 then r = r + TWO32 end
return r
end
function B.lrotate(a, n)
n = n % 32
local r = n == 0 and band(a, -1) or bor(lshift(a, n), rshift(a, 32 - n))
if r < 0 then r = r + TWO32 end
return r
end
function B.rrotate(a, n)
return B.lrotate(a, -n)
end
function B.extract(a, field, width)
width = width or 1
if field < 0 or width <= 0 or field + width > 32 then error("bit32.extract: trying to access non-existent bits", 2) end
local r = rshift(a, field)
if width < 32 then r = band(r, lshift(1, width) - 1) end
if r < 0 then r = r + TWO32 end
return r
end
function B.replace(a, v, field, width)
width = width or 1
if field < 0 or width <= 0 or field + width > 32 then error("bit32.replace: trying to access non-existent bits", 2) end
local m = width == 32 and -1 or lshift(lshift(1, width) - 1, field)
local r = bor(band(a, bnot(m)), band(lshift(v, field), m))
if r < 0 then r = r + TWO32 end
return r
end
function B.countlz(a)
a = band(a, -1)
if a == 0 then return 32 end
local n = 0
if band(a, -65536) == 0 then n = n + 16; a = lshift(a, 16) end
if band(a, -16777216) == 0 then n = n + 8; a = lshift(a, 8) end
if band(a, -268435456) == 0 then n = n + 4; a = lshift(a, 4) end
if band(a, -1073741824) == 0 then n = n + 2; a = lshift(a, 2) end
if band(a, -2147483648) == 0 then n = n + 1 end
return n
end
function B.countrz(a)
a = band(a, -1)
if a == 0 then return 32 end
local n = 0
while band(a, 1) == 0 do
a = rshift(a, 1)
n = n + 1
end
return n
end
function B.byteswap(a)
local r = bswap(a)
if r < 0 then r = r + TWO32 end
return r
end
M.bit32 = B
end
-- ---------------------------------------------------------------------------------------------------- buffer
do
ffi.cdef([[
void *memmove(void *dst, const void *src, size_t n);
void *memset(void *s, int c, size_t n);
void *calloc(size_t n, size_t size);
void free(void *p);
]])
local C = ffi.C
local u8p = ffi.typeof("uint8_t*")
local i8p = ffi.typeof("int8_t*")
local u16p, i16p = ffi.typeof("uint16_t*"), ffi.typeof("int16_t*")
local u32p, i32p = ffi.typeof("uint32_t*"), ffi.typeof("int32_t*")
local f32p, f64p = ffi.typeof("float*"), ffi.typeof("double*")
local u8arr = ffi.typeof("uint8_t[?]")
local cast, fstring, fcopy = ffi.cast, ffi.string, ffi.copy
local BUF = { __name = "buffer" }
BUF.__index = function() error("attempt to index a buffer value", 2) end
BUF.__tostring = function(b) return ("buffer: %p"):format(b.p) end
M.BUFFER_MT = BUF
-- Small buffers live in GC memory (ffi.new); big ones in calloc'd memory, so they do not count against the
-- 2 GB GC heap of non-GC64 builds (LÖVE). The GC does not see calloc'd bytes, so a full collection runs every
-- 512 MB of them.
local BIG = 262144
local external = 0
local function oob()
error("buffer access out of bounds", 3)
end
local Buf = {}
local function create(n)
if rawtype(n) ~= "number" or n < 0 then error("buffer.create: invalid size", 2) end
n = floor(n)
local mem, p
if n < BIG then
mem = u8arr(n > 0 and n or 1)
p = cast(u8p, mem)
else
external = external + n
if external > 536870912 then
external = 0
collectgarbage()
end
local raw = C.calloc(n, 1)
if raw == nil then error("buffer.create: out of memory", 2) end
mem = ffi.gc(cast(u8p, raw), C.free)
p = mem
end
-- p, n and m are raw fields, so the throwing __index only runs for misuse (b.x on a buffer)
return setmetatable({ p = p, n = n, m = mem }, BUF)
end
Buf.create = create
function Buf.len(b) return b.n end
-- reads / writes: o must satisfy 0 <= o and o + size <= n (Luau truncates a fractional offset)
function Buf.readu8(b, o)
if o < 0 or o >= b.n then oob() end
return b.p[o]
end
function Buf.readi8(b, o)
if o < 0 or o >= b.n then oob() end
return cast(i8p, b.p)[o]
end
function Buf.readu16(b, o)
if o < 0 or o + 2 > b.n then oob() end
return cast(u16p, b.p + o)[0]
end
function Buf.readi16(b, o)
if o < 0 or o + 2 > b.n then oob() end
return cast(i16p, b.p + o)[0]
end
function Buf.readu32(b, o)
if o < 0 or o + 4 > b.n then oob() end
return cast(u32p, b.p + o)[0]
end
function Buf.readi32(b, o)
if o < 0 or o + 4 > b.n then oob() end
return cast(i32p, b.p + o)[0]
end
-- NaNs are checked through their bits before the float is loaded: a NaN with an arbitrary payload, handed back by
-- the FFI, can alias LuaJIT's NaN-tagged object values (read as a table / userdata). Return the canonical NaN.
local NAN = 0 / 0
function Buf.readf32(b, o)
if o < 0 or o + 4 > b.n then oob() end
local bits = cast(u32p, b.p + o)[0]
if bits % 0x80000000 > 0x7f800000 then return NAN end
return cast(f32p, b.p + o)[0]
end
function Buf.readf64(b, o)
if o < 0 or o + 8 > b.n then oob() end
local hi = cast(u32p, b.p + o + 4)[0] % 0x80000000 -- little-endian: sign / exponent / top mantissa bits
if hi >= 0x7ff00000 and (hi > 0x7ff00000 or cast(u32p, b.p + o)[0] ~= 0) then return NAN end
return cast(f64p, b.p + o)[0]
end
-- integer writes wrap like Luau (300 -> 44, -1 -> 255); the double -> int conversion goes through int32 for
-- 8/16-bit stores and through int64 for 32-bit ones, so values in +-2^51 wrap correctly
function Buf.writeu8(b, o, v)
if o < 0 or o >= b.n then oob() end
b.p[o] = v
end
function Buf.writei8(b, o, v)
if o < 0 or o >= b.n then oob() end
b.p[o] = v
end
function Buf.writeu16(b, o, v)
if o < 0 or o + 2 > b.n then oob() end
cast(u16p, b.p + o)[0] = v
end
Buf.writei16 = Buf.writeu16
function Buf.writeu32(b, o, v)
if o < 0 or o + 4 > b.n then oob() end
cast(u32p, b.p + o)[0] = v % TWO32
end
Buf.writei32 = Buf.writeu32
function Buf.writef32(b, o, v)
if o < 0 or o + 4 > b.n then oob() end
cast(f32p, b.p + o)[0] = v
end
function Buf.writef64(b, o, v)
if o < 0 or o + 8 > b.n then oob() end
cast(f64p, b.p + o)[0] = v
end
function Buf.readstring(b, o, count)
if o < 0 or count < 0 or o + count > b.n then oob() end
return fstring(b.p + o, count)
end
function Buf.writestring(b, o, s, count)
count = count or #s
if count < 0 or count > #s then error("buffer.writestring: string length overflow", 2) end
if o < 0 or o + count > b.n then oob() end
fcopy(b.p + o, s, count)
end
function Buf.copy(target, toff, source, soff, count)
soff = soff or 0
if soff < 0 or soff > source.n then oob() end
count = count or (source.n - soff)
if count < 0 or soff + count > source.n or toff < 0 or toff + count > target.n then oob() end
if count > 0 then C.memmove(target.p + toff, source.p + soff, count) end
end
function Buf.fill(b, o, v, count)
if o < 0 or o > b.n then oob() end
count = count or (b.n - o)
if count < 0 or o + count > b.n then oob() end
if count > 0 then C.memset(b.p + o, v % 256, count) end
end
function Buf.tostring(b) return fstring(b.p, b.n) end
function Buf.fromstring(s)
local b = create(#s)
fcopy(b.p, s, #s)
return b
end
-- readbits / writebits: bit i of the buffer is bit (i % 8) of byte i // 8 (little-endian bit order), up to 32 bits
function Buf.readbits(b, bitOffset, bitCount)
if bitCount < 0 or bitCount > 32 then error("bit count is out of range of [0; 32]", 2) end
if bitOffset < 0 or bitOffset + bitCount > b.n * 8 then oob() end
local v, scale = 0, 1
local i = bitOffset
local e = bitOffset + bitCount
while i < e do
local byte = floor(i / 8)
local sh = i % 8
local take = 8 - sh
if take > e - i then take = e - i end
local x = bit.band(bit.rshift(b.p[byte], sh), bit.lshift(1, take) - 1)
v = v + x * scale
scale = scale * 2 ^ take
i = i + take
end
return v
end
function Buf.writebits(b, bitOffset, bitCount, value)
if bitCount < 0 or bitCount > 32 then error("bit count is out of range of [0; 32]", 2) end
if bitOffset < 0 or bitOffset + bitCount > b.n * 8 then oob() end
value = value % TWO32
local i = bitOffset
local e = bitOffset + bitCount
while i < e do
local byte = floor(i / 8)
local sh = i % 8
local take = 8 - sh
if take > e - i then take = e - i end
local m = bit.lshift(bit.lshift(1, take) - 1, sh)
local x = bit.band(bit.lshift(value % 256, sh), m)
b.p[byte] = bit.bor(bit.band(b.p[byte], bit.bnot(m)), x)
value = floor(value / 2 ^ take)
i = i + take
end
end
-- LuaJIT-only extensions
function Buf.toffi(b) return b.p end
function Buf.fromffi(ptr, n)
local b = create(n)
if n > 0 then fcopy(b.p, ptr, n) end
return b
end
M.buffer = Buf
end
-- ---------------------------------------------------------------------------------------------------- typeof / type
do
local BUF = M.BUFFER_MT
function M.type(v)
local t = rawtype(v)
if t == "table" and getmetatable(v) == BUF then
return "buffer"
end
return t
end
M.typeof = M.type
M.isbuffer = function(v) return getmetatable(v) == BUF end
end
-- ---------------------------------------------------------------------------------------------------- __iter
local function arrayIter(s, i)
local t, n = s[1], s[2]
i = i + 1
local v = t[i]
while v == nil and i < n do
i = i + 1
v = t[i]
end
if v ~= nil then return i, v end
end
function M.__iter(t, s, c)
if rawtype(t) == "function" then return t, s, c end
if rawtype(t) ~= "table" then error("attempt to iterate over a " .. M.type(t) .. " value", 2) end
local mt = getmetatable(t)
if rawtype(mt) == "table" and mt.__iter then return mt.__iter(t) end
local n = #t
-- every key is an integer in 1..n (next(t, n) == nil: nothing after n in the array part, an empty hash part;
-- LuaJIT keeps t[0] in the array part, so check it): walk 1..n skipping holes. #t is any border, so sparse maps
-- such as {[6] = a, [7] = b} (n = 7, t[1] == nil) and arrays with holes visit every key, as in Luau.
if n > 0 and t[0] == nil and next(t, n) == nil then
return arrayIter, { t, n }, 0
end
return next, t, nil
end
-- ---------------------------------------------------------------------------------------------------- table
do
local okn, tnew = pcall(require, "table.new")
local okc, tclear = pcall(require, "table.clear")
if not table.create then
function table.create(n, v)
local t = okn and tnew(n, 0) or {}
if v ~= nil then for i = 1, n do t[i] = v end end
return t
end
end
table.clear = table.clear or (okc and tclear) or function(t) for k in pairs(t) do t[k] = nil end end
table.unpack = table.unpack or unpack
table.pack = table.pack or function(...) return { n = select("#", ...), ... } end
table.find = table.find or function(t, v, init)
for i = init or 1, #t do if t[i] == v then return i end end
return nil
end
table.move = table.move or function(a1, f, e, t, a2)
a2 = a2 or a1
if e >= f then
if t > f or t > e or a1 ~= a2 then
for i = 0, e - f do a2[t + i] = a1[f + i] end
else
for i = e - f, 0, -1 do a2[t + i] = a1[f + i] end
end
end
return a2
end
-- freeze is advisory on LuaJIT (no read-only tables): it only records the table for isfrozen
local frozen = setmetatable({}, { __mode = "k" })
table.freeze = table.freeze or function(t) frozen[t] = true; return t end
table.isfrozen = table.isfrozen or function(t) return frozen[t] == true end
table.clone = table.clone or function(t)
local c = {}
for k, v in pairs(t) do c[k] = v end
return setmetatable(c, getmetatable(t))
end
table.maxn = table.maxn or function(t)
local m = 0
for k in pairs(t) do if rawtype(k) == "number" and k > m then m = k end end
return m
end
end
-- ---------------------------------------------------------------------------------------------------- math
do
-- math.min / math.max are LuaJIT fast functions (branch-free minsd / maxsd in a trace); the two data-dependent
-- branches of `if x < lo ... elseif x > hi` spawned side traces in hot loops (codecs/Dct, colour conversion) and
-- ran ~3.5x slower. NaN stays NaN, as in Luau (maxsd would return lo).
local mmin, mmax = math.min, math.max
math.clamp = math.clamp or function(x, lo, hi)
if lo > hi then error("max must be greater than or equal to min", 2) end
if x ~= x then return x end
return mmin(mmax(x, lo), hi)
end
math.sign = math.sign or function(x)
if x > 0 then return 1 elseif x < 0 then return -1 end
return 0
end
-- Luau rounds half away from zero
math.round = math.round or function(x)
if x >= 0 then return floor(x + 0.5) end
return -floor(-x + 0.5)
end
math.lerp = math.lerp or function(a, b, t) return t == 1 and b or a + (b - a) * t end
math.map = math.map or function(x, a, b, c, d) return c + (d - c) * (x - a) / (b - a) end
math.isnan = math.isnan or function(x) return x ~= x end
math.isinf = math.isinf or function(x) return x == math.huge or x == -math.huge end
math.isfinite = math.isfinite or function(x) return x == x and x ~= math.huge and x ~= -math.huge end
-- stub: deterministic but not Roblox's Perlin noise (nothing in the library depends on its values)
math.noise = math.noise or function(x, y, z)
local s = math.sin((x or 0) * 12.9898 + (y or 0) * 78.233 + (z or 0) * 37.719) * 43758.5453
return (s - floor(s)) - 0.5
end
end
-- ---------------------------------------------------------------------------------------------------- string
string.split = string.split or function(s, sep)
sep = sep or ","
local out = {}
if sep == "" then
for i = 1, #s do out[i] = s:sub(i, i) end
return out
end
local i = 1
while true do
local a, b = s:find(sep, i, true)
if not a then
out[#out + 1] = s:sub(i)
return out
end
out[#out + 1] = s:sub(i, a - 1)
i = b + 1
end
end
-- ---------------------------------------------------------------------------------------------------- utf8
do
-- Lua 5.1 patterns cannot hold a NUL byte: %z stands for it
local U = { charpattern = "[%z\x01-\x7F\xC2-\xFD][\x80-\xBF]*" }
local char, byte = string.char, string.byte
local function enc(c)
if c < 0x80 then return char(c)
elseif c < 0x800 then return char(0xC0 + floor(c / 64), 0x80 + c % 64)
elseif c < 0x10000 then return char(0xE0 + floor(c / 4096), 0x80 + floor(c / 64) % 64, 0x80 + c % 64)
end
return char(0xF0 + floor(c / 262144), 0x80 + floor(c / 4096) % 64, 0x80 + floor(c / 64) % 64, 0x80 + c % 64)
end
function U.char(...)
local n = select("#", ...)
if n == 1 then return enc((...)) end
local out = {}
for i = 1, n do out[i] = enc((select(i, ...))) end
return table.concat(out)
end
-- decode at byte i: codepoint, length; nil on invalid UTF-8
local function dec(s, i)
local c = byte(s, i)
if not c then return nil end
if c < 0x80 then return c, 1 end
local n, v
if c >= 0xF0 and c < 0xF8 then n, v = 4, c % 8
elseif c >= 0xE0 then n, v = 3, c % 16
elseif c >= 0xC2 then n, v = 2, c % 32
else return nil end
if c >= 0xF8 then return nil end
for k = 1, n - 1 do
local cc = byte(s, i + k)
if not cc or cc < 0x80 or cc >= 0xC0 then return nil end
v = v * 64 + cc % 64
end
if (n == 3 and v < 0x800) or (n == 4 and (v < 0x10000 or v > 0x10FFFF)) or (v >= 0xD800 and v <= 0xDFFF) then
return nil
end
return v, n
end
function U.codes(s)
local i = 1
return function()
if i > #s then return nil end
local c, n = dec(s, i)
if not c then error("invalid UTF-8 code", 2) end
local p = i
i = i + n
return p, c
end
end
function U.codepoint(s, i, j)
i = i or 1
if i < 0 then i = #s + i + 1 end
j = j or i
if j < 0 then j = #s + j + 1 end
local out, k = {}, 0
while i <= j do
local c, n = dec(s, i)
if not c then error("invalid UTF-8 code", 2) end
k = k + 1
out[k] = c
i = i + n
end
return unpack(out, 1, k)
end
-- len(s, i, j) -> count | nil, position of the first invalid byte
function U.len(s, i, j)
i = i or 1
j = j or #s
if i < 0 then i = #s + i + 1 end
if j < 0 then j = #s + j + 1 end
local n = 0
while i <= j do
local c, l = dec(s, i)
if not c then return nil, i end
n = n + 1
i = i + l
end
return n
end
local function iscont(s, i)
local c = byte(s, i)
return c ~= nil and c >= 0x80 and c < 0xC0
end
function U.offset(s, n, i)
i = i or (n >= 0 and 1 or #s + 1)
if i < 0 then i = #s + i + 1 end
if n == 0 then
while i > 1 and iscont(s, i) do i = i - 1 end
return i
end
if iscont(s, i) then error("initial position is a continuation byte", 2) end
if n > 0 then
n = n - 1
while n > 0 and i <= #s do
i = i + 1
while iscont(s, i) do i = i + 1 end
n = n - 1
end
if n == 0 then return i end
return nil
end
while n < 0 and i > 1 do
i = i - 1
while i > 1 and iscont(s, i) do i = i - 1 end
n = n + 1
end
if n == 0 then return i end
return nil
end
function U.graphemes(s)
return U.codes(s)
end
M.utf8 = utf8 or U
end
-- install(): put the Luau globals in _G for code outside the library (a LÖVE game that wants buffer / bit32 itself)
function M.install(env)
env = env or _G
env.buffer = env.buffer or M.buffer
env.bit32 = env.bit32 or M.bit32
env.utf8 = env.utf8 or M.utf8
env.typeof = env.typeof or M.typeof
return M
end
return M