#!/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 # "-- : ..." (core/Bytes, image/png, image/png/Decode, Rosetta for the root, ...); every test # starts with a comment. # REQUIRE requires are string literals "@rosetta/" (tests / tools may also use "@tests/") 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 (/) # < 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// (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 .sniff, at least # one of decode / encode / open, the section markers in order, and ends with return ; it has a test # tests//.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. # DOCS the module lists in README.md's Layout block and docs/STYLE.md's layer block name every codec # (codecs//), container and core module in the tree; README.md's format counts # ("images (25)", ...) match the registry (docs/FORMATS.md); docs/guide/README.md links every guide page. import os, re, sys 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", "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/Rosetta/image/png/init.luau -> image/png; src/Rosetta/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'"@rosetta(?:/([\w/]+))?"', arg) if not mm: bad(f, i, "REQUIRE: requires in src must be require(\"@rosetta/\"), got require(%s)" % arg) continue target = mm.group(1) or "" if not resolve(target): bad(f, i, "REQUIRE: no module @rosetta/%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 "Rosetta" 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'"@(rosetta|tests)(/[\w/]+)?"', m.group(1).strip()): bad(p, i, "REQUIRE: tests require \"@rosetta/...\" 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 "Rosetta", 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>/ (%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 = {` 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])) # ---------------------------------------------------------------------------------------------------- DOCS def module_names(rel): """the module names directly under src/Rosetta/: Foo.luau and Foo/ (a folder module)""" d = os.path.join(SRC, rel) names = set() for n in os.listdir(d): if n.endswith(".luau"): names.add(n[:-5]) elif os.path.isdir(os.path.join(d, n)): names.add(n) return names def layout_block(path): """(first line, text) of the first fenced block of a markdown file that starts with src/Rosetta/""" lines = open(path, encoding="utf-8").read().split("\n") for i, line in enumerate(lines): if line.startswith("```") and i + 1 < len(lines) and lines[i + 1].startswith("src/Rosetta/"): j = i + 1 while j < len(lines) and not lines[j].startswith("```"): j += 1 return i + 1, "\n".join(lines[i + 1:j]) return 1, "" modules = [] for dom in sorted(os.listdir(os.path.join(SRC, "codecs"))): modules += ["codecs/%s/%s" % (dom, n) for n in sorted(module_names("codecs/" + dom))] modules += ["containers/" + n for n in sorted(module_names("containers"))] modules += ["core/" + n for n in sorted(module_names("core"))] for doc in ("README.md", os.path.join("docs", "STYLE.md")): path = os.path.join(ROOT, doc) ln, block = layout_block(path) if not block: bad(path, 1, "DOCS: no layout block (a ``` block starting with src/Rosetta/)") continue for m in modules: if not re.search(r"(? 3 and cells[1] in LABELS: counts[cells[1]] = counts.get(cells[1], 0) + 1 readme = os.path.join(ROOT, "README.md") rtext = open(readme, encoding="utf-8").read() m = re.search(r"(\d+) formats:", rtext) if not m or int(m.group(1)) != sum(counts.values()): bad(readme, 1, "DOCS: README.md should say \"%d formats:\" (docs/FORMATS.md)" % sum(counts.values())) for cat, label in LABELS.items(): m = re.search(r"\s+".join(map(re.escape, label.split())) + r"\s+\((\d+)\)", rtext) if not m or int(m.group(1)) != counts.get(cat, 0): bad(readme, 1, "DOCS: README.md should say \"%s (%d)\" (docs/FORMATS.md)" % (label, counts.get(cat, 0))) guide = os.path.join(ROOT, "docs", "guide") gindex = open(os.path.join(guide, "README.md"), encoding="utf-8").read() for n in sorted(os.listdir(guide)): if n.endswith(".md") and n != "README.md" and "](%s" % n not in gindex: bad(os.path.join(guide, "README.md"), 1, "DOCS: the guide index does not link %s" % n) print("\n".join(out)) sys.exit(1 if out else 0)