#!/usr/bin/env python3 # Bundles (python3 -I tools/bundle.py [roblox|luajit ...] [--stage-tests] [--check-rbxm] [--where [chunk] ]): # # build/Rosetta.luau Roblox, no native code (one ModuleScript; also runs under the luau CLI), from src/Rosetta # build/Rosetta.rbxm Roblox, native: a Rosetta ModuleScript + chunk ModuleScripts loaded on demand (see "chunked" # below); build/Rosetta.rbxmx is the same model as XML. Both written with the roblox target. # build/rosetta.lua LÖVE / LuaJIT (one file), from build/_modules/luajit/rosetta (tools/build.py luajit first) # build/.linemap.json [[first bundle line, source file], ...]: bundle line L of a module starting at line S is # line L - S + 1 of its source file (both bundles keep every source line on its line) # # Every module becomes a function in __FILES, keyed by its module path ("core/Bytes", "image/png", "" for the root); # __include(path) runs it on first use and caches the result. Requires become __include calls, so requiring the bundle # runs only the root and what it requires at load time; every other module runs on first use, like separate modules. # The returned table is the root's API table plus Rosetta._internal(path): __include of any module by its src path # ("codecs/video/Mpeg1"), for code that uses internals. An unknown path throws. # # Roblox bundle: # --!optimize 2 for the whole file and --!nocheck (types are kept, but a cross-module type such as Bytes.Reader # cannot resolve once requires are __include calls). No --!native / @native: one 5.9 MB module is over Roblox's # per-module native codegen budget (Studio logs a failure for most of it), so it runs interpreted. # export type -> type (a function body cannot export). # Chunked build (Rosetta.rbxm): the same module bodies; --!native cannot apply to one module inside a file, so a # --!native module gets @native on every function it defines, its module function included (@native does not reach # nested functions). The NATIVE lint rule (no error / assert in a --!native module or what it requires) is checked # again here on the bundled text. # LuaJIT bundle: compat/luajit.lua runs once at the top; each module's compat header reads it (`__compat`) instead of # require("rosetta._compat"). The bundle sets package.loaded["rosetta._compat"] (when unset), so # require("rosetta._compat").install() keeps working, and _internal("_compat") returns it too. # Load: package.path = "build/?.lua;" .. package.path; require("rosetta"), or dofile("build/rosetta.lua"). # # Limits (Luau 200 locals / 200 upvalues per function, LuaJIT 60 upvalues, constants per function): the main chunk # holds 3 locals and one string constant per module; a module function adds at most 2 upvalues (__include, # __compat) to what its source chunk had. Both bundles are compiled here as a check (luau-compile, luajit -bl). # # --stage-tests: the api test and the docs / example tests (tests/docs/snippets) rewritten to use the bundles, in # build/_modules/bundle_tests/{luau,luau_chunked,luajit} (tools/test.sh runs them; luau_chunked runs against # build/_modules/chunked/Rosetta, the rbxm's ModuleScripts as files). # --check-rbxm: lune reads build/Rosetta.rbxm, .rbxmx and rojo's build of default.project.json; same tree and sources. # --where | : the source file and line of a bundle # line (a Roblox error in the chunked build reads "...Rosetta.:"). import json, os, re, shutil, subprocess, sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) from build import lex, apply, ROOT, SRC, BUILD, MODULES LJ_MODULES = os.path.join(MODULES, "luajit", "rosetta") STAGE = os.path.join(MODULES, "bundle_tests") THROW = {"error", "assert"} DIRECTIVE = re.compile(r"^--!(strict|nonstrict|nocheck|native|optimize \d)[ \t]*$") def modpath(rel): """'image/png/init.luau' -> 'image/png', 'init.luau' -> '', 'core/Bytes.lua' -> 'core/Bytes'""" rel = rel.replace(os.sep, "/").rsplit(".", 1)[0] if rel == "init": return "" return rel[:-5] if rel.endswith("/init") else rel def modules(root, ext): out = {} for d, dirs, fs in os.walk(root): dirs.sort() for f in sorted(fs): if f.endswith(ext): p = os.path.join(d, f) out[modpath(os.path.relpath(p, root))] = p return dict(sorted(out.items())) def include_requires(src, pattern, key, known, where): """require("") -> __include("") for the literals matching pattern (a compiled regex on the string contents); other requires stay. Token-based: comments and strings are never touched.""" toks = lex(src) edits = [] for i in range(len(toks) - 3): if toks[i][1] != "require" or toks[i][0] != "name" or toks[i + 1][1] != "(" or toks[i + 2][0] != "str" \ or toks[i + 3][1] != ")" or (i > 0 and toks[i - 1][1] in (".", ":")): continue lit = toks[i + 2][1] m = pattern.fullmatch(lit[1:-1]) if not m: continue k = key(m) if k is not None and k not in known: sys.exit("bundle: %s requires %s: no such module" % (where, lit)) edits.append((toks[i][2], toks[i + 3][3], "__include(%s)" % json.dumps(k) if k is not None else "__compat")) return apply(src, edits) def native_functions(src): """@native before every function a module defines (`@native local function`, `@native function a.b()`, `@native function(...)`).""" toks = lex(src) edits = [] for i, (k, t, s, e) in enumerate(toks): if k == "name" and t == "function": at = toks[i - 1][2] if i > 0 and toks[i - 1][1] == "local" else s edits.append((at, at, "@native ")) return apply(src, edits) def header_lines(src): """the leading --! directive lines become empty lines (same line count)""" lines = src.split("\n") native = False for i, l in enumerate(lines): if not l.startswith("--!"): break if DIRECTIVE.match(l): native = native or l.strip() == "--!native" lines[i] = "" return "\n".join(lines), native RUNTIME = """local __FILES = {} local __LOADED = {} local function __include(path) local r = __LOADED[path] if r == nil then local f = __FILES[path] if f == nil then error("rosetta: no module '" .. tostring(path) .. "'", 2) end __LOADED[path] = false -- while it runs (a cycle, or a module that threw) r = f() if r == nil then r = true end __LOADED[path] = r elseif r == false then error("rosetta: module '" .. path .. "' is required in a cycle or failed to load", 2) end return r end""" TAIL = """local Rosetta = __include("") Rosetta._internal = function(path) return __include(path) end return Rosetta""" def assemble(head, mods, native): """head lines + one __FILES function per module + the tail -> (text, linemap)""" out = list(head) + RUNTIME.split("\n") linemap = [] for key, (src, rel) in mods.items(): out.append("__FILES[%s] = %sfunction()" % (json.dumps(key), "@native " if key in native else "")) linemap.append([len(out) + 1, rel]) body = src.rstrip("\n") out += body.split("\n") out.append("end") out += TAIL.split("\n") return "\n".join(out) + "\n", linemap def check_native(mods, native, deps): """NATIVE on the bundled text: a native module's code has no error( / assert( and requires no module that has.""" def throws(src): toks = lex(src) return any(t[0] == "name" and t[1] in THROW and toks[i + 1][1] == "(" and (i == 0 or toks[i - 1][1] not in (".", ":")) for i, t in enumerate(toks[:-1])) throwing = {k for k, (s, _) in mods.items() if throws(s)} bad = [] for k in sorted(native): if k in throwing: bad.append("%s is @native and calls error / assert" % (k or "")) for d in sorted(deps[k] & throwing): bad.append("%s is @native and includes %s, which can throw" % (k or "", d)) if bad: sys.exit("bundle: NATIVE:\n " + "\n ".join(bad)) INCLUDES = re.compile(r'__include\("([^"]*)"\)') def write(name, text, linemap): os.makedirs(BUILD, exist_ok=True) with open(os.path.join(BUILD, name), "w") as f: f.write(text) with open(os.path.join(BUILD, name + ".linemap.json"), "w") as f: f.write("[\n" + ",\n".join(json.dumps(x) for x in linemap) + "\n]\n") print("bundle: %-14s %4d modules, %d lines, %.2f MB -> build/%s" % ( name, len(linemap), text.count("\n"), len(text) / 1e6, name)) def tool(name): env = {"luau-compile": "LUAU_COMPILE", "luau": "LUAU", "luajit": "LUAJIT", "rojo": "ROJO", "lune": "LUNE"}[name] if os.environ.get(env): return [os.environ[env]] if shutil.which(name): return [name] pkg = "luau" if name.startswith("luau") else name return ["nix", "shell", "nixpkgs#" + pkg, "-c", name] def compile_check(cmd, what): r = subprocess.run(cmd, capture_output=True, text=True) if r.returncode != 0: sys.exit("bundle: %s does not compile:\n%s" % (what, (r.stdout + r.stderr)[-3000:])) # ------------------------------------------------------------------------------------------------ roblox ROSETTA_REQ = re.compile(r"@rosetta(?:/([\w/]+))?") def roblox_modules(): """the src modules as bundle module bodies: {key: (text, src rel path)}, the --!native keys, the include deps. The text has no @native yet (native_functions adds it, for the chunked build).""" files = modules(SRC, ".luau") mods, native, deps = {}, set(), {} for key, path in files.items(): with open(path) as f: src = f.read() src, is_native = header_lines(src) src = include_requires(src, ROSETTA_REQ, lambda m: m.group(1) or "", files, os.path.relpath(path, ROOT)) src = re.sub(r"^export type\b", "type", src, flags=re.M) deps[key] = set(INCLUDES.findall(src)) if is_native: native.add(key) mods[key] = (src, os.path.relpath(path, ROOT).replace(os.sep, "/")) return mods, native, deps def bundle_roblox(): mods, native, deps = roblox_modules() head = ["--!optimize 2", "--!nocheck", "-- rosetta (Roblox bundle, no native code): GENERATED by tools/bundle.py from src/Rosetta - do not edit.", "-- One ModuleScript, interpreted: as one module it is over Roblox's per-module native codegen budget, so it", "-- carries no --!native / @native. build/Rosetta.rbxm is the native build (chunked, loaded on demand).", "-- require(this) -> the API (docs/API.md); Rosetta._internal(\"codecs/video/Mpeg1\") -> an internal module.", "-- Error lines map back to the sources through Rosetta.luau.linemap.json (python3 -I tools/bundle.py --where)."] text, linemap = assemble(head, mods, set()) write("Rosetta.luau", text, linemap) compile_check(tool("luau-compile") + ["--null", os.path.join(BUILD, "Rosetta.luau")], "build/Rosetta.luau") bundle_chunked(mods, native, deps) # ------------------------------------------------------------------------------------------------ chunked (rbxm) # build/Rosetta.rbxm: a ModuleScript "Rosetta" (the root: the registry, __include, _internal and a module -> chunk # map) with one child ModuleScript per chunk. Roblox compiles native code per ModuleScript, within a budget per module # (Luau's CodegenHeuristicsInstructionLimit, 2^20 IR instructions summed over a module: "exceeded total module # instruction limit"; and a native code memory limit); the 5.9 MB bundle has 1.5M IR instructions. Each chunk stays # under CHUNK_SRC_MAX source bytes (the packing limit) and CHUNK_IR_MAX / CHUNK_ASM_MAX of native IR / code (checked # after, with luau-compile --codegennull), with no function that fails native lowering. # A chunk returns function(__FILES, __include) that registers its modules into the root's registry. __include of a # module with no entry yet requires its chunk (require(script:FindFirstChild(name)); under the luau CLI, with no # `script`, require("@self/" .. name) over the same files in build/_modules/chunked/Rosetta). So requiring the root # loads Core (what the root runs at load time) and every other chunk on first use, per Actor. # Chunks: Core; Detect (DETECT: what F.detect runs, apart from Core); one per hot codec (HOT); the rest packed per family # (top folder, or codecs/) in path order. # A --!native module's functions get @native (a chunk can mix native and non-native modules); a chunk with no native # module has none. Outputs: build/Rosetta.rbxm (LZ4, written by model/rbxm under the luau CLI), build/Rosetta.rbxmx, # build/Rosetta.rbxm.linemap.json ({chunk: [[first line, source file], ...]}). CHUNK_SRC_MAX = 256 * 1024 CHUNK_IR_MAX = 1 << 18 CHUNK_ASM_MAX = 4 << 20 CHUNKED = os.path.join(MODULES, "chunked", "Rosetta") DETECT = ["Sniffs"] # F.detect: Sniffs.luau and what it requires at load time (core/Sniff), one small chunk HOT = [ ("Mpeg2", ["codecs/video/Mpeg2", "codecs/video/Mpeg1", "codecs/video/Dsp"]), ("H263", ["codecs/video/H263"]), ("H264", ["codecs/video/H264"]), ("Theora", ["codecs/video/Theora"]), ("Legacy", ["codecs/video/Legacy"]), ("MpegTs", ["containers/MpegTs", "containers/MpegEs", "containers/MpegPs"]), ("Dct", ["codecs/image/Dct"]), ("Jpeg", ["codecs/image/Jpeg"]), ("Vp8", ["codecs/image/Vp8", "codecs/image/Vp8L"]), ("Bcn", ["codecs/image/Bcn"]), ("Png", ["image/png"]), ("Deflate", ["codecs/compress/Deflate"]), ("Brotli", ["codecs/compress/Brotli"]), ("Lzma", ["codecs/compress/Lzma"]), ("Zstd", ["codecs/compress/Zstd"]), ("Mpa", ["codecs/audio/Mpa"]), ("Opus", ["codecs/audio/Opus"]), ("Vorbis", ["codecs/audio/Vorbis"]), ("Aac", ["codecs/audio/Aac"]), ("Flac", ["codecs/audio/Flac"]), ("Musepack", ["codecs/audio/Musepack"]), ("WavPack", ["codecs/audio/WavPack"]), ("Tracker", ["codecs/audio/Tracker"]), ("Hively", ["codecs/audio/Hively"]), ("SoundFont", ["codecs/audio/SoundFont"]), ("Draco", ["codecs/model/Draco"]), ] def under(key, prefix): return key == prefix or key.startswith(prefix + "/") def family(key): parts = key.split("/") if len(parts) == 1: return "Root" return "_".join(parts[:2]) if parts[0] == "codecs" and len(parts) > 2 else parts[0] def eager(src): """the includes a module runs at load time: those on a line with no indentation (a top-level statement; style)""" return {m.group(1) for line in src.split("\n") if line[:1] not in ("\t", " ") for m in INCLUDES.finditer(line)} def plan_chunks(mods): """[(chunk name, [module keys])], deterministic: Core, HOT, then the rest packed per family""" left = dict(mods) chunks = [] def pack(name, keys): part, size, n = [], 0, [] for k in keys: sz = len(mods[k][0]) if part and size + sz > CHUNK_SRC_MAX - 4096: # the chunk header and wrappers n.append(part) part, size = [], 0 part.append(k) size += sz if part: n.append(part) for i, p in enumerate(n): chunks.append((name if len(n) == 1 else "%s_%d" % (name, i + 1), p)) for k in p: left.pop(k) core, todo = set(), [""] while todo: k = todo.pop() if k not in core: core.add(k) todo += sorted(eager(mods[k][0])) pack("Core", sorted(core)) detect, todo = set(), [k for k in DETECT if k in left] while todo: k = todo.pop() if k in left and k not in detect: detect.add(k) todo += sorted(eager(mods[k][0])) pack("Detect", sorted(detect)) for name, prefixes in HOT: keys = [k for k in left if any(under(k, p) for p in prefixes)] if not keys: sys.exit("bundle: HOT chunk %s matches no module" % name) pack(name, keys) fams = {} for k in left: fams.setdefault(family(k), []).append(k) for f in sorted(fams): pack(f, fams[f]) return chunks ROOT_RUNTIME = """local __FILES = {} local __LOADED = {} local __DONE = {} local __script = script local __include local function __chunk(path) local name = __CHUNK[path] if name == nil or __DONE[name] then return nil end __DONE[name] = true local m if __script ~= nil then m = __script:FindFirstChild(name) if m == nil then error("rosetta: the chunk ModuleScript '" .. name .. "' is missing under " .. __script:GetFullName(), 3) end else m = "@self/" .. name -- the luau CLI: the same tree as files (Rosetta/init.luau, Rosetta/.luau) end require(m)(__FILES, __include) return __FILES[path] end __include = function(path) local r = __LOADED[path] if r == nil then local f = __FILES[path] or __chunk(path) if f == nil then error("rosetta: no module '" .. tostring(path) .. "'", 2) end __LOADED[path] = false -- while it runs (a cycle, or a module that threw) r = f() if r == nil then r = true end __LOADED[path] = r elseif r == false then error("rosetta: module '" .. path .. "' is required in a cycle or failed to load", 2) end return r end""" def bundle_chunked(mods, native, deps): check_native(mods, native, deps) chunks = plan_chunks(mods) names = [c for c, _ in chunks] if len(set(names)) != len(names): sys.exit("bundle: duplicate chunk names") shutil.rmtree(os.path.dirname(CHUNKED), ignore_errors=True) os.makedirs(CHUNKED) sources, linemaps = [], {} for name, keys in chunks: nat = sorted(k for k in keys if k in native) out = ["--!optimize 2", "--!nocheck", "-- rosetta chunk %s (build/Rosetta.rbxm): GENERATED by tools/bundle.py from src/Rosetta - do not edit." % name, "-- %d modules (%d native: @native); the Rosetta root requires it when one of them is first included." % (len(keys), len(nat)), "-- Error lines map back to the sources through Rosetta.rbxm.linemap.json (tools/bundle.py --where).", "return function(__FILES, __include)"] lm = [] for k in keys: src, rel = mods[k] if k in native: src = native_functions(src) out.append("__FILES[%s] = %sfunction()" % (json.dumps(k), "@native " if k in native else "")) lm.append([len(out) + 1, rel]) out += src.rstrip("\n").split("\n") out.append("end") out.append("end") sources.append((name, "\n".join(out) + "\n")) linemaps[name] = lm cmap = ["local __CHUNK = {"] + ["\t[%s] = %s," % (json.dumps(k), json.dumps(name)) for name, keys in chunks for k in sorted(keys)] + ["}"] root = "\n".join(["--!optimize 2", "--!nocheck", "-- rosetta (Roblox, native build): GENERATED by tools/bundle.py from src/Rosetta - do not edit.", "-- The root of build/Rosetta.rbxm: the module registry; each child ModuleScript is a chunk of modules,", "-- required on the first include of one of them. require(this) -> the API (docs/API.md);", "-- Rosetta._internal(\"codecs/video/Mpeg1\") -> an internal module."] + cmap + ROOT_RUNTIME.split("\n") + TAIL.split("\n")) + "\n" with open(os.path.join(CHUNKED, "init.luau"), "w") as f: f.write(root) for name, text in sources: with open(os.path.join(CHUNKED, name + ".luau"), "w") as f: f.write(text) with open(os.path.join(BUILD, "Rosetta.rbxm.linemap.json"), "w") as f: f.write("{\n" + ",\n".join("%s: [%s]" % (json.dumps(n), ", ".join(json.dumps(x) for x in lm)) for n, lm in linemaps.items()) + "\n}\n") for name, text in [("Rosetta", root)] + sources: # Roblox runs a script at O1 unless it says otherwise if not text.startswith("--!optimize 2\n"): sys.exit("bundle: chunk %s does not start with --!optimize 2" % name) codegen_check([("Rosetta", root)] + sources, chunks, native) write_rbxm(root, sources) def codegen_check(sources, chunks, native): """every chunk compiles natively (luau-compile --codegennull) within the budget; prints the chunk table""" paths = [os.path.join(CHUNKED, "init.luau")] + [os.path.join(CHUNKED, n + ".luau") for n, _ in chunks] stats = os.path.join(MODULES, "chunked", "codegen.json") cmd = tool("luau-compile") + ["--codegennull", "-O2", "--record-stats=function", "--stats-file=" + stats] + paths r = subprocess.run(cmd, capture_output=True, text=True) if r.returncode != 0: sys.exit("bundle: a chunk does not compile:\n" + (r.stdout + r.stderr)[-3000:]) with open(stats) as f: st = json.load(f) keys = dict(chunks) rows, bad = [], [] for (name, text), path in zip(sources, paths): s = st.get(path) or st[os.path.relpath(path)] n = len(keys.get(name, [])) nn = len([k for k in keys.get(name, []) if k in native]) # luau-compile compiles every function of a file with no @native one; Roblox compiles none of it fns = s["lowerStats"]["functions"] if nn else [] ir = sum(x["irCount"] for x in fns) asm = sum(x["asmSize"] for x in fns) failed = [x["name"] for x in fns if x["asmCount"] == 0 and x["irCount"] > 0] if nn and (s["lowerStats"]["regAllocErrors"] or s["lowerStats"]["loweringErrors"]): failed.append("(%d regalloc / %d lowering errors)" % (s["lowerStats"]["regAllocErrors"], s["lowerStats"]["loweringErrors"])) rows.append((name, n, nn, len(text), len(fns), ir, asm)) if len(text) > CHUNK_SRC_MAX and n > 1: bad.append("%s: %d source bytes > %d" % (name, len(text), CHUNK_SRC_MAX)) if ir > CHUNK_IR_MAX: bad.append("%s: %d native IR instructions > %d (split it in HOT)" % (name, ir, CHUNK_IR_MAX)) if asm > CHUNK_ASM_MAX: bad.append("%s: %d bytes of native code > %d" % (name, asm, CHUNK_ASM_MAX)) if failed: bad.append("%s: native lowering failed: %s" % (name, ", ".join(failed))) table = os.path.join(MODULES, "chunked", "chunks.txt") with open(table, "w") as f: f.write("%-16s %7s %6s %9s %7s %8s %10s\n" % ("chunk", "modules", "native", "source", "@native", "IR", "native code")) for row in rows: f.write("%-16s %7d %6d %9d %7d %8d %10d\n" % row) big = max(rows, key=lambda x: x[5]) print("bundle: Rosetta.rbxm %d chunks, largest native %s: %d modules, %.0f KB source, %d IR (limit %d), %.2f MB" " native code (table: %s)" % (len(chunks), big[0], big[1], big[3] / 1024, big[5], CHUNK_IR_MAX, big[6] / 1e6, os.path.relpath(table, ROOT))) if bad: sys.exit("bundle: chunk budget:\n " + "\n ".join(bad)) def long_string(s): n = 0 while "]" + "=" * n + "]" in s: n += 1 return "[" + "=" * n + "[\n" + s + "]" + "=" * n + "]" RBXM_WRITE = """-- GENERATED by tools/bundle.py: writes build/Rosetta.rbxm / .rbxmx with rosetta's own model/rbxm, model/rbxmx local Rbx = require("@rosetta/codecs/model/Rbx") local Rbxm = require("@rosetta/model/rbxm") local Rbxmx = require("@rosetta/model/rbxmx") local S = __SOURCES__ local tree = Rbx.tree(false) local root = Rbx.add(tree, Rbx.instance("ModuleScript", "Rosetta")) Rbx.set(root, "Source", "ProtectedString", S[1][2]) for i = 2, #S do local c = Rbx.add(root, Rbx.instance("ModuleScript", S[i][1])) Rbx.set(c, "Source", "ProtectedString", S[i][2]) end local HEX = {} for i = 0, 255 do HEX[i] = string.format("%02x", i) end local function hex(b: buffer): string local n = buffer.len(b) local out = buffer.create(n * 2) for i = 0, n - 1 do buffer.writestring(out, i * 2, HEX[buffer.readu8(b, i)]) end return buffer.tostring(out) end local bin = assert(Rbxm.encode(tree, { compression = "lz4" })) local xml = assert(Rbxmx.encode(tree)) print(hex(bin)) print(hex(xml)) """ def write_rbxm(root, sources): items = [("Rosetta", root)] + sources lua = RBXM_WRITE.replace("__SOURCES__", "{\n" + "".join("\t{ %s, %s },\n" % (json.dumps(n), long_string(t)) for n, t in items) + "}") script = os.path.join(MODULES, "chunked", "rbxm_write.luau") with open(script, "w") as f: f.write(lua) r = subprocess.run(tool("luau") + [os.path.relpath(script, ROOT)], capture_output=True, text=True, cwd=ROOT) out = r.stdout.split("\n") if r.returncode != 0 or len(out) < 2: sys.exit("bundle: rbxm_write failed:\n" + (r.stdout[-2000:] + r.stderr[-2000:])) for name, h in (("Rosetta.rbxm", out[0]), ("Rosetta.rbxmx", out[1])): data = bytes.fromhex(h) with open(os.path.join(BUILD, name), "wb") as f: f.write(data) print("bundle: %-14s %4d ModuleScripts, %.2f MB -> build/%s" % (name, len(items), len(data) / 1e6, name)) LUNE_CHECK = """-- GENERATED by tools/bundle.py --check-rbxm: lune reads the models and compares them with the chunk sources local fs = require("@lune/fs") local roblox = require("@lune/roblox") local process = require("@lune/process") local dir, models = process.args[1], { table.unpack(process.args, 2) } local fail = 0 for _, path in models do local ok, m = pcall(roblox.deserializeModel, fs.readFile(path)) local function bad(msg) print("check-rbxm: " .. path .. ": " .. msg) fail += 1 end if not ok then bad("does not load: " .. tostring(m)) elseif #m ~= 1 or m[1].ClassName ~= "ModuleScript" or m[1].Name ~= "Rosetta" then bad("expected one ModuleScript Rosetta") else local root = m[1] if root.Source ~= fs.readFile(dir .. "/init.luau") then bad("the root Source differs") end local want = {} for _, f in fs.readDir(dir) do if f ~= "init.luau" then want[string.gsub(f, "%.luau$", "")] = true end end local n = 0 for _, c in root:GetChildren() do n += 1 if c.ClassName ~= "ModuleScript" or not want[c.Name] then bad("unexpected child " .. c.Name) elseif c.Source ~= fs.readFile(dir .. "/" .. c.Name .. ".luau") then bad(c.Name .. ": Source differs") elseif #c:GetChildren() ~= 0 then bad(c.Name .. " has children") end want[c.Name] = nil end for k in want do bad("missing chunk " .. k) end if fail == 0 then print("check-rbxm: " .. path .. ": ok, Rosetta + " .. n .. " chunks, sources identical") end end end process.exit(if fail == 0 then 0 else 1) """ def check_rbxm(): """lune (@lune/roblox) reads build/Rosetta.rbxm, .rbxmx and rojo's build of default.project.json: the same tree and sources as build/_modules/chunked/Rosetta""" out = os.path.join(MODULES, "chunked") rojo_out = os.path.join(out, "rojo.rbxm") r = subprocess.run(tool("rojo") + ["build", os.path.join(ROOT, "default.project.json"), "-o", rojo_out], capture_output=True, text=True) if r.returncode != 0: sys.exit("bundle: rojo build default.project.json failed:\n" + r.stdout + r.stderr) script = os.path.join(out, "check.luau") with open(script, "w") as f: f.write(LUNE_CHECK) r = subprocess.run(tool("lune") + ["run", script, CHUNKED, os.path.join(BUILD, "Rosetta.rbxm"), os.path.join(BUILD, "Rosetta.rbxmx"), rojo_out], text=True) if r.returncode != 0: sys.exit("bundle: --check-rbxm failed") # ------------------------------------------------------------------------------------------------ luajit LJ_REQ = re.compile(r"rosetta(?:\.([\w.]+))?") def bundle_luajit(): if not os.path.isdir(LJ_MODULES): sys.exit("bundle: no %s (python3 -I tools/build.py luajit)" % os.path.relpath(LJ_MODULES, ROOT)) files = modules(LJ_MODULES, ".lua") files.pop("_compat", None) srcs = modules(SRC, ".luau") def key(m): k = (m.group(1) or "").replace(".", "/") return None if k == "_compat" else k mods = {} for k, path in files.items(): with open(path) as f: src = f.read() src = include_requires(src, LJ_REQ, key, files, os.path.relpath(path, ROOT)) mods[k] = (src, os.path.relpath(srcs[k], ROOT).replace(os.sep, "/")) with open(os.path.join(ROOT, "compat", "luajit.lua")) as f: compat = f.read().rstrip("\n") head = ["-- rosetta (LuaJIT / LÖVE bundle): GENERATED by tools/bundle.py from src/Rosetta - do not edit.", "-- require(\"rosetta\") with build/?.lua on package.path, or dofile(\"build/rosetta.lua\"): the API", "-- (docs/API.md); Rosetta._internal(\"codecs/video/Mpeg1\") -> an internal module. Error lines map back to", "-- the sources through rosetta.lua.linemap.json (python3 -I tools/bundle.py --where).", "local __compat = (function()"] + compat.split("\n") + [ "end)()", "if package and package.loaded and package.loaded[\"rosetta._compat\"] == nil then", "\tpackage.loaded[\"rosetta._compat\"] = __compat", "end"] text, linemap = assemble(head, mods, set()) text = text.replace(RUNTIME, RUNTIME + "\n__LOADED[\"_compat\"] = __compat", 1) linemap = [[a + 1, b] for a, b in linemap] write("rosetta.lua", text, linemap) compile_check(tool("luajit") + ["-bl", os.path.join(BUILD, "rosetta.lua"), "/dev/null"], "build/rosetta.lua") # ------------------------------------------------------------------------------------------------ tests on the bundles LUAU_RC = {"languageMode": "nonstrict", "aliases": {"tests": "../../../../tests", "bundle": "../../.."}} def stage_tests(): """tests/api.luau + tests/docs/snippets/*.luau against build/Rosetta.luau (luau) and their LuaJIT builds against build/rosetta.lua: build/_modules/bundle_tests/{luau,luajit}/""" shutil.rmtree(STAGE, ignore_errors=True) names = ["api.luau"] + ["docs/snippets/" + f for f in sorted(os.listdir(os.path.join(ROOT, "tests", "docs", "snippets"))) if f.endswith(".luau") and not f.startswith("_")] luau_req = re.compile(r"@rosetta(?:/([\w/]+))?") lj_req = re.compile(r"rosetta(?:\.([\w.]+))?") n = 0 for rel in names: with open(os.path.join(ROOT, "tests", rel)) as f: src = f.read() src = rewrite_api(src, luau_req, lambda m: m.group(1), 'require("@bundle/Rosetta")') dst = os.path.join(STAGE, "luau", rel) os.makedirs(os.path.dirname(dst), exist_ok=True) with open(dst, "w") as f: f.write(src) lj = os.path.join(MODULES, "luajit", "tests", rel[:-5] + ".lua") with open(lj) as f: src = f.read() src = rewrite_api(src, lj_req, lambda m: m.group(1) and m.group(1).replace(".", "/"), 'require("rosetta")') dst = os.path.join(STAGE, "luajit", rel[:-5] + ".lua") os.makedirs(os.path.dirname(dst), exist_ok=True) with open(dst, "w") as f: f.write(src) n += 1 with open(os.path.join(STAGE, "luau", ".luaurc"), "w") as f: json.dump(LUAU_RC, f, indent="\t") # the same luau tests against the chunked build (build/_modules/chunked/Rosetta: the rbxm's ModuleScripts as files) shutil.copytree(os.path.join(STAGE, "luau"), os.path.join(STAGE, "luau_chunked")) with open(os.path.join(STAGE, "luau_chunked", ".luaurc"), "w") as f: json.dump(dict(LUAU_RC, aliases=dict(LUAU_RC["aliases"], bundle="../../chunked")), f, indent="\t") print("bundle: %d tests staged -> %s/{luau,luau_chunked,luajit}" % (n, os.path.relpath(STAGE, ROOT))) def rewrite_api(src, pattern, sub, root): """the library requires of a test -> the bundle: the root as it is, a submodule through _internal""" toks = lex(src) edits = [] for i in range(len(toks) - 3): if toks[i][1] == "require" and toks[i + 1][1] == "(" and toks[i + 2][0] == "str" and toks[i + 3][1] == ")": m = pattern.fullmatch(toks[i + 2][1][1:-1]) if m: k = sub(m) edits.append((toks[i][2], toks[i + 3][3], root if not k else "%s._internal(%s)" % (root, json.dumps(k)))) return apply(src, edits) def where(name, line, chunk=None): with open(os.path.join(BUILD, name + ".linemap.json")) as f: lm = json.load(f) if chunk is not None: if chunk not in lm: return "%s: no chunk %s (the root, or one of: %s)" % (name, chunk, ", ".join(lm)) lm = lm[chunk] name = "%s %s" % (name, chunk) best = None for start, path in lm: if start <= line: best = (start, path) if not best: return "%s:%d (bundle runtime)" % (name, line) return "%s:%d" % (best[1], line - best[0] + 1) if __name__ == "__main__": args = sys.argv[1:] if args[:1] == ["--where"]: if os.path.basename(args[1]).startswith("Rosetta.rbxm"): print(where("Rosetta.rbxm", int(args[3]), args[2])) else: print(where(os.path.basename(args[1]), int(args[2]))) sys.exit(0) if args[:1] == ["--check-rbxm"]: check_rbxm() sys.exit(0) targets = [a for a in args if not a.startswith("--")] or ([] if "--stage-tests" in args else ["roblox", "luajit"]) if "roblox" in targets: bundle_roblox() if "luajit" in targets: bundle_luajit() if "--stage-tests" in args: stage_tests()