-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathrunner.ts
48 lines (45 loc) · 1.82 KB
/
runner.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// This is a mashup of tutorials from:
//
// - https://github.com/AssemblyScript/wabt.js/
// - https://developer.mozilla.org/en-US/docs/WebAssembly/Using_the_JavaScript_API
import wabt from 'wabt';
import * as compiler from './compiler';
import {parse} from './parser';
// NOTE(joe): This is a hack to get the CLI Repl to run. WABT registers a global
// uncaught exn handler, and this is not allowed when running the REPL
// (https://nodejs.org/api/repl.html#repl_global_uncaught_exceptions). No reason
// is given for this in the docs page, and I haven't spent time on the domain
// module to figure out what's going on here. It doesn't seem critical for WABT
// to have this support, so we patch it away.
if(typeof process !== "undefined") {
const oldProcessOn = process.on;
process.on = (...args : any) : any => {
if(args[0] === "uncaughtException") { return; }
else { return oldProcessOn.apply(process, args); }
};
}
export async function run(source : string, config: any) : Promise<number> {
const wabtInterface = await wabt();
const parsed = parse(source);
var returnType = "";
var returnExpr = "";
const lastExpr = parsed[parsed.length - 1]
if(lastExpr.tag === "expr") {
returnType = "(result i32)";
returnExpr = "(local.get $$last)"
}
const compiled = compiler.compile(source);
const importObject = config.importObject;
const wasmSource = `(module
(func $print (import "imports" "print") (param i32) (result i32))
(func (export "exported_func") ${returnType}
${compiled.wasmSource}
${returnExpr}
)
)`;
const myModule = wabtInterface.parseWat("test.wat", wasmSource);
var asBinary = myModule.toBinary({});
var wasmModule = await WebAssembly.instantiate(asBinary.buffer, importObject);
const result = (wasmModule.instance.exports.exported_func as any)();
return result;
}