merge master

This commit is contained in:
4DBug committed 2026-11-02 22:17:13 -06:00
commit f9e2e6a455
18 files changed
+16515 -1468

No files matched your search

+3671 -44
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
Binary file not shown.
+3 -2
View File
@@ -1,6 +1,6 @@
{
"Core_1": [[8, "src/Rosetta/init.luau"], [892, "src/Rosetta/Registry.luau"], [3301, "src/Rosetta/Types.luau"], [4414, "src/Rosetta/codecs/audio/Adpcm/init.luau"], [5168, "src/Rosetta/codecs/image/Yuv.luau"], [5473, "src/Rosetta/codecs/model/Rbx/init.luau"], [5710, "src/Rosetta/codecs/video/Video/init.luau"], [6268, "src/Rosetta/containers/AudioWrap.luau"], [6778, "src/Rosetta/containers/Ogg/Mux.luau"], [6967, "src/Rosetta/core/Bytes.luau"], [7494, "src/Rosetta/core/Crc32.luau"], [7645, "src/Rosetta/core/Err.luau"], [7727, "src/Rosetta/core/Input.luau"], [7803, "src/Rosetta/host/init.luau"]],
"Core_2": [[8, "src/Rosetta/ops/ImageOps/init.luau"], [656, "src/Rosetta/ops/ImageOps/Kernels.luau"]],
"Core_1": [[8, "src/Rosetta/init.luau"], [925, "src/Rosetta/Registry.luau"], [3542, "src/Rosetta/Types.luau"], [4655, "src/Rosetta/codecs/audio/Adpcm/init.luau"], [5409, "src/Rosetta/codecs/image/Yuv.luau"], [5714, "src/Rosetta/codecs/model/Rbx/init.luau"], [5951, "src/Rosetta/codecs/video/Video/init.luau"], [6509, "src/Rosetta/containers/AudioWrap.luau"], [7019, "src/Rosetta/containers/Ogg/Mux.luau"], [7208, "src/Rosetta/core/Bytes.luau"], [7735, "src/Rosetta/core/Crc32.luau"], [7886, "src/Rosetta/core/Err.luau"], [7968, "src/Rosetta/core/Input.luau"]],
"Core_2": [[8, "src/Rosetta/host/init.luau"], [53, "src/Rosetta/ops/ImageOps/init.luau"], [701, "src/Rosetta/ops/ImageOps/Kernels.luau"]],
"Mpeg2": [[8, "src/Rosetta/codecs/video/Dsp.luau"], [846, "src/Rosetta/codecs/video/Mpeg1/init.luau"], [859, "src/Rosetta/codecs/video/Mpeg2/init.luau"], [1227, "src/Rosetta/codecs/video/Mpeg2/Decoder.luau"], [2754, "src/Rosetta/codecs/video/Mpeg2/Tables.luau"], [2894, "src/Rosetta/codecs/video/Mpeg2/Vlc.luau"]],
"H263": [[8, "src/Rosetta/codecs/video/H263/init.luau"], [165, "src/Rosetta/codecs/video/H263/Decoder.luau"], [1023, "src/Rosetta/codecs/video/H263/Tables.luau"]],
"H264": [[8, "src/Rosetta/codecs/video/H264/init.luau"], [382, "src/Rosetta/codecs/video/H264/Bitstream.luau"], [657, "src/Rosetta/codecs/video/H264/Cabac.luau"], [1788, "src/Rosetta/codecs/video/H264/Cavlc.luau"], [2556, "src/Rosetta/codecs/video/H264/Deblock.luau"], [2818, "src/Rosetta/codecs/video/H264/Decoder.luau"], [3828, "src/Rosetta/codecs/video/H264/Inter.luau"], [4154, "src/Rosetta/codecs/video/H264/Intra.luau"], [4561, "src/Rosetta/codecs/video/H264/Mb.luau"], [5500, "src/Rosetta/codecs/video/H264/Params.luau"], [5948, "src/Rosetta/codecs/video/H264/Slice.luau"], [6200, "src/Rosetta/codecs/video/H264/Tables.luau"], [6242, "src/Rosetta/codecs/video/H264/Transform.luau"]],
@@ -27,6 +27,7 @@
"Hively": [[8, "src/Rosetta/codecs/audio/Hively/init.luau"], [205, "src/Rosetta/codecs/audio/Hively/Load.luau"], [455, "src/Rosetta/codecs/audio/Hively/Player.luau"], [1414, "src/Rosetta/codecs/audio/Hively/Tables.luau"]],
"SoundFont": [[8, "src/Rosetta/codecs/audio/SoundFont/init.luau"], [63, "src/Rosetta/codecs/audio/SoundFont/Fallback.luau"], [207, "src/Rosetta/codecs/audio/SoundFont/Parse.luau"], [721, "src/Rosetta/codecs/audio/SoundFont/Synth.luau"]],
"Draco": [[8, "src/Rosetta/codecs/model/Draco/init.luau"], [340, "src/Rosetta/codecs/model/Draco/Attributes.luau"], [809, "src/Rosetta/codecs/model/Draco/Connectivity.luau"], [1998, "src/Rosetta/codecs/model/Draco/Int64.luau"], [2147, "src/Rosetta/codecs/model/Draco/KdTree.luau"], [2506, "src/Rosetta/codecs/model/Draco/Predict.luau"], [3468, "src/Rosetta/codecs/model/Draco/Reader.luau"]],
"Root": [[8, "src/Rosetta/Sniffs.luau"]],
"archive_1": [[8, "src/Rosetta/archive/7z/init.luau"], [393, "src/Rosetta/archive/7z/Header.luau"], [920, "src/Rosetta/archive/adf/init.luau"], [1202, "src/Rosetta/archive/applesingle/init.luau"], [1388, "src/Rosetta/archive/ar/init.luau"], [1791, "src/Rosetta/archive/arj/init.luau"], [2001, "src/Rosetta/archive/binhex/init.luau"], [2250, "src/Rosetta/archive/br/init.luau"], [2325, "src/Rosetta/archive/bz2/init.luau"], [2389, "src/Rosetta/archive/cab/init.luau"], [2802, "src/Rosetta/archive/cab/Sum.luau"], [2843, "src/Rosetta/archive/cpio/init.luau"], [3011, "src/Rosetta/archive/d64/init.luau"], [3425, "src/Rosetta/archive/fat/init.luau"], [3547, "src/Rosetta/archive/grp/init.luau"], [3661, "src/Rosetta/archive/gzip/init.luau"], [3846, "src/Rosetta/archive/iso/init.luau"], [3918, "src/Rosetta/archive/lha/init.luau"], [4343, "src/Rosetta/archive/lz4/init.luau"], [4687, "src/Rosetta/archive/macbinary/init.luau"], [4885, "src/Rosetta/archive/mpq/init.luau"], [5291, "src/Rosetta/archive/mpq/Crypt.luau"], [5356, "src/Rosetta/archive/pak/init.luau"], [5490, "src/Rosetta/archive/rpm/init.luau"], [5814, "src/Rosetta/archive/tar/init.luau"], [5932, "src/Rosetta/archive/unitypackage/init.luau"], [6168, "src/Rosetta/archive/uu/init.luau"], [6438, "src/Rosetta/archive/vpk/init.luau"], [6749, "src/Rosetta/archive/vswap/init.luau"], [7019, "src/Rosetta/archive/wad/init.luau"], [7473, "src/Rosetta/archive/wad/Picture.luau"], [7575, "src/Rosetta/archive/wad2/init.luau"], [7857, "src/Rosetta/archive/xz/init.luau"]],
"archive_2": [[8, "src/Rosetta/archive/yenc/init.luau"], [280, "src/Rosetta/archive/z/init.luau"], [376, "src/Rosetta/archive/zip/init.luau"], [595, "src/Rosetta/archive/zoo/init.luau"], [791, "src/Rosetta/archive/zst/init.luau"]],
"audio": [[8, "src/Rosetta/audio/aac/init.luau"], [221, "src/Rosetta/audio/ac3/init.luau"], [368, "src/Rosetta/audio/adpcm/init.luau"], [514, "src/Rosetta/audio/adx/init.luau"], [746, "src/Rosetta/audio/aiff/init.luau"], [1138, "src/Rosetta/audio/ape/init.luau"], [1267, "src/Rosetta/audio/au/init.luau"], [1429, "src/Rosetta/audio/brstm/init.luau"], [1721, "src/Rosetta/audio/caf/init.luau"], [2388, "src/Rosetta/audio/flac/init.luau"], [2537, "src/Rosetta/audio/flac/Meta.luau"], [2759, "src/Rosetta/audio/flac/Stream.luau"], [3129, "src/Rosetta/audio/m4a/init.luau"], [3472, "src/Rosetta/audio/mp3/init.luau"], [3733, "src/Rosetta/audio/mp3/Index.luau"], [3924, "src/Rosetta/audio/mp3/Stream.luau"], [4151, "src/Rosetta/audio/mp3/Tags.luau"], [4463, "src/Rosetta/audio/mpc/init.luau"], [4558, "src/Rosetta/audio/opus/init.luau"], [4937, "src/Rosetta/audio/opus/Encode.luau"], [5049, "src/Rosetta/audio/qoa/init.luau"], [5230, "src/Rosetta/audio/tta/init.luau"], [5349, "src/Rosetta/audio/vag/init.luau"], [5573, "src/Rosetta/audio/voc/init.luau"], [5849, "src/Rosetta/audio/vorbis/init.luau"], [6304, "src/Rosetta/audio/vorbis/Encode.luau"], [7117, "src/Rosetta/audio/wav/init.luau"], [7738, "src/Rosetta/audio/wav/Codecs.luau"], [7917, "src/Rosetta/audio/wavpack/init.luau"]],
+3732 -91
View File
File diff suppressed because it is too large. Load diff
+3673 -46
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -24,7 +24,7 @@ come back as a third value `{ [file name] = buffer }` (or in the caller's `opts.
| `F.save(value, dest?, opts?)` | `buffer` / `true` (+ the extra files, see above) |
| `F.saveString(value, opts?)` | the encoded bytes as a string |
| `F.convert(src, format, opts?)` | load + save (`opts` go to both; `opts.out = path` writes a file) |
| `F.detect(src, opts?)` | the format name (content sniffing first, then the extension); a format's optional `variant(r)` can name the flavour (`"webm"` for a WebM file read by mkv) |
| `F.detect(src, opts?)` | the format name (content sniffing first, then the extension); a format's optional `variant(r)` can name the flavour (`"webm"` for a WebM file read by mkv). Sniffing loads no format module (the generated `Sniffs.luau`); `load` / `open` / `save` load only the format they use |
| `F.formats(category?)` | `{ { name, category, extensions, mime, caps } }` without loading any format (also [FORMATS.md](FORMATS.md)) |
| `F.format(name)` | the format module itself (`sniff` / `decode` / `encode` / `open` and extras such as `png.info`) |
+8 -3
View File
@@ -18,7 +18,7 @@ The reference implementation to copy is **PNG**:
```
src/Rosetta/
init.luau Registry.luau (generated) api (layer 6)
init.luau Registry.luau Sniffs.luau (gen.) api (layer 6)
ops/ ops (layer 5.5) editing on the standard types (F.ops.image /
mesh / layers / audio / music; ImageOps, ...)
<category>/<fmt>/ formats (layer 5) image audio video model cad font archive data
@@ -156,6 +156,11 @@ Rules:
inside a bigger buffer; never assume offset 0). It returns the category's standard type from `Types.luau`
(`Types.Image.new(w, h)`, `Types.Scene.new()`, ...), `rgba8` for images unless `opts.native` asks for the source layout.
Fill `meta.source = { format = "<name>", ... }` with the source facts (bit depth, colour type, codec, ...).
- `sniff(r)` scores 0..1 and is copied, with the top-level locals, types and loops it reaches, into the generated
`Sniffs.luau`, so detection requires no format module (requires outside `core/` become proxies loaded at sniff time).
A sniff that reaches its module table (`Png.info(r)`), a forward-declared local or a load-time read of a non-core
module is not copied: its module then loads on every detection that gets that far. `tests/detect.luau` checks the
copies against the modules.
- `encode(value, opts)` returns a buffer. Validate the value first and return `Err.ARG` for anything wrong.
- `open(r, opts)` (audio / video) returns the streaming Decoder / VideoDecoder / Demuxer from `Types.luau`. If a format
has `open` but no `decode`, `F.load` decodes the whole stream through it.
@@ -312,8 +317,8 @@ t:done()
2. Shared code (a codec two formats need, a container) goes to `codecs/<domain>/` or `containers/` instead, with its
own test in `tests/codecs/` / `tests/containers/`.
3. `deps = { ... }` = the requires outside the folder.
4. `python3 -I tools/gen_registry.py` (regenerates `src/Rosetta/Registry.luau` and `docs/FORMATS.md`; never edit those
by hand; after a merge, just rerun it).
4. `python3 -I tools/gen_registry.py` (regenerates `src/Rosetta/Registry.luau`, `Sniffs.luau` and `docs/FORMATS.md`;
never edit those by hand; after a merge, just rerun it).
5. `tools/fixtures/<fmt>.py` + `tests/<category>/<fmt>.luau`.
6. `bash tools/test.sh <fmt>` while working (both runtimes), then `bash tools/test.sh` (everything + lint).
7. The docs line comes from the contract (`docs/FORMATS.md`); put format notes (limits, spec deviations, bench numbers)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+77 -44
View File
@@ -78,6 +78,56 @@ end
local LATE: { [string]: number } = { br = 0.3 } -- archive/br: a trial decode of up to 256 KB
-- detection order: by the cost of a sniff (Registry.sniff: Sniffs.luau, Sniffs.luau reaching a codec, the format
-- module), then registry order; the costly LATE sniffs last
local order: { number }? = nil
local byExt: { [string]: { number } } = {}
local Sniffs: { [string]: (any) -> number }? = nil
local function sniffOrder(): { number }
local o = order
if o then
return o
end
local list: { number } = {}
for idx, e in Registry do
table.insert(list, idx)
for _, x in e.extensions do
byExt[x] = byExt[x] or {}
table.insert(byExt[x], idx)
end
end
local function rank(idx: number): number
local e = Registry[idx]
return if LATE[e.name] then 3 else e.sniff
end
table.sort(list, function(a: number, b: number): boolean
local ra, rb = rank(a), rank(b)
if ra ~= rb then
return ra < rb
end
return a < b
end)
order = list
return list
end
local function sniffer(e: Registry.Entry): ((any) -> number)?
if e.sniff < 2 then
local s = Sniffs
if not s then
s = require("@rosetta/Sniffs") :: any
Sniffs = s
end
local f = (s :: { [string]: (any) -> number })[e.path]
if f then
return f
end
end
local m = module(e)
return if m and type(m.sniff) == "function" then m.sniff else nil
end
local function detect(buf: buffer, name: string?, category: string?, format: string?): (Registry.Entry?, Err.Err?)
if format then
local e = find(format, category)
@@ -87,52 +137,35 @@ local function detect(buf: buffer, name: string?, category: string?, format: str
return e, nil
end
local ext = Input.extension(name)
local list = sniffOrder()
local hits = if ext then byExt[ext] else nil
local best: Registry.Entry? = nil
local bestScore, bestIdx = 0, 0
-- sniffs score 0..1 (core/Sniff); the extension's format scoring 1 cannot be beaten. Formats with a costly sniff
-- (LATE: the most they score) run last, and only when they could still win; ties go to registry order.
local late: { number }? = nil
for idx, e in Registry do
if inCategory(e, category) and (e.caps.decode or e.caps.open) then
local cap = LATE[e.name]
if cap then
late = late or {}
table.insert(late :: { number }, idx)
continue
end
local m = module(e)
if m and m.sniff then
local ok, score = pcall(m.sniff, Bytes.reader(buf))
if ok and type(score) == "number" and score > 0 then
local extHit = ext and table.find(e.extensions, ext)
if extHit then
score += 0.01 -- ties go to the extension
end
if score > bestScore then
best, bestScore, bestIdx = e, score, idx
if extHit and score >= 1.01 then
return e, nil
end
end
-- sniffs score 0..1 (core/Sniff), +0.01 for the extension's formats; the best wins, ties go to registry order. The
-- extension's formats run first, and a sniff runs only while its cap (1, or LATE) could still win.
for pass = 1, 2 do
local ids = if pass == 1 then hits else list
if ids then
for _, idx in ids do
if pass == 2 and bestScore > 1 then
break
end
end
end
end
if late then
for _, idx in late do
local e = Registry[idx]
local extHit = ext and table.find(e.extensions, ext)
local cap = LATE[e.name] + (if extHit then 0.01 else 0)
if cap > bestScore or (cap == bestScore and idx < bestIdx) then
local m = module(e)
if m and m.sniff then
local ok, score = pcall(m.sniff, Bytes.reader(buf))
if ok and type(score) == "number" and score > 0 then
if extHit then
score += 0.01
end
if score > bestScore or (score == bestScore and idx < bestIdx) then
best, bestScore, bestIdx = e, score, idx
local e = Registry[idx]
local extHit = pass == 1 or (hits ~= nil and table.find(hits, idx) ~= nil)
if (pass == 1 or not extHit) and inCategory(e, category) and (e.caps.decode or e.caps.open) then
local cap = (LATE[e.name] or 1) + (if extHit then 0.01 else 0)
if cap > bestScore or (cap == bestScore and idx < bestIdx) then
local sniff = sniffer(e)
if sniff then
local ok, score = pcall(sniff, Bytes.reader(buf))
if ok and type(score) == "number" and score > 0 then
if extHit then
score += 0.01
end
if score > bestScore or (score == bestScore and idx < bestIdx) then
best, bestScore, bestIdx = e, score, idx
end
end
end
end
end
@@ -696,7 +729,7 @@ function F.detect(src: any, opts: Options?): (string?, Err.Err?)
return nil, err
end
-- a format may name the file's flavour more precisely (video/mkv: "webm" for DocType webm)
local m = module(entry)
local m = if entry.variant then module(entry) else nil
if m and type(m.variant) == "function" then
local ok, v = pcall(m.variant, Bytes.reader(buf))
if ok and type(v) == "string" then
+210
View File
@@ -0,0 +1,210 @@
-- detect tests: lazy detection (Sniffs.luau, cost order, extension first) against the eager reference (every format
-- module's own sniff, registry order) on samples of every fixture module, with and without names and categories;
-- which modules a first detect loads. Fixtures: tools/fixtures/detect.py.
local T = require("@tests/T")
local Registry = require("@rosetta/Registry")
local loads: { string } = {}
for _, e in Registry do
local load = e.load
e.load = function(): any
table.insert(loads, e.path)
return load()
end
end
local F = require("@rosetta")
local Bytes = require("@rosetta/core/Bytes")
local Input = require("@rosetta/core/Input")
local Sniffs = require("@rosetta/Sniffs")
local Blobs1 = require("@tests/gen/detect_blobs_1")
local Blobs2 = require("@tests/gen/detect_blobs_2")
local Blobs3 = require("@tests/gen/detect_blobs_3")
local Blobs4 = require("@tests/gen/detect_blobs_4")
local t = T.suite("detect")
-- 1. a first detect of a PNG loads no format module, with or without its name
local PNG = buffer.fromstring("\137PNG\r\n\26\n\0\0\0\rIHDR\0\0\0\1\0\0\0\1\8\6\0\0\0\31\21\196\137\0\0\0\rIDATx\218c\248\255\255?\0\5\254\2\254\167\53\129\132\0\0\0\0IEND\174B`\130")
t:eq(F.detect(PNG, { name = "a.png" }), "png", "png with name")
t:eq(F.detect(PNG), "png", "png without name")
t:eq(F.detect(PNG, { name = "a.jpg" }), "png", "png named .jpg")
t:eq(#loads, 0, "no format module loaded (" .. table.concat(loads, " ") .. ")")
local junk = buffer.create(4096)
for i = 0, 4095 do
buffer.writeu8(junk, i, (i * 7919) % 251)
end
F.detect(junk)
local need = 0
for _, e in Registry do
if e.sniff == 2 then
need += 1
end
end
t:check(#loads <= need + 1, "unknown data loads only the modules that sniff themselves: " .. table.concat(loads, " "))
t:note("unknown data: %d format modules loaded (%s)", #loads, table.concat(loads, " "))
-- 2. the eager reference: each module's own sniff in registry order, the extension's format at 1 returns at once,
-- archive/br (a trial decode, at most 0.3) last
local modules: { [string]: any } = {}
for _, e in Registry do
modules[e.path] = e.load()
end
local function refDetect(buf: buffer, name: string?, category: string?): any
local ext = Input.extension(name)
local best, bestScore, bestIdx = nil, 0, 0
local late: { number } = {}
for idx, e in Registry do
if (category == nil or e.category == category) and (e.caps.decode or e.caps.open) then
if e.name == "br" then
table.insert(late, idx)
continue
end
local ok, score = pcall(modules[e.path].sniff, Bytes.reader(buf))
if ok and type(score) == "number" and score > 0 then
local extHit = ext and table.find(e.extensions, ext)
if extHit then
score += 0.01
end
if score > bestScore then
best, bestScore, bestIdx = e, score, idx
if extHit and score >= 1.01 then
return e
end
end
end
end
end
for _, idx in late do
local e = Registry[idx]
local extHit = ext and table.find(e.extensions, ext)
local cap = 0.3 + (if extHit then 0.01 else 0)
if cap > bestScore or (cap == bestScore and idx < bestIdx) then
local ok, score = pcall(modules[e.path].sniff, Bytes.reader(buf))
if ok and type(score) == "number" and score > 0 then
if extHit then
score += 0.01
end
if score > bestScore or (score == bestScore and idx < bestIdx) then
best, bestScore, bestIdx = e, score, idx
end
end
end
end
if best then
return best
end
if ext then
for _, e in Registry do
if (category == nil or e.category == category) and e.name == ext then
return e
end
end
for _, e in Registry do
if (category == nil or e.category == category) and table.find(e.extensions, ext) then
return e
end
end
end
return nil
end
local function refName(buf: buffer, name: string?, category: string?): string?
local e = refDetect(buf, name, category)
if not e then
return nil
end
local m = modules[e.path]
if type(m.variant) == "function" then
local ok, v = pcall(m.variant, Bytes.reader(buf))
if ok and type(v) == "string" then
return v
end
end
return e.name
end
local blobs: { { from: string, data: string } } = {}
for _, part in { Blobs1, Blobs2, Blobs3, Blobs4 } do
for _, b in part :: any do
table.insert(blobs, b)
end
end
local rng = T.rng(7)
for n = 0, 40 do
local b = buffer.create(n * 7)
for i = 0, n * 7 - 1 do
buffer.writeu8(b, i, rng(256) - 1)
end
table.insert(blobs, { from = "random", data = buffer.tostring(b) })
end
table.insert(blobs, { from = "junk", data = buffer.tostring(junk) })
table.insert(blobs, { from = "png", data = buffer.tostring(PNG) })
t:check(#blobs > 1000, "samples from the fixture modules (" .. #blobs .. ")")
-- 3. every copied sniff scores as the module's own, and every score is in 0..1 (the cost order relies on it)
local copied, diff, over = 0, 0, 0
for _, e in Registry do
local s = (Sniffs :: any)[e.path]
t:eq(s ~= nil, e.sniff < 2, e.path .. ": in Sniffs.luau as Registry.sniff says")
if s then
copied += 1
end
end
for _, b in blobs do
local buf = buffer.fromstring(b.data)
for _, e in Registry do
local own = modules[e.path].sniff
local ok1, s1 = pcall(own, Bytes.reader(buf))
if ok1 and type(s1) == "number" and s1 > 1 then
over += 1
t:note("%s scores %s on a sample of %s", e.path, tostring(s1), b.from)
end
local s = (Sniffs :: any)[e.path]
if s then
local ok2, s2 = pcall(s, Bytes.reader(buf))
if ok1 ~= ok2 or (ok1 and s1 ~= s2) then
diff += 1
if diff <= 10 then
t:note("%s on a sample of %s: module %s, copy %s", e.path, b.from, tostring(s1), tostring(s2))
end
end
end
end
end
t:eq(diff, 0, "copied sniffs score as the modules do")
t:eq(over, 0, "no sniff scores over 1")
-- 4. F.detect = the reference: no name, the reference's own extension, a wrong one, an unknown one; and per category
local runs, mismatch = 0, 0
local function same(buf: buffer, from: string, name: string?, category: string?)
local want = refName(buf, name, category)
local got = F.detect(buf, { name = name, category = category })
runs += 1
if got ~= want then
mismatch += 1
if mismatch <= 10 then
t:note("sample of %s, name %s, category %s: got %s, want %s", from, tostring(name), tostring(category), tostring(got), tostring(want))
end
end
end
for _, b in blobs do
local buf = buffer.fromstring(b.data)
same(buf, b.from, nil, nil)
local e = refDetect(buf, nil, nil)
if e then
same(buf, b.from, "x." .. e.extensions[1], nil)
same(buf, b.from, nil, e.category)
end
same(buf, b.from, "x.png", nil)
same(buf, b.from, "x.txt", nil)
same(buf, b.from, "x.bin", "audio")
end
t:eq(mismatch, 0, "F.detect matches the eager reference (" .. runs .. " detects)")
t:note("%d samples, %d detects, %d of %d sniffs copied into Sniffs.luau", #blobs, runs, copied, #Registry)
t:fuzz("detect", function(b: buffer): any
return F.detect(b)
end, { PNG, junk })
t:done()
+6 -1
View File
@@ -8,6 +8,7 @@
# 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).
# LAST = True runs it after the others; it also reruns when any other generator's output changed (it reads them)
#
# 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
@@ -123,12 +124,16 @@ def main():
if "--list" in sys.argv:
print("\n".join(names))
return
mods = {name: load(os.path.join(GENERATORS, name + ".py")) for name in names}
names.sort(key=lambda n: bool(getattr(mods[n], "LAST", False)))
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)
mod = mods[name]
inputs = [path, os.path.abspath(__file__)] + [os.path.join(ROOT, p) for p in getattr(mod, "INPUTS", [])]
if getattr(mod, "LAST", False):
inputs += [os.path.join(stamps, n) for n in names if n != name and not getattr(mods[n], "LAST", False)]
stamp = os.path.join(stamps, name)
if not force and os.path.exists(stamp):
outs = open(stamp).read().split("\n")
+56
View File
@@ -0,0 +1,56 @@
# Detection fixtures (tools/fixtures.py): samples of every other fixture module, for tests/detect.luau (lazy detection
# against the eager reference). Runs after the other generators (LAST) and reads their tests/gen output.
# tests/gen/detect_blobs_<1..4>.luau { { from = "<module>", data = <bytes> } }: up to PER_MODULE string literals of
# 16 bytes or more per module, evenly spaced, cut to CUT bytes, without repeats
import hashlib, os, re
LAST = True
PER_MODULE = 6
CUT = 16384
PARTS = 4
PART_BYTES = 5_000_000
HEADER = "-- generated by tools/fixtures.py"
LITERAL = re.compile(rb'"([^"]*)"')
ESCAPE = re.compile(rb"\\x([0-9a-f]{2})")
def decode(raw):
return ESCAPE.sub(lambda m: bytes([int(m.group(1), 16)]), raw)
def generate(ctx):
names = sorted(f[:-5] for f in os.listdir(ctx.gen) if f.endswith(".luau") and not f.startswith("detect_"))
seen, blobs = set(), []
for name in names:
with open(os.path.join(ctx.gen, name + ".luau"), "rb") as f:
text = f.read()
if not text.startswith(HEADER.encode()):
continue
lits = [m.span(1) for m in LITERAL.finditer(text) if m.end(1) - m.start(1) >= 16]
lits = [(a, b) for a, b in lits if len(decode(text[a:min(b, a + 64)])) >= 16]
if not lits:
continue
step = max(1, len(lits) / PER_MODULE)
picks = sorted({int(i * step) for i in range(PER_MODULE)} & set(range(len(lits))))
for i in picks:
a, b = lits[i]
data = decode(text[a:min(b, a + CUT * 4)])[:CUT]
h = hashlib.sha1(data).digest()
if h in seen:
continue
seen.add(h)
blobs.append({"from": name, "data": data})
parts, cur, size = [], [], 0
for b in blobs:
if size + len(b["data"]) > PART_BYTES and cur:
parts.append(cur)
cur, size = [], 0
cur.append(b)
size += len(b["data"])
parts.append(cur)
if len(parts) > PARTS:
raise SystemExit("fixtures/detect: %d parts, raise PARTS (and the requires in tests/detect.luau)" % len(parts))
while len(parts) < PARTS:
parts.append([])
for i, p in enumerate(parts, 1):
ctx.emit("detect_blobs_%d" % i, p)
+48 -1
View File
@@ -3,6 +3,8 @@
# src/Rosetta/<category>/<fmt>/init.luau and writes
# src/Rosetta/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
# src/Rosetta/Sniffs.luau each format's sniff, copied with what it reaches (tools/sniff_extract.py), so detection
# runs without requiring the format modules
# docs/FORMATS.md the capability matrix, from each contract's caps
# README.md the format table (read / write) and the codec + container list, between the markers
# <!-- formats:begin --> / <!-- formats:end --> and <!-- codecs:begin --> / <!-- codecs:end -->
@@ -11,6 +13,9 @@
# --check: exit 1 when any of them is out of date (tools/lint.sh runs this).
import os, re, sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import sniff_extract
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SRC = os.path.join(ROOT, "src", "Rosetta")
CATEGORIES = ["image", "audio", "video", "model", "cad", "font", "archive", "data", "vector", "layered", "subtitle",
@@ -50,6 +55,9 @@ def scan():
sys.exit("gen_registry: %s/%s/init.luau: missing contract fields %s" % (cat, fmt, ", ".join(missing)))
c["path"] = cat + "/" + fmt
c["folder_category"] = cat
text = open(init).read()
c["sniff_cost"], c["sniff_block"], self_name = sniff_extract.extract(text, c["path"])
c["variant"] = sniff_extract.has_variant(text, self_name)
formats.append(c)
return formats
@@ -60,6 +68,8 @@ def registry(formats):
"-- 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.",
"-- sniff: where detection finds the format's sniff (tools/sniff_extract.py): 0 Sniffs.luau, 1 Sniffs.luau reaching a",
"-- codec / container on first call, 2 the format module. variant: the module has variant(r).",
"export type Entry = {",
"\tname: string,",
"\tcategory: string,",
@@ -68,6 +78,8 @@ def registry(formats):
"\tmime: { string },",
"\tdeps: { string },",
"\tcaps: { [string]: any },",
"\tsniff: number,",
"\tvariant: boolean?,",
"\tload: () -> any,",
"}",
"",
@@ -83,6 +95,8 @@ def registry(formats):
"\t\tmime = %s," % c["mime"],
"\t\tdeps = %s," % c["deps"],
"\t\tcaps = %s," % c["caps"],
"\t\tsniff = %d," % c["sniff_cost"],
] + (["\t\tvariant = true,"] if c["variant"] else []) + [
"\t\tload = function()",
'\t\t\treturn require("@rosetta/%s")' % c["path"],
"\t\tend,",
@@ -92,6 +106,38 @@ def registry(formats):
return "\n".join(out)
def sniffs(formats):
out = [
"--!strict",
"--!optimize 2",
"-- Sniffs: GENERATED by tools/gen_registry.py from the format folders - do not edit.",
"-- Each format's sniff (format path -> sniff(r)), copied from its init.luau with the top-level locals and types it",
"-- reaches (tools/sniff_extract.py), so detection requires no format module. Requires outside core/ are proxies that",
"-- require on first use. Formats whose sniff needs their module (Registry sniff = 2) are not here.",
"local S: { [string]: (any) -> number } = {}",
"",
"local function lazy(load: () -> any): any",
"\tlocal proxy = {}",
"\treturn setmetatable(proxy, {",
"\t\t__index = function(_, k: any): any",
"\t\t\tlocal m = load()",
"\t\t\tsetmetatable(proxy, { __index = m })",
"\t\t\treturn m[k]",
"\t\tend,",
"\t})",
"end",
"",
]
for c in formats:
if c["sniff_block"] is None:
continue
out.append("do -- %s" % c["path"])
out += c["sniff_block"]
out += ["end", ""]
out += ["return S", ""]
return "\n".join(out)
def caps_dict(lit):
"""{ decode = true, depths = { 8 } } -> ordered [(key, text)] at the top level."""
body = lit.strip()[1:-1]
@@ -220,6 +266,7 @@ def main():
readme_path = os.path.join(ROOT, "README.md")
outputs = {
os.path.join(SRC, "Registry.luau"): registry(formats),
os.path.join(SRC, "Sniffs.luau"): sniffs(formats),
os.path.join(ROOT, "docs", "FORMATS.md"): formats_md(formats),
readme_path: readme(formats, readme_path),
}
@@ -239,7 +286,7 @@ def main():
sys.exit(1)
print("gen_registry: up to date (%d formats)" % len(formats))
else:
print("gen_registry: %d formats -> src/Rosetta/Registry.luau, docs/FORMATS.md, README.md%s" % (
print("gen_registry: %d formats -> src/Rosetta/Registry.luau, Sniffs.luau, docs/FORMATS.md, README.md%s" % (
len(formats), "" if stale else " (unchanged)"))
+6 -3
View File
@@ -9,7 +9,7 @@
# 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
# < ops < api (init, Registry, Sniffs). 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.
# codecs live in a domain folder: codecs/<domain>/<Name> (CODEC_DOMAINS).
# DEPS a format folder's requires outside itself are exactly the contract's deps = { ... }.
@@ -19,7 +19,8 @@
# tests/<category>/<fmt>.luau with a fuzz pass (:fuzz().
# DUP no copy-pasted code: a function body of DUP_LINES (12) or more code lines whose tokens (comments and
# whitespace dropped, identifiers kept) equal another module's function body fails; move it down to a
# shared module (core / codecs / containers) and call it from both.
# shared module (core / codecs / containers) and call it from both. Sniffs.luau (generated copies of the
# formats' sniffs) is not compared.
# DOCS docs/STYLE.md's layer block names every codec (codecs/<domain>/<Name>), container and core module in the
# tree; README.md's generated format table and codec list (<!-- formats:begin --> ... <!-- codecs:end -->)
# match tools/gen_registry.py's output; README.md links every docs/guide page, docs/API.md and
@@ -69,7 +70,7 @@ def resolve(target):
def layer(mod):
"""(rank, group) of a module path"""
top = mod.split("/")[0] if mod else ""
if mod in ("", "Registry"):
if mod in ("", "Registry", "Sniffs"):
return 6, "api"
if top == "core":
return 0, "core"
@@ -296,6 +297,8 @@ TOKEN = re.compile(r'"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'|\[=*\[.*?\]=*\]|[A-Z
FUNC = re.compile(r"^(\s*)(?:local\s+)?function\b")
bodies = {}
for f, lines in text.items():
if mods[f] == "Sniffs":
continue
for i, line in enumerate(lines):
m = FUNC.match(line)
if not m:
+198
View File
@@ -0,0 +1,198 @@
#!/usr/bin/env python3
# Sniff extraction for tools/gen_registry.py: copies each format's sniff function out of its init.luau, with the
# top-level locals, types and statements it reaches, so src/Rosetta/Sniffs.luau can sniff without requiring the
# format module. A format whose sniff reaches its own module table (or a forward-declared local) is not copied: the api
# loads the module to sniff it. Requires the copy reaches: core/* as they are; any other module through a proxy that
# requires it on first field access (sniff time).
# cost 0: the copy needs only core/*; 1: it reaches a proxied module; 2: not copied (the module sniffs).
import re
KEYWORDS = set("and break continue do else elseif end false for function if in local nil not or repeat return then "
"true until while type export typeof".split())
NAME = r"[A-Za-z_]\w*"
def clean(text):
"""text with string, comment and long-bracket contents blanked (newlines kept), same length"""
out, i, n = [], 0, len(text)
while i < n:
c = text[i]
if c == "-" and text.startswith("--", i):
m = re.match(r"--\[(=*)\[", text[i:])
if m:
j = text.find("]" + m.group(1) + "]", i + len(m.group(0)))
j = n if j < 0 else j + len(m.group(1)) + 2
else:
j = text.find("\n", i)
j = n if j < 0 else j
out.append(re.sub(r"[^\n]", " ", text[i:j]))
i = j
elif c == "[" and re.match(r"\[(=*)\[", text[i:]):
m = re.match(r"\[(=*)\[", text[i:])
j = text.find("]" + m.group(1) + "]", i + len(m.group(0)))
j = n if j < 0 else j + len(m.group(1)) + 2
out.append('"' + re.sub(r"[^\n]", " ", text[i + 1:j - 1]) + '"')
i = j
elif c in "\"'":
j = i + 1
while j < n and text[j] != c and text[j] != "\n":
j += 2 if text[j] == "\\" else 1
j = min(j + 1, n)
out.append(c + " " * (j - i - 2) + c if j - i >= 2 else text[i:j])
i = j
else:
out.append(c)
i += 1
return "".join(out)
def split_top(s):
"""split s on commas outside brackets"""
parts, depth, cur = [], 0, ""
for ch in s:
if ch in "({[<":
depth += 1
elif ch in ")}]>":
depth -= 1
if ch == "," and depth == 0:
parts.append(cur)
cur = ""
else:
cur += ch
parts.append(cur)
return parts
def statements(text):
"""[(first line, last line, cleaned text)] of the top-level statements (0-based inclusive line numbers)"""
lines = text.split("\n")
cl = clean(text).split("\n")
starts = [i for i, l in enumerate(cl) if l[:1] not in ("", " ", "\t") and not re.match(r"(end|until)\b|[}\])]", l)]
out = []
for k, s in enumerate(starts):
e = (starts[k + 1] if k + 1 < len(starts) else len(lines)) - 1
while e > s and cl[e].strip() == "":
e -= 1
out.append((s, e, "\n".join(cl[s:e + 1])))
return out
def free_names(code):
"""identifiers read by code that are not field / method names (an over-approximation: locals are included)"""
return {m.group(1) for m in re.finditer(r"(?<![.:\w])\s*(" + NAME + r")", code)} - KEYWORDS
def defines(st):
"""(names, kind) a top-level statement declares: kind 'local', 'func', 'type', 'forward' or None"""
m = re.match(r"local\s+function\s+(" + NAME + ")", st)
if m:
return [m.group(1)], "func"
m = re.match(r"(?:export\s+)?type\s+(" + NAME + ")", st)
if m:
return [m.group(1)], "type"
m = re.match(r"local\s+(.*)", st, re.S)
if m:
rest = m.group(1)
depth, cut = 0, None
for i, ch in enumerate(rest):
if ch in "({[":
depth += 1
elif ch in ")}]":
depth -= 1
elif ch == "=" and depth == 0 and rest[i + 1:i + 2] != "=" and rest[i - 1:i] not in ("=", "~", "<", ">"):
cut = i
break
head = rest if cut is None else rest[:cut]
names = [p.split(":")[0].strip() for p in split_top(head.split("\n")[0] if cut is None else head)]
return [n for n in names if re.fullmatch(NAME, n)], ("forward" if cut is None else "local")
return [], None
REQUIRE = re.compile(r'^local\s+(' + NAME + r')\s*=\s*require\("@rosetta/([\w/]+)"\)\s*$')
def extract(text, path):
"""(cost, block lines or None, module table name) for one format's init.luau"""
lines = text.split("\n")
sts = statements(text)
sniff_i, self_name = None, None
for i, (s, e, st) in enumerate(sts):
m = re.match(r"function\s+(" + NAME + r")\.sniff\s*\(", st)
if m:
sniff_i, self_name = i, m.group(1)
if sniff_i is None:
return 2, None, None
defs = [] # (statement index, name, kind)
for i, (s, e, st) in enumerate(sts):
names, kind = defines(st)
for n in names:
defs.append((i, n, kind))
def_names = {n for _, n, _ in defs}
# top-level statements that are not declarations: assignments, loops (a table filled at load time)
others = [i for i, (s, e, st) in enumerate(sts) if defines(st)[1] is None and i != sniff_i]
def resolve(name, before):
best = None
for i, n, kind in defs:
if n == name and i < before:
best = (i, kind)
return best
include, lazy, todo, bad = set(), {}, [sniff_i], False
reached = set()
while todo:
i = todo.pop()
if i in include:
continue
include.add(i)
st = sts[i][2]
body = st
if i == sniff_i:
body = st[st.index("("):]
for n in free_names(body):
if n == self_name:
bad = True
continue
r = resolve(n, i)
if r is None:
continue
j, kind = r
if kind == "forward":
bad = True
continue
reached.add(n)
req = REQUIRE.match(lines[sts[j][0]]) if sts[j][0] == sts[j][1] else None
if req and not req.group(2).startswith("core/"):
lazy[j] = (req.group(1), req.group(2))
continue
todo.append(j)
# load-time statements that touch a reached local (a lookup table filled by a loop)
for k in others:
if k not in include and re.match(r"(function\s+)?" + re.escape(self_name) + r"\b|return\b", sts[k][2]) is None:
if free_names(sts[k][2]) & reached:
todo.append(k)
if bad:
return 2, None, self_name
# a non-function statement that reads a proxied module runs at load time: the proxy would load it at once
for i in include:
if i != sniff_i and defines(sts[i][2])[1] not in ("func", "type"):
if free_names(sts[i][2]) & {a for a, _ in lazy.values()}:
return 2, None, self_name
block = []
for i in sorted(set(include) | set(lazy)):
s, e, st = sts[i]
if i in lazy:
alias, mod = lazy[i]
block.append('local %s = lazy(function()\n\treturn require("@rosetta/%s")\nend)' % (alias, mod))
elif i == sniff_i:
src = "\n".join(lines[s:e + 1])
src = re.sub(r"^function\s+" + re.escape(self_name) + r"\.sniff\s*\(", 'S["%s"] = function(' % path, src)
block.append(src)
else:
src = "\n".join(lines[s:e + 1])
block.append(re.sub(r"^export\s+type\b", "type", src))
return (1 if lazy else 0), block, self_name
def has_variant(text, self_name):
return self_name is not None and re.search(r"^function\s+" + re.escape(self_name) + r"\.variant\s*\(", text, re.M) is not None