Skip to content

Commit

Permalink
Lua stack frame refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
zefhemel committed Oct 20, 2024
1 parent 64c9867 commit 8acb112
Show file tree
Hide file tree
Showing 14 changed files with 300 additions and 201 deletions.
9 changes: 6 additions & 3 deletions common/space_lua.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
LuaEnv,
LuaFunction,
LuaRuntimeError,
LuaStackFrame,
} from "$common/space_lua/runtime.ts";
import { parse as parseLua } from "$common/space_lua/parse.ts";
import { evalStatement } from "$common/space_lua/eval.ts";
Expand Down Expand Up @@ -39,10 +40,11 @@ export class SpaceLuaEnvironment {
const ast = parseLua(script.script, { ref: script.ref });
// We create a local scope for each script
const scriptEnv = new LuaEnv(this.env);
await evalStatement(ast, scriptEnv);
const sf = new LuaStackFrame(new LuaEnv(), ast.ctx);
await evalStatement(ast, scriptEnv, sf);
} catch (e: any) {
if (e instanceof LuaRuntimeError) {
const origin = resolveASTReference(e.context);
const origin = resolveASTReference(e.sf.astCtx!);
if (origin) {
console.error(
`Error evaluating script: ${e.message} at [[${origin.page}@${origin.pos}]]`,
Expand All @@ -62,7 +64,8 @@ export class SpaceLuaEnvironment {
if (value instanceof LuaFunction) {
console.log("Now registering Lua function", globalName);
scriptEnv.registerFunction({ name: globalName }, (...args: any[]) => {
return luaValueToJS(value.call(...args.map(jsToLuaValue)));
const sf = new LuaStackFrame(new LuaEnv(), value.body.ctx);
return luaValueToJS(value.call(sf, ...args.map(jsToLuaValue)));
});
}
}
Expand Down
11 changes: 8 additions & 3 deletions common/space_lua/eval.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { assertEquals } from "@std/assert/equals";
import {
LuaEnv,
LuaNativeJSFunction,
LuaStackFrame,
luaValueToJS,
singleResult,
} from "./runtime.ts";
Expand All @@ -11,15 +12,19 @@ import { evalExpression, evalStatement } from "./eval.ts";
import { luaBuildStandardEnv } from "$common/space_lua/stdlib.ts";

function evalExpr(s: string, e = new LuaEnv()): any {
const node = parse(`e(${s})`).statements[0] as LuaFunctionCallStatement;
const sf = new LuaStackFrame(e, node.ctx);
return evalExpression(
(parse(`e(${s})`).statements[0] as LuaFunctionCallStatement).call
.args[0],
node.call.args[0],
e,
sf,
);
}

function evalBlock(s: string, e = new LuaEnv()): Promise<void> {
return evalStatement(parse(s) as LuaBlock, e);
const node = parse(s) as LuaBlock;
const sf = new LuaStackFrame(e, node.ctx);
return evalStatement(node, e, sf);
}

Deno.test("Evaluator test", async () => {
Expand Down
Loading

0 comments on commit 8acb112

Please sign in to comment.