#!/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"(?"): 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