Files
rosetta/tools/gen_registry.py
T
4DBug 51b08575c4 ws-cleanup: codecs/ grouped by domain; containers/Chunks, codecs/audio/Stream, codecs/image/Pixels, codecs/model/Mat4
C2, the hierarchy (tools/move.py, every reference rewritten mechanically):
- codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder;
  codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample
  VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url;
  codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err
  Crc32 Adler32 Base64 Md5 Input Sniff.
- LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md).
- Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes.

C3, generic code out of format folders:
- containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first,
  trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64
  through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it.
- codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position,
  priming and end trimming) that aac, caf and m4a each carried (~70 lines each).
- codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of
  its own (the AND mask / alpha rule stay ICO's).
- codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model),
  Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is
  Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the
  fixtures' bind shapes).
- README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes:
  FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the
  shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks
  decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type
  baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93.
2026-10-31 12:25:03 -05:00

187 lines
7.2 KiB
Python

#!/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 3, shared by formats; not loadable on their own), by domain:", ""]
cdir = os.path.join(SRC, "codecs")
for domain in sorted(os.listdir(cdir)) if os.path.isdir(cdir) else []:
ddir = os.path.join(cdir, domain)
if not os.path.isdir(ddir):
continue
lines.append("- **%s**" % domain)
for name in sorted(os.listdir(ddir)):
p = os.path.join(ddir, name)
init = os.path.join(p, "init.luau") if os.path.isdir(p) else p
if os.path.isfile(init) and init.endswith(".luau"):
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()