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.
This commit is contained in:
1 parent
0bd7b87d2b
commit
bcf6d46fb7
16 files changed
+399611
-210
No files matched your search
+2
-2
@@ -1,9 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
# Timings (bash tools/bench.sh): tools/bench.luau under luau --codegen -O2 and under LuaJIT (the build output).
|
||||
# Timings (bash tools/bench.sh): tools/bench.luau under luau --codegen -O2 and under LuaJIT (the module build, build/_modules/luajit).
|
||||
cd "$(dirname "$0")/.." || exit 1
|
||||
LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')}
|
||||
LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')}
|
||||
python3 -I tools/fixtures.py > /dev/null || exit 1
|
||||
python3 -I tools/build.py luajit > /dev/null || exit 1
|
||||
"$LUAU" --codegen -O2 tools/bench.luau
|
||||
"$LUAJIT" -e 'package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path' build/luajit/tools/bench.lua
|
||||
"$LUAJIT" -e 'package.path = "build/_modules/luajit/?.lua;build/_modules/luajit/?/init.lua;" .. package.path' build/_modules/luajit/tools/bench.lua
|
||||
+21
-12
@@ -1,16 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
# Build (python3 -I tools/build.py [roblox|luajit ...]): the two outputs of the one Luau source tree.
|
||||
#
|
||||
# build/roblox/Rosetta/... darklua convert_require (luau aliases -> Roblox instance paths). Types, --!native and
|
||||
# @native are kept. Mounted by default.project.json (rojo build / rojo serve).
|
||||
# build/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").
|
||||
# build/luajit/tools/... tools/*.luau (bench), built the same way.
|
||||
# build/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).
|
||||
# The shipped files are the single-file bundles build/Rosetta.luau (roblox) 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 output with package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path, then
|
||||
# local F = require("rosetta").
|
||||
# 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
|
||||
@@ -29,6 +33,7 @@ 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"])
|
||||
@@ -329,8 +334,8 @@ def pass_reserved_children(src):
|
||||
|
||||
|
||||
def build_roblox():
|
||||
out = os.path.join(BUILD, "roblox", "Rosetta")
|
||||
shutil.rmtree(os.path.join(BUILD, "roblox"), ignore_errors=True)
|
||||
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:
|
||||
@@ -379,7 +384,7 @@ def build_luajit_tree(src_root, out_root, skip_dirs=()):
|
||||
|
||||
|
||||
def build_luajit():
|
||||
base = os.path.join(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)
|
||||
@@ -459,7 +464,11 @@ if __name__ == "__main__":
|
||||
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()
|
||||
+336
@@ -0,0 +1,336 @@
|
||||
#!/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()
|
||||
+65
-4
@@ -4,9 +4,11 @@
|
||||
# src/Rosetta/Registry.luau a static list (Roblox has no dynamic require): each format's contract metadata, copied
|
||||
# from its init.luau, and a load() that requires the module on first use
|
||||
# docs/FORMATS.md the capability matrix, from each contract's caps
|
||||
# README.md the format table (read / write) and the codec + container list, between the markers
|
||||
# <!-- formats:begin --> / <!-- formats:end --> and <!-- codecs:begin --> / <!-- codecs:end -->
|
||||
# The metadata fields must be one-line literals in the contract table (tools/lint.sh CONTRACT checks the shape):
|
||||
# name = "png", category = "image", extensions = { ... }, mime = { ... }, deps = { ... }, caps = { ... },
|
||||
# --check: exit 1 when either file is out of date (tools/lint.sh runs this).
|
||||
# --check: exit 1 when any of them is out of date (tools/lint.sh runs this).
|
||||
import os, re, sys
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
@@ -156,21 +158,80 @@ def formats_md(formats):
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
LABELS = {"image": "Images", "audio": "Audio", "video": "Video", "model": "3D models", "cad": "CAD", "font": "Fonts",
|
||||
"archive": "Archives", "data": "Data", "vector": "Vector graphics and tile maps", "layered": "Layered images",
|
||||
"subtitle": "Subtitles", "music": "Music", "playlist": "Playlists"}
|
||||
|
||||
|
||||
def module_list(rel):
|
||||
"""[(name, file)] of the modules directly under src/Rosetta/<rel> (Foo.luau or Foo/init.luau)"""
|
||||
d = os.path.join(SRC, rel)
|
||||
out = []
|
||||
for name in sorted(os.listdir(d)) if os.path.isdir(d) else []:
|
||||
p = os.path.join(d, name)
|
||||
f = os.path.join(p, "init.luau") if os.path.isdir(p) else p
|
||||
if os.path.isfile(f) and f.endswith(".luau"):
|
||||
out.append((name[:-5] if name.endswith(".luau") else name, f))
|
||||
return out
|
||||
|
||||
|
||||
def readme_formats(formats):
|
||||
by = {}
|
||||
for c in formats:
|
||||
by.setdefault(c["folder_category"], []).append(c)
|
||||
lines = ["%d formats. Generated from the format contracts by `tools/gen_registry.py`; [docs/FORMATS.md](docs/FORMATS.md)"
|
||||
% len(formats), "adds each format's capabilities.", "",
|
||||
"| Category | Format | Extensions | Read | Write |", "|---|---|---|---|---|"]
|
||||
for cat in CATEGORIES:
|
||||
for c in by.get(cat, []):
|
||||
cd = dict(caps_dict(c["caps"]))
|
||||
lines.append("| %s | %s | %s | %s | %s |" % (
|
||||
LABELS[cat], lua_strings(c["name"])[0], " ".join("." + e for e in lua_strings(c["extensions"])),
|
||||
"yes" if cd.get("decode") == "true" else "-", "yes" if cd.get("encode") == "true" else "-"))
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def readme_codecs():
|
||||
lines = ["Shared by the formats, not loadable on their own (`src/Rosetta/codecs/<domain>/`, `src/Rosetta/containers/`;",
|
||||
"[docs/FORMATS.md](docs/FORMATS.md) describes each). The bundles reach them as `F._internal(\"codecs/video/Mpeg1\")`.",
|
||||
"", "| Domain | Modules |", "|---|---|"]
|
||||
cdir = os.path.join(SRC, "codecs")
|
||||
for domain in sorted(os.listdir(cdir)):
|
||||
if os.path.isdir(os.path.join(cdir, domain)):
|
||||
lines.append("| %s | %s |" % (domain, ", ".join(n for n, _ in module_list("codecs/" + domain))))
|
||||
lines.append("| containers | %s |" % ", ".join(n for n, _ in module_list("containers")))
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def readme(formats, path):
|
||||
"""README.md with its generated sections replaced"""
|
||||
text = open(path, encoding="utf-8").read()
|
||||
for tag, body in (("formats", readme_formats(formats)), ("codecs", readme_codecs())):
|
||||
begin, end = "<!-- %s:begin -->" % tag, "<!-- %s:end -->" % tag
|
||||
m = re.search(re.escape(begin) + r".*?" + re.escape(end), text, re.S)
|
||||
if not m:
|
||||
sys.exit("gen_registry: README.md has no %s ... %s section" % (begin, end))
|
||||
text = text[:m.start()] + begin + "\n" + body + "\n" + end + text[m.end():]
|
||||
return text
|
||||
|
||||
|
||||
def main():
|
||||
formats = scan()
|
||||
readme_path = os.path.join(ROOT, "README.md")
|
||||
outputs = {
|
||||
os.path.join(SRC, "Registry.luau"): registry(formats),
|
||||
os.path.join(ROOT, "docs", "FORMATS.md"): formats_md(formats),
|
||||
readme_path: readme(formats, readme_path),
|
||||
}
|
||||
check = "--check" in sys.argv
|
||||
stale = []
|
||||
for path, text in outputs.items():
|
||||
old = open(path).read() if os.path.exists(path) else None
|
||||
old = open(path, encoding="utf-8").read() if os.path.exists(path) else None
|
||||
if old != text:
|
||||
stale.append(os.path.relpath(path, ROOT))
|
||||
if not check:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w") as f:
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
if check:
|
||||
if stale:
|
||||
@@ -178,7 +239,7 @@ def main():
|
||||
sys.exit(1)
|
||||
print("gen_registry: up to date (%d formats)" % len(formats))
|
||||
else:
|
||||
print("gen_registry: %d formats -> src/Rosetta/Registry.luau, docs/FORMATS.md%s" % (
|
||||
print("gen_registry: %d formats -> src/Rosetta/Registry.luau, docs/FORMATS.md, README.md%s" % (
|
||||
len(formats), "" if stale else " (unchanged)"))
|
||||
|
||||
|
||||
|
||||
+18
-19
@@ -20,9 +20,10 @@
|
||||
# DUP no copy-pasted code: a function body of DUP_LINES (12) or more code lines whose tokens (comments and
|
||||
# whitespace dropped, identifiers kept) equal another module's function body fails; move it down to a
|
||||
# shared module (core / codecs / containers) and call it from both.
|
||||
# DOCS the module lists in README.md's Layout block and docs/STYLE.md's layer block name every codec
|
||||
# (codecs/<domain>/<Name>), container and core module in the tree; README.md's format counts
|
||||
# ("images (25)", ...) match the registry (docs/FORMATS.md); docs/guide/README.md links every guide page.
|
||||
# DOCS docs/STYLE.md's layer block names every codec (codecs/<domain>/<Name>), container and core module in the
|
||||
# tree; README.md's generated format table and codec list (<!-- formats:begin --> ... <!-- codecs:end -->)
|
||||
# match tools/gen_registry.py's output; README.md links every docs/guide page, docs/API.md and
|
||||
# docs/STYLE.md; docs/guide/README.md links every guide page.
|
||||
import os, re, sys
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
@@ -347,7 +348,7 @@ for dom in sorted(os.listdir(os.path.join(SRC, "codecs"))):
|
||||
modules += ["codecs/%s/%s" % (dom, n) for n in sorted(module_names("codecs/" + dom))]
|
||||
modules += ["containers/" + n for n in sorted(module_names("containers"))]
|
||||
modules += ["core/" + n for n in sorted(module_names("core"))]
|
||||
for doc in ("README.md", os.path.join("docs", "STYLE.md")):
|
||||
for doc in (os.path.join("docs", "STYLE.md"),):
|
||||
path = os.path.join(ROOT, doc)
|
||||
ln, block = layout_block(path)
|
||||
if not block:
|
||||
@@ -357,23 +358,21 @@ for doc in ("README.md", os.path.join("docs", "STYLE.md")):
|
||||
if not re.search(r"(?<![\w/])" + re.escape(m.rsplit("/", 1)[1]) + r"\b", block):
|
||||
bad(path, ln, "DOCS: the layout block does not list %s" % m)
|
||||
|
||||
LABELS = {"image": "images", "audio": "audio", "video": "video", "model": "3D models", "cad": "CAD", "font": "fonts",
|
||||
"archive": "archives", "data": "data", "vector": "vector graphics and tile maps", "layered": "layered images",
|
||||
"subtitle": "subtitles", "music": "music", "playlist": "playlists"}
|
||||
counts = {}
|
||||
for line in open(os.path.join(ROOT, "docs", "FORMATS.md"), encoding="utf-8"):
|
||||
cells = [c.strip() for c in line.split("|")]
|
||||
if len(cells) > 3 and cells[1] in LABELS:
|
||||
counts[cells[1]] = counts.get(cells[1], 0) + 1
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import gen_registry
|
||||
readme = os.path.join(ROOT, "README.md")
|
||||
rtext = open(readme, encoding="utf-8").read()
|
||||
m = re.search(r"(\d+) formats:", rtext)
|
||||
if not m or int(m.group(1)) != sum(counts.values()):
|
||||
bad(readme, 1, "DOCS: README.md should say \"%d formats:\" (docs/FORMATS.md)" % sum(counts.values()))
|
||||
for cat, label in LABELS.items():
|
||||
m = re.search(r"\s+".join(map(re.escape, label.split())) + r"\s+\((\d+)\)", rtext)
|
||||
if not m or int(m.group(1)) != counts.get(cat, 0):
|
||||
bad(readme, 1, "DOCS: README.md should say \"%s (%d)\" (docs/FORMATS.md)" % (label, counts.get(cat, 0)))
|
||||
want = gen_registry.readme(gen_registry.scan(), readme)
|
||||
for tag in ("formats", "codecs"):
|
||||
begin, end = "<!-- %s:begin -->" % tag, "<!-- %s:end -->" % tag
|
||||
if begin not in rtext or end not in rtext:
|
||||
bad(readme, 1, "DOCS: README.md has no generated %s section (%s ... %s)" % (tag, begin, end))
|
||||
if rtext != want:
|
||||
bad(readme, 1, "DOCS: README.md's generated format / codec sections are out of date (python3 -I tools/gen_registry.py)")
|
||||
for link in ["docs/guide/" + n for n in sorted(os.listdir(os.path.join(ROOT, "docs", "guide"))) if n.endswith(".md")] + \
|
||||
["docs/API.md", "docs/STYLE.md"]:
|
||||
if "](%s)" % link not in rtext:
|
||||
bad(readme, 1, "DOCS: README.md does not link %s" % link)
|
||||
|
||||
guide = os.path.join(ROOT, "docs", "guide")
|
||||
gindex = open(os.path.join(guide, "README.md"), encoding="utf-8").read()
|
||||
|
||||
+35
-8
@@ -1,33 +1,60 @@
|
||||
#!/usr/bin/env bash
|
||||
# Tests (bash tools/test.sh [filter]): generate the fixtures (tools/fixtures.py -> tests/gen), regenerate the registry,
|
||||
# build both targets (tools/build.py), then run every tests/**/*.luau twice: under `luau --codegen -O2` (the source,
|
||||
# through the .luaurc aliases) and under `luajit` (build/luajit/tests/**/*.lua, with the compat prelude), then the lint.
|
||||
# build both targets (tools/build.py: the module trees in build/_modules and the bundles build/Rosetta.luau,
|
||||
# build/rosetta.lua), then run every tests/**/*.luau twice: under `luau --codegen -O2` (the source, through the
|
||||
# .luaurc aliases) and under `luajit` (build/_modules/luajit/tests/**/*.lua, with the compat prelude). The api test and
|
||||
# the docs / example tests run once more against the bundles (build/Rosetta.luau under luau, build/rosetta.lua under
|
||||
# LuaJIT; tools/bundle.py --stage-tests). Then the lint, and a check that the committed bundles are up to date.
|
||||
# A filter runs only the tests whose path contains it (and the fixture generators whose name contains it), and skips
|
||||
# the lint. RUNTIMES="luau" or "luajit" runs one runtime only.
|
||||
# the lint and the bundle check. RUNTIMES="luau" or "luajit" runs one runtime only.
|
||||
cd "$(dirname "$0")/.." || exit 1
|
||||
LUAU=${LUAU:-$(command -v luau || nix shell nixpkgs#luau -c sh -c 'command -v luau')}
|
||||
LUAJIT=${LUAJIT:-$(command -v luajit || nix shell nixpkgs#luajit -c sh -c 'command -v luajit')}
|
||||
export LUAJIT
|
||||
RUNTIMES=${RUNTIMES:-"luau luajit"}
|
||||
LJPATH='package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path'
|
||||
LJPATH='package.path = "build/_modules/luajit/?.lua;build/_modules/luajit/?/init.lua;" .. package.path'
|
||||
# the bundle first: rosetta and rosetta._compat come from build/rosetta.lua, tests.* from the module build
|
||||
LJBUNDLE='package.path = "build/?.lua;build/_modules/luajit/?.lua;build/_modules/luajit/?/init.lua;" .. package.path; require("rosetta")'
|
||||
BUNDLES="build/Rosetta.luau build/rosetta.lua build/Rosetta.luau.linemap.json build/rosetta.lua.linemap.json"
|
||||
fail=0
|
||||
python3 -I tools/fixtures.py $1 || { echo "FAILED: fixtures"; exit 1; }
|
||||
python3 -I tools/gen_registry.py > /dev/null || { echo "FAILED: gen_registry"; exit 1; }
|
||||
python3 -I tools/build.py || { echo "FAILED: build"; exit 1; }
|
||||
python3 -I tools/bundle.py --stage-tests > /dev/null || { echo "FAILED: bundle --stage-tests"; exit 1; }
|
||||
passed=0
|
||||
run() { # run <test label> <runtime> <command...>
|
||||
local t=$1 rt=$2
|
||||
shift 2
|
||||
echo "== $t ($rt)"
|
||||
if "$@"; then passed=$((passed + 1)); else echo "FAILED: $t ($rt)"; fail=1; fi
|
||||
}
|
||||
for t in $(find tests -name '*.luau' -not -path 'tests/gen/*' -not -path 'tests/fixtures/*' -not -name 'T.luau' -not -name '_*' | sort); do
|
||||
[ -n "$1" ] && [[ "$t" != *$1* ]] && continue
|
||||
for rt in $RUNTIMES; do
|
||||
echo "== $t ($rt)"
|
||||
if [ "$rt" = luau ]; then
|
||||
"$LUAU" --codegen -O2 "$t" || { echo "FAILED: $t ($rt)"; fail=1; continue; }
|
||||
run "$t" luau "$LUAU" --codegen -O2 "$t"
|
||||
else
|
||||
"$LUAJIT" -e "$LJPATH" "build/luajit/${t%.luau}.lua" || { echo "FAILED: $t ($rt)"; fail=1; continue; }
|
||||
run "$t" luajit "$LUAJIT" -e "$LJPATH" "build/_modules/luajit/${t%.luau}.lua"
|
||||
fi
|
||||
done
|
||||
done
|
||||
for t in $(cd build/_modules/bundle_tests/luau && find . -name '*.luau' | sed 's#^\./##' | sort); do
|
||||
[ -n "$1" ] && [[ "tests/$t" != *$1* ]] && continue
|
||||
for rt in $RUNTIMES; do
|
||||
if [ "$rt" = luau ]; then
|
||||
run "tests/$t" "luau, build/Rosetta.luau" "$LUAU" --codegen -O2 "build/_modules/bundle_tests/luau/$t"
|
||||
else
|
||||
run "tests/$t" "luajit, build/rosetta.lua" "$LUAJIT" -e "$LJBUNDLE" "build/_modules/bundle_tests/luajit/${t%.luau}.lua"
|
||||
fi
|
||||
passed=$((passed + 1))
|
||||
done
|
||||
done
|
||||
if [ -z "$1" ]; then
|
||||
bash tools/lint.sh || fail=1
|
||||
if [ -n "$(git status --porcelain -- $BUNDLES)" ]; then
|
||||
git status --short -- $BUNDLES
|
||||
echo "FAILED: the bundles in build/ differ from the committed ones (tools/build.py rewrote them): commit them"
|
||||
fail=1
|
||||
fi
|
||||
fi
|
||||
[ $fail -eq 0 ] && echo "rosetta: all tests passed ($passed runs)" || echo "rosetta: FAILURES"
|
||||
exit $fail
|
||||
Reference in new issue
Block a user