Files
rosetta/docs/STYLE.md
T
4DBug e05392ee8e api: lazy format detection (Sniffs.luau): F.detect loads no format module
tools/gen_registry.py now also writes src/Rosetta/Sniffs.luau: each format's sniff copied
(tools/sniff_extract.py) with the top-level locals, types and load-time loops it reaches;
requires outside core/ become proxies that require on first field access. 198 of 199
sniffs are copied (model/fbx reads Binary.MAGIC at load time: its module sniffs).
Registry entries gain sniff (0 copy, 1 copy reaching a codec / container, 2 module) and
variant (the module has variant(r)).

init.luau detect: the extension's formats first, then by sniff cost and registry order;
a sniff runs only while its cap (1, or LATE) could still win, ties to registry order, so
results equal the eager path. F.detect loads the winner only when it has variant().

tests/detect.luau: every copied sniff against its module's on samples of every fixture
module (tools/fixtures/detect.py), scores within 0..1, and F.detect against the eager
reference with no name, the right / wrong / unknown extension and per category.

Outside init / Registry / gen_registry: tools/fixtures.py (LAST generators run after
the others and rerun when their outputs change), tools/lint_rules.py (Sniffs is api
layer, skipped by DUP), docs/STYLE.md and docs/API.md notes, build/ regenerated.
2026-11-02 21:58:10 -06:00

363 lines
24 KiB
Markdown

# rosetta style guide
Every format looks the same: one folder, one contract, one test, one fixture generator, and the folder holds only what
is specific to the format (section 2a). `bash tools/lint.sh` enforces most of what follows (the rule names in
CAPITALS are lint rules, implemented in `tools/lint_rules.py`).
The reference implementation to copy is **PNG**:
| What | Copy from |
|---|---|
| Format contract (`init.luau`) | `src/Rosetta/image/png/init.luau` |
| Private hot submodules (`--!native`) | `src/Rosetta/image/png/Decode.luau`, `src/Rosetta/image/png/Encode.luau` |
| Test | `tests/image/png.luau` |
| Fixture generator | `tools/fixtures/png.py` (a reference tool through nix: `tools/fixtures/_png_reference.py`) |
| A codec (layer 3) | `src/Rosetta/codecs/compress/Deflate/` + `tests/codecs/deflate.luau` + `tools/fixtures/deflate.py` |
## 1. Layout and layers
```
src/Rosetta/
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
vector layered subtitle music playlist
containers/ containers (layer 4) Archive AudioWrap Avi Chunks Cpio Demux Ebml
Fat Iso9660 IsoBmff MacFile MpegEs MpegPs
MpegTs Ogg Riff Tar Zip
codecs/<domain>/<Name> codecs (layer 3) generic algorithms, by domain:
compress/ Brotli Bzip2 Deflate Explode Lz4 Lzh Lzma Lzw Lzx PackBits Quantum UnixCompress Xxh32 Zstd
entropy/ Huffman RangeCoder
image/ Bcn Blend Dct Etc Half Jpeg Miptex Pixels Quantize Raster Texel Texture Vp8 Vp8L Yuv
audio/ Aac Ac3 Adpcm Alac Ape ApeTag Flac Hively Mdct MidiRender Mpa Musepack Opus Pcm Qoa Resample
SoundFont Stream Tracker Tta Vorbis VorbisComment WavPack
video/ Dsp H263 H264 Legacy Mpeg1 Mpeg2 Theora Video (the video codec registry)
text/ Json KeyValues Nbt Text Url Xml
text/ GodotVariant Json Nbt Text Url Xml
font/ Bitmap Cff GlyphNames TrueType
model/ Brush Displacement Draco Mat4 MeshFlatten Minecraft Patch Polygon Rbx Rig Sampler SourceAnim Vrml
text/ Json Lexer Nbt Text Url Xml
font/ Bitmap Cff GlyphNames TrueType
model/ Brush DoomMap Draco Mat4 MeshFlatten Minecraft Patch Polygon Rbx Rig Sampler Vrml
host/ host (layer 2) runtime adapters; only the api uses them
Types.luau types (layer 1) standard types + constructors
core/ core (layer 0) Adler32 Base64 Bits Bytes Crc16 Crc32 Err Input
Md5 Sniff (runtime-neutral primitives)
```
LAYERS: a module requires only what is below it. core requires core; Types requires core; codecs require core, Types
and other codecs; containers add codecs; a format may require core, Types, codecs, containers and **its own folder**,
never another format (shared code moves down to `codecs/` or `containers/`: WebP lossy and WebM both use `codecs/image/Vp8`).
Nothing but the api requires `host/`: formats are pure functions of bytes. A codec lives in a domain folder
(`codecs/<compress|entropy|image|audio|video|text|font|model>/<Name>`); `containers/` and `core/` are flat. Moving a
module: `python3 -I tools/move.py old/Path=new/Path` rewrites every reference (requires, deps, headers, docs).
REQUIRE: every require is a string literal `require("@rosetta/<path>")` (tests and tools may also use
`require("@tests/<path>")`). No `script.X`, no `@self`, no relative paths, no computed requires: `tools/build.py` turns
these literals into Roblox instance paths and `require("rosetta.x.y")` for LuaJIT. `@rosetta/image/png` is the folder's
`init.luau`.
DEPS: a format's `deps = { ... }` lists exactly the modules outside its folder that the folder requires.
## 2. The format template
### Files
```
src/Rosetta/<category>/<fmt>/init.luau the contract (interpreted: never --!native)
src/Rosetta/<category>/<fmt>/<Private>.luau hot code, --!native allowed (Decode, Encode, Huffman tables, ...)
tests/<category>/<fmt>.luau the test (both runtimes)
tools/fixtures/<fmt>.py fixture generator (reference tools via nix) -> tests/gen/<fmt>_*.luau
```
### File header (HEADER)
```luau
--!strict
--!native -- private hot submodules only
--!optimize 2 -- optional
-- image/png/Decode: <what it is>. <Spec / port origin>. <Supports / not supported>.
```
The first comment line starts with the module path (`core/Bytes:`, `image/png:`, `image/png/Decode:`; `Rosetta:` for
the root). A format's `init.luau` header says what is supported and what is not, and where it came from (spec, port,
absorbed repo).
### Comments
Comments carry specifications, not documentation. Usage lives in `docs/API.md` and `docs/guide`, and the code says what
it does. Keep:
- the file header, 1-3 lines (above);
- spec citations: section numbers, field and bit layouts, magic values, where a table comes from;
- one-line notes where the code deliberately matches a reference tool's quirk or follows a non-obvious spec rule;
- units and layouts on type fields (`pts: number, -- seconds`, `data: buffer, -- u16 LE per cell`);
- licence / provenance lines and the `--!` directives.
Remove signature and docstring comments, comments that restate the code, narrative and history ("we tried X"),
usage examples, and divider banners other than the CONTRACT section markers.
```luau
-- keep
-- CRC-32/MPEG-2 (poly 0x04C11DB7, init 0xFFFFFFFF, MSB first, no final xor): a section including its CRC sums to 0
break -- no end-of-archive blocks: accepted, as GNU tar does (with a warning)
-- LuaJIT keeps t[0] in the array part, so check it
-- remove
-- expect(ctx, i, ch) -> next position after ch (skipping blanks), or nil
-- UTF-8 of a code point
-- ---------------------------------------------------------------------------------------------- helpers
```
`python3 -I tools/comment_diff.py <base>` checks that a comment-only change leaves every file's token stream unchanged.
### Section order (CONTRACT)
Section markers are `-- ` + 96 dashes + ` <name>`; in a format's `init.luau` they appear in this order (requires and
contract are mandatory, the rest as needed):
`requires`, `contract`, `types`, `constants`, `sniff`, `decode`, `encode`, `open`, `extras`
### The contract
```luau
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Decode = require("@rosetta/image/qoi/Decode")
-- ------------------------------------------------------------------------------------------------ contract
local Qoi = {
name = "qoi", -- = the folder name
category = "image", -- = the folder category
extensions = { "qoi" }, -- lower case, no dot; the first is the canonical one
mime = { "image/qoi" },
deps = { "core/Err", "core/Bytes", "Types" }, -- exactly the requires outside the folder
caps = { decode = true, encode = true, alpha = true, depths = { 8 } },
}
-- ------------------------------------------------------------------------------------------------ sniff
function Qoi.sniff(r: Bytes.Reader): number -- 0..1 from the first bytes; never consumes, never throws
return if r:peek(4) == "qoif" then 1 else 0
end
-- ------------------------------------------------------------------------------------------------ decode
function Qoi.decode(r: Bytes.Reader, opts: DecodeOptions?): (Types.Image?, Err.Err?)
...
return img, nil
end
-- ------------------------------------------------------------------------------------------------ encode
function Qoi.encode(img: Types.Image, opts: EncodeOptions?): (buffer?, Err.Err?)
...
end
return Qoi
```
Rules:
- The six fields are **one-line literals** in the table (`tools/gen_registry.py` copies them into `Registry.luau` and
`docs/FORMATS.md` without running Luau). `caps.decode` / `caps.encode` match the functions that exist
(`decode = true` also when only `open` exists). Other caps keys are free-form facts (`animation`, `alpha`, `depths`,
`lossy`, `channels`, `streaming`, ...).
- `decode(r, opts)` gets a `core/Bytes` Reader over exactly the file (`r.buf`, `r.base`, `r.limit`: the data may sit
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.
- Options are a typed table with defaults documented on each field (`level: number?, -- 0..9, default 6`).
- Extra format-specific functions (`Png.info(r)`) are fine; `F.format("png")` returns the module. Two optional ones the
api calls: `variant(r) -> string?` (a more precise name for `F.detect`: video/mkv gives `"webm"`), and encoders
that write extra files into `opts.files` declare `caps.extraFiles = true` (the api then returns them from
`F.save` without a destination).
- No globals, no state between calls, no host access (no files, no `game`).
### Conventions shared by every format
- Images: `rgba8` unless `opts.native`; `img.loops` is the play count (0 = forever: GIF stores repeats, APNG / WebP
play counts); animation frames per `Types.Frame`.
- Audio: interleaved f32 in **WAVE channel order** (FL FR C LFE BL BR SL SR; Vorbis / Opus streams are reordered with
`Pcm.WAVE_FROM_VORBIS`); `tags` keys are **lower case** (title, artist, album, albumartist, date, genre, track,
disc, comment, ...: `codecs/audio/VorbisComment` for Vorbis / Opus / FLAC); raw fields go in `meta.source`.
- Hooks: a format never requires another format. For embedded data in another format the api passes
`opts.decodeImage(buf)`, `opts.encodeImage(img, format)`, `opts.openAudio(demuxer, track)` (audio tracks of video
containers, through `containers/AudioWrap`), `opts.plugins` (injected optional dependencies such as the B-rep
kernel) and `opts.resolve(uri)` (sibling files); without them the embedded part is `Err.UNSUPPORTED`. Video codecs
register in `codecs/video/Video` (fourcc / Matroska id -> decoder) so every container finds them.
### Errors (Err)
Nothing throws on bad data or bad arguments. Every failure is `return nil, Err.new(code, message, offset?)`:
| Code | When |
|---|---|
| `Err.TRUNCATED` | the data ends early (a `Bytes` reader past its end sets this itself) |
| `Err.CORRUPT` | malformed data |
| `Err.CHECKSUM` | CRC / Adler / hash mismatch |
| `Err.UNSUPPORTED` | valid data using a feature not implemented (say which) |
| `Err.LIMIT` | over `opts.maxPixels` / `opts.maxBytes` / ... (decoders must have a size limit before allocating) |
| `Err.ARG` | bad argument / option / value to encode |
| `Err.IO`, `Err.UNKNOWN_FORMAT` | used by the api |
Messages are lower case, without the format name (the api adds it: `png: CORRUPT at 0x21: bad filter type 7`).
The `Bytes` reader's errors are sticky: read a run of fields, then check `if r.err then return nil, r.err end` once.
Private submodules may return `false, "message"` or `nil, "message"[, kind]`; `init.luau` turns that into an `Err`
with `Err.from(message, offset?, kind?)` (kind = "truncated" / "limit" / ...; without it a `"limit: "` /
`"unsupported: "` prefix or "truncated" / "past the end" in the message picks the code, else CORRUPT).
### Native code (NATIVE)
A Luau error unwinding through a native frame crashes Roblox Studio, even inside `pcall`. So:
- `--!native` only in private submodules (never a format's `init.luau`), and on `core/` / `codecs/` modules.
- A `--!native` module contains no `error(` / `assert(` and requires no module that does; an `@native` function body
contains none either.
- Every buffer access in native code is in range by construction: check lengths before loops (`r:need(n)`, explicit
`if p + n > limit then return nil, "truncated" end`), clamp table indexes, validate sizes against limits first.
- The fuzz pass in every test (truncations, mutations, garbage) is the safety net: it must report 0 throws.
### Performance on both runtimes
- Hot loops cache library functions in locals (`local readu8 = buffer.readu8`) and keep their own bit buffers.
- Bits / Bytes readers are for headers; inner loops read the buffer directly.
- LuaJIT runs the same code through `compat/luajit.lua` (FFI `buffer`, unsigned `bit32`). It is fastest with
straight-line code in the hottest loop: a tiny inner loop (`for k = 0, len - 1 do ... end` inside the symbol loop)
splits LuaJIT's traces; codecs/compress/Deflate/Inflate copies short matches with four `readu32` / `writeu32` instead.
- Benchmark with `bash tools/bench.sh` pinned to one core (`taskset -c 2 bash tools/bench.sh`): on hybrid CPUs (this
machine: Zen 5 + Zen 5c) the same run differs 2x between core types.
- Avoid `string.pack` / `string.unpack` (not in LuaJIT), `\0` inside Lua patterns (LuaJIT: use `%z` or plain find),
and fractional operands to `bit32` (LuaJIT rounds where Luau truncates).
## 2a. What belongs in a format folder
A format folder holds only what is specific to the format: its header / chunk parsing, the mapping to and from the
standard type, its writer, and hot loops nothing else shares. A codec is not the format: the Opus, Vorbis, FLAC and
MPEG audio decoders / encoders live in `codecs/audio/` (audio/opus is Ogg Opus around `codecs/audio/Opus`), as JPEG,
VP8 / VP8L, H.264 and MPEG-1 live in `codecs/image/` / `codecs/video/`, so containers and other formats can reach
them. Anything generic goes down a layer and is called:
| Need | Use |
|---|---|
| chunked files (RIFF / IFF / PNG / CAF style: id, size, body, pad, trailer) | `containers/Chunks` (`containers/Riff` for RIFF forms) |
| a decode() that drains open() | `codecs/audio/Pcm.drain(dec, source)` |
| a streaming Decoder over packets (priming, end padding, seek pre-roll) | `codecs/audio/Stream.packets` |
| encoder input (Audio or Decoder), sample formats, channel order | `codecs/audio/Pcm` (`source`, `collect`, `Convert`, `reorder`) |
| other sample rates | `codecs/audio/Resample` |
| Vorbis comments | `codecs/audio/VorbisComment` |
| bitmap rows (indexed bits, BGR / BGRA, 5-5-5, masks, RLE4 / 8, bottom-up) | `codecs/image/Pixels` |
| 4x4 matrices, quaternions, TRS | `codecs/model/Mat4` |
| compression, entropy coding, CRCs, base64 | `codecs/compress/*`, `codecs/entropy/*`, `core/Crc32` (`.msb` too), `core/Base64` |
| bit writing for encoders | `core/Bits` (`msbWriter`, or `Bits.msbPut` on a raw record) |
| argument checking of (buffer \| string, offset, length) | `core/Bytes.span` |
| sniffing text (BOM) / magic | `core/Sniff` |
| private-submodule errors -> Err | `core/Err.from` |
| UTF-8 code points, text decoding | `codecs/text/Text` |
| ADPCM (IMA, MS, ADX, PS-ADPCM, DSP, Flash, ModPlug) | `codecs/audio/Adpcm` |
| APE tags | `codecs/audio/ApeTag` |
| GPU texture pixels (BCn, ETC / EAC, uncompressed texel layouts, half floats) | `codecs/image/Texture` (`Bcn`, `Etc`, `Texel`, `Half`) |
| animation channels sampled at a time; game-model frames, joints and skins -> Scene | `codecs/model/Sampler`, `codecs/model/Rig` |
| polygons with holes -> triangles | `codecs/model/Polygon` |
| studio model animation values (GoldSrc / Source run-length shorts, Quaternion48 / 64, bone records) | `codecs/model/SourceAnim` |
| Doom-engine maps (binary lumps, UDMF) -> tables and a Scene | `codecs/model/DoomMap` |
| C-style tokens (id Tech / UDMF text: comments, strings, numbers, words) | `codecs/text/Lexer` |
| plane brushes -> polygons (CSG hull, coplanar merge, Quake / Valve 220 / brush-primitive texturing); Bezier patches | `codecs/model/Brush`, `codecs/model/Patch` |
| Quake / GoldSrc mip textures, WAD2 / WAD3 directories; palettes (keyed index, grey, colormap) | `codecs/image/Miptex`, `codecs/image/Pixels` |
| NBT / SNBT values; Minecraft block states and colours | `codecs/text/Nbt`, `codecs/model/Minecraft` |
| Valve KeyValues (text, binary, the BSP entity lump); Source displacement surfaces | `codecs/text/KeyValues`, `codecs/model/Displacement` |
| Roblox instance trees and property values | `codecs/model/Rbx` |
| bitmap fonts as a Font; PostScript glyph names | `codecs/font/Bitmap`, `codecs/font/GlyphNames` |
| CRC-16 (XMODEM / ARC), xxHash32 | `core/Crc16`, `codecs/compress/Xxh32` |
| Mac files (data + resource forks), FAT / ISO 9660 file systems, cpio | `containers/MacFile`, `containers/Fat`, `containers/Iso9660`, `containers/Cpio` |
| 8x8 IDCT and half-pel motion compensation of MPEG-style video | `codecs/video/Dsp` |
DUP enforces the direction: a function body of 12 or more code lines repeated token for token in another module
fails the lint. When two formats need the same code, move it down (to `codecs/<domain>/` or `containers/`) instead of
copying.
## 3. Tests
`tests/<category>/<fmt>.luau`, run by `bash tools/test.sh [filter]` under `luau --codegen -O2` **and** LuaJIT. Template:
```luau
-- image/qoi tests: <what is covered>. Fixtures: tools/fixtures/qoi.py.
local T = require("@tests/T")
local Qoi = require("@rosetta/image/qoi")
local Bytes = require("@rosetta/core/Bytes")
local Crc32 = require("@rosetta/core/Crc32")
local Fx = require("@tests/gen/qoi") -- written by tools/fixtures/qoi.py
local t = T.suite("qoi")
-- 1. the contract fields
-- 2. every fixture against the reference tool's output (pixel CRC / PSNR for lossy / PCM / mesh checksums)
for _, c in Fx.cases do
local img, err = Qoi.decode(Bytes.reader(buffer.fromstring(c.data)))
t:check(img, c.name .. ": " .. tostring(err))
t:eq(Crc32.of(img.pixels), c.crc, c.name .. ": pixels")
end
-- 3. round trips through the encoder (lossless: equal; lossy: the reference decoder reads it, in the fixture step)
-- 4. error codes for crafted bad input (t:check(e.code == Err.CORRUPT, ...))
-- 5. the fuzz no-throw pass
t:fuzz("decode", function(b: buffer) return Qoi.decode(Bytes.reader(b)) end, samples)
t:done()
```
- `tests/T.luau`: `T.suite(name)` with `:check(cond, label)`, `:eq(got, want, label)`, `:note(fmt, ...)`,
`:fuzz(label, fn, samples, opts?)`, `:done()`; `T.rng(seed)` (the same numbers on both runtimes), `T.bytes{...}`,
`T.hex(buf)`, `T.runtime`.
- Fixtures: the luau CLI has no file I/O, so fixtures are Luau modules of string literals in `tests/gen/` (gitignored).
Write `tools/fixtures/<fmt>.py` with `def generate(ctx)` (see the header of `tools/fixtures.py`): `ctx.emit(name,
value)` writes `tests/gen/<name>.luau`; `ctx.nix("imagemagick", [...])` / `ctx.python(["pillow"], code)` run
reference tools through nix; `INPUTS = [...]` lists committed inputs (`tests/fixtures/<fmt>/`, small files with
their licence in `licenses/`). Prefer generating over committing. Keep fixture modules under ~15 MB.
- Both runtimes read the same `require("@tests/gen/<name>")`; there is no second mechanism.
- A fuzz pass is mandatory for every decoder (CONTRACT checks `:fuzz(`).
- Types: `luau-analyze` diagnostics are counted by the lint (TYPES) and may not rise above
`tools/lint_types_baseline.txt`; new code should add none (`LINT_TYPES=1 bash tools/lint.sh` lists them, and
`LINT_TYPES_UPDATE=1` lowers the baseline after a cleanup).
## 4. Adding a format
1. `src/Rosetta/<category>/<fmt>/init.luau` from the template above (copy `image/png/init.luau`), private submodules
next to it. Use `core/Bytes` for parsing, `core/Bits` / `codecs/entropy/Huffman` for entropy coding, the shared
modules of section 2a for everything generic, `Types` constructors for the result.
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`, `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)
in the init header or `docs/<category>/<fmt>.md` if long.
Workstreams running in parallel own their folders (`<category>/<fmt>/`, their tests, their fixture generators).
`core/`, `Types.luau`, the api, `tools/`, `compat/` and this file belong to the lead: propose changes there instead of
making them (a missing `Bytes` method, a new `Types` field, a `Err` code).
## 5. Absorbing an existing repo
1. Copy the source into its place (a codec into `codecs/<Name>/`, a format into `<category>/<fmt>/`); the old repo stays
untouched (other projects use it).
2. Provenance: the module header says `Absorbed from <repo> <version> (<author / licence>)` and what changed.
3. Licence: copy the repo's licence / NOTICE into `licenses/` (`licenses/<repo>-LICENSE.txt`) and add a line to
`licenses/NOTICE.md`. Third-party ports keep their upstream licence text there too.
4. Requires: `if script then require(script.X) else require("@self/X")` becomes `require("@rosetta/<cat>/<fmt>/X")`;
injected dependencies (`require(Png)(Deflate)`) become direct requires of the codec.
5. Checksums / bit readers / Huffman tables the repo carries are replaced by `core/` ones when equivalent.
6. Wrap the public API in the contract: `sniff`, `decode(r: Reader, opts)` (reading from `r.buf` between `r.base` and
`r.limit`), `encode`, the standard type out, `Err` values instead of strings or throws.
7. Port the tests to `tests/<category>/<fmt>.luau` with `T`, and the fixture script to `tools/fixtures/<fmt>.py`
(`ctx.emit` instead of writing files). Both runtimes must pass.
## 6. Build notes (tools/build.py)
darklua 0.19 does most of the LuaJIT lowering (`remove_types`, `remove_attribute`, `remove_compound_assignment`,
`remove_continue`, `remove_if_expression`, `remove_interpolated_string`, `remove_floor_division`,
`convert_luau_number`) and the Roblox require conversion (`convert_require` luau -> roblox). Token passes in build.py
cover what it cannot:
- **Generalized iteration** (`for k, v in t do`): no darklua rule. Rewritten to `for k, v in __iter(t) do`
(compat: functions pass through; arrays with no keys past `#t` use `ipairs`; other tables `next`).
- **darklua bug**: `remove_if_expression` nests `elseif` branches in reverse order (`if a then 1 elseif b then 2
elseif c then 3 else 4` gives `a and 1 or (c and 3 or (b and 2 or 4))`). build.py rewrites every if-expression
`elseif` to `else if` before darklua.
- **If-expression tables**: darklua lowers `if c then x else y` to `(c and {x} or {y})[1]` unless `x` is a literal.
build.py turns it back into `(c and (x) or (y))` when `x` is provably not nil/false (numbers, strings, arithmetic).
- **Requires** become `require("rosetta.a.b")`; **stdlib names** come from `rosetta._compat` through locals injected on
the first line of each module (only the ones used: LuaJIT allows 60 upvalues per function).
- `string.format("%s", x)` with interpolation and `tostring` of floats print differently on LuaJIT (14 significant
digits); never compare formatted floats in tests.