binaryen.js is a port of Binaryen to the Web, allowing you to generate WebAssembly using a JavaScript API.
$> npm install binaryen
import binaryen from "binaryen";
// 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)
)
),
myModule.return(
myModule.local.get(2, binaryen.i32)
)
])
);
myModule.addFunctionExport("add", "add");
// Optimize the module using default passes and levels
myModule.optimize();
// Validate the module
if (!myModule.validate())
throw new Error("validation error");
// Generate text format and binary
var textData = myModule.emitText();
var wasmData = myModule.emitBinary();
// 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));The buildbot also publishes nightly versions once a day if there have been changes. The latest nightly can be installed through
$> npm install binaryen@nightly
or you can use one of the previous versions instead if necessary.
- From GitHub via jsDelivr:
https://cdn.jsdelivr.net/gh/AssemblyScript/binaryen.js@VERSION/index.js - From npm via jsDelivr:
https://cdn.jsdelivr.net/npm/binaryen@VERSION/index.js - From npm via unpkg:
https://unpkg.com/binaryen@VERSION/index.js
Replace VERSION with a specific version or omit it (not recommended in production) to use main/latest.
The package includes Node.js builds of Binaryen's command line tools: wasm-shell, wasm-opt, wasm-metadce, wasm2js, wasm-as, wasm-dis, wasm-ctor-eval, wasm-reduce and wasm-merge.
Please note that the Binaryen API is evolving fast and that definitions and documentation provided by the package tend to get out of sync despite our best efforts. It's a bot after all. If you rely on binaryen.js and spot an issue, please consider sending a PR our way by updating index.d.ts and README.md to reflect the current API.
- Types
- Module construction
- Module manipulation
- Module validation
- Module optimization
- Module creation
- Expression construction
- Control flow
- Variable accesses
- Integer operations
- Floating point operations
- Datatype conversions
- Function calls
- Linear memory accesses
- Host operations
- Bulk memory operations
- Sign extension operations
- Reference types operations
- Vector operations
- Multi-value operations
- Atomic memory accesses 🦄
- Atomic read-modify-write operations 🦄
- Atomic wait and notify operations 🦄
- Exception handling operations 🦄
- Expression manipulation
- Relooper
- Source maps
- Debugging
Future features 🦄 might not be supported by all runtimes.
-
none:
Type
The none type, e.g.,void. -
i32:
Type
32-bit integer type. -
i64:
Type
64-bit integer type. -
f32:
Type
32-bit float type. -
f64:
Type
64-bit float (double) type. -
v128:
Type
128-bit vector type. 🦄 -
funcref:
Type
A function reference. 🦄 -
externref:
Type
An external (host) reference. 🦄 -
anyref:
Type
Any (top type) reference. 🦄 -
eqref:
Type
Equal reference. 🦄 -
i31ref:
Type
i31 reference. 🦄 -
structref:
Type
Structure reference. 🦄 -
stringref:
Type
String reference. 🦄 -
unreachable:
Type
Special type indicating unreachable code when obtaining information about an expression. -
auto:
Type
Special type used in Module#block exclusively. Lets the API figure out a block's result type automatically. -
createType(types:
Type[]):Type
Creates a multi-value type from an array of types. -
expandType(type:
Type):Type[]
Expands a multi-value type to an array of types.
-
new Module()
Constructs a new module. -
parseText(text:
string):Module
Creates a module from Binaryen's s-expression text format (not official stack-style text format). -
readBinary(data:
Uint8Array):Module
Creates a module from binary data.
-
Module#addFunction(name:
string, params:Type, results:Type, vars:Type[], body:ExpressionRef):FunctionRef
Adds a function.varsindicate additional locals, in the given order. -
Module#getFunction(name:
string):FunctionRef
Gets a function, by name, -
Module#removeFunction(name:
string):void
Removes a function, by name. -
Module#getNumFunctions():
number
Gets the number of functions within the module. -
Module#getFunctionByIndex(index:
number):FunctionRef
Gets the function at the specified index. -
Module#addFunctionImport(internalName:
string, externalModuleName:string, externalBaseName:string, params:Type, results:Type):void
Adds a function import. -
Module#addTableImport(internalName:
string, externalModuleName:string, externalBaseName:string):void
Adds a table import. There's just one table for now, using name"0". -
Module#addMemoryImport(internalName:
string, externalModuleName:string, externalBaseName:string):void
Adds a memory import. There's just one memory for now, using name"0". -
Module#addGlobalImport(internalName:
string, externalModuleName:string, externalBaseName:string, globalType:Type):void
Adds a global variable import. Imported globals must be immutable. -
Module#addFunctionExport(internalName:
string, externalName:string):ExportRef
Adds a function export. -
Module#addTableExport(internalName:
string, externalName:string):ExportRef
Adds a table export. There's just one table for now, using name"0". -
Module#addMemoryExport(internalName:
string, externalName:string):ExportRef
Adds a memory export. There's just one memory for now, using name"0". -
Module#addGlobalExport(internalName:
string, externalName:string):ExportRef
Adds a global variable export. Exported globals must be immutable. -
Module#getNumExports():
number
Gets the number of exports witin the module. -
Module#getExportByIndex(index:
number):ExportRef
Gets the export at the specified index. -
Module#removeExport(externalName:
string):void
Removes an export, by external name. -
Module#addGlobal(name:
string, type:Type, mutable:number, value:ExpressionRef):GlobalRef
Adds a global instance variable. -
Module#getGlobal(name:
string):GlobalRef
Gets a global, by name, -
Module#removeGlobal(name:
string):void
Removes a global, by name. -
Module#setMemory(initial:
number, maximum:number, exportName:string | null, segments:MemorySegment[], shared?:boolean):void
Sets the memory. There's just one memory for now, using name"0". ProvidingexportNamealso creates a memory export.- MemorySegment#offset:
ExpressionRef - MemorySegment#data:
Uint8Array - MemorySegment#passive:
boolean
- MemorySegment#offset:
-
Module#getNumMemorySegments():
number
Gets the number of memory segments within the module. -
Module#getMemorySegmentInfo(name:
string):MemorySegmentInfo
Gets information about the memory segment at the specified index.- MemorySegmentInfo#offset:
number - MemorySegmentInfo#data:
Uint8Array - MemorySegmentInfo#passive:
boolean
- MemorySegmentInfo#offset:
-
Module#getStart():
FunctionRef
Gets the start function, if any. -
Module#setStart(start:
FunctionRef):void
Sets the start function. -
Module#getFeatures():
Features
Gets the WebAssembly features enabled for this module.Note that the return value may be a bitmask indicating multiple features. Possible feature flags are:
- Features.MVP:
Features - Features.Atomics:
Features - Features.BulkMemory:
Features - Features.MutableGlobals:
Features - Features.NontrappingFPToInt:
Features - Features.SignExt:
Features - Features.SIMD128:
Features - Features.ExceptionHandling:
Features - Features.TailCall:
Features - Features.ReferenceTypes:
Features - Features.Multivalue:
Features - Features.StackSwitching:
Features - Features.SharedEverything:
Features - Features.FP16:
Features - Features.BulkMemoryOpt:
Features - Features.CallIndirectOverlong:
Features - Features.All:
Features
- Features.MVP:
-
Module#setFeatures(features:
Features):void
Sets the WebAssembly features enabled for this module. -
Module#addCustomSection(name:
string, contents:Uint8Array):void
Adds a custom section to the binary. -
getFunctionInfo(ftype:
FunctionRef:FunctionInfo
Obtains information about a function.- FunctionInfo#name:
string - FunctionInfo#module:
string | null(if imported) - FunctionInfo#base:
string | null(if imported) - FunctionInfo#type:
Type - FunctionInfo#params:
Type - FunctionInfo#results:
Type - FunctionInfo#vars:
Type - FunctionInfo#body:
ExpressionRef
- FunctionInfo#name:
-
getGlobalInfo(global:
GlobalRef):GlobalInfo
Obtains information about a global.- GlobalInfo#name:
string - GlobalInfo#module:
string | null(if imported) - GlobalInfo#base:
string | null(if imported) - GlobalInfo#type:
Type - GlobalInfo#mutable:
boolean - GlobalInfo#init:
ExpressionRef
- GlobalInfo#name:
-
getTableInfo(table:
TableRef):TableInfo
Obtains information about a table.- TableInfo#name:
string - TableInfo#module:
string | null(if imported) - TableInfo#base:
string | null(if imported) - TableInfo#initial:
number; - TableInfo#max?:
number;
- TableInfo#name:
-
getExportInfo(export_:
ExportRef):ExportInfo
Obtains information about an export.- ExportInfo#kind:
ExternalKind - ExportInfo#name:
string - ExportInfo#value:
string
Possible
ExternalKindvalues are:- ExternalFunction:
ExternalKind - ExternalTable:
ExternalKind - ExternalMemory:
ExternalKind - ExternalGlobal:
ExternalKind - ExternalTag:
ExternalKind
- ExportInfo#kind:
-
getTagInfo(tag:
TagRef):TagInfo
Obtains information about a tag.- TagInfo#name:
string - TagInfo#module:
string | null(if imported) - TagInfo#base:
string | null(if imported) - TagInfo#params:
Type - TagInfo#results:
Type
- TagInfo#name:
-
getSideEffects(expr:
ExpressionRef, features:FeatureFlags):SideEffects
Gets the side effects of the specified expression.- SideEffects.None:
SideEffects - SideEffects.Branches:
SideEffects - SideEffects.Calls:
SideEffects - SideEffects.ReadsLocal:
SideEffects - SideEffects.WritesLocal:
SideEffects - SideEffects.ReadsGlobal:
SideEffects - SideEffects.WritesGlobal:
SideEffects - SideEffects.ReadsMemory:
SideEffects - SideEffects.WritesMemory:
SideEffects - SideEffects.ReadsTable:
SideEffects - SideEffects.WritesTable:
SideEffects - SideEffects.ImplicitTrap:
SideEffects - SideEffects.IsAtomic:
SideEffects - SideEffects.Throws:
SideEffects - SideEffects.DanglingPop:
SideEffects - SideEffects.TrapsNeverHappen:
SideEffects - SideEffects.Any:
SideEffects
- SideEffects.None:
- Module#validate():
boolean
Validates the module. Returnstrueif valid, otherwise prints validation errors and returnsfalse.
-
Module#optimize():
void
Optimizes the module using the default optimization passes. -
Module#optimizeFunction(func:
FunctionRef | string):void
Optimizes a single function using the default optimization passes. -
Module#runPasses(passes:
string[]):void
Runs the specified passes on the module. -
Module#runPassesOnFunction(func:
FunctionRef | string, passes:string[]):void
Runs the specified passes on a single function. -
getOptimizeLevel():
number
Gets the currently set optimize level.0,1,2correspond to-O0,-O1,-O2(default), etc. -
setOptimizeLevel(level:
number):void
Sets the optimization level to use.0,1,2correspond to-O0,-O1,-O2(default), etc. -
getShrinkLevel():
number
Gets the currently set shrink level.0,1,2correspond to-O0,-Os(default),-Oz. -
setShrinkLevel(level:
number):void
Sets the shrink level to use.0,1,2correspond to-O0,-Os(default),-Oz. -
getDebugInfo():
boolean
Gets whether generating debug information is currently enabled or not. -
setDebugInfo(on:
boolean):void
Enables or disables debug information in emitted binaries. -
getTrapsNeverHappen():
boolean
Gets whether no traps can be considered reached at runtime when optimizing. -
setTrapsNeverHappen(on:
boolean):void
Enables or disables whether no traps can be considered reached at runtime when optimizing. -
getClosedWorld():
boolean
Gets whether considering that the code outside of the module does not inspect or interact with GC and function references. -
setClosedWorld(on:
boolean):void
Enables or disables whether considering that the code outside of the module does not inspect or interact with GC and function references. -
getLowMemoryUnused():
boolean
Gets whether the low 1K of memory can be considered unused when optimizing. -
setLowMemoryUnused(on:
boolean):void
Enables or disables whether the low 1K of memory can be considered unused when optimizing. -
getZeroFilledMemory():
boolean
Gets whether an imported memory is considered zero-initialized. -
setZeroFilledMemory(on:
boolean):void
Enables or disables whether an imported memory is considered zero-initialized. -
getFastMath():
boolean
Gets whether fast math optimizations are enabled, ignoring for example corner cases of floating-point math like NaN changes. -
setFastMath(on:
boolean):void
Enables or disables fast math optimizations, ignoring for example corner cases of floating-point math like NaN changes. -
getGenerateStackIR():
boolean
Gets whether to generate StackIR during binary writing. -
setGenerateStackIR(on:
boolean):void
Enable or disable StackIR generation during binary writing. -
getOptimizeStackIR():
boolean
Gets whether to optimize StackIR during binary writing. -
setOptimizeStackIR(on:
boolean):void
Enable or disable StackIR optimisation during binary writing. -
getPassArgument(key:
string):string | null
Gets the value of the specified arbitrary pass argument. -
setPassArgument(key:
string, value:string | null):void
Sets the value of the specified arbitrary pass argument. Removes the respective argument ifvalueisnull. -
clearPassArguments():
void
Clears all arbitrary pass arguments. -
hasPassToSkip(pass:
string):boolean
Gets whether a pass is in the set of passes to skip. -
addPassToSkip(pass:
string):void
Add a pass to the set of passes to skip. -
clearPassesToSkip():
void
Clears the set of passes to skip. -
getAlwaysInlineMaxSize():
number
Gets the function size at which we always inline. -
setAlwaysInlineMaxSize(size:
number):void
Sets the function size at which we always inline. -
getFlexibleInlineMaxSize():
number
Gets the function size which we inline when functions are lightweight. -
setFlexibleInlineMaxSize(size:
number):void
Sets the function size which we inline when functions are lightweight. -
getOneCallerInlineMaxSize():
number
Gets the function size which we inline when there is only one caller. -
setOneCallerInlineMaxSize(size:
number):void
Sets the function size which we inline when there is only one caller.
-
Module#emitBinary():
Uint8Array
Returns the module in binary format. -
Module#emitBinary(sourceMapUrl:
string | null):BinaryWithSourceMap
Returns the module in binary format with its source map. IfsourceMapUrlisnull, source map generation is skipped.- BinaryWithSourceMap#binary:
Uint8Array - BinaryWithSourceMap#sourceMap:
string | null
- BinaryWithSourceMap#binary:
-
Module#emitText():
string
Returns the module in Binaryen's s-expression text format (not official stack-style text format). -
Module#emitStackIR():
string
Returns the module in official stack-style text format. -
Module#emitAsmjs():
string
Returns the asm.js representation of the module. -
Module#dispose():
void
Releases the resources held by the module once it isn't needed anymore.
-
Module#block(label:
string | null, children:ExpressionRef[], resultType?:Type):ExpressionRef
Creates a block.resultTypedefaults tonone. -
Module#if(condition:
ExpressionRef, ifTrue:ExpressionRef, ifFalse?:ExpressionRef):ExpressionRef
Creates an if or if/else combination. -
Module#loop(label:
string | null, body:ExpressionRef):ExpressionRef
Creates a loop. -
Module#br(label:
string, condition?:ExpressionRef, value?:ExpressionRef):ExpressionRef
Creates a branch (br) to a label. -
Module#switch(labels:
string[], defaultLabel:string, condition:ExpressionRef, value?:ExpressionRef):ExpressionRef
Creates a switch (br_table). -
Module#