Skip to content

Commit d075097

Browse files
authored
Precompile lualib and jsonlib for tests (#983)
1 parent 0fba69b commit d075097

File tree

1 file changed

+28
-4
lines changed

1 file changed

+28
-4
lines changed

test/util.ts

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,32 @@ import * as vm from "vm";
1010
import * as tstl from "../src";
1111
import { createEmitOutputCollector } from "../src/transpilation/output-collector";
1212

13-
const minimalTestLib = fs.readFileSync(path.join(__dirname, "json.lua"), "utf8");
14-
const lualibContent = fs.readFileSync(path.resolve(__dirname, "../dist/lualib/lualib_bundle.lua"), "utf8");
13+
export function toByteCode(luaCode: string) {
14+
const L = lauxlib.luaL_newstate();
15+
16+
if (lauxlib.luaL_loadstring(L, to_luastring(luaCode)) !== lua.LUA_OK) throw Error(lua.lua_tojsstring(L, -1));
17+
18+
const writer = (_: any, newBytes: Uint8Array, size: number, data: number[]) => {
19+
data.push(...newBytes.slice(0, size));
20+
return 0;
21+
};
22+
23+
const data: number[] = [];
24+
25+
const dumpExitCode = lua.lua_dump(L, writer, data, false);
26+
27+
if (dumpExitCode !== 0) {
28+
throw Error("Unable to dump byte code");
29+
}
30+
31+
return Uint8Array.from(data);
32+
}
33+
34+
const jsonLib = fs.readFileSync(path.join(__dirname, "json.lua"), "utf8");
35+
const jsonLibByteCode = toByteCode(jsonLib);
36+
37+
const luaLib = fs.readFileSync(path.resolve(__dirname, "../dist/lualib/lualib_bundle.lua"), "utf8");
38+
const luaLibByteCode = toByteCode(luaLib);
1539

1640
// Using `test` directly makes eslint-plugin-jest consider this file as a test
1741
const defineTest = test;
@@ -345,7 +369,7 @@ export abstract class TestBuilder {
345369
// Json
346370
lua.lua_getglobal(L, "package");
347371
lua.lua_getfield(L, -1, "preload");
348-
lauxlib.luaL_loadstring(L, to_luastring(minimalTestLib));
372+
lauxlib.luaL_loadstring(L, jsonLibByteCode);
349373
lua.lua_setfield(L, -2, "json");
350374
// Lua lib
351375
if (
@@ -354,7 +378,7 @@ export abstract class TestBuilder {
354378
) {
355379
lua.lua_getglobal(L, "package");
356380
lua.lua_getfield(L, -1, "preload");
357-
lauxlib.luaL_loadstring(L, to_luastring(lualibContent));
381+
lauxlib.luaL_loadstring(L, luaLibByteCode);
358382
lua.lua_setfield(L, -2, "lualib_bundle");
359383
}
360384

0 commit comments

Comments
 (0)