59 lines · 2.0 KB · JavaScript
RawDownload
// wasmCompilation.js// Created by Ada <ada@thingvellir.net> on 2026-03-28// SPDX-License-Identifier: Apache-2.0"use strict"; /*(module  (import "host" "memory" (memory 1))  (import "host" "log" (func $log (param i32 i32)))   (data (i32.const 0) "Hello, world!")   (func (export "logTest")        (call $log (i32.const 0) (i32.const 13)))   (func (export "square") (param $n i32) (result i32)        (i32.mul (local.get $n) (local.get $n))))*/const moduleData = Uint8Array.from([    0x00, 0x61, 0x73, 0x6D, 0x01, 0x00, 0x00, 0x00,    0x01, 0x0E, 0x03, 0x60, 0x02, 0x7F, 0x7F, 0x00,    0x60, 0x00, 0x00, 0x60, 0x01, 0x7F, 0x01, 0x7F,    0x02, 0x1B, 0x02, 0x04, 0x68, 0x6F, 0x73, 0x74,    0x06, 0x6D, 0x65, 0x6D, 0x6F, 0x72, 0x79, 0x02,    0x00, 0x01, 0x04, 0x68, 0x6F, 0x73, 0x74, 0x03,    0x6C, 0x6F, 0x67, 0x00, 0x00, 0x03, 0x03, 0x02,    0x01, 0x02, 0x07, 0x14, 0x02, 0x07, 0x6C, 0x6F,    0x67, 0x54, 0x65, 0x73, 0x74, 0x00, 0x01, 0x06,    0x73, 0x71, 0x75, 0x61, 0x72, 0x65, 0x00, 0x02,    0x0A, 0x12, 0x02, 0x08, 0x00, 0x41, 0x00, 0x41,    0x0D, 0x10, 0x00, 0x0B, 0x07, 0x00, 0x20, 0x00,    0x20, 0x00, 0x6C, 0x0B, 0x0B, 0x13, 0x01, 0x00,    0x41, 0x00, 0x0B, 0x0D, 0x48, 0x65, 0x6C, 0x6C,    0x6F, 0x2C, 0x20, 0x77, 0x6F, 0x72, 0x6C, 0x64,    0x21,]); let memory = new WebAssembly.Memory({ initial: 1 }); console.debug("WebAssembly.instantiate"); WebAssembly.instantiate(moduleData, {    host: {        memory,        log: (ptr, length) => {            // NOTE: We don't have an equivalent to the Web's TextDecoder class,            // so we'll cheat a little and just assume each byte is ASCII            let slice = new Uint8Array(memory.buffer, ptr, length);            const str = String.fromCodePoint(...slice);             console.log(`WASM: "${str}"`);        },    }}).then(({ instance }) => {    console.debug("WASM module successfully instantiated");     console.info("square(4) =", instance.exports.square(4));    instance.exports.logTest();});