Files
rosetta/tools/sniff_extract.py
T
4DBug e05392ee8e api: lazy format detection (Sniffs.luau): F.detect loads no format module
tools/gen_registry.py now also writes src/Rosetta/Sniffs.luau: each format's sniff copied
(tools/sniff_extract.py) with the top-level locals, types and load-time loops it reaches;
requires outside core/ become proxies that require on first field access. 198 of 199
sniffs are copied (model/fbx reads Binary.MAGIC at load time: its module sniffs).
Registry entries gain sniff (0 copy, 1 copy reaching a codec / container, 2 module) and
variant (the module has variant(r)).

init.luau detect: the extension's formats first, then by sniff cost and registry order;
a sniff runs only while its cap (1, or LATE) could still win, ties to registry order, so
results equal the eager path. F.detect loads the winner only when it has variant().

tests/detect.luau: every copied sniff against its module's on samples of every fixture
module (tools/fixtures/detect.py), scores within 0..1, and F.detect against the eager
reference with no name, the right / wrong / unknown extension and per category.

Outside init / Registry / gen_registry: tools/fixtures.py (LAST generators run after
the others and rerun when their outputs change), tools/lint_rules.py (Sniffs is api
layer, skipped by DUP), docs/STYLE.md and docs/API.md notes, build/ regenerated.
2026-11-02 21:58:10 -06:00

199 lines
7.7 KiB
Python

#!/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