Files
rosetta/docs/STYLE.md
T

15 KiB

formats-luau style guide

Every format looks the same: one folder, one contract, one test, one fixture generator. 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/Formats/image/png/init.luau
Private hot submodules (--!native) src/Formats/image/png/Decode.luau, src/Formats/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 1) src/Formats/codecs/Deflate/ + tests/codecs/deflate.luau + tools/fixtures/deflate.py

1. Layout and layers

src/Formats/
  init.luau  Registry.luau (generated)        api        (layer 6)
  ops/                                         ops        (layer 5.5) editing on the standard types
  <category>/<fmt>/                            formats    (layer 5)   image audio video model cad font archive data
                                                                      vector layered subtitle music playlist
  containers/                                  containers (layer 4)   Riff, IsoBmff, Ebml, Ogg, Zip, Tar, ...
  codecs/                                      codecs     (layer 3)   Deflate, Lzw, Dct, Huffman-heavy algorithms
  host/                                        host       (layer 2)   runtime adapters; only the api uses them
  Types.luau                                   types      (layer 1)   standard types + constructors
  core/                                        core       (layer 0)   Bytes, Bits, Err, Crc32, Adler32, Huffman, Input

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/Vp8). Nothing but the api requires host/: formats are pure functions of bytes.

REQUIRE: every require is a string literal require("@formats/<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("formats.x.y") for LuaJIT. @formats/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/Formats/<category>/<fmt>/init.luau      the contract (interpreted: never --!native)
src/Formats/<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)

--!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:; Formats: 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).

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

-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@formats/core/Err")
local Bytes = require("@formats/core/Bytes")
local Types = require("@formats/Types")
local Decode = require("@formats/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, ...).
  • 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.
  • No globals, no state between calls, no host access (no files, no game).

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"; init.luau turns that into an Err.

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/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).

3. Tests

tests/<category>/<fmt>.luau, run by bash tools/test.sh [filter] under luau --codegen -O2 and LuaJIT. Template:

-- image/qoi tests: <what is covered>. Fixtures: tools/fixtures/qoi.py.
local T = require("@tests/T")
local Qoi = require("@formats/image/qoi")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/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().

4. Adding a format

  1. src/Formats/<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 / core/Huffman for entropy coding, Types constructors for the result.
  2. Shared code (a codec two formats need, a container) goes to codecs/ 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/Formats/Registry.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("@formats/<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("formats.a.b"); stdlib names come from formats._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.