diff options
Diffstat (limited to 'crates/cli/src/wast_runner.rs')
| -rw-r--r-- | crates/cli/src/wast_runner.rs | 517 |
1 files changed, 302 insertions, 215 deletions
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(); + } } |
