formats-luau foundation: build (darklua + token passes) for Roblox and LuaJIT, compat prelude, core, Types, host adapters, API + registry, lint, tests on both runtimes; absorb deflate (codecs/Deflate + new compressor) and png (image/png + new encoder)

This commit is contained in:
4DBug committed 2026-10-31 08:18:01 -05:00
commit cdcb5b0b77
226 files changed
+8409

No files matched your search

+58
View File
@@ -0,0 +1,58 @@
-- Throughput (bash tools/bench.sh): codec MB/s under both runtimes. MB/s are of decompressed output, best of n runs.
-- Fixtures: tools/fixtures/deflate.py (a 6 MB corpus) and tools/fixtures/png.py (1024 x 768 images).
local Deflate = require("@formats/codecs/Deflate")
local Crc32 = require("@formats/core/Crc32")
local Bytes = require("@formats/core/Bytes")
local Png = require("@formats/image/png")
local B = require("@tests/gen/deflate_bench")
local PB = require("@tests/gen/png_bench")
local runtime = if (_G :: any).jit ~= nil then "luajit" else "luau"
local function bench(label: string, n: number, bytes: number, f: () -> ())
f()
local dt = math.huge -- best of n: the machine is shared, the mean is noisy
for _ = 1, n do
local t0 = os.clock()
f()
dt = math.min(dt, os.clock() - t0)
end
print(string.format("%-8s %-30s %8.2f ms %7.1f MB/s", runtime, label, dt * 1000, bytes / dt / 1e6))
end
local z = buffer.fromstring(B.zlib)
local g = buffer.fromstring(B.gzip)
local out = assert(Deflate.zlib(z))
assert(buffer.len(out) == B.size and Crc32.of(out) == B.crc, "bench corpus mismatch")
bench("inflate (growing output)", 5, B.size, function()
Deflate.inflate(z, 2, buffer.len(z) - 6)
end)
bench("inflate (exact size)", 5, B.size, function()
Deflate.inflate(z, 2, buffer.len(z) - 6, B.size)
end)
bench("zlib (+ adler32)", 5, B.size, function()
Deflate.zlib(z)
end)
bench("gunzip (+ crc32)", 5, B.size, function()
Deflate.gunzip(g)
end)
bench("crc32", 10, B.size, function()
Crc32.of(out)
end)
local part = buffer.create(1500000)
buffer.copy(part, 0, out, 0, 1500000)
bench("compress -6 (1.5 MB in)", 2, 1500000, function()
Deflate.compress(part, { level = 6 })
end)
for _, c in PB do
local b = buffer.fromstring(c.data)
bench("png decode " .. c.name, 3, c.width * c.height * 4, function()
Png.decode(Bytes.reader(b))
end)
end
do
local img = assert(Png.decode(Bytes.reader(buffer.fromstring(PB[1].data))))
bench("png encode rgba8", 2, img.width * img.height * 4, function()
Png.encode(img)
end)
end
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Timings (bash tools/bench.sh): tools/bench.luau under luau --codegen -O2 and under LuaJIT (the build output).
cd "$(dirname "$0")/.." || exit 1
LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')}
LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')}
python3 -I tools/fixtures.py deflate png > /dev/null || exit 1
python3 -I tools/build.py luajit > /dev/null || exit 1
"$LUAU" --codegen -O2 tools/bench.luau
"$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua
+440
View File
@@ -0,0 +1,440 @@
#!/usr/bin/env python3
# Build (python3 -I tools/build.py [roblox|luajit ...]): the two outputs of the one Luau source tree.
#
# build/roblox/Formats/... darklua convert_require (luau aliases -> Roblox instance paths). Types, --!native and
# @native are kept. Mounted by default.project.json (rojo build / rojo serve).
# build/luajit/formats/... plain Lua 5.1 for LuaJIT / LÖVE: darklua strips types, attributes (@native) and the
# Luau-only syntax, then the token passes below; requires become require("formats.a.b").
# build/luajit/tools/... tools/*.luau (bench), built the same way.
# build/luajit/tests/... the tests, built the same way (require("@tests/T") -> require("tests.T")); tests/gen
# fixture modules are copied as they are (plain string literals; darklua is slow on them).
#
# Load the LuaJIT output with package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path, then
# local F = require("formats").
#
# What darklua 0.19 cannot do, done here as token-level passes (lexer from imgui-luau tools/minify.py):
# 1. Generalized iteration (`for k, v in t do`): darklua has no rule for it. Every generic for whose iterator
# expression does not start with pairs / ipairs / next becomes `for k, v in __iter(expr) do` (compat's __iter:
# functions pass through with their state, arrays use ipairs, other tables next).
# 2. Luau stdlib names: each module gets, on its first line (line numbers stay the same), only the locals it uses of
# buffer, bit32, utf8, typeof, type, __iter from formats._compat (LuaJIT has a 60-upvalue limit per function).
# 3. If-expressions: darklua lowers `if c then a else b` to `(c and {a} or {b})[1]`, a table per evaluation. When
# `a` is provably not nil/false (a number or string literal, `#x`, or an arithmetic / concatenation expression
# at its top level) it becomes `(c and a or b)`.
# 4. Requires: `require("@formats/x/y")` -> `require("formats.x.y")`, `require("@tests/x")` -> `require("tests.x")`,
# done on the source before darklua (string literals only; computed requires are not allowed in the library).
import json, os, re, shutil, subprocess, sys, tempfile
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC = os.path.join(ROOT, "src", "Formats")
TESTS = os.path.join(ROOT, "tests")
BUILD = os.path.join(ROOT, "build")
# darklua 0.19: $DARKLUA, else on PATH, else through nix
DARKLUA = os.environ.get("DARKLUA", "").split() or (["darklua"] if shutil.which("darklua") else
["nix", "shell", "nixpkgs#darklua", "-c", "darklua"])
LUAJIT_RULES = [
"remove_types",
"remove_attribute",
"remove_compound_assignment",
"remove_continue",
"remove_if_expression",
"remove_interpolated_string",
"remove_floor_division",
"convert_luau_number",
]
ROBLOX_RULES = [
{"rule": "convert_require", "current": {"name": "luau"}, "target": {"name": "roblox", "indexing_style": "property"}},
]
COMPAT_NAMES = ["buffer", "bit32", "utf8", "typeof", "type", "__iter"]
# ------------------------------------------------------------------------------------------------ lexer
TOKEN = re.compile(r"""
(?P<ws>[ \t\r\n\f\v]+)
| (?P<lcom>--\[(?P<ceq>=*)\[.*?\](?P=ceq)\])
| (?P<com>--[^\n]*)
| (?P<lstr>\[(?P<seq>=*)\[.*?\](?P=seq)\])
| (?P<str>"(?:\\.|\\\n|[^"\\\n])*"|'(?:\\.|\\\n|[^'\\\n])*'|`(?:\\.|\\\n|[^`\\])*`)
| (?P<num>0[xX][0-9a-fA-F_]*(?:\.[0-9a-fA-F_]*)?(?:[pP][+-]?\d+)?|0[bB][01_]+|(?:\d[\d_]*(?:\.[\d_]*)?|\.\d[\d_]*)(?:[eE][+-]?\d+)?)
| (?P<name>@?[A-Za-z_]\w*)
| (?P<op>\.\.\.|\.\.=|//=|\.\.|==|~=|<=|>=|//|::|->|[-+*/%^]=|.)
""", re.S | re.X)
def lex(src):
"""[(kind, text, start, end)] of the significant tokens (whitespace and comments dropped)."""
out, pos = [], 0
while pos < len(src):
m = TOKEN.match(src, pos)
kind = m.lastgroup
if kind in ("ceq", "seq"):
kind = "lcom" if m.group(0).startswith("--") else "lstr"
if kind not in ("ws", "lcom", "com"):
out.append(("str" if kind == "lstr" else kind, m.group(0), m.start(), m.end()))
pos = m.end()
return out
def apply(src, edits):
"""edits: [(start, end, text)], non-overlapping."""
for s, e, t in sorted(edits, reverse=True):
src = src[:s] + t + src[e:]
return src
OPEN = {"(": ")", "[": "]", "{": "}"}
BLOCK_OPEN = {"function", "do", "then", "repeat"} # each closes with `end` (repeat with `until`)
def match_close(toks, i):
"""index of the bracket closing toks[i] ( ( [ { )."""
depth = 0
for j in range(i, len(toks)):
t = toks[j][1]
if toks[j][0] == "op" and t in OPEN:
depth += 1
elif toks[j][0] == "op" and t in (")", "]", "}"):
depth -= 1
if depth == 0:
return j
return -1
# ------------------------------------------------------------------------------------------------ pass 1: __iter
def pass_iter(src):
toks = lex(src)
edits = []
for i, (k, t, s, e) in enumerate(toks):
if k != "name" or t != "for":
continue
# find `in` or `=` at depth 0
j = i + 1
while j < len(toks) and not (toks[j][0] == "name" and toks[j][1] == "in") and toks[j][1] != "=":
j += 1
if j >= len(toks) or toks[j][1] == "=":
continue
first = j + 1
# the expression runs to the `do` at bracket depth 0 and function depth 0
depth, fdepth, comma, q = 0, 0, False, first
while q < len(toks):
qk, qt = toks[q][0], toks[q][1]
if qk == "op" and qt in OPEN:
depth += 1
elif qk == "op" and qt in (")", "]", "}"):
depth -= 1
elif qk == "name" and qt == "function":
fdepth += 1
elif qk == "name" and qt == "end" and fdepth > 0:
fdepth -= 1
elif qk == "name" and qt == "do" and depth == 0 and fdepth == 0:
break
elif qk == "op" and qt == "," and depth == 0 and fdepth == 0:
comma = True
q += 1
if q >= len(toks) or comma:
continue
if toks[first][0] == "name" and toks[first][1] in ("pairs", "ipairs", "next"):
continue
edits.append((toks[first][2], toks[first][2], "__iter("))
edits.append((toks[q - 1][3], toks[q - 1][3], ")"))
return apply(src, edits)
# ------------------------------------------------------------------------------------------------ pass 0: elseif
# darklua 0.19's remove_if_expression nests the elseif branches of an if-expression in reverse order (it folds them
# front to back): `if a then 1 elseif b then 2 elseif c then 3 else 4` becomes `a and 1 or (c and 3 or (b and 2 or 4))`.
# Before darklua, every `elseif` of an if-expression becomes `else if` (a nested if-expression, same meaning), so
# darklua only ever sees single-branch if-expressions. Statement ifs are told apart from expression ifs by the token
# before `if` and a stack of open constructs (blocks close with end / until; an expression if closes at its else).
EXPR_PREV = {"=", "(", ",", "{", "[", "return", "in", "and", "or", "not", "..", "+", "-", "*", "/", "//", "%", "^",
"#", "==", "~=", "<", ">", "<=", ">=", "+=", "-=", "*=", "/=", "//=", "%=", "^=", "..=", "if", "elseif",
"while", "until"}
def pass_elseif(src):
toks = lex(src)
edits = []
stack = [] # "block" (function / do: end), "repeat" (until), "sif" (statement if: end), "eif" (expression if)
prev, prev_else_eif, prev_then_eif = None, False, False
for k, t, s, e in toks:
kw = t if k == "name" else (t if k == "op" else None)
else_eif = then_eif = False
if kw == "if":
expr = prev in EXPR_PREV or (prev == "then" and prev_then_eif) or (prev == "else" and prev_else_eif)
stack.append("eif" if expr else "sif")
elif kw == "then":
then_eif = bool(stack) and stack[-1] == "eif"
elif kw == "elseif":
if stack and stack[-1] == "eif":
edits.append((s, e, "else if"))
# the old expression closes at this else; the new nested one is still an expression if
then_eif = False
elif kw == "else":
if stack and stack[-1] == "eif":
stack.pop()
else_eif = True
elif kw in ("function", "do"):
stack.append("block")
elif kw == "repeat":
stack.append("repeat")
elif kw == "end" or kw == "until":
while stack and stack[-1] == "eif": # malformed input; keep going
stack.pop()
if stack:
stack.pop()
prev = t if k in ("name", "op") else k
prev_else_eif, prev_then_eif = else_eif, then_eif
return apply(src, edits)
# ------------------------------------------------------------------------------------------------ pass 3: if-expressions
ARITH = {"+", "-", "*", "/", "%", "^", ".."}
NOT_SAFE = {"and", "or", "not", "==", "~=", "<", ">", "<=", ">="}
def safe_truthy(toks):
"""True when the expression toks always yields a number or a string (never nil / false)."""
if not toks:
return False
if len(toks) == 1:
return toks[0][0] in ("num", "str")
depth, arith = 0, False
for idx, (k, t, _, _) in enumerate(toks):
if k == "op" and t in OPEN:
depth += 1
elif k == "op" and t in (")", "]", "}"):
depth -= 1
elif depth == 0:
if t in NOT_SAFE or t == "function":
return False
if k == "op" and t in ARITH and idx > 0:
arith = True
if toks[0][1] == "#" and not arith:
# `#x` alone; `#x .. y` etc are covered by arith
return all(tk[1] not in NOT_SAFE for tk in toks)
if toks[0][1] == "(" and match_close(toks, 0) == len(toks) - 1:
return safe_truthy(toks[1:-1])
return arith
def pass_ifexpr(src):
while True:
toks = lex(src)
edits = None
# ( C and { A } or { B } ) [ 1 ]
for i in range(len(toks)):
if toks[i][1] != "(" or toks[i][0] != "op":
continue
close = match_close(toks, i)
if close < 0 or close + 3 >= len(toks):
continue
if [t[1] for t in toks[close + 1:close + 4]] != ["[", "1", "]"]:
continue
# find `and {` at depth 1
depth, a_open = 0, -1
for j in range(i, close):
t = toks[j][1]
if toks[j][0] == "op" and t in OPEN:
depth += 1
elif toks[j][0] == "op" and t in (")", "]", "}"):
depth -= 1
elif depth == 1 and toks[j][0] == "name" and t == "and" and toks[j + 1][1] == "{":
a_open = j + 1
if a_open < 0:
continue
a_close = match_close(toks, a_open)
if a_close + 2 > close or toks[a_close + 1][1] != "or" or toks[a_close + 2][1] != "{":
continue
b_open = a_close + 2
b_close = match_close(toks, b_open)
if b_close != close - 1:
continue
a = toks[a_open + 1:a_close]
b = toks[b_open + 1:b_close]
if not safe_truthy(a) or any(t[1] == "," for t in a) or any(t[1] == "," for t in b):
continue
# rewrite: braces -> parentheses (a and b stay whole expressions), drop the [1]
edits = [
(toks[a_open][2], toks[a_open][3], "("),
(toks[a_close][2], toks[a_close][3], ")"),
(toks[b_open][2], toks[b_open][3], "("),
(toks[b_close][2], toks[b_close][3], ")"),
(toks[close + 1][2], toks[close + 3][3], ""),
]
break
if not edits:
return src
src = apply(src, edits)
# ------------------------------------------------------------------------------------------------ pass 2: compat header
def pass_header(src):
used = {t for k, t, _, _ in lex(src) if k == "name"}
names = [n for n in COMPAT_NAMES if n in used]
if not names:
return src
head = 'local __compat = require("formats._compat") local %s = %s ' % (
", ".join(names), ", ".join("__compat." + n for n in names))
return head + src
# ------------------------------------------------------------------------------------------------ requires
REQ = re.compile(r'require\(\s*"@(formats|tests)((?:/[\w.]+)*)"\s*\)')
def luajit_requires(src):
def sub(m):
mod = m.group(1) + m.group(2).replace("/", ".")
return 'require("%s")' % mod
return REQ.sub(sub, src)
# ------------------------------------------------------------------------------------------------ darklua
def darklua(rules, src_dir, out_dir, cwd):
with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as f:
json.dump({"generator": "retain_lines", "rules": rules}, f)
cfg = f.name
try:
r = subprocess.run(DARKLUA + ["process", "-c", cfg, src_dir, out_dir], cwd=cwd, capture_output=True, text=True)
if r.returncode != 0:
sys.stderr.write(r.stdout + r.stderr)
sys.exit("build: darklua failed")
finally:
os.unlink(cfg)
def files(root, ext=".luau"):
for d, _, fs in os.walk(root):
for f in sorted(fs):
if f.endswith(ext):
yield os.path.join(d, f)
def build_roblox():
out = os.path.join(BUILD, "roblox", "Formats")
shutil.rmtree(os.path.join(BUILD, "roblox"), ignore_errors=True)
darklua(ROBLOX_RULES, os.path.relpath(SRC, ROOT), os.path.relpath(out, ROOT), ROOT)
n = sum(1 for _ in files(out))
print("build: roblox %3d modules -> %s" % (n, os.path.relpath(out, ROOT)))
def build_luajit_tree(src_root, out_root, skip_dirs=()):
"""src_root/**/*.luau -> out_root/**/*.lua through the require rewrite, darklua and the token passes."""
tmp = tempfile.mkdtemp(prefix="formats-build-")
try:
stage = os.path.join(tmp, "in")
dl = os.path.join(tmp, "out")
count = 0
for f in files(src_root):
rel = os.path.relpath(f, src_root)
if rel.split(os.sep)[0] in skip_dirs:
continue
dst = os.path.join(stage, rel)
os.makedirs(os.path.dirname(dst), exist_ok=True)
with open(f) as fh:
s = fh.read()
with open(dst, "w") as fh:
fh.write(pass_elseif(luajit_requires(s)))
count += 1
if count == 0:
return 0
darklua(LUAJIT_RULES, stage, dl, tmp)
for f in files(dl):
rel = os.path.relpath(f, dl)
with open(f) as fh:
s = fh.read()
s = pass_header(pass_ifexpr(pass_iter(s)))
dst = os.path.join(out_root, rel[:-5] + ".lua")
os.makedirs(os.path.dirname(dst), exist_ok=True)
with open(dst, "w") as fh:
fh.write(s)
return count
finally:
shutil.rmtree(tmp, ignore_errors=True)
def build_luajit():
base = os.path.join(BUILD, "luajit")
shutil.rmtree(base, ignore_errors=True)
out = os.path.join(base, "formats")
n = build_luajit_tree(SRC, out)
shutil.copy(os.path.join(ROOT, "compat", "luajit.lua"), os.path.join(out, "_compat.lua"))
print("build: luajit %3d modules -> %s" % (n, os.path.relpath(out, ROOT)))
tout = os.path.join(base, "tests")
nt = build_luajit_tree(TESTS, tout, skip_dirs=("gen", "fixtures"))
gen = os.path.join(TESTS, "gen")
ng = 0
for f in files(gen):
dst = os.path.join(tout, "gen", os.path.relpath(f, gen)[:-5] + ".lua")
os.makedirs(os.path.dirname(dst), exist_ok=True)
shutil.copy(f, dst)
ng += 1
print("build: luajit %3d tests + %d fixture modules -> %s" % (nt, ng, os.path.relpath(tout, ROOT)))
# tools/*.luau (bench.luau): run with the same package.path
build_luajit_tree(os.path.join(ROOT, "tools"), os.path.join(base, "tools"), skip_dirs=("fixtures",))
def selftest():
cases = [
("for k, v in t do end", "for k, v in __iter(t) do end"),
("for k, v in pairs(t) do end", "for k, v in pairs(t) do end"),
("for k, v in next, t do end", "for k, v in next, t do end"),
("for i = 1, 3 do end", "for i = 1, 3 do end"),
("for _, x in f(function() for a in b do end end) do end",
"for _, x in __iter(f(function() for a in __iter(b) do end end)) do end"),
]
for a, want in cases:
got = pass_iter(a)
assert got == want, (a, got)
ifs = [
("local a = (c and{v + 1 }or{0\n})[1]", "local a = (c and(v + 1 )or(0\n))"),
("local a = (c and{v }or{w})[1]", None),
("local a = (c and{x < 1 }or{w})[1]", None),
("local a = (c and{#t }or{w})[1]", "local a = (c and(#t )or(w))"),
("local a = (c and{(f(x) .. \"s\") }or{w})[1]", "local a = (c and((f(x) .. \"s\") )or(w))"),
]
for a, want in ifs:
got = pass_ifexpr(a)
assert got == (want or a), (a, got)
els = [
("local x = if a then 1 elseif b then 2 elseif c then 3 else 4",
"local x = if a then 1 else if b then 2 else if c then 3 else 4"),
("if a then f() elseif b then g() else h() end", None),
("if a then x = if b then 1 elseif c then 2 else 3 elseif d then y() end",
"if a then x = if b then 1 else if c then 2 else 3 elseif d then y() end"),
("return f(if a then 1 elseif b then 2 else 3), function() if p then elseif q then end end",
"return f(if a then 1 else if b then 2 else 3), function() if p then elseif q then end end"),
("local y = if a then if b then 1 elseif c then 2 else 3 elseif d then 4 else 5",
"local y = if a then if b then 1 else if c then 2 else 3 else if d then 4 else 5"),
]
for a, want in els:
got = pass_elseif(a)
assert got == (want or a), (a, got)
assert luajit_requires('require("@formats/core/Bytes")') == 'require("formats.core.Bytes")'
els = [
("local x = if a then 1 elseif b then 2 elseif c then 3 else 4",
"local x = if a then 1 else if b then 2 else if c then 3 else 4"),
("if a then f() elseif b then g() else h() end", None),
("if a then x = if b then 1 elseif c then 2 else 3 elseif d then y() end",
"if a then x = if b then 1 else if c then 2 else 3 elseif d then y() end"),
("return f(if a then 1 elseif b then 2 else 3), function() if p then elseif q then end end",
"return f(if a then 1 else if b then 2 else 3), function() if p then elseif q then end end"),
("local y = if a then if b then 1 elseif c then 2 else 3 elseif d then 4 else 5",
"local y = if a then if b then 1 else if c then 2 else 3 else if d then 4 else 5"),
]
for a, want in els:
got = pass_elseif(a)
assert got == (want or a), (a, got)
assert luajit_requires('require( "@tests/gen/png_suite" )') == 'require("tests.gen.png_suite")'
print("build: self-test OK")
if __name__ == "__main__":
targets = sys.argv[1:] or ["roblox", "luajit"]
if "--test" in targets:
selftest()
sys.exit(0)
if "roblox" in targets:
build_roblox()
if "luajit" in targets:
build_luajit()
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env python3
# Test fixtures (python3 -I tools/fixtures.py [filter] [--force] [--list]): runs every generator in tools/fixtures/*.py
# (or those whose name contains filter). Each writes Luau modules into tests/gen/ (gitignored) that return the fixture
# data as string literals, because the luau CLI has no file I/O; the LuaJIT test build copies them as they are, so
# both runtimes read the same bytes through the same require("@tests/gen/<name>").
#
# A generator is tools/fixtures/<name>.py with:
# INPUTS = ["tests/fixtures/pngsuite", ...] # optional: files / dirs whose change triggers a rebuild
# def generate(ctx): ... # ctx.emit("png_suite", value), ctx.nix("imagemagick", [...]), ...
# A generator is skipped while all its outputs are newer than itself and its INPUTS (--force reruns it).
#
# ctx.emit(name, value): writes tests/gen/<name>.luau returning value. Python values map to Luau: bytes -> string
# literal (any bytes), str -> string literal, int / float / bool, list / tuple -> array, dict -> table (string keys
# become fields). None is not allowed (nil cannot sit in a table): leave the key out.
# ctx.nix(packages, argv, input=None) -> stdout bytes: runs argv under `nix shell nixpkgs#<pkg>...` (reference tools:
# ffmpeg, imagemagick, libwebp, flac, lame, opus-tools, ...). ctx.python(packages, code, input=None): a nix python3
# with the given python packages (pypng, pillow, fonttools, msgpack, cbor2, ...).
# ctx.rng(seed): a random.Random. ctx.root / ctx.gen: paths. ctx.read(relpath) -> bytes from the repo.
import importlib.util, os, random, subprocess, sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
GEN = os.path.join(ROOT, "tests", "gen")
GENERATORS = os.path.join(ROOT, "tools", "fixtures")
ESC = [chr(c) if 32 <= c < 127 and c not in (34, 92) else "\\x%02x" % c for c in range(256)]
def lit(b):
"""bytes / str -> a Luau (and Lua 5.1 / LuaJIT) string literal"""
if isinstance(b, str):
b = b.encode()
return '"' + "".join(map(ESC.__getitem__, b)) + '"'
def luau(v, indent=1):
if isinstance(v, bool):
return "true" if v else "false"
if isinstance(v, (bytes, bytearray, str)):
return lit(bytes(v) if not isinstance(v, str) else v)
if isinstance(v, int):
return str(v)
if isinstance(v, float):
if v != v:
return "(0/0)"
if v in (float("inf"), float("-inf")):
return "math.huge" if v > 0 else "-math.huge"
return repr(v)
pad = "\t" * indent
if isinstance(v, (list, tuple)):
if not v:
return "{}"
return "{\n" + "".join("%s%s,\n" % (pad, luau(x, indent + 1)) for x in v) + "\t" * (indent - 1) + "}"
if isinstance(v, dict):
if not v:
return "{}"
out = []
for k, x in v.items():
if isinstance(k, str) and k.isidentifier() and k not in LUA_KEYWORDS:
key = k
else:
key = "[%s]" % luau(k)
out.append("%s%s = %s,\n" % (pad, key, luau(x, indent + 1)))
return "{\n" + "".join(out) + "\t" * (indent - 1) + "}"
raise TypeError("fixtures: cannot emit %r" % type(v))
LUA_KEYWORDS = {"and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local", "nil",
"not", "or", "repeat", "return", "then", "true", "until", "while", "continue"}
class Ctx:
def __init__(self, name):
self.name = name
self.root = ROOT
self.gen = GEN
self.outputs = []
def emit(self, name, value):
path = os.path.join(GEN, name + ".luau")
with open(path, "w") as f:
f.write("-- generated by tools/fixtures.py (tools/fixtures/%s.py) - do not edit\nreturn %s\n" % (self.name, luau(value)))
self.outputs.append(path)
def rng(self, seed):
return random.Random(seed)
def read(self, rel):
with open(os.path.join(ROOT, rel), "rb") as f:
return f.read()
def nix(self, packages, argv, input=None):
if isinstance(packages, str):
packages = [packages]
cmd = ["nix", "shell"] + ["nixpkgs#" + p for p in packages] + ["-c"] + list(argv)
return subprocess.run(cmd, input=input, capture_output=True, check=True).stdout
def python(self, packages, code, input=None):
expr = "with import <nixpkgs> {}; python3.withPackages (p: [%s])" % " ".join("p." + p for p in packages)
cmd = ["nix", "shell", "--impure", "--expr", expr, "-c", "python3", "-I", "-c", code]
return subprocess.run(cmd, input=input, capture_output=True, check=True).stdout
def load(path):
spec = importlib.util.spec_from_file_location("fixture_" + os.path.basename(path)[:-3], path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
def mtime(p):
if os.path.isdir(p):
return max([os.path.getmtime(p)] + [mtime(os.path.join(p, f)) for f in os.listdir(p)])
return os.path.getmtime(p) if os.path.exists(p) else float("inf")
def main():
args = [a for a in sys.argv[1:] if not a.startswith("--")]
force = "--force" in sys.argv
os.makedirs(GEN, exist_ok=True)
stamps = os.path.join(GEN, ".stamps")
os.makedirs(stamps, exist_ok=True)
names = sorted(f[:-3] for f in os.listdir(GENERATORS) if f.endswith(".py") and not f.startswith("_"))
if "--list" in sys.argv:
print("\n".join(names))
return
for name in names:
if args and not any(a in name for a in args):
continue
path = os.path.join(GENERATORS, name + ".py")
mod = load(path)
inputs = [path, os.path.abspath(__file__)] + [os.path.join(ROOT, p) for p in getattr(mod, "INPUTS", [])]
stamp = os.path.join(stamps, name)
if not force and os.path.exists(stamp):
outs = open(stamp).read().split("\n")
newest = max(mtime(p) for p in inputs)
if all(os.path.exists(o) and os.path.getmtime(o) > newest for o in outs if o):
print("fixtures: %s up to date" % name)
continue
ctx = Ctx(name)
mod.generate(ctx)
with open(stamp, "w") as f:
f.write("\n".join(ctx.outputs))
size = sum(os.path.getsize(o) for o in ctx.outputs)
print("fixtures: %s -> %s (%.1f MB)" % (name, ", ".join(os.path.relpath(o, ROOT) for o in ctx.outputs), size / 1e6))
if __name__ == "__main__":
main()
+55
View File
@@ -0,0 +1,55 @@
# Reference decodes of the PngSuite (run once, the output is committed; from png-luau tools/png_reference.py):
# nix shell --impure --expr 'with import <nixpkgs> {}; python3.withPackages (p: [p.pypng p.pillow])' \
# -c python3 -I tools/fixtures/_png_reference.py
# Writes tests/fixtures/pngsuite_ref.txt: "<file> <width> <height> <crc32 of RGBA8 pixels>" per image, or
# "<file> corrupt" for the suite's deliberately broken x* files. Pixels come from pypng (pure Python, exact at every bit depth) as RGBA,
# scaled to 8 bits the way png-luau does: 16-bit samples keep the high byte, 1/2/4-bit samples are scaled by
# 255 / (2^depth - 1). Pillow cross-checks every image without 16-bit samples.
import os, sys, zlib
import png
from PIL import Image
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
SUITE = os.path.join(ROOT, "tests", "fixtures", "pngsuite")
def rgba8(path):
r = png.Reader(filename=path)
w, h, rows, info = r.asRGBA()
bd = info["bitdepth"]
out = bytearray()
for row in rows:
if bd == 16:
out += bytes(v >> 8 for v in row)
elif bd == 8:
out += bytes(row)
else:
m = (1 << bd) - 1
out += bytes(v * 255 // m for v in row)
return w, h, bytes(out), bd
lines, agree, checked = [], 0, 0
for name in sorted(os.listdir(SUITE)):
if not name.endswith(".png"):
continue
path = os.path.join(SUITE, name)
if name.startswith("x"):
lines.append("%s corrupt" % name) # the suite's deliberately corrupt files (x*: bad signature, CRC, ...)
continue
try:
w, h, px, bd = rgba8(path)
except Exception as e:
lines.append("%s error" % name)
continue
lines.append("%s %d %d %08x" % (name, w, h, zlib.crc32(px)))
with open(path, "rb") as f:
raw = f.read()
if bd != 16 and b"sBIT" not in raw:
checked += 1
im = Image.open(path).convert("RGBA")
if im.tobytes() == px:
agree += 1
else:
print("pillow disagrees:", name, file=sys.stderr)
with open(os.path.join(ROOT, "tests", "fixtures", "pngsuite_ref.txt"), "w") as f:
f.write("\n".join(lines) + "\n")
print("%d images, %d rejected; pillow agrees on %d of %d checked" % (len(lines), sum(l.endswith(" error") for l in lines), agree, checked))
+124
View File
@@ -0,0 +1,124 @@
# Deflate fixtures (tools/fixtures.py): deterministic corpora compressed with Python's zlib at every level and
# strategy, raw / zlib / gzip framing, small windows, flushes, gzip headers and multi-member gzip; plus a 6 MB bench
# corpus. Ported from deflate-luau tools/fixtures.py. Reads Webamp skins (zips of BMPs) from $SKINS_DIR as data only,
# if present (the corpus is smaller without them; the tests do not depend on it).
# tests/gen/deflate.luau { corpora = { [name] = bytes }, cases = { { name, kind, corpus, data } } }
# tests/gen/deflate_bench.luau { size, crc, zlib, gzip }
import gzip, os, random, zipfile, zlib
SKINS = os.environ.get("SKINS_DIR", "/tmp/wa-ref/webamp/packages/webamp-demo/skins")
def text_corpus(limit):
# Python's own stdlib sources: real text, deterministic for a given Python
base = os.path.dirname(os.__file__)
out = bytearray()
for name in sorted(os.listdir(base)):
if name.endswith(".py"):
with open(os.path.join(base, name), "rb") as f:
out += f.read()
if len(out) >= limit:
break
return bytes(out[:limit])
def skin_bmps(limit):
out = bytearray()
if os.path.isdir(SKINS):
for name in sorted(os.listdir(SKINS)):
if name.lower().endswith(".wsz"):
with zipfile.ZipFile(os.path.join(SKINS, name)) as z:
for i in z.infolist():
if i.filename.lower().endswith(".bmp"):
out += z.read(i)
if len(out) >= limit:
return bytes(out[:limit])
return bytes(out)
def generate(ctx):
rng = random.Random(1)
def text_corpus(limit):
# Python's own stdlib sources: real text, deterministic for a given Python
base = os.path.dirname(os.__file__)
out = bytearray()
for name in sorted(os.listdir(base)):
if name.endswith(".py"):
with open(os.path.join(base, name), "rb") as f:
out += f.read()
if len(out) >= limit:
break
return bytes(out[:limit])
def skin_bmps(limit):
out = bytearray()
if os.path.isdir(SKINS):
for name in sorted(os.listdir(SKINS)):
if name.lower().endswith(".wsz"):
with zipfile.ZipFile(os.path.join(SKINS, name)) as z:
for i in z.infolist():
if i.filename.lower().endswith(".bmp"):
out += z.read(i)
if len(out) >= limit:
return bytes(out[:limit])
return bytes(out)
corpora = {
"empty": b"",
"one": b"a",
"text": text_corpus(160000),
"random": rng.randbytes(40000),
"runs": b"abc" * 4000 + b"\0" * 20000 + bytes(range(256)) * 40 + b"z" * 300,
"far": (lambda r: r + rng.randbytes(20000) + r)(rng.randbytes(12000)),
"bmp": skin_bmps(120000),
"binary": bytes(rng.choice(b"\0\0\0\x01\x02\xff ABC") for _ in range(30000)),
}
cases = [] # (name, kind, corpus, compressed)
for cname, data in corpora.items():
for level in range(10):
cases.append(("%s/zlib%d" % (cname, level), "zlib", cname, zlib.compress(data, level)))
for sname, strat in (("fixed", zlib.Z_FIXED), ("huffman", zlib.Z_HUFFMAN_ONLY), ("rle", zlib.Z_RLE), ("filtered", zlib.Z_FILTERED)):
c = zlib.compressobj(6, zlib.DEFLATED, -15, 8, strat)
cases.append(("%s/raw-%s" % (cname, sname), "raw", cname, c.compress(data) + c.flush()))
for wbits, mem in ((-9, 1), (-12, 9)):
c = zlib.compressobj(9, zlib.DEFLATED, wbits, mem)
cases.append(("%s/raw-w%d-m%d" % (cname, -wbits, mem), "raw", cname, c.compress(data) + c.flush()))
# flushes in the middle: empty stored blocks, byte alignment, several block types in one stream
c = zlib.compressobj(5, zlib.DEFLATED, -15)
parts = []
step = max(1, len(data) // 5)
for i in range(0, len(data), step):
parts.append(c.compress(data[i:i + step]))
parts.append(c.flush(zlib.Z_SYNC_FLUSH if (i // step) % 2 == 0 else zlib.Z_FULL_FLUSH))
parts.append(c.flush())
cases.append(("%s/raw-flushes" % cname, "raw", cname, b"".join(parts)))
cases.append(("%s/gzip" % cname, "gzip", cname, gzip.compress(data, 6, mtime=0)))
# gzip with a file name / comment / extra / header CRC (written by hand), and multi-member
def gzip_full(data):
hdr = bytearray(b"\x1f\x8b\x08\x1e\0\0\0\0\x00\x03") # FEXTRA | FNAME | FCOMMENT | FHCRC
hdr += (4).to_bytes(2, "little") + b"ab\x01\x00"
hdr += b"name.txt\0" + b"a comment\0"
hdr += (zlib.crc32(bytes(hdr)) & 0xFFFF).to_bytes(2, "little")
c = zlib.compressobj(9, zlib.DEFLATED, -15)
body = c.compress(data) + c.flush()
return bytes(hdr) + body + zlib.crc32(data).to_bytes(4, "little") + (len(data) & 0xFFFFFFFF).to_bytes(4, "little")
corpora["multi"] = corpora["text"][:50000] + corpora["runs"] + b"" + corpora["one"]
multi = gzip.compress(corpora["text"][:50000], 9, mtime=0) + gzip_full(corpora["runs"]) + gzip.compress(b"", mtime=0) + gzip.compress(b"a", 1, mtime=0) + b"\0" * 7
cases.append(("multi/gzip-members", "gzip", "multi", multi))
cases.append(("runs/gzip-fullheader", "gzip", "runs", gzip_full(corpora["runs"])))
ctx.emit("deflate", {
"corpora": corpora,
"cases": [{"name": n, "kind": k, "corpus": c, "data": d} for n, k, c, d in cases],
})
# bench corpus: ~6 MB of text and BMPs, zlib level 6
bench = (corpora["text"] + corpora["bmp"]) * 1
while len(bench) < 6_000_000:
bench += corpora["text"] + skin_bmps(600000) + corpora["binary"]
bench = bench[:6_000_000]
ctx.emit("deflate_bench", {"size": len(bench), "crc": zlib.crc32(bench), "zlib": zlib.compress(bench, 6),
"gzip": gzip.compress(bench, 6, mtime=0)})
+165
View File
@@ -0,0 +1,165 @@
# PNG fixtures (tools/fixtures.py). Ported from png-luau tools/fixtures.py.
# tests/gen/png_suite.luau the PngSuite (tests/fixtures/pngsuite, licence in licenses/) with the committed reference
# decodes (tests/fixtures/pngsuite_ref.txt, from pypng: tools/fixtures/_png_reference.py)
# tests/gen/png_gen.luau images written by a small PNG writer here: every colour type and bit depth, plain and
# Adam7, odd sizes, every filter, split IDATs, tRNS keys; with the CRC-32 of the RGBA8 pixels
# tests/gen/png_bench.luau 1024 x 768 RGBA / RGB / Adam7 / palette images for tools/bench.luau
import os, random, struct, zlib
INPUTS = ["tests/fixtures/pngsuite", "tests/fixtures/pngsuite_ref.txt"]
# --- a small PNG writer
CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
PASSES = [(0, 0, 8, 8), (4, 0, 8, 8), (0, 4, 4, 8), (2, 0, 4, 4), (0, 2, 2, 4), (1, 0, 2, 2), (0, 1, 1, 2)]
def chunk(t, d):
return struct.pack(">I", len(d)) + t + d + struct.pack(">I", zlib.crc32(t + d))
def pack_row(samples, depth):
if depth == 8:
return bytes(samples)
if depth == 16:
return b"".join(struct.pack(">H", s) for s in samples)
out, acc, nb = bytearray(), 0, 0
for s in samples:
acc = (acc << depth) | s
nb += depth
if nb == 8:
out.append(acc)
acc, nb = 0, 0
if nb:
out.append(acc << (8 - nb))
return bytes(out)
def paeth(a, b, c):
p = a + b - c
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
return a if pa <= pb and pa <= pc else (b if pb <= pc else c)
def filt(row, prev, bpp, ft):
out = bytearray([ft])
for i, x in enumerate(row):
a = row[i - bpp] if i >= bpp else 0
b = prev[i] if prev else 0
c = prev[i - bpp] if prev and i >= bpp else 0
pred = (0, a, b, (a + b) // 2, paeth(a, b, c))[ft]
out.append((x - pred) & 255)
return out
def encode(w, h, ct, depth, px, interlace, rng, plte=None, trns=None, filters=None, idat_split=1, level=6):
# px[y][x] = tuple of samples at depth
ch = CHANNELS[ct]
bpp = max(1, ch * depth // 8)
raw = bytearray()
passes = PASSES if interlace else [(0, 0, 1, 1)]
for (x0, y0, dx, dy) in passes:
prev = None
for y in range(y0, h, dy):
xs = range(x0, w, dx)
if not len(xs):
break
row = pack_row([s for x in xs for s in px[y][x]], depth)
ft = filters(rng) if filters else rng.randrange(5)
raw += filt(row, prev, bpp, ft)
prev = row
z = zlib.compress(bytes(raw), level)
out = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, depth, ct, 0, 0, interlace))
out += chunk(b"tEXt", b"Comment\0made by formats-luau tools/fixtures/png.py")
if plte:
out += chunk(b"PLTE", b"".join(bytes(c[:3]) for c in plte))
if trns is not None:
out += chunk(b"tRNS", trns)
step = max(1, -(-len(z) // idat_split))
for i in range(0, len(z), step):
out += chunk(b"IDAT", z[i:i + step])
return out + chunk(b"IEND", b"")
def rgba8(ct, depth, s, plte=None, palpha=None, key=None):
def sc(v):
return v >> 8 if depth == 16 else (v if depth == 8 else v * 255 // ((1 << depth) - 1))
if ct == 3:
c = plte[s[0]] if s[0] < len(plte) else (0, 0, 0)
a = palpha[s[0]] if palpha and s[0] < len(palpha) else 255
return bytes((c[0], c[1], c[2], a))
if ct == 0:
return bytes((sc(s[0]),) * 3 + (0 if key == s[0] else 255,))
if ct == 2:
return bytes((sc(s[0]), sc(s[1]), sc(s[2]), 0 if key == tuple(s) else 255))
if ct == 4:
return bytes((sc(s[0]),) * 3 + (sc(s[1]),))
return bytes(sc(v) for v in s)
def image(w, h, ct, depth, rng, photo=False):
m = (1 << depth) - 1
ch = CHANNELS[ct]
px = []
for y in range(h):
row = []
for x in range(w):
if photo:
base = [(x * 255 // max(1, w - 1) + rng.randrange(-6, 7)) & 255, (y * 255 // max(1, h - 1)) & 255, ((x + y) // 3 + rng.randrange(-3, 4)) & 255, 255 - ((x ^ y) & 63)]
row.append(tuple(v * m // 255 for v in base[:ch]) if ct != 3 else (base[0] * m // 255,))
else:
row.append(tuple(rng.randrange(m + 1) if rng.random() < 0.5 else (x * 7 + y * 3 + k * 50) % (m + 1) for k in range(ch)))
px.append(row)
return px
def make(w, h, ct, depth, interlace, rng, photo=False, **kw):
px = image(w, h, ct, depth, rng, photo)
want_key = kw.pop("key", True)
plte = palpha = trns = key = None
if ct == 3:
n = min(1 << depth, 256) - (1 if depth > 1 else 0) # leave an index past the palette now and then
plte = [(rng.randrange(256), rng.randrange(256), rng.randrange(256)) for _ in range(n)]
palpha = [rng.randrange(256) for _ in range(rng.randrange(n + 1))]
trns = bytes(palpha) if palpha else None
elif ct in (0, 2) and want_key:
key = px[h // 2][w // 2] if ct == 2 else px[h // 2][w // 2][0]
trns = b"".join(struct.pack(">H", v) for v in (key if ct == 2 else (key,)))
key = tuple(key) if ct == 2 else key
data = encode(w, h, ct, depth, px, interlace, rng, plte=plte, trns=trns, **kw)
exp = b"".join(rgba8(ct, depth, px[y][x], plte, palpha, key) for y in range(h) for x in range(w))
return data, exp
def generate(ctx):
suite = []
for line in open(os.path.join(ctx.root, "tests", "fixtures", "pngsuite_ref.txt")).read().split("\n"):
if not line:
continue
parts = line.split()
data = ctx.read(os.path.join("tests", "fixtures", "pngsuite", parts[0]))
if parts[1] == "corrupt":
suite.append({"name": parts[0], "corrupt": True, "data": data})
else:
suite.append({"name": parts[0], "width": int(parts[1]), "height": int(parts[2]), "crc": int(parts[3], 16), "data": data})
ctx.emit("png_suite", suite)
rng = random.Random(5)
cases = []
for ct, depths in ((0, (1, 2, 4, 8, 16)), (2, (8, 16)), (3, (1, 2, 4, 8)), (4, (8, 16)), (6, (8, 16))):
for depth in depths:
for interlace in (0, 1):
for (w, h) in ((1, 1), (3, 2), (13, 11), (37, 29)):
data, exp = make(w, h, ct, depth, interlace, rng, idat_split=rng.choice((1, 1, 3)))
cases.append(("ct%d-d%d-%s-%dx%d" % (ct, depth, "adam7" if interlace else "plain", w, h), w, h, data, exp))
for ft in range(5): # one filter for the whole image
data, exp = make(41, 23, 6, 8, 0, rng, filters=lambda r, ft=ft: ft)
cases.append(("filter%d" % ft, 41, 23, data, exp))
data, exp = make(41, 23, 0, 2, 1, rng, filters=lambda r, ft=ft: ft)
cases.append(("filter%d-grey2-adam7" % ft, 41, 23, data, exp))
data, exp = make(200, 150, 6, 8, 0, rng, photo=True, idat_split=40)
cases.append(("photo-200x150-40idat", 200, 150, data, exp))
data, exp = make(64, 64, 2, 8, 0, rng, key=False, level=0)
cases.append(("stored-zlib", 64, 64, data, exp))
ctx.emit("png_gen", [{"name": n, "width": w, "height": h, "crc": zlib.crc32(exp), "data": d} for n, w, h, d, exp in cases])
# --- bench images (Paeth / up / sub mix, as encoders choose)
bench = []
for label, ct, interlace in (("rgba8", 6, 0), ("rgb8", 2, 0), ("rgba8-adam7", 6, 1), ("palette8", 3, 0)):
data, exp = make(1024, 768, ct, 8, interlace, rng, photo=True, key=False, filters=lambda r: r.choice((1, 2, 4, 4)))
bench.append((label, data, zlib.crc32(exp)))
ctx.emit("png_bench", [{"name": l, "width": 1024, "height": 768, "crc": c, "data": d} for l, d, c in bench])
+181
View File
@@ -0,0 +1,181 @@
#!/usr/bin/env python3
# Registry generator (python3 -I tools/gen_registry.py [--check]): scans the format folders
# src/Formats/<category>/<fmt>/init.luau and writes
# src/Formats/Registry.luau a static list (Roblox has no dynamic require): each format's contract metadata, copied
# from its init.luau, and a load() that requires the module on first use
# docs/FORMATS.md the capability matrix, from each contract's caps
# The metadata fields must be one-line literals in the contract table (tools/lint.sh CONTRACT checks the shape):
# name = "png", category = "image", extensions = { ... }, mime = { ... }, deps = { ... }, caps = { ... },
# --check: exit 1 when either file is out of date (tools/lint.sh runs this).
import os, re, sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC = os.path.join(ROOT, "src", "Formats")
CATEGORIES = ["image", "audio", "video", "model", "cad", "font", "archive", "data", "vector", "layered", "subtitle",
"music", "playlist"]
FIELDS = ["name", "category", "extensions", "mime", "deps", "caps"]
FIELD = re.compile(r"^\t(name|category|extensions|mime|deps|caps) = (.*),\s*(--.*)?$")
def contract(path):
"""The one-line contract fields of a format's init.luau: {field: luau literal text}."""
out = {}
with open(path) as f:
for line in f:
m = FIELD.match(line.rstrip("\n"))
if m and m.group(1) not in out:
out[m.group(1)] = m.group(2).strip()
return out
def lua_strings(lit):
return re.findall(r'"([^"]*)"', lit)
def scan():
formats = []
for cat in CATEGORIES:
d = os.path.join(SRC, cat)
if not os.path.isdir(d):
continue
for fmt in sorted(os.listdir(d)):
init = os.path.join(d, fmt, "init.luau")
if not os.path.isfile(init):
continue
c = contract(init)
missing = [k for k in FIELDS if k not in c]
if missing:
sys.exit("gen_registry: %s/%s/init.luau: missing contract fields %s" % (cat, fmt, ", ".join(missing)))
c["path"] = cat + "/" + fmt
c["folder_category"] = cat
formats.append(c)
return formats
def registry(formats):
out = [
"--!strict",
"-- Registry: GENERATED by tools/gen_registry.py from the format folders - do not edit.",
"-- One entry per format: the contract metadata (copied from its init.luau) and load(), which requires the format",
"-- module on first use (a static require, as Roblox needs). Order: category, then name.",
"export type Entry = {",
"\tname: string,",
"\tcategory: string,",
"\tpath: string,",
"\textensions: { string },",
"\tmime: { string },",
"\tdeps: { string },",
"\tcaps: { [string]: any },",
"\tload: () -> any,",
"}",
"",
"local list: { Entry } = {",
]
for c in formats:
out += [
"\t{",
"\t\tname = %s," % c["name"],
"\t\tcategory = %s," % c["category"],
'\t\tpath = "%s",' % c["path"],
"\t\textensions = %s," % c["extensions"],
"\t\tmime = %s," % c["mime"],
"\t\tdeps = %s," % c["deps"],
"\t\tcaps = %s," % c["caps"],
"\t\tload = function()",
'\t\t\treturn require("@formats/%s")' % c["path"],
"\t\tend,",
"\t},",
]
out += ["}", "", "return list", ""]
return "\n".join(out)
def caps_dict(lit):
"""{ decode = true, depths = { 8 } } -> ordered [(key, text)] at the top level."""
body = lit.strip()[1:-1]
items, depth, cur = [], 0, ""
for ch in body:
if ch == "{":
depth += 1
elif ch == "}":
depth -= 1
if ch == "," and depth == 0:
items.append(cur)
cur = ""
else:
cur += ch
if cur.strip():
items.append(cur)
out = []
for it in items:
if "=" in it:
k, v = it.split("=", 1)
out.append((k.strip(), v.strip()))
return out
def formats_md(formats):
lines = [
"# Formats",
"",
"GENERATED by `tools/gen_registry.py` from each format's contract (`caps`) - do not edit. Every format listed here",
"is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build) by `bash tools/test.sh`.",
"",
"| Category | Format | Extensions | Read | Write | Capabilities | Test |",
"|---|---|---|---|---|---|---|",
]
for c in formats:
caps = caps_dict(c["caps"])
cd = dict(caps)
other = ", ".join("%s: %s" % (k, v.replace("{ ", "").replace(" }", "")) for k, v in caps if k not in ("decode", "encode"))
test = "tests/%s/%s.luau" % (c["folder_category"], lua_strings(c["name"])[0])
has = os.path.isfile(os.path.join(ROOT, test))
lines.append("| %s | %s | %s | %s | %s | %s | %s |" % (
c["folder_category"], lua_strings(c["name"])[0], " ".join("." + e for e in lua_strings(c["extensions"])),
"yes" if cd.get("decode") == "true" else "-", "yes" if cd.get("encode") == "true" else "-",
other or "", "`%s`" % test if has else "**missing**"))
lines += ["", "Codecs (layer 1, shared by formats; not loadable on their own):", ""]
cdir = os.path.join(SRC, "codecs")
for name in sorted(os.listdir(cdir)) if os.path.isdir(cdir) else []:
p = os.path.join(cdir, name)
init = os.path.join(p, "init.luau") if os.path.isdir(p) else p
if os.path.isfile(init):
first = ""
with open(init) as f:
for line in f:
if line.startswith("-- codecs/"):
first = line[3:].strip()
break
lines.append("- %s" % (first or name))
lines.append("")
return "\n".join(lines)
def main():
formats = scan()
outputs = {
os.path.join(SRC, "Registry.luau"): registry(formats),
os.path.join(ROOT, "docs", "FORMATS.md"): formats_md(formats),
}
check = "--check" in sys.argv
stale = []
for path, text in outputs.items():
old = open(path).read() if os.path.exists(path) else None
if old != text:
stale.append(os.path.relpath(path, ROOT))
if not check:
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as f:
f.write(text)
if check:
if stale:
print("gen_registry: out of date: %s (run python3 -I tools/gen_registry.py)" % ", ".join(stale))
sys.exit(1)
print("gen_registry: up to date (%d formats)" % len(formats))
else:
print("gen_registry: %d formats -> src/Formats/Registry.luau, docs/FORMATS.md%s" % (
len(formats), "" if stale else " (unchanged)"))
if __name__ == "__main__":
main()
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env bash
# Lint (bash tools/lint.sh):
# 1. GLOBALS: unknown globals (luau-analyze), a local used before its declaration compiles fine but reads a nil
# global at runtime. Roblox globals are allowed (the library runs in Roblox, luau and LuaJIT). Other type errors
# are counted and printed with LINT_TYPES=1, but do not fail the lint (absorbed code predates --!strict).
# 2. HEADER, REQUIRE, NATIVE (native code never throws: it crashes Roblox Studio), LAYERS, DEPS, CONTRACT:
# tools/lint_rules.py (its header lists the rules; docs/STYLE.md explains them).
# 3. The generated registry / docs/FORMATS.md are up to date (tools/gen_registry.py --check), and tools/build.py's
# token passes pass their self-test.
cd "$(dirname "$0")/.." || exit 1
ANALYZE=${ANALYZE:-$(command -v luau-analyze || nix shell nixpkgs#luau -c sh -c 'command -v luau-analyze')}
ALLOW="game|script|workspace|Instance|Enum|Vector3|Vector2|Color3|CFrame|task|typeof|warn|tick|time|buffer|vector|bit32|utf8|debug|shared|plugin|SharedTable|Random"
fail=0
mapfile -t files < <(find src tests tools -name '*.luau' -not -path 'tests/gen/*' | sort)
report=$("$ANALYZE" "${files[@]}" 2>&1)
bad=$(echo "$report" | grep "Unknown global" | grep -vE "'($ALLOW)'")
if [ -n "$bad" ]; then
echo "$bad"
echo "lint: unknown globals (a local used before it is declared?)"
fail=1
fi
ntype=$(echo "$report" | grep -c "Error:")
[ -n "$LINT_TYPES" ] && echo "$report" | grep -v "Unknown global"
python3 -I tools/lint_rules.py || { echo "lint: structure rules failed (see tools/lint_rules.py)"; fail=1; }
python3 -I tools/gen_registry.py --check > /dev/null || { python3 -I tools/gen_registry.py --check; fail=1; }
python3 -I tools/build.py --test > /dev/null || { echo "lint: tools/build.py --test failed"; fail=1; }
if [ $fail -eq 0 ]; then
echo "lint passed (globals, header, require, native, layers, deps, contract, registry; $ntype type diagnostics: LINT_TYPES=1 shows them)"
fi
exit $fail
+279
View File
@@ -0,0 +1,279 @@
#!/usr/bin/env python3
# The structural lint rules (python3 -I tools/lint_rules.py), run by tools/lint.sh. Prints one line per violation and
# exits 1 if there is any. The rules (docs/STYLE.md explains each):
# HEADER every src module starts with --!strict (then optional --!native / --!optimize N) and a comment line
# "-- <module path>: ..." (core/Bytes, image/png, image/png/Decode, Formats for the root, ...); every test
# starts with a comment.
# REQUIRE requires are string literals "@formats/<path>" (tests / tools may also use "@tests/<path>") naming an
# existing module; no script / @self / relative requires in src.
# NATIVE native code never throws: a --!native module has no error( / assert( and requires no module that has
# one; an @native function body has no error( / assert(. A format's init.luau is never --!native.
# LAYERS requires go downward: core < Types < host; core, Types < codecs < containers < formats (<category>/<fmt>)
# < ops < api (init, Registry). core / codecs / containers / ops may require their own layer; a format
# may require its own folder but never another format; only the api requires host.
# DEPS a format folder's requires outside itself are exactly the contract's deps = { ... }.
# CONTRACT a format's init.luau has the one-line fields name (= folder name), category (= folder category),
# extensions, mime, deps, caps (with decode / encode matching the functions), function <X>.sniff, at least
# one of decode / encode / open, the section markers in order, and ends with return <X>; it has a test
# tests/<category>/<fmt>.luau with a fuzz pass (:fuzz().
import os, re, sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC = os.path.join(ROOT, "src", "Formats")
CATEGORIES = ["image", "audio", "video", "model", "cad", "font", "archive", "data", "vector", "layered", "subtitle",
"music", "playlist"]
SECTIONS = ["requires", "contract", "types", "constants", "sniff", "decode", "encode", "open", "extras"]
THROW = re.compile(r"\b(error|assert)\s*\(")
REQ = re.compile(r"\brequire\s*\(([^)]*)\)")
MARKER = re.compile(r"^-- -{20,} (\w+)")
out = []
def bad(path, line, msg):
out.append("%s:%s: %s" % (os.path.relpath(path, ROOT), line, msg))
def code(line):
"""the line without its comment (strings containing -- are rare enough in this codebase)"""
return line.split("--", 1)[0]
def modpath(path):
"""src/Formats/image/png/init.luau -> image/png; src/Formats/init.luau -> '' (the root)"""
rel = os.path.relpath(path, SRC)[:-5].replace(os.sep, "/")
if rel == "init":
return ""
if rel.endswith("/init"):
rel = rel[:-5]
return rel
def resolve(target):
"""'core/Bytes' -> the file, or None"""
base = os.path.join(SRC, *target.split("/")) if target else SRC
for p in (base + ".luau", os.path.join(base, "init.luau")):
if os.path.isfile(p):
return p
return None
def layer(mod):
"""(rank, group) of a module path"""
top = mod.split("/")[0] if mod else ""
if mod in ("", "Registry"):
return 6, "api"
if top == "core":
return 0, "core"
if mod == "Types":
return 1, "types"
if top == "host":
return 2, "host"
if top == "codecs":
return 3, "codecs"
if top == "containers":
return 4, "containers"
if top in CATEGORIES:
return 5, "format"
if top == "ops":
return 5.5, "ops"
return 7, "unknown"
def format_folder(mod):
parts = mod.split("/")
if parts[0] in CATEGORIES and len(parts) >= 2:
return parts[0] + "/" + parts[1]
return None
files = []
for d, _, fs in os.walk(SRC):
for f in sorted(fs):
if f.endswith(".luau"):
files.append(os.path.join(d, f))
files.sort()
text = {f: open(f).read().split("\n") for f in files}
mods = {f: modpath(f) for f in files}
# requires per file: [(line, target)]
requires = {}
for f, lines in text.items():
reqs = []
for i, l in enumerate(lines, 1):
for m in REQ.finditer(code(l)):
arg = m.group(1).strip()
mm = re.fullmatch(r'"@formats(?:/([\w/]+))?"', arg)
if not mm:
bad(f, i, "REQUIRE: requires in src must be require(\"@formats/<path>\"), got require(%s)" % arg)
continue
target = mm.group(1) or ""
if not resolve(target):
bad(f, i, "REQUIRE: no module @formats/%s" % target)
continue
reqs.append((i, target))
requires[f] = reqs
# ---------------------------------------------------------------------------------------------------- HEADER
for f, lines in text.items():
i = 0
if not lines or lines[0].strip() != "--!strict":
bad(f, 1, "HEADER: the first line must be --!strict")
while i < len(lines) and lines[i].startswith("--!"):
if not re.fullmatch(r"--!(strict|native|optimize [012])", lines[i].strip()):
bad(f, i + 1, "HEADER: unknown directive " + lines[i])
i += 1
want = mods[f] or "Formats"
if i >= len(lines) or not lines[i].startswith("-- %s:" % want):
bad(f, i + 1, "HEADER: the first comment line must start with \"-- %s:\"" % want)
TESTS = os.path.join(ROOT, "tests")
for d, _, fs in os.walk(TESTS):
if os.path.relpath(d, TESTS).split(os.sep)[0] in ("gen", "fixtures"):
continue
for fn in fs:
if fn.endswith(".luau"):
p = os.path.join(d, fn)
first = open(p).readline()
if not first.startswith("--"):
bad(p, 1, "HEADER: a test starts with a comment saying what it covers")
for i, l in enumerate(open(p).read().split("\n"), 1):
for m in REQ.finditer(code(l)):
if not re.fullmatch(r'"@(formats|tests)(/[\w/]+)?"', m.group(1).strip()):
bad(p, i, "REQUIRE: tests require \"@formats/...\" or \"@tests/...\"")
# ---------------------------------------------------------------------------------------------------- NATIVE
throwing = {mods[f] for f, lines in text.items() if any(THROW.search(code(l)) for l in lines)}
for f, lines in text.items():
native = any(l.strip() == "--!native" for l in lines[:5])
mod = mods[f]
if native:
if format_folder(mod) == mod:
bad(f, 1, "NATIVE: a format's init.luau is never --!native (put hot code in a private submodule)")
for i, l in enumerate(lines, 1):
if THROW.search(code(l)):
bad(f, i, "NATIVE: error / assert in a --!native module")
for i, target in requires[f]:
if target in throwing:
bad(f, i, "NATIVE: a --!native module requires %s, which can throw" % target)
for i, l in enumerate(lines):
if l.strip() == "@native":
ind = l[: len(l) - len(l.lstrip())]
j = i + 2
while j < len(lines) and lines[j] != ind + "end":
if THROW.search(code(lines[j])):
bad(f, j + 1, "NATIVE: error / assert in an @native function")
j += 1
if j == len(lines):
bad(f, i + 1, "NATIVE: @native function without a closing end at its indentation")
# ---------------------------------------------------------------------------------------------------- LAYERS
ALLOWED = {
"core": {"core"},
"types": {"core"},
"host": {"core", "types", "host"},
"codecs": {"core", "types", "codecs"},
"containers": {"core", "types", "codecs", "containers"},
"format": {"core", "types", "codecs", "containers"},
"ops": {"core", "types", "codecs", "containers", "ops"},
"api": {"core", "types", "host", "codecs", "containers", "format", "ops", "api"},
}
for f in files:
mod = mods[f]
_, group = layer(mod)
if group == "unknown":
bad(f, 1, "LAYERS: %s is not in a known layer folder" % mod)
continue
for i, target in requires[f]:
_, tgroup = layer(target)
if group == "format":
mine, theirs = format_folder(mod), format_folder(target)
if tgroup == "format":
if mine != theirs:
bad(f, i, "LAYERS: a format never requires another format (%s -> %s): promote shared code to "
"codecs/ or containers/" % (mine, theirs))
continue
if tgroup not in ALLOWED[group]:
bad(f, i, "LAYERS: %s (%s) may not require %s (%s)" % (mod or "Formats", group, target, tgroup))
# ---------------------------------------------------------------------------------------------------- DEPS + CONTRACT
FIELD = re.compile(r"^\t(name|category|extensions|mime|deps|caps) = (.*),\s*(--.*)?$")
folders = sorted({format_folder(m) for m in mods.values() if format_folder(m)})
for folder in folders:
cat, fmt = folder.split("/")
init = os.path.join(SRC, cat, fmt, "init.luau")
if not os.path.isfile(init):
bad(os.path.join(SRC, cat, fmt), 0, "CONTRACT: a format folder needs an init.luau")
continue
lines = text[init]
fields = {}
for i, l in enumerate(lines, 1):
m = FIELD.match(l)
if m and m.group(1) not in fields:
fields[m.group(1)] = (i, m.group(2).strip())
for k in ("name", "category", "extensions", "mime", "deps", "caps"):
if k not in fields:
bad(init, 0, "CONTRACT: missing the one-line field `%s = ...,` in the contract table" % k)
if "name" in fields and fields["name"][1] != '"%s"' % fmt:
bad(init, fields["name"][0], "CONTRACT: name must be \"%s\" (the folder name)" % fmt)
if "category" in fields and fields["category"][1] != '"%s"' % cat:
bad(init, fields["category"][0], "CONTRACT: category must be \"%s\" (the folder category)" % cat)
# the contract table's local name: `local X = {` right before the fields
tname = None
for l in lines:
m = re.match(r"^local (\w+) = \{$", l)
if m:
tname = m.group(1)
break
if not tname:
bad(init, 0, "CONTRACT: the contract is a table `local <Name> = {` with the fields on their own lines")
continue
funcs = {m.group(1) for l in lines for m in [re.match(r"^function %s\.(\w+)\(" % tname, l)] if m}
if "sniff" not in funcs:
bad(init, 0, "CONTRACT: missing function %s.sniff(r)" % tname)
if not funcs & {"decode", "encode", "open"}:
bad(init, 0, "CONTRACT: needs at least one of %s.decode / encode / open" % tname)
if "caps" in fields:
caps = fields["caps"][1]
for k in ("decode", "encode"):
m = re.search(r"\b%s = (true|false)" % k, caps)
if not m:
bad(init, fields["caps"][0], "CONTRACT: caps needs %s = true|false" % k)
elif (m.group(1) == "true") != (k in funcs or (k == "decode" and "open" in funcs)):
bad(init, fields["caps"][0], "CONTRACT: caps.%s = %s but %s.%s is %s" % (
k, m.group(1), tname, k, "defined" if k in funcs else "missing"))
last = [l for l in lines if l.strip()][-1]
if last.strip() != "return %s" % tname:
bad(init, len(lines), "CONTRACT: the module ends with `return %s`" % tname)
seen = [MARKER.match(l).group(1) for l in lines if MARKER.match(l)]
for s in seen:
if s not in SECTIONS:
bad(init, 0, "CONTRACT: unknown section marker `%s` (known: %s)" % (s, ", ".join(SECTIONS)))
order = [SECTIONS.index(s) for s in seen if s in SECTIONS]
if order != sorted(order):
bad(init, 0, "CONTRACT: sections out of order (%s); the order is %s" % (", ".join(seen), ", ".join(SECTIONS)))
for s in ("requires", "contract"):
if s not in seen:
bad(init, 0, "CONTRACT: missing the `-- ---- %s` section marker" % s)
# DEPS
if "deps" in fields:
declared = set(re.findall(r'"([^"]*)"', fields["deps"][1]))
used = set()
for f in files:
if format_folder(mods[f]) == folder:
for _, target in requires[f]:
if format_folder(target) != folder:
used.add(target)
for d in sorted(used - declared):
bad(init, fields["deps"][0], "DEPS: requires %s but deps does not list it" % d)
for d in sorted(declared - used):
bad(init, fields["deps"][0], "DEPS: deps lists %s but nothing in %s requires it" % (d, folder))
# the test
test = os.path.join(ROOT, "tests", cat, fmt + ".luau")
if not os.path.isfile(test):
bad(init, 0, "CONTRACT: missing the test tests/%s/%s.luau" % (cat, fmt))
elif ":fuzz(" not in open(test).read():
bad(test, 0, "CONTRACT: a format test includes the fuzz no-throw pass (t:fuzz(...))")
print("\n".join(out))
sys.exit(1 if out else 0)
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
# Tests (bash tools/test.sh [filter]): generate the fixtures (tools/fixtures.py -> tests/gen), regenerate the registry,
# build both targets (tools/build.py), then run every tests/**/*.luau twice: under `luau --codegen -O2` (the source,
# through the .luaurc aliases) and under `luajit` (build/luajit/tests/**/*.lua, with the compat prelude), then the lint.
# A filter runs only the tests whose path contains it (and the fixture generators whose name contains it), and skips
# the lint. RUNTIMES="luau" or "luajit" runs one runtime only.
cd "$(dirname "$0")/.." || exit 1
LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')}
LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')}
RUNTIMES=${RUNTIMES:-"luau luajit"}
LJPATH='package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path'
fail=0
python3 -I tools/fixtures.py $1 || { echo "FAILED: fixtures"; exit 1; }
python3 -I tools/gen_registry.py > /dev/null || { echo "FAILED: gen_registry"; exit 1; }
python3 -I tools/build.py || { echo "FAILED: build"; exit 1; }
passed=0
for t in $(find tests -name '*.luau' -not -path 'tests/gen/*' -not -path 'tests/fixtures/*' -not -name 'T.luau' | sort); do
[ -n "$1" ] && [[ "$t" != *$1* ]] && continue
for rt in $RUNTIMES; do
echo "== $t ($rt)"
if [ "$rt" = luau ]; then
"$LUAU" --codegen -O2 "$t" || { echo "FAILED: $t ($rt)"; fail=1; continue; }
else
"$LUAJIT" -e "$LJPATH" "build/luajit/${t%.luau}.lua" || { echo "FAILED: $t ($rt)"; fail=1; continue; }
fi
passed=$((passed + 1))
done
done
if [ -z "$1" ]; then
bash tools/lint.sh || fail=1
fi
[ $fail -eq 0 ] && echo "formats-luau: all tests passed ($passed runs)" || echo "formats-luau: FAILURES"
exit $fail