Files
rosetta/tools/sniff_extract.py

390 lines
15 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).
# A field the copy reads from a proxied module (Aac.adts, Zstd.MAGIC) is copied too when it reaches only core/*,
# literals and other such fields (of that module or of modules it requires; FIELD_MAX bytes at most per module): once,
# at the top of Sniffs.luau, onto the module's shared proxy, which then loads its module only for the fields left (a
# decoder). So detection runs Sniffs alone (build/Rosetta.rbxm: one small chunk), not the codecs behind the proxies.
import os, re
SRC = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "src", "Rosetta")
FIELD_MAX = 16384
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 or table / type keys ({ name = ..., name: T }; an
over-approximation: locals are included)"""
code = re.sub(r"([{,]\s*)" + NAME + r"(\s*(=(?!=)|:\s))", r"\1\2", code)
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
left = {}
for j, (alias, mod) in lazy.items():
left[j] = share(mod, used_fields(alias, [sts[i][2] for i in include])) # the fields that load mod
USED.add(mod)
# 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"):
for j, (alias, _) in lazy.items():
if alias in free_names(sts[i][2]) and (left[j] or not re.search(
r"(?<![.:\w])" + re.escape(alias) + r"\s*\.", sts[i][2])):
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 = %s" % (alias, shared_name(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 any(reaches_left(m) for _, m in lazy.values()) else 0), block, self_name
# ------------------------------------------------------------------------------------------------ shared field copies
# SHARED: module -> [fields the sniffs read, fields left to the proxy]; one table per module at the top of Sniffs.luau
# (shared_lines), a lazy proxy when a field is left, with the copied fields set on it.
SHARED = {}
USED = set() # the modules the sniffs read (emit also adds what their copies read)
def shared_name(mod):
return "P_" + re.sub(r"\W", "_", mod)
def used_fields(alias, texts):
pat = re.compile(r"(?<![.:\w])" + re.escape(alias) + r"\s*\.\s*(" + NAME + ")")
return {f for t in texts for f in pat.findall(t)}
def module_file(mod):
for p in (os.path.join(SRC, mod + ".luau"), os.path.join(SRC, mod, "init.luau")):
if os.path.isfile(p):
return p
return None
def field_statements(mod, fields, depth):
"""(lines, self name, required modules) of the top-level statements module mod needs for fields (function M.f /
M.f = ..., with the locals, types, M fields, load-time statements and fields of required modules they reach), or
None"""
path = module_file(mod)
if path is None:
return None
with open(path) as f:
text = f.read()
lines = text.split("\n")
sts = statements(text)
self_name = None
for s, e, st in sts:
m = re.match(r"return\s+(" + NAME + r")\s*$", st)
if m:
self_name = m.group(1)
if self_name is None:
return None
field_at = {}
for i, (s, e, st) in enumerate(sts):
m = re.match(r"(?:function\s+)?" + re.escape(self_name) + r"\s*\.\s*(" + NAME + r")\s*(\(|=(?!=))", st)
if m and m.group(1) not in field_at:
field_at[m.group(1)] = i
defs = []
for i, (s, e, st) in enumerate(sts):
names, kind = defines(st)
for n in names:
defs.append((i, n, kind))
others = [i for i, (s, e, st) in enumerate(sts) if defines(st)[1] is None and i not in field_at.values()
and not re.match(r"return\b", st)]
def resolve(name, before):
best = None
for i, n, kind in defs:
if n == name and i < before:
best = (i, kind)
return best
include, reqs, todo, reached, got = set(), {}, [], set(), set()
for f in fields:
if f not in field_at:
return None
todo.append(field_at[f])
got.add(f)
while todo:
while todo:
i = todo.pop()
if i in include:
continue
include.add(i)
st = sts[i][2]
for f in used_fields(self_name, [st]):
if f in field_at:
got.add(f)
todo.append(field_at[f])
for n in free_names(st):
if n == self_name:
continue
r = resolve(n, i)
if r is None:
continue
j, kind = r
if kind == "forward":
return None
if kind == "local" and re.search(r"^[ \t]*" + re.escape(n) + r"\s*=(?!=)", text, re.M):
return None # module state (a cache): a copy would hold a second one
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/"):
reqs[j] = req.group(1), req.group(2)
continue
todo.append(j)
# load-time statements that fill a reached local or field (a table built by a loop)
for k in others:
if k not in include and (free_names(sts[k][2]) & reached or used_fields(self_name, [sts[k][2]]) & got):
todo.append(k)
out, deps = [], []
for i in sorted(include | set(reqs)):
s, e, st = sts[i]
if i in reqs:
alias, sub = reqs[i]
used = used_fields(alias, [sts[k][2] for k in include])
if depth >= 3 or not used or alias in free_names(" ".join(
re.sub(r"(?<![.:\w])" + re.escape(alias) + r"\s*\.\s*" + NAME, "", sts[k][2]) for k in include)):
return None # the module table itself is used, not only its fields
share(sub, used, depth + 1) # a field left there loads sub when the copy reaches it
deps.append(sub)
out.append("local %s = %s" % (alias, shared_name(sub)))
else:
out.append(re.sub(r"^export\s+type\b", "type", "\n".join(lines[s:e + 1])))
if sum(len(x) + 1 for x in out) > FIELD_MAX:
return None
return out, self_name, deps
def share(mod, fields, depth=0):
"""registers fields of mod for Sniffs.luau; -> the fields left to the proxy"""
e = SHARED.setdefault(mod, [set(), set()])
new = set(fields) - e[0] - e[1]
if new:
if field_statements(mod, sorted(new | e[0]), depth) is not None:
e[0] |= new
else:
for f in sorted(new): # each field alone: some may copy
if field_statements(mod, sorted(e[0] | {f}), depth) is not None:
e[0].add(f)
else:
e[1].add(f)
return set(fields) & e[1]
def reaches_left(mod, seen=None):
"""a sniff reading mod may load a module (a field left to a proxy, there or in what the copies read)"""
seen = set() if seen is None else seen
if mod in seen:
return False
seen.add(mod)
copied, left = SHARED[mod]
got = field_statements(mod, sorted(copied), 0) if copied else None
return bool(left) or (got is not None and any(reaches_left(d, seen) for d in got[2]))
def shared_lines():
"""the top of Sniffs.luau: the shared proxies / copies, each after the modules its copies read"""
out, done = [], set()
def emit(mod):
if mod in done:
return
done.add(mod)
copied, left = SHARED[mod]
got = field_statements(mod, sorted(copied), 0) if copied else ([], None, [])
body, self_name, deps = got
for d in deps:
emit(d)
name = shared_name(mod)
if left:
out.append('local %s = lazy(function()\n\treturn require("@rosetta/%s")\nend)' % (name, mod))
else:
out.append("local %s: any = {}" % name)
if copied:
out.append("do -- %s: %s" % (mod, ", ".join(sorted(copied))))
out.append("local %s = {}" % self_name)
out.extend(body)
out.extend("%s.%s = %s.%s" % (name, f, self_name, f) for f in sorted(copied))
out.append("end")
out.append("")
for mod in sorted(USED):
emit(mod)
return out
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