summaryrefslogtreecommitdiff
path: root/test/binaryen.js/hello-world.js
diff options
context:
space:
mode:
authorAlon Zakai <alonzakai@gmail.com>2017-03-24 15:45:31 -0700
committerGitHub <noreply@github.com>2017-03-24 15:45:31 -0700
commitf1c992f946438ba8785c418e769ee024606fdde0 (patch)
treea2c91c8e21fdddbc22e9455f2c180f446fa4bf70 /test/binaryen.js/hello-world.js
parent7b71bb6b0d3966ce42b631d433c772e24d6e68be (diff)
downloadbinaryen-f1c992f946438ba8785c418e769ee024606fdde0.tar.gz
binaryen-f1c992f946438ba8785c418e769ee024606fdde0.tar.bz2
binaryen-f1c992f946438ba8785c418e769ee024606fdde0.zip
New binaryen.js (#922)
New binaryen.js implementation, based on the C API underneath and with a JS-friendly API on top. See docs under docs/ for API details.
Diffstat (limited to 'test/binaryen.js/hello-world.js')
-rw-r--r--test/binaryen.js/hello-world.js53
1 files changed, 53 insertions, 0 deletions
diff --git a/test/binaryen.js/hello-world.js b/test/binaryen.js/hello-world.js
new file mode 100644
index 000000000..c08e67342
--- /dev/null
+++ b/test/binaryen.js/hello-world.js
@@ -0,0 +1,53 @@
+
+// "hello world" type example: create a function that adds two i32s and
+// returns the result
+
+// Create a module to work on
+var module = new Binaryen.Module();
+
+// Create a function type for i32 (i32, i32) (i.e., return i32, pass two
+// i32 params)
+var iii = module.addFunctionType('iii', Binaryen.i32, [Binaryen.i32, Binaryen.i32]);
+
+// Start to create the function, starting with the contents: Get the 0 and
+// 1 arguments, and add them, then return them
+var left = module.getLocal(0, Binaryen.i32);
+var right = module.getLocal(1, Binaryen.i32);
+var add = module.i32.add(left, right);
+var ret = module.return(add);
+
+// Create the add function
+// Note: no additional local variables (that's the [])
+module.addFunction('adder', iii, [], ret);
+
+// Export the function, so we can call it later (for simplicity we
+// export it as the same name as it has internally)
+module.addExport('adder', 'adder');
+
+// Print out the text
+console.log(module.emitText());
+
+// Optimize the module! This removes the 'return', since the
+// output of the add can just fall through
+module.optimize();
+
+// Print out the optimized module's text
+console.log('optimized:\n\n' + module.emitText());
+
+// Get the binary in typed array form
+var binary = module.emitBinary();
+console.log('binary size: ' + binary.length);
+console.log();
+
+// We don't need the Binaryen module anymore, so we can tell it to
+// clean itself up
+module.dispose();
+
+// Compile the binary and create an instance
+var wasm = new WebAssembly.Instance(new WebAssembly.Module(binary), {})
+console.log(wasm); // prints something like "[object WebAssembly.Instance]"
+console.log();
+
+// Call the code!
+console.log('an addition: ' + wasm.exports.adder(40, 2));
+