From c20a2e57400b692d877c55d13dfd10f5268ac81a Mon Sep 17 00:00:00 2001 From: Brian Carroll Date: Sat, 18 Sep 2021 23:52:18 +0100 Subject: [PATCH] Hello web is working!! --- examples/hello-web/hello-world.wasm | 1 + examples/hello-web/index.html | 12 +++++++ examples/hello-web/platform/host.js | 50 ++++++++++++++++++----------- 3 files changed, 44 insertions(+), 19 deletions(-) create mode 120000 examples/hello-web/hello-world.wasm create mode 100644 examples/hello-web/index.html diff --git a/examples/hello-web/hello-world.wasm b/examples/hello-web/hello-world.wasm new file mode 120000 index 0000000000..bdd51cc27b --- /dev/null +++ b/examples/hello-web/hello-world.wasm @@ -0,0 +1 @@ +hello-world \ No newline at end of file diff --git a/examples/hello-web/index.html b/examples/hello-web/index.html new file mode 100644 index 0000000000..cf2c92688f --- /dev/null +++ b/examples/hello-web/index.html @@ -0,0 +1,12 @@ + + +
+ + + + diff --git a/examples/hello-web/platform/host.js b/examples/hello-web/platform/host.js index b737379379..d6af6ffde0 100644 --- a/examples/hello-web/platform/host.js +++ b/examples/hello-web/platform/host.js @@ -1,31 +1,43 @@ const test_decoder = true; -function run() { - const memory = new Uint8Array(1024); +async function roc_web_platform_run(wasm_filename, dom_node) { const decoder = new TextDecoder(); + let memory_bytes; + let exit_code; function js_display_roc_string(str_bytes, str_len) { - const utf8_bytes = memory.subarray(str_bytes, str_bytes + str_len); + const utf8_bytes = memory_bytes.subarray(str_bytes, str_bytes + str_len); const js_string = decoder.decode(utf8_bytes); - console.log(js_string); + dom_node.textContent = js_string; } - if (test_decoder) { - const testAddress = 123; - const testString = "Hello, world"; + const importObj = { + wasi_snapshot_preview1: { + proc_exit: (code) => { + if (code !== 0) { + console.error(`Exited with code ${code}`); + } + exit_code = code; + }, + }, + env: { + js_display_roc_string, + }, + }; - const utf8Encoder = new TextEncoder(); - const targetBytes = memory.subarray( - testAddress, - testAddress + testString.length - ); - const { read, written } = utf8Encoder.encodeInto(testString, targetBytes); - if (written !== read) { - throw new Error("Not enough space"); + const wasm = await WebAssembly.instantiateStreaming( + fetch(wasm_filename), + importObj + ); + + memory_bytes = new Uint8Array(wasm.instance.exports.memory.buffer); + + try { + wasm.instance.exports._start(); + } catch (e) { + const is_ok = e.message === "unreachable" && exit_code === 0; + if (!is_ok) { + console.error(e); } - - js_display_roc_string(testAddress, testString.length); } } - -run();