formats-luau foundation: build (darklua + token passes) for Roblox and LuaJIT, compat prelude, core, Types, host adapters, API + registry, lint, tests on both runtimes; absorb deflate (codecs/Deflate + new compressor) and png (image/png + new encoder)
This commit is contained in:
commit
cdcb5b0b77
226 files changed
+8409
No files matched your search
@@ -0,0 +1,279 @@
|
||||
#!/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.
|
||||
# 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().
|
||||
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))
|
||||
|
||||
# ---------------------------------------------------------------------------------------------------- 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(...))")
|
||||
|
||||
print("\n".join(out))
|
||||
sys.exit(1 if out else 0)
|
||||
Reference in new issue
Block a user