@onda-lang/binaryen-web 0.5.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Francesco Cameli
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,168 @@
1
+ # Onda Binaryen Web Backend
2
+
3
+ This package consumes Onda's versioned MIR as compact MessagePack, JSON, or an already-decoded
4
+ object and emits an executable WebAssembly DSP module with Binaryen.js. It runs in browsers and Node
5
+ without LLVM, `wasm-ld`, or an Onda toolchain in the code-generation environment.
6
+
7
+ This is the supported low-level MIR backend. Applications starting from Onda source should normally
8
+ use [`@onda-lang/wasm-compiler`](../onda_wasm_compiler/README.md), which packages the browser
9
+ frontend and this backend behind one typed source/project API and the `onda-wasm` CLI.
10
+
11
+ Compatibility status: this package implements the current MIR schema and consumes output from
12
+ `onda compile --emit mir-messagepack`, `--emit mir-json`, and `crates/onda_compiler_web`. It validates explicit control-mirror
13
+ IDs/persistence, checked `make_slice`, fixed-array and slice reference windows, and current-schema
14
+ function attributes before code generation.
15
+
16
+ ```js
17
+ import {
18
+ compileTrustedMir,
19
+ } from "@onda-lang/binaryen-web";
20
+
21
+ const mir = await fetch("patch.mir.msgpack").then((response) => response.arrayBuffer());
22
+ const { wasm, metadata } = compileTrustedMir(mir);
23
+ const instance = await WebAssembly.instantiate(wasm);
24
+ ```
25
+
26
+ `compileTrustedMir` accepts only output from Onda's semantic MIR producer, which owns the complete
27
+ validator proof including bounds, types, structured definite assignment, and resource legality.
28
+ The package intentionally does not expose a partial validator for downloaded or hand-authored MIR:
29
+ such a boundary would need to reproduce every invariant enforced by `onda_mir`. The function accepts
30
+ a JSON string, a MessagePack `ArrayBuffer`/typed-array view, or a decoded object. JSON remains useful
31
+ for inspection; the browser compiler and test corpus use MessagePack as the production transport.
32
+
33
+ The generated module exports `memory`, `__heap_base`, `onda_init(params_ptr, state_ptr)`, the
34
+ 11-argument processor `onda_process`, and one `onda_event_N` function per declared event. These are
35
+ the complete wasm32-module profile of the generic
36
+ [`Onda processor ABI`](../../docs/processor-abi.md), not a Web Audio-specific interface. The host
37
+ owns allocation in linear memory. Metadata contains resolved target/integration facts,
38
+ state/parameter layouts, state-backed control-output offsets, flattened audio-port channels, packed
39
+ event payload layouts, and all exported ABI names.
40
+
41
+ `createProcessorArtifactFiles()` validates the final module, computes a SHA-256 digest, and returns
42
+ a reusable `.wasm` plus `.onda.json` descriptor pair. `validateProcessorArtifact`,
43
+ `parseProcessorMetadata`, and `serializeProcessorMetadata` are also exported for loaders. The
44
+ `loadProcessorArtifactFiles()` validates both files and verifies their SHA-256 association before
45
+ returning an artifact. The package includes TypeScript declarations and is publishable as
46
+ `@onda-lang/binaryen-web`.
47
+
48
+ The executable backend supports:
49
+
50
+ - scalar locals, value parameters, state, and runtime parameters
51
+ - scalar and fixed scalar-array state/parameter/audio-port addressing
52
+ - constants, casts, arithmetic, comparisons, structured `if`/loop control, calls, and scalar or multi-value returns
53
+ - input loads, output stores, and immutable constant-data loads
54
+ - scalar/fixed-array event payload loads and event ABI wrappers
55
+ - scalar/fixed-array control-output stores in the shared state blob
56
+ - interleaved mono/static/dynamic external buffers, including reads, writes, bounds modes, and runtime metadata queries
57
+ - checked slice construction plus fixed-array/slice reference windows
58
+ - address-taken scalar locals legalized through per-function reference scratch storage
59
+ - SIMD contiguous slice fill with a scalar tail and bulk-memory contiguous slice copy
60
+ - current-schema function attributes as validated, portable optimization hints
61
+ - native WebAssembly numeric intrinsics plus on-demand internal transcendental and strict-FMA helpers
62
+ - Binaryen validation and optimization before emission
63
+
64
+ The backend also supports primitive slice locals and reference arguments, event slices, flattened data structs, structure-of-arrays processor state, recursive processor arrays, and canonical top-level/processor oversampling schedules. Oversampling interpolation, substeps, sinc-filter state updates, and output decimation are ordinary MIR operations; Binaryen has no Onda-specific scheduling logic. Recursive call graphs are rejected as unbounded realtime work before fixed-array local storage can become re-entrant. Aggregate shapes that cannot be represented by portable MIR are rejected above the backend boundary.
65
+
66
+ The MIR schema defines three ordered `i32` process parameters:
67
+ `(start_frame, frames, flags)`. `process_frame(offset)` is the checked source of audio-I/O
68
+ addresses. The public 11-argument `onda_process` export keeps full-block base pointers and accepts
69
+ any segment contained in the configured block. BEGIN and END flags independently gate block hooks;
70
+ they do not assert a position or maintain a hidden ABI cursor, and zero-frame calls are valid. The
71
+ reference AudioWorklet maintains its own compile-block cursor so Web Audio render quanta may be
72
+ smaller or larger than the configured MIR block while DSP state and block-boundary hooks remain
73
+ continuous.
74
+
75
+ Emitted metadata distinguishes physical Wasm state storage from the packed persistent snapshot:
76
+ `runtime.state_size_bytes` sizes linear-memory state, while `runtime.snapshot_size_bytes` and
77
+ `metadata.states` describe the deterministic scratch-free snapshot layout shared with native MIR.
78
+
79
+ Core WebAssembly has no scalar fused multiply-add or transcendental instructions. The backend
80
+ therefore links only the required closure from an embedded, pure-Wasm math kernel into each DSP
81
+ module before Binaryen optimization. Calls remain inside one Wasm instance: generated artifacts
82
+ have no `onda_math` or exact-FMA host imports, and the AudioWorklet performs no JavaScript math on
83
+ the render path. The kernel provides the same f32/f64 `sin`, `cos`, `tan`, `tanh`, `atan`, `atan2`,
84
+ `exp`, `log`, `pow`, and strict `fma` surface as native LLVM lowering. Core Wasm instructions still
85
+ handle `sqrt`, `abs`, `floor`, `ceil`, `trunc`, `min`, and `max`; a small internal helper implements
86
+ LLVM-compatible half-away-from-zero `round`.
87
+
88
+ The kernel is a reproducible `no_std` Rust build of MIT-licensed `libm` 0.2.16. Its strict software
89
+ FMA performs one correctly rounded operation without an allocating JavaScript `BigInt` boundary.
90
+ `npm run build:math-kernel` regenerates the embedded module, while `npm run test:fma-oracle`
91
+ compares targeted edge cases and deterministic random bit patterns against Rust's native
92
+ `mul_add` oracle. Binaryen removes unused helper functions, so a program pays code size only for
93
+ the math closure it calls. `createDefaultImports()` remains as a compatibility convenience and now
94
+ returns an empty object.
95
+
96
+ Compilation defaults to Binaryen O4 for speed, strict floating-point optimization, WebAssembly
97
+ SIMD enabled, and Binaryen's ordinary inlining policy. Options are explicit and recorded in
98
+ `artifact.metadata.optimization`:
99
+
100
+ ```js
101
+ compileTrustedMir(mir, {
102
+ optimize: true,
103
+ optimizeLevel: 4, // 0..4
104
+ shrinkLevel: 0, // 0..2
105
+ fastMath: false, // opt in to relaxed floating-point rewrites
106
+ simd: true, // set false for pre-SIMD Wasm hosts
107
+ allowInliningFunctionsWithLoops: false,
108
+ emitText: false,
109
+ });
110
+ ```
111
+
112
+ Loop-containing inlining remains opt-in because controlled measurements were workload-dependent:
113
+ it helped the oversampling fixture but regressed the language and saturator fixtures. The compiler
114
+ saves and restores Binaryen's process-global optimization settings around every module, so one
115
+ compile cannot silently change another compile's numerical or inlining policy.
116
+
117
+ O4 was selected by an affinity-pinned O3/O4 A/B over language, oversampling, saturator, and complete
118
+ math workloads. It improved three workloads and left saturator effectively unchanged, at the cost
119
+ of higher one-time compilation latency. Binaryen StackIR generation remains off because it improved
120
+ some workloads but regressed others in the same matrix.
121
+
122
+ The MIR schema uses lossless scalar encoding: `i64` values are decimal strings and non-finite floats are exact hexadecimal IEEE bit patterns. The compiler and reference AudioWorklet decode both forms before constructing Wasm constants or initializing host storage.
123
+
124
+ Install the pinned Binaryen dependency and run the test layers from this directory:
125
+
126
+ ```sh
127
+ npm install
128
+ npm test
129
+ npm run test:onda
130
+ npm run test:corpus
131
+ ```
132
+
133
+ `npm test` runs current-schema backend, embedded-math-kernel, artifact, and reference-worklet fixtures. `npm run test:onda`
134
+ compiles real Onda sources, runs LLVM/MIR-Binaryen render parity through MessagePack, and verifies
135
+ exact FMA against Rust's `mul_add`; `npm run test:parity` selects only the differential renderer.
136
+ That renderer covers full/segmented/zero-frame scheduling, events, snapshots/restores, numeric edge
137
+ semantics, buffers, slices, processor arrays, and oversampling. Strict arithmetic scenarios compare
138
+ raw f32 output bits and f64 snapshot storage, with NaN payloads treated as unspecified; only scenarios
139
+ that exercise approximate transcendental kernels use numeric tolerances. The source-driven
140
+ and parity commands require the native Rust/LLVM Onda build. `npm run test:corpus` continuously
141
+ discovers every `.onda` program under `examples/` and this package's positive fixtures, compiles each
142
+ through the CLI to current-schema MIR, lowers it with Binaryen, and validates the generated Wasm. It also
143
+ requires the native build. `npm test` does not.
144
+
145
+ Run `npm run bench` for the reproducible development comparison documented in
146
+ [`docs/backend-benchmarks.md`](../../docs/backend-benchmarks.md). Those measurements validate output
147
+ and compare native LLVM JIT/processing with Binaryen compilation, Wasm instantiation, and Wasm
148
+ processing; they require the native Rust/LLVM Onda build and are not universal browser-performance
149
+ claims. The benchmark fails by default if Binaryen/Wasm beats LLVM in any checked scenario; the
150
+ report includes the current CPU affinity so heterogeneous-core placement is visible.
151
+
152
+ The embedded-compiler playground under `examples/web/onda_wasm_playground` builds the Rust compiler
153
+ with `wasm-pack`, loads this backend as an ESM module, and compiles edited source to executable DSP
154
+ Wasm inside the page. The separate `examples/web/onda_wasm_aot_sample_player` example invokes this
155
+ backend at build time and ships only the resulting module and descriptor to the browser.
156
+
157
+ Current limitations are explicit:
158
+
159
+ - scalar FMA and transcendental operations are software helpers on core Wasm targets, so LLVM may
160
+ still use faster target instructions or platform libm implementations
161
+ - recursive call graphs are rejected as unbounded realtime work
162
+ - `inline: always` and `inline: never` are validated but remain advisory because Binaryen.js does
163
+ not expose per-function inline/no-inline annotations; its module optimizer chooses whether to
164
+ inline a call
165
+ - this low-level package accepts MIR rather than source; the product-facing `onda-wasm` CLI lives in
166
+ `@onda-lang/wasm-compiler`, while the native `onda compile` command does not yet emit linked Wasm
167
+ - production consumers must package/cache Binaryen; Web Audio users can use the separate optional
168
+ `@onda-lang/webaudio` adapter, while other hosts consume the generic artifact directly
@@ -0,0 +1,19 @@
1
+ rust-lang/libm as a whole is available for use under the MIT license:
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@onda-lang/binaryen-web",
3
+ "version": "0.5.0-rc.0",
4
+ "type": "module",
5
+ "description": "Binaryen backend for versioned Onda MIR in browsers and Node.js",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/onda-lang/onda.git",
10
+ "directory": "packages/onda_binaryen_web"
11
+ },
12
+ "homepage": "https://onda-lang.github.io/onda/",
13
+ "bugs": {
14
+ "url": "https://github.com/onda-lang/onda/issues"
15
+ },
16
+ "engines": {
17
+ "node": ">=20"
18
+ },
19
+ "types": "./src/index.d.ts",
20
+ "exports": {
21
+ ".": {
22
+ "types": "./src/index.d.ts",
23
+ "default": "./src/index.js"
24
+ },
25
+ "./artifact": {
26
+ "types": "./src/artifact.d.ts",
27
+ "default": "./src/artifact.js"
28
+ }
29
+ },
30
+ "files": [
31
+ "src",
32
+ "math-kernel/LICENSE-libm.txt",
33
+ "LICENSE",
34
+ "README.md"
35
+ ],
36
+ "scripts": {
37
+ "build:math-kernel": "node ./scripts/build-math-kernel.mjs",
38
+ "test": "node --test",
39
+ "test:onda": "node ./scripts/verify-language-slice.mjs && node ./scripts/verify-backend-parity.mjs && node ./scripts/verify-fma-oracle.mjs",
40
+ "test:corpus": "node ./scripts/verify-source-corpus.mjs",
41
+ "test:fma-oracle": "node ./scripts/verify-fma-oracle.mjs",
42
+ "test:parity": "node ./scripts/verify-backend-parity.mjs",
43
+ "bench": "node ./scripts/benchmark-backends.mjs",
44
+ "verify-mir": "node ./scripts/verify-mir.mjs"
45
+ },
46
+ "dependencies": {
47
+ "@onda-lang/processor-abi": "0.5.0-rc.0",
48
+ "binaryen": "130.0.0"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
52
+ }
53
+ }
@@ -0,0 +1,18 @@
1
+ export {
2
+ OndaArtifactError,
3
+ PROCESSOR_ABI_VERSION,
4
+ PROCESSOR_ARTIFACT_FORMAT,
5
+ PROCESSOR_ARTIFACT_FORMAT_VERSION,
6
+ PROCESSOR_SNAPSHOT_FORMAT_VERSION,
7
+ createProcessorArtifactFiles,
8
+ loadProcessorArtifactFiles,
9
+ parseProcessorMetadata,
10
+ serializeProcessorMetadata,
11
+ validateProcessorArtifact,
12
+ validateProcessorMetadata,
13
+ validateProcessorModule,
14
+ } from "@onda-lang/processor-abi";
15
+ export type {
16
+ OndaProcessorArtifact,
17
+ OndaProcessorMetadata,
18
+ } from "@onda-lang/processor-abi";
@@ -0,0 +1 @@
1
+ export * from "@onda-lang/processor-abi";
@@ -0,0 +1,2 @@
1
+ // Synchronized from format-versions.json; do not edit this copy directly.
2
+ export const SUPPORTED_MIR_SCHEMA_VERSION = 1;
package/src/errors.js ADDED
@@ -0,0 +1,6 @@
1
+ export class OndaBinaryenError extends Error {
2
+ constructor(message) {
3
+ super(message);
4
+ this.name = "OndaBinaryenError";
5
+ }
6
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ export const SUPPORTED_MIR_SCHEMA_VERSION: number;
2
+ export {
3
+ OndaArtifactError,
4
+ PROCESSOR_ABI_VERSION,
5
+ PROCESSOR_ARTIFACT_FORMAT,
6
+ PROCESSOR_ARTIFACT_FORMAT_VERSION,
7
+ PROCESSOR_SNAPSHOT_FORMAT_VERSION,
8
+ createProcessorArtifactFiles,
9
+ loadProcessorArtifactFiles,
10
+ parseProcessorMetadata,
11
+ serializeProcessorMetadata,
12
+ validateProcessorArtifact,
13
+ validateProcessorMetadata,
14
+ validateProcessorModule,
15
+ } from "@onda-lang/processor-abi";
16
+ export type {
17
+ OndaProcessorArtifact,
18
+ OndaProcessorMetadata,
19
+ } from "@onda-lang/processor-abi";
20
+ import type { OndaProcessorArtifact } from "@onda-lang/processor-abi";
21
+
22
+ export interface OndaBinaryenOptions {
23
+ optimize?: boolean;
24
+ optimizeLevel?: 0 | 1 | 2 | 3 | 4;
25
+ shrinkLevel?: 0 | 1 | 2;
26
+ fastMath?: boolean;
27
+ simd?: boolean;
28
+ allowInliningFunctionsWithLoops?: boolean;
29
+ emitText?: boolean;
30
+ }
31
+
32
+ export class OndaBinaryenError extends Error {}
33
+ export function compileTrustedMir(
34
+ mir: string | ArrayBuffer | ArrayBufferView | object,
35
+ options?: OndaBinaryenOptions,
36
+ ): OndaProcessorArtifact;
37
+ export function createDefaultImports(): Record<string, never>;