From 9893a51d2712f82a2ee57316a66bc26500eb3fdd Mon Sep 17 00:00:00 2001 From: Henry Date: Sun, 9 Aug 2026 16:11:57 +0200 Subject: feat: add reusable host imports and simplify function calls - make host definitions reusable across stores with gc-aware import linking - reorganize function calls, resumable execution, and typed value handling - expand typed tuples to arity 20 and update parser and store APIs Signed-off-by: Henry --- examples/doom/src/runtime.rs | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) (limited to 'examples/doom/src/runtime.rs') diff --git a/examples/doom/src/runtime.rs b/examples/doom/src/runtime.rs index 980dc21..bee961c 100644 --- a/examples/doom/src/runtime.rs +++ b/examples/doom/src/runtime.rs @@ -30,7 +30,7 @@ impl Runtime { let mut store = Store::default(); let host_state = Rc::new(RefCell::new(HostState::new(wad_path))); let imports = build_imports(&mut store, host_state.clone()); - let instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))?; + let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; let wad_path_buf = instance.func::<(), i32>(&store, "tinywasm_doom_wad_path_buf")?; let init = instance.func::<(), ()>(&store, "tinywasm_doom_init")?; @@ -169,7 +169,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_open", - HostFunction::from(store, move |ctx: FuncContext<'_>, (filename_ptr, mode_ptr): (i32, i32)| { + HostFunction::from(move |ctx: FuncContext<'_>, (filename_ptr, mode_ptr): (i32, i32)| { let memory = ctx.memory("memory")?; let filename = memory.read_cstring_until_null(ctx.store(), filename_ptr as usize, 1024)?; let mode = memory.read_cstring_until_null(ctx.store(), mode_ptr as usize, 16)?; @@ -208,7 +208,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_close", - HostFunction::from(store, move |_ctx: FuncContext<'_>, handle: i32| { + HostFunction::from(move |_ctx: FuncContext<'_>, handle: i32| { state.borrow_mut().files.remove(&handle); Ok(()) }), @@ -220,7 +220,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_read", - HostFunction::from(store, move |mut ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { + HostFunction::from(move |mut ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { let mut state = state.borrow_mut(); let Some(file) = state.files.get_mut(&handle) else { return Ok(0); @@ -238,7 +238,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_write", - HostFunction::from(store, move |ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { + HostFunction::from(move |ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { let data = ctx.memory("memory")?.read_vec(ctx.store(), buf_ptr as usize, count.max(0) as usize)?; let mut state = state.borrow_mut(); let Some(file) = state.files.get_mut(&handle) else { @@ -255,7 +255,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_seek", - HostFunction::from(store, move |_ctx: FuncContext<'_>, (handle, offset, origin): (i32, i32, i32)| { + HostFunction::from(move |_ctx: FuncContext<'_>, (handle, offset, origin): (i32, i32, i32)| { let seek_from = match origin { 0 => SeekFrom::Start(offset.max(0) as u64), 1 => SeekFrom::Current(offset as i64), @@ -277,7 +277,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_tell", - HostFunction::from(store, move |_ctx: FuncContext<'_>, handle: i32| { + HostFunction::from(move |_ctx: FuncContext<'_>, handle: i32| { let mut state = state.borrow_mut(); let Some(file) = state.files.get_mut(&handle) else { return Ok(-1); @@ -293,7 +293,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_eof", - HostFunction::from(store, move |_ctx: FuncContext<'_>, handle: i32| { + HostFunction::from(move |_ctx: FuncContext<'_>, handle: i32| { let mut state = state.borrow_mut(); let Some(file) = state.files.get_mut(&handle) else { return Ok(1); @@ -310,7 +310,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_gettime", - HostFunction::from(store, move |mut ctx: FuncContext<'_>, (sec_ptr, usec_ptr): (i32, i32)| { + HostFunction::from(move |mut ctx: FuncContext<'_>, (sec_ptr, usec_ptr): (i32, i32)| { let elapsed = state.borrow().start.elapsed(); let sec = elapsed.as_secs().min(i32::MAX as u64) as i32; let usec = elapsed.subsec_micros() as i32; @@ -327,7 +327,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_exit", - HostFunction::from(store, move |_ctx: FuncContext<'_>, code: i32| { + HostFunction::from(move |_ctx: FuncContext<'_>, code: i32| { state.borrow_mut().exit_code = Some(code); Ok(()) }), @@ -337,7 +337,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { imports.define( IMPORT_MODULE, "host_print", - HostFunction::from(store, move |ctx: FuncContext<'_>, ptr: i32| { + HostFunction::from(move |ctx: FuncContext<'_>, ptr: i32| { let text = ctx.memory("memory")?.read_cstring_until_null(ctx.store(), ptr as usize, 4096)?; log::info!("guest: {}", text.to_string_lossy()); Ok(()) -- cgit v1.3.1 From 70c5bb2e4816f7ee458a6180845af3bd6b1d2d1d Mon Sep 17 00:00:00 2001 From: Henry Date: Mon, 10 Aug 2026 16:21:47 +0200 Subject: chore: cleanup tests / devdeps, fix doom example Signed-off-by: Henry --- Cargo.lock | 36 ++--- Cargo.toml | 26 +++- benches/argon2id.rs | 46 ++++++ benches/fibonacci.rs | 52 +++++++ benches/memory_backends.rs | 152 +++++++++++++++++++ benches/tinywasm.rs | 49 ++++++ benches/tinywasm_modes.rs | 100 +++++++++++++ crates/cli/Cargo.toml | 6 +- crates/cli/src/bin.rs | 2 +- crates/cli/src/cmd/compile.rs | 2 +- crates/cli/src/cmd/completion.rs | 2 +- crates/cli/src/cmd/dump.rs | 2 +- crates/cli/src/cmd/inspect.rs | 2 +- crates/cli/src/cmd/run.rs | 8 +- crates/cli/src/cmd/wast.rs | 2 +- crates/cli/src/engine_flags.rs | 2 +- crates/cli/src/lib.rs | 4 +- crates/cli/src/load.rs | 2 +- crates/cli/src/testsuite.rs | 166 +++++++++++++++++++++ crates/cli/src/value_parse.rs | 6 +- crates/cli/src/wast_runner.rs | 80 +++++----- crates/tinywasm/Cargo.toml | 27 +--- crates/tinywasm/benches/argon2id.rs | 47 ------ crates/tinywasm/benches/fibonacci.rs | 53 ------- crates/tinywasm/benches/memory_backends.rs | 152 ------------------- crates/tinywasm/benches/tinywasm.rs | 50 ------- crates/tinywasm/benches/tinywasm_modes.rs | 99 ------------ crates/tinywasm/tests/host_func_signature_check.rs | 18 +-- crates/tinywasm/tests/import_linking.rs | 7 +- crates/tinywasm/tests/imported_table_init.rs | 3 +- crates/tinywasm/tests/internal_refs.rs | 13 +- crates/tinywasm/tests/memory_backends.rs | 31 ++-- crates/tinywasm/tests/memory_ref_api.rs | 3 +- crates/tinywasm/tests/module_descriptors.rs | 8 +- crates/tinywasm/tests/resume_execution.rs | 3 +- crates/tinywasm/tests/start_function.rs | 3 +- crates/tinywasm/tests/store_ownership.rs | 11 +- crates/tinywasm/tests/test-wasm-1.rs | 6 +- crates/tinywasm/tests/test-wasm-2.rs | 6 +- crates/tinywasm/tests/test-wasm-3.rs | 6 +- .../tinywasm/tests/test-wasm-custom-page-sizes.rs | 6 +- crates/tinywasm/tests/test-wasm-custom.rs | 6 +- crates/tinywasm/tests/test-wasm-gc.rs | 6 +- crates/tinywasm/tests/test-wasm-latest.rs | 6 +- crates/tinywasm/tests/test-wasm-memory64.rs | 6 +- crates/tinywasm/tests/test-wasm-multi-memory.rs | 6 +- crates/tinywasm/tests/test-wasm-relaxed-simd.rs | 6 +- crates/tinywasm/tests/test-wasm-simd.rs | 6 +- crates/tinywasm/tests/test-wasm-threads.rs | 6 +- crates/tinywasm/tests/test-wasm-wide-arithmetic.rs | 6 +- crates/tinywasm/tests/test-wast.rs | 17 +-- crates/tinywasm/tests/testsuite/mod.rs | 150 ------------------- crates/tinywasm/tests/typed_globals.rs | 5 +- crates/tinywasm/tests/typed_lookup.rs | 5 +- examples/archive.rs | 2 +- examples/doom/Cargo.toml | 2 +- examples/doom/src/main.rs | 10 +- examples/doom/src/runtime.rs | 35 +++-- examples/funcref_callbacks.rs | 2 +- examples/linking.rs | 2 +- examples/reentrance.rs | 2 +- examples/resumable.rs | 2 +- examples/simple.rs | 2 +- examples/simple2.rs | 2 +- examples/wasm-rust.rs | 4 +- 65 files changed, 781 insertions(+), 814 deletions(-) create mode 100644 benches/argon2id.rs create mode 100644 benches/fibonacci.rs create mode 100644 benches/memory_backends.rs create mode 100644 benches/tinywasm.rs create mode 100644 benches/tinywasm_modes.rs create mode 100644 crates/cli/src/testsuite.rs delete mode 100644 crates/tinywasm/benches/argon2id.rs delete mode 100644 crates/tinywasm/benches/fibonacci.rs delete mode 100644 crates/tinywasm/benches/memory_backends.rs delete mode 100644 crates/tinywasm/benches/tinywasm.rs delete mode 100644 crates/tinywasm/benches/tinywasm_modes.rs delete mode 100644 crates/tinywasm/tests/testsuite/mod.rs (limited to 'examples/doom/src/runtime.rs') diff --git a/Cargo.lock b/Cargo.lock index 5312e7f..c4dbba7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -76,6 +76,12 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + [[package]] name = "assert_cmd" version = "2.2.2" @@ -351,16 +357,6 @@ dependencies = [ "windows-sys", ] -[[package]] -name = "eyre" -version = "0.6.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cd915d99f24784cdc19fd37ef22b97e3ff0ae756c7e492e9fbfe897d61e2aec" -dependencies = [ - "indenter", - "once_cell", -] - [[package]] name = "fastrand" version = "2.5.0" @@ -447,12 +443,6 @@ dependencies = [ "quote", ] -[[package]] -name = "indenter" -version = "0.3.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "964de6e86d545b246d84badc0fef527924ace5134f30641c203ef52ba83f58d5" - [[package]] name = "indexmap" version = "2.14.0" @@ -872,13 +862,8 @@ dependencies = [ name = "tinywasm" version = "0.11.0-pre.0" dependencies = [ - "criterion", - "eyre", "libm", "log", - "owo-colors", - "serde", - "serde_json", "tinywasm-cli", "tinywasm-parser", "tinywasm-types", @@ -891,16 +876,19 @@ name = "tinywasm-cli" version = "0.11.0-pre.0" dependencies = [ "anstream", + "anyhow", "assert_cmd", "clap", "clap_complete", - "eyre", "log", "owo-colors", "predicates", "pretty_env_logger", + "serde", + "serde_json", "tempfile", "tinywasm", + "wasm-testsuite", "wast", "wat", ] @@ -918,9 +906,11 @@ dependencies = [ name = "tinywasm-root" version = "0.11.0-pre.0" dependencies = [ - "eyre", + "anyhow", + "criterion", "pretty_env_logger", "tinywasm", + "tinywasm-parser", "wat", ] diff --git a/Cargo.toml b/Cargo.toml index ca80b66..5a4e83f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,7 +24,7 @@ tinywasm = { path = "crates/tinywasm", version = "0.11.0-pre.0", default-feature tinywasm-parser = { path = "crates/parser", version = "0.11.0-pre.0", default-features = false } tinywasm-types = { path = "crates/types", version = "0.11.0-pre.0", default-features = false } -eyre = "0.6" +anyhow = "1.0" log = "0.4" owo-colors = { version = "4.3" } pretty_env_logger = "0.5" @@ -44,10 +44,32 @@ criterion = { version = "0.8", default-features = false, features = [ name = "wasm-rust" test = false +[[bench]] +harness = false +name = "argon2id" + +[[bench]] +harness = false +name = "fibonacci" + +[[bench]] +harness = false +name = "tinywasm" + +[[bench]] +harness = false +name = "tinywasm_modes" + +[[bench]] +harness = false +name = "memory_backends" + [dev-dependencies] -eyre.workspace = true +anyhow.workspace = true +criterion.workspace = true pretty_env_logger.workspace = true tinywasm = { path = "crates/tinywasm" } +tinywasm-parser.workspace = true wat.workspace = true [profile.bench] diff --git a/benches/argon2id.rs b/benches/argon2id.rs new file mode 100644 index 0000000..3121062 --- /dev/null +++ b/benches/argon2id.rs @@ -0,0 +1,46 @@ +use criterion::{Criterion, criterion_group, criterion_main}; +use tinywasm::{ModuleInstance, Result, Store, types}; +use types::Module; + +const WASM: &[u8] = include_bytes!("../examples/rust/out/argon2id.wasm"); + +fn argon2id_parse() -> Result { + let parser = tinywasm_parser::Parser::default(); + let data = parser.parse_module_bytes(WASM)?; + Ok(data) +} + +fn argon2id_to_twasm(module: &Module) -> Result> { + let twasm = module.serialize_twasm()?; + Ok(twasm) +} + +fn argon2id_from_twasm(twasm: &[u8]) -> Result { + let module = Module::try_from_twasm(twasm)?; + Ok(module) +} + +fn argon2id_run(module: Module) -> Result<()> { + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let argon2 = instance.func::<(i32, i32, i32), i32>(&store, "argon2id")?; + argon2.call(&mut store, (1000, 2, 1))?; + Ok(()) +} + +fn criterion_benchmark(c: &mut Criterion) { + let module = argon2id_parse().expect("argon2id_parse"); + let twasm = argon2id_to_twasm(&module).expect("argon2id_to_twasm"); + let mut group = c.benchmark_group("argon2id"); + + group.measurement_time(std::time::Duration::from_secs(2)); + group.bench_function("argon2id_parse", |b| b.iter(argon2id_parse)); + group.bench_function("argon2id_to_twasm", |b| b.iter(|| argon2id_to_twasm(&module))); + group.bench_function("argon2id_from_twasm", |b| b.iter(|| argon2id_from_twasm(&twasm))); + + group.measurement_time(std::time::Duration::from_secs(10)); + group.bench_function("argon2id", |b| b.iter(|| argon2id_run(module.clone()))); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/benches/fibonacci.rs b/benches/fibonacci.rs new file mode 100644 index 0000000..51fd2d3 --- /dev/null +++ b/benches/fibonacci.rs @@ -0,0 +1,52 @@ +use criterion::{Criterion, criterion_group, criterion_main}; +use tinywasm::{ModuleInstance, Result, Store, types}; +use types::Module; + +const WASM: &[u8] = include_bytes!("../examples/rust/out/fibonacci.wasm"); + +fn fibonacci_parse() -> Result { + let parser = tinywasm_parser::Parser::default(); + let data = parser.parse_module_bytes(WASM)?; + Ok(data) +} + +fn fibonacci_to_twasm(module: &Module) -> Result> { + let twasm = module.serialize_twasm()?; + Ok(twasm) +} + +fn fibonacci_from_twasm(twasm: &[u8]) -> Result { + Ok(Module::try_from_twasm(twasm)?) +} + +fn fibonacci_run(module: Module, recursive: bool, n: i32) -> Result<()> { + let mut store = Store::default(); + let instance = ModuleInstance::instantiate(&mut store, &module, None)?; + let argon2 = instance.func::( + &store, + match recursive { + true => "fibonacci_recursive", + false => "fibonacci", + }, + )?; + argon2.call(&mut store, n)?; + Ok(()) +} + +fn criterion_benchmark(c: &mut Criterion) { + let module = fibonacci_parse().expect("fibonacci_parse"); + let twasm = fibonacci_to_twasm(&module).expect("fibonacci_to_twasm"); + let mut group = c.benchmark_group("fibonacci"); + + group.measurement_time(std::time::Duration::from_secs(2)); + group.bench_function("fibonacci_parse", |b| b.iter(fibonacci_parse)); + group.bench_function("fibonacci_to_twasm", |b| b.iter(|| fibonacci_to_twasm(&module))); + group.bench_function("fibonacci_from_twasm", |b| b.iter(|| fibonacci_from_twasm(&twasm))); + + group.measurement_time(std::time::Duration::from_secs(10)); + group.bench_function("fibonacci_iterative_60", |b| b.iter(|| fibonacci_run(module.clone(), false, 60))); + group.bench_function("fibonacci_recursive_26", |b| b.iter(|| fibonacci_run(module.clone(), true, 26))); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/benches/memory_backends.rs b/benches/memory_backends.rs new file mode 100644 index 0000000..3a59f8c --- /dev/null +++ b/benches/memory_backends.rs @@ -0,0 +1,152 @@ +use criterion::measurement::WallTime; +use criterion::{BatchSize, BenchmarkGroup, BenchmarkId, Criterion, criterion_group, criterion_main}; +use std::hint::black_box; +use tinywasm::{LinearMemory, PagedMemory, VecMemory}; + +const PAGE_SIZE: usize = 64 * 1024; +const CHUNK_SIZE: usize = 4 * 1024; +const GROW_STEPS: usize = 32; +const BENCH_MEASUREMENT_TIME: std::time::Duration = std::time::Duration::from_secs(10); + +const MEMORY_LEN: usize = PAGE_SIZE * 4; +const CONTIGUOUS_OFFSET: usize = 1024; +const CONTIGUOUS_LEN: usize = 2048; +const CROSS_CHUNK_OFFSET: usize = CHUNK_SIZE - 512; +const CROSS_CHUNK_LEN: usize = CHUNK_SIZE * 2; + +fn bench_grow(group: &mut BenchmarkGroup<'_, WallTime>, backend: &str, make_memory: F) +where + M: LinearMemory, + F: Fn() -> M + Copy, +{ + group.bench_function(BenchmarkId::new("grow", backend), |b| { + b.iter_batched( + make_memory, + |mut memory| { + for page_count in 2..=GROW_STEPS + 1 { + memory.grow_to(page_count * PAGE_SIZE).unwrap(); + } + black_box(memory.len()) + }, + BatchSize::SmallInput, + ) + }); +} + +fn bench_write_all( + group: &mut BenchmarkGroup<'_, WallTime>, + backend: &str, + workload: &str, + mut memory: M, + offset: usize, + len: usize, +) { + let src = vec![0xA5; len]; + group.bench_function(BenchmarkId::new(format!("write_all/{workload}"), backend), |b| { + b.iter(|| { + memory.write_all(offset, black_box(&src)).unwrap(); + black_box(memory.len()) + }) + }); +} + +fn bench_read_exact( + group: &mut BenchmarkGroup<'_, WallTime>, + backend: &str, + workload: &str, + mut memory: M, + offset: usize, + len: usize, +) { + let src = vec![0x5A; len]; + memory.write_all(offset, &src).unwrap(); + + let mut dst = vec![0; len]; + group.bench_function(BenchmarkId::new(format!("read_exact/{workload}"), backend), |b| { + b.iter(|| { + memory.read_exact(offset, black_box(&mut dst)).unwrap(); + black_box(&dst); + }) + }); +} + +fn criterion_benchmark(c: &mut Criterion) { + let mut group = c.benchmark_group("memory_backends"); + group.measurement_time(BENCH_MEASUREMENT_TIME); + + bench_grow(&mut group, "vec", || VecMemory::try_new(PAGE_SIZE).expect("bench memory should be constructible")); + bench_grow(&mut group, "paged", || { + PagedMemory::try_new(PAGE_SIZE, CHUNK_SIZE).expect("bench memory should be constructible") + }); + + bench_write_all( + &mut group, + "vec", + "contiguous", + VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"), + CONTIGUOUS_OFFSET, + CONTIGUOUS_LEN, + ); + bench_write_all( + &mut group, + "paged", + "contiguous", + PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"), + CONTIGUOUS_OFFSET, + CONTIGUOUS_LEN, + ); + bench_read_exact( + &mut group, + "vec", + "contiguous", + VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"), + CONTIGUOUS_OFFSET, + CONTIGUOUS_LEN, + ); + bench_read_exact( + &mut group, + "paged", + "contiguous", + PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"), + CONTIGUOUS_OFFSET, + CONTIGUOUS_LEN, + ); + + bench_write_all( + &mut group, + "vec", + "cross_chunk", + VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"), + CROSS_CHUNK_OFFSET, + CROSS_CHUNK_LEN, + ); + bench_write_all( + &mut group, + "paged", + "cross_chunk", + PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"), + CROSS_CHUNK_OFFSET, + CROSS_CHUNK_LEN, + ); + bench_read_exact( + &mut group, + "vec", + "cross_chunk", + VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"), + CROSS_CHUNK_OFFSET, + CROSS_CHUNK_LEN, + ); + bench_read_exact( + &mut group, + "paged", + "cross_chunk", + PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"), + CROSS_CHUNK_OFFSET, + CROSS_CHUNK_LEN, + ); + + group.finish(); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/benches/tinywasm.rs b/benches/tinywasm.rs new file mode 100644 index 0000000..aff8c70 --- /dev/null +++ b/benches/tinywasm.rs @@ -0,0 +1,49 @@ +use criterion::{Criterion, criterion_group, criterion_main}; +use tinywasm::engine::Config; +use tinywasm::{Engine, FuncContext, HostFunction, Imports, ModuleInstance, Result, Store, types}; +use types::Module; + +const WASM: &[u8] = include_bytes!("../examples/rust/out/tinywasm.wasm"); + +fn tinywasm_parse() -> Result { + let parser = tinywasm_parser::Parser::default(); + let data = parser.parse_module_bytes(WASM)?; + Ok(data) +} + +fn tinywasm_to_twasm(module: &Module) -> Result> { + let twasm = module.serialize_twasm()?; + Ok(twasm) +} + +fn tinywasm_from_twasm(twasm: &[u8]) -> Result { + let module = Module::try_from_twasm(twasm)?; + Ok(module) +} + +fn tinywasm_run(module: &Module) -> Result<()> { + let engine = Engine::new(Config::default()); + let mut store = Store::new(engine); + let mut imports = Imports::default(); + imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _: i32| Ok(()))); + let instance = ModuleInstance::instantiate(&mut store, module, Some(&imports)).expect("instantiate"); + let hello = instance.func::<(), ()>(&store, "hello").expect("func_typed"); + hello.call(&mut store, ()).expect("call"); + Ok(()) +} + +fn criterion_benchmark(c: &mut Criterion) { + let module = tinywasm_parse().expect("tinywasm_parse"); + let twasm = tinywasm_to_twasm(&module).expect("tinywasm_to_twasm"); + let mut group = c.benchmark_group("tinywasm"); + + group.measurement_time(std::time::Duration::from_secs(2)); + group.bench_function("tinywasm_parse", |b| b.iter(tinywasm_parse)); + group.bench_function("tinywasm_to_twasm", |b| b.iter(|| tinywasm_to_twasm(&module))); + group.bench_function("tinywasm_from_twasm", |b| b.iter(|| tinywasm_from_twasm(&twasm))); + group.measurement_time(std::time::Duration::from_secs(10)); + group.bench_function("tinywasm", |b| b.iter(|| tinywasm_run(&module))); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/benches/tinywasm_modes.rs b/benches/tinywasm_modes.rs new file mode 100644 index 0000000..7d1d993 --- /dev/null +++ b/benches/tinywasm_modes.rs @@ -0,0 +1,100 @@ +use criterion::{BatchSize, Criterion, criterion_group, criterion_main}; +use tinywasm::engine::{Config, FuelPolicy}; +use tinywasm::types::Module; +use tinywasm::{ + Engine, ExecProgress, FuncContext, FunctionTyped, HostFunction, Imports, ModuleInstance, Result, Store, +}; + +const WASM: &[u8] = include_bytes!("../examples/rust/out/tinywasm.wasm"); +const FUEL_PER_ROUND: u32 = 512; +const TIME_BUDGET_PER_ROUND: core::time::Duration = core::time::Duration::from_micros(50); +const BENCH_MEASUREMENT_TIME: core::time::Duration = core::time::Duration::from_secs(10); + +fn tinywasm_parse() -> Result { + let parser = tinywasm_parser::Parser::default(); + Ok(parser.parse_module_bytes(WASM)?) +} + +fn setup_typed_func(module: &Module, engine: Option) -> Result<(Store, FunctionTyped<(), ()>)> { + let mut store = match engine { + Some(engine) => Store::new(engine), + None => Store::default(), + }; + + let mut imports = Imports::default(); + imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _: i32| Ok(()))); + + let instance = ModuleInstance::instantiate(&mut store, module, Some(&imports))?; + let func = instance.func::<(), ()>(&store, "hello")?; + Ok((store, func)) +} + +fn run_call(store: &mut Store, func: &FunctionTyped<(), ()>) -> Result<()> { + func.call(store, ())?; + Ok(()) +} + +fn run_resume_with_fuel(store: &mut Store, func: &FunctionTyped<(), ()>) -> Result<()> { + let mut execution = func.call_resumable(store, ())?; + loop { + match execution.resume_with_fuel(FUEL_PER_ROUND)? { + ExecProgress::Completed(_) => return Ok(()), + ExecProgress::Suspended => {} + } + } +} + +fn run_resume_with_time_budget(store: &mut Store, func: &FunctionTyped<(), ()>) -> Result<()> { + let mut execution = func.call_resumable(store, ())?; + loop { + match execution.resume_with_time_budget(TIME_BUDGET_PER_ROUND)? { + ExecProgress::Completed(_) => return Ok(()), + ExecProgress::Suspended => {} + } + } +} + +fn criterion_benchmark(c: &mut Criterion) { + let module = tinywasm_parse().expect("tinywasm_parse"); + let mut group = c.benchmark_group("tinywasm_modes"); + group.measurement_time(BENCH_MEASUREMENT_TIME); + + let per_instruction_engine = Engine::new(Config::new().with_fuel_policy(FuelPolicy::PerInstruction)); + group.bench_function("resume_fuel_per_instruction", |b| { + b.iter_batched_ref( + || setup_typed_func(&module, Some(per_instruction_engine.clone())).expect("setup fuel per-instruction"), + |(store, func)| run_resume_with_fuel(store, func).expect("run fuel per-instruction"), + BatchSize::LargeInput, + ) + }); + + let weighted_engine = Engine::new(Config::new().with_fuel_policy(FuelPolicy::Weighted)); + group.bench_function("resume_fuel_weighted", |b| { + b.iter_batched_ref( + || setup_typed_func(&module, Some(weighted_engine.clone())).expect("setup fuel weighted"), + |(store, func)| run_resume_with_fuel(store, func).expect("run fuel weighted"), + BatchSize::LargeInput, + ) + }); + + group.bench_function("resume_time_budget", |b| { + b.iter_batched_ref( + || setup_typed_func(&module, None).expect("setup time budget"), + |(store, func)| run_resume_with_time_budget(store, func).expect("run time budget"), + BatchSize::LargeInput, + ) + }); + + group.bench_function("call", |b| { + b.iter_batched_ref( + || setup_typed_func(&module, None).expect("setup call"), + |(store, func)| run_call(store, func).expect("run call"), + BatchSize::LargeInput, + ) + }); + + group.finish(); +} + +criterion_group!(benches, criterion_benchmark); +criterion_main!(benches); diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 17b56e6..1aae437 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -23,12 +23,14 @@ path = "src/bin.rs" [dependencies] anstream = { version = "1.0" } +anyhow.workspace = true clap = { version = "4.6", features = ["derive"] } clap_complete = "4.6" -eyre.workspace = true log.workspace = true owo-colors = { workspace = true } pretty_env_logger.workspace = true +serde = { workspace = true, optional = true } +serde_json = { workspace = true, optional = true } tinywasm = { workspace = true, features = [ "archive", "canonicalize-nans", @@ -39,6 +41,7 @@ tinywasm = { workspace = true, features = [ "std", "validate", ] } +wasm-testsuite = { workspace = true, optional = true } wast = { workspace = true, optional = true } wat = { workspace = true, optional = true } @@ -49,5 +52,6 @@ tempfile = "3.27" [features] default = ["wast", "wat"] +tests = ["dep:serde", "dep:serde_json", "dep:wasm-testsuite", "wast"] wast = ["dep:wast"] wat = ["dep:wat"] diff --git a/crates/cli/src/bin.rs b/crates/cli/src/bin.rs index 592fda7..d630fcf 100644 --- a/crates/cli/src/bin.rs +++ b/crates/cli/src/bin.rs @@ -1,5 +1,5 @@ +use anyhow::Result; use clap::Parser; -use eyre::Result; use tinywasm_cli::{Cli, run_cli}; fn main() -> Result<()> { diff --git a/crates/cli/src/cmd/compile.rs b/crates/cli/src/cmd/compile.rs index 93e38d5..c7007ee 100644 --- a/crates/cli/src/cmd/compile.rs +++ b/crates/cli/src/cmd/compile.rs @@ -1,4 +1,4 @@ -use eyre::Result; +use anyhow::Result; use crate::cli::CompileArgs; use crate::load::{default_twasm_output_path, load_compilable_module, write_output_bytes}; diff --git a/crates/cli/src/cmd/completion.rs b/crates/cli/src/cmd/completion.rs index 5815f57..b3aec7c 100644 --- a/crates/cli/src/cmd/completion.rs +++ b/crates/cli/src/cmd/completion.rs @@ -1,7 +1,7 @@ use std::io; +use anyhow::Result; use clap::CommandFactory; -use eyre::Result; use crate::cli::{Cli, CompletionArgs}; diff --git a/crates/cli/src/cmd/dump.rs b/crates/cli/src/cmd/dump.rs index 7a88cc2..da98a0b 100644 --- a/crates/cli/src/cmd/dump.rs +++ b/crates/cli/src/cmd/dump.rs @@ -1,5 +1,5 @@ use anstream::println; -use eyre::Result; +use anyhow::Result; use owo_colors::OwoColorize; use tinywasm::types::{ExternalKind, ImportKind}; diff --git a/crates/cli/src/cmd/inspect.rs b/crates/cli/src/cmd/inspect.rs index ea2cec7..cf7cb5f 100644 --- a/crates/cli/src/cmd/inspect.rs +++ b/crates/cli/src/cmd/inspect.rs @@ -1,4 +1,4 @@ -use eyre::Result; +use anyhow::Result; use crate::cli::ModuleInputArgs; use crate::load::load_module; diff --git a/crates/cli/src/cmd/run.rs b/crates/cli/src/cmd/run.rs index 06f29f1..3d25641 100644 --- a/crates/cli/src/cmd/run.rs +++ b/crates/cli/src/cmd/run.rs @@ -1,4 +1,4 @@ -use eyre::Result; +use anyhow::Result; use tinywasm::types::ExportType; use tinywasm::{ModuleInstance, Store}; @@ -8,7 +8,7 @@ use crate::output::print_results; use crate::value_parse::parse_invocation_args; pub fn run(args: RunArgs) -> Result<()> { - let module_path = args.module.as_deref().ok_or_else(|| eyre::eyre!("missing module path"))?; + let module_path = args.module.as_deref().ok_or_else(|| anyhow::anyhow!("missing module path"))?; let loaded = load_module(module_path)?; let mut store = Store::new(args.engine.build_engine()?); let instance = ModuleInstance::instantiate_no_start(&mut store, &loaded.module, None)?; @@ -26,7 +26,7 @@ pub fn run(args: RunArgs) -> Result<()> { (true, ExportType::Func(ty)) => Some(ty), _ => None, }) - .ok_or_else(|| eyre::eyre!("export is not a function: {export}"))?; + .ok_or_else(|| anyhow::anyhow!("export is not a function: {export}"))?; let func = instance.func_untyped(&store, export)?; let params = parse_invocation_args(func_ty, &args.args)?; let results = func.call(&mut store, ¶ms)?; @@ -40,7 +40,7 @@ pub fn run(args: RunArgs) -> Result<()> { } let start = instance.func_untyped(&store, "_start").map_err(|_| { - eyre::eyre!( + anyhow::anyhow!( "module has no start function or `_start` export. Use `tinywasm inspect {module_path}` or `tinywasm run --invoke {module_path}`" ) })?; diff --git a/crates/cli/src/cmd/wast.rs b/crates/cli/src/cmd/wast.rs index ef9c263..c669a0a 100644 --- a/crates/cli/src/cmd/wast.rs +++ b/crates/cli/src/cmd/wast.rs @@ -1,6 +1,6 @@ use std::path::PathBuf; -use eyre::Result; +use anyhow::Result; use crate::cli::WastArgs; use crate::wast_runner::WastRunner; diff --git a/crates/cli/src/engine_flags.rs b/crates/cli/src/engine_flags.rs index c8df1fe..3d90847 100644 --- a/crates/cli/src/engine_flags.rs +++ b/crates/cli/src/engine_flags.rs @@ -1,5 +1,5 @@ +use anyhow::{Result, bail}; use clap::{Args, ValueEnum}; -use eyre::{Result, bail}; use tinywasm::{Engine, StackConfig, engine::FuelPolicy}; #[derive(Args, Clone, Default)] diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index bef6b72..877bfe1 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -3,12 +3,14 @@ pub mod cmd; pub mod engine_flags; pub mod load; pub mod output; +#[cfg(feature = "tests")] +pub mod testsuite; pub mod value_parse; #[cfg(feature = "wast")] pub mod wast_runner; +use anyhow::Result; use clap::CommandFactory; -use eyre::Result; pub use cli::{Cli, Commands}; diff --git a/crates/cli/src/load.rs b/crates/cli/src/load.rs index 9f7c616..12c0e1f 100644 --- a/crates/cli/src/load.rs +++ b/crates/cli/src/load.rs @@ -2,7 +2,7 @@ use std::ffi::OsStr; use std::io::{Read, Write}; use std::path::Path; -use eyre::{Context, Result, bail}; +use anyhow::{Context, Result, bail}; use tinywasm::Module; #[derive(Clone, Copy, Debug, PartialEq, Eq)] diff --git a/crates/cli/src/testsuite.rs b/crates/cli/src/testsuite.rs new file mode 100644 index 0000000..032aa88 --- /dev/null +++ b/crates/cli/src/testsuite.rs @@ -0,0 +1,166 @@ +use crate::wast_runner::{GroupResult, TestFile as RunnerTestFile, WastRunner}; +use owo_colors::OwoColorize; +use serde::{Deserialize, Serialize}; +use std::fmt::{Display, Formatter}; +use std::io::{BufRead, BufReader, Seek, SeekFrom}; + +/// Result type used by the WAST test utilities. +pub type TestResult = core::result::Result>; + +#[derive(Debug)] +struct TestFailure(String); + +impl Display for TestFailure { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.write_str(&self.0) + } +} + +impl core::error::Error for TestFailure {} + +#[derive(Serialize, Deserialize)] +pub struct TestGroupResult { + pub name: String, + pub passed: usize, + pub failed: usize, +} + +pub struct TestSuite { + runner: WastRunner, +} + +impl TestSuite { + pub fn set_log_level(level: log::LevelFilter) { + WastRunner::set_log_level(level); + } + + pub fn new() -> Self { + Self { runner: WastRunner::new() } + } + + pub fn run_paths(&mut self, tests: &[std::path::PathBuf]) -> TestResult<()> { + let mut files = Vec::new(); + for path in tests { + if path.is_dir() { + for entry in std::fs::read_dir(path)? { + let entry = entry?; + let path = entry.path(); + if path.extension().is_some_and(|ext| ext == "wast") { + files.push(path); + } + } + } else { + files.push(path.clone()); + } + } + files.sort(); + + let runner_files = files + .iter() + .map(|path| { + let contents = std::fs::read_to_string(path)?; + let name = path.to_string_lossy().into_owned(); + Ok((name, contents)) + }) + .collect::>>()?; + + self.runner.run_files(runner_files.iter().map(|(name, contents)| RunnerTestFile { + name: name.clone(), + parent: name.clone(), + contents, + }))?; + Ok(()) + } + + pub fn run_files<'a>( + &mut self, + tests: impl IntoIterator>, + ) -> TestResult<()> { + self.runner.run_files(tests.into_iter().map(|file| RunnerTestFile { + name: file.name().to_string(), + parent: file.parent().to_string(), + contents: file.raw(), + }))?; + Ok(()) + } + + pub fn print_errors(&self) { + self.runner.print_errors(); + } + + pub fn report_status(&self) -> TestResult<()> { + if self.runner.failed() { + println!(); + Err(TestFailure(format!("{}:\n{self}", "failed one or more tests".red().bold())).into()) + } else { + println!("{self}"); + Ok(()) + } + } + + pub fn save_csv(&self, path: &str, version: &str) -> TestResult<()> { + use std::fs::OpenOptions; + use std::io::Write; + + let mut file = OpenOptions::new().create(true).append(true).read(true).open(path)?; + let last_line = BufReader::new(&file).lines().last().transpose()?; + + if let Some(last) = last_line + && last.starts_with(version) + { + let len_to_truncate = last.len() as i64; + file.set_len(file.metadata()?.len() - len_to_truncate as u64 - 1)?; + } + + file.seek(SeekFrom::End(0))?; + + let mut passed = 0; + let mut failed = 0; + let mut groups = Vec::new(); + + for group in self.runner.group_results() { + passed += group.passed; + failed += group.failed; + groups.push(TestGroupResult { name: group.name, passed: group.passed, failed: group.failed }); + } + + let groups = serde_json::to_string(&groups)?; + let line = format!("{version},{passed},{failed},{groups}\n"); + file.write_all(line.as_bytes())?; + Ok(()) + } + + fn group_results(&self) -> Vec { + self.runner.group_results() + } +} + +impl Default for TestSuite { + fn default() -> Self { + Self::new() + } +} + +impl Display for TestSuite { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let mut total_passed = 0; + let mut total_failed = 0; + + for group in self.group_results() { + total_passed += group.passed; + total_failed += group.failed; + + writeln!(f, "{}", group.name.bold().underline())?; + writeln!(f, " Tests Passed: {}", group.passed.to_string().green())?; + if group.failed != 0 { + writeln!(f, " Tests Failed: {}", group.failed.to_string().red())?; + } + } + + writeln!(f, "\n{}", "Total Test Summary:".bold().underline())?; + writeln!(f, " Total Tests: {}", total_passed + total_failed)?; + writeln!(f, " Total Passed: {}", total_passed.to_string().green())?; + writeln!(f, " Total Failed: {}", total_failed.to_string().red())?; + Ok(()) + } +} diff --git a/crates/cli/src/value_parse.rs b/crates/cli/src/value_parse.rs index eabbdc4..3191eaf 100644 --- a/crates/cli/src/value_parse.rs +++ b/crates/cli/src/value_parse.rs @@ -1,4 +1,4 @@ -use eyre::{Result, bail}; +use anyhow::{Result, bail}; use tinywasm::types::{FuncType, WasmType, WasmValue}; use crate::output::format_wasm_type; @@ -33,8 +33,8 @@ fn parse_arg(index: usize, ty: WasmType, value: &str) -> Result { Ok(parsed) } -fn format_error(index: usize, ty: WasmType, value: &str, error: impl core::fmt::Display) -> eyre::Report { - eyre::eyre!("failed to parse argument {} as {} from `{value}`: {error}", index + 1, format_wasm_type(ty)) +fn format_error(index: usize, ty: WasmType, value: &str, error: impl core::fmt::Display) -> anyhow::Error { + anyhow::anyhow!("failed to parse argument {} as {} from `{value}`: {error}", index + 1, format_wasm_type(ty)) } #[cfg(test)] diff --git a/crates/cli/src/wast_runner.rs b/crates/cli/src/wast_runner.rs index 24483b6..1b8ae9c 100644 --- a/crates/cli/src/wast_runner.rs +++ b/crates/cli/src/wast_runner.rs @@ -5,7 +5,7 @@ use std::panic::{self, AssertUnwindSafe}; use std::path::PathBuf; use std::time::Duration; -use eyre::{Context, Result, bail, eyre}; +use anyhow::{Context, Result, anyhow, bail}; use log::{debug, error}; use tinywasm::types::{ AbstractHeapType as TinyAbstractHeapType, AnyRef, ExternRef, FuncRef, MemoryType, RefType, RefValue, TableType, @@ -111,7 +111,7 @@ impl WastRunner { self.print_errors(); if self.failed() { anstream::println!("{self}"); - Err(eyre!("failed one or more tests")) + Err(anyhow!("failed one or more tests")) } else { anstream::println!("{self}"); Ok(()) @@ -238,7 +238,7 @@ impl WastRunner { test_group.add_result( &format!("Register({i})"), span.linecol_in(wast_raw), - Err(eyre!("module instance to register was not found")), + Err(anyhow!("module instance to register was not found")), ); continue; } @@ -251,7 +251,7 @@ impl WastRunner { .expect("failed to instantiate module"); (name, instance) }) - .map_err(|e| eyre!("failed to parse wat module: {}", try_downcast_panic(e))); + .map_err(|e| anyhow!("failed to parse wat module: {}", try_downcast_panic(e))); match &result { Err(err) => debug!("failed to parse module: {err:?}"), @@ -263,7 +263,7 @@ impl WastRunner { ModuleDefinition(module) => { let result = catch_unwind_silent(|| parse_quote_module(module).expect("failed to parse module definition")) - .map_err(|err| eyre!("failed to parse module definition: {}", try_downcast_panic(err))); + .map_err(|err| anyhow!("failed to parse module definition: {}", try_downcast_panic(err))); if let Ok((name, module)) = &result { module_registry.define(module.clone(), name.clone()); @@ -280,10 +280,10 @@ impl WastRunner { let result = catch_unwind_silent(|| { let module = module_registry .definition(module) - .ok_or_else(|| eyre!("module definition was not found"))?; + .ok_or_else(|| anyhow!("module definition was not found"))?; Self::instantiate_module(&mut store, &module_registry, &module) }) - .map_err(|err| eyre!("failed to instantiate module definition: {}", try_downcast_panic(err))) + .map_err(|err| anyhow!("failed to instantiate module definition: {}", try_downcast_panic(err))) .and_then(|result| result); if let Ok(instance) = &result { @@ -301,7 +301,7 @@ impl WastRunner { continue; }; let res = catch_unwind_silent(|| parse_module_bytes(&encoded)) - .map_err(|e| eyre!("failed to parse module (expected): {}", try_downcast_panic(e))) + .map_err(|e| anyhow!("failed to parse module (expected): {}", try_downcast_panic(e))) .and_then(|res| res); test_group.add_result( &format!("AssertMalformed({i})"), @@ -314,7 +314,7 @@ impl WastRunner { { continue; } - Err(eyre!("expected module to be malformed: {message}")) + Err(anyhow!("expected module to be malformed: {message}")) } Err(_) => Ok(()), }, @@ -326,13 +326,13 @@ impl WastRunner { continue; } let res = catch_unwind_silent(move || parse_module_bytes(&module.encode().unwrap())) - .map_err(|e| eyre!("failed to parse module (invalid): {}", try_downcast_panic(e))) + .map_err(|e| anyhow!("failed to parse module (invalid): {}", try_downcast_panic(e))) .and_then(|res| res); test_group.add_result( &format!("AssertInvalid({i})"), span.linecol_in(wast_raw), match res { - Ok(_) => Err(eyre!("expected module to be invalid")), + Ok(_) => Err(anyhow!("expected module to be invalid")), Err(_) => Ok(()), }, ); @@ -346,7 +346,7 @@ impl WastRunner { test_group.add_result( &format!("AssertExhaustion({i})"), span.linecol_in(wast_raw), - Err(eyre!("expected trap")), + Err(anyhow!("expected trap")), ); continue; }; @@ -354,7 +354,7 @@ impl WastRunner { test_group.add_result( &format!("AssertExhaustion({i})"), span.linecol_in(wast_raw), - Err(eyre!("expected trap: {}, got: {}", message, trap.message())), + Err(anyhow!("expected trap: {}, got: {}", message, trap.message())), ); continue; } @@ -382,14 +382,14 @@ impl WastRunner { Err(err) => test_group.add_result( &format!("AssertTrap({i})"), span.linecol_in(wast_raw), - Err(eyre!("test panicked: {}", try_downcast_panic(err))), + Err(anyhow!("test panicked: {}", try_downcast_panic(err))), ), Ok(Err(tinywasm::Error::Trap(trap))) => { if !message.starts_with(trap.message()) && !trap.message().starts_with(message) { test_group.add_result( &format!("AssertTrap({i})"), span.linecol_in(wast_raw), - Err(eyre!("expected trap: {}, got: {}", message, trap.message())), + Err(anyhow!("expected trap: {}, got: {}", message, trap.message())), ); continue; } @@ -398,12 +398,12 @@ impl WastRunner { Ok(Err(err)) => test_group.add_result( &format!("AssertTrap({i})"), span.linecol_in(wast_raw), - Err(eyre!("expected trap, {}, got: {:?}", message, err)), + Err(anyhow!("expected trap, {}, got: {:?}", message, err)), ), Ok(Ok(())) => test_group.add_result( &format!("AssertTrap({i})"), span.linecol_in(wast_raw), - Err(eyre!("expected trap {}, got Ok", message)), + Err(anyhow!("expected trap {}, got Ok", message)), ), } } @@ -426,10 +426,10 @@ impl WastRunner { exec_fn_instance(module, &mut store, invoke.name, &args).map(|_| ()) }); let result = match res { - Err(err) => Err(eyre!("test panicked: {}", try_downcast_panic(err))), + Err(err) => Err(anyhow!("test panicked: {}", try_downcast_panic(err))), Ok(Err(tinywasm::Error::Exception(_))) => Ok(()), - Ok(Err(err)) => Err(eyre!("expected exception, got: {err:?}")), - Ok(Ok(())) => Err(eyre!("expected exception, got Ok")), + Ok(Err(err)) => Err(anyhow!("expected exception, got: {err:?}")), + Ok(Ok(())) => Err(anyhow!("expected exception, got Ok")), }; test_group.add_result(&format!("AssertException({i})"), span.linecol_in(wast_raw), result); } @@ -444,7 +444,7 @@ impl WastRunner { Err(err) => test_group.add_result( &format!("AssertUnlinkable({i})"), span.linecol_in(wast_raw), - Err(eyre!("test panicked: {}", try_downcast_panic(err))), + Err(anyhow!("test panicked: {}", try_downcast_panic(err))), ), Ok(Err(tinywasm::Error::Linker(err))) => { if err.message() != message @@ -454,7 +454,7 @@ impl WastRunner { test_group.add_result( &format!("AssertUnlinkable({i})"), span.linecol_in(wast_raw), - Err(eyre!("expected linker error: {}, got: {}", message, err.message())), + Err(anyhow!("expected linker error: {}, got: {}", message, err.message())), ); continue; } @@ -463,12 +463,12 @@ impl WastRunner { Ok(Err(err)) => test_group.add_result( &format!("AssertUnlinkable({i})"), span.linecol_in(wast_raw), - Err(eyre!("expected linker error, {}, got: {:?}", message, err)), + Err(anyhow!("expected linker error, {}, got: {:?}", message, err)), ), Ok(Ok(_)) => test_group.add_result( &format!("AssertUnlinkable({i})"), span.linecol_in(wast_raw), - Err(eyre!("expected linker error {}, got Ok", message)), + Err(anyhow!("expected linker error {}, got Ok", message)), ), } } @@ -483,7 +483,7 @@ impl WastRunner { })?; Ok(()) }); - let res = res.map_err(|e| eyre!("test panicked: {}", try_downcast_panic(e))).and_then(|r| r); + let res = res.map_err(|e| anyhow!("test panicked: {}", try_downcast_panic(e))).and_then(|r| r); test_group.add_result(&format!("Invoke({name}-{i})"), span.linecol_in(wast_raw), res); } AssertReturn { span, exec, results } => { @@ -492,7 +492,7 @@ impl WastRunner { test_group.add_result( &format!("AssertReturn(unsupported-{i})"), span.linecol_in(wast_raw), - Err(eyre!("failed to convert expected results: {err:?}")), + Err(anyhow!("failed to convert expected results: {err:?}")), ); continue; } @@ -500,13 +500,13 @@ impl WastRunner { }; let invoke = match match exec { - wast::WastExecute::Wat(_) => Err(eyre!("wat not supported")), + wast::WastExecute::Wat(_) => Err(anyhow!("wat not supported")), wast::WastExecute::Get { module: module_id, global, .. } => { let Some(module) = module_registry.get(module_id) else { test_group.add_result( &format!("AssertReturn(unsupported-{i})"), span.linecol_in(wast_raw), - Err(eyre!("no module to get global from")), + Err(anyhow!("no module to get global from")), ); continue; }; @@ -516,7 +516,7 @@ impl WastRunner { test_group.add_result( &format!("AssertReturn(unsupported-{i})"), span.linecol_in(wast_raw), - Err(eyre!("failed to get global: {err:?}")), + Err(anyhow!("failed to get global: {err:?}")), ); continue; } @@ -529,7 +529,7 @@ impl WastRunner { test_group.add_result( &format!("AssertReturn(unsupported-{i})"), span.linecol_in(wast_raw), - Err(eyre!( + Err(anyhow!( "global value did not match any expected alternative: {:?}", module_global )), @@ -550,7 +550,7 @@ impl WastRunner { test_group.add_result( &format!("AssertReturn(unsupported-{i})"), span.linecol_in(wast_raw), - Err(eyre!("unsupported directive: {err:?}")), + Err(anyhow!("unsupported directive: {err:?}")), ); continue; } @@ -565,7 +565,7 @@ impl WastRunner { e })?; if !expected_alternatives.iter().any(|expected| expected.len() == outcomes.len()) { - return Err(eyre!( + return Err(anyhow!( "expected {} results, got {}", expected_alternatives.first().map_or(0, |v| v.len()), outcomes.len() @@ -580,17 +580,17 @@ impl WastRunner { }) { Ok(()) } else { - Err(eyre!("results did not match any expected alternative")) + Err(anyhow!("results did not match any expected alternative")) } }); - let res = res.map_err(|e| eyre!("test panicked: {}", try_downcast_panic(e))).and_then(|r| r); + let res = res.map_err(|e| anyhow!("test panicked: {}", try_downcast_panic(e))).and_then(|r| r); test_group.add_result(&format!("AssertReturn({invoke_name}-{i})"), span.linecol_in(wast_raw), res); } _ => test_group.add_result( &format!("Unknown({i})"), span.linecol_in(wast_raw), - Err(eyre!("unsupported directive")), + Err(anyhow!("unsupported directive")), ), } } @@ -828,7 +828,7 @@ fn wastarg2tinywasmvalue(arg: wast::WastArg) -> Result { I32(i) => WasmValue::I32(i), I64(i) => WasmValue::I64(i), V128(i) => WasmValue::V128(i.to_le_bytes()), - RefExtern(v) => ExternRef::try_new(v).ok_or_else(|| eyre!("external reference address is too large"))?.into(), + RefExtern(v) => ExternRef::try_new(v).ok_or_else(|| anyhow!("external reference address is too large"))?.into(), RefNull(t) => match t { wast::core::HeapType::Abstract { shared: false, ty: AbstractHeapType::Func } => RefValue::Null.into(), wast::core::HeapType::Abstract { shared: false, ty: AbstractHeapType::Extern | AbstractHeapType::Any } => { @@ -839,7 +839,8 @@ fn wastarg2tinywasmvalue(arg: wast::WastArg) -> Result { } }, RefHost(value) => { - RefValue::Any(AnyRef::from_host(value).ok_or_else(|| eyre!("host reference address is too large"))?).into() + RefValue::Any(AnyRef::from_host(value).ok_or_else(|| anyhow!("host reference address is too large"))?) + .into() } }) } @@ -918,7 +919,7 @@ fn wastretcore2tinywasmvalue(ret: wast::core::WastRetCore) -> Result ExpectedValue::Exact(WasmValue::V128(wast_v128_to_bytes(i))), RefNull(_) => ExpectedValue::RefNull, RefExtern(Some(v)) => ExpectedValue::Exact( - ExternRef::try_new(v).ok_or_else(|| eyre!("external reference address is too large"))?.into(), + ExternRef::try_new(v).ok_or_else(|| anyhow!("external reference address is too large"))?.into(), ), RefExtern(None) => ExpectedValue::RefExtern, RefFunc(Some(wast::token::Index::Num(n, _))) => ExpectedValue::Exact(FuncRef::new(n).into()), @@ -932,7 +933,8 @@ fn wastretcore2tinywasmvalue(ret: wast::core::WastRetCore) -> Result ExpectedValue::RefStruct, RefArray => ExpectedValue::RefArray, RefHost(value) => ExpectedValue::Exact( - RefValue::Any(AnyRef::from_host(value).ok_or_else(|| eyre!("host reference address is too large"))?).into(), + RefValue::Any(AnyRef::from_host(value).ok_or_else(|| anyhow!("host reference address is too large"))?) + .into(), ), a => { bail!("unsupported arg type {:?}", a); diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml index 65ef7f8..eb5dd94 100644 --- a/crates/tinywasm/Cargo.toml +++ b/crates/tinywasm/Cargo.toml @@ -85,26 +85,6 @@ name = "test-wasm-simd" harness = false name = "test-wasm-wide-arithmetic" -[[bench]] -harness = false -name = "argon2id" - -[[bench]] -harness = false -name = "fibonacci" - -[[bench]] -harness = false -name = "tinywasm" - -[[bench]] -harness = false -name = "tinywasm_modes" - -[[bench]] -harness = false -name = "memory_backends" - [dependencies] libm = { version = "0.2", default-features = false } log = { workspace = true, optional = true } @@ -112,12 +92,7 @@ tinywasm-parser = { workspace = true, optional = true } tinywasm-types = { workspace = true } [dev-dependencies] -criterion.workspace = true -eyre.workspace = true -owo-colors.workspace = true -serde.workspace = true -serde_json.workspace = true -tinywasm-cli = { path = "../cli", features = ["wast", "wat"] } +tinywasm-cli = { path = "../cli", features = ["tests", "wat"] } wasm-testsuite.workspace = true wat.workspace = true diff --git a/crates/tinywasm/benches/argon2id.rs b/crates/tinywasm/benches/argon2id.rs deleted file mode 100644 index d2845c5..0000000 --- a/crates/tinywasm/benches/argon2id.rs +++ /dev/null @@ -1,47 +0,0 @@ -use criterion::{Criterion, criterion_group, criterion_main}; -use eyre::Result; -use tinywasm::{ModuleInstance, Store, types}; -use types::Module; - -const WASM: &[u8] = include_bytes!("../../../examples/rust/out/argon2id.wasm"); - -fn argon2id_parse() -> Result { - let parser = tinywasm_parser::Parser::default(); - let data = parser.parse_module_bytes(WASM)?; - Ok(data) -} - -fn argon2id_to_twasm(module: &Module) -> Result> { - let twasm = module.serialize_twasm()?; - Ok(twasm) -} - -fn argon2id_from_twasm(twasm: &[u8]) -> Result { - let module = Module::try_from_twasm(twasm)?; - Ok(module) -} - -fn argon2id_run(module: Module) -> Result<()> { - let mut store = Store::default(); - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - let argon2 = instance.func::<(i32, i32, i32), i32>(&store, "argon2id")?; - argon2.call(&mut store, (1000, 2, 1))?; - Ok(()) -} - -fn criterion_benchmark(c: &mut Criterion) { - let module = argon2id_parse().expect("argon2id_parse"); - let twasm = argon2id_to_twasm(&module).expect("argon2id_to_twasm"); - let mut group = c.benchmark_group("argon2id"); - - group.measurement_time(std::time::Duration::from_secs(2)); - group.bench_function("argon2id_parse", |b| b.iter(argon2id_parse)); - group.bench_function("argon2id_to_twasm", |b| b.iter(|| argon2id_to_twasm(&module))); - group.bench_function("argon2id_from_twasm", |b| b.iter(|| argon2id_from_twasm(&twasm))); - - group.measurement_time(std::time::Duration::from_secs(10)); - group.bench_function("argon2id", |b| b.iter(|| argon2id_run(module.clone()))); -} - -criterion_group!(benches, criterion_benchmark); -criterion_main!(benches); diff --git a/crates/tinywasm/benches/fibonacci.rs b/crates/tinywasm/benches/fibonacci.rs deleted file mode 100644 index 1bf0791..0000000 --- a/crates/tinywasm/benches/fibonacci.rs +++ /dev/null @@ -1,53 +0,0 @@ -use criterion::{Criterion, criterion_group, criterion_main}; -use eyre::Result; -use tinywasm::{ModuleInstance, Store, types}; -use types::Module; - -const WASM: &[u8] = include_bytes!("../../../examples/rust/out/fibonacci.wasm"); - -fn fibonacci_parse() -> Result { - let parser = tinywasm_parser::Parser::default(); - let data = parser.parse_module_bytes(WASM)?; - Ok(data) -} - -fn fibonacci_to_twasm(module: &Module) -> Result> { - let twasm = module.serialize_twasm()?; - Ok(twasm) -} - -fn fibonacci_from_twasm(twasm: &[u8]) -> Result { - Ok(Module::try_from_twasm(twasm)?) -} - -fn fibonacci_run(module: Module, recursive: bool, n: i32) -> Result<()> { - let mut store = Store::default(); - let instance = ModuleInstance::instantiate(&mut store, &module, None)?; - let argon2 = instance.func::( - &store, - match recursive { - true => "fibonacci_recursive", - false => "fibonacci", - }, - )?; - argon2.call(&mut store, n)?; - Ok(()) -} - -fn criterion_benchmark(c: &mut Criterion) { - let module = fibonacci_parse().expect("fibonacci_parse"); - let twasm = fibonacci_to_twasm(&module).expect("fibonacci_to_twasm"); - let mut group = c.benchmark_group("fibonacci"); - - group.measurement_time(std::time::Duration::from_secs(2)); - group.bench_function("fibonacci_parse", |b| b.iter(fibonacci_parse)); - group.bench_function("fibonacci_to_twasm", |b| b.iter(|| fibonacci_to_twasm(&module))); - group.bench_function("fibonacci_from_twasm", |b| b.iter(|| fibonacci_from_twasm(&twasm))); - - group.measurement_time(std::time::Duration::from_secs(10)); - group.bench_function("fibonacci_iterative_60", |b| b.iter(|| fibonacci_run(module.clone(), false, 60))); - group.bench_function("fibonacci_recursive_26", |b| b.iter(|| fibonacci_run(module.clone(), true, 26))); -} - -criterion_group!(benches, criterion_benchmark); -criterion_main!(benches); diff --git a/crates/tinywasm/benches/memory_backends.rs b/crates/tinywasm/benches/memory_backends.rs deleted file mode 100644 index 3a59f8c..0000000 --- a/crates/tinywasm/benches/memory_backends.rs +++ /dev/null @@ -1,152 +0,0 @@ -use criterion::measurement::WallTime; -use criterion::{BatchSize, BenchmarkGroup, BenchmarkId, Criterion, criterion_group, criterion_main}; -use std::hint::black_box; -use tinywasm::{LinearMemory, PagedMemory, VecMemory}; - -const PAGE_SIZE: usize = 64 * 1024; -const CHUNK_SIZE: usize = 4 * 1024; -const GROW_STEPS: usize = 32; -const BENCH_MEASUREMENT_TIME: std::time::Duration = std::time::Duration::from_secs(10); - -const MEMORY_LEN: usize = PAGE_SIZE * 4; -const CONTIGUOUS_OFFSET: usize = 1024; -const CONTIGUOUS_LEN: usize = 2048; -const CROSS_CHUNK_OFFSET: usize = CHUNK_SIZE - 512; -const CROSS_CHUNK_LEN: usize = CHUNK_SIZE * 2; - -fn bench_grow(group: &mut BenchmarkGroup<'_, WallTime>, backend: &str, make_memory: F) -where - M: LinearMemory, - F: Fn() -> M + Copy, -{ - group.bench_function(BenchmarkId::new("grow", backend), |b| { - b.iter_batched( - make_memory, - |mut memory| { - for page_count in 2..=GROW_STEPS + 1 { - memory.grow_to(page_count * PAGE_SIZE).unwrap(); - } - black_box(memory.len()) - }, - BatchSize::SmallInput, - ) - }); -} - -fn bench_write_all( - group: &mut BenchmarkGroup<'_, WallTime>, - backend: &str, - workload: &str, - mut memory: M, - offset: usize, - len: usize, -) { - let src = vec![0xA5; len]; - group.bench_function(BenchmarkId::new(format!("write_all/{workload}"), backend), |b| { - b.iter(|| { - memory.write_all(offset, black_box(&src)).unwrap(); - black_box(memory.len()) - }) - }); -} - -fn bench_read_exact( - group: &mut BenchmarkGroup<'_, WallTime>, - backend: &str, - workload: &str, - mut memory: M, - offset: usize, - len: usize, -) { - let src = vec![0x5A; len]; - memory.write_all(offset, &src).unwrap(); - - let mut dst = vec![0; len]; - group.bench_function(BenchmarkId::new(format!("read_exact/{workload}"), backend), |b| { - b.iter(|| { - memory.read_exact(offset, black_box(&mut dst)).unwrap(); - black_box(&dst); - }) - }); -} - -fn criterion_benchmark(c: &mut Criterion) { - let mut group = c.benchmark_group("memory_backends"); - group.measurement_time(BENCH_MEASUREMENT_TIME); - - bench_grow(&mut group, "vec", || VecMemory::try_new(PAGE_SIZE).expect("bench memory should be constructible")); - bench_grow(&mut group, "paged", || { - PagedMemory::try_new(PAGE_SIZE, CHUNK_SIZE).expect("bench memory should be constructible") - }); - - bench_write_all( - &mut group, - "vec", - "contiguous", - VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"), - CONTIGUOUS_OFFSET, - CONTIGUOUS_LEN, - ); - bench_write_all( - &mut group, - "paged", - "contiguous", - PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"), - CONTIGUOUS_OFFSET, - CONTIGUOUS_LEN, - ); - bench_read_exact( - &mut group, - "vec", - "contiguous", - VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"), - CONTIGUOUS_OFFSET, - CONTIGUOUS_LEN, - ); - bench_read_exact( - &mut group, - "paged", - "contiguous", - PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"), - CONTIGUOUS_OFFSET, - CONTIGUOUS_LEN, - ); - - bench_write_all( - &mut group, - "vec", - "cross_chunk", - VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"), - CROSS_CHUNK_OFFSET, - CROSS_CHUNK_LEN, - ); - bench_write_all( - &mut group, - "paged", - "cross_chunk", - PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"), - CROSS_CHUNK_OFFSET, - CROSS_CHUNK_LEN, - ); - bench_read_exact( - &mut group, - "vec", - "cross_chunk", - VecMemory::try_new(MEMORY_LEN).expect("bench memory should be constructible"), - CROSS_CHUNK_OFFSET, - CROSS_CHUNK_LEN, - ); - bench_read_exact( - &mut group, - "paged", - "cross_chunk", - PagedMemory::try_new(MEMORY_LEN, CHUNK_SIZE).expect("bench memory should be constructible"), - CROSS_CHUNK_OFFSET, - CROSS_CHUNK_LEN, - ); - - group.finish(); -} - -criterion_group!(benches, criterion_benchmark); -criterion_main!(benches); diff --git a/crates/tinywasm/benches/tinywasm.rs b/crates/tinywasm/benches/tinywasm.rs deleted file mode 100644 index 3560d3c..0000000 --- a/crates/tinywasm/benches/tinywasm.rs +++ /dev/null @@ -1,50 +0,0 @@ -use criterion::{Criterion, criterion_group, criterion_main}; -use eyre::Result; -use tinywasm::engine::Config; -use tinywasm::{Engine, FuncContext, HostFunction, Imports, ModuleInstance, Store, types}; -use types::Module; - -const WASM: &[u8] = include_bytes!("../../../examples/rust/out/tinywasm.wasm"); - -fn tinywasm_parse() -> Result { - let parser = tinywasm_parser::Parser::default(); - let data = parser.parse_module_bytes(WASM)?; - Ok(data) -} - -fn tinywasm_to_twasm(module: &Module) -> Result> { - let twasm = module.serialize_twasm()?; - Ok(twasm) -} - -fn tinywasm_from_twasm(twasm: &[u8]) -> Result { - let module = Module::try_from_twasm(twasm)?; - Ok(module) -} - -fn tinywasm_run(module: &Module) -> Result<()> { - let engine = Engine::new(Config::default()); - let mut store = Store::new(engine); - let mut imports = Imports::default(); - imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _: i32| Ok(()))); - let instance = ModuleInstance::instantiate(&mut store, module, Some(&imports)).expect("instantiate"); - let hello = instance.func::<(), ()>(&store, "hello").expect("func_typed"); - hello.call(&mut store, ()).expect("call"); - Ok(()) -} - -fn criterion_benchmark(c: &mut Criterion) { - let module = tinywasm_parse().expect("tinywasm_parse"); - let twasm = tinywasm_to_twasm(&module).expect("tinywasm_to_twasm"); - let mut group = c.benchmark_group("tinywasm"); - - group.measurement_time(std::time::Duration::from_secs(2)); - group.bench_function("tinywasm_parse", |b| b.iter(tinywasm_parse)); - group.bench_function("tinywasm_to_twasm", |b| b.iter(|| tinywasm_to_twasm(&module))); - group.bench_function("tinywasm_from_twasm", |b| b.iter(|| tinywasm_from_twasm(&twasm))); - group.measurement_time(std::time::Duration::from_secs(10)); - group.bench_function("tinywasm", |b| b.iter(|| tinywasm_run(&module))); -} - -criterion_group!(benches, criterion_benchmark); -criterion_main!(benches); diff --git a/crates/tinywasm/benches/tinywasm_modes.rs b/crates/tinywasm/benches/tinywasm_modes.rs deleted file mode 100644 index 6c1badf..0000000 --- a/crates/tinywasm/benches/tinywasm_modes.rs +++ /dev/null @@ -1,99 +0,0 @@ -use criterion::{BatchSize, Criterion, criterion_group, criterion_main}; -use eyre::Result; -use tinywasm::engine::{Config, FuelPolicy}; -use tinywasm::types::Module; -use tinywasm::{Engine, ExecProgress, FuncContext, FunctionTyped, HostFunction, Imports, ModuleInstance, Store}; - -const WASM: &[u8] = include_bytes!("../../../examples/rust/out/tinywasm.wasm"); -const FUEL_PER_ROUND: u32 = 512; -const TIME_BUDGET_PER_ROUND: core::time::Duration = core::time::Duration::from_micros(50); -const BENCH_MEASUREMENT_TIME: core::time::Duration = core::time::Duration::from_secs(10); - -fn tinywasm_parse() -> Result { - let parser = tinywasm_parser::Parser::default(); - Ok(parser.parse_module_bytes(WASM)?) -} - -fn setup_typed_func(module: &Module, engine: Option) -> Result<(Store, FunctionTyped<(), ()>)> { - let mut store = match engine { - Some(engine) => Store::new(engine), - None => Store::default(), - }; - - let mut imports = Imports::default(); - imports.define("env", "printi32", HostFunction::from(|_: FuncContext<'_>, _: i32| Ok(()))); - - let instance = ModuleInstance::instantiate(&mut store, module, Some(&imports))?; - let func = instance.func::<(), ()>(&store, "hello")?; - Ok((store, func)) -} - -fn run_call(store: &mut Store, func: &FunctionTyped<(), ()>) -> Result<()> { - func.call(store, ())?; - Ok(()) -} - -fn run_resume_with_fuel(store: &mut Store, func: &FunctionTyped<(), ()>) -> Result<()> { - let mut execution = func.call_resumable(store, ())?; - loop { - match execution.resume_with_fuel(FUEL_PER_ROUND)? { - ExecProgress::Completed(_) => return Ok(()), - ExecProgress::Suspended => {} - } - } -} - -fn run_resume_with_time_budget(store: &mut Store, func: &FunctionTyped<(), ()>) -> Result<()> { - let mut execution = func.call_resumable(store, ())?; - loop { - match execution.resume_with_time_budget(TIME_BUDGET_PER_ROUND)? { - ExecProgress::Completed(_) => return Ok(()), - ExecProgress::Suspended => {} - } - } -} - -fn criterion_benchmark(c: &mut Criterion) { - let module = tinywasm_parse().expect("tinywasm_parse"); - let mut group = c.benchmark_group("tinywasm_modes"); - group.measurement_time(BENCH_MEASUREMENT_TIME); - - let per_instruction_engine = Engine::new(Config::new().with_fuel_policy(FuelPolicy::PerInstruction)); - group.bench_function("resume_fuel_per_instruction", |b| { - b.iter_batched_ref( - || setup_typed_func(&module, Some(per_instruction_engine.clone())).expect("setup fuel per-instruction"), - |(store, func)| run_resume_with_fuel(store, func).expect("run fuel per-instruction"), - BatchSize::LargeInput, - ) - }); - - let weighted_engine = Engine::new(Config::new().with_fuel_policy(FuelPolicy::Weighted)); - group.bench_function("resume_fuel_weighted", |b| { - b.iter_batched_ref( - || setup_typed_func(&module, Some(weighted_engine.clone())).expect("setup fuel weighted"), - |(store, func)| run_resume_with_fuel(store, func).expect("run fuel weighted"), - BatchSize::LargeInput, - ) - }); - - group.bench_function("resume_time_budget", |b| { - b.iter_batched_ref( - || setup_typed_func(&module, None).expect("setup time budget"), - |(store, func)| run_resume_with_time_budget(store, func).expect("run time budget"), - BatchSize::LargeInput, - ) - }); - - group.bench_function("call", |b| { - b.iter_batched_ref( - || setup_typed_func(&module, None).expect("setup call"), - |(store, func)| run_call(store, func).expect("run call"), - BatchSize::LargeInput, - ) - }); - - group.finish(); -} - -criterion_group!(benches, criterion_benchmark); -criterion_main!(benches); diff --git a/crates/tinywasm/tests/host_func_signature_check.rs b/crates/tinywasm/tests/host_func_signature_check.rs index 35e0d9b..128f1ed 100644 --- a/crates/tinywasm/tests/host_func_signature_check.rs +++ b/crates/tinywasm/tests/host_func_signature_check.rs @@ -1,8 +1,6 @@ -use eyre::Result; use std::fmt::Write; -use tinywasm::types::{FuncType, RefType, RefValue, WasmType, WasmValue}; +use tinywasm::types::{ExternRef, FuncType, RefType, RefValue, WasmType, WasmValue}; use tinywasm::{FuncContext, HostFunction, Imports, Module, ModuleInstance, Store}; -use tinywasm_types::ExternRef; const VAL_LISTS: &[&[WasmValue]] = &[ &[], @@ -27,7 +25,7 @@ fn module_cases() -> Vec<(Module, FuncType, Vec)> { } #[test] -fn test_return_invalid_type() -> Result<()> { +fn test_return_invalid_type() -> Result<(), Box> { let cases = module_cases(); for (module, ty, args) in cases { @@ -51,7 +49,7 @@ fn test_return_invalid_type() -> Result<()> { } #[test] -fn test_linking_invalid_untyped_func() -> Result<()> { +fn test_linking_invalid_untyped_func() -> Result<(), Box> { let cases = module_cases(); for (module, expected_func_ty, _) in &cases { for (_, ty, _) in &cases { @@ -69,7 +67,7 @@ fn test_linking_invalid_untyped_func() -> Result<()> { } #[test] -fn test_linking_invalid_typed_func() -> Result<()> { +fn test_linking_invalid_typed_func() -> Result<(), Box> { type Existing = (i32, i32, f64); type NonMatchingSingle = f64; type NonMatchingTuple = (f64, i32, i32); @@ -107,7 +105,7 @@ fn test_linking_invalid_typed_func() -> Result<()> { } #[test] -fn concrete_host_references_use_canonical_types() -> Result<()> { +fn concrete_host_references_use_canonical_types() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -145,7 +143,7 @@ fn concrete_host_references_use_canonical_types() -> Result<()> { } #[test] -fn imported_host_functions_resolve_concrete_types() -> Result<()> { +fn imported_host_functions_resolve_concrete_types() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -173,7 +171,7 @@ fn imported_host_functions_resolve_concrete_types() -> Result<()> { } #[test] -fn host_tail_calls_return_from_the_current_frame() -> Result<()> { +fn host_tail_calls_return_from_the_current_frame() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -210,7 +208,7 @@ fn host_tail_calls_return_from_the_current_frame() -> Result<()> { } #[test] -fn host_calls_reject_unknown_function_references() -> Result<()> { +fn host_calls_reject_unknown_function_references() -> Result<(), Box> { let mut store = Store::default(); let ty = FuncType::new(&[WasmType::Ref(tinywasm::types::RefType::FUNCREF)], &[]); let host = HostFunction::from_untyped(&ty, |_, _| Ok(Vec::new())).instantiate(&mut store)?; diff --git a/crates/tinywasm/tests/import_linking.rs b/crates/tinywasm/tests/import_linking.rs index 1d5db1b..a65c8a4 100644 --- a/crates/tinywasm/tests/import_linking.rs +++ b/crates/tinywasm/tests/import_linking.rs @@ -1,4 +1,3 @@ -use eyre::Result; use tinywasm::{Error, Imports, Module, ModuleInstance, Store, Trap}; const WASM_ADD: &str = r#" @@ -19,14 +18,14 @@ const WASM_IMPORT: &str = r#" call $add)) "#; -fn parse_modules() -> Result<(Module, Module)> { +fn parse_modules() -> Result<(Module, Module), Box> { let add = tinywasm::parse_bytes(&wat::parse_str(WASM_ADD)?)?; let import = tinywasm::parse_bytes(&wat::parse_str(WASM_IMPORT)?)?; Ok((add, import)) } #[test] -fn link_module_links_same_store_instance() -> Result<()> { +fn link_module_links_same_store_instance() -> Result<(), Box> { let (add_module, import_module) = parse_modules()?; let mut store = Store::default(); @@ -41,7 +40,7 @@ fn link_module_links_same_store_instance() -> Result<()> { } #[test] -fn link_module_rejects_cross_store_instance() -> Result<()> { +fn link_module_rejects_cross_store_instance() -> Result<(), Box> { let (add_module, import_module) = parse_modules()?; let mut source_store = Store::default(); diff --git a/crates/tinywasm/tests/imported_table_init.rs b/crates/tinywasm/tests/imported_table_init.rs index ca52e9e..aaa781b 100644 --- a/crates/tinywasm/tests/imported_table_init.rs +++ b/crates/tinywasm/tests/imported_table_init.rs @@ -1,9 +1,8 @@ -use eyre::Result; use tinywasm::types::{FuncRef, RefType, TableType}; use tinywasm::{HostFunction, Imports, ModuleInstance, Store, Table}; #[test] -fn imported_table_uses_provided_init_value() -> Result<()> { +fn imported_table_uses_provided_init_value() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module diff --git a/crates/tinywasm/tests/internal_refs.rs b/crates/tinywasm/tests/internal_refs.rs index 196ad0a..07cbde2 100644 --- a/crates/tinywasm/tests/internal_refs.rs +++ b/crates/tinywasm/tests/internal_refs.rs @@ -1,4 +1,3 @@ -use eyre::Result; use tinywasm::types::WasmValue; #[cfg(feature = "guest-debug")] use tinywasm::types::{FuncRef, RefValue}; @@ -6,7 +5,7 @@ use tinywasm::{ExternItem, ModuleInstance, Store}; #[test] #[cfg(feature = "guest-debug")] -fn private_items_are_accessible_by_index() -> Result<()> { +fn private_items_are_accessible_by_index() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -42,7 +41,7 @@ fn private_items_are_accessible_by_index() -> Result<()> { } #[test] -fn exported_tables_and_globals_have_handle_and_helper_apis() -> Result<()> { +fn exported_tables_and_globals_have_handle_and_helper_apis() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -73,7 +72,7 @@ fn exported_tables_and_globals_have_handle_and_helper_apis() -> Result<()> { } #[test] -fn extern_item_lookup_returns_expected_kinds() -> Result<()> { +fn extern_item_lookup_returns_expected_kinds() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -98,7 +97,7 @@ fn extern_item_lookup_returns_expected_kinds() -> Result<()> { } #[test] -fn extern_item_and_exports_use_actual_function_type() -> Result<()> { +fn extern_item_and_exports_use_actual_function_type() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -134,7 +133,7 @@ fn extern_item_and_exports_use_actual_function_type() -> Result<()> { } #[test] -fn export_func_type_index_mismatch_fixture_would_break_old_lookup() -> Result<()> { +fn export_func_type_index_mismatch_fixture_would_break_old_lookup() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -177,7 +176,7 @@ fn export_func_type_index_mismatch_fixture_would_break_old_lookup() -> Result<() } #[test] -fn start_resolves_module_func_index_to_store_addr() -> Result<()> { +fn start_resolves_module_func_index_to_store_addr() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module diff --git a/crates/tinywasm/tests/memory_backends.rs b/crates/tinywasm/tests/memory_backends.rs index 0cf5707..b7f9438 100644 --- a/crates/tinywasm/tests/memory_backends.rs +++ b/crates/tinywasm/tests/memory_backends.rs @@ -6,13 +6,14 @@ use core::sync::atomic::{AtomicUsize, Ordering}; #[cfg(feature = "std")] use std::io::{Read, Seek, SeekFrom, Write}; -use eyre::Result; use tinywasm::engine::Config; use tinywasm::types::{MemoryArch, MemoryType}; use tinywasm::{Engine, Memory, MemoryBackend, Module, ModuleInstance, PagedMemory, Store}; use tinywasm_parser::{Parser, ParserOptions}; -fn instantiate_module_with_counting_backend(module: Module) -> Result { +type TestResult = Result>; + +fn instantiate_module_with_counting_backend(module: Module) -> TestResult { let created = Arc::new(AtomicUsize::new(0)); let factory_calls = created.clone(); let backend = MemoryBackend::custom(move |ty| { @@ -27,7 +28,7 @@ fn instantiate_module_with_counting_backend(module: Module) -> Result { Ok(created.load(Ordering::Relaxed)) } -fn instantiate_with_counting_backend(wat: &str) -> Result { +fn instantiate_with_counting_backend(wat: &str) -> TestResult { let wasm = wat::parse_str(wat)?; let module = tinywasm::parse_bytes(&wasm)?; instantiate_module_with_counting_backend(module) @@ -35,7 +36,7 @@ fn instantiate_with_counting_backend(wat: &str) -> Result { fn instantiate_exported_memory_with_counting_backend( wat: &str, -) -> Result<(Store, tinywasm::ModuleInstance, Arc)> { +) -> TestResult<(Store, tinywasm::ModuleInstance, Arc)> { let wasm = wat::parse_str(wat)?; let module = tinywasm::parse_bytes(&wasm)?; let created = Arc::new(AtomicUsize::new(0)); @@ -51,7 +52,7 @@ fn instantiate_exported_memory_with_counting_backend( } #[test] -fn paged_backend_works_for_module_memories() -> Result<()> { +fn paged_backend_works_for_module_memories() -> TestResult { let wasm = wat::parse_str( r#" (module @@ -73,7 +74,7 @@ fn paged_backend_works_for_module_memories() -> Result<()> { } #[test] -fn custom_backend_factory_is_used_for_host_memories() -> Result<()> { +fn custom_backend_factory_is_used_for_host_memories() -> TestResult { let created = Arc::new(AtomicUsize::new(0)); let seen_page_size = Arc::new(AtomicUsize::new(0)); let factory_calls = created.clone(); @@ -100,7 +101,7 @@ fn custom_backend_factory_is_used_for_host_memories() -> Result<()> { } #[test] -fn local_memory_without_observable_use_is_not_allocated() -> Result<()> { +fn local_memory_without_observable_use_is_not_allocated() -> TestResult { let created = instantiate_with_counting_backend( r#" (module @@ -115,7 +116,7 @@ fn local_memory_without_observable_use_is_not_allocated() -> Result<()> { } #[test] -fn exported_local_memory_is_not_eagerly_allocated() -> Result<()> { +fn exported_local_memory_is_not_eagerly_allocated() -> TestResult { let created = instantiate_with_counting_backend( r#" (module @@ -129,7 +130,7 @@ fn exported_local_memory_is_not_eagerly_allocated() -> Result<()> { } #[test] -fn exported_local_memory_reads_zeroes_without_materializing() -> Result<()> { +fn exported_local_memory_reads_zeroes_without_materializing() -> TestResult { let (mut store, instance, created) = instantiate_exported_memory_with_counting_backend( r#" (module @@ -151,7 +152,7 @@ fn exported_local_memory_reads_zeroes_without_materializing() -> Result<()> { } #[test] -fn active_data_segment_on_local_memory_is_allocated() -> Result<()> { +fn active_data_segment_on_local_memory_is_allocated() -> TestResult { let created = instantiate_with_counting_backend( r#" (module @@ -166,7 +167,7 @@ fn active_data_segment_on_local_memory_is_allocated() -> Result<()> { } #[test] -fn local_memory_instruction_is_allocated() -> Result<()> { +fn local_memory_instruction_is_allocated() -> TestResult { let created = instantiate_with_counting_backend( r#" (module @@ -181,7 +182,7 @@ fn local_memory_instruction_is_allocated() -> Result<()> { } #[test] -fn disabled_local_memory_allocation_optimization_keeps_old_behavior() -> Result<()> { +fn disabled_local_memory_allocation_optimization_keeps_old_behavior() -> TestResult { let wasm = wat::parse_str( r#" (module @@ -200,7 +201,7 @@ fn disabled_local_memory_allocation_optimization_keeps_old_behavior() -> Result< } #[test] -fn read_returns_short_count_at_end_of_memory() -> Result<()> { +fn read_returns_short_count_at_end_of_memory() -> TestResult { let mut store = Store::default(); let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(1), Some(4)))?; memory.copy_from_slice(&mut store, 0, &[1, 2, 3, 4])?; @@ -214,7 +215,7 @@ fn read_returns_short_count_at_end_of_memory() -> Result<()> { } #[test] -fn paged_read_and_write_stop_at_chunk_boundaries() -> Result<()> { +fn paged_read_and_write_stop_at_chunk_boundaries() -> TestResult { let engine = Engine::new(Config::new().with_memory_backend(MemoryBackend::paged(4))); let mut store = Store::new(engine); let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(1), Some(16)))?; @@ -241,7 +242,7 @@ fn paged_read_and_write_stop_at_chunk_boundaries() -> Result<()> { #[cfg(feature = "std")] #[test] -fn memory_cursor_supports_read_write_and_seek() -> Result<()> { +fn memory_cursor_supports_read_write_and_seek() -> TestResult { let mut store = Store::default(); let memory = Memory::new(&mut store, MemoryType::new(MemoryArch::I32, 1, Some(1), Some(8)))?; diff --git a/crates/tinywasm/tests/memory_ref_api.rs b/crates/tinywasm/tests/memory_ref_api.rs index 6f72477..768c873 100644 --- a/crates/tinywasm/tests/memory_ref_api.rs +++ b/crates/tinywasm/tests/memory_ref_api.rs @@ -1,8 +1,7 @@ -use eyre::Result; use tinywasm::{ModuleInstance, Store}; #[test] -fn memory_ref_mut_copy_within_uses_src_then_dst_order() -> Result<()> { +fn memory_ref_mut_copy_within_uses_src_then_dst_order() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module diff --git a/crates/tinywasm/tests/module_descriptors.rs b/crates/tinywasm/tests/module_descriptors.rs index 81ab5ab..8bd73b6 100644 --- a/crates/tinywasm/tests/module_descriptors.rs +++ b/crates/tinywasm/tests/module_descriptors.rs @@ -1,9 +1,7 @@ -use eyre::Result; -use tinywasm::types::WasmType; -use tinywasm_types::{ExportType, ImportType}; +use tinywasm::types::{ExportType, ImportType, WasmType}; #[test] -fn module_descriptors_resolve_imported_and_local_export_types() -> Result<()> { +fn module_descriptors_resolve_imported_and_local_export_types() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -91,7 +89,7 @@ fn module_descriptors_resolve_imported_and_local_export_types() -> Result<()> { } #[test] -fn module_descriptors_resolve_imported_and_local_table_and_memory_exports() -> Result<()> { +fn module_descriptors_resolve_imported_and_local_table_and_memory_exports() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module diff --git a/crates/tinywasm/tests/resume_execution.rs b/crates/tinywasm/tests/resume_execution.rs index 060cefb..2798e7b 100644 --- a/crates/tinywasm/tests/resume_execution.rs +++ b/crates/tinywasm/tests/resume_execution.rs @@ -1,6 +1,5 @@ -use eyre::Result; use tinywasm::engine::{Config, FuelPolicy}; -use tinywasm::{ExecProgress, ModuleInstance, types::WasmValue}; +use tinywasm::{ExecProgress, ModuleInstance, Result, types::WasmValue}; #[cfg(feature = "std")] use std::time::Duration; diff --git a/crates/tinywasm/tests/start_function.rs b/crates/tinywasm/tests/start_function.rs index 077c0fc..912b200 100644 --- a/crates/tinywasm/tests/start_function.rs +++ b/crates/tinywasm/tests/start_function.rs @@ -1,8 +1,7 @@ -use eyre::Result; use tinywasm::{ModuleInstance, Store}; #[test] -fn exported_wasi_start_is_not_run_during_instantiation() -> Result<()> { +fn exported_wasi_start_is_not_run_during_instantiation() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module diff --git a/crates/tinywasm/tests/store_ownership.rs b/crates/tinywasm/tests/store_ownership.rs index bcb8e07..a508817 100644 --- a/crates/tinywasm/tests/store_ownership.rs +++ b/crates/tinywasm/tests/store_ownership.rs @@ -1,4 +1,3 @@ -use eyre::Result; use tinywasm::types::{GlobalType, WasmType}; use tinywasm::{Global, Imports, ModuleInstance, Store}; @@ -13,7 +12,7 @@ const MODULE_WAT: &str = r#" "#; #[test] -fn func_handle_rejects_wrong_store() -> Result<()> { +fn func_handle_rejects_wrong_store() -> Result<(), Box> { let wasm = wat::parse_str(MODULE_WAT)?; let module = tinywasm::parse_bytes(&wasm)?; @@ -29,7 +28,7 @@ fn func_handle_rejects_wrong_store() -> Result<()> { } #[test] -fn memory_access_rejects_wrong_store() -> Result<()> { +fn memory_access_rejects_wrong_store() -> Result<(), Box> { let wasm = wat::parse_str(MODULE_WAT)?; let module = tinywasm::parse_bytes(&wasm)?; @@ -45,7 +44,7 @@ fn memory_access_rejects_wrong_store() -> Result<()> { } #[test] -fn global_access_rejects_wrong_store() -> Result<()> { +fn global_access_rejects_wrong_store() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -67,7 +66,7 @@ fn global_access_rejects_wrong_store() -> Result<()> { } #[test] -fn table_grow_rejects_wrong_store_with_invalid_store_error() -> Result<()> { +fn table_grow_rejects_wrong_store_with_invalid_store_error() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -89,7 +88,7 @@ fn table_grow_rejects_wrong_store_with_invalid_store_error() -> Result<()> { } #[test] -fn global_import_rejects_wrong_store() -> Result<()> { +fn global_import_rejects_wrong_store() -> Result<(), Box> { let wasm = wat::parse_str(r#"(module (import "env" "g" (global i32)))"#)?; let module = tinywasm::parse_bytes(&wasm)?; let mut owner_store = Store::default(); diff --git a/crates/tinywasm/tests/test-wasm-1.rs b/crates/tinywasm/tests/test-wasm-1.rs index be235ae..723f007 100644 --- a/crates/tinywasm/tests/test-wasm-1.rs +++ b/crates/tinywasm/tests/test-wasm-1.rs @@ -1,9 +1,7 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; +use tinywasm_cli::testsuite::TestSuite; use wasm_testsuite::data::{SpecVersion, spec}; -fn main() -> Result<()> { +fn main() -> Result<(), Box> { TestSuite::set_log_level(log::LevelFilter::Off); let mut test_suite = TestSuite::new(); diff --git a/crates/tinywasm/tests/test-wasm-2.rs b/crates/tinywasm/tests/test-wasm-2.rs index 0379ca6..c762eec 100644 --- a/crates/tinywasm/tests/test-wasm-2.rs +++ b/crates/tinywasm/tests/test-wasm-2.rs @@ -1,9 +1,7 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; +use tinywasm_cli::testsuite::TestSuite; use wasm_testsuite::data::{SpecVersion, spec}; -fn main() -> Result<()> { +fn main() -> Result<(), Box> { TestSuite::set_log_level(log::LevelFilter::Off); let mut test_suite = TestSuite::new(); diff --git a/crates/tinywasm/tests/test-wasm-3.rs b/crates/tinywasm/tests/test-wasm-3.rs index 11ebbc8..a843ae0 100644 --- a/crates/tinywasm/tests/test-wasm-3.rs +++ b/crates/tinywasm/tests/test-wasm-3.rs @@ -1,9 +1,7 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; +use tinywasm_cli::testsuite::TestSuite; use wasm_testsuite::data::{SpecVersion, spec}; -fn main() -> Result<()> { +fn main() -> Result<(), Box> { TestSuite::set_log_level(log::LevelFilter::Off); let mut test_suite = TestSuite::new(); diff --git a/crates/tinywasm/tests/test-wasm-custom-page-sizes.rs b/crates/tinywasm/tests/test-wasm-custom-page-sizes.rs index e4aacfc..a71266a 100644 --- a/crates/tinywasm/tests/test-wasm-custom-page-sizes.rs +++ b/crates/tinywasm/tests/test-wasm-custom-page-sizes.rs @@ -1,9 +1,7 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; +use tinywasm_cli::testsuite::TestSuite; use wasm_testsuite::data::{Proposal, proposal}; -fn main() -> Result<()> { +fn main() -> Result<(), Box> { TestSuite::set_log_level(log::LevelFilter::Off); let mut test_suite = TestSuite::new(); diff --git a/crates/tinywasm/tests/test-wasm-custom.rs b/crates/tinywasm/tests/test-wasm-custom.rs index ae08142..b516428 100644 --- a/crates/tinywasm/tests/test-wasm-custom.rs +++ b/crates/tinywasm/tests/test-wasm-custom.rs @@ -1,8 +1,6 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; +use tinywasm_cli::testsuite::TestSuite; -fn main() -> Result<()> { +fn main() -> Result<(), Box> { TestSuite::set_log_level(log::LevelFilter::Off); let custom_dir = std::path::Path::new("./tests/wasm-custom"); diff --git a/crates/tinywasm/tests/test-wasm-gc.rs b/crates/tinywasm/tests/test-wasm-gc.rs index a80d347..86496c4 100644 --- a/crates/tinywasm/tests/test-wasm-gc.rs +++ b/crates/tinywasm/tests/test-wasm-gc.rs @@ -1,9 +1,7 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; +use tinywasm_cli::testsuite::TestSuite; use wasm_testsuite::data::{Proposal, proposal}; -fn main() -> Result<()> { +fn main() -> Result<(), Box> { TestSuite::set_log_level(log::LevelFilter::Off); let mut test_suite = TestSuite::new(); diff --git a/crates/tinywasm/tests/test-wasm-latest.rs b/crates/tinywasm/tests/test-wasm-latest.rs index af83c2f..649c44c 100644 --- a/crates/tinywasm/tests/test-wasm-latest.rs +++ b/crates/tinywasm/tests/test-wasm-latest.rs @@ -1,9 +1,7 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; +use tinywasm_cli::testsuite::TestSuite; use wasm_testsuite::data::{SpecVersion, spec}; -fn main() -> Result<()> { +fn main() -> Result<(), Box> { TestSuite::set_log_level(log::LevelFilter::Off); let mut test_suite = TestSuite::new(); diff --git a/crates/tinywasm/tests/test-wasm-memory64.rs b/crates/tinywasm/tests/test-wasm-memory64.rs index 447bbfc..717ae03 100644 --- a/crates/tinywasm/tests/test-wasm-memory64.rs +++ b/crates/tinywasm/tests/test-wasm-memory64.rs @@ -1,9 +1,7 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; +use tinywasm_cli::testsuite::TestSuite; use wasm_testsuite::data::{Proposal, proposal}; -fn main() -> Result<()> { +fn main() -> Result<(), Box> { TestSuite::set_log_level(log::LevelFilter::Off); let mut test_suite = TestSuite::new(); diff --git a/crates/tinywasm/tests/test-wasm-multi-memory.rs b/crates/tinywasm/tests/test-wasm-multi-memory.rs index e4487f1..b0963b2 100644 --- a/crates/tinywasm/tests/test-wasm-multi-memory.rs +++ b/crates/tinywasm/tests/test-wasm-multi-memory.rs @@ -1,9 +1,7 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; +use tinywasm_cli::testsuite::TestSuite; use wasm_testsuite::data::{Proposal, proposal}; -fn main() -> Result<()> { +fn main() -> Result<(), Box> { TestSuite::set_log_level(log::LevelFilter::Off); let mut test_suite = TestSuite::new(); diff --git a/crates/tinywasm/tests/test-wasm-relaxed-simd.rs b/crates/tinywasm/tests/test-wasm-relaxed-simd.rs index 0851d18..92a5991 100644 --- a/crates/tinywasm/tests/test-wasm-relaxed-simd.rs +++ b/crates/tinywasm/tests/test-wasm-relaxed-simd.rs @@ -1,9 +1,7 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; +use tinywasm_cli::testsuite::TestSuite; use wasm_testsuite::data::{Proposal, proposal}; -fn main() -> Result<()> { +fn main() -> Result<(), Box> { TestSuite::set_log_level(log::LevelFilter::Off); let mut test_suite = TestSuite::new(); diff --git a/crates/tinywasm/tests/test-wasm-simd.rs b/crates/tinywasm/tests/test-wasm-simd.rs index d8f15ea..3d1932f 100644 --- a/crates/tinywasm/tests/test-wasm-simd.rs +++ b/crates/tinywasm/tests/test-wasm-simd.rs @@ -1,9 +1,7 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; +use tinywasm_cli::testsuite::TestSuite; use wasm_testsuite::data::{Proposal, proposal}; -fn main() -> Result<()> { +fn main() -> Result<(), Box> { TestSuite::set_log_level(log::LevelFilter::Off); let mut test_suite = TestSuite::new(); diff --git a/crates/tinywasm/tests/test-wasm-threads.rs b/crates/tinywasm/tests/test-wasm-threads.rs index 2fd5a9b..5cff235 100644 --- a/crates/tinywasm/tests/test-wasm-threads.rs +++ b/crates/tinywasm/tests/test-wasm-threads.rs @@ -1,9 +1,7 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; +use tinywasm_cli::testsuite::TestSuite; use wasm_testsuite::data::{Proposal, proposal}; -fn main() -> Result<()> { +fn main() -> Result<(), Box> { TestSuite::set_log_level(log::LevelFilter::Off); let mut test_suite = TestSuite::new(); diff --git a/crates/tinywasm/tests/test-wasm-wide-arithmetic.rs b/crates/tinywasm/tests/test-wasm-wide-arithmetic.rs index 2aa6b43..e4b5647 100644 --- a/crates/tinywasm/tests/test-wasm-wide-arithmetic.rs +++ b/crates/tinywasm/tests/test-wasm-wide-arithmetic.rs @@ -1,9 +1,7 @@ -mod testsuite; -use eyre::Result; -use testsuite::TestSuite; +use tinywasm_cli::testsuite::TestSuite; use wasm_testsuite::data::{Proposal, proposal}; -fn main() -> Result<()> { +fn main() -> Result<(), Box> { TestSuite::set_log_level(log::LevelFilter::Off); let mut test_suite = TestSuite::new(); diff --git a/crates/tinywasm/tests/test-wast.rs b/crates/tinywasm/tests/test-wast.rs index 92fcbd2..004bafa 100644 --- a/crates/tinywasm/tests/test-wast.rs +++ b/crates/tinywasm/tests/test-wast.rs @@ -1,12 +1,9 @@ -use std::path::PathBuf; - -use eyre::{Result, bail}; use tinywasm_cli::wast_runner::WastRunner; -fn main() -> Result<()> { - let args = std::env::args().collect::>(); - if args.len() < 2 { - bail!("usage: cargo test-wast "); +fn main() -> Result<(), Box> { + let Some(input) = std::env::args().nth(1) else { + eprintln!("usage: cargo test-wast "); + std::process::exit(2); }; let mut cwd = std::env::current_dir()?; @@ -15,8 +12,7 @@ fn main() -> Result<()> { cwd.pop(); } - // if its a folder, run all the wast files in the folder - let arg = PathBuf::from(cwd.clone()).join(&args[1]); + let arg = cwd.join(input); println!("running tests in {:?}", arg); let files = if arg.is_dir() { @@ -26,5 +22,6 @@ fn main() -> Result<()> { }; let mut test_suite = WastRunner::new(); - test_suite.run_paths(&files) + test_suite.run_paths(&files)?; + Ok(()) } diff --git a/crates/tinywasm/tests/testsuite/mod.rs b/crates/tinywasm/tests/testsuite/mod.rs deleted file mode 100644 index ea44c29..0000000 --- a/crates/tinywasm/tests/testsuite/mod.rs +++ /dev/null @@ -1,150 +0,0 @@ -#![allow(dead_code)] - -use eyre::{Result, eyre}; -use owo_colors::OwoColorize; -use serde::{Deserialize, Serialize}; -use std::fmt::{Display, Formatter}; -use std::io::{BufRead, BufReader, Seek, SeekFrom}; -use tinywasm_cli::wast_runner::{GroupResult, TestFile as RunnerTestFile, WastRunner}; - -#[derive(Serialize, Deserialize)] -pub struct TestGroupResult { - pub name: String, - pub passed: usize, - pub failed: usize, -} - -pub struct TestSuite { - runner: WastRunner, -} - -impl TestSuite { - pub fn set_log_level(level: log::LevelFilter) { - WastRunner::set_log_level(level); - } - - pub fn new() -> Self { - Self { runner: WastRunner::new() } - } - - pub fn run_paths(&mut self, tests: &[std::path::PathBuf]) -> Result<()> { - let mut files = Vec::new(); - for path in tests { - if path.is_dir() { - for entry in std::fs::read_dir(path)? { - let entry = entry?; - let path = entry.path(); - if path.extension().is_some_and(|ext| ext == "wast") { - files.push(path); - } - } - } else { - files.push(path.clone()); - } - } - files.sort(); - - let runner_files = files - .iter() - .map(|path| { - let contents = std::fs::read_to_string(path)?; - let name = path.to_string_lossy().into_owned(); - Ok((name, contents)) - }) - .collect::>>()?; - - self.runner.run_files(runner_files.iter().map(|(name, contents)| RunnerTestFile { - name: name.clone(), - parent: name.clone(), - contents, - })) - } - - pub fn run_files<'a>(&mut self, tests: impl IntoIterator>) -> Result<()> { - self.runner.run_files(tests.into_iter().map(|file| RunnerTestFile { - name: file.name().to_string(), - parent: file.parent().to_string(), - contents: file.raw(), - })) - } - - pub fn print_errors(&self) { - self.runner.print_errors(); - } - - pub fn report_status(&self) -> Result<()> { - if self.runner.failed() { - println!(); - Err(eyre!(format!("{}:\n{self}", "failed one or more tests".red().bold()))) - } else { - println!("{self}"); - Ok(()) - } - } - - pub fn save_csv(&self, path: &str, version: &str) -> Result<()> { - use std::fs::OpenOptions; - use std::io::Write; - - let mut file = OpenOptions::new().create(true).append(true).read(true).open(path)?; - let last_line = BufReader::new(&file).lines().last().transpose()?; - - if let Some(last) = last_line - && last.starts_with(version) - { - let len_to_truncate = last.len() as i64; - file.set_len(file.metadata()?.len() - len_to_truncate as u64 - 1)?; - } - - file.seek(SeekFrom::End(0))?; - - let mut passed = 0; - let mut failed = 0; - let mut groups = Vec::new(); - - for group in self.runner.group_results() { - passed += group.passed; - failed += group.failed; - groups.push(TestGroupResult { name: group.name, passed: group.passed, failed: group.failed }); - } - - let groups = serde_json::to_string(&groups)?; - let line = format!("{version},{passed},{failed},{groups}\n"); - file.write_all(line.as_bytes())?; - Ok(()) - } - - fn group_results(&self) -> Vec { - self.runner.group_results() - } -} - -impl Default for TestSuite { - fn default() -> Self { - Self::new() - } -} - -impl Display for TestSuite { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - let mut total_passed = 0; - let mut total_failed = 0; - - for group in self.group_results() { - total_passed += group.passed; - total_failed += group.failed; - - writeln!(f, "{}", group.name.bold().underline())?; - writeln!(f, " Tests Passed: {}", group.passed.to_string().green())?; - if group.failed != 0 { - writeln!(f, " Tests Failed: {}", group.failed.to_string().red())?; - } - } - - writeln!(f, "\n{}", "Total Test Summary:".bold().underline())?; - writeln!(f, " Total Tests: {}", total_passed + total_failed)?; - writeln!(f, " Total Passed: {}", total_passed.to_string().green())?; - writeln!(f, " Total Failed: {}", total_failed.to_string().red())?; - Ok(()) - } -} diff --git a/crates/tinywasm/tests/typed_globals.rs b/crates/tinywasm/tests/typed_globals.rs index 9d88ec8..ac79f6a 100644 --- a/crates/tinywasm/tests/typed_globals.rs +++ b/crates/tinywasm/tests/typed_globals.rs @@ -1,9 +1,8 @@ -use eyre::Result; use tinywasm::types::{GlobalType, Instruction, RefValue, WasmType, WasmValue}; use tinywasm::{Global, Imports, ModuleInstance, Store}; #[test] -fn globals_use_typed_instructions_and_roundtrip_values() -> Result<()> { +fn globals_use_typed_instructions_and_roundtrip_values() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -70,7 +69,7 @@ fn globals_use_typed_instructions_and_roundtrip_values() -> Result<()> { } #[test] -fn imported_global_keeps_its_typed_store_address() -> Result<()> { +fn imported_global_keeps_its_typed_store_address() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module diff --git a/crates/tinywasm/tests/typed_lookup.rs b/crates/tinywasm/tests/typed_lookup.rs index 15b31b1..c5e052e 100644 --- a/crates/tinywasm/tests/typed_lookup.rs +++ b/crates/tinywasm/tests/typed_lookup.rs @@ -1,8 +1,7 @@ -use eyre::Result; use tinywasm::ModuleInstance; #[test] -fn func_typed_rejects_wrong_param_or_result_types() -> Result<()> { +fn func_typed_rejects_wrong_param_or_result_types() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module @@ -26,7 +25,7 @@ fn func_typed_rejects_wrong_param_or_result_types() -> Result<()> { } #[test] -fn func_typed_rejects_partial_multi_value_results() -> Result<()> { +fn func_typed_rejects_partial_multi_value_results() -> Result<(), Box> { let wasm = wat::parse_str( r#" (module diff --git a/examples/archive.rs b/examples/archive.rs index 7a2ebab..3f64704 100644 --- a/examples/archive.rs +++ b/examples/archive.rs @@ -1,4 +1,4 @@ -use eyre::Result; +use anyhow::Result; use tinywasm::{Module, ModuleInstance, Store, parser::Parser}; const WASM: &str = r#" diff --git a/examples/doom/Cargo.toml b/examples/doom/Cargo.toml index 38e16c4..abec73d 100644 --- a/examples/doom/Cargo.toml +++ b/examples/doom/Cargo.toml @@ -7,7 +7,7 @@ publish = false [workspace] [dependencies] -eyre = "0.6" +anyhow = "1.0" log = "0.4" pretty_env_logger = "0.5" softbuffer = "0.4" diff --git a/examples/doom/src/main.rs b/examples/doom/src/main.rs index 095183d..c5e49b5 100644 --- a/examples/doom/src/main.rs +++ b/examples/doom/src/main.rs @@ -4,7 +4,7 @@ use std::num::NonZeroU32; use std::path::{Path, PathBuf}; use std::rc::Rc; -use eyre::{ContextCompat, Result, bail, eyre}; +use anyhow::{Context, Result, anyhow, bail}; use runtime::{Runtime, SCREEN_HEIGHT, SCREEN_WIDTH}; use softbuffer::{Context as SoftbufferContext, Surface}; use winit::application::ApplicationHandler; @@ -60,10 +60,10 @@ impl DoomApp { surface .resize(NonZeroU32::new(SCREEN_WIDTH as u32).unwrap(), NonZeroU32::new(SCREEN_HEIGHT as u32).unwrap()) - .map_err(|err| eyre!(err.to_string()))?; - let mut buffer = surface.buffer_mut().map_err(|err| eyre!(err.to_string()))?; + .map_err(|err| anyhow!(err.to_string()))?; + let mut buffer = surface.buffer_mut().map_err(|err| anyhow!(err.to_string()))?; self.runtime.write_framebuffer(&mut buffer)?; - buffer.present().map_err(|err| eyre!(err.to_string()))?; + buffer.present().map_err(|err| anyhow!(err.to_string()))?; Ok(()) } } @@ -129,7 +129,7 @@ impl ApplicationHandler for DoomApp { window.request_redraw(); } - if self.runtime.host_state.borrow().exit_code.is_some() { + if self.runtime.host_state.lock().unwrap().exit_code.is_some() { event_loop.exit(); } } diff --git a/examples/doom/src/runtime.rs b/examples/doom/src/runtime.rs index bee961c..2ad02ae 100644 --- a/examples/doom/src/runtime.rs +++ b/examples/doom/src/runtime.rs @@ -1,12 +1,11 @@ -use std::cell::RefCell; use std::collections::BTreeMap; use std::fs::{File, OpenOptions, create_dir_all}; use std::io::{Read, Seek, SeekFrom, Write}; use std::path::{Path, PathBuf}; -use std::rc::Rc; -use std::time::Instant; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; -use eyre::Result; +use anyhow::Result; use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store}; const IMPORT_MODULE: &str = "env"; @@ -21,15 +20,15 @@ pub struct Runtime { key_up: tinywasm::FunctionTyped, memory: tinywasm::Memory, framebuffer_bytes: Vec, - pub host_state: Rc>, + pub host_state: Arc>, } impl Runtime { pub fn new(wad_path: PathBuf, guest_path: PathBuf) -> Result { let module = tinywasm::parse_file(&guest_path)?; let mut store = Store::default(); - let host_state = Rc::new(RefCell::new(HostState::new(wad_path))); - let imports = build_imports(&mut store, host_state.clone()); + let host_state = Arc::new(Mutex::new(HostState::new(wad_path))); + let imports = build_imports(host_state.clone()); let instance = ModuleInstance::instantiate(&mut store, &module, Some(&imports))?; let wad_path_buf = instance.func::<(), i32>(&store, "tinywasm_doom_wad_path_buf")?; @@ -41,7 +40,7 @@ impl Runtime { let memory = instance.memory("memory")?; let buf_ptr = wad_path_buf.call(&mut store, ())? as usize; - let wad_path_string = host_state.borrow().wad_path.to_string_lossy().into_owned(); + let wad_path_string = host_state.lock().unwrap().wad_path.to_string_lossy().into_owned(); memory.write_cstring_bytes(&mut store, buf_ptr, &wad_path_string)?; init.call(&mut store, ())?; @@ -161,7 +160,7 @@ impl HostState { } } -fn build_imports(store: &mut Store, state: Rc>) -> Imports { +fn build_imports(state: Arc>) -> Imports { let mut imports = Imports::new(); { @@ -175,7 +174,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { let mode = memory.read_cstring_until_null(ctx.store(), mode_ptr as usize, 16)?; let filename = filename.to_string_lossy(); let mode = mode.to_string_lossy(); - let mut state = state.borrow_mut(); + let mut state = state.lock().unwrap(); let path = if filename == state.wad_path.to_string_lossy() || state.should_redirect_to_wad(&filename) { state.wad_path.clone() } else { @@ -209,7 +208,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { IMPORT_MODULE, "host_close", HostFunction::from(move |_ctx: FuncContext<'_>, handle: i32| { - state.borrow_mut().files.remove(&handle); + state.lock().unwrap().files.remove(&handle); Ok(()) }), ); @@ -221,7 +220,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { IMPORT_MODULE, "host_read", HostFunction::from(move |mut ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { - let mut state = state.borrow_mut(); + let mut state = state.lock().unwrap(); let Some(file) = state.files.get_mut(&handle) else { return Ok(0); }; @@ -240,7 +239,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { "host_write", HostFunction::from(move |ctx: FuncContext<'_>, (handle, buf_ptr, count): (i32, i32, i32)| { let data = ctx.memory("memory")?.read_vec(ctx.store(), buf_ptr as usize, count.max(0) as usize)?; - let mut state = state.borrow_mut(); + let mut state = state.lock().unwrap(); let Some(file) = state.files.get_mut(&handle) else { return Ok(-1); }; @@ -262,7 +261,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { 2 => SeekFrom::End(offset as i64), _ => return Err(tinywasm::Error::Other(format!("invalid seek origin: {origin}"))), }; - let mut state = state.borrow_mut(); + let mut state = state.lock().unwrap(); let Some(file) = state.files.get_mut(&handle) else { return Ok(-1); }; @@ -278,7 +277,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { IMPORT_MODULE, "host_tell", HostFunction::from(move |_ctx: FuncContext<'_>, handle: i32| { - let mut state = state.borrow_mut(); + let mut state = state.lock().unwrap(); let Some(file) = state.files.get_mut(&handle) else { return Ok(-1); }; @@ -294,7 +293,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { IMPORT_MODULE, "host_eof", HostFunction::from(move |_ctx: FuncContext<'_>, handle: i32| { - let mut state = state.borrow_mut(); + let mut state = state.lock().unwrap(); let Some(file) = state.files.get_mut(&handle) else { return Ok(1); }; @@ -311,7 +310,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { IMPORT_MODULE, "host_gettime", HostFunction::from(move |mut ctx: FuncContext<'_>, (sec_ptr, usec_ptr): (i32, i32)| { - let elapsed = state.borrow().start.elapsed(); + let elapsed = state.lock().unwrap().start.elapsed() + Duration::from_secs(1); let sec = elapsed.as_secs().min(i32::MAX as u64) as i32; let usec = elapsed.subsec_micros() as i32; let memory = ctx.memory("memory")?; @@ -328,7 +327,7 @@ fn build_imports(store: &mut Store, state: Rc>) -> Imports { IMPORT_MODULE, "host_exit", HostFunction::from(move |_ctx: FuncContext<'_>, code: i32| { - state.borrow_mut().exit_code = Some(code); + state.lock().unwrap().exit_code = Some(code); Ok(()) }), ); diff --git a/examples/funcref_callbacks.rs b/examples/funcref_callbacks.rs index 5e21a6b..959d798 100644 --- a/examples/funcref_callbacks.rs +++ b/examples/funcref_callbacks.rs @@ -1,4 +1,4 @@ -use eyre::Result; +use anyhow::Result; use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store, types::FuncRef}; const LHS: i32 = 5; diff --git a/examples/linking.rs b/examples/linking.rs index 02cb88d..2df7133 100644 --- a/examples/linking.rs +++ b/examples/linking.rs @@ -1,4 +1,4 @@ -use eyre::Result; +use anyhow::Result; use tinywasm::{ModuleInstance, Store}; // WebAssembly module defining and exporting an `add` function. diff --git a/examples/reentrance.rs b/examples/reentrance.rs index 8a1988e..0084a61 100644 --- a/examples/reentrance.rs +++ b/examples/reentrance.rs @@ -1,4 +1,4 @@ -use eyre::Result; +use anyhow::Result; use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store}; const WASM: &str = r#" diff --git a/examples/resumable.rs b/examples/resumable.rs index 0163414..26b5f47 100644 --- a/examples/resumable.rs +++ b/examples/resumable.rs @@ -1,4 +1,4 @@ -use eyre::Result; +use anyhow::Result; use tinywasm::{ExecProgress, ModuleInstance, Store}; const WASM: &str = r#" diff --git a/examples/simple.rs b/examples/simple.rs index a902b4c..0d57265 100644 --- a/examples/simple.rs +++ b/examples/simple.rs @@ -1,4 +1,4 @@ -use eyre::Result; +use anyhow::Result; use tinywasm::{ModuleInstance, Store}; const WASM: &str = r#" diff --git a/examples/simple2.rs b/examples/simple2.rs index da7def7..f673dfe 100644 --- a/examples/simple2.rs +++ b/examples/simple2.rs @@ -1,4 +1,4 @@ -use eyre::Result; +use anyhow::Result; use tinywasm::{ModuleInstance, Store}; const WASM: &str = r#" diff --git a/examples/wasm-rust.rs b/examples/wasm-rust.rs index e4af3cd..672b290 100644 --- a/examples/wasm-rust.rs +++ b/examples/wasm-rust.rs @@ -1,6 +1,6 @@ use std::hint::black_box; -use eyre::{Result, eyre}; +use anyhow::{Result, anyhow}; use tinywasm::{FuncContext, HostFunction, Imports, ModuleInstance, Store}; /// Examples of using WebAssembly compiled from Rust with tinywasm. @@ -23,7 +23,7 @@ fn main() -> Result<()> { pretty_env_logger::init(); if !std::path::Path::new("./examples/rust/out/").exists() { - return Err(eyre!("No WebAssembly files found. See examples/wasm-rust.rs for instructions.")); + return Err(anyhow!("No WebAssembly files found. See examples/wasm-rust.rs for instructions.")); } let args = std::env::args().collect::>(); -- cgit v1.3.1 From 741955aed21c814a0805386a4f9be997c2eb1199 Mon Sep 17 00:00:00 2001 From: Henry Date: Mon, 14 Sep 2026 12:05:52 +0200 Subject: feat: add custom store state Signed-off-by: Henry --- CHANGELOG.md | 1 + README.md | 1 + crates/tinywasm/Cargo.toml | 7 +- crates/tinywasm/src/store/mod.rs | 63 ++++++++ crates/tinywasm/tests/store_state.rs | 36 +++++ examples/doom/Cargo.toml | 1 + examples/doom/src/main.rs | 2 +- examples/doom/src/runtime.rs | 305 ++++++++++++++++------------------- examples/rust.rs | 2 +- examples/rust/build.sh | 4 +- examples/state.rs | 51 ++++++ 11 files changed, 302 insertions(+), 171 deletions(-) create mode 100644 crates/tinywasm/tests/store_state.rs create mode 100644 examples/state.rs (limited to 'examples/doom/src/runtime.rs') diff --git a/CHANGELOG.md b/CHANGELOG.md index a37655e..dc59e5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,7 @@ This release adds garbage collection and typed function reference support, singl ### Added +- Optional store-owned host state through `Store::with_state`, `Store::state`, and `Store::state_mut`. - Support for the typed function references, garbage collection, exception handling, and compact import section proposals. - `ResourceLimiter` callbacks for memory and table allocation or growth. - A default-enabled `validate` Cargo feature and a parser option to skip WebAssembly validation. diff --git a/README.md b/README.md index 383b007..eca0d97 100644 --- a/README.md +++ b/README.md @@ -56,6 +56,7 @@ See the [examples](./examples) directory and [documentation](https://docs.rs/tin - **`archive`:** Enables serialization and deserialization of the internal `twasm` format. Enabled by default. - **`log`:** Enables integration with the `log` crate. Enabled by default. - **`send`:** Makes stores and store-local handles movable across threads. +- **`state`:** Adds store-owned host state for access from host callbacks. - **`portable-atomic`:** Supports targets without native atomic compare-and-swap. - **`canonicalize-nans`:** Uses a [canonical NaN](https://en.wikipedia.org/wiki/NaN#Canonical_NaN) for normalized NaN results. Enabled by default. - **`debug`:** Derives `Debug` for runtime types. Enabled by default. diff --git a/crates/tinywasm/Cargo.toml b/crates/tinywasm/Cargo.toml index d59d3dd..15b151c 100644 --- a/crates/tinywasm/Cargo.toml +++ b/crates/tinywasm/Cargo.toml @@ -11,7 +11,7 @@ keywords.workspace = true categories.workspace = true [package.metadata.docs.rs] -features = ["std", "validate", "parser", "archive", "log", "canonicalize-nans", "debug", "guest-debug"] +features = ["std", "validate", "parser", "archive", "log", "canonicalize-nans", "state", "debug", "guest-debug"] rustdoc-args = ["--cfg", "docsrs"] [lib] @@ -90,7 +90,7 @@ wat.workspace = true [features] default = ["full", "std"] -full = ["archive", "debug", "parallel-parser", "parser", "validate"] +full = ["archive", "debug", "parallel-parser", "parser", "state", "validate"] log = ["dep:log", "tinywasm-parser?/log"] std = ["tinywasm-parser?/std", "tinywasm-types/std"] @@ -98,6 +98,9 @@ std = ["tinywasm-parser?/std", "tinywasm-types/std"] # make stores, instances, references, and host callbacks movable across threads send = [] +# store host state for access from host callbacks +state = [] + # support for parsing WebAssembly parser = ["dep:tinywasm-parser"] diff --git a/crates/tinywasm/src/store/mod.rs b/crates/tinywasm/src/store/mod.rs index e157240..ed9b4f0 100644 --- a/crates/tinywasm/src/store/mod.rs +++ b/crates/tinywasm/src/store/mod.rs @@ -1,4 +1,8 @@ +#[cfg(feature = "state")] +use alloc::collections::BTreeMap; use alloc::{boxed::Box, format, vec::Vec}; +#[cfg(feature = "state")] +use core::any::{Any, TypeId}; use core::hint::cold_path; use tinywasm_types::*; @@ -110,6 +114,25 @@ pub trait ResourceLimiter: Send + Sync { } } +/// A value stored as host state. +#[doc(hidden)] +#[cfg(all(feature = "state", not(feature = "send")))] +pub trait StoreState: Any {} +#[cfg(all(feature = "state", not(feature = "send")))] +impl StoreState for T {} + +/// A value stored as host state. +#[doc(hidden)] +#[cfg(all(feature = "state", feature = "send"))] +pub trait StoreState: Any + Send {} +#[cfg(all(feature = "state", feature = "send"))] +impl StoreState for T {} + +#[cfg(all(feature = "state", not(feature = "send")))] +type StoredState = dyn Any; +#[cfg(all(feature = "state", feature = "send"))] +type StoredState = dyn Any + Send; + /// Runtime state used by WebAssembly instances and host functions. /// /// ## Example @@ -133,6 +156,8 @@ pub struct Store { pub(crate) call_stack: CallStack, pub(crate) value_stack: ValueStack, value_scratch: ValueScratch, + #[cfg(feature = "state")] + host_state: BTreeMap>, } #[derive(Default)] @@ -238,9 +263,47 @@ impl Store { engine, execution_fuel: 0, execution_active: false, + #[cfg(feature = "state")] + host_state: BTreeMap::new(), } } + /// Adds host state to this store. + /// + /// Host callbacks can access the value through [`Store::state`] and + /// [`Store::state_mut`]. If state of the same type already exists, this + /// method replaces it. + /// + /// # Example + /// + /// ```rust + /// use tinywasm::Store; + /// + /// struct AppState { + /// requests: usize, + /// } + /// + /// let store = Store::default().with_state(AppState { requests: 0 }); + /// assert_eq!(store.state::().unwrap().requests, 0); + /// ``` + #[cfg(feature = "state")] + pub fn with_state(mut self, state: T) -> Self { + self.host_state.insert(TypeId::of::(), Box::new(state)); + self + } + + /// Get host state. + #[cfg(feature = "state")] + pub fn state(&self) -> Option<&T> { + self.host_state.get(&TypeId::of::()).and_then(|state| state.downcast_ref()) + } + + /// Get mutable access to host state. + #[cfg(feature = "state")] + pub fn state_mut(&mut self) -> Option<&mut T> { + self.host_state.get_mut(&TypeId::of::()).and_then(|state| state.downcast_mut()) + } + pub(crate) const fn id(&self) -> StoreId { self.id } diff --git a/crates/tinywasm/tests/store_state.rs b/crates/tinywasm/tests/store_state.rs new file mode 100644 index 0000000..573c250 --- /dev/null +++ b/crates/tinywasm/tests/store_state.rs @@ -0,0 +1,36 @@ +#![cfg(feature = "state")] + +use tinywasm::types::WasmValue; +use tinywasm::{HostFunction, Store}; + +struct Counter(i32); +struct Label(&'static str); + +#[test] +fn stores_state_by_type() { + let mut store = Store::default().with_state(Counter(1)).with_state(Label("first")).with_state(Counter(2)); + + assert_eq!(store.state::().unwrap().0, 2); + assert_eq!(store.state::