1#[cfg(feature = "component-model")]
2use crate::component;
3use crate::core;
4use crate::spectest::*;
5#[cfg(feature = "component-model")]
6use json_from_wast::CoreConst;
7use json_from_wast::{Action, Command, Const, WasmFile, WasmFileType};
8use std::collections::HashMap;
9use std::path::{Path, PathBuf};
10use std::str;
11use std::sync::Arc;
12use std::thread;
13use wasmtime::{error::Context as _, *};
14use wast::lexer::Lexer;
15use wast::parser::{self, ParseBuffer};
16
17pub struct WastContext {
20 current: Option<InstanceKind>,
23 core_linker: Linker<()>,
24 modules: HashMap<Option<String>, ModuleKind>,
25 #[cfg(feature = "component-model")]
26 component_linker: component::Linker<()>,
27
28 pub(crate) core_store: Store<()>,
33 pub(crate) async_runtime: Option<tokio::runtime::Runtime>,
34 generate_dwarf: bool,
35 precompile_save: Option<PathBuf>,
36 precompile_load: Option<PathBuf>,
37
38 modules_by_filename: Arc<HashMap<String, Vec<u8>>>,
39 configure_store: Arc<dyn Fn(&mut Store<()>) + Send + Sync>,
40 ignore_error_messages: bool,
41}
42
43enum Outcome<T = Results> {
44 Ok(T),
45 Trap(Error),
46}
47
48impl<T> Outcome<T> {
49 fn map<U>(self, map: impl FnOnce(T) -> U) -> Outcome<U> {
50 match self {
51 Outcome::Ok(t) => Outcome::Ok(map(t)),
52 Outcome::Trap(t) => Outcome::Trap(t),
53 }
54 }
55
56 fn into_result(self) -> Result<T> {
57 match self {
58 Outcome::Ok(t) => Ok(t),
59 Outcome::Trap(t) => Err(t),
60 }
61 }
62}
63
64#[derive(Debug)]
65enum Results {
66 Core(Vec<Val>),
67 #[cfg(feature = "component-model")]
68 Component(Vec<component::Val>),
69}
70
71#[derive(Clone, Debug)]
72enum ModuleKind {
73 Core(Module),
74 #[cfg(feature = "component-model")]
75 Component(component::Component),
76}
77
78enum InstanceKind {
79 Core(Instance),
80 #[cfg(feature = "component-model")]
81 Component(Store<()>, component::Instance),
82}
83
84enum Export<'a> {
85 Core(Extern),
86 #[cfg(feature = "component-model")]
87 Component(&'a mut Store<()>, component::Func),
88
89 _Unused(std::convert::Infallible, &'a ()),
92}
93
94#[derive(Debug, Copy, Clone, PartialEq)]
98#[expect(missing_docs, reason = "self-describing variants")]
99pub enum Async {
100 Yes,
101 No,
102}
103
104impl WastContext {
105 pub fn new(
113 engine: &Engine,
114 async_: Async,
115 configure: impl Fn(&mut Store<()>) + Send + Sync + 'static,
116 ) -> Self {
117 let mut core_linker = Linker::new(engine);
121 core_linker.allow_shadowing(true);
122 Self {
123 current: None,
124 core_linker,
125 #[cfg(feature = "component-model")]
126 component_linker: {
127 let mut linker = component::Linker::new(engine);
128 linker.allow_shadowing(true);
129 linker
130 },
131 core_store: {
132 let mut store = Store::new(engine, ());
133 configure(&mut store);
134 store
135 },
136 modules: Default::default(),
137 async_runtime: if async_ == Async::Yes {
138 Some(
139 tokio::runtime::Builder::new_current_thread()
140 .build()
141 .unwrap(),
142 )
143 } else {
144 None
145 },
146 generate_dwarf: true,
147 precompile_save: None,
148 precompile_load: None,
149 modules_by_filename: Arc::default(),
150 configure_store: Arc::new(configure),
151 ignore_error_messages: false,
152 }
153 }
154
155 fn engine(&self) -> &Engine {
156 self.core_linker.engine()
157 }
158
159 pub fn ignore_error_messages(&mut self, ignore: bool) -> &mut Self {
162 self.ignore_error_messages = ignore;
163 self
164 }
165
166 pub fn precompile_save(&mut self, path: impl AsRef<Path>) -> &mut Self {
169 self.precompile_save = Some(path.as_ref().into());
170 self
171 }
172
173 pub fn precompile_load(&mut self, path: impl AsRef<Path>) -> &mut Self {
176 self.precompile_load = Some(path.as_ref().into());
177 self
178 }
179
180 fn get_export(&mut self, module: Option<&str>, name: &str) -> Result<Export<'_>> {
181 if let Some(module) = module {
182 return Ok(Export::Core(
183 self.core_linker
184 .get(&mut self.core_store, module, name)
185 .with_context(|| format_err!("no item named `{module}::{name}` found"))?,
186 ));
187 }
188
189 let cur = self
190 .current
191 .as_mut()
192 .ok_or_else(|| format_err!("no previous instance found"))?;
193 Ok(match cur {
194 InstanceKind::Core(i) => Export::Core(
195 i.get_export(&mut self.core_store, name)
196 .ok_or_else(|| format_err!("no item named `{name}` found"))?,
197 ),
198 #[cfg(feature = "component-model")]
199 InstanceKind::Component(store, i) => {
200 let export = i
201 .get_func(&mut *store, name)
202 .ok_or_else(|| format_err!("no func named `{name}` found"))?;
203 Export::Component(store, export)
204 }
205 })
206 }
207
208 fn instantiate_module(&mut self, module: &Module) -> Result<Outcome<Instance>> {
209 let instance = match &self.async_runtime {
210 Some(rt) => rt.block_on(
211 self.core_linker
212 .instantiate_async(&mut self.core_store, &module),
213 ),
214 None => self.core_linker.instantiate(&mut self.core_store, &module),
215 };
216 Ok(match instance {
217 Ok(i) => Outcome::Ok(i),
218 Err(e) => Outcome::Trap(e),
219 })
220 }
221
222 #[cfg(feature = "component-model")]
223 fn instantiate_component(
224 &mut self,
225 component: &component::Component,
226 ) -> Result<Outcome<(component::Component, Store<()>, component::Instance)>> {
227 let mut store = Store::new(self.engine(), ());
228 (self.configure_store)(&mut store);
229 let instance = match &self.async_runtime {
230 Some(rt) => rt.block_on(
231 self.component_linker
232 .instantiate_async(&mut store, &component),
233 ),
234 None => self.component_linker.instantiate(&mut store, &component),
235 };
236 Ok(match instance {
237 Ok(i) => Outcome::Ok((component.clone(), store, i)),
238 Err(e) => Outcome::Trap(e),
239 })
240 }
241
242 pub fn register_spectest(&mut self, config: &SpectestConfig) -> Result<()> {
244 link_spectest(&mut self.core_linker, &mut self.core_store, config)?;
245 #[cfg(feature = "component-model")]
246 link_component_spectest(&mut self.component_linker)?;
247 Ok(())
248 }
249
250 pub fn register_wasmtime(&mut self) -> Result<()> {
253 self.core_linker
254 .func_wrap("wasmtime", "gc", |mut caller: Caller<_>| {
255 caller.gc(None)?;
256 Ok(())
257 })?;
258 self.core_linker.func_wrap(
259 "wasmtime",
260 "set-fuel",
261 |mut caller: Caller<_>, fuel: u64| caller.set_fuel(fuel),
262 )?;
263 self.core_linker
264 .func_wrap("wasmtime", "get-fuel", |caller: Caller<_>| {
265 caller.get_fuel()
266 })?;
267 self.core_linker.func_wrap(
268 "wasmtime",
269 "new-externref",
270 |mut caller: Caller<_>, x: u32| -> Result<Option<Rooted<ExternRef>>> {
271 Ok(Some(ExternRef::new(&mut caller, x)?))
272 },
273 )?;
274 #[cfg(feature = "component-model")]
275 {
276 let mut i = self.component_linker.instance("wasmtime")?;
277 i.func_wrap(
278 "set-max-table-capacity",
279 |mut store, (capacity,): (u32,)| {
280 store
281 .as_context_mut()
282 .concurrent_resource_table()
283 .expect("table must be present")
284 .set_max_capacity(capacity.try_into().unwrap());
285 Ok(())
286 },
287 )?;
288 i.func_wrap("gc", |mut store, (): ()| {
289 store.as_context_mut().gc(None)?;
290 Ok(())
291 })?;
292 i.func_wrap("set-hostcall-fuel", |mut store, (fuel,): (u64,)| {
293 store
294 .as_context_mut()
295 .set_hostcall_fuel(usize::try_from(fuel).unwrap_or(usize::MAX));
296 Ok(())
297 })?;
298 }
299 Ok(())
300 }
301
302 fn perform_action(&mut self, action: &Action<'_>) -> Result<Outcome> {
304 struct ReplaceRuntime<'a> {
309 ctx: &'a mut WastContext,
310 rt: Option<tokio::runtime::Runtime>,
311 }
312 impl Drop for ReplaceRuntime<'_> {
313 fn drop(&mut self) {
314 self.ctx.async_runtime = self.rt.take();
315 }
316 }
317 let replace = ReplaceRuntime {
318 rt: self.async_runtime.take(),
319 ctx: self,
320 };
321 let me = &mut *replace.ctx;
322 match action {
323 Action::Invoke {
324 module,
325 field,
326 args,
327 } => match me.get_export(module.as_deref(), field)? {
328 Export::Core(export) => {
329 drop(replace);
330 let func = export
331 .into_func()
332 .ok_or_else(|| format_err!("no function named `{field}`"))?;
333 let values = args
334 .iter()
335 .map(|v| match v {
336 Const::Core(v) => core::val(self, v),
337 _ => bail!("expected core function, found other other argument {v:?}"),
338 })
339 .collect::<Result<Vec<_>>>()?;
340
341 let mut results =
342 vec![Val::null_func_ref(); func.ty(&self.core_store).results().len()];
343 let result = match &self.async_runtime {
344 Some(rt) => rt.block_on(func.call_async(
345 &mut self.core_store,
346 &values,
347 &mut results,
348 )),
349 None => func.call(&mut self.core_store, &values, &mut results),
350 };
351
352 Ok(match result {
353 Ok(()) => {
354 Val::ensure_all_rooted(&mut self.core_store, &mut results)?;
357 Outcome::Ok(Results::Core(results))
358 }
359 Err(e) => Outcome::Trap(e),
360 })
361 }
362 #[cfg(feature = "component-model")]
363 Export::Component(store, func) => {
364 let values = args
365 .iter()
366 .map(|v| match v {
367 Const::Component(v) => component::val(v),
368 Const::Core(CoreConst::F32 { value }) => {
369 Ok(component::Val::Float32(f32::from_bits(value.to_bits())))
370 }
371 Const::Core(CoreConst::F64 { value }) => {
372 Ok(component::Val::Float64(f64::from_bits(value.to_bits())))
373 }
374 _ => bail!("expected component function, found other argument {v:?}"),
375 })
376 .collect::<Result<Vec<_>>>()?;
377
378 let mut results =
379 vec![component::Val::Bool(false); func.ty(&store).results().len()];
380 let result = match &replace.rt {
381 Some(rt) => {
382 rt.block_on(func.call_async(&mut *store, &values, &mut results))
383 }
384 None => func.call(&mut *store, &values, &mut results),
385 };
386 Ok(match result {
387 Ok(()) => Outcome::Ok(Results::Component(results)),
388 Err(e) => Outcome::Trap(e),
389 })
390 }
391 },
392 Action::Get { module, field, .. } => me.get(module.as_deref(), field),
393 }
394 }
395
396 fn module(&mut self, name: Option<&str>, module: &ModuleKind) -> Result<()> {
399 match module {
400 ModuleKind::Core(module) => {
401 let instance = match self.instantiate_module(&module)? {
402 Outcome::Ok(i) => i,
403 Outcome::Trap(e) => return Err(e).context("instantiation failed"),
404 };
405 if let Some(name) = name {
406 self.core_linker
407 .instance(&mut self.core_store, name, instance)?;
408 }
409 self.current = Some(InstanceKind::Core(instance));
410 }
411 #[cfg(feature = "component-model")]
412 ModuleKind::Component(module) => {
413 let (component, mut store, instance) = match self.instantiate_component(&module)? {
414 Outcome::Ok(i) => i,
415 Outcome::Trap(e) => return Err(e).context("instantiation failed"),
416 };
417 if let Some(name) = name {
418 let ty = component.component_type();
419 let engine = self.engine().clone();
420 let mut linker = self.component_linker.instance(name)?;
421 for (name, item) in ty.exports(&engine) {
422 match item.ty {
423 component::types::ComponentItem::Module(_) => {
424 let module = instance.get_module(&mut store, name).unwrap();
425 linker.module(name, &module)?;
426 }
427 component::types::ComponentItem::Resource(_) => {
428 let resource = instance.get_resource(&mut store, name).unwrap();
429 linker.resource(name, resource, |_, _| Ok(()))?;
430 }
431 _ => {}
438 }
439 }
440 }
441 self.current = Some(InstanceKind::Component(store, instance));
442 }
443 }
444 Ok(())
445 }
446
447 fn module_definition(&mut self, file: &WasmFile) -> Result<ModuleKind> {
452 let name = match file.module_type {
453 WasmFileType::Text => file.binary_filename.as_ref().unwrap_or(&file.filename),
454 WasmFileType::Binary => &file.filename,
455 };
456
457 match &self.precompile_load {
458 Some(path) => {
459 let cwasm = path.join(&name[..]).with_extension("cwasm");
460 match Engine::detect_precompiled_file(&cwasm)
461 .with_context(|| format!("failed to read {cwasm:?}"))?
462 {
463 Some(Precompiled::Module) => {
464 let module = unsafe { Module::deserialize_file(self.engine(), &cwasm)? };
465 Ok(ModuleKind::Core(module))
466 }
467 #[cfg(feature = "component-model")]
468 Some(Precompiled::Component) => {
469 let component = unsafe {
470 component::Component::deserialize_file(self.engine(), &cwasm)?
471 };
472 Ok(ModuleKind::Component(component))
473 }
474 #[cfg(not(feature = "component-model"))]
475 Some(Precompiled::Component) => {
476 bail!("support for components disabled at compile time")
477 }
478 None => bail!("expected a cwasm file"),
479 }
480 }
481 None => {
482 let bytes = &self.modules_by_filename[&name[..]];
483
484 if wasmparser::Parser::is_core_wasm(&bytes) {
485 let module = Module::new(self.engine(), &bytes)?;
486 Ok(ModuleKind::Core(module))
487 } else {
488 #[cfg(feature = "component-model")]
489 {
490 let component = component::Component::new(self.engine(), &bytes)?;
491 Ok(ModuleKind::Component(component))
492 }
493 #[cfg(not(feature = "component-model"))]
494 bail!("component-model support not enabled");
495 }
496 }
497 }
498 }
499
500 fn register(&mut self, name: Option<&str>, as_name: &str) -> Result<()> {
502 match name {
503 Some(name) => self.core_linker.alias_module(name, as_name),
504 None => {
505 let current = self
506 .current
507 .as_ref()
508 .ok_or(format_err!("no previous instance"))?;
509 match current {
510 InstanceKind::Core(current) => {
511 self.core_linker
512 .instance(&mut self.core_store, as_name, *current)?;
513 }
514 #[cfg(feature = "component-model")]
515 InstanceKind::Component(..) => {
516 bail!("register not implemented for components");
517 }
518 }
519 Ok(())
520 }
521 }
522 }
523
524 fn get(&mut self, instance_name: Option<&str>, field: &str) -> Result<Outcome> {
526 let global = match self.get_export(instance_name, field)? {
527 Export::Core(e) => e
528 .into_global()
529 .ok_or_else(|| format_err!("no global named `{field}`"))?,
530 #[cfg(feature = "component-model")]
531 Export::Component(..) => bail!("no global named `{field}`"),
532 };
533 let mut val = global.get(&mut self.core_store);
534 val.ensure_rooted(&mut self.core_store)?;
535 Ok(Outcome::Ok(Results::Core(vec![val])))
536 }
537
538 fn assert_return(&mut self, result: Outcome, results: &[Const]) -> Result<()> {
539 match result.into_result()? {
540 Results::Core(values) => {
541 if values.len() != results.len() {
542 bail!("expected {} results found {}", results.len(), values.len());
543 }
544 for (i, (v, e)) in values.iter().zip(results).enumerate() {
545 let e = match e {
546 Const::Core(core) => core,
547 _ => bail!("expected core value found other value {e:?}"),
548 };
549 core::match_val(&mut self.core_store, v, e)
550 .with_context(|| format!("result {i} didn't match"))?;
551 }
552 }
553 #[cfg(feature = "component-model")]
554 Results::Component(values) => {
555 if values.len() != results.len() {
556 bail!("expected {} results found {}", results.len(), values.len());
557 }
558 for (i, (v, e)) in values.iter().zip(results).enumerate() {
559 match (e, v) {
560 (Const::Component(e), v) => component::match_val(e, v),
561 (Const::Core(CoreConst::F32 { value }), component::Val::Float32(v)) => {
562 core::match_f32(v.to_bits(), value)
563 }
564 (Const::Core(CoreConst::F64 { value }), component::Val::Float64(v)) => {
565 core::match_f64(v.to_bits(), value)
566 }
567 _ => bail!("expected component value found other value {e:?}"),
568 }
569 .with_context(|| format!("result {i} didn't match"))?;
570 }
571 }
572 }
573 Ok(())
574 }
575
576 fn assert_trap(&self, result: Outcome, expected: &str) -> Result<()> {
577 let trap = match result {
578 Outcome::Ok(values) => bail!("expected trap, got {values:?}"),
579 Outcome::Trap(t) => t,
580 };
581 let actual = format!("{trap:?}");
582 if actual.contains(expected)
583 || (expected.contains("uninitialized element 2") && actual.contains("uninitialized element"))
587 || (expected.contains("null function") && (actual.contains("uninitialized element") || actual.contains("null reference")))
589 || (expected.contains("null") && expected.contains("reference") && actual.contains("null reference"))
591 {
592 return Ok(());
593 }
594 bail!("expected '{expected}', got '{actual}'")
595 }
596
597 fn assert_exception(&mut self, result: Outcome) -> Result<()> {
598 match result {
599 Outcome::Ok(values) => bail!("expected exception, got {values:?}"),
600 Outcome::Trap(err) if err.is::<ThrownException>() => {
601 let _ = self
603 .core_store
604 .take_pending_exception()
605 .expect("there should be a pending exception on the store");
606 Ok(())
607 }
608 Outcome::Trap(err) => bail!("expected exception, got {err:?}"),
609 }
610 }
611
612 fn assert_suspension(&self, result: Outcome, _expected: &str) -> Result<()> {
613 match result {
614 Outcome::Ok(values) => bail!("expected suspension, got {values:?}"),
615 Outcome::Trap(err) if err.downcast_ref::<Trap>() == Some(&Trap::UnhandledTag) => Ok(()),
616 Outcome::Trap(err) => bail!("expected suspension, got {err:?}"),
617 }
618 }
619
620 pub fn run_wast(&mut self, filename: &str, wast: &[u8]) -> Result<()> {
622 let wast = str::from_utf8(wast)?;
623
624 let adjust_wast = |mut err: wast::Error| {
625 err.set_path(filename.as_ref());
626 err.set_text(wast);
627 err
628 };
629
630 let mut lexer = Lexer::new(wast);
631 lexer.allow_confusing_unicode(filename.ends_with("names.wast"));
632 let mut buf = ParseBuffer::new_with_lexer(lexer).map_err(adjust_wast)?;
633 buf.track_instr_spans(self.generate_dwarf);
634 let ast = parser::parse::<wast::Wast>(&buf).map_err(adjust_wast)?;
635
636 let mut ast = json_from_wast::Opts::default()
637 .dwarf(self.generate_dwarf)
638 .convert(filename, wast, ast)
639 .to_wasmtime_result()?;
640
641 if !self.modules_by_filename.is_empty() {
644 self.modules_by_filename = Arc::default();
645 }
646 let modules_by_filename = Arc::get_mut(&mut self.modules_by_filename).unwrap();
647 for (name, bytes) in ast.wasms.drain(..) {
648 let prev = modules_by_filename.insert(name, bytes);
649 assert!(prev.is_none());
650 }
651
652 match &self.precompile_save {
653 Some(path) => {
654 let json_path = path
655 .join(Path::new(filename).file_name().unwrap())
656 .with_extension("json");
657 let json = serde_json::to_string(&ast)?;
658 std::fs::write(&json_path, json)
659 .with_context(|| format!("failed to write {json_path:?}"))?;
660 for (name, bytes) in self.modules_by_filename.iter() {
661 let cwasm_path = path.join(name).with_extension("cwasm");
662 let cwasm = if wasmparser::Parser::is_core_wasm(&bytes) {
663 self.engine().precompile_module(bytes)
664 } else {
665 #[cfg(feature = "component-model")]
666 {
667 self.engine().precompile_component(bytes)
668 }
669 #[cfg(not(feature = "component-model"))]
670 bail!("component-model support not enabled");
671 };
672 if let Ok(cwasm) = cwasm {
673 std::fs::write(&cwasm_path, cwasm)
674 .with_context(|| format!("failed to write {cwasm_path:?}"))?;
675 }
676 }
677 Ok(())
678 }
679 None => self.run_directives(ast.commands, filename),
680 }
681 }
682
683 fn run_directives(&mut self, directives: Vec<Command<'_>>, filename: &str) -> Result<()> {
684 thread::scope(|scope| {
685 let mut threads = HashMap::new();
686 for directive in directives {
687 let line = directive.line();
688 log::debug!("running directive on {filename}:{line}");
689 self.run_directive(directive, filename, &scope, &mut threads)
690 .with_context(|| format!("failed directive on {filename}:{line}"))?;
691 }
692 Ok(())
693 })
694 }
695
696 fn run_directive<'a>(
697 &mut self,
698 directive: Command<'a>,
699 filename: &'a str,
700 scope: &'a thread::Scope<'a, '_>,
702 threads: &mut HashMap<String, thread::ScopedJoinHandle<'a, Result<()>>>,
703 ) -> Result<()> {
704 use Command::*;
705
706 match directive {
707 Module {
708 name,
709 file,
710 line: _,
711 } => {
712 let module = self.module_definition(&file)?;
713 self.module(name.as_deref(), &module)?;
714 }
715 ModuleDefinition {
716 name,
717 file,
718 line: _,
719 } => {
720 let module = self.module_definition(&file)?;
721 self.modules.insert(name.map(|s| s.to_string()), module);
722 }
723 ModuleInstance {
724 instance,
725 module,
726 line: _,
727 } => {
728 let module = self
729 .modules
730 .get(&module.as_ref().map(|s| s.to_string()))
731 .cloned()
732 .ok_or_else(|| format_err!("no module named {module:?}"))?;
733 self.module(instance.as_deref(), &module)?;
734 }
735 Register { line: _, name, as_ } => {
736 self.register(name.as_deref(), &as_)?;
737 }
738 Action { action, line: _ } => {
739 self.perform_action(&action)?;
740 }
741 AssertReturn {
742 action,
743 expected,
744 line: _,
745 } => {
746 let result = self.perform_action(&action)?;
747 self.assert_return(result, &expected)?;
748 }
749 AssertTrap {
750 action,
751 text,
752 line: _,
753 } => {
754 let result = self.perform_action(&action)?;
755 self.assert_trap(result, &text)?;
756 }
757 AssertUninstantiable {
758 file,
759 text,
760 line: _,
761 } => {
762 let result = match self.module_definition(&file)? {
763 ModuleKind::Core(module) => self
764 .instantiate_module(&module)?
765 .map(|_| Results::Core(Vec::new())),
766 #[cfg(feature = "component-model")]
767 ModuleKind::Component(component) => self
768 .instantiate_component(&component)?
769 .map(|_| Results::Component(Vec::new())),
770 };
771 self.assert_trap(result, &text)?;
772 }
773 AssertExhaustion {
774 action,
775 text,
776 line: _,
777 } => {
778 let result = self.perform_action(&action)?;
779 self.assert_trap(result, &text)?;
780 }
781 AssertInvalid {
782 file,
783 text,
784 line: _,
785 }
786 | AssertMalformed {
787 file,
788 text,
789 line: _,
790 } => {
791 let err = match self.module_definition(&file) {
792 Ok(_) => bail!("expected module to fail to build"),
793 Err(e) => e,
794 };
795 self.match_error_message(&text, err)?;
796 }
797 AssertUnlinkable {
798 file,
799 text,
800 line: _,
801 } => {
802 let module = self.module_definition(&file)?;
803 let err = match self.module(None, &module) {
804 Ok(_) => bail!("expected module to fail to link"),
805 Err(e) => e,
806 };
807 self.match_error_message(&text, err)?;
808 }
809 AssertException { line: _, action } => {
810 let result = self.perform_action(&action)?;
811 self.assert_exception(result)?;
812 }
813 AssertSuspension {
814 line: _,
815 action,
816 text,
817 } => {
818 let result = self.perform_action(&action)?;
819 self.assert_suspension(result, &text)?;
820 }
821
822 Thread {
823 name,
824 shared_module,
825 commands,
826 line: _,
827 } => {
828 let mut core_linker = Linker::new(self.engine());
829 if let Some(id) = shared_module {
830 let items = self
831 .core_linker
832 .iter(&mut self.core_store)
833 .filter(|(module, _, _)| *module == &id[..])
834 .collect::<Vec<_>>();
835 for (module, name, item) in items {
836 core_linker.define(&mut self.core_store, module, name, item)?;
837 }
838 }
839 let mut child_cx = WastContext {
840 current: None,
841 core_linker,
842 #[cfg(feature = "component-model")]
843 component_linker: component::Linker::new(self.engine()),
844 core_store: {
845 let mut store = Store::new(self.engine(), ());
846 (self.configure_store)(&mut store);
847 store
848 },
849 modules: self.modules.clone(),
850 async_runtime: self.async_runtime.as_ref().map(|_| {
851 tokio::runtime::Builder::new_current_thread()
852 .build()
853 .unwrap()
854 }),
855 generate_dwarf: self.generate_dwarf,
856 modules_by_filename: self.modules_by_filename.clone(),
857 precompile_load: self.precompile_load.clone(),
858 precompile_save: self.precompile_save.clone(),
859 configure_store: self.configure_store.clone(),
860 ignore_error_messages: self.ignore_error_messages,
861 };
862 let child = scope.spawn(move || child_cx.run_directives(commands, filename));
863 threads.insert(name.to_string(), child);
864 }
865 Wait { thread, .. } => {
866 threads
867 .remove(&thread[..])
868 .ok_or_else(|| format_err!("no thread named `{thread}`"))?
869 .join()
870 .unwrap()?;
871 }
872
873 AssertMalformedCustom {
874 file: _,
875 text: _,
876 line: _,
877 }
878 | AssertInvalidCustom {
879 file: _,
880 text: _,
881 line: _,
882 } => bail!("unimplemented wast directives"),
883 }
884
885 Ok(())
886 }
887
888 pub fn run_file(&mut self, path: &Path) -> Result<()> {
890 match &self.precompile_load {
891 Some(precompile) => {
892 let file = precompile
893 .join(path.file_name().unwrap())
894 .with_extension("json");
895 let json = std::fs::read_to_string(&file)
896 .with_context(|| format!("failed to read {file:?}"))?;
897 let wast = serde_json::from_str::<json_from_wast::Wast<'_>>(&json)?;
898 self.run_directives(wast.commands, &wast.source_filename)
899 }
900 None => {
901 let bytes = std::fs::read(path)
902 .with_context(|| format!("failed to read `{}`", path.display()))?;
903 self.run_wast(path.to_str().unwrap(), &bytes)
904 }
905 }
906 }
907
908 pub fn generate_dwarf(&mut self, enable: bool) -> &mut Self {
911 self.generate_dwarf = enable;
912 self
913 }
914
915 fn match_error_message(&self, expected: &str, err: wasmtime::Error) -> Result<()> {
916 if self.ignore_error_messages {
917 return Ok(());
918 }
919 let actual = format!("{err:?}");
920 if actual.contains(expected) {
921 return Ok(());
922 }
923 bail!("assert_invalid: expected \"{expected}\", got \"{actual}\"",)
924 }
925}