Files
rosetta/tools/bundle.py
T
4DBug bcf6d46fb7 build: single-file bundles build/Rosetta.luau + build/rosetta.lua (tools/bundle.py), terse README with generated format / codec tables
- tools/bundle.py: every module a function in __FILES with a cached __include; requires become __include
  calls, so only the API and its load-time requires run on require. Rosetta._internal(path) includes any
  module by its src path. --!native modules get @native on each function (NATIVE re-checked on the bundle);
  linemaps map bundle lines back to sources (--where). LuaJIT bundle inlines the compat prelude.
- tools/build.py: the multi-file trees move to build/_modules (gitignored); each target also writes its bundle.
- tools/test.sh: api + docs/example tests also run against both bundles; fails when build/ is stale.
- default.project.json mounts build/Rosetta.luau; examples/love loads build/rosetta.lua.
- README: one line, install, quick start, doc links, generated format table and codec list
  (tools/gen_registry.py), licence TODO. DOCS lint checks the generated sections and the links.
2026-11-01 01:00:35 -06:00

337 lines
15 KiB
Python

#!/usr/bin/env python3
# Single-file bundles (python3 -I tools/bundle.py [roblox|luajit ...] [--stage-tests] [--where <file> <line>]):
#
# build/Rosetta.luau Roblox (one ModuleScript; also runs under the luau CLI), from src/Rosetta directly
# build/rosetta.lua LÖVE / LuaJIT (one file), from build/_modules/luajit/rosetta (tools/build.py luajit first)
# build/<file>.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; native codegen reads the annotations, not the checker).
# --!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.
# export type -> type (a function body cannot export).
# 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,luajit} (tools/test.sh runs them).
# --where <Rosetta.luau|rosetta.lua> <line>: the source file and line of a bundle line.
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("<literal>") -> __include("<key>") 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 "<root>"))
for d in sorted(deps[k] & throwing):
bad.append("%s is @native and includes %s, which can throw" % (k or "<root>", 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", "luajit": "LUAJIT"}[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 bundle_roblox():
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)
src = native_functions(src)
mods[key] = (src, os.path.relpath(path, ROOT).replace(os.sep, "/"))
check_native(mods, native, deps)
head = ["--!optimize 2", "--!nocheck",
"-- rosetta (Roblox bundle): GENERATED by tools/bundle.py from src/Rosetta - do not edit.",
"-- 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, native)
write("Rosetta.luau", text, linemap)
compile_check(tool("luau-compile") + ["--null", os.path.join(BUILD, "Rosetta.luau")], "build/Rosetta.luau")
# ------------------------------------------------------------------------------------------------ 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}/<same relative path>"""
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")
print("bundle: %d tests staged -> %s/{luau,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):
with open(os.path.join(BUILD, name + ".linemap.json")) as f:
lm = json.load(f)
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"]:
print(where(os.path.basename(args[1]), int(args[2])))
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()