silverbullet/common/syscalls/lua.ts

55 lines
1.8 KiB
TypeScript
Raw Normal View History

import type { SysCallMapping } from "$lib/plugos/system.ts";
2025-02-06 18:58:27 +08:00
import { evalExpression } from "$common/space_lua/eval.ts";
import { parse, parseExpressionString } from "../space_lua/parse.ts";
import type { CommonSystem } from "$common/common_system.ts";
2025-02-08 23:51:31 +08:00
import {
LuaStackFrame,
luaToString,
luaValueToJS,
} from "$common/space_lua/runtime.ts";
2025-02-06 19:21:21 +08:00
import { buildThreadLocalEnv } from "$common/space_lua_api.ts";
2025-02-08 23:51:31 +08:00
import { isSendable } from "$lib/plugos/util.ts";
2025-02-06 18:58:27 +08:00
export function luaSyscalls(commonSystem: CommonSystem): SysCallMapping {
2024-10-11 21:34:27 +08:00
return {
"lua.parse": (_ctx, code: string) => {
return parse(code);
},
2025-02-06 18:58:27 +08:00
/**
* Evaluates a Lua expression and returns the result as a JavaScript value
* @param _ctx
* @param expression
* @returns
*/
2025-02-06 19:21:21 +08:00
"lua.evalExpression": async (_ctx, expression: string) => {
try {
const ast = parseExpressionString(expression);
const env = await buildThreadLocalEnv(
commonSystem.system,
2025-02-06 18:58:27 +08:00
commonSystem.spaceLuaEnv.env,
2025-02-06 19:21:21 +08:00
);
const sf = new LuaStackFrame(env, null);
2025-02-13 03:09:02 +08:00
const luaResult = await evalExpression(
ast,
commonSystem.spaceLuaEnv.env,
sf,
);
const jsResult = luaValueToJS(luaResult);
if (isSendable(jsResult)) {
return jsResult;
2025-02-08 23:51:31 +08:00
} else {
// This may evaluate to e.g. a function, which is not sendable, in this case we'll console.warn and return a stringified version of the result
console.warn(
"Lua eval result is not sendable, returning stringified version",
2025-02-13 03:09:02 +08:00
jsResult,
2025-02-08 23:51:31 +08:00
);
2025-02-13 03:09:02 +08:00
return luaToString(luaResult);
2025-02-08 23:51:31 +08:00
}
2025-02-06 19:21:21 +08:00
} catch (e: any) {
console.error("Lua eval error: ", e.message, e.sf?.astCtx);
throw e;
}
2025-02-06 18:58:27 +08:00
},
2024-10-11 21:34:27 +08:00
};
}