spacewasm 0.4.5

A no_std WebAssembly 1.0 decoder, validator, and interpreter for on-board spacecraft use
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
///
/// Copyright 2026 California Institute of Technology
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// ---
/// Portions of this file are derived from https://github.com/DLR-FT/wasm-interpreter:
/// Copyright © 2024-2026 Deutsches Zentrum für Luft- und Raumfahrt e.V.
/// (DLR).
/// Copyright © 2024-2025 OxidOS Automotive SRL.
use super::inspector::{Inspector, LimitedVec};
use core::panic;
use serde::{Deserialize, Serialize};
use spacewasm::{
    AllocError, Allocator, CodeBuilder, CompilerOptions, ConstantExprError, Engine, ExportDesc,
    GlobalValue, GlobalValueError, HostFunction, HostGlobal, HostModule, InnerVec, Interpreter,
    InterpreterResult, InterpreterRunner, Limit, Memory, MemoryError, MemoryStatistics, Module,
    ModuleRef, ParseError, Ref, StartInvocation, TrapReason, ValType, ValidationError, Value,
    WasmMemoryAllocator, WasmRef, WasmStream, global_allocator, vec,
};
use std::alloc::Layout;
use std::cell::RefCell;
use std::ops::ControlFlow;
use std::panic::catch_unwind;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command as ProcessCommand;
use std::ptr::NonNull;
use std::rc::Rc;

type SubtestLogType = Arc<Mutex<Option<Rc<RefCell<LimitedVec<String>>>>>>;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

#[derive(Debug, Deserialize, Serialize)]
struct TestFile {
    source_filename: String,
    commands: Vec<Command>,
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
enum Command {
    Module {
        line: u32,
        #[serde(default)]
        name: Option<String>,
        filename: String,
    },
    AssertReturn {
        line: u32,
        action: Action,
        expected: Vec<ValueSpec>,
    },
    AssertTrap {
        line: u32,
        action: Action,
        text: String,
    },
    AssertUninstantiable {
        line: u32,
        filename: String,
        text: String,
        module_type: String,
    },
    AssertMalformed {
        line: u32,
        filename: String,
        text: String,
        module_type: String,
    },
    AssertInvalid {
        line: u32,
        filename: String,
        text: String,
        module_type: String,
    },
    AssertUnlinkable {
        line: u32,
        filename: String,
        text: String,
        module_type: String,
    },
    AssertExhaustion {
        line: u32,
        action: Action,
        text: String,
    },
    Register {
        line: u32,
        name: Option<String>,
        #[serde(rename = "as")]
        as_name: String,
    },
    Action {
        line: u32,
        action: Action,
    },
}

#[derive(Debug, Deserialize, Serialize)]
#[serde(tag = "type")]
#[serde(rename_all = "snake_case")]
enum Action {
    Invoke {
        #[serde(default)]
        module: Option<String>,
        field: String,
        args: Vec<ValueSpec>,
    },
    Get {
        #[serde(default)]
        module: Option<String>,
        field: String,
    },
}

#[derive(Debug, Deserialize, Serialize, Clone)]
struct ValueSpec {
    #[serde(rename = "type")]
    ty: String,
    #[serde(default)]
    value: Option<String>,
}

struct RustSystemAllocator;

unsafe impl Allocator for RustSystemAllocator {
    unsafe fn alloc(&self, layout: Layout) -> Result<*mut u8, AllocError> {
        unsafe { Ok(std::alloc::alloc(layout)) }
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        unsafe { std::alloc::dealloc(ptr, layout) }
    }

    fn memory_statistics(&self) -> MemoryStatistics {
        MemoryStatistics {
            total_bytes: 0,
            pad_bytes: 0,
        }
    }
}

impl WasmMemoryAllocator for RustSystemAllocator {
    fn allocate(&self, layout: Layout) -> Result<NonNull<u8>, AllocError> {
        unsafe { NonNull::new(std::alloc::alloc(layout)).ok_or(AllocError::AllocationFailed) }
    }

    fn reallocate(
        &self,
        ptr: NonNull<u8>,
        old_layout: Layout,
        layout: Layout,
    ) -> Result<NonNull<u8>, AllocError> {
        unsafe {
            NonNull::new(std::alloc::realloc(ptr.as_ptr(), old_layout, layout.size()))
                .ok_or(AllocError::AllocationFailed)
        }
    }

    fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
        unsafe { std::alloc::dealloc(ptr.as_ptr(), layout) }
    }
}

global_allocator!(RustSystemAllocator, RustSystemAllocator);

pub struct ByteStream {
    buffer: Option<Vec<u8>>,
    consumed: bool,
}

impl ByteStream {
    fn new(data: &[u8]) -> Self {
        Self {
            buffer: Some(data.to_vec()),
            consumed: false,
        }
    }
}

struct StaticGlobal {
    value: Mutex<Value>,
    ty: ValType,
}

impl GlobalValue for StaticGlobal {
    fn write(&self, value: Value) -> Result<(), GlobalValueError> {
        *self.value.lock().unwrap() = value;
        Ok(())
    }

    fn read(&self) -> Result<Value, GlobalValueError> {
        Ok(*self.value.lock().unwrap())
    }

    fn ty(&self) -> ValType {
        self.ty
    }

    fn mutable(&self) -> bool {
        false
    }
}

pub struct MutableStaticGlobal {
    pub value: Mutex<Value>,
    pub ty: ValType,
}

impl GlobalValue for MutableStaticGlobal {
    fn write(&self, value: Value) -> Result<(), GlobalValueError> {
        *self.value.lock().unwrap() = value;
        Ok(())
    }

    fn read(&self) -> Result<Value, GlobalValueError> {
        Ok(*self.value.lock().unwrap())
    }

    fn ty(&self) -> ValType {
        self.ty
    }

    fn mutable(&self) -> bool {
        true
    }
}

impl WasmStream for ByteStream {
    fn read(&mut self) -> Result<Option<InnerVec<u8>>, u8> {
        if self.consumed {
            return Ok(None);
        }

        if let Some(ref mut vec) = self.buffer {
            self.consumed = true;
            let inner = InnerVec {
                ptr: vec.as_mut_ptr(),
                capacity: vec.len() as u32,
                len: vec.len() as u32,
            };
            Ok(Some(inner))
        } else {
            Ok(None)
        }
    }

    fn return_(&mut self, _chunk: InnerVec<u8>) {
        // Buffer is kept alive in self.buffer, so nothing to do
    }
}

const MAX_CODE_PAGES: u32 = 256;
const MAX_CONTROL_FRAMES: usize = 128;
const MAX_STACK_DEPTH: usize = 256;

/// Builds the set of host modules an engine is instantiated with. A factory
/// (rather than a `Vec`) is required because the engine is rebuilt on every
/// [`TestContext::save_store`], and [`HostModule`] is not `Clone`.
type HostModuleFactory = fn() -> spacewasm::Vec<HostModule>;

struct TestContext {
    engine: Engine,
    code_builder: CodeBuilder,
    /// Maps instance names (like "$Mf") to module indices
    /// This is separate from the module's name field which is used for linking/imports
    instance_names: std::collections::HashMap<String, usize>,
    /// Produces the host modules exposed to the test's modules. Stored so the
    /// store can be rebuilt with the same host modules in `save_store`.
    host_modules: HostModuleFactory,
    /// Return types of the currently paused function (if any)
    paused_return_types: Option<spacewasm::Vec<ValType>>,
}

fn new_engine(host_modules: HostModuleFactory) -> Engine {
    Engine::new(1024, 256, host_modules()).unwrap()
}

impl TestContext {
    fn new(host_modules: HostModuleFactory) -> Self {
        TestContext {
            engine: new_engine(host_modules),
            code_builder: CodeBuilder::new(CompilerOptions {
                allow_memory_grow: true,
                max_backpatch_iterations: 0,
                max_code_pages: MAX_CODE_PAGES,
            })
            .unwrap(),
            instance_names: std::collections::HashMap::new(),
            host_modules,
            paused_return_types: None,
        }
    }

    fn current_module_index(&self) -> usize {
        if self.engine.store.modules().is_empty() {
            0
        } else {
            self.engine.store.modules().len() - 1
        }
    }

    fn find_module_by_name(&self, name: &str) -> Option<usize> {
        // First check instance names
        if let Some(&idx) = self.instance_names.get(name) {
            return Some(idx);
        }
        // Fall back to checking the module's name field (registered name)
        self.engine
            .store
            .modules()
            .iter()
            .position(|m| m.name == name)
    }

    /// Save the current store state
    /// Used to restore state after failed module loads that mutate the store (memory/tables)
    fn save_store(&self) -> Engine {
        let mut cloned = new_engine(self.host_modules);

        // Clone all modules into the new store
        for module in self.engine.store.modules().iter() {
            let cloned_module = clone_module(module);
            cloned.store.push_module(cloned_module);
        }

        cloned
    }

    /// Restore the store from a saved copy
    fn restore_store(&mut self, saved: Engine) {
        self.engine = saved;
    }
}

fn parse_value(spec: &ValueSpec) -> Value {
    let value_str = spec.value.as_ref().expect("Missing value field in spec");
    match spec.ty.as_str() {
        "i32" => Value::I32(
            value_str
                .parse::<u32>()
                .unwrap_or_else(|e| panic!("Failed to parse i32 '{value_str}': {e}"))
                as i32,
        ),
        "i64" => Value::I64(
            value_str
                .parse::<u64>()
                .unwrap_or_else(|e| panic!("Failed to parse i64 '{value_str}': {e}"))
                as i64,
        ),
        "f32" => {
            let bits = value_str
                .parse::<u32>()
                .unwrap_or_else(|e| panic!("Failed to parse f32 bits '{value_str}': {e}"));
            Value::F32(f32::from_bits(bits))
        }
        "f64" => {
            let bits = value_str
                .parse::<u64>()
                .unwrap_or_else(|e| panic!("Failed to parse f64 bits '{value_str}': {e}"));
            Value::F64(f64::from_bits(bits))
        }
        _ => panic!("Unsupported value type: {}", spec.ty),
    }
}

fn assert_nan_f32(z: f32, arithmetic: bool) {
    let bits = z.to_bits();

    let exponent = (bits >> 23) & 0xFF;
    let payload = bits & 0x7F_FFFF;

    if arithmetic {
        assert!(
            (exponent == 0xFF) && ((payload & 0x40_0000) != 0),
            "Expected arithmetic NaN f32 {} ({:x}) (exponent={}), (payload={:x})",
            z,
            bits,
            exponent,
            payload
        )
    } else {
        assert!(
            (exponent == 0xFF) && (payload == 0x400000),
            "Expected canonical NaN f32 {} ({:x}) (exponent={}), (payload={:x})",
            z,
            bits,
            exponent,
            payload
        );
    }
}

fn assert_nan_f64(z: f64, arithmetic: bool) {
    let bits = z.to_bits();

    let exponent = (bits >> 52) & 0x7FF;
    let payload = bits & 0xF_FFFF_FFFF_FFFF;

    if arithmetic {
        assert!(
            (exponent == 0x7FF) && ((payload & 0x8_0000_0000_0000) != 0),
            "Expected arithmetic NaN f64 {} ({:x}) (exponent={}), (payload={:x})",
            z,
            bits,
            exponent,
            payload
        )
    } else {
        assert!(
            (exponent == 0x7FF) && (payload == 0x8_0000_0000_0000),
            "Expected canonical NaN f32 {} ({:08x}) (exponent={}), (payload={:08x})",
            z,
            bits,
            exponent,
            payload
        );
    }
}

fn compare_values(actual: Value, expected: &ValueSpec) {
    let value_str = expected
        .value
        .as_ref()
        .expect("Missing expected value in spec");

    match expected.ty.as_str() {
        "i32" => {
            let Value::I32(a) = actual else {
                panic!("Expected i32, got {actual:?}");
            };
            let e = value_str.parse::<u32>().expect("failed to parse i32") as i32;
            assert_eq!(a, e, "Expected i32 {e}, got {a}");
        }
        "i64" => {
            let Value::I64(a) = actual else {
                panic!("Expected i64, got {actual:?}");
            };
            let e = value_str.parse::<u64>().expect("failed to parse i64") as i64;
            assert_eq!(a, e, "Expected i64 {e}, got {a}");
        }
        "f32" => {
            let Value::F32(a) = actual else {
                panic!("Expected f32, got {actual:?}");
            };

            match value_str.as_str() {
                "nan:arithmetic" => assert_nan_f32(a, true),
                "nan:canonical" => assert_nan_f32(a, false),
                _ => {
                    let expected_f32 =
                        f32::from_bits(value_str.parse::<u32>().expect("failed to parse f32 bits"));
                    assert_eq!(
                        a.to_bits(),
                        expected_f32.to_bits(),
                        "Expected f32 {} ({:08x}), got {} ({:08x})",
                        expected_f32,
                        expected_f32.to_bits(),
                        a,
                        a.to_bits()
                    );
                }
            };
        }
        "f64" => {
            let Value::F64(a) = actual else {
                panic!("Expected f64, got {actual:?}");
            };

            match value_str.as_str() {
                "nan:arithmetic" => assert_nan_f64(a, true),
                "nan:canonical" => assert_nan_f64(a, false),
                _ => {
                    let expected_f64 =
                        f64::from_bits(value_str.parse::<u64>().expect("failed to parse f64 bits"));
                    assert_eq!(
                        a.to_bits(),
                        expected_f64.to_bits(),
                        "Expected f64 {} ({:08x}), got {} ({:08x})",
                        expected_f64,
                        expected_f64.to_bits(),
                        a,
                        a.to_bits()
                    );
                }
            };
        }
        _ => panic!("Unsupported expected value type: {}", expected.ty),
    }
}

#[derive(Debug)]
#[allow(clippy::enum_variant_names)]
enum ModuleLoadError {
    DecodeError(ParseError),
    AllocationError(MemoryError),
    InitializeError(InterpreterResult),
}

impl From<ParseError> for ModuleLoadError {
    fn from(e: ParseError) -> Self {
        ModuleLoadError::DecodeError(e)
    }
}

impl From<MemoryError> for ModuleLoadError {
    fn from(value: MemoryError) -> Self {
        ModuleLoadError::AllocationError(value)
    }
}

fn clone_memory(memory: &Memory) -> spacewasm::Rc<Memory> {
    // Deep clone memory contents
    let mem_type = memory.mem_type();
    let mut new_memory = Memory::new(
        mem_type,
        spacewasm::Rc::new(RustSystemAllocator)
            .unwrap()
            .into_wasm_memory_allocator(),
    )
    .unwrap();

    // Grow the new memory to match the source memory size
    let current_size = memory.size();
    let initial_size = mem_type.min();

    // Only grow if the current size is larger than the initial size
    if current_size > initial_size {
        let grow_by = current_size - initial_size;
        if let Err(e) = new_memory.grow(grow_by) {
            panic!("Failed to grow cloned memory: {:?}", e);
        }
    }

    // Copy the memory contents
    if current_size > 0 {
        let size_in_bytes = (current_size as usize) * 65536;
        let data = memory.load(0, size_in_bytes).unwrap();
        new_memory.store(0, data).unwrap();
    }

    spacewasm::Rc::new(new_memory).unwrap()
}

// Clone a module with deep copies of memory and table contents
// This creates a true snapshot that can be restored after a failed module load
fn clone_module(module: &Module) -> Module {
    use spacewasm::{MemoryKind, TableKind};

    Module {
        name: module.name.clone(),
        types: module.types.clone(),
        functions: module.functions.clone(),
        table: match &module.table {
            None => None,
            Some(TableKind::Import(r)) => Some(TableKind::Import(*r)),
            Some(TableKind::ImportHost(r)) => Some(TableKind::ImportHost(*r)),
            Some(TableKind::Owned((r, ty))) => {
                // Deep clone table elements
                Some(TableKind::Owned((
                    spacewasm::Rc::new_slice(r.len(), |i| r[i]).unwrap(),
                    *ty,
                )))
            }
        },
        memory: match &module.memory {
            None => None,
            Some(MemoryKind::Import(r)) => Some(MemoryKind::Import(*r)),
            Some(MemoryKind::ImportHost(r)) => Some(MemoryKind::ImportHost(*r)),
            Some(MemoryKind::Owned(r)) => Some(MemoryKind::Owned(clone_memory(r))),
        },
        globals: module.globals.clone(),
        imports: module.imports.clone(),
        exports: module.exports.clone(),
        start: module.start,
    }
}

// We need to add a method to Store to support pushing modules
// For now, TestContext will manage store cloning by saving/restoring the entire Store

fn load_module(
    ctx: &mut TestContext,
    module_name: Option<String>,
    wasm_bytes: &[u8],
) -> Result<(), ModuleLoadError> {
    // Remove the last module if it has an empty name (unreferenceable)
    // This prevents hitting the 256 module limit in long test suites
    // We can only remove the last module to maintain index-based references
    {
        let modules = ctx.engine.store.modules();
        if !modules.is_empty() && modules[modules.len() - 1].name.is_empty() {
            ctx.engine.store.pop_module();
        }
    }

    // The engine persists across module loads
    // Clear the run state before invoking new functions
    ctx.engine.reset();

    // Create a ByteStream
    let mut stream = ByteStream::new(wasm_bytes);

    // Parse and validate the module
    let module = Module::new::<MAX_CONTROL_FRAMES, MAX_STACK_DEPTH>(
        module_name.as_ref().map(|f| f.as_ref()).unwrap_or(""),
        &mut stream,
        &mut ctx.engine.store,
        &mut ctx.code_builder,
        spacewasm::Rc::new(RustSystemAllocator)
            .unwrap()
            .into_wasm_memory_allocator(),
    )?;

    // Append the module and run its start function.
    let module_ref = ctx.engine.push_module(module).unwrap();
    let result = match ctx.engine.invoke_start(module_ref) {
        StartInvocation::Finished => InterpreterResult::Finished,
        StartInvocation::Trap(t) => InterpreterResult::Trap(t),
        StartInvocation::Pause => InterpreterResult::Pause,
        StartInvocation::Running => {
            Interpreter.run(ctx.code_builder.pages(), &mut ctx.engine, usize::MAX)
        }
    };
    match result {
        InterpreterResult::Finished => Ok(()),
        result => Err(ModuleLoadError::InitializeError(result)),
    }
}

fn invoke_function(
    ctx: &mut TestContext,
    module_name: &Option<String>,
    func_name: &str,
    args: &[ValueSpec],
    test_log: Rc<RefCell<LimitedVec<String>>>,
) -> Result<Option<Value>, InterpreterResult> {
    // Check if the engine is paused from a previous invocation
    if ctx.engine.host_pause_result.is_some() {
        invoke_function_resume(ctx, args, test_log)
    } else {
        // Normal invocation path
        invoke_function_normal(ctx, module_name, func_name, args, test_log)
    }
}

fn invoke_function_resume(
    ctx: &mut TestContext,
    args: &[ValueSpec],
    test_log: Rc<RefCell<LimitedVec<String>>>,
) -> Result<Option<Value>, InterpreterResult> {
    // Engine is paused, resume with the provided arguments
    let resume_value = if args.is_empty() {
        None
    } else if args.len() == 1 {
        Some(parse_value(&args[0]))
    } else {
        panic!("Resume expects exactly 0 or 1 argument, got {}", args.len());
    };

    test_log
        .borrow_mut()
        .push(format!("resume {:?}", resume_value));

    ctx.engine.resume(resume_value);

    // Continue execution from the paused state
    let test_runner: Inspector<'_, _, _, _> = Inspector {
        v: &Interpreter,
        out: test_log.clone(),
    };

    let result = test_runner.run(ctx.code_builder.pages(), &mut ctx.engine, 10000000);

    // Get the return types we saved when the function paused
    let return_types = ctx
        .paused_return_types
        .take()
        .expect("No saved return types for paused function");

    match result {
        InterpreterResult::Finished => {
            if return_types.is_empty() {
                Ok(None)
            } else if return_types.len() == 1 {
                Ok(Some(ctx.engine.result.unwrap().to_value(return_types[0])))
            } else {
                panic!("Multi-value returns not supported");
            }
        }
        InterpreterResult::OutOfFuel => panic!("Infinite loop detected"),
        err => Err(err),
    }
}

fn invoke_function_normal(
    ctx: &mut TestContext,
    module_name: &Option<String>,
    func_name: &str,
    args: &[ValueSpec],
    test_log: Rc<RefCell<LimitedVec<String>>>,
) -> Result<Option<Value>, InterpreterResult> {
    // Resolve module index by name lookup
    let module_index = if let Some(name) = module_name {
        ctx.find_module_by_name(name)
            .unwrap_or_else(|| panic!("Module '{name}' not found"))
    } else {
        ctx.current_module_index()
    };

    // Look up function metadata from the store
    let (f_ref, return_types, params) = {
        let module = ctx
            .engine
            .store
            .modules()
            .get(module_index)
            .unwrap_or_else(|| panic!("Module at index {module_index} not found"));

        // Find the exported function
        let export = module
            .exports
            .iter()
            .find(|e| e.name == func_name)
            .expect("Export not found");

        let func_idx = match &export.desc {
            ExportDesc::Func(idx) => *idx,
            _ => panic!("{} is not a function export", func_name),
        };

        // Get the function reference
        let func_ref = module
            .get_func_ref(func_idx)
            .unwrap_or_else(|| panic!("Function {} not found in exports", func_name));

        let func_ref = match func_ref {
            Ref::Module(index) => WasmRef {
                module: ModuleRef(module_index as u8),
                index,
            },
            Ref::Extern { module, index } => WasmRef { module, index },
            _ => panic!(
                "Function {} is not a function export: {:?}",
                func_name, func_ref
            ),
        };

        // Get all the immutable data we need
        let m = &ctx.engine.store.modules()[func_ref.module.0 as usize];
        let f = &m.functions[func_ref.index as usize];
        let func_type = &m.types[f.ty.0 as usize];
        let return_types = func_type.returns.clone();

        // Convert arguments
        let params: Vec<Value> = args.iter().map(parse_value).collect();

        (func_ref, return_types, params)
    };

    ctx.engine.invoke(f_ref, &params).unwrap();

    let test_runner: Inspector<'_, _, _, _> = Inspector {
        v: &Interpreter,
        out: test_log.clone(),
    };

    test_runner
        .out
        .borrow_mut()
        .push(format!("invoke {}({:?})", func_name, params));

    // Run until completion - up to 10-million instructions to catch infinite loops
    let result = test_runner.run(ctx.code_builder.pages(), &mut ctx.engine, 10000000);

    // Check the result
    match result {
        InterpreterResult::Finished => {
            if return_types.is_empty() {
                Ok(None)
            } else if return_types.len() == 1 {
                Ok(Some(ctx.engine.result.unwrap().to_value(return_types[0])))
            } else {
                panic!("Multi-value returns not supported");
            }
        }
        InterpreterResult::OutOfFuel => panic!("Infinite loop detected"),
        InterpreterResult::Pause => {
            // Save the return types so we can use them after resume
            ctx.paused_return_types = Some(return_types);
            Err(InterpreterResult::Pause)
        }
        err => Err(err),
    }
}

fn check_trap_reason(reason: TrapReason, text: &str) {
    /*
    RuntimeError::Trap(TrapError::DivideBy0) => Ok("integer divide by zero"),
        RuntimeError::Trap(TrapError::UnrepresentableResult) => Ok("integer overflow"),
        RuntimeError::Trap(TrapError::BadConversionToInteger) => {
            Ok("invalid conversion to integer")
        }
        RuntimeError::Trap(TrapError::ReachedUnreachable) => Ok("unreachable"),
        RuntimeError::Trap(TrapError::MemoryOrDataAccessOutOfBounds) => {
            Ok("out of bounds memory access")
        }
        RuntimeError::Trap(TrapError::TableOrElementAccessOutOfBounds) => {
            Ok("out of bounds table access")
        }
        RuntimeError::Trap(TrapError::UninitializedElement) => Ok("uninitialized element"),
        RuntimeError::Trap(TrapError::SignatureMismatch) => Ok("indirect call type mismatch"),
        RuntimeError::Trap(TrapError::TableAccessOutOfBounds) => Ok("undefined element"),

        RuntimeError::StackExhaustion => Ok("call stack exhausted"),
        RuntimeError::ModuleNotFound => Ok("module not found"),
        RuntimeError::FunctionNotFound => Err(WastError::UnrepresentedRuntimeError),
        RuntimeError::HostFunctionSignatureMismatch => Ok("host function signature mismatch"),

     */
    match (reason, text) {
        (TrapReason::Unreachable, "unreachable") => {}
        (TrapReason::DivideByZero, "integer divide by zero") => {}
        (TrapReason::InvalidTableIndex, "out of bounds table access") => {}
        (TrapReason::InvalidTableFunctionType, "indirect call type mismatch") => {}
        (TrapReason::MemoryOutOfBounds, "out of bounds memory access") => {}
        (TrapReason::StackOverflow, "stack overflow") => {}
        (TrapReason::InvalidTableIndex, "undefined element") => {}
        (TrapReason::UnrepresentableResult, "integer overflow") => {}
        (TrapReason::BadConversionToInteger, "invalid conversion to integer") => {}
        (TrapReason::IntegerOverflow, "integer overflow") => {}
        (TrapReason::UninitializedTableElement, "uninitialized element") => {}
        (TrapReason::StackOverflow, "call stack exhausted") => {}
        err => {
            panic!("Could not match expected trap text '{text}' with error {err:?}")
        }
    }
}

fn check_decode_error(err: ParseError, text: String) {
    match (err.err.err, text.as_str()) {
        (
            ValidationError::MalformedInteger,
            "integer too large" | "integer representation too long",
        ) => {}
        (ValidationError::MalformedMagic, "magic header not detected") => {}
        (ValidationError::MalformedVersion, "unknown binary version") => {}
        (ValidationError::ExpectedTerminal(0), "zero byte expected") => {}
        (
            ValidationError::Eof,
            "unexpected end" | "length out of bounds" | "unexpected end of section or function",
        ) => {}
        (ValidationError::TooManyLocals, "too many locals") => {}
        (ValidationError::MalformedUtf8, "malformed UTF-8 encoding") => {}
        (
            ValidationError::InvalidCodeSectionFunctionCount,
            "function and code section have inconsistent lengths",
        ) => {}
        (ValidationError::MalformedSectionSize, "section size mismatch") => {}
        (ValidationError::LocalIdxOutOfRange, "unknown local") => {}
        (ValidationError::MultipleMemories, "multiple memories") => {}
        (ValidationError::AlignmentLargerThanType, "alignment must not be larger than natural") => {
        }
        (ValidationError::TypeMismatch, "type mismatch") => {}
        (ValidationError::BlockResultTypeMismatch, "type mismatch") => {}
        (ValidationError::InvalidLabelIndex, "unknown label") => {}
        (ValidationError::MalformedSectionSize, "unexpected end") => {}
        (ValidationError::GlobalIdxOutOfRange, "unknown global") => {}
        (ValidationError::MalformedSectionId(_), "malformed section id") => {}
        (ValidationError::VecTooLong, "length out of bounds") => {}
        (ValidationError::StackUnderflow, "type mismatch") => {}
        (ValidationError::TypeIdxOutOfRange, "unknown type") => {}
        (ValidationError::FunctionResultTypeMismatch, "type mismatch") => {}
        (ValidationError::FunctionIdxOutOfRange, "unknown function") => {}
        (ValidationError::FunctionReturnsTooLarge, "invalid result arity") => {}
        (ValidationError::TableNotDefined, "unknown table") => {}
        (ValidationError::InvalidTableIndex, "malformed value type") => {}
        (ValidationError::InvalidLabelIndex, "unexpected end of section or function") => {}
        (ValidationError::MalformedValueType(_), "malformed value type") => {}
        (ValidationError::DuplicateSection(_), "unexpected content after last section") => {}
        (ValidationError::GlobalIsNotMutable, "immutable global") => {}
        (ValidationError::InvalidElementOffset, "type mismatch") => {}
        (
            ValidationError::InvalidConstantExpr(ConstantExprError::InvalidConstantInstruction),
            "constant expression required",
        ) => {}
        (ValidationError::FunctionImportOutOfRange, "unknown type") => {}
        (ValidationError::GlobalTypeMismatch, "type mismatch") => {}
        (
            ValidationError::InvalidConstantExpr(ConstantExprError::AlreadyHasValue),
            "type mismatch",
        ) => {}
        (ValidationError::InvalidConstantExpr(ConstantExprError::NoValue), "type mismatch") => {}
        (
            ValidationError::InvalidConstantExpr(ConstantExprError::InvalidGlobal),
            "unknown global",
        ) => {}
        (ValidationError::ExpectedConstOrVar(_), "malformed mutability") => {}
        (ValidationError::MemoryNotDefined, "unknown memory") => {}
        (ValidationError::InvalidMaxLimit, "size minimum must not be greater than maximum") => {}
        (ValidationError::MemoryTooLarge, "memory size must be at most 65536 pages (4GiB)") => {}
        (ValidationError::MemoryTooLarge, "memory size must be at most 4 GiB") => {}
        (ValidationError::InvalidNegativeMemOffset, "data segment does not fit") => {}
        (ValidationError::InvalidMemOffsetType, "type mismatch") => {}
        (ValidationError::InvalidStartFunctionSignature, "start function") => {}
        (ValidationError::DuplicateExportName, "duplicate export name") => {}
        (ValidationError::InvalidTableIndex, "unknown table") => {}
        (ValidationError::MemoryError(MemoryError::OutOfBounds), "data segment does not fit") => {}
        (ValidationError::InvalidMemIndex, "unknown memory") => {}
        (ValidationError::FunctionImportNotFound, "unknown import") => {}
        (ValidationError::GlobalImportNotFound, "unknown import") => {}
        (ValidationError::MemoryImportNotFound, "unknown import") => {}
        (ValidationError::FunctionImportTypeMismatch, "incompatible import type") => {}
        (ValidationError::GlobalImportTypeMismatch, "incompatible import type") => {}
        (ValidationError::MemoryImportTypeMismatch, "incompatible import type") => {}
        (ValidationError::FunctionImportNotFound, "incompatible import type") => {}
        (ValidationError::GlobalImportNotFound, "incompatible import type") => {}
        (ValidationError::MemoryImportNotFound, "incompatible import type") => {}
        (ValidationError::GlobalIsNotMutable, "incompatible import type") => {}
        (ValidationError::InvalidElementOutOfBounds, "elements segment does not fit") => {}
        (ValidationError::InvalidElementOffset, "elements segment does not fit") => {}
        (ValidationError::MultipleTables, "multiple tables") => {}
        (ValidationError::TableImportNotFound, "unknown import") => {}
        (ValidationError::TableImportIncompatibleSize, "incompatible import type") => {}
        (ValidationError::TableImportTypeMismatch, "incompatible import type") => {}
        (ValidationError::TableImportNotFound, "incompatible import type") => {}
        (ValidationError::MemoryImportTooLarge, "incompatible import type") => {}
        (ValidationError::InvalidPageSize(_), "invalid custom page size") => {}
        (ValidationError::GuestMemoryAllocationFailure, "allocation failed") => {}
        (ValidationError::MalformedFunction(_), "malformed function type") => {}
        (ValidationError::MalformedElemType(_), "malformed element type") => {}
        (ValidationError::MalformedLimit(_), "malformed limits flag") => {}
        (ValidationError::MalformedMemType(_), "malformed memory type") => {}
        (ValidationError::MalformedImportExportDesc(_), "malformed import kind") => {}
        (ValidationError::MalformedImportExportDesc(_), "malformed export kind") => {}
        (ValidationError::InvalidSectionOrdering(_, _), "unexpected section order") => {}
        err => {
            panic!("Could not match validation error text '{text}' with error {err:?}")
        }
    }
}

fn check_initialization_error(result: InterpreterResult, text: &str) {
    match (result, text) {
        (InterpreterResult::Trap(TrapReason::Unreachable), "unreachable") => {}
        (InterpreterResult::Trap(TrapReason::StackOverflow), "stack overflow") => {}
        (result, text) => {
            panic!("Could not match initialization error text '{text}' with result {result:?}")
        }
    }
}

// Simple temp directory that cleans up on drop
struct TempDir {
    path: PathBuf,
}

impl TempDir {
    fn new() -> std::io::Result<Self> {
        static COUNTER: AtomicU64 = AtomicU64::new(0);
        let pid = std::process::id();
        let count = COUNTER.fetch_add(1, Ordering::SeqCst);
        let dir_name = format!("spacewasm-test-{}-{}", pid, count);
        let path = std::env::temp_dir().join(dir_name);
        std::fs::create_dir(&path)?;
        Ok(TempDir { path })
    }

    fn path(&self) -> &Path {
        &self.path
    }
}

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.path);
    }
}

/// The standard `spectest` host module required by most of the spec test
/// suite (print functions, well-known globals, a memory and a table).
pub fn spectest_host_module() -> HostModule {
    HostModule {
        name: "spectest".into(),
        globals: vec![
            HostGlobal {
                name: "global_i32".into(),
                value: spacewasm::Box::new(StaticGlobal {
                    value: Mutex::new(Value::I32(666)),
                    ty: ValType::I32,
                })
                .unwrap()
                .into_global_value_dyn(),
            },
            HostGlobal {
                name: "global_i64".into(),
                value: spacewasm::Box::new(StaticGlobal {
                    value: Mutex::new(Value::I64(666)),
                    ty: ValType::I64,
                })
                .unwrap()
                .into_global_value_dyn(),
            },
            HostGlobal {
                name: "global_f32".into(),
                value: spacewasm::Box::new(StaticGlobal {
                    value: Mutex::new(Value::F32(666.6)),
                    ty: ValType::F32,
                })
                .unwrap()
                .into_global_value_dyn(),
            },
            HostGlobal {
                name: "global_f64".into(),
                value: spacewasm::Box::new(StaticGlobal {
                    value: Mutex::new(Value::F64(666.6)),
                    ty: ValType::F64,
                })
                .unwrap()
                .into_global_value_dyn(),
            },
        ],
        functions: vec![
            HostFunction::new("print", "".into(), "".into(), |_, _| {
                ControlFlow::Continue(None)
            }),
            HostFunction::new("print_i32", "i".into(), "".into(), |_, _| {
                ControlFlow::Continue(None)
            }),
            HostFunction::new("print_i64", "I".into(), "".into(), |_, _| {
                ControlFlow::Continue(None)
            }),
            HostFunction::new("print_f32", "f".into(), "".into(), |_, _| {
                ControlFlow::Continue(None)
            }),
            HostFunction::new("print_f64", "d".into(), "".into(), |_, _| {
                ControlFlow::Continue(None)
            }),
            HostFunction::new("print_i32_f32", "if".into(), "".into(), |_, _| {
                ControlFlow::Continue(None)
            }),
            HostFunction::new("print_f64_f64", "dd".into(), "".into(), |_, _| {
                ControlFlow::Continue(None)
            }),
        ],
        memory: vec![spacewasm::HostSymbol {
            name: "memory".into(),
            value: spacewasm::Rc::new(
                Memory::new(
                    spacewasm::MemType {
                        initial_pages: 1,
                        max_pages: Some(2),
                        page_size: spacewasm::MemPageSize::_65536,
                    },
                    spacewasm::Rc::new(RustSystemAllocator)
                        .unwrap()
                        .into_wasm_memory_allocator(),
                )
                .unwrap(),
            )
            .unwrap(),
        }],
        table: vec![spacewasm::HostSymbol {
            name: "table".into(),
            value: (
                spacewasm::Rc::new_slice_with_default(10).unwrap(),
                Limit {
                    min: 10,
                    max: Some(20),
                },
            ),
        }],
    }
}

fn run_wast_command(
    command: Command,
    test_dir: &Path,
    ctx: &mut TestContext,
    log: Rc<RefCell<LimitedVec<String>>>,
) {
    match command {
        Command::Module { name, filename, .. } => {
            let wasm_path = test_dir.join(&filename);
            let wasm_bytes =
                std::fs::read(&wasm_path).unwrap_or_else(|e| panic!("Failed to read module: {e}"));
            load_module(ctx, name.clone(), &wasm_bytes).unwrap();

            // Register the instance name if provided
            if let Some(instance_name) = name {
                let module_index = ctx.current_module_index();
                ctx.instance_names.insert(instance_name, module_index);
            }
        }
        Command::AssertReturn {
            action, expected, ..
        } => {
            let result = match action {
                Action::Invoke {
                    module,
                    field,
                    args,
                } => match invoke_function(ctx, &module, &field, &args, log) {
                    Ok(val) => val,
                    Err(e) => {
                        panic!("Invoke '{field}' failed: {e:?}")
                    }
                },
                Action::Get { .. } => {
                    // Skip Get actions for now as they're not fully implemented
                    return;
                }
            };

            if expected.is_empty() {
                assert!(result.is_none(), "Expected no return value, got {result:?}");
            } else if expected.len() == 1 {
                let actual = result.unwrap_or_else(|| panic!("Expected return value, got none"));
                compare_values(actual, &expected[0]);
            } else {
                panic!("Multi-value returns not yet supported");
            }
        }
        Command::AssertUninstantiable {
            text,
            filename,
            module_type,
            ..
        } => {
            if module_type != "text" {
                let wasm_path = test_dir.join(&filename);
                let wasm_bytes = std::fs::read(&wasm_path)
                    .unwrap_or_else(|e| panic!("Failed to read module: {e}"));

                match load_module(ctx, None, &wasm_bytes) {
                    Ok(_) => {
                        panic!("Expected error when linking/initializing module");
                    }
                    Err(ModuleLoadError::InitializeError(result)) => {
                        check_initialization_error(result, &text);
                    }
                    Err(err) => {
                        panic!("Failed to decode module '{err:?}'");
                    }
                }
            }
        }
        Command::AssertTrap { action, text, .. } => match action {
            Action::Invoke {
                module,
                field,
                args,
            } => match invoke_function(ctx, &module, &field, &args, log) {
                Err(InterpreterResult::Trap(reason)) => {
                    check_trap_reason(reason, &text);
                }
                Err(InterpreterResult::Pause) => {
                    if text != "paused" {
                        panic!("Interpreter paused while expecting trap '{text}'");
                    }
                }
                Err(err) => {
                    panic!("Expected trap '{text}', got error: {err:?}")
                }
                Ok(_) => {
                    panic!("Expected trap '{text}', but execution succeeded")
                }
            },
            Action::Get { .. } => {
                panic!("Get actions not implemented yet")
            }
        },
        Command::AssertMalformed {
            filename,
            module_type,
            text,
            ..
        } => {
            // Skip text format tests as we only handle binary Wasm
            if module_type != "text" {
                let wasm_path = test_dir.join(&filename);
                let wasm_bytes = std::fs::read(&wasm_path).unwrap();

                let saved_store = ctx.save_store();
                match load_module(ctx, None, &wasm_bytes) {
                    Err(ModuleLoadError::DecodeError(err)) => {
                        check_decode_error(err, text);
                        ctx.restore_store(saved_store);
                    }
                    _ => {
                        ctx.restore_store(saved_store);
                        panic!("Expected error when decoding module");
                    }
                }
            }
        }
        Command::AssertInvalid {
            filename,
            module_type,
            text,
            ..
        }
        | Command::AssertUnlinkable {
            filename,
            module_type,
            text,
            ..
        } => {
            if module_type != "text" {
                let wasm_path = test_dir.join(&filename);
                let wasm_bytes = std::fs::read(&wasm_path)
                    .unwrap_or_else(|e| panic!("Failed to read {}: {e}", wasm_path.display()));

                let saved_store = ctx.save_store();
                match load_module(ctx, None, &wasm_bytes) {
                    Err(ModuleLoadError::DecodeError(err)) => {
                        check_decode_error(err, text);
                        ctx.restore_store(saved_store);
                    }
                    Err(ModuleLoadError::AllocationError(err)) => {
                        ctx.restore_store(saved_store);
                        panic!("Expected error when decoding module '{err:?}'");
                    }
                    _ => {
                        ctx.restore_store(saved_store);
                        panic!("Expected error when decoding module");
                    }
                }
            }
        }
        Command::AssertExhaustion { action, text, .. } => match action {
            Action::Invoke {
                module,
                field,
                args,
            } => match invoke_function(ctx, &module, &field, &args, log) {
                Err(InterpreterResult::Trap(reason)) => check_trap_reason(reason, &text),
                Err(err) => {
                    panic!("Expected exhaustion '{text}', got error: {err:?}")
                }
                Ok(_) => {
                    panic!("Expected exhaustion '{text}', but execution succeeded")
                }
            },
            Action::Get { .. } => {
                panic!("Get actions not implemented yet")
            }
        },
        Command::Register { name, as_name, .. } => {
            // Register updates the module name in the store to the alias
            let module_index = if let Some(ref module_name) = name {
                ctx.find_module_by_name(module_name)
                    .unwrap_or_else(|| panic!("Module '{module_name}' not found for registration"))
            } else {
                ctx.current_module_index()
            };

            // Update the module name in the store to the registered alias
            // This allows linking to find it by the registered name
            let module = ctx
                .engine
                .store
                .modules_mut()
                .get_mut(module_index)
                .unwrap();
            module.name = as_name.as_str().try_into().unwrap();
        }
        Command::Action { action, .. } => match action {
            Action::Invoke {
                module,
                field,
                args,
            } => {
                invoke_function(ctx, &module, &field, &args, log).unwrap();
            }
            Action::Get { .. } => {
                panic!("Get actions not implemented yet")
            }
        },
    }
}

fn run_wast_test_file_inner(
    test_dir: PathBuf,
    test_name: &str,
    host_modules: HostModuleFactory,
    wast_line: Arc<Mutex<Option<u32>>>,
    subtest_log: SubtestLogType,
) {
    let json_path = test_dir.join(format!("{}.json", test_name));

    let json_content = std::fs::read_to_string(&json_path)
        .unwrap_or_else(|e| panic!("Failed to read JSON file: {}: {e}", json_path.display()));

    let test_file: TestFile = serde_json::from_str(&json_content)
        .unwrap_or_else(|e| panic!("Failed to parse JSON file {}: {}", json_path.display(), e));

    let mut ctx = TestContext::new(host_modules);

    for command in test_file.commands {
        let test_log = Rc::new(RefCell::new(LimitedVec::<String>::new()));
        *subtest_log.lock().unwrap() = Some(test_log.clone());
        *wast_line.lock().unwrap() = match &command {
            Command::Module { line, .. }
            | Command::AssertReturn { line, .. }
            | Command::AssertTrap { line, .. }
            | Command::AssertUninstantiable { line, .. }
            | Command::AssertMalformed { line, .. }
            | Command::AssertInvalid { line, .. }
            | Command::AssertExhaustion { line, .. }
            | Command::Register { line, .. }
            | Command::Action { line, .. }
            | Command::AssertUnlinkable { line, .. } => Some(*line),
        };

        run_wast_command(command, &test_dir, &mut ctx, test_log);

        *subtest_log.lock().unwrap() = None;
        *wast_line.lock().unwrap() = None;
    }
}

/// Run a spec test file with a caller-provided set of host modules. Use this
/// for suites that depend on host modules beyond the standard `spectest` one
/// (for example the regression tests, which also need
/// [`regression_host_module`]).
pub fn run_wast_test_file(test_name: &str, host_modules: HostModuleFactory) {
    let manifest_dir = env!("CARGO_MANIFEST_DIR");
    let source_wast_path = PathBuf::from(manifest_dir)
        .join("tests")
        .join(format!("{}.wast", test_name));

    // Create a temporary directory for generated files
    let temp_dir =
        TempDir::new().unwrap_or_else(|e| panic!("Failed to create temp directory: {e}"));
    let temp_path = temp_dir.path();

    // Extract just the filename (without directory path) for the JSON output
    let test_filename = PathBuf::from(test_name)
        .file_stem()
        .unwrap()
        .to_string_lossy()
        .to_string();

    // Run wast2json to generate Wasm modules and JSON descriptor
    let output = ProcessCommand::new("wast2json")
        .arg(&source_wast_path)
        .arg("--enable-custom-page-sizes")
        .arg("-o")
        .arg(temp_path.join(format!("{}.json", test_filename)))
        .current_dir(temp_path)
        .output()
        .unwrap_or_else(|e| panic!("Failed to run wast2json: {e}"));

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        panic!("wast2json failed: {}", stderr);
    }

    let wast_line = Arc::new(Mutex::new(None));
    #[allow(clippy::arc_with_non_send_sync)]
    let subtest_log = Arc::new(Mutex::new(None));

    match catch_unwind(|| {
        run_wast_test_file_inner(
            temp_path.to_path_buf(),
            &test_filename,
            host_modules,
            wast_line.clone(),
            subtest_log.clone(),
        )
    }) {
        Ok(_) => {}
        Err(err) => {
            if let Some(log) = &*subtest_log.lock().unwrap() {
                let log_lines: Vec<String> = log.borrow().clone().into();
                if !log_lines.is_empty() {
                    eprintln!("Subtest failed, dumping invoke log");
                    for line in log_lines.iter() {
                        eprintln!("{}", line);
                    }
                    eprintln!("========")
                }
            }

            let msg = if let Some(s) = err.downcast_ref::<&'static str>() {
                s.to_string()
            } else if let Some(s) = err.downcast_ref::<String>() {
                s.clone()
            } else {
                "Unknown panic payload".to_string()
            };

            if let Some(line_no) = *wast_line.lock().unwrap() {
                panic!("{}:{}: {}", source_wast_path.display(), line_no, msg)
            } else {
                panic!("{}: {}", source_wast_path.display(), msg)
            }
        }
    }
}