Onyx – DECODE https://decode.red/blog data decode, decoder or decoded ... design of code Mon, 15 Dec 2025 06:15:00 +0000 ja hourly 1 https://wordpress.org/?v=4.7.29 Onyx WebAssembly ../../../202503021870/ Sun, 02 Mar 2025 07:09:06 +0000 ../../../?p=1870 JavaScriptおよびTypeScriptが全盛の今、その周辺の技術も賑やかです。
WebAssemblyというのは、処理の高速化等で使用されますが、これにコンパイルできるOnyxという言語を試してみました。

https://onyxlang.io/

インストール)

sh <(curl https://get.onyxlang.io -sSfL)

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Onyx WebAssembly</title>
</head>
<body>
    <h1>Onyx WebAssembly</h1>
    <div>
        <button id="runButton">11 + 22</button>
        <p id="result"></p>
    </div>
    <script>
        async function loadWasm() {
            const response = await fetch('add.wasm');
            console.log(response)
            const bytes = await response.arrayBuffer();
            console.log(bytes)

            const imports = {
                "host": {
                    "print_str": (offset, length) => {
                    console.log(`WASM tried to print a string at offset ${offset} with length ${length}`);
                    }
                }
            };
            const importObject = {}

            const wasmModule = await WebAssembly.instantiate(bytes, imports);
            console.log('wasm', wasmModule)
            return wasmModule.instance.exports.add;
        }
        document.getElementById('runButton').addEventListener('click', async () => {
            const add = await loadWasm();
            console.log(add)
            const result = add(11, 22);
            document.getElementById('result').innerText = `11 + 22 = ${result}`;
        });
    </script>
</body>
</html>

#export "add"  (a: i32, b: i32) -> i32 {
    return a + b
}
main :: () {}

onyx build -o add.wasm -r js add.onyx

python3 -m http.server 8080

wasmを外部モジュールとして呼び出すサンプルです。
下記、node でもやってみました。

import fs from 'fs/promises';

async function loadWasm() {
    const bytes = await fs.readFile('./add.wasm');
    const imports = {
        "host": {
            "print_str": (offset, length) => {
    	   		console.log(`WASM tried to print a string at offset ${offset} with length ${length}`);
       		}
       }
    };
    const { instance } = await WebAssembly.instantiate(bytes, imports);
    return instance.exports.add;
}

loadWasm().then(add => {
    console.log("11 + 22 =", add(11, 22));
}).catch(console.error);

% node index.js
11 + 22 = 33

どちらでも使える共通モジュールを持つことができます。
アルゴリズムなどで利用すると便利ですね。

]]>