Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 42 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,40 +15,66 @@ $> npm install binaryen
```

```js
import binaryen from "binaryen";
import {
Module,
createType,
i32 as I32,
} from "binaryen";

/*
(func (export "add") $add (param $0 i32) (param $1 i32) (result i32)
⋮ (local $2 i32)
⋮ (local.set $2
⋮ ⋮ (i32.add
⋮ ⋮ ⋮ (local.get $0)
⋮ ⋮ ⋮ (local.get $1)
⋮ ⋮ )
⋮ )
⋮ (return
⋮ ⋮ (local.get $2)
⋮ )
)

Let's build above wasm function using binaryen IR
*/

// Create a module with a single function
var myModule = new binaryen.Module();

myModule.addFunction("add", binaryen.createType([ binaryen.i32, binaryen.i32 ]), binaryen.i32, [ binaryen.i32 ],
myModule.block(null, [
myModule.local.set(2,
myModule.i32.add(
myModule.local.get(0, binaryen.i32),
myModule.local.get(1, binaryen.i32)
const mod = new Module();
const { local, i32 } = mod;

mod.addFunction("add", createType([ I32, I32 ]), I32, [ I32 ],
mod.block(null, [ // entry block (usually not visible in wat/wast)
local.set(2,
i32.add(
local.get(0, I32),
local.get(1, I32)
)
),
myModule.return(
myModule.local.get(2, binaryen.i32)
mod.return(
local.get(2, I32)
)
])
);
myModule.addFunctionExport("add", "add");
mod.addFunctionExport("add", "add");

// Optimize the module using default passes and levels
myModule.optimize();
mod.optimize();

// Validate the module
if (!myModule.validate())
if (!mod.validate())
throw new Error("validation error");

// Generate text format and binary
var textData = myModule.emitText();
var wasmData = myModule.emitBinary();
var textData = mod.emitText();
var wasmData = mod.emitBinary();

// Free resources
mod.dispose();

// Example usage with the WebAssembly API
var compiled = new WebAssembly.Module(wasmData);
var instance = new WebAssembly.Instance(compiled, {});

console.log(instance.exports.add(41, 1));
```

Expand Down