Lua stack frame refactor

This commit is contained in:
Zef Hemel
2024-10-20 15:06:23 +02:00
parent 64c98678bc
commit 8acb112e4e
14 changed files with 300 additions and 201 deletions
+31 -17
View File
@@ -1,9 +1,12 @@
import { parse } from "$common/space_lua/parse.ts";
import { luaBuildStandardEnv } from "$common/space_lua/stdlib.ts";
import { LuaEnv, type LuaRuntimeError } from "$common/space_lua/runtime.ts";
import {
LuaEnv,
type LuaRuntimeError,
LuaStackFrame,
} from "$common/space_lua/runtime.ts";
import { evalStatement } from "$common/space_lua/eval.ts";
import { assert } from "@std/assert/assert";
Deno.test("Lua language tests", async () => {
// Read the Lua file
const luaFile = await Deno.readTextFile(
@@ -11,9 +14,10 @@ Deno.test("Lua language tests", async () => {
);
const chunk = parse(luaFile, {});
const env = new LuaEnv(luaBuildStandardEnv());
const sf = new LuaStackFrame(new LuaEnv(), chunk.ctx);
try {
await evalStatement(chunk, env);
await evalStatement(chunk, env, sf);
} catch (e: any) {
console.error(`Error evaluating script:`, toPrettyString(e, luaFile));
assert(false);
@@ -21,22 +25,32 @@ Deno.test("Lua language tests", async () => {
});
function toPrettyString(err: LuaRuntimeError, code: string): string {
if (!err.context || !err.context.from || !err.context.to) {
if (!err.sf || !err.sf.astCtx?.from || !err.sf.astCtx?.to) {
return err.toString();
}
const from = err.context.from;
// Find the line and column
let line = 1;
let column = 0;
for (let i = 0; i < from; i++) {
if (code[i] === "\n") {
line++;
column = 0;
} else {
column++;
let traceStr = "";
let current: LuaStackFrame | undefined = err.sf;
while (current) {
const ctx = current.astCtx;
if (!ctx || !ctx.from || !ctx.to) {
break;
}
// Find the line and column
let line = 1;
let column = 0;
for (let i = 0; i < ctx.from; i++) {
if (code[i] === "\n") {
line++;
column = 0;
} else {
column++;
}
}
traceStr += `* ${ctx.ref || "(unknown source)"} @ ${line}:${column}:\n ${
code.substring(ctx.from, ctx.to)
}\n`;
current = current.parent;
}
return `LuaRuntimeError: ${err.message} at ${line}:${column}:\n ${
code.substring(from, err.context.to)
}`;
return `LuaRuntimeError: ${err.message} ${traceStr}`;
}