#!/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"(?"): 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"(? [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"(?= 3 or not used or alias in free_names(" ".join( re.sub(r"(? 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