Skip to content

Instantly share code, notes, and snippets.

@laughinghan
Last active June 7, 2017 21:10
Show Gist options
  • Save laughinghan/3d38968f86d534436d3edab0d7882e13 to your computer and use it in GitHub Desktop.
Save laughinghan/3d38968f86d534436d3edab0d7882e13 to your computer and use it in GitHub Desktop.
int main() {
/* for some reason if I declare these constants outside main(){},
then the implicit imports of defString/get/set etc stop working */
const int null = 0;
const int window = 1;
int hello_world = jsString("hello world");
dispose(eval1("log(_)", hello_world));
int args = eval2("[_0, _1]", jsInt(1), jsInt(2));
dispose(eval2("_0.push(_1)", args, jsInt(3)));
dispose(eval2("_0.push(_1)", args, jsInt(4)));
dispose(eval1("log(_)", args));
return 0;
}
function str(ptr) {
return lib.UTF8ArrayToString(new Uint8Array(wasmInstance.exports.memory.buffer), ptr);
}
const WASM_VULGAR_REFS = [null, window];
const empties = [];
function ref(val) {
const ref = empties.length ? empties.pop() : WASM_VULGAR_REFS.length;
WASM_VULGAR_REFS[ref] = val;
return ref;
}
function unref(ref) {
WASM_VULGAR_REFS[ref] = null;
empties.push(ref);
}
wasmImports.env = {
jsInt: ref,
jsFloat: ref,
jsString: ptr => ref(str(ptr)),
jsArray: () => ref([]),
eval0: expr => ref(new Function('return ' + str(expr))()),
eval1: (expr, arg) =>
ref(new Function('_', 'return ' + str(expr))(WASM_VULGAR_REFS[arg])),
eval2: (expr, arg1, arg2) =>
ref(new Function('_0', '_1',
'return ' + str(expr))(WASM_VULGAR_REFS[arg1], WASM_VULGAR_REFS[arg2])),
dispose: unref,
};
var wasmModule = new WebAssembly.Module(wasmCode);
var wasmInstance = new WebAssembly.Instance(wasmModule, wasmImports);
wasmInstance.exports.main();
window.wasmInstance = wasmInstance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment