summaryrefslogtreecommitdiff
path: root/examples
diff options
context:
space:
mode:
Diffstat (limited to 'examples')
-rw-r--r--examples/archive.rs8
-rw-r--r--examples/basic.rs (renamed from examples/simple.rs)6
-rw-r--r--examples/exceptions.rs28
-rw-r--r--examples/funcref_callbacks.rs123
-rw-r--r--examples/gc.rs33
-rw-r--r--examples/linking.rs12
-rw-r--r--examples/reentrance.rs5
-rw-r--r--examples/references.rs34
-rw-r--r--examples/resumable.rs2
-rw-r--r--examples/rust.rs (renamed from examples/wasm-rust.rs)10
-rw-r--r--examples/rust/README.md4
-rw-r--r--examples/simple2.rs21
12 files changed, 121 insertions, 165 deletions
diff --git a/examples/archive.rs b/examples/archive.rs
index 3f64704..3f118f2 100644
--- a/examples/archive.rs
+++ b/examples/archive.rs
@@ -11,13 +11,13 @@ const WASM: &str = r#"
"#;
fn main() -> Result<()> {
- let wasm = wat::parse_str(WASM).expect("Failed to parse WAT");
+ let wasm = wat::parse_str(WASM)?;
let module = Parser::default().parse_module_bytes(wasm)?;
- let twasm = module.serialize_twasm()?;
- // Now, you could e.g. write `twasm` to a file called `add.twasm`
- // and load it later in a different program.
+ // Serialize the optimized module for storage or distribution.
+ let twasm = module.serialize_twasm()?;
+ // Archived modules load without parsing Wasm again and should only come from trusted sources.
let module = Module::try_from_twasm(&twasm)?;
let mut store = Store::default();
let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
diff --git a/examples/simple.rs b/examples/basic.rs
index 0d57265..1f717c5 100644
--- a/examples/simple.rs
+++ b/examples/basic.rs
@@ -11,10 +11,14 @@ const WASM: &str = r#"
"#;
fn main() -> Result<()> {
- let wasm = wat::parse_str(WASM).expect("failed to parse wat");
+ let wasm = wat::parse_str(WASM)?;
let module = tinywasm::parse_bytes(&wasm)?;
+
+ // Module is reusable, while Store owns the runtime state for this instance.
let mut store = Store::default();
let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
+
+ // Typed handles validate parameters and results. Use func_untyped for dynamic values.
let add = instance.func::<(i32, i32), i32>(&store, "add")?;
assert_eq!(add.call(&mut store, (1, 2))?, 3);
diff --git a/examples/exceptions.rs b/examples/exceptions.rs
new file mode 100644
index 0000000..7c2f88e
--- /dev/null
+++ b/examples/exceptions.rs
@@ -0,0 +1,28 @@
+use anyhow::{Result, bail};
+use tinywasm::{Error, ModuleInstance, Store, WasmValue};
+
+const WASM: &str = r#"
+(module
+ (tag $failure (export "failure") (param i32))
+ (func (export "fail") (param i32)
+ local.get 0
+ throw $failure))
+"#;
+
+fn main() -> Result<()> {
+ let wasm = wat::parse_str(WASM)?;
+ let module = tinywasm::parse_bytes(&wasm)?;
+ let mut store = Store::default();
+ let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
+ let fail = instance.func::<i32, ()>(&store, "fail")?;
+
+ // Uncaught guest exceptions cross the host boundary as owned ExnRef handles.
+ let Err(Error::Exception(exception)) = fail.call(&mut store, 42) else {
+ bail!("expected a guest exception");
+ };
+
+ // The handle exposes the exception tag and typed payload values.
+ assert_eq!(exception.tag(&store)?, instance.tag("failure")?);
+ assert_eq!(exception.fields(&mut store)?, [WasmValue::I32(42)]);
+ Ok(())
+}
diff --git a/examples/funcref_callbacks.rs b/examples/funcref_callbacks.rs
deleted file mode 100644
index 959d798..0000000
--- a/examples/funcref_callbacks.rs
+++ /dev/null
@@ -1,123 +0,0 @@
-use anyhow::Result;
-use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store, types::FuncRef};
-
-const LHS: i32 = 5;
-const RHS: i32 = 3;
-
-fn main() -> Result<()> {
- run_passed_funcref_example()?;
- run_returned_funcref_example()?;
- Ok(())
-}
-
-fn run_passed_funcref_example() -> Result<()> {
- // Host receives funcref and calls it via an exported proxy.
- const WASM: &str = r#"
- (module
- (import "host" "call_this" (func $host_callback_caller (param funcref)))
- (import "host" "mul" (func $host_mul (param $x i32) (param $y i32) (result i32)))
-
- (func $tell_host_to_call (export "tell_host_to_call")
- (call $host_callback_caller (ref.func $add))
- (call $host_callback_caller (ref.func $sub))
- (call $host_callback_caller (ref.func $host_mul))
- )
-
- (type $binop (func (param i32 i32) (result i32)))
-
- (table 3 funcref)
- (elem (i32.const 0) $add $sub $host_mul)
- (func $add (param $x i32) (param $y i32) (result i32)
- local.get $x
- local.get $y
- i32.add
- )
- (func $sub (param $x i32) (param $y i32) (result i32)
- local.get $x
- local.get $y
- i32.sub
- )
-
- (table $callback_register 1 funcref)
- (func (export "call_binop_by_ref") (param funcref i32 i32) (result i32)
- (table.set $callback_register (i32.const 0) (local.get 0))
- (call_indirect $callback_register (type $binop) (local.get 1)(local.get 2)(i32.const 0))
- )
- )
- "#;
-
- let wasm = wat::parse_str(WASM).expect("failed to parse wat");
- let module = tinywasm::parse_bytes(&wasm)?;
- let mut store = Store::default();
-
- let mul = HostFunction::from(|_, (lhs, rhs): (i32, i32)| -> tinywasm::Result<i32> { Ok(lhs * rhs) });
- let call_this = HostFunction::from(|mut ctx: FuncContext<'_>, func_ref: FuncRef| -> tinywasm::Result<()> {
- // Host cannot call a funcref directly, so it routes through Wasm.
- let call_by_ref = ctx.module().func::<(FuncRef, i32, i32), i32>(ctx.store(), "call_binop_by_ref")?;
- let _result = call_by_ref.call(ctx.store_mut(), (func_ref, LHS, RHS))?;
- Ok(())
- });
-
- let mut imports = Imports::new();
- imports.define("host", "call_this", call_this).define("host", "mul", mul);
-
- let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
- let caller = instance.func::<(), ()>(&store, "tell_host_to_call")?;
-
- caller.call(&mut store, ())?;
-
- Ok(())
-}
-
-fn run_returned_funcref_example() -> Result<()> {
- // Wasm returns funcref values, host executes them through the same proxy.
- const WASM: &str = r#"
- (module
- (import "host" "mul" (func $host_mul (param $x i32) (param $y i32) (result i32)))
- (type $binop (func (param i32 i32) (result i32)))
- (table 3 funcref)
- (elem (i32.const 0) $add $sub $host_mul)
- (func $add (param $x i32) (param $y i32) (result i32)
- local.get $x
- local.get $y
- i32.add
- )
- (func $sub (param $x i32) (param $y i32) (result i32)
- local.get $x
- local.get $y
- i32.sub
- )
- (func $ref_to_funcs (export "what_should_host_call") (result funcref funcref funcref)
- (ref.func $add)
- (ref.func $sub)
- (ref.func $host_mul)
- )
-
- (table $callback_register 1 funcref)
- (func $call (export "call_binop_by_ref") (param funcref i32 i32) (result i32)
- (table.set $callback_register (i32.const 0) (local.get 0))
- (call_indirect $callback_register (type $binop) (local.get 1)(local.get 2)(i32.const 0))
- )
- )
- "#;
-
- let wasm = wat::parse_str(WASM).expect("failed to parse wat");
- let module = tinywasm::parse_bytes(&wasm)?;
- let mut store = Store::default();
- let mut imports = Imports::new();
-
- let mul = HostFunction::from(|_, (lhs, rhs): (i32, i32)| -> tinywasm::Result<i32> { Ok(lhs * rhs) });
- imports.define("host", "mul", mul);
-
- let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
- let (add_ref, sub_ref, mul_ref) = {
- let get_funcrefs = instance.func::<(), (FuncRef, FuncRef, FuncRef)>(&store, "what_should_host_call")?;
- get_funcrefs.call(&mut store, ())?
- };
-
- let call_by_ref = instance.func::<(FuncRef, i32, i32), i32>(&store, "call_binop_by_ref")?;
- for func_ref in [add_ref, sub_ref, mul_ref] {
- let _result = call_by_ref.call(&mut store, (func_ref, LHS, RHS))?;
- }
- Ok(())
-}
diff --git a/examples/gc.rs b/examples/gc.rs
new file mode 100644
index 0000000..9a73d04
--- /dev/null
+++ b/examples/gc.rs
@@ -0,0 +1,33 @@
+use anyhow::Result;
+use tinywasm::{ModuleInstance, Store, StructRef, WasmValue};
+
+const WASM: &str = r#"
+(module
+ (type $cube (struct (field (mut i32)) (field (mut i32))))
+ (func $make-cube (result (ref $cube))
+ i32.const 3
+ i32.const 4
+ struct.new $cube)
+ (func (export "cube") (result (ref struct))
+ call $make-cube))
+"#;
+
+fn main() -> Result<()> {
+ let wasm = wat::parse_str(WASM)?;
+ let module = tinywasm::parse_bytes(&wasm)?;
+ let mut store = Store::default();
+ let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
+ let cube = instance.func::<(), StructRef>(&store, "cube")?.call(&mut store, ())?;
+
+ // GC handles are Store-bound and expose typed field access through that Store.
+ assert_eq!(cube.fields(&mut store)?, [WasmValue::I32(3), WasmValue::I32(4)]);
+ cube.set_field(&mut store, 0, WasmValue::I32(5))?;
+
+ // Cloned handles keep their guest objects live across explicit collection.
+ let retained = cube.clone();
+ drop(cube);
+ store.gc()?;
+
+ assert_eq!(retained.field(&mut store, 0)?, WasmValue::I32(5)); // still alive
+ Ok(())
+}
diff --git a/examples/linking.rs b/examples/linking.rs
index 2df7133..92c0b7d 100644
--- a/examples/linking.rs
+++ b/examples/linking.rs
@@ -1,7 +1,6 @@
use anyhow::Result;
use tinywasm::{ModuleInstance, Store};
-// WebAssembly module defining and exporting an `add` function.
const WASM_ADD: &str = r#"
(module
(func $add (param $lhs i32) (param $rhs i32) (result i32)
@@ -11,7 +10,6 @@ const WASM_ADD: &str = r#"
(export "add" (func $add)))
"#;
-// WebAssembly module importing an `add` function and using it.
const WASM_IMPORT: &str = r#"
(module
(import "adder" "add" (func $add (param i32 i32) (result i32)))
@@ -24,25 +22,23 @@ const WASM_IMPORT: &str = r#"
"#;
fn main() -> Result<()> {
- let wasm_add = wat::parse_str(WASM_ADD).expect("failed to parse wat");
- let wasm_import = wat::parse_str(WASM_IMPORT).expect("failed to parse wat");
+ let wasm_add = wat::parse_str(WASM_ADD)?;
+ let wasm_import = wat::parse_str(WASM_IMPORT)?;
let add_module = tinywasm::parse_bytes(&wasm_add)?;
let import_module = tinywasm::parse_bytes(&wasm_import)?;
let mut store = Store::default();
- // Instantiate the `add` module.
let add_instance = ModuleInstance::instantiate(&mut store, &add_module, None)?;
- // Link the `adder` namespace to the `add` module's instance.
+ // Imports can link a module namespace and define individual host items together.
let mut imports = tinywasm::Imports::new();
imports.link_module("adder", add_instance)?;
- // Instantiate the `import` module with the linked imports.
let import_instance = ModuleInstance::instantiate(&mut store, &import_module, Some(&imports))?;
- // Call the `main` function, which uses the imported `add` function.
+ // Calling `main` crosses the linked module boundary to `add`.
let main = import_instance.func::<(), i32>(&store, "main")?;
assert_eq!(main.call(&mut store, ())?, 3);
diff --git a/examples/reentrance.rs b/examples/reentrance.rs
index 0084a61..cf57891 100644
--- a/examples/reentrance.rs
+++ b/examples/reentrance.rs
@@ -23,10 +23,11 @@ fn main() -> Result<()> {
let mut store = Store::default();
let call_add_twice = HostFunction::from(|mut ctx: FuncContext<'_>, value: i32| {
+ // FuncContext exposes the active module and its Store to the callback.
let add_one = ctx.module().func::<i32, i32>(ctx.store(), "add_one")?;
- // Use ctx.call for reentrant calls from host functions. Function::call
- // starts a root invocation and cannot preserve the active call stacks.
+ // Use ctx.call while a host callback has an active Wasm invocation.
+ // Function::call only starts top-level invocations.
let value = ctx.call(&add_one, value)?;
ctx.call(&add_one, value)
});
diff --git a/examples/references.rs b/examples/references.rs
new file mode 100644
index 0000000..b02dd07
--- /dev/null
+++ b/examples/references.rs
@@ -0,0 +1,34 @@
+use anyhow::Result;
+use tinywasm::{FuncRef, HostFunction, Imports, ModuleInstance, Store};
+
+const WASM: &str = r#"
+(module
+ (type $callback (func (param i32) (result i32)))
+ (import "host" "double" (func $double (type $callback)))
+ (elem declare func $double)
+ (func (export "callback") (result funcref)
+ ref.func $double)
+ (func (export "apply") (param funcref i32) (result i32)
+ local.get 1
+ local.get 0
+ ref.cast (ref $callback)
+ call_ref $callback))
+"#;
+
+fn main() -> Result<()> {
+ let mut store = Store::default();
+ let mut imports = Imports::new();
+ // Imports resolve reusable host definitions against each module's runtime types.
+ // HostFunction::instantiate is available when a standalone Function is needed.
+ imports.define("host", "double", HostFunction::from(|_, value: i32| -> tinywasm::Result<i32> { Ok(value * 2) }));
+
+ let wasm = wat::parse_str(WASM)?;
+ let module = tinywasm::parse_bytes(&wasm)?;
+ let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
+ // Option<FuncRef> maps nullable funcref. Bare FuncRef maps a non-null reference.
+ let callback = instance.func::<(), Option<FuncRef>>(&store, "callback")?.call(&mut store, ())?;
+ let apply = instance.func::<(Option<FuncRef>, i32), i32>(&store, "apply")?;
+
+ assert_eq!(apply.call(&mut store, (callback, 21))?, 42);
+ Ok(())
+}
diff --git a/examples/resumable.rs b/examples/resumable.rs
index 26b5f47..70b0db1 100644
--- a/examples/resumable.rs
+++ b/examples/resumable.rs
@@ -29,10 +29,12 @@ fn main() -> Result<()> {
let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
let count_down = instance.func::<i32, i32>(&store, "count_down")?;
+ // A resumable call returns execution state instead of running to completion.
let mut execution = count_down.call_resumable(&mut store, 10_000)?;
let fuel_per_round = 128;
let mut fuel_rounds = 0;
+ // Each resume call limits one round. std builds also support wall-clock budgets.
let result = loop {
fuel_rounds += 1;
match execution.resume_with_fuel(fuel_per_round)? {
diff --git a/examples/wasm-rust.rs b/examples/rust.rs
index 0cfb0ce..24b3b73 100644
--- a/examples/wasm-rust.rs
+++ b/examples/rust.rs
@@ -5,8 +5,8 @@ use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store};
/// Examples of using WebAssembly compiled from Rust with tinywasm.
///
-/// These examples are meant to be run with `cargo run --example wasm-rust <example>`.
-/// For example, `cargo run --example wasm-rust hello`.
+/// These examples are meant to be run with `cargo run --example rust <example>`.
+/// For example, `cargo run --example rust hello`.
///
/// To run these, you first need to compile the Rust examples to WebAssembly:
///
@@ -23,12 +23,12 @@ fn main() -> Result<()> {
pretty_env_logger::init();
if !std::path::Path::new("./examples/rust/out/").exists() {
- return Err(anyhow!("No WebAssembly files found. See examples/wasm-rust.rs for instructions."));
+ return Err(anyhow!("No WebAssembly files found. See examples/rust.rs for instructions."));
}
let args = std::env::args().collect::<Vec<_>>();
if args.len() < 2 {
- println!("Usage: cargo run --example wasm-rust <rust_example>");
+ println!("Usage: cargo run --example rust <rust_example>");
println!("Available examples:");
println!(" hello");
println!(" printi32");
@@ -105,6 +105,7 @@ fn hello() -> Result<()> {
let module = tinywasm::parse_file("./examples/rust/out/hello.opt.wasm")?;
let mut store = Store::default();
+ // The host callback reads the guest's exported memory through FuncContext.
let print_utf8 = HostFunction::from(|ctx: FuncContext<'_>, (ptr, len): (i64, i32)| {
let mem = ctx.memory("memory")?;
let string = mem.read_string(ctx.store(), ptr as usize, len as usize)?;
@@ -119,6 +120,7 @@ fn hello() -> Result<()> {
let arg_ptr = instance.func::<(), i32>(&store, "arg_ptr")?.call(&mut store, ())?;
let arg = b"world";
+ // Write the host argument into guest memory before calling the Rust export.
instance.memory("memory")?.copy_from_slice(&mut store, arg_ptr as usize, arg)?;
let hello = instance.func::<i32, ()>(&store, "hello")?;
hello.call(&mut store, arg.len() as i32)?;
diff --git a/examples/rust/README.md b/examples/rust/README.md
index 8d3178a..305a29c 100644
--- a/examples/rust/README.md
+++ b/examples/rust/README.md
@@ -1,9 +1,9 @@
# WebAssembly Rust Examples
This is a separate crate that generates WebAssembly from Rust code.
-It is used by the `wasm-rust` example.
+It is used by the `rust` example.
Requires the `wasm32-unknown-unknown` target to be installed.
-To build the example artifacts used by `cargo run --example wasm-rust -- <name>`, run `./examples/rust/build.sh`.
+To build the example artifacts used by `cargo run --example rust -- <name>`, run `./examples/rust/build.sh`.
That script also requires `binaryen` and `wabt` to be installed.
diff --git a/examples/simple2.rs b/examples/simple2.rs
deleted file mode 100644
index f673dfe..0000000
--- a/examples/simple2.rs
+++ /dev/null
@@ -1,21 +0,0 @@
-use anyhow::Result;
-use tinywasm::{ModuleInstance, Store};
-
-const WASM: &str = r#"
-(module
- (func $return (param $lhs i32) (param $rhs i64) (result i32 i64)
- local.get $lhs
- local.get $rhs)
- (export "return" (func $return)))
-"#;
-
-fn main() -> Result<()> {
- let wasm = wat::parse_str(WASM).expect("failed to parse wat");
- let module = tinywasm::parse_bytes(&wasm)?;
- let mut store = Store::default();
- let instance = ModuleInstance::instantiate(&mut store, &module, None)?;
- let add = instance.func::<(i32, i64), (i32, i64)>(&store, "return")?;
-
- assert_eq!(add.call(&mut store, (1, 2))?, (1, 2));
- Ok(())
-}