summaryrefslogtreecommitdiff
path: root/crates/cli
diff options
context:
space:
mode:
authorMica White <botahamec@outlook.com>2026-10-31 11:10:49 -0400
committerMica White <botahamec@outlook.com>2026-10-31 11:10:49 -0400
commit264ea48cc8c6dd9c3c9e0fe1a559252863fc9962 (patch)
tree84a4a58de14442f4fcfa06bd0d82480508f82759 /crates/cli
parent7877eca4e8be283e7c51168ee3a3b05d9000f39c (diff)
parentb45a98a85c776d956a797773acd2f198c06b40ed (diff)
Merge branch 'main' into bota-tortuise
Diffstat (limited to 'crates/cli')
-rw-r--r--crates/cli/Cargo.toml18
-rw-r--r--crates/cli/src/bin.rs2
-rw-r--r--crates/cli/src/cmd/compile.rs2
-rw-r--r--crates/cli/src/cmd/completion.rs2
-rw-r--r--crates/cli/src/cmd/dump.rs2
-rw-r--r--crates/cli/src/cmd/inspect.rs2
-rw-r--r--crates/cli/src/cmd/run.rs13
-rw-r--r--crates/cli/src/cmd/wast.rs2
-rw-r--r--crates/cli/src/engine_flags.rs36
-rw-r--r--crates/cli/src/lib.rs4
-rw-r--r--crates/cli/src/load.rs2
-rw-r--r--crates/cli/src/output.rs4
-rw-r--r--crates/cli/src/testsuite.rs167
-rw-r--r--crates/cli/src/value_parse.rs6
-rw-r--r--crates/cli/src/wast_runner.rs517
15 files changed, 505 insertions, 274 deletions
diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml
index 7dbd4d2..73b537f 100644
--- a/crates/cli/Cargo.toml
+++ b/crates/cli/Cargo.toml
@@ -4,8 +4,7 @@ version.workspace = true
edition.workspace = true
rust-version.workspace = true
description = "Minimal command-line interface for TinyWasm"
-documentation = "https://docs.rs/tinywasm-cli"
-readme = "README.md"
+homepage.workspace = true
repository.workspace = true
license.workspace = true
keywords = ["cli", "runtime", "tinywasm", "wasm", "webassembly"]
@@ -23,21 +22,24 @@ 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",
"debug",
+ "full",
+ "guest-debug",
"log",
- "parallel-parser",
- "parser",
"std",
] }
+tinywasm-wasi.workspace = true
+wasm-testsuite = { workspace = true, optional = true }
wast = { workspace = true, optional = true }
wat = { workspace = true, optional = true }
@@ -48,5 +50,9 @@ tempfile = "3.27"
[features]
default = ["wast", "wat"]
+tests = ["dep:serde", "dep:serde_json", "dep:wasm-testsuite", "wast"]
wast = ["dep:wast"]
wat = ["dep:wat"]
+
+[lints]
+workspace = true
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..52cd273 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,10 +26,11 @@ 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, &params)?;
+ let mut results = vec![tinywasm::WasmValue::I32(0); func.ty(&store)?.results().len()];
+ func.call(&mut store, &params, &mut results)?;
print_results(&results);
Ok(())
}
@@ -40,11 +41,11 @@ 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 <export> {module_path}`"
)
})?;
- start.call(&mut store, &[])?;
+ start.call(&mut store, &[], &mut [])?;
Ok(())
}
}
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..edc56aa 100644
--- a/crates/cli/src/engine_flags.rs
+++ b/crates/cli/src/engine_flags.rs
@@ -1,5 +1,5 @@
+use anyhow::Result;
use clap::{Args, ValueEnum};
-use eyre::{Result, bail};
use tinywasm::{Engine, StackConfig, engine::FuelPolicy};
#[derive(Args, Clone, Default)]
@@ -8,18 +8,6 @@ pub struct EngineFlags {
#[arg(long, value_enum)]
pub fuel_policy: Option<FuelPolicyArg>,
- /// Trap immediately on memory or stack allocation failure
- #[arg(long)]
- pub trap_on_oom: bool,
-
- /// Memory backend to use for instantiated memories
- #[arg(long, value_enum)]
- pub memory_backend: Option<MemoryBackendArg>,
-
- /// Chunk size in bytes for the paged memory backend
- #[arg(long, default_value_t = 64 * 1024)]
- pub memory_page_chunk_size: usize,
-
/// Fixed value stack size for all value lanes
#[arg(long, conflicts_with = "value_stack_dynamic")]
pub value_stack_size: Option<usize>,
@@ -43,12 +31,6 @@ pub enum FuelPolicyArg {
Weighted,
}
-#[derive(Clone, Copy, ValueEnum)]
-pub enum MemoryBackendArg {
- Vec,
- Paged,
-}
-
#[derive(Clone)]
pub struct StackSpec {
initial: usize,
@@ -86,18 +68,6 @@ impl EngineFlags {
});
}
- if let Some(memory_backend) = self.memory_backend {
- config = config.with_memory_backend(match memory_backend {
- MemoryBackendArg::Vec => tinywasm::MemoryBackend::vec(),
- MemoryBackendArg::Paged => {
- if self.memory_page_chunk_size == 0 {
- bail!("--memory-page-chunk-size must be greater than zero");
- }
- tinywasm::MemoryBackend::paged(self.memory_page_chunk_size)
- }
- });
- }
-
if let Some(value_stack_size) = self.value_stack_size {
config = config.with_value_stack(StackConfig::fixed(value_stack_size));
}
@@ -114,10 +84,6 @@ impl EngineFlags {
config = config.with_call_stack(call_stack_dynamic.into_stack_config());
}
- if self.trap_on_oom {
- config = config.with_trap_on_oom(true);
- }
-
Ok(Engine::new(config))
}
}
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/output.rs b/crates/cli/src/output.rs
index 40a271e..75be9f8 100644
--- a/crates/cli/src/output.rs
+++ b/crates/cli/src/output.rs
@@ -48,7 +48,7 @@ pub fn format_memory_type(ty: &MemoryType) -> String {
MemoryArch::I32 => "i32",
MemoryArch::I64 => "i64",
};
- let max = if ty.page_count_max() == ty.page_count_initial() && ty.max_size() == ty.initial_size() {
+ let max = if ty.page_count_max() == ty.page_count_initial() {
ty.page_count_initial().to_string()
} else {
ty.page_count_max().to_string()
@@ -77,6 +77,7 @@ pub fn format_export_type(ty: ExportType<'_>) -> String {
ExportType::Memory(ty) => format_memory_type(ty),
ExportType::Table(ty) => format_table_type(ty),
ExportType::Global(ty) => format_global_type(ty),
+ ExportType::Tag(ty) => format!("tag {}", format_func_type(ty)),
}
}
@@ -86,5 +87,6 @@ pub fn format_import_type(ty: ImportType<'_>) -> String {
ImportType::Memory(ty) => format_memory_type(ty),
ImportType::Table(ty) => format_table_type(ty),
ImportType::Global(ty) => format_global_type(ty),
+ ImportType::Tag(ty) => format!("tag {}", format_func_type(ty)),
}
}
diff --git a/crates/cli/src/testsuite.rs b/crates/cli/src/testsuite.rs
new file mode 100644
index 0000000..b23b2c8
--- /dev/null
+++ b/crates/cli/src/testsuite.rs
@@ -0,0 +1,167 @@
+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<T> = core::result::Result<T, Box<dyn core::error::Error>>;
+
+struct TestFailure(String);
+
+impl core::fmt::Debug for TestFailure {
+ fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
+ Display::fmt(self, f)
+ }
+}
+
+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::<TestResult<Vec<_>>>()?;
+
+ 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<Item = wasm_testsuite::data::TestFile<'a>>,
+ ) -> 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<()> {
+ self.print_errors();
+ println!("{self}");
+ if self.runner.failed() { Err(TestFailure("failed one or more tests".into()).into()) } else { 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<GroupResult> {
+ 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<WasmValue> {
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 c773663..4ebdc6c 100644
--- a/crates/cli/src/wast_runner.rs
+++ b/crates/cli/src/wast_runner.rs
@@ -5,63 +5,77 @@ 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::{ExternRef, FuncRef, MemoryType, RefType, RefValue, TableType, WasmType, WasmValue};
+use tinywasm::types::{MemoryType, RefType, RefValue, TableType, WasmType, WasmValue};
use tinywasm::{ExecProgress, Global, HostFunction, Imports, Memory, Module, ModuleInstance, Store, Table};
-use wast::{QuoteWat, core::AbstractHeapType};
+use wast::QuoteWat;
+use wast::core::{AbstractHeapType, NanPattern};
const TEST_TIME_SLICE: Duration = Duration::from_millis(20);
const TEST_MAX_SUSPENSIONS: u32 = 1000;
+// Older suites classify encodings that wasmparser accepts with the latest feature set as malformed.
+const ACCEPTED_MALFORMED_MESSAGES: &[&str] =
+ &["integer representation too long", "zero byte expected", "zero flag expected"];
+const ACCEPTED_INVALID_MESSAGES: &[&str] = &["multiple memories"];
+
+macro_rules! float_value {
+ ($pattern:expr, $float:ty, $variant:ident) => {
+ match $pattern {
+ NanPattern::CanonicalNan | NanPattern::ArithmeticNan => WasmValue::$variant(<$float>::NAN),
+ NanPattern::Value(value) => WasmValue::$variant(<$float>::from_bits(value.bits)),
+ }
+ };
+}
#[derive(Default)]
struct ModuleRegistry {
- modules: HashMap<String, ModuleInstance>,
- named_modules: HashMap<String, ModuleInstance>,
- last_module: Option<ModuleInstance>,
+ definitions: HashMap<String, Module>,
+ instances: HashMap<String, ModuleInstance>,
+ registered: HashMap<String, ModuleInstance>,
+ last_definition: Option<Module>,
+ last_instance: Option<ModuleInstance>,
}
impl ModuleRegistry {
- fn modules(&self) -> &HashMap<String, ModuleInstance> {
- &self.modules
+ fn registered(&self) -> &HashMap<String, ModuleInstance> {
+ &self.registered
}
- fn update_last_module(&mut self, module: ModuleInstance, name: Option<String>) {
- self.last_module = Some(module.clone());
+ fn define(&mut self, module: Module, name: Option<String>) {
+ self.last_definition = Some(module.clone());
if let Some(name) = name {
- self.named_modules.insert(name, module);
+ self.definitions.insert(name, module);
}
}
- fn register(&mut self, name: String, module: ModuleInstance) {
- debug!("registering module: {name}");
- self.modules.insert(name.clone(), module.clone());
- self.last_module = Some(module.clone());
- self.named_modules.insert(name, module);
+ fn definition(&self, id: Option<wast::token::Id<'_>>) -> Option<Module> {
+ let Some(id) = id else { return self.last_definition.clone() };
+ self.definitions.get(id.name()).cloned()
}
- fn get_idx(&self, module_id: Option<wast::token::Id<'_>>) -> Option<u32> {
- match module_id {
- Some(module) => self
- .modules
- .get(module.name())
- .or_else(|| self.named_modules.get(module.name()))
- .map(ModuleInstance::id),
- None => self.last_module.as_ref().map(ModuleInstance::id),
+ fn update_last_instance(&mut self, instance: ModuleInstance, name: Option<String>) {
+ self.last_instance = Some(instance.clone());
+ if let Some(name) = name {
+ self.instances.insert(name, instance);
}
}
- fn get(&self, module_id: Option<wast::token::Id<'_>>) -> Option<ModuleInstance> {
- match module_id {
- Some(module_id) => {
- self.modules.get(module_id.name()).or_else(|| self.named_modules.get(module_id.name())).cloned()
- }
- None => self.last_module.clone(),
- }
+ fn register(&mut self, name: String, id: Option<wast::token::Id<'_>>) -> bool {
+ let Some(instance) = self.get(id) else { return false };
+ debug!("registering module: {name}");
+ self.registered.insert(name, instance);
+ true
+ }
+
+ fn get_idx(&self, module_id: Option<wast::token::Id<'_>>) -> Option<u32> {
+ let Some(module_id) = module_id else { return self.last_instance.as_ref().map(ModuleInstance::id) };
+ self.registered.get(module_id.name()).or_else(|| self.instances.get(module_id.name())).map(ModuleInstance::id)
}
- fn last(&self) -> Option<ModuleInstance> {
- self.last_module.clone()
+ fn get(&self, module_id: Option<wast::token::Id<'_>>) -> Option<ModuleInstance> {
+ let Some(module_id) = module_id else { return self.last_instance.clone() };
+ self.registered.get(module_id.name()).or_else(|| self.instances.get(module_id.name())).cloned()
}
}
@@ -98,7 +112,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(())
@@ -154,17 +168,18 @@ impl WastRunner {
fn imports(store: &mut Store, modules: &HashMap<String, ModuleInstance>) -> Result<Imports> {
let mut imports = Imports::new();
- let table = Table::new(store, TableType::new(RefType::FUNCREF, 10, Some(20)), RefValue::Null.into())?;
- let table64 = Table::new(store, TableType::new64(RefType::FUNCREF, 10, Some(20)), RefValue::Null.into())?;
- let memory = Memory::new(store, MemoryType::default().with_page_count_initial(1).with_page_count_max(Some(2)))?;
+ let table = Table::try_new(store, TableType::new(RefType::FUNCREF, 10, Some(20)), RefValue::Null.into())?;
+ let table64 = Table::try_new(store, TableType::new64(RefType::FUNCREF, 10, Some(20)), RefValue::Null.into())?;
+ let memory =
+ Memory::try_new(store, MemoryType::default().with_page_count_initial(1).with_page_count_max(Some(2)))?;
let global_i32 =
- Global::new(store, tinywasm::types::GlobalType::new(WasmType::I32, false), WasmValue::I32(666))?;
+ Global::try_new(store, tinywasm::types::GlobalType::new(WasmType::I32, false), WasmValue::I32(666))?;
let global_i64 =
- Global::new(store, tinywasm::types::GlobalType::new(WasmType::I64, false), WasmValue::I64(666))?;
+ Global::try_new(store, tinywasm::types::GlobalType::new(WasmType::I64, false), WasmValue::I64(666))?;
let global_f32 =
- Global::new(store, tinywasm::types::GlobalType::new(WasmType::F32, false), WasmValue::F32(666.6))?;
+ Global::try_new(store, tinywasm::types::GlobalType::new(WasmType::F32, false), WasmValue::F32(666.6))?;
let global_f64 =
- Global::new(store, tinywasm::types::GlobalType::new(WasmType::F64, false), WasmValue::F64(666.6))?;
+ Global::try_new(store, tinywasm::types::GlobalType::new(WasmType::F64, false), WasmValue::F64(666.6))?;
imports
.define("spectest", "memory", memory)
@@ -174,20 +189,20 @@ impl WastRunner {
.define("spectest", "global_i64", global_i64)
.define("spectest", "global_f32", global_f32)
.define("spectest", "global_f64", global_f64)
- .define("spectest", "print", HostFunction::from(store, |_ctx: tinywasm::FuncContext, (): ()| Ok(())))
- .define("spectest", "print_i32", HostFunction::from(store, |_ctx: tinywasm::FuncContext, _arg: i32| Ok(())))
- .define("spectest", "print_i64", HostFunction::from(store, |_ctx: tinywasm::FuncContext, _arg: i64| Ok(())))
- .define("spectest", "print_f32", HostFunction::from(store, |_ctx: tinywasm::FuncContext, _arg: f32| Ok(())))
- .define("spectest", "print_f64", HostFunction::from(store, |_ctx: tinywasm::FuncContext, _arg: f64| Ok(())))
+ .define("spectest", "print", HostFunction::from(|_ctx: tinywasm::FuncContext, (): ()| Ok(())))
+ .define("spectest", "print_i32", HostFunction::from(|_ctx: tinywasm::FuncContext, _arg: i32| Ok(())))
+ .define("spectest", "print_i64", HostFunction::from(|_ctx: tinywasm::FuncContext, _arg: i64| Ok(())))
+ .define("spectest", "print_f32", HostFunction::from(|_ctx: tinywasm::FuncContext, _arg: f32| Ok(())))
+ .define("spectest", "print_f64", HostFunction::from(|_ctx: tinywasm::FuncContext, _arg: f64| Ok(())))
.define(
"spectest",
"print_i32_f32",
- HostFunction::from(store, |_ctx: tinywasm::FuncContext, _args: (i32, f32)| Ok(())),
+ HostFunction::from(|_ctx: tinywasm::FuncContext, _args: (i32, f32)| Ok(())),
)
.define(
"spectest",
"print_f64_f64",
- HostFunction::from(store, |_ctx: tinywasm::FuncContext, _args: (f64, f64)| Ok(())),
+ HostFunction::from(|_ctx: tinywasm::FuncContext, _args: (f64, f64)| Ok(())),
);
for (name, module) in modules {
@@ -197,6 +212,11 @@ impl WastRunner {
Ok(imports)
}
+ fn instantiate_module(store: &mut Store, registry: &ModuleRegistry, module: &Module) -> Result<ModuleInstance> {
+ let imports = Self::imports(store, registry.registered())?;
+ Ok(ModuleInstance::instantiate(store, module, Some(&imports))?)
+ }
+
pub fn run_file(&mut self, file: TestFile<'_>) -> Result<()> {
let test_group = self.test_group(file.name(), file.parent());
let wast_raw = file.raw();
@@ -205,56 +225,78 @@ impl WastRunner {
let mut store = Store::default();
let mut module_registry = ModuleRegistry::default();
+ let mut call_results = Vec::new();
println!("running {} tests for group: {}", directives.len(), file.name());
for (i, directive) in directives.into_iter().enumerate() {
let span = directive.span();
use wast::WastDirective::{
- AssertExhaustion, AssertInvalid, AssertMalformed, AssertReturn, AssertTrap, AssertUnlinkable, Invoke,
- Module as Wat, ModuleDefinition, Register,
+ AssertException, AssertExhaustion, AssertInvalid, AssertMalformed, AssertReturn, AssertTrap,
+ AssertUnlinkable, Invoke, Module as Wat, ModuleDefinition, ModuleInstance as Instance, Register,
};
match directive {
- Register { span, name, .. } => {
- let Some(last) = module_registry.last() else {
+ Register { span, name, module } => {
+ if !module_registry.register(name.to_string(), module) {
test_group.add_result(
&format!("Register({i})"),
span.linecol_in(wast_raw),
- Err(eyre!("no module to register")),
+ Err(anyhow!("module instance to register was not found")),
);
continue;
- };
- module_registry.register(name.to_string(), last);
+ }
test_group.add_result(&format!("Register({i})"), span.linecol_in(wast_raw), Ok(()));
}
Wat(module) => {
let result = catch_unwind_silent(|| {
- let (name, bytes) = encode_quote_wat(module);
- let module = parse_module_bytes(&bytes).expect("failed to parse module bytes");
- let imports = Self::imports(&mut store, module_registry.modules()).unwrap();
- let module_instance = ModuleInstance::instantiate(&mut store, &module, Some(imports))
+ let (name, module) = parse_quote_module(module).expect("failed to parse module bytes");
+ let instance = Self::instantiate_module(&mut store, &module_registry, &module)
.expect("failed to instantiate module");
- (name, module_instance)
+ (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:?}"),
- Ok((name, module)) => module_registry.update_last_module(module.clone(), name.clone()),
+ Ok((name, instance)) => module_registry.update_last_instance(instance.clone(), name.clone()),
};
test_group.add_result(&format!("Wat({i})"), span.linecol_in(wast_raw), result.map(|_| ()));
}
ModuleDefinition(module) => {
+ let result =
+ catch_unwind_silent(|| parse_quote_module(module).expect("failed to parse module definition"))
+ .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());
+ }
+
+ test_group.add_result(
+ &format!("ModuleDefinition({i})"),
+ span.linecol_in(wast_raw),
+ result.map(|_| ()),
+ );
+ }
+ Instance { span, instance, module } => {
+ let name = instance.map(|id| id.name().to_string());
let result = catch_unwind_silent(|| {
- let (_, bytes) = encode_quote_wat(module);
- parse_module_bytes(&bytes)
+ let module = module_registry
+ .definition(module)
+ .ok_or_else(|| anyhow!("module definition was not found"))?;
+ Self::instantiate_module(&mut store, &module_registry, &module)
})
- .map_err(|err| eyre!("failed to parse module definition: {}", try_downcast_panic(err)))
- .and_then(|result| result)
- .map(|_| ());
+ .map_err(|err| anyhow!("failed to instantiate module definition: {}", try_downcast_panic(err)))
+ .and_then(|result| result);
- test_group.add_result(&format!("ModuleDefinition({i})"), span.linecol_in(wast_raw), result);
+ if let Ok(instance) = &result {
+ module_registry.update_last_instance(instance.clone(), name);
+ }
+ test_group.add_result(
+ &format!("ModuleInstance({i})"),
+ span.linecol_in(wast_raw),
+ result.map(|_| ()),
+ );
}
AssertMalformed { span, mut module, message } => {
let Ok(encoded) = module.encode() else {
@@ -262,52 +304,43 @@ 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})"),
span.linecol_in(wast_raw),
match res {
- Ok(_) => {
- if message == "zero byte expected"
- || message == "integer representation too long"
- || message == "zero flag expected"
- {
- continue;
- }
- Err(eyre!("expected module to be malformed: {message}"))
- }
+ Ok(_) if ACCEPTED_MALFORMED_MESSAGES.contains(&message) => Ok(()),
+ Ok(_) => Err(anyhow!("expected module to be malformed: {message}")),
Err(_) => Ok(()),
},
);
}
AssertInvalid { span, mut module, message } => {
- if ["multiple memories", "type mismatch"].contains(&message) {
- test_group.add_result(&format!("AssertInvalid({i})"), span.linecol_in(wast_raw), Ok(()));
- 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(_) if ACCEPTED_INVALID_MESSAGES.contains(&message) => Ok(()),
+ Ok(_) => Err(anyhow!("expected module to be invalid: {message}")),
Err(_) => Ok(()),
},
);
}
AssertExhaustion { call, message, span } => {
let module = module_registry.get_idx(call.module);
- let args = convert_wastargs(call.args)?;
- let res =
- catch_unwind_silent(|| exec_fn_instance(module, &mut store, call.name, &args).map(|_| ()));
+ let args = convert_wastargs(&mut store, call.args)?;
+ let res = catch_unwind_silent(|| {
+ exec_fn_instance(module, &mut store, call.name, &args, &mut call_results)
+ });
let Ok(Err(tinywasm::Error::Trap(trap))) = res else {
test_group.add_result(
&format!("AssertExhaustion({i})"),
span.linecol_in(wast_raw),
- Err(eyre!("expected trap")),
+ Err(anyhow!("expected trap")),
);
continue;
};
@@ -315,7 +348,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;
}
@@ -327,30 +360,30 @@ impl WastRunner {
wast::WastExecute::Wat(mut wat) => {
let module = parse_module_bytes(&wat.encode().expect("failed to encode module"))
.expect("failed to parse module");
- let imports = Self::imports(&mut store, module_registry.modules()).unwrap();
- ModuleInstance::instantiate(&mut store, &module, Some(imports))?;
+ let imports = Self::imports(&mut store, module_registry.registered()).unwrap();
+ ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
return Ok(());
}
wast::WastExecute::Get { .. } => panic!("get not supported"),
wast::WastExecute::Invoke(invoke) => invoke,
};
let module = module_registry.get_idx(invoke.module);
- let args =
- convert_wastargs(invoke.args).map_err(|err| tinywasm::Error::Other(err.to_string()))?;
- exec_fn_instance(module, &mut store, invoke.name, &args).map(|_| ())
+ let args = convert_wastargs(&mut store, invoke.args)
+ .map_err(|err| tinywasm::Error::Other(err.to_string()))?;
+ exec_fn_instance(module, &mut store, invoke.name, &args, &mut call_results)
});
match res {
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;
}
@@ -359,27 +392,53 @@ 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)),
),
}
}
+ AssertException { exec, span } => {
+ let res: Result<tinywasm::Result<()>, _> = catch_unwind_silent(|| {
+ let invoke = match exec {
+ wast::WastExecute::Wat(mut wat) => {
+ let module = parse_module_bytes(&wat.encode().expect("failed to encode module"))
+ .expect("failed to parse module");
+ let imports = Self::imports(&mut store, module_registry.registered()).unwrap();
+ ModuleInstance::instantiate(&mut store, &module, Some(&imports))?;
+ return Ok(());
+ }
+ wast::WastExecute::Get { .. } => panic!("get not supported"),
+ wast::WastExecute::Invoke(invoke) => invoke,
+ };
+ let module = module_registry.get_idx(invoke.module);
+ let args = convert_wastargs(&mut store, invoke.args)
+ .map_err(|err| tinywasm::Error::Other(err.to_string()))?;
+ exec_fn_instance(module, &mut store, invoke.name, &args, &mut call_results)
+ });
+ let result = match res {
+ Err(err) => Err(anyhow!("test panicked: {}", try_downcast_panic(err))),
+ Ok(Err(tinywasm::Error::Exception(_))) => 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);
+ }
AssertUnlinkable { mut module, span, message } => {
let res = catch_unwind_silent(|| {
let module = parse_module_bytes(&module.encode().expect("failed to encode module"))
.expect("failed to parse module");
- let imports = Self::imports(&mut store, module_registry.modules()).unwrap();
- ModuleInstance::instantiate(&mut store, &module, Some(imports))
+ let imports = Self::imports(&mut store, module_registry.registered()).unwrap();
+ ModuleInstance::instantiate(&mut store, &module, Some(&imports))
});
match res {
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
@@ -389,7 +448,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;
}
@@ -398,27 +457,27 @@ 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)),
),
}
}
Invoke(invoke) => {
let name = invoke.name;
let res: Result<Result<()>, _> = catch_unwind_silent(|| {
- let args = convert_wastargs(invoke.args)?;
+ let args = convert_wastargs(&mut store, invoke.args)?;
let module = module_registry.get_idx(invoke.module);
- exec_fn_instance(module, &mut store, invoke.name, &args).map_err(|e| {
+ exec_fn_instance(module, &mut store, invoke.name, &args, &mut call_results).map_err(|e| {
error!("failed to execute function: {e:?}");
e
})?;
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 } => {
@@ -427,7 +486,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;
}
@@ -435,23 +494,23 @@ 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;
};
- let module_global = match module.global_get(&store, global) {
+ let module_global = match module.global_get(&mut store, global) {
Ok(value) => value,
Err(err) => {
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;
}
@@ -459,12 +518,12 @@ impl WastRunner {
let expected = expected_alternatives
.iter()
.filter_map(|alts| alts.first())
- .find(|exp| exp.matches(&module_global));
+ .find(|exp| exp.matches(&module_global, &store, &module));
if expected.is_none() {
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
)),
@@ -485,7 +544,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;
}
@@ -493,36 +552,42 @@ impl WastRunner {
let invoke_name = invoke.name;
let res: Result<Result<()>, _> = catch_unwind_silent(|| {
- let args = convert_wastargs(invoke.args)?;
- let module = module_registry.get_idx(invoke.module);
- let outcomes = exec_fn_instance(module, &mut store, invoke.name, &args).map_err(|e| {
- error!("failed to execute function: {e:?}");
- e
- })?;
- if !expected_alternatives.iter().any(|expected| expected.len() == outcomes.len()) {
- return Err(eyre!(
+ let args = convert_wastargs(&mut store, invoke.args)?;
+ let module = module_registry
+ .get(invoke.module)
+ .ok_or_else(|| anyhow!("module instance was not found"))?;
+ exec_fn_instance(Some(module.id()), &mut store, invoke.name, &args, &mut call_results)
+ .map_err(|e| {
+ error!("failed to execute function: {e:?}");
+ e
+ })?;
+ if !expected_alternatives.iter().any(|expected| expected.len() == call_results.len()) {
+ return Err(anyhow!(
"expected {} results, got {}",
expected_alternatives.first().map_or(0, |v| v.len()),
- outcomes.len()
+ call_results.len()
));
}
if expected_alternatives.iter().any(|expected| {
- expected.len() == outcomes.len()
- && outcomes.iter().zip(expected.iter()).all(|(outcome, exp)| exp.matches(outcome))
+ expected.len() == call_results.len()
+ && call_results
+ .iter()
+ .zip(expected.iter())
+ .all(|(outcome, exp)| exp.matches(outcome, &store, &module))
}) {
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")),
),
}
}
@@ -594,17 +659,20 @@ struct TestCase {
fn expand_paths(paths: &[PathBuf]) -> Result<Vec<PathBuf>> {
let mut files = Vec::new();
- for path in paths {
+ let mut pending = paths.to_vec();
+ while let Some(path) = pending.pop() {
if path.is_dir() {
- for entry in std::fs::read_dir(path)? {
+ for entry in std::fs::read_dir(&path)? {
let entry = entry?;
let path = entry.path();
- if path.extension().is_some_and(|ext| ext == "wast") {
+ if entry.file_type()?.is_dir() {
+ pending.push(path);
+ } else if path.extension().is_some_and(|ext| ext == "wast") {
files.push(path);
}
}
} else {
- files.push(path.clone());
+ files.push(path);
}
}
files.sort();
@@ -653,12 +721,12 @@ fn exec_with_budget(
func: &tinywasm::Function,
store: &mut Store,
args: &[WasmValue],
-) -> Result<Vec<WasmValue>, tinywasm::Error> {
- let mut exec = func.call_resumable(store, args)?;
+ results: &mut [WasmValue],
+) -> Result<(), tinywasm::Error> {
+ let mut exec = func.call_resumable(store, args, results)?;
for _ in 0..TEST_MAX_SUSPENSIONS {
- match exec.resume_with_time_budget(TEST_TIME_SLICE)? {
- ExecProgress::Completed(values) => return Ok(values),
- ExecProgress::Suspended => {}
+ if let ExecProgress::Completed(()) = exec.resume_with_time_budget(TEST_TIME_SLICE)? {
+ return Ok(());
}
}
Err(tinywasm::Error::Other(format!(
@@ -679,7 +747,8 @@ fn exec_fn_instance(
store: &mut Store,
name: &str,
args: &[WasmValue],
-) -> Result<Vec<WasmValue>, tinywasm::Error> {
+ results: &mut Vec<WasmValue>,
+) -> Result<(), tinywasm::Error> {
let Some(instance) = instance else {
return Err(tinywasm::Error::Other("no instance found".to_string()));
};
@@ -687,7 +756,9 @@ fn exec_fn_instance(
return Err(tinywasm::Error::Other("no instance found".to_string()));
};
let func = instance.func_untyped(store, name)?;
- exec_with_budget(&func, store, args)
+ results.clear();
+ results.resize(func.ty(store)?.results().len(), WasmValue::I32(0));
+ exec_with_budget(&func, store, args, results)
}
fn catch_unwind_silent<R>(f: impl FnOnce() -> R) -> std::thread::Result<R> {
@@ -723,8 +794,13 @@ fn parse_module_bytes(bytes: &[u8]) -> Result<Module> {
Ok(tinywasm::parse_bytes(bytes)?)
}
-fn convert_wastargs(args: Vec<wast::WastArg>) -> Result<Vec<WasmValue>> {
- args.into_iter().map(wastarg2tinywasmvalue).collect()
+fn parse_quote_module(module: QuoteWat) -> Result<(Option<String>, Module)> {
+ let (name, bytes) = encode_quote_wat(module);
+ Ok((name, parse_module_bytes(&bytes)?))
+}
+
+fn convert_wastargs(store: &mut Store, args: Vec<wast::WastArg>) -> Result<Vec<WasmValue>> {
+ args.into_iter().map(|arg| wastarg2tinywasmvalue(store, arg)).collect()
}
fn convert_wastret<'a>(args: impl Iterator<Item = wast::WastRet<'a>>) -> Result<Vec<Vec<ExpectedValue>>> {
@@ -735,7 +811,7 @@ fn convert_wastret<'a>(args: impl Iterator<Item = wast::WastRet<'a>>) -> Result<
for prefix in alternatives {
for choice in &choices {
let mut candidate = prefix.clone();
- candidate.push(*choice);
+ candidate.push(choice.clone());
next.push(candidate);
}
}
@@ -744,7 +820,7 @@ fn convert_wastret<'a>(args: impl Iterator<Item = wast::WastRet<'a>>) -> Result<
Ok(alternatives)
}
-fn wastarg2tinywasmvalue(arg: wast::WastArg) -> Result<WasmValue> {
+fn wastarg2tinywasmvalue(store: &mut Store, arg: wast::WastArg) -> Result<WasmValue> {
let wast::WastArg::Core(arg) = arg else {
bail!("unsupported arg type: Component");
};
@@ -755,27 +831,27 @@ fn wastarg2tinywasmvalue(arg: wast::WastArg) -> Result<WasmValue> {
I32(i) => WasmValue::I32(i),
I64(i) => WasmValue::I64(i),
V128(i) => WasmValue::V128(i.to_le_bytes()),
- RefExtern(v) => ExternRef::new(v).into(),
+ RefExtern(v) => tinywasm::ExternRef::try_new(store, v)?.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 } => RefValue::Null.into(),
+ wast::core::HeapType::Abstract { shared: false, ty: AbstractHeapType::Extern | AbstractHeapType::Any } => {
+ RefValue::Null.into()
+ }
_ => {
bail!("unsupported arg type: refnull: {:?}", t);
}
},
- RefHost(_) => {
- bail!("unsupported arg type: RefHost");
- }
+ RefHost(value) => RefValue::Any(tinywasm::ExternRef::try_new(store, value)?.to_any()).into(),
})
}
fn wast_v128_to_bytes(i: wast::core::V128Pattern) -> [u8; 16] {
let res: Vec<u8> = match i {
wast::core::V128Pattern::F32x4(f) => {
- f.iter().flat_map(|v| nanpattern2tinywasmvalue(*v).unwrap().as_f32().unwrap().to_le_bytes()).collect()
+ f.iter().flat_map(|v| float_value!(*v, f32, F32).as_f32().unwrap().to_le_bytes()).collect()
}
wast::core::V128Pattern::F64x2(f) => {
- f.iter().flat_map(|v| nanpattern2tinywasmvalue(*v).unwrap().as_f64().unwrap().to_le_bytes()).collect()
+ f.iter().flat_map(|v| float_value!(*v, f64, F64).as_f64().unwrap().to_le_bytes()).collect()
}
wast::core::V128Pattern::I16x8(f) => f.iter().flat_map(|v| v.to_le_bytes()).collect(),
wast::core::V128Pattern::I32x4(f) => f.iter().flat_map(|v| v.to_le_bytes()).collect(),
@@ -785,21 +861,46 @@ fn wast_v128_to_bytes(i: wast::core::V128Pattern) -> [u8; 16] {
res.try_into().unwrap()
}
-#[derive(Clone, Copy)]
+#[derive(Clone)]
enum ExpectedValue {
Exact(WasmValue),
RefNull,
RefFunc,
RefExtern,
+ RefAny,
+ RefEq,
+ RefI31,
+ RefStruct,
+ RefArray,
+ RefExternExact(u32),
+ RefFuncExact(u32),
+ RefHostExact(u32),
}
impl ExpectedValue {
- fn matches(&self, value: &WasmValue) -> bool {
+ fn matches(&self, value: &WasmValue, store: &Store, module: &ModuleInstance) -> bool {
match self {
Self::Exact(expected) => value.eq_loose(expected),
Self::RefNull => matches!(value, WasmValue::Ref(RefValue::Null)),
Self::RefFunc => matches!(value, WasmValue::Ref(RefValue::Func(_))),
Self::RefExtern => matches!(value, WasmValue::Ref(RefValue::Extern(_))),
+ Self::RefAny => matches!(value, WasmValue::Ref(RefValue::Any(_))),
+ Self::RefEq => matches!(value, WasmValue::Ref(RefValue::Any(value)) if value.as_eq().is_some()),
+ Self::RefI31 => matches!(value, WasmValue::Ref(RefValue::Any(value)) if value.as_i31().is_some()),
+ Self::RefStruct => matches!(value, WasmValue::Ref(RefValue::Any(value)) if value.as_struct().is_some()),
+ Self::RefArray => matches!(value, WasmValue::Ref(RefValue::Any(value)) if value.as_array().is_some()),
+ Self::RefExternExact(expected) => match value {
+ WasmValue::Ref(RefValue::Extern(value)) => value.key(store) == Ok(*expected),
+ _ => false,
+ },
+ Self::RefHostExact(expected) => match value {
+ WasmValue::Ref(RefValue::Any(value)) => value.to_extern().key(store) == Ok(*expected),
+ _ => false,
+ },
+ Self::RefFuncExact(expected) => module
+ .func_by_index(store, *expected)
+ .and_then(|function| function.as_func_ref(store))
+ .is_ok_and(|expected| matches!(value, WasmValue::Ref(RefValue::Func(value)) if *value == expected)),
}
}
}
@@ -817,84 +918,36 @@ fn wastret2tinywasmvalues(ret: wast::WastRet) -> Result<Vec<ExpectedValue>> {
}
fn wastretcore2tinywasmvalue(ret: wast::core::WastRetCore) -> Result<ExpectedValue> {
- use wast::core::WastRetCore::{F32, F64, I32, I64, RefExtern, RefFunc, RefNull, V128};
+ use wast::core::WastRetCore::{
+ F32, F64, I32, I64, RefAny, RefArray, RefEq, RefExtern, RefFunc, RefHost, RefI31, RefI31Shared, RefNull,
+ RefStruct, V128,
+ };
Ok(match ret {
- F32(f) => ExpectedValue::Exact(nanpattern2tinywasmvalue(f)?),
- F64(f) => ExpectedValue::Exact(nanpattern2tinywasmvalue(f)?),
+ F32(f) => ExpectedValue::Exact(float_value!(f, f32, F32)),
+ F64(f) => ExpectedValue::Exact(float_value!(f, f64, F64)),
I32(i) => ExpectedValue::Exact(WasmValue::I32(i)),
I64(i) => ExpectedValue::Exact(WasmValue::I64(i)),
V128(i) => ExpectedValue::Exact(WasmValue::V128(wast_v128_to_bytes(i))),
RefNull(_) => ExpectedValue::RefNull,
- RefExtern(Some(v)) => ExpectedValue::Exact(ExternRef::new(v).into()),
+ RefExtern(Some(v)) => ExpectedValue::RefExternExact(v),
RefExtern(None) => ExpectedValue::RefExtern,
- RefFunc(Some(wast::token::Index::Num(n, _))) => ExpectedValue::Exact(FuncRef::new(n).into()),
+ RefFunc(Some(wast::token::Index::Num(n, _))) => ExpectedValue::RefFuncExact(n),
RefFunc(None) => ExpectedValue::RefFunc,
RefFunc(v) => {
bail!("unsupported arg type: reffunc: {:?}", v);
}
+ RefAny => ExpectedValue::RefAny,
+ RefEq => ExpectedValue::RefEq,
+ RefI31 | RefI31Shared => ExpectedValue::RefI31,
+ RefStruct => ExpectedValue::RefStruct,
+ RefArray => ExpectedValue::RefArray,
+ RefHost(value) => ExpectedValue::RefHostExact(value),
a => {
bail!("unsupported arg type {:?}", a);
}
})
}
-enum Bits {
- U32(u32),
- U64(u64),
-}
-
-trait FloatToken {
- fn bits(&self) -> Bits;
- fn canonical_nan() -> WasmValue;
- fn arithmetic_nan() -> WasmValue;
- fn value(&self) -> WasmValue {
- match self.bits() {
- Bits::U32(v) => WasmValue::F32(f32::from_bits(v)),
- Bits::U64(v) => WasmValue::F64(f64::from_bits(v)),
- }
- }
-}
-
-impl FloatToken for wast::token::F32 {
- fn bits(&self) -> Bits {
- Bits::U32(self.bits)
- }
-
- fn canonical_nan() -> WasmValue {
- WasmValue::F32(f32::NAN)
- }
-
- fn arithmetic_nan() -> WasmValue {
- WasmValue::F32(f32::NAN)
- }
-}
-
-impl FloatToken for wast::token::F64 {
- fn bits(&self) -> Bits {
- Bits::U64(self.bits)
- }
-
- fn canonical_nan() -> WasmValue {
- WasmValue::F64(f64::NAN)
- }
-
- fn arithmetic_nan() -> WasmValue {
- WasmValue::F64(f64::NAN)
- }
-}
-
-fn nanpattern2tinywasmvalue<T>(arg: wast::core::NanPattern<T>) -> Result<WasmValue>
-where
- T: FloatToken,
-{
- use wast::core::NanPattern::{ArithmeticNan, CanonicalNan, Value};
- Ok(match arg {
- CanonicalNan => T::canonical_nan(),
- ArithmeticNan => T::arithmetic_nan(),
- Value(v) => v.value(),
- })
-}
-
#[cfg(test)]
mod tests {
use super::*;
@@ -912,4 +965,38 @@ mod tests {
let mut runner = WastRunner::new();
runner.run_paths(&[path]).unwrap();
}
+
+ #[test]
+ fn recursively_runs_wast_files_and_ignores_other_files() {
+ let dir = tempfile::tempdir().unwrap();
+ let nested = dir.path().join("nested");
+ std::fs::create_dir(&nested).unwrap();
+ std::fs::write(dir.path().join("README.md"), "not a wast file").unwrap();
+ std::fs::write(nested.join("simple.wast"), "(module)").unwrap();
+
+ let mut runner = WastRunner::new();
+ runner.run_paths(&[dir.path().to_path_buf()]).unwrap();
+ }
+
+ #[test]
+ fn runs_module_definition_and_instance_directives() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("instance.wast");
+ std::fs::write(
+ &path,
+ r#"
+ (module definition $M (global (export "g") i32 (i32.const 42)))
+ (module instance $I $M)
+ (register "I" $I)
+ (module
+ (import "I" "g" (global $g i32))
+ (func (export "get") (result i32) global.get $g))
+ (assert_return (invoke "get") (i32.const 42))
+ "#,
+ )
+ .unwrap();
+
+ let mut runner = WastRunner::new();
+ runner.run_paths(&[path]).unwrap();
+ }
}