merge master
This commit is contained in:
commit
f9e2e6a455
18 files changed
+16515
-1468
No files matched your search
+6
-1
@@ -8,6 +8,7 @@
|
||||
# INPUTS = ["tests/fixtures/pngsuite", ...] # optional: files / dirs whose change triggers a rebuild
|
||||
# def generate(ctx): ... # ctx.emit("png_suite", value), ctx.nix("imagemagick", [...]), ...
|
||||
# A generator is skipped while all its outputs are newer than itself and its INPUTS (--force reruns it).
|
||||
# LAST = True runs it after the others; it also reruns when any other generator's output changed (it reads them)
|
||||
#
|
||||
# ctx.emit(name, value): writes tests/gen/<name>.luau returning value. Python values map to Luau: bytes -> string
|
||||
# literal (any bytes), str -> string literal, int / float / bool, list / tuple -> array, dict -> table (string keys
|
||||
@@ -123,12 +124,16 @@ def main():
|
||||
if "--list" in sys.argv:
|
||||
print("\n".join(names))
|
||||
return
|
||||
mods = {name: load(os.path.join(GENERATORS, name + ".py")) for name in names}
|
||||
names.sort(key=lambda n: bool(getattr(mods[n], "LAST", False)))
|
||||
for name in names:
|
||||
if args and not any(a in name for a in args):
|
||||
continue
|
||||
path = os.path.join(GENERATORS, name + ".py")
|
||||
mod = load(path)
|
||||
mod = mods[name]
|
||||
inputs = [path, os.path.abspath(__file__)] + [os.path.join(ROOT, p) for p in getattr(mod, "INPUTS", [])]
|
||||
if getattr(mod, "LAST", False):
|
||||
inputs += [os.path.join(stamps, n) for n in names if n != name and not getattr(mods[n], "LAST", False)]
|
||||
stamp = os.path.join(stamps, name)
|
||||
if not force and os.path.exists(stamp):
|
||||
outs = open(stamp).read().split("\n")
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
# Detection fixtures (tools/fixtures.py): samples of every other fixture module, for tests/detect.luau (lazy detection
|
||||
# against the eager reference). Runs after the other generators (LAST) and reads their tests/gen output.
|
||||
# tests/gen/detect_blobs_<1..4>.luau { { from = "<module>", data = <bytes> } }: up to PER_MODULE string literals of
|
||||
# 16 bytes or more per module, evenly spaced, cut to CUT bytes, without repeats
|
||||
import hashlib, os, re
|
||||
|
||||
LAST = True
|
||||
PER_MODULE = 6
|
||||
CUT = 16384
|
||||
PARTS = 4
|
||||
PART_BYTES = 5_000_000
|
||||
HEADER = "-- generated by tools/fixtures.py"
|
||||
LITERAL = re.compile(rb'"([^"]*)"')
|
||||
ESCAPE = re.compile(rb"\\x([0-9a-f]{2})")
|
||||
|
||||
|
||||
def decode(raw):
|
||||
return ESCAPE.sub(lambda m: bytes([int(m.group(1), 16)]), raw)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
names = sorted(f[:-5] for f in os.listdir(ctx.gen) if f.endswith(".luau") and not f.startswith("detect_"))
|
||||
seen, blobs = set(), []
|
||||
for name in names:
|
||||
with open(os.path.join(ctx.gen, name + ".luau"), "rb") as f:
|
||||
text = f.read()
|
||||
if not text.startswith(HEADER.encode()):
|
||||
continue
|
||||
lits = [m.span(1) for m in LITERAL.finditer(text) if m.end(1) - m.start(1) >= 16]
|
||||
lits = [(a, b) for a, b in lits if len(decode(text[a:min(b, a + 64)])) >= 16]
|
||||
if not lits:
|
||||
continue
|
||||
step = max(1, len(lits) / PER_MODULE)
|
||||
picks = sorted({int(i * step) for i in range(PER_MODULE)} & set(range(len(lits))))
|
||||
for i in picks:
|
||||
a, b = lits[i]
|
||||
data = decode(text[a:min(b, a + CUT * 4)])[:CUT]
|
||||
h = hashlib.sha1(data).digest()
|
||||
if h in seen:
|
||||
continue
|
||||
seen.add(h)
|
||||
blobs.append({"from": name, "data": data})
|
||||
parts, cur, size = [], [], 0
|
||||
for b in blobs:
|
||||
if size + len(b["data"]) > PART_BYTES and cur:
|
||||
parts.append(cur)
|
||||
cur, size = [], 0
|
||||
cur.append(b)
|
||||
size += len(b["data"])
|
||||
parts.append(cur)
|
||||
if len(parts) > PARTS:
|
||||
raise SystemExit("fixtures/detect: %d parts, raise PARTS (and the requires in tests/detect.luau)" % len(parts))
|
||||
while len(parts) < PARTS:
|
||||
parts.append([])
|
||||
for i, p in enumerate(parts, 1):
|
||||
ctx.emit("detect_blobs_%d" % i, p)
|
||||
+48
-1
@@ -3,6 +3,8 @@
|
||||
# src/Rosetta/<category>/<fmt>/init.luau and writes
|
||||
# src/Rosetta/Registry.luau a static list (Roblox has no dynamic require): each format's contract metadata, copied
|
||||
# from its init.luau, and a load() that requires the module on first use
|
||||
# src/Rosetta/Sniffs.luau each format's sniff, copied with what it reaches (tools/sniff_extract.py), so detection
|
||||
# runs without requiring the format modules
|
||||
# docs/FORMATS.md the capability matrix, from each contract's caps
|
||||
# README.md the format table (read / write) and the codec + container list, between the markers
|
||||
# <!-- formats:begin --> / <!-- formats:end --> and <!-- codecs:begin --> / <!-- codecs:end -->
|
||||
@@ -11,6 +13,9 @@
|
||||
# --check: exit 1 when any of them is out of date (tools/lint.sh runs this).
|
||||
import os, re, sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import sniff_extract
|
||||
|
||||
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",
|
||||
@@ -50,6 +55,9 @@ def scan():
|
||||
sys.exit("gen_registry: %s/%s/init.luau: missing contract fields %s" % (cat, fmt, ", ".join(missing)))
|
||||
c["path"] = cat + "/" + fmt
|
||||
c["folder_category"] = cat
|
||||
text = open(init).read()
|
||||
c["sniff_cost"], c["sniff_block"], self_name = sniff_extract.extract(text, c["path"])
|
||||
c["variant"] = sniff_extract.has_variant(text, self_name)
|
||||
formats.append(c)
|
||||
return formats
|
||||
|
||||
@@ -60,6 +68,8 @@ def registry(formats):
|
||||
"-- Registry: GENERATED by tools/gen_registry.py from the format folders - do not edit.",
|
||||
"-- One entry per format: the contract metadata (copied from its init.luau) and load(), which requires the format",
|
||||
"-- module on first use (a static require, as Roblox needs). Order: category, then name.",
|
||||
"-- sniff: where detection finds the format's sniff (tools/sniff_extract.py): 0 Sniffs.luau, 1 Sniffs.luau reaching a",
|
||||
"-- codec / container on first call, 2 the format module. variant: the module has variant(r).",
|
||||
"export type Entry = {",
|
||||
"\tname: string,",
|
||||
"\tcategory: string,",
|
||||
@@ -68,6 +78,8 @@ def registry(formats):
|
||||
"\tmime: { string },",
|
||||
"\tdeps: { string },",
|
||||
"\tcaps: { [string]: any },",
|
||||
"\tsniff: number,",
|
||||
"\tvariant: boolean?,",
|
||||
"\tload: () -> any,",
|
||||
"}",
|
||||
"",
|
||||
@@ -83,6 +95,8 @@ def registry(formats):
|
||||
"\t\tmime = %s," % c["mime"],
|
||||
"\t\tdeps = %s," % c["deps"],
|
||||
"\t\tcaps = %s," % c["caps"],
|
||||
"\t\tsniff = %d," % c["sniff_cost"],
|
||||
] + (["\t\tvariant = true,"] if c["variant"] else []) + [
|
||||
"\t\tload = function()",
|
||||
'\t\t\treturn require("@rosetta/%s")' % c["path"],
|
||||
"\t\tend,",
|
||||
@@ -92,6 +106,38 @@ def registry(formats):
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def sniffs(formats):
|
||||
out = [
|
||||
"--!strict",
|
||||
"--!optimize 2",
|
||||
"-- Sniffs: GENERATED by tools/gen_registry.py from the format folders - do not edit.",
|
||||
"-- Each format's sniff (format path -> sniff(r)), copied from its init.luau with the top-level locals and types it",
|
||||
"-- reaches (tools/sniff_extract.py), so detection requires no format module. Requires outside core/ are proxies that",
|
||||
"-- require on first use. Formats whose sniff needs their module (Registry sniff = 2) are not here.",
|
||||
"local S: { [string]: (any) -> number } = {}",
|
||||
"",
|
||||
"local function lazy(load: () -> any): any",
|
||||
"\tlocal proxy = {}",
|
||||
"\treturn setmetatable(proxy, {",
|
||||
"\t\t__index = function(_, k: any): any",
|
||||
"\t\t\tlocal m = load()",
|
||||
"\t\t\tsetmetatable(proxy, { __index = m })",
|
||||
"\t\t\treturn m[k]",
|
||||
"\t\tend,",
|
||||
"\t})",
|
||||
"end",
|
||||
"",
|
||||
]
|
||||
for c in formats:
|
||||
if c["sniff_block"] is None:
|
||||
continue
|
||||
out.append("do -- %s" % c["path"])
|
||||
out += c["sniff_block"]
|
||||
out += ["end", ""]
|
||||
out += ["return S", ""]
|
||||
return "\n".join(out)
|
||||
|
||||
|
||||
def caps_dict(lit):
|
||||
"""{ decode = true, depths = { 8 } } -> ordered [(key, text)] at the top level."""
|
||||
body = lit.strip()[1:-1]
|
||||
@@ -220,6 +266,7 @@ def main():
|
||||
readme_path = os.path.join(ROOT, "README.md")
|
||||
outputs = {
|
||||
os.path.join(SRC, "Registry.luau"): registry(formats),
|
||||
os.path.join(SRC, "Sniffs.luau"): sniffs(formats),
|
||||
os.path.join(ROOT, "docs", "FORMATS.md"): formats_md(formats),
|
||||
readme_path: readme(formats, readme_path),
|
||||
}
|
||||
@@ -239,7 +286,7 @@ def main():
|
||||
sys.exit(1)
|
||||
print("gen_registry: up to date (%d formats)" % len(formats))
|
||||
else:
|
||||
print("gen_registry: %d formats -> src/Rosetta/Registry.luau, docs/FORMATS.md, README.md%s" % (
|
||||
print("gen_registry: %d formats -> src/Rosetta/Registry.luau, Sniffs.luau, docs/FORMATS.md, README.md%s" % (
|
||||
len(formats), "" if stale else " (unchanged)"))
|
||||
|
||||
|
||||
|
||||
+6
-3
@@ -9,7 +9,7 @@
|
||||
# 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
|
||||
# < ops < api (init, Registry, Sniffs). 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 = { ... }.
|
||||
@@ -19,7 +19,8 @@
|
||||
# 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.
|
||||
# shared module (core / codecs / containers) and call it from both. Sniffs.luau (generated copies of the
|
||||
# formats' sniffs) is not compared.
|
||||
# DOCS docs/STYLE.md's layer block names every codec (codecs/<domain>/<Name>), container and core module in the
|
||||
# tree; README.md's generated format table and codec list (<!-- formats:begin --> ... <!-- codecs:end -->)
|
||||
# match tools/gen_registry.py's output; README.md links every docs/guide page, docs/API.md and
|
||||
@@ -69,7 +70,7 @@ def resolve(target):
|
||||
def layer(mod):
|
||||
"""(rank, group) of a module path"""
|
||||
top = mod.split("/")[0] if mod else ""
|
||||
if mod in ("", "Registry"):
|
||||
if mod in ("", "Registry", "Sniffs"):
|
||||
return 6, "api"
|
||||
if top == "core":
|
||||
return 0, "core"
|
||||
@@ -296,6 +297,8 @@ TOKEN = re.compile(r'"(?:[^"\\]|\\.)*"|\'(?:[^\'\\]|\\.)*\'|\[=*\[.*?\]=*\]|[A-Z
|
||||
FUNC = re.compile(r"^(\s*)(?:local\s+)?function\b")
|
||||
bodies = {}
|
||||
for f, lines in text.items():
|
||||
if mods[f] == "Sniffs":
|
||||
continue
|
||||
for i, line in enumerate(lines):
|
||||
m = FUNC.match(line)
|
||||
if not m:
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
#!/usr/bin/env python3
|
||||
# Sniff extraction for tools/gen_registry.py: copies each format's sniff function out of its init.luau, with the
|
||||
# top-level locals, types and statements it reaches, so src/Rosetta/Sniffs.luau can sniff without requiring the
|
||||
# format module. A format whose sniff reaches its own module table (or a forward-declared local) is not copied: the api
|
||||
# loads the module to sniff it. Requires the copy reaches: core/* as they are; any other module through a proxy that
|
||||
# requires it on first field access (sniff time).
|
||||
# cost 0: the copy needs only core/*; 1: it reaches a proxied module; 2: not copied (the module sniffs).
|
||||
import re
|
||||
|
||||
KEYWORDS = set("and break continue do else elseif end false for function if in local nil not or repeat return then "
|
||||
"true until while type export typeof".split())
|
||||
NAME = r"[A-Za-z_]\w*"
|
||||
|
||||
|
||||
def clean(text):
|
||||
"""text with string, comment and long-bracket contents blanked (newlines kept), same length"""
|
||||
out, i, n = [], 0, len(text)
|
||||
while i < n:
|
||||
c = text[i]
|
||||
if c == "-" and text.startswith("--", i):
|
||||
m = re.match(r"--\[(=*)\[", text[i:])
|
||||
if m:
|
||||
j = text.find("]" + m.group(1) + "]", i + len(m.group(0)))
|
||||
j = n if j < 0 else j + len(m.group(1)) + 2
|
||||
else:
|
||||
j = text.find("\n", i)
|
||||
j = n if j < 0 else j
|
||||
out.append(re.sub(r"[^\n]", " ", text[i:j]))
|
||||
i = j
|
||||
elif c == "[" and re.match(r"\[(=*)\[", text[i:]):
|
||||
m = re.match(r"\[(=*)\[", text[i:])
|
||||
j = text.find("]" + m.group(1) + "]", i + len(m.group(0)))
|
||||
j = n if j < 0 else j + len(m.group(1)) + 2
|
||||
out.append('"' + re.sub(r"[^\n]", " ", text[i + 1:j - 1]) + '"')
|
||||
i = j
|
||||
elif c in "\"'":
|
||||
j = i + 1
|
||||
while j < n and text[j] != c and text[j] != "\n":
|
||||
j += 2 if text[j] == "\\" else 1
|
||||
j = min(j + 1, n)
|
||||
out.append(c + " " * (j - i - 2) + c if j - i >= 2 else text[i:j])
|
||||
i = j
|
||||
else:
|
||||
out.append(c)
|
||||
i += 1
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def split_top(s):
|
||||
"""split s on commas outside brackets"""
|
||||
parts, depth, cur = [], 0, ""
|
||||
for ch in s:
|
||||
if ch in "({[<":
|
||||
depth += 1
|
||||
elif ch in ")}]>":
|
||||
depth -= 1
|
||||
if ch == "," and depth == 0:
|
||||
parts.append(cur)
|
||||
cur = ""
|
||||
else:
|
||||
cur += ch
|
||||
parts.append(cur)
|
||||
return parts
|
||||
|
||||
|
||||
def statements(text):
|
||||
"""[(first line, last line, cleaned text)] of the top-level statements (0-based inclusive line numbers)"""
|
||||
lines = text.split("\n")
|
||||
cl = clean(text).split("\n")
|
||||
starts = [i for i, l in enumerate(cl) if l[:1] not in ("", " ", "\t") and not re.match(r"(end|until)\b|[}\])]", l)]
|
||||
out = []
|
||||
for k, s in enumerate(starts):
|
||||
e = (starts[k + 1] if k + 1 < len(starts) else len(lines)) - 1
|
||||
while e > s and cl[e].strip() == "":
|
||||
e -= 1
|
||||
out.append((s, e, "\n".join(cl[s:e + 1])))
|
||||
return out
|
||||
|
||||
|
||||
def free_names(code):
|
||||
"""identifiers read by code that are not field / method names (an over-approximation: locals are included)"""
|
||||
return {m.group(1) for m in re.finditer(r"(?<![.:\w])\s*(" + NAME + r")", code)} - KEYWORDS
|
||||
|
||||
|
||||
def defines(st):
|
||||
"""(names, kind) a top-level statement declares: kind 'local', 'func', 'type', 'forward' or None"""
|
||||
m = re.match(r"local\s+function\s+(" + NAME + ")", st)
|
||||
if m:
|
||||
return [m.group(1)], "func"
|
||||
m = re.match(r"(?:export\s+)?type\s+(" + NAME + ")", st)
|
||||
if m:
|
||||
return [m.group(1)], "type"
|
||||
m = re.match(r"local\s+(.*)", st, re.S)
|
||||
if m:
|
||||
rest = m.group(1)
|
||||
depth, cut = 0, None
|
||||
for i, ch in enumerate(rest):
|
||||
if ch in "({[":
|
||||
depth += 1
|
||||
elif ch in ")}]":
|
||||
depth -= 1
|
||||
elif ch == "=" and depth == 0 and rest[i + 1:i + 2] != "=" and rest[i - 1:i] not in ("=", "~", "<", ">"):
|
||||
cut = i
|
||||
break
|
||||
head = rest if cut is None else rest[:cut]
|
||||
names = [p.split(":")[0].strip() for p in split_top(head.split("\n")[0] if cut is None else head)]
|
||||
return [n for n in names if re.fullmatch(NAME, n)], ("forward" if cut is None else "local")
|
||||
return [], None
|
||||
|
||||
|
||||
REQUIRE = re.compile(r'^local\s+(' + NAME + r')\s*=\s*require\("@rosetta/([\w/]+)"\)\s*$')
|
||||
|
||||
|
||||
def extract(text, path):
|
||||
"""(cost, block lines or None, module table name) for one format's init.luau"""
|
||||
lines = text.split("\n")
|
||||
sts = statements(text)
|
||||
sniff_i, self_name = None, None
|
||||
for i, (s, e, st) in enumerate(sts):
|
||||
m = re.match(r"function\s+(" + NAME + r")\.sniff\s*\(", st)
|
||||
if m:
|
||||
sniff_i, self_name = i, m.group(1)
|
||||
if sniff_i is None:
|
||||
return 2, None, None
|
||||
defs = [] # (statement index, name, kind)
|
||||
for i, (s, e, st) in enumerate(sts):
|
||||
names, kind = defines(st)
|
||||
for n in names:
|
||||
defs.append((i, n, kind))
|
||||
def_names = {n for _, n, _ in defs}
|
||||
# top-level statements that are not declarations: assignments, loops (a table filled at load time)
|
||||
others = [i for i, (s, e, st) in enumerate(sts) if defines(st)[1] is None and i != sniff_i]
|
||||
|
||||
def resolve(name, before):
|
||||
best = None
|
||||
for i, n, kind in defs:
|
||||
if n == name and i < before:
|
||||
best = (i, kind)
|
||||
return best
|
||||
|
||||
include, lazy, todo, bad = set(), {}, [sniff_i], False
|
||||
reached = set()
|
||||
while todo:
|
||||
i = todo.pop()
|
||||
if i in include:
|
||||
continue
|
||||
include.add(i)
|
||||
st = sts[i][2]
|
||||
body = st
|
||||
if i == sniff_i:
|
||||
body = st[st.index("("):]
|
||||
for n in free_names(body):
|
||||
if n == self_name:
|
||||
bad = True
|
||||
continue
|
||||
r = resolve(n, i)
|
||||
if r is None:
|
||||
continue
|
||||
j, kind = r
|
||||
if kind == "forward":
|
||||
bad = True
|
||||
continue
|
||||
reached.add(n)
|
||||
req = REQUIRE.match(lines[sts[j][0]]) if sts[j][0] == sts[j][1] else None
|
||||
if req and not req.group(2).startswith("core/"):
|
||||
lazy[j] = (req.group(1), req.group(2))
|
||||
continue
|
||||
todo.append(j)
|
||||
# load-time statements that touch a reached local (a lookup table filled by a loop)
|
||||
for k in others:
|
||||
if k not in include and re.match(r"(function\s+)?" + re.escape(self_name) + r"\b|return\b", sts[k][2]) is None:
|
||||
if free_names(sts[k][2]) & reached:
|
||||
todo.append(k)
|
||||
if bad:
|
||||
return 2, None, self_name
|
||||
# a non-function statement that reads a proxied module runs at load time: the proxy would load it at once
|
||||
for i in include:
|
||||
if i != sniff_i and defines(sts[i][2])[1] not in ("func", "type"):
|
||||
if free_names(sts[i][2]) & {a for a, _ in lazy.values()}:
|
||||
return 2, None, self_name
|
||||
block = []
|
||||
for i in sorted(set(include) | set(lazy)):
|
||||
s, e, st = sts[i]
|
||||
if i in lazy:
|
||||
alias, mod = lazy[i]
|
||||
block.append('local %s = lazy(function()\n\treturn require("@rosetta/%s")\nend)' % (alias, mod))
|
||||
elif i == sniff_i:
|
||||
src = "\n".join(lines[s:e + 1])
|
||||
src = re.sub(r"^function\s+" + re.escape(self_name) + r"\.sniff\s*\(", 'S["%s"] = function(' % path, src)
|
||||
block.append(src)
|
||||
else:
|
||||
src = "\n".join(lines[s:e + 1])
|
||||
block.append(re.sub(r"^export\s+type\b", "type", src))
|
||||
return (1 if lazy else 0), block, self_name
|
||||
|
||||
|
||||
def has_variant(text, self_name):
|
||||
return self_name is not None and re.search(r"^function\s+" + re.escape(self_name) + r"\.variant\s*\(", text, re.M) is not None
|
||||
Reference in new issue
Block a user