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.
319 lines
15 KiB
Python
319 lines
15 KiB
Python
#!/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.
|
|
# 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 = { ... }.
|
|
# 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().
|
|
# 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.
|
|
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))
|
|
|
|
CODEC_DOMAINS = {"compress", "entropy", "image", "audio", "video", "text", "font", "model"}
|
|
for f in files:
|
|
mod = mods[f]
|
|
parts = mod.split("/")
|
|
if parts[0] == "codecs" and (len(parts) < 3 or parts[1] not in CODEC_DOMAINS):
|
|
bad(f, 1, "LAYERS: codecs go in a domain folder codecs/<%s>/<Name> (%s)" % ("|".join(sorted(CODEC_DOMAINS)), mod))
|
|
|
|
# ---------------------------------------------------------------------------------------------------- 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(...))")
|
|
|
|
# ---------------------------------------------------------------------------------------------------- DUP
|
|
DUP_LINES = 12
|
|
TOKEN = re.compile(r'"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'|\[=*\[.*?\]=*\]|[A-Za-z_][A-Za-z0-9_]*|\d[\w.]*|\S')
|
|
FUNC = re.compile(r"^(\s*)(?:local\s+)?function\b")
|
|
bodies = {}
|
|
for f, lines in text.items():
|
|
for i, line in enumerate(lines):
|
|
m = FUNC.match(line)
|
|
if not m:
|
|
continue
|
|
end = re.compile("^" + re.escape(m.group(1)) + r"end\b")
|
|
j = i + 1
|
|
while j < len(lines) and not end.match(lines[j]):
|
|
j += 1
|
|
body = [code(x).strip() for x in lines[i + 1:j]]
|
|
body = [x for x in body if x]
|
|
if len(body) < DUP_LINES:
|
|
continue
|
|
key = " ".join(TOKEN.findall(" ".join(body)))
|
|
bodies.setdefault(key, []).append((f, i + 1, line.strip()))
|
|
for key, where in bodies.items():
|
|
files_ = {w[0] for w in where}
|
|
if len(files_) > 1:
|
|
first = where[0]
|
|
for f, ln, head in where[1:]:
|
|
if f != first[0]:
|
|
bad(f, ln, "DUP: `%s` repeats %s:%d (move it to a shared module)" % (head[:60], os.path.relpath(first[0], ROOT), first[1]))
|
|
|
|
print("\n".join(out))
|
|
sys.exit(1 if out else 0)
|