#!/usr/bin/env python3 # Build (python3 -I tools/build.py [roblox|luajit ...]): the two outputs of the one Luau source tree. # # The shipped files are the bundles build/Rosetta.luau (roblox, one module, no native code), build/Rosetta.rbxm / # .rbxmx (roblox, native, chunked) and build/rosetta.lua (luajit), written by tools/bundle.py after each target # (committed). The multi-file trees below are internal (gitignored), for the tests: # build/_modules/roblox/Rosetta/... darklua convert_require (luau aliases -> Roblox instance paths). Types, --!native # and @native are kept. # build/_modules/luajit/rosetta/... plain Lua 5.1 for LuaJIT / LÖVE: darklua strips types, attributes (@native) and # the Luau-only syntax, then the token passes below; requires become # require("rosetta.a.b"). tools/bundle.py builds build/rosetta.lua from it. # build/_modules/luajit/tools/... tools/*.luau (bench), built the same way. # build/_modules/luajit/tests/... the tests, built the same way (require("@tests/T") -> require("tests.T")); # tests/gen fixture modules are copied as they are (plain string literals; darklua # is slow on them). # # Load the LuaJIT tree with package.path = "build/_modules/luajit/?.lua;build/_modules/luajit/?/init.lua;" .. # package.path, then local F = require("rosetta"). # # What darklua 0.19 cannot do, done here as token-level passes (lexer from imgui-luau tools/minify.py): # 1. Generalized iteration (`for k, v in t do`): darklua has no rule for it. Every generic for whose iterator # expression does not start with pairs / ipairs / next becomes `for k, v in __iter(expr) do` (compat's __iter: # functions pass through with their state, arrays use ipairs, other tables next). # 2. Luau stdlib names: each module gets, on its first line (line numbers stay the same), only the locals it uses of # buffer, bit32, utf8, typeof, type, __iter from rosetta._compat (LuaJIT has a 60-upvalue limit per function). # 3. If-expressions: darklua lowers `if c then a else b` to `(c and {a} or {b})[1]`, a table per evaluation. When # `a` is provably not nil/false (a number or string literal, `#x`, or an arithmetic / concatenation expression # at its top level) it becomes `(c and a or b)`. # 4. Requires: `require("@rosetta/x/y")` -> `require("rosetta.x.y")`, `require("@tests/x")` -> `require("tests.x")`, # done on the source before darklua (string literals only; computed requires are not allowed in the library). import json, os, re, shutil, subprocess, sys, tempfile ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SRC = os.path.join(ROOT, "src", "Rosetta") TESTS = os.path.join(ROOT, "tests") BUILD = os.path.join(ROOT, "build") MODULES = os.path.join(BUILD, "_modules") # darklua 0.19: $DARKLUA, else on PATH, else through nix DARKLUA = os.environ.get("DARKLUA", "").split() or (["darklua"] if shutil.which("darklua") else ["nix", "shell", "nixpkgs#darklua", "-c", "darklua"]) LUAJIT_RULES = [ "remove_types", "remove_attribute", "remove_compound_assignment", "remove_continue", "remove_if_expression", "remove_interpolated_string", "remove_floor_division", "convert_luau_number", ] ROBLOX_RULES = [ {"rule": "convert_require", "current": {"name": "luau"}, "target": {"name": "roblox", "indexing_style": "property"}}, ] COMPAT_NAMES = ["buffer", "bit32", "utf8", "typeof", "type", "__iter"] # ------------------------------------------------------------------------------------------------ lexer TOKEN = re.compile(r""" (?P[ \t\r\n\f\v]+) | (?P--\[(?P=*)\[.*?\](?P=ceq)\]) | (?P--[^\n]*) | (?P\[(?P=*)\[.*?\](?P=seq)\]) | (?P"(?:\\.|\\\n|[^"\\\n])*"|'(?:\\.|\\\n|[^'\\\n])*'|`(?:\\.|\\\n|[^`\\])*`) | (?P0[xX][0-9a-fA-F_]*(?:\.[0-9a-fA-F_]*)?(?:[pP][+-]?\d+)?|0[bB][01_]+|(?:\d[\d_]*(?:\.[\d_]*)?|\.\d[\d_]*)(?:[eE][+-]?\d+)?) | (?P@?[A-Za-z_]\w*) | (?P\.\.\.|\.\.=|//=|\.\.|==|~=|<=|>=|//|::|->|[-+*/%^]=|.) """, re.S | re.X) def lex(src): """[(kind, text, start, end)] of the significant tokens (whitespace and comments dropped).""" out, pos = [], 0 while pos < len(src): m = TOKEN.match(src, pos) kind = m.lastgroup if kind in ("ceq", "seq"): kind = "lcom" if m.group(0).startswith("--") else "lstr" if kind not in ("ws", "lcom", "com"): out.append(("str" if kind == "lstr" else kind, m.group(0), m.start(), m.end())) pos = m.end() return out def apply(src, edits): """edits: [(start, end, text)], non-overlapping.""" for s, e, t in sorted(edits, reverse=True): src = src[:s] + t + src[e:] return src OPEN = {"(": ")", "[": "]", "{": "}"} BLOCK_OPEN = {"function", "do", "then", "repeat"} # each closes with `end` (repeat with `until`) def match_close(toks, i): """index of the bracket closing toks[i] ( ( [ { ).""" depth = 0 for j in range(i, len(toks)): t = toks[j][1] if toks[j][0] == "op" and t in OPEN: depth += 1 elif toks[j][0] == "op" and t in (")", "]", "}"): depth -= 1 if depth == 0: return j return -1 # ------------------------------------------------------------------------------------------------ pass 1: __iter def pass_iter(src): toks = lex(src) edits = [] for i, (k, t, s, e) in enumerate(toks): if k != "name" or t != "for": continue # find `in` or `=` at depth 0 j = i + 1 while j < len(toks) and not (toks[j][0] == "name" and toks[j][1] == "in") and toks[j][1] != "=": j += 1 if j >= len(toks) or toks[j][1] == "=": continue first = j + 1 # the expression runs to the `do` at bracket depth 0 and function depth 0 depth, fdepth, comma, q = 0, 0, False, first while q < len(toks): qk, qt = toks[q][0], toks[q][1] if qk == "op" and qt in OPEN: depth += 1 elif qk == "op" and qt in (")", "]", "}"): depth -= 1 elif qk == "name" and qt == "function": fdepth += 1 elif qk == "name" and qt == "end" and fdepth > 0: fdepth -= 1 elif qk == "name" and qt == "do" and depth == 0 and fdepth == 0: break elif qk == "op" and qt == "," and depth == 0 and fdepth == 0: comma = True q += 1 if q >= len(toks) or comma: continue if toks[first][0] == "name" and toks[first][1] in ("pairs", "ipairs", "next"): continue edits.append((toks[first][2], toks[first][2], "__iter(")) edits.append((toks[q - 1][3], toks[q - 1][3], ")")) return apply(src, edits) # ------------------------------------------------------------------------------------------------ pass 0: elseif # darklua 0.19's remove_if_expression nests the elseif branches of an if-expression in reverse order (it folds them # front to back): `if a then 1 elseif b then 2 elseif c then 3 else 4` becomes `a and 1 or (c and 3 or (b and 2 or 4))`. # Before darklua, every `elseif` of an if-expression becomes `else if` (a nested if-expression, same meaning), so # darklua only ever sees single-branch if-expressions. Statement ifs are told apart from expression ifs by the token # before `if` and a stack of open constructs (blocks close with end / until; an expression if closes at its else). EXPR_PREV = {"=", "(", ",", "{", "[", "return", "in", "and", "or", "not", "..", "+", "-", "*", "/", "//", "%", "^", "#", "==", "~=", "<", ">", "<=", ">=", "+=", "-=", "*=", "/=", "//=", "%=", "^=", "..=", "if", "elseif", "while", "until"} def pass_elseif(src): toks = lex(src) edits = [] stack = [] # "block" (function / do: end), "repeat" (until), "sif" (statement if: end), "eif" (expression if) prev, prev_else_eif, prev_then_eif = None, False, False for k, t, s, e in toks: kw = t if k == "name" else (t if k == "op" else None) else_eif = then_eif = False if kw == "if": expr = prev in EXPR_PREV or (prev == "then" and prev_then_eif) or (prev == "else" and prev_else_eif) stack.append("eif" if expr else "sif") elif kw == "then": then_eif = bool(stack) and stack[-1] == "eif" elif kw == "elseif": if stack and stack[-1] == "eif": edits.append((s, e, "else if")) # the old expression closes at this else; the new nested one is still an expression if then_eif = False elif kw == "else": if stack and stack[-1] == "eif": stack.pop() else_eif = True elif kw in ("function", "do"): stack.append("block") elif kw == "repeat": stack.append("repeat") elif kw == "end" or kw == "until": while stack and stack[-1] == "eif": # malformed input; keep going stack.pop() if stack: stack.pop() prev = t if k in ("name", "op") else k prev_else_eif, prev_then_eif = else_eif, then_eif return apply(src, edits) # ------------------------------------------------------------------------------------------------ pass 3: if-expressions ARITH = {"+", "-", "*", "/", "%", "^", ".."} NOT_SAFE = {"and", "or", "not", "==", "~=", "<", ">", "<=", ">="} def safe_truthy(toks): """True when the expression toks always yields a number or a string (never nil / false).""" if not toks: return False if len(toks) == 1: return toks[0][0] in ("num", "str") depth, arith = 0, False for idx, (k, t, _, _) in enumerate(toks): if k == "op" and t in OPEN: depth += 1 elif k == "op" and t in (")", "]", "}"): depth -= 1 elif depth == 0: if t in NOT_SAFE or t == "function": return False if k == "op" and t in ARITH and idx > 0: arith = True if toks[0][1] == "#" and not arith: # `#x` alone; `#x .. y` etc are covered by arith return all(tk[1] not in NOT_SAFE for tk in toks) if toks[0][1] == "(" and match_close(toks, 0) == len(toks) - 1: return safe_truthy(toks[1:-1]) return arith def pass_ifexpr(src): while True: toks = lex(src) edits = None # ( C and { A } or { B } ) [ 1 ] for i in range(len(toks)): if toks[i][1] != "(" or toks[i][0] != "op": continue close = match_close(toks, i) if close < 0 or close + 3 >= len(toks): continue if [t[1] for t in toks[close + 1:close + 4]] != ["[", "1", "]"]: continue # find `and {` at depth 1 depth, a_open = 0, -1 for j in range(i, close): t = toks[j][1] if toks[j][0] == "op" and t in OPEN: depth += 1 elif toks[j][0] == "op" and t in (")", "]", "}"): depth -= 1 elif depth == 1 and toks[j][0] == "name" and t == "and" and toks[j + 1][1] == "{": a_open = j + 1 if a_open < 0: continue a_close = match_close(toks, a_open) if a_close + 2 > close or toks[a_close + 1][1] != "or" or toks[a_close + 2][1] != "{": continue b_open = a_close + 2 b_close = match_close(toks, b_open) if b_close != close - 1: continue a = toks[a_open + 1:a_close] b = toks[b_open + 1:b_close] if not safe_truthy(a) or any(t[1] == "," for t in a) or any(t[1] == "," for t in b): continue # rewrite: braces -> parentheses (a and b stay whole expressions), drop the [1] edits = [ (toks[a_open][2], toks[a_open][3], "("), (toks[a_close][2], toks[a_close][3], ")"), (toks[b_open][2], toks[b_open][3], "("), (toks[b_close][2], toks[b_close][3], ")"), (toks[close + 1][2], toks[close + 3][3], ""), ] break if not edits: return src src = apply(src, edits) # ------------------------------------------------------------------------------------------------ pass 2: compat header def pass_header(src): used = {t for k, t, _, _ in lex(src) if k == "name"} names = [n for n in COMPAT_NAMES if n in used] if not names: return src head = 'local __compat = require("rosetta._compat") local %s = %s ' % ( ", ".join(names), ", ".join("__compat." + n for n in names)) return head + src # ------------------------------------------------------------------------------------------------ requires REQ = re.compile(r'require\(\s*"@(rosetta|tests)((?:/[\w.]+)*)"\s*\)') def luajit_requires(src): def sub(m): mod = m.group(1) + m.group(2).replace("/", ".") return 'require("%s")' % mod return REQ.sub(sub, src) # ------------------------------------------------------------------------------------------------ darklua def darklua(rules, src_dir, out_dir, cwd): with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False) as f: json.dump({"generator": "retain_lines", "rules": rules}, f) cfg = f.name try: r = subprocess.run(DARKLUA + ["process", "-c", cfg, src_dir, out_dir], cwd=cwd, capture_output=True, text=True) if r.returncode != 0: sys.stderr.write(r.stdout + r.stderr) sys.exit("build: darklua failed") finally: os.unlink(cfg) def files(root, ext=".luau"): for d, _, fs in os.walk(root): for f in sorted(fs): if f.endswith(ext): yield os.path.join(d, f) # Module names that are also properties of a ModuleScript: `script.Parent.Video.Source` reads the Video ModuleScript's # Source property (its code) instead of the child module named Source, so those path parts become :FindFirstChild. RESERVED_CHILD_NAMES = {"Source", "Name", "ClassName", "Archivable", "LinkedSource", "Capabilities", "Sandboxed", "Tags"} REQUIRE_PATH = re.compile(r"require\((script(?:\.Parent)*)((?:\.[A-Za-z_]\w*)+)\)") def pass_reserved_children(src): def sub(m): parts = m.group(2).split(".")[1:] if not any(p in RESERVED_CHILD_NAMES for p in parts): return m.group(0) out = m.group(1) for p in parts: out += ':FindFirstChild("%s")' % p if p in RESERVED_CHILD_NAMES else "." + p return "require(%s)" % out return REQUIRE_PATH.sub(sub, src) def build_roblox(): out = os.path.join(MODULES, "roblox", "Rosetta") shutil.rmtree(os.path.join(MODULES, "roblox"), ignore_errors=True) darklua(ROBLOX_RULES, os.path.relpath(SRC, ROOT), os.path.relpath(out, ROOT), ROOT) for f in files(out): with open(f) as fh: src = fh.read() fixed = pass_reserved_children(src) if fixed != src: with open(f, "w") as fh: fh.write(fixed) n = sum(1 for _ in files(out)) print("build: roblox %3d modules -> %s" % (n, os.path.relpath(out, ROOT))) def build_luajit_tree(src_root, out_root, skip_dirs=()): """src_root/**/*.luau -> out_root/**/*.lua through the require rewrite, darklua and the token passes.""" tmp = tempfile.mkdtemp(prefix="rosetta-build-") try: stage = os.path.join(tmp, "in") dl = os.path.join(tmp, "out") count = 0 for f in files(src_root): rel = os.path.relpath(f, src_root) if rel.split(os.sep)[0] in skip_dirs: continue dst = os.path.join(stage, rel) os.makedirs(os.path.dirname(dst), exist_ok=True) with open(f) as fh: s = fh.read() with open(dst, "w") as fh: fh.write(pass_elseif(luajit_requires(s))) count += 1 if count == 0: return 0 darklua(LUAJIT_RULES, stage, dl, tmp) for f in files(dl): rel = os.path.relpath(f, dl) with open(f) as fh: s = fh.read() s = pass_header(pass_ifexpr(pass_iter(s))) dst = os.path.join(out_root, rel[:-5] + ".lua") os.makedirs(os.path.dirname(dst), exist_ok=True) with open(dst, "w") as fh: fh.write(s) return count finally: shutil.rmtree(tmp, ignore_errors=True) def build_luajit(): base = os.path.join(MODULES, "luajit") shutil.rmtree(base, ignore_errors=True) out = os.path.join(base, "rosetta") n = build_luajit_tree(SRC, out) shutil.copy(os.path.join(ROOT, "compat", "luajit.lua"), os.path.join(out, "_compat.lua")) print("build: luajit %3d modules -> %s" % (n, os.path.relpath(out, ROOT))) tout = os.path.join(base, "tests") nt = build_luajit_tree(TESTS, tout, skip_dirs=("gen", "fixtures")) gen = os.path.join(TESTS, "gen") ng = 0 for f in files(gen): dst = os.path.join(tout, "gen", os.path.relpath(f, gen)[:-5] + ".lua") os.makedirs(os.path.dirname(dst), exist_ok=True) shutil.copy(f, dst) ng += 1 print("build: luajit %3d tests + %d fixture modules -> %s" % (nt, ng, os.path.relpath(tout, ROOT))) # tools/*.luau (bench.luau): run with the same package.path build_luajit_tree(os.path.join(ROOT, "tools"), os.path.join(base, "tools"), skip_dirs=("fixtures",)) def selftest(): cases = [ ("for k, v in t do end", "for k, v in __iter(t) do end"), ("for k, v in pairs(t) do end", "for k, v in pairs(t) do end"), ("for k, v in next, t do end", "for k, v in next, t do end"), ("for i = 1, 3 do end", "for i = 1, 3 do end"), ("for _, x in f(function() for a in b do end end) do end", "for _, x in __iter(f(function() for a in __iter(b) do end end)) do end"), ] for a, want in cases: got = pass_iter(a) assert got == want, (a, got) ifs = [ ("local a = (c and{v + 1 }or{0\n})[1]", "local a = (c and(v + 1 )or(0\n))"), ("local a = (c and{v }or{w})[1]", None), ("local a = (c and{x < 1 }or{w})[1]", None), ("local a = (c and{#t }or{w})[1]", "local a = (c and(#t )or(w))"), ("local a = (c and{(f(x) .. \"s\") }or{w})[1]", "local a = (c and((f(x) .. \"s\") )or(w))"), ] for a, want in ifs: got = pass_ifexpr(a) assert got == (want or a), (a, got) els = [ ("local x = if a then 1 elseif b then 2 elseif c then 3 else 4", "local x = if a then 1 else if b then 2 else if c then 3 else 4"), ("if a then f() elseif b then g() else h() end", None), ("if a then x = if b then 1 elseif c then 2 else 3 elseif d then y() end", "if a then x = if b then 1 else if c then 2 else 3 elseif d then y() end"), ("return f(if a then 1 elseif b then 2 else 3), function() if p then elseif q then end end", "return f(if a then 1 else if b then 2 else 3), function() if p then elseif q then end end"), ("local y = if a then if b then 1 elseif c then 2 else 3 elseif d then 4 else 5", "local y = if a then if b then 1 else if c then 2 else 3 else if d then 4 else 5"), ] for a, want in els: got = pass_elseif(a) assert got == (want or a), (a, got) assert luajit_requires('require("@rosetta/core/Bytes")') == 'require("rosetta.core.Bytes")' els = [ ("local x = if a then 1 elseif b then 2 elseif c then 3 else 4", "local x = if a then 1 else if b then 2 else if c then 3 else 4"), ("if a then f() elseif b then g() else h() end", None), ("if a then x = if b then 1 elseif c then 2 else 3 elseif d then y() end", "if a then x = if b then 1 else if c then 2 else 3 elseif d then y() end"), ("return f(if a then 1 elseif b then 2 else 3), function() if p then elseif q then end end", "return f(if a then 1 else if b then 2 else 3), function() if p then elseif q then end end"), ("local y = if a then if b then 1 elseif c then 2 else 3 elseif d then 4 else 5", "local y = if a then if b then 1 else if c then 2 else 3 else if d then 4 else 5"), ] for a, want in els: got = pass_elseif(a) assert got == (want or a), (a, got) assert luajit_requires('require( "@tests/gen/png_suite" )') == 'require("tests.gen.png_suite")' print("build: self-test OK") if __name__ == "__main__": targets = sys.argv[1:] or ["roblox", "luajit"] if "--test" in targets: selftest() sys.exit(0) sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import bundle if "roblox" in targets: build_roblox() bundle.bundle_roblox() if "luajit" in targets: build_luajit() bundle.bundle_luajit()