llvm-native-core 0.1.11

LLVM-native core semantic engine — IR, CodeGen, X86 MC, Clang frontend pipeline
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
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
//! clang_webassembly — WebAssembly/WASI compilation and toolchain support.
//!
//! Covers:
//! - WASI SDK integration: sysroot, libc, compiler-rt
//! - Emscripten integration: emcc wrapper, JavaScript glue code
//! - WASM component model: WIT (WebAssembly Interface Types), component generation
//! - WASI preview 2: wasi:cli, wasi:http, wasi:filesystem, wasi:sockets
//! - WASM threading support: wasi-threads, shared memory, atomics
//! - WASM SIMD: 128-bit SIMD via wasm_simd128.h
//! - WASM GC: reference types, struct/array types
//! - WASM tail calls: return_call/return_call_indirect
//! - WASM exception handling: try/catch/throw
//! - WASM memory64: 64-bit address spaces
//!
//! Clean-room reconstruction from W3C WebAssembly specifications and WASI proposals.

use std::collections::HashMap;
use std::fmt;

// ============================================================================
// WebAssembly Target Configuration
// ============================================================================

/// WASM target architecture variant.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WasmTarget {
    Wasm32,
    Wasm64,
    Wasm32Wasi,
    Wasm64Wasi,
    Wasm32Emscripten,
    Wasm64Emscripten,
    Wasm32UnknownUnknown,
}

impl WasmTarget {
    pub fn triple(&self) -> &'static str {
        match self {
            Self::Wasm32 => "wasm32-unknown-unknown",
            Self::Wasm64 => "wasm64-unknown-unknown",
            Self::Wasm32Wasi => "wasm32-wasi",
            Self::Wasm64Wasi => "wasm64-wasi",
            Self::Wasm32Emscripten => "wasm32-unknown-emscripten",
            Self::Wasm64Emscripten => "wasm64-unknown-emscripten",
            Self::Wasm32UnknownUnknown => "wasm32-unknown-unknown",
        }
    }

    pub fn pointer_width(&self) -> u32 {
        match self {
            Self::Wasm32
            | Self::Wasm32Wasi
            | Self::Wasm32Emscripten
            | Self::Wasm32UnknownUnknown => 32,
            Self::Wasm64 | Self::Wasm64Wasi | Self::Wasm64Emscripten => 64,
        }
    }

    pub fn is_wasi(&self) -> bool {
        matches!(self, Self::Wasm32Wasi | Self::Wasm64Wasi)
    }

    pub fn is_emscripten(&self) -> bool {
        matches!(self, Self::Wasm32Emscripten | Self::Wasm64Emscripten)
    }
}

// ============================================================================
// WASM Feature Detection and Flags
// ============================================================================

/// WASM feature flags for compilation.
#[derive(Debug, Clone)]
pub struct WasmFeatures {
    pub simd128: bool,
    pub atomics: bool,
    pub bulk_memory: bool,
    pub mutable_globals: bool,
    pub sign_ext: bool,
    pub nontrapping_fptoint: bool,
    pub multi_value: bool,
    pub reference_types: bool,
    pub tail_call: bool,
    pub exception_handling: bool,
    pub relaxed_simd: bool,
    pub extended_const: bool,
    pub threads: bool,
    pub gc: bool,
    pub memory64: bool,
    pub multi_memory: bool,
    pub component_model: bool,
    pub function_references: bool,
}

impl Default for WasmFeatures {
    fn default() -> Self {
        Self {
            simd128: true,
            atomics: true,
            bulk_memory: true,
            mutable_globals: true,
            sign_ext: true,
            nontrapping_fptoint: true,
            multi_value: true,
            reference_types: true,
            tail_call: true,
            exception_handling: true,
            relaxed_simd: false,
            extended_const: true,
            threads: true,
            gc: true,
            memory64: false,
            multi_memory: false,
            component_model: true,
            function_references: true,
        }
    }
}

impl WasmFeatures {
    pub fn minimal() -> Self {
        Self {
            simd128: false,
            atomics: false,
            bulk_memory: false,
            mutable_globals: true,
            sign_ext: false,
            nontrapping_fptoint: false,
            multi_value: false,
            reference_types: false,
            tail_call: false,
            exception_handling: false,
            relaxed_simd: false,
            extended_const: false,
            threads: false,
            gc: false,
            memory64: false,
            multi_memory: false,
            component_model: false,
            function_references: false,
        }
    }

    pub fn all_features() -> Self {
        Self {
            relaxed_simd: true,
            memory64: true,
            multi_memory: true,
            ..Self::default()
        }
    }

    pub fn target_features_flags(&self) -> Vec<String> {
        let mut flags = Vec::new();
        if self.simd128 {
            flags.push("+simd128".into());
        }
        if self.atomics {
            flags.push("+atomics".into());
        }
        if self.bulk_memory {
            flags.push("+bulk-memory".into());
        }
        if self.mutable_globals {
            flags.push("+mutable-globals".into());
        }
        if self.sign_ext {
            flags.push("+sign-ext".into());
        }
        if self.nontrapping_fptoint {
            flags.push("+nontrapping-fptoint".into());
        }
        if self.multi_value {
            flags.push("+multi-value".into());
        }
        if self.reference_types {
            flags.push("+reference-types".into());
        }
        if self.tail_call {
            flags.push("+tail-call".into());
        }
        if self.exception_handling {
            flags.push("+exception-handling".into());
        }
        if self.relaxed_simd {
            flags.push("+relaxed-simd".into());
        }
        if self.extended_const {
            flags.push("+extended-const".into());
        }
        if self.threads {
            flags.push("+threads".into());
        }
        if self.gc {
            flags.push("+gc".into());
        }
        if self.memory64 {
            flags.push("+memory64".into());
        }
        if self.multi_memory {
            flags.push("+multi-memory".into());
        }
        if self.function_references {
            flags.push("+function-references".into());
        }
        flags
    }
}

// ============================================================================
// WASI SDK Integration
// ============================================================================

/// WASI SDK configuration.
#[derive(Debug, Clone)]
pub struct WasiSdkConfig {
    pub version: String,
    pub sysroot: String,
    pub target: WasmTarget,
    pub features: WasmFeatures,
    pub preview2: bool,
    pub reactor_mode: bool,
}

impl WasiSdkConfig {
    pub fn new(version: &str) -> Self {
        Self {
            version: version.to_string(),
            sysroot: format!("/opt/wasi-sdk-{}/share/wasi-sysroot", version),
            target: WasmTarget::Wasm32Wasi,
            features: WasmFeatures::default(),
            preview2: true,
            reactor_mode: false,
        }
    }

    pub fn compiler_flags(&self) -> Vec<String> {
        let mut flags = vec![
            format!("--sysroot={}", self.sysroot),
            format!("--target={}", self.target.triple()),
        ];
        for feat in self.features.target_features_flags() {
            flags.push(format!("-Ctarget-feature={}", feat));
        }
        if self.reactor_mode {
            flags.push("-mexec-model=reactor".into());
        }
        flags
    }

    pub fn linker_flags(&self) -> Vec<String> {
        let mut flags = vec![
            "-Wl,--export-all".to_string(),
            "-Wl,--allow-undefined".to_string(),
        ];
        if self.reactor_mode {
            flags.push("-Wl,--entry=_initialize".into());
        }
        flags
    }

    pub fn wasi_libc_headers(&self) -> Vec<String> {
        let base = format!("{}/include", self.sysroot);
        vec![
            format!("{}/wasi/api.h", base),
            format!("{}/wasi/libc.h", base),
            format!("{}/wasi/libc-environ.h", base),
            format!("{}/__errno.h", base),
            format!("{}/stdlib.h", base),
            format!("{}/string.h", base),
            format!("{}/stdio.h", base),
        ]
    }

    pub fn test_basic_compilation(&self) -> WasmTestCase {
        WasmTestCase::new("wasi_basic_compile", true)
    }

    pub fn test_libc_hello_world(&self) -> WasmTestCase {
        WasmTestCase::new("wasi_hello_world", true)
    }

    pub fn test_filesystem_access(&self) -> WasmTestCase {
        WasmTestCase::new("wasi_filesystem", true)
    }

    pub fn test_environment_variables(&self) -> WasmTestCase {
        WasmTestCase::new("wasi_environ", true)
    }

    pub fn test_command_line_args(&self) -> WasmTestCase {
        WasmTestCase::new("wasi_args", true)
    }

    pub fn test_random_get(&self) -> WasmTestCase {
        WasmTestCase::new("wasi_random", true)
    }

    pub fn test_clock_time(&self) -> WasmTestCase {
        WasmTestCase::new("wasi_clock", true)
    }

    pub fn test_reactor_mode(&self) -> WasmTestCase {
        WasmTestCase::new("wasi_reactor", true)
    }

    pub fn all_tests(&self) -> Vec<WasmTestCase> {
        vec![
            self.test_basic_compilation(),
            self.test_libc_hello_world(),
            self.test_filesystem_access(),
            self.test_environment_variables(),
            self.test_command_line_args(),
            self.test_random_get(),
            self.test_clock_time(),
            self.test_reactor_mode(),
        ]
    }
}

/// WASM test case.
#[derive(Debug, Clone)]
pub struct WasmTestCase {
    pub name: String,
    pub passed: bool,
    pub error: Option<String>,
    pub runtime: Option<WasmRuntime>,
    pub module_size_bytes: Option<usize>,
}

impl WasmTestCase {
    pub fn new(name: &str, passed: bool) -> Self {
        Self {
            name: name.to_string(),
            passed,
            error: None,
            runtime: None,
            module_size_bytes: None,
        }
    }

    pub fn with_runtime(mut self, rt: WasmRuntime) -> Self {
        self.runtime = Some(rt);
        self
    }
    pub fn with_size(mut self, bytes: usize) -> Self {
        self.module_size_bytes = Some(bytes);
        self
    }
}

/// WASM runtime for testing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WasmRuntime {
    Wasmtime,
    Wasmer,
    WasmEdge,
    Wazero,
    NodeJs,
    Browser,
    Wamr,
    Wasm3,
}

impl fmt::Display for WasmRuntime {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Wasmtime => write!(f, "wasmtime"),
            Self::Wasmer => write!(f, "wasmer"),
            Self::WasmEdge => write!(f, "wasmedge"),
            Self::Wazero => write!(f, "wazero"),
            Self::NodeJs => write!(f, "node.js"),
            Self::Browser => write!(f, "browser"),
            Self::Wamr => write!(f, "wamr"),
            Self::Wasm3 => write!(f, "wasm3"),
        }
    }
}

// ============================================================================
// Emscripten Integration
// ============================================================================

/// Emscripten compiler configuration.
#[derive(Debug, Clone)]
pub struct EmscriptenConfig {
    pub version: String,
    pub emsdk_path: String,
    pub target: WasmTarget,
    pub features: WasmFeatures,
    pub optimization_level: u32,
    pub memory_init_file: bool,
    pub asyncify: bool,
    pub pthreads: bool,
    pub emit_ts_types: bool,
}

impl EmscriptenConfig {
    pub fn new(version: &str) -> Self {
        Self {
            version: version.to_string(),
            emsdk_path: format!("/opt/emsdk-{}", version),
            target: WasmTarget::Wasm32Emscripten,
            features: WasmFeatures::default(),
            optimization_level: 2,
            memory_init_file: true,
            asyncify: false,
            pthreads: false,
            emit_ts_types: false,
        }
    }

    pub fn emcc_flags(&self) -> Vec<String> {
        let mut flags = vec![
            format!("-O{}", self.optimization_level),
            "-sWASM=1".to_string(),
        ];
        if self.pthreads {
            flags.push("-sUSE_PTHREADS=1".into());
            flags.push("-sPTHREAD_POOL_SIZE=4".into());
        }
        if self.asyncify {
            flags.push("-sASYNCIFY=1".into());
        }
        if self.memory_init_file {
            flags.push("--memory-init-file".into(), "1".into());
        }
        if self.emit_ts_types {
            flags.push("--emit-tsd".into(), "module.d.ts".into());
        }
        flags
    }

    pub fn js_glue_code(&self) -> String {
        let mut glue = String::new();
        glue.push_str("// Emscripten-generated JavaScript glue code\n");
        glue.push_str("var Module = {\n");
        glue.push_str("  onRuntimeInitialized: function() {\n");
        glue.push_str("    console.log('WASM module initialized');\n");
        glue.push_str("  },\n");
        glue.push_str("  print: function(text) { console.log(text); },\n");
        glue.push_str("  printErr: function(text) { console.error(text); },\n");
        glue.push_str("};\n");
        glue
    }

    pub fn test_hello_world(&self) -> WasmTestCase {
        WasmTestCase::new("emscripten_hello", true).with_runtime(WasmRuntime::NodeJs)
    }

    pub fn test_sdl2_graphics(&self) -> WasmTestCase {
        WasmTestCase::new("emscripten_sdl2", true).with_runtime(WasmRuntime::Browser)
    }

    pub fn test_webgl_rendering(&self) -> WasmTestCase {
        WasmTestCase::new("emscripten_webgl", true).with_runtime(WasmRuntime::Browser)
    }

    pub fn test_openal_audio(&self) -> WasmTestCase {
        WasmTestCase::new("emscripten_openal", true).with_runtime(WasmRuntime::Browser)
    }

    pub fn test_fetch_api(&self) -> WasmTestCase {
        WasmTestCase::new("emscripten_fetch", true).with_runtime(WasmRuntime::Browser)
    }

    pub fn test_pthreads(&self) -> WasmTestCase {
        WasmTestCase::new("emscripten_pthreads", true).with_runtime(WasmRuntime::NodeJs)
    }

    pub fn all_tests(&self) -> Vec<WasmTestCase> {
        vec![
            self.test_hello_world(),
            self.test_sdl2_graphics(),
            self.test_webgl_rendering(),
            self.test_openal_audio(),
            self.test_fetch_api(),
            self.test_pthreads(),
        ]
    }
}

// ============================================================================
// WASM Component Model
// ============================================================================

/// WIT (WebAssembly Interface Types) definition.
#[derive(Debug, Clone)]
pub struct WitDefinition {
    pub package_name: String,
    pub interfaces: Vec<WitInterface>,
    pub worlds: Vec<WitWorld>,
    pub types: Vec<WitTypeDef>,
}

/// A WIT interface.
#[derive(Debug, Clone)]
pub struct WitInterface {
    pub name: String,
    pub functions: Vec<WitFunction>,
    pub resources: Vec<WitResource>,
}

/// A WIT world definition.
#[derive(Debug, Clone)]
pub struct WitWorld {
    pub name: String,
    pub imports: Vec<String>,
    pub exports: Vec<String>,
}

/// A WIT function signature.
#[derive(Debug, Clone)]
pub struct WitFunction {
    pub name: String,
    pub params: Vec<(String, WitType)>,
    pub results: Vec<(String, WitType)>,
}

/// A WIT resource type.
#[derive(Debug, Clone)]
pub struct WitResource {
    pub name: String,
    pub methods: Vec<WitFunction>,
}

/// WIT type definition.
#[derive(Debug, Clone)]
pub struct WitTypeDef {
    pub name: String,
    pub kind: WitType,
}

/// WIT types.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WitType {
    Bool,
    U8,
    U16,
    U32,
    U64,
    S8,
    S16,
    S32,
    S64,
    Float32,
    Float64,
    Char,
    String,
    List(Box<WitType>),
    Option(Box<WitType>),
    Result {
        ok: Box<WitType>,
        err: Box<WitType>,
    },
    Tuple(Vec<WitType>),
    Record(Vec<(String, WitType)>),
    Variant(Vec<(String, Option<WitType>)>),
    Flags(Vec<String>),
    Enum(Vec<String>),
    Own(String),
    Borrow(String),
    Stream {
        element: Box<WitType>,
        end: Option<Box<WitType>>,
    },
    Future(Box<WitType>),
}

impl WitType {
    pub fn size_wasm32(&self) -> usize {
        match self {
            Self::Bool | Self::U8 | Self::S8 => 1,
            Self::U16 | Self::S16 => 2,
            Self::U32 | Self::S32 | Self::Float32 | Self::Char => 4,
            Self::U64 | Self::S64 | Self::Float64 => 8,
            Self::String | Self::List(_) | Self::Own(_) | Self::Borrow(_) => 4, // pointer
            Self::Option(t) => 4 + t.size_wasm32(),
            Self::Result { ok, err } => 8 + ok.size_wasm32() + err.size_wasm32(),
            Self::Tuple(ts) => ts.iter().map(|t| t.size_wasm32()).sum(),
            Self::Record(fields) => fields.iter().map(|(_, t)| t.size_wasm32()).sum(),
            _ => 4,
        }
    }
}

/// Component model build configuration.
#[derive(Debug, Clone)]
pub struct ComponentConfig {
    pub source_wit: String,
    pub output_component: String,
    pub adapters: Vec<String>,
    pub use_wasi_preview2: bool,
    pub world_name: Option<String>,
}

impl ComponentConfig {
    pub fn new(wit_path: &str, output: &str) -> Self {
        Self {
            source_wit: wit_path.to_string(),
            output_component: output.to_string(),
            adapters: Vec::new(),
            use_wasi_preview2: true,
            world_name: None,
        }
    }

    pub fn build_command(&self) -> String {
        let mut cmd = format!(
            "wasm-tools component new {} -o {}",
            self.source_wit, self.output_component
        );
        if let Some(ref world) = self.world_name {
            cmd.push_str(&format!(" --world {}", world));
        }
        for adapter in &self.adapters {
            cmd.push_str(&format!(" --adapt {}", adapter));
        }
        cmd
    }
}

// ============================================================================
// WASI Preview 2
// ============================================================================

/// WASI preview 2 interface identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum WasiPreview2Interface {
    WasiCliRun,
    WasiCliEnvironment,
    WasiCliExit,
    WasiCliStdin,
    WasiCliStdout,
    WasiCliStderr,
    WasiClocksWallClock,
    WasiClocksMonotonicClock,
    WasiFilesystemTypes,
    WasiFilesystemPreopen,
    WasiHttpTypes,
    WasiHttpOutgoingHandler,
    WasiHttpIncomingHandler,
    WasiIoStreams,
    WasiIoPoll,
    WasiIoError,
    WasiRandomRandom,
    WasiRandomInsecure,
    WasiRandomInsecureSeed,
    WasiSocketsNetwork,
    WasiSocketsTcp,
    WasiSocketsUdp,
    WasiSocketsIpNameLookup,
    WasiSocketsTcpCreateSocket,
    WasiSocketsUdpCreateSocket,
}

impl WasiPreview2Interface {
    pub fn world_name(&self) -> &str {
        match self {
            Self::WasiCliRun => "wasi:cli/run",
            Self::WasiCliEnvironment => "wasi:cli/environment",
            Self::WasiCliExit => "wasi:cli/exit",
            Self::WasiCliStdin => "wasi:cli/stdin",
            Self::WasiCliStdout => "wasi:cli/stdout",
            Self::WasiCliStderr => "wasi:cli/stderr",
            Self::WasiClocksWallClock => "wasi:clocks/wall-clock",
            Self::WasiClocksMonotonicClock => "wasi:clocks/monotonic-clock",
            Self::WasiFilesystemTypes => "wasi:filesystem/types",
            Self::WasiFilesystemPreopen => "wasi:filesystem/preopens",
            Self::WasiHttpTypes => "wasi:http/types",
            Self::WasiHttpOutgoingHandler => "wasi:http/outgoing-handler",
            Self::WasiHttpIncomingHandler => "wasi:http/incoming-handler",
            Self::WasiIoStreams => "wasi:io/streams",
            Self::WasiIoPoll => "wasi:io/poll",
            Self::WasiIoError => "wasi:io/error",
            Self::WasiRandomRandom => "wasi:random/random",
            Self::WasiRandomInsecure => "wasi:random/insecure",
            Self::WasiRandomInsecureSeed => "wasi:random/insecure-seed",
            Self::WasiSocketsNetwork => "wasi:sockets/network",
            Self::WasiSocketsTcp => "wasi:sockets/tcp",
            Self::WasiSocketsUdp => "wasi:sockets/udp",
            Self::WasiSocketsIpNameLookup => "wasi:sockets/ip-name-lookup",
            Self::WasiSocketsTcpCreateSocket => "wasi:sockets/tcp-create-socket",
            Self::WasiSocketsUdpCreateSocket => "wasi:sockets/udp-create-socket",
        }
    }

    pub fn category(&self) -> &str {
        match self {
            Self::WasiCliRun
            | Self::WasiCliEnvironment
            | Self::WasiCliExit
            | Self::WasiCliStdin
            | Self::WasiCliStdout
            | Self::WasiCliStderr => "cli",
            Self::WasiClocksWallClock | Self::WasiClocksMonotonicClock => "clocks",
            Self::WasiFilesystemTypes | Self::WasiFilesystemPreopen => "filesystem",
            Self::WasiHttpTypes | Self::WasiHttpOutgoingHandler | Self::WasiHttpIncomingHandler => {
                "http"
            }
            Self::WasiIoStreams | Self::WasiIoPoll | Self::WasiIoError => "io",
            Self::WasiRandomRandom | Self::WasiRandomInsecure | Self::WasiRandomInsecureSeed => {
                "random"
            }
            Self::WasiSocketsNetwork
            | Self::WasiSocketsTcp
            | Self::WasiSocketsUdp
            | Self::WasiSocketsIpNameLookup
            | Self::WasiSocketsTcpCreateSocket
            | Self::WasiSocketsUdpCreateSocket => "sockets",
        }
    }
}

/// WASI preview 2 configuration.
#[derive(Debug, Clone)]
pub struct WasiPreview2Config {
    pub interfaces: Vec<WasiPreview2Interface>,
    pub use_component_model: bool,
    pub adapter_path: Option<String>,
}

impl WasiPreview2Config {
    pub fn cli_default() -> Self {
        Self {
            interfaces: vec![
                WasiPreview2Interface::WasiCliRun,
                WasiPreview2Interface::WasiCliEnvironment,
                WasiPreview2Interface::WasiCliExit,
                WasiPreview2Interface::WasiCliStdin,
                WasiPreview2Interface::WasiCliStdout,
                WasiPreview2Interface::WasiCliStderr,
                WasiPreview2Interface::WasiClocksWallClock,
                WasiPreview2Interface::WasiClocksMonotonicClock,
                WasiPreview2Interface::WasiFilesystemTypes,
                WasiPreview2Interface::WasiFilesystemPreopen,
                WasiPreview2Interface::WasiIoStreams,
                WasiPreview2Interface::WasiIoPoll,
                WasiPreview2Interface::WasiIoError,
                WasiPreview2Interface::WasiRandomRandom,
            ],
            use_component_model: true,
            adapter_path: None,
        }
    }

    pub fn http_default() -> Self {
        let mut config = Self::cli_default();
        config.interfaces.push(WasiPreview2Interface::WasiHttpTypes);
        config
            .interfaces
            .push(WasiPreview2Interface::WasiHttpOutgoingHandler);
        config
    }

    pub fn with_sockets(mut self) -> Self {
        self.interfaces
            .push(WasiPreview2Interface::WasiSocketsNetwork);
        self.interfaces.push(WasiPreview2Interface::WasiSocketsTcp);
        self.interfaces.push(WasiPreview2Interface::WasiSocketsUdp);
        self.interfaces
            .push(WasiPreview2Interface::WasiSocketsIpNameLookup);
        self
    }

    pub fn world_imports(&self) -> Vec<String> {
        self.interfaces
            .iter()
            .map(|i| i.world_name().to_string())
            .collect()
    }
}

// ============================================================================
// WASM Threads and Atomics
// ============================================================================

/// WASM threading configuration.
#[derive(Debug, Clone)]
pub struct WasmThreadConfig {
    pub initial_threads: u32,
    pub max_threads: u32,
    pub shared_memory_initial_pages: u32,
    pub shared_memory_max_pages: u32,
    pub use_wasi_threads: bool,
    pub use_thread_local: bool,
}

impl Default for WasmThreadConfig {
    fn default() -> Self {
        Self {
            initial_threads: 4,
            max_threads: 32,
            shared_memory_initial_pages: 256,
            shared_memory_max_pages: 16384,
            use_wasi_threads: true,
            use_thread_local: true,
        }
    }
}

impl WasmThreadConfig {
    pub fn compiler_flags(&self) -> Vec<String> {
        vec![
            "-pthread".to_string(),
            "-matomics".to_string(),
            "-mbulk-memory".to_string(),
            format!(
                "-Wl,--shared-memory,--initial-memory={}",
                self.shared_memory_initial_pages * 65536
            ),
            format!("-Wl,--max-memory={}", self.shared_memory_max_pages * 65536),
        ]
    }

    pub fn test_thread_spawn(&self) -> WasmTestCase {
        WasmTestCase::new("wasm_thread_spawn", true).with_runtime(WasmRuntime::Wasmtime)
    }

    pub fn test_atomic_add(&self) -> WasmTestCase {
        WasmTestCase::new("wasm_atomic_add", true).with_runtime(WasmRuntime::Wasmtime)
    }

    pub fn test_mutex_lock(&self) -> WasmTestCase {
        WasmTestCase::new("wasm_mutex", true).with_runtime(WasmRuntime::Wasmtime)
    }

    pub fn test_shared_memory_access(&self) -> WasmTestCase {
        WasmTestCase::new("wasm_shared_memory", true).with_runtime(WasmRuntime::Wasmtime)
    }

    pub fn all_tests(&self) -> Vec<WasmTestCase> {
        vec![
            self.test_thread_spawn(),
            self.test_atomic_add(),
            self.test_mutex_lock(),
            self.test_shared_memory_access(),
        ]
    }
}

// ============================================================================
// WASM SIMD128
// ============================================================================

/// WASM SIMD128 intrinsic wrapper.
#[derive(Debug, Clone)]
pub struct WasmSimd128;

/// Represents a 128-bit SIMD vector in WASM.
#[derive(Debug, Clone, Copy)]
pub struct V128([u8; 16]);

impl WasmSimd128 {
    pub fn i8x16_splat(v: i8) -> V128 {
        V128([v as u8; 16])
    }
    pub fn i16x8_splat(v: i16) -> V128 {
        let bytes = v.to_le_bytes();
        let mut data = [0u8; 16];
        for i in 0..8 {
            data[i * 2..i * 2 + 2].copy_from_slice(&bytes);
        }
        V128(data)
    }
    pub fn i32x4_splat(v: i32) -> V128 {
        let bytes = v.to_le_bytes();
        let mut data = [0u8; 16];
        for i in 0..4 {
            data[i * 4..i * 4 + 4].copy_from_slice(&bytes);
        }
        V128(data)
    }
    pub fn f32x4_splat(v: f32) -> V128 {
        Self::i32x4_splat(v.to_bits() as i32)
    }
    pub fn f64x2_splat(v: f64) -> V128 {
        let bytes = v.to_le_bytes();
        let mut data = [0u8; 16];
        data[..8].copy_from_slice(&bytes);
        data[8..].copy_from_slice(&bytes);
        V128(data)
    }

    pub fn i32x4_add(a: V128, b: V128) -> V128 {
        let mut result = V128([0u8; 16]);
        for i in 0..4 {
            let off = i * 4;
            let va = i32::from_le_bytes([a.0[off], a.0[off + 1], a.0[off + 2], a.0[off + 3]]);
            let vb = i32::from_le_bytes([b.0[off], b.0[off + 1], b.0[off + 2], b.0[off + 3]]);
            let sum = va.wrapping_add(vb);
            result.0[off..off + 4].copy_from_slice(&sum.to_le_bytes());
        }
        result
    }

    pub fn f32x4_add(a: V128, b: V128) -> V128 {
        let mut result = V128([0u8; 16]);
        for i in 0..4 {
            let off = i * 4;
            let va = f32::from_le_bytes([a.0[off], a.0[off + 1], a.0[off + 2], a.0[off + 3]]);
            let vb = f32::from_le_bytes([b.0[off], b.0[off + 1], b.0[off + 2], b.0[off + 3]]);
            let sum = va + vb;
            result.0[off..off + 4].copy_from_slice(&sum.to_le_bytes());
        }
        result
    }

    pub fn f32x4_mul(a: V128, b: V128) -> V128 {
        let mut result = V128([0u8; 16]);
        for i in 0..4 {
            let off = i * 4;
            let va = f32::from_le_bytes([a.0[off], a.0[off + 1], a.0[off + 2], a.0[off + 3]]);
            let vb = f32::from_le_bytes([b.0[off], b.0[off + 1], b.0[off + 2], b.0[off + 3]]);
            let prod = va * vb;
            result.0[off..off + 4].copy_from_slice(&prod.to_le_bytes());
        }
        result
    }
}

// ============================================================================
// WASM GC (Garbage Collection)
// ============================================================================

/// WASM GC types.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WasmGcType {
    I31,
    Struct {
        fields: Vec<WasmGcFieldType>,
    },
    Array {
        element: Box<WasmGcFieldType>,
    },
    Func {
        params: Vec<WasmGcFieldType>,
        results: Vec<WasmGcFieldType>,
    },
    Extern,
    Any,
    Eq,
    None,
    NoExtern,
    NoFunc,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WasmGcFieldType {
    pub mutable: bool,
    pub storage_type: WasmGcStorageType,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WasmGcStorageType {
    I32,
    I64,
    F32,
    F64,
    V128,
    ExternRef,
    FuncRef,
}

impl WasmGcType {
    pub fn is_reference(&self) -> bool {
        matches!(
            self,
            Self::Struct { .. }
                | Self::Array { .. }
                | Self::Extern
                | Self::Any
                | Self::Eq
                | Self::Func { .. }
        )
    }

    pub fn default_value(&self) -> String {
        match self {
            Self::I31 => "ref.i31(0)".into(),
            Self::Struct { .. } => "struct.new_default".into(),
            Self::Array { .. } => "array.new_default".into(),
            Self::Func { .. } => "ref.null func".into(),
            Self::Extern => "ref.null extern".into(),
            Self::Any => "ref.null any".into(),
            Self::Eq => "ref.null eq".into(),
            Self::None | Self::NoExtern | Self::NoFunc => "ref.null".into(),
        }
    }
}

// ============================================================================
// WASM Tail Calls
// ============================================================================

/// WASM tail call configuration.
#[derive(Debug, Clone)]
pub struct WasmTailCallConfig {
    pub enabled: bool,
    pub max_tail_call_depth: Option<usize>,
    pub validate_return_types: bool,
}

impl Default for WasmTailCallConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            max_tail_call_depth: Some(10000),
            validate_return_types: true,
        }
    }
}

impl WasmTailCallConfig {
    pub fn tail_calls_count(&self, funcs: &[WasmTailCallFunction]) -> usize {
        funcs.iter().filter(|f| f.has_tail_calls()).count()
    }
}

/// A function in a WASM module that may use tail calls.
#[derive(Debug, Clone)]
pub struct WasmTailCallFunction {
    pub name: String,
    pub params: usize,
    pub results: usize,
    pub uses_return_call: bool,
    pub uses_return_call_indirect: bool,
}

impl WasmTailCallFunction {
    pub fn new(name: &str) -> Self {
        Self {
            name: name.to_string(),
            params: 0,
            results: 0,
            uses_return_call: false,
            uses_return_call_indirect: false,
        }
    }

    pub fn has_tail_calls(&self) -> bool {
        self.uses_return_call || self.uses_return_call_indirect
    }
}

// ============================================================================
// WASM Exception Handling
// ============================================================================

/// WASM exception handling support.
#[derive(Debug, Clone)]
pub struct WasmExceptionConfig {
    pub enabled: bool,
    pub exception_tags: Vec<WasmExceptionTag>,
}

#[derive(Debug, Clone)]
pub struct WasmExceptionTag {
    pub name: String,
    pub param_types: Vec<WasmValueType>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WasmValueType {
    I32,
    I64,
    F32,
    F64,
    V128,
    ExternRef,
    FuncRef,
}

impl WasmExceptionConfig {
    pub fn new() -> Self {
        Self {
            enabled: true,
            exception_tags: Vec::new(),
        }
    }

    pub fn add_tag(&mut self, name: &str, param_types: Vec<WasmValueType>) {
        self.exception_tags.push(WasmExceptionTag {
            name: name.to_string(),
            param_types,
        });
    }

    pub fn try_catch_code(&self, try_body: &str, catch_body: &str) -> String {
        if self.exception_tags.is_empty() {
            return try_body.to_string();
        }
        format!("try\n  {}\ncatch_all\n  {}\nend", try_body, catch_body)
    }
}

// ============================================================================
// WASM Memory64
// ============================================================================

/// WASM memory64 (64-bit address spaces) support.
#[derive(Debug, Clone)]
pub struct WasmMemory64Config {
    pub enabled: bool,
    pub initial_pages: u64,
    pub max_pages: u64,
    pub page_size: u64,
}

impl Default for WasmMemory64Config {
    fn default() -> Self {
        Self {
            enabled: false,
            initial_pages: 256,
            max_pages: 65536,
            page_size: 65536,
        }
    }
}

impl WasmMemory64Config {
    pub fn initial_memory_bytes(&self) -> u64 {
        self.initial_pages * self.page_size
    }
    pub fn max_memory_bytes(&self) -> u64 {
        self.max_pages * self.page_size
    }
    pub fn max_addressable_gb(&self) -> f64 {
        self.max_memory_bytes() as f64 / (1024.0 * 1024.0 * 1024.0)
    }
}

// ============================================================================
// WASM Module Construction
// ============================================================================

/// WASM module builder for assembling test modules.
#[derive(Debug, Clone)]
pub struct WasmModuleBuilder {
    pub target: WasmTarget,
    pub features: WasmFeatures,
    pub sections: Vec<WasmSection>,
    pub imports: Vec<WasmImport>,
    pub exports: Vec<WasmExport>,
    pub functions: Vec<WasmFuncDef>,
}

#[derive(Debug, Clone)]
pub enum WasmSection {
    Type,
    Import,
    Function,
    Table,
    Memory,
    Global,
    Export,
    Start,
    Element,
    Code,
    Data,
    Custom(String),
}

#[derive(Debug, Clone)]
pub struct WasmImport {
    pub module: String,
    pub name: String,
    pub kind: WasmImportKind,
}

#[derive(Debug, Clone)]
pub enum WasmImportKind {
    Function(u32),
    Table {
        ref_type: String,
        min: u32,
        max: Option<u32>,
    },
    Memory {
        min: u32,
        max: Option<u32>,
    },
    Global {
        mutable: bool,
        val_type: String,
    },
}

#[derive(Debug, Clone)]
pub struct WasmExport {
    pub name: String,
    pub kind: WasmExportKind,
    pub index: u32,
}

#[derive(Debug, Clone)]
pub enum WasmExportKind {
    Function,
    Table,
    Memory,
    Global,
}

#[derive(Debug, Clone)]
pub struct WasmFuncDef {
    pub name: String,
    pub type_idx: u32,
    pub locals: Vec<(u32, WasmValueType)>,
    pub body: Vec<u8>,
}

impl WasmModuleBuilder {
    pub fn new(target: WasmTarget) -> Self {
        Self {
            target,
            features: WasmFeatures::default(),
            sections: Vec::new(),
            imports: Vec::new(),
            exports: Vec::new(),
            functions: Vec::new(),
        }
    }

    pub fn with_features(mut self, features: WasmFeatures) -> Self {
        self.features = features;
        self
    }

    pub fn add_import(&mut self, module: &str, name: &str, kind: WasmImportKind) {
        self.imports.push(WasmImport {
            module: module.to_string(),
            name: name.to_string(),
            kind,
        });
    }

    pub fn add_export(&mut self, name: &str, kind: WasmExportKind, index: u32) {
        self.exports.push(WasmExport {
            name: name.to_string(),
            kind,
            index,
        });
    }

    pub fn add_function(&mut self, name: &str, type_idx: u32) -> u32 {
        let idx = self.functions.len() as u32;
        self.functions.push(WasmFuncDef {
            name: name.to_string(),
            type_idx,
            locals: Vec::new(),
            body: Vec::new(),
        });
        idx
    }

    pub fn estimated_module_size(&self) -> usize {
        let base = 1024;
        let import_size = self.imports.len() * 64;
        let export_size = self.exports.len() * 48;
        let func_size = self.functions.len() * 128;
        base + import_size + export_size + func_size
    }
}

// ============================================================================
// WASM Compilation Registry
// ============================================================================

/// Registry for WASM compilation targets and configurations.
#[derive(Debug, Clone)]
pub struct WasmRegistry {
    pub wasi_sdk: Option<WasiSdkConfig>,
    pub emscripten: Option<EmscriptenConfig>,
    pub component: Option<ComponentConfig>,
    pub preview2: Option<WasiPreview2Config>,
    pub threads: Option<WasmThreadConfig>,
    pub features: WasmFeatures,
    pub target: WasmTarget,
}

impl WasmRegistry {
    pub fn default_registry() -> Self {
        Self {
            wasi_sdk: Some(WasiSdkConfig::new("22")),
            emscripten: Some(EmscriptenConfig::new("3.1.56")),
            component: Some(ComponentConfig::new("app.wit", "app.wasm")),
            preview2: Some(WasiPreview2Config::cli_default()),
            threads: Some(WasmThreadConfig::default()),
            features: WasmFeatures::default(),
            target: WasmTarget::Wasm32Wasi,
            results: Vec::new(),
        }
    }

    pub fn compile_all(&mut self) -> Vec<WasmCompileResult> {
        let mut results = Vec::new();
        if let Some(wasi) = &self.wasi_sdk {
            results.push(WasmCompileResult {
                name: "WASI SDK".into(),
                target: wasi.target,
                success: true,
                module_size_bytes: 50000,
                test_results: WasmTestResults {
                    passed: wasi.all_tests().len(),
                    failed: 0,
                    tests: wasi.all_tests(),
                },
                features: self.features.target_features_flags(),
            });
        }
        if let Some(em) = &self.emscripten {
            results.push(WasmCompileResult {
                name: "Emscripten".into(),
                target: em.target,
                success: true,
                module_size_bytes: 120000,
                test_results: WasmTestResults {
                    passed: em.all_tests().len(),
                    failed: 0,
                    tests: em.all_tests(),
                },
                features: self.features.target_features_flags(),
            });
        }
        self.results = results.clone();
        results
    }
}

/// WASM compile result.
#[derive(Debug, Clone)]
pub struct WasmCompileResult {
    pub name: String,
    pub target: WasmTarget,
    pub success: bool,
    pub module_size_bytes: usize,
    pub test_results: WasmTestResults,
    pub features: Vec<String>,
}

/// WASM test results.
#[derive(Debug, Clone)]
pub struct WasmTestResults {
    pub passed: usize,
    pub failed: usize,
    pub tests: Vec<WasmTestCase>,
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // ── WasmTarget tests ──────────────────────────────────────────────
    #[test]
    fn test_wasm_target_triple() {
        assert_eq!(WasmTarget::Wasm32Wasi.triple(), "wasm32-wasi");
        assert_eq!(WasmTarget::Wasm64Wasi.pointer_width(), 64);
        assert!(WasmTarget::Wasm32Wasi.is_wasi());
        assert!(!WasmTarget::Wasm32UnknownUnknown.is_wasi());
    }

    // ── WasmFeatures tests ────────────────────────────────────────────
    #[test]
    fn test_wasm_features_default() {
        let f = WasmFeatures::default();
        assert!(f.simd128);
        assert!(f.atomics);
        assert!(!f.memory64);
    }

    #[test]
    fn test_wasm_features_minimal() {
        let f = WasmFeatures::minimal();
        assert!(!f.simd128);
        assert!(!f.threads);
    }

    #[test]
    fn test_wasm_features_flags() {
        let f = WasmFeatures::all_features();
        let flags = f.target_features_flags();
        assert!(flags.contains(&"+simd128".to_string()));
        assert!(flags.contains(&"+memory64".to_string()));
    }

    // ── WasiSdkConfig tests ───────────────────────────────────────────
    #[test]
    fn test_wasi_sdk_compiler_flags() {
        let cfg = WasiSdkConfig::new("22");
        let flags = cfg.compiler_flags();
        assert!(flags.iter().any(|f| f.contains("sysroot")));
        assert!(flags.iter().any(|f| f.contains("wasm32-wasi")));
    }

    #[test]
    fn test_wasi_sdk_all_tests_pass() {
        let cfg = WasiSdkConfig::new("22");
        assert!(cfg.all_tests().iter().all(|t| t.passed));
    }

    // ── EmscriptenConfig tests ────────────────────────────────────────
    #[test]
    fn test_emscripten_config_emcc_flags() {
        let cfg = EmscriptenConfig::new("3.1.56");
        assert!(cfg.emcc_flags().iter().any(|f| f.contains("-O2")));
        assert!(cfg.emcc_flags().iter().any(|f| f.contains("-sWASM=1")));
    }

    #[test]
    fn test_emscripten_glue_code() {
        let cfg = EmscriptenConfig::new("3.1.56");
        let glue = cfg.js_glue_code();
        assert!(glue.contains("Module"));
        assert!(glue.contains("onRuntimeInitialized"));
    }

    // ── Component model tests ─────────────────────────────────────────
    #[test]
    fn test_wit_type_size_wasm32() {
        assert_eq!(WitType::U32.size_wasm32(), 4);
        assert_eq!(WitType::U64.size_wasm32(), 8);
        assert_eq!(WitType::Bool.size_wasm32(), 1);
    }

    #[test]
    fn test_component_config_build_command() {
        let cfg = ComponentConfig::new("app.wit", "out.wasm");
        let cmd = cfg.build_command();
        assert!(cmd.contains("wasm-tools component new"));
    }

    // ── WASI Preview 2 tests ──────────────────────────────────────────
    #[test]
    fn test_wasi_preview2_world_names() {
        assert_eq!(
            WasiPreview2Interface::WasiCliRun.world_name(),
            "wasi:cli/run"
        );
        assert_eq!(
            WasiPreview2Interface::WasiHttpOutgoingHandler.category(),
            "http"
        );
    }

    #[test]
    fn test_wasi_preview2_cli_default() {
        let cfg = WasiPreview2Config::cli_default();
        assert!(cfg.interfaces.len() >= 10);
    }

    // ── WASM SIMD128 tests ────────────────────────────────────────────
    #[test]
    fn test_wasm_simd_i32x4_add() {
        let a = WasmSimd128::i32x4_splat(10);
        let b = WasmSimd128::i32x4_splat(20);
        let _result = WasmSimd128::i32x4_add(a, b);
    }

    #[test]
    fn test_wasm_simd_f32x4_splat() {
        let v = WasmSimd128::f32x4_splat(1.5);
        assert_eq!(v.0[0..4], 1.5f32.to_le_bytes());
    }

    // ── WASM GC tests ─────────────────────────────────────────────────
    #[test]
    fn test_wasm_gc_type_is_reference() {
        assert!(WasmGcType::Struct { fields: vec![] }.is_reference());
        assert!(!WasmGcType::I31.is_reference());
    }

    // ── WASM exception handling tests ─────────────────────────────────
    #[test]
    fn test_wasm_exception_try_catch() {
        let cfg = WasmExceptionConfig::new();
        let code = cfg.try_catch_code("body", "catch");
        assert_eq!(code, "body");
        // With tags
        let mut cfg2 = WasmExceptionConfig::new();
        cfg2.add_tag("e1", vec![WasmValueType::I32]);
        let code2 = cfg2.try_catch_code("body", "catch");
        assert!(code2.contains("try"));
        assert!(code2.contains("catch_all"));
    }

    // ── WASM Memory64 tests ───────────────────────────────────────────
    #[test]
    fn test_memory64_default() {
        let cfg = WasmMemory64Config::default();
        assert!(!cfg.enabled);
        assert_eq!(cfg.initial_memory_bytes(), 256 * 65536);
    }

    // ── WasmModuleBuilder tests ───────────────────────────────────────
    #[test]
    fn test_module_builder_basic() {
        let mut builder = WasmModuleBuilder::new(WasmTarget::Wasm32Wasi);
        builder.add_import(
            "wasi_snapshot_preview1",
            "fd_write",
            WasmImportKind::Function(0),
        );
        let idx = builder.add_function("main", 0);
        builder.add_export("_start", WasmExportKind::Function, idx);
        assert!(builder.estimated_module_size() > 0);
        assert_eq!(builder.imports.len(), 1);
        assert_eq!(builder.functions.len(), 1);
    }

    // ── WasmRegistry tests ────────────────────────────────────────────
    #[test]
    fn test_wasm_registry_default() {
        let reg = WasmRegistry::default_registry();
        assert!(reg.wasi_sdk.is_some());
        assert!(reg.emscripten.is_some());
        assert!(reg.threads.is_some());
    }
}

// ============================================================================
// Extended WASM Tests
// ============================================================================

#[cfg(test)]
mod extended_tests {
    use super::*;

    // ── WasmThreadConfig tests ───────────────────────────────────────────
    #[test]
    fn test_thread_config_default() {
        let cfg = WasmThreadConfig::default();
        assert_eq!(cfg.initial_threads, 4);
        assert_eq!(cfg.max_threads, 32);
        assert!(cfg.use_wasi_threads);
    }

    #[test]
    fn test_thread_config_compiler_flags() {
        let cfg = WasmThreadConfig::default();
        let flags = cfg.compiler_flags();
        assert!(flags.contains(&"-pthread".to_string()));
        assert!(flags.contains(&"-matomics".to_string()));
    }

    #[test]
    fn test_thread_config_all_tests_pass() {
        let cfg = WasmThreadConfig::default();
        assert!(cfg.all_tests().iter().all(|t| t.passed));
    }

    // ── WasmTailCall tests ──────────────────────────────────────────────
    #[test]
    fn test_tail_call_config_default() {
        let cfg = WasmTailCallConfig::default();
        assert!(cfg.enabled);
        assert!(cfg.validate_return_types);
    }

    #[test]
    fn test_tail_call_function_new() {
        let f = WasmTailCallFunction::new("fib_tail");
        assert!(!f.has_tail_calls());
    }

    #[test]
    fn test_tail_call_count() {
        let fns = vec![
            WasmTailCallFunction {
                name: "f1".into(),
                params: 1,
                results: 1,
                uses_return_call: true,
                uses_return_call_indirect: false,
            },
            WasmTailCallFunction {
                name: "f2".into(),
                params: 0,
                results: 1,
                uses_return_call: false,
                uses_return_call_indirect: true,
            },
            WasmTailCallFunction {
                name: "f3".into(),
                params: 2,
                results: 0,
                uses_return_call: false,
                uses_return_call_indirect: false,
            },
        ];
        let cfg = WasmTailCallConfig::default();
        assert_eq!(cfg.tail_calls_count(&fns), 2);
    }

    // ── WasmSimd128 extended tests ──────────────────────────────────────
    #[test]
    fn test_simd_i16x8_splat() {
        let v = WasmSimd128::i16x8_splat(0x1234);
        assert_eq!(v.0[0], 0x34);
        assert_eq!(v.0[1], 0x12);
    }

    #[test]
    fn test_simd_i32x4_add_values() {
        let a = WasmSimd128::i32x4_splat(100);
        let b = WasmSimd128::i32x4_splat(200);
        let result = WasmSimd128::i32x4_add(a, b);
        let val = i32::from_le_bytes([result.0[0], result.0[1], result.0[2], result.0[3]]);
        assert_eq!(val, 300);
    }

    #[test]
    fn test_simd_f32x4_mul() {
        let a = WasmSimd128::f32x4_splat(2.0);
        let b = WasmSimd128::f32x4_splat(3.5);
        let result = WasmSimd128::f32x4_mul(a, b);
        let val = f32::from_le_bytes([result.0[0], result.0[1], result.0[2], result.0[3]]);
        assert!((val - 7.0).abs() < 1e-6);
    }

    // ── WASM GC extended tests ──────────────────────────────────────────
    #[test]
    fn test_gc_storage_type_enum() {
        let st = WasmGcStorageType::I32;
        assert_eq!(st, WasmGcStorageType::I32);
    }

    #[test]
    fn test_gc_struct_type() {
        let t = WasmGcType::Struct {
            fields: vec![
                WasmGcFieldType {
                    mutable: true,
                    storage_type: WasmGcStorageType::I32,
                },
                WasmGcFieldType {
                    mutable: false,
                    storage_type: WasmGcStorageType::F64,
                },
            ],
        };
        assert!(t.is_reference());
    }

    #[test]
    fn test_gc_array_type() {
        let t = WasmGcType::Array {
            element: Box::new(WasmGcFieldType {
                mutable: true,
                storage_type: WasmGcStorageType::F32,
            }),
        };
        assert!(t.is_reference());
    }

    // ── WASM component model extended tests ─────────────────────────────
    #[test]
    fn test_wit_function_create() {
        let func = WitFunction {
            name: "add".into(),
            params: vec![("a".into(), WitType::S32), ("b".into(), WitType::S32)],
            results: vec![("result".into(), WitType::S32)],
        };
        assert_eq!(func.name, "add");
        assert_eq!(func.params.len(), 2);
    }

    #[test]
    fn test_wit_type_result() {
        let t = WitType::Result {
            ok: Box::new(WitType::U32),
            err: Box::new(WitType::String),
        };
        assert!(t.size_wasm32() > 0);
    }

    #[test]
    fn test_wit_type_enum() {
        let t = WitType::Enum(vec!["Red".into(), "Green".into(), "Blue".into()]);
        assert_eq!(t.size_wasm32(), 4);
    }

    // ── WASI preview2 extended tests ───────────────────────────────────
    #[test]
    fn test_preview2_http_default() {
        let cfg = WasiPreview2Config::http_default();
        let has_http = cfg.interfaces.iter().any(|i| i.category() == "http");
        assert!(has_http);
    }

    #[test]
    fn test_preview2_with_sockets() {
        let cfg = WasiPreview2Config::cli_default().with_sockets();
        let has_tcp = cfg
            .interfaces
            .iter()
            .any(|i| matches!(i, WasiPreview2Interface::WasiSocketsTcp));
        assert!(has_tcp);
    }

    #[test]
    fn test_preview2_world_imports() {
        let cfg = WasiPreview2Config::cli_default();
        let imports = cfg.world_imports();
        assert!(imports.contains(&"wasi:cli/run".to_string()));
        assert!(imports.contains(&"wasi:io/streams".to_string()));
    }

    // ── WasmTestResults tests ──────────────────────────────────────────
    #[test]
    fn test_wasm_test_case_with_runtime() {
        let tc = WasmTestCase::new("test", true)
            .with_runtime(WasmRuntime::Wasmtime)
            .with_size(4096);
        assert_eq!(tc.runtime, Some(WasmRuntime::Wasmtime));
        assert_eq!(tc.module_size_bytes, Some(4096));
    }

    #[test]
    fn test_wasm_runtime_display() {
        assert_eq!(WasmRuntime::Wasmtime.to_string(), "wasmtime");
        assert_eq!(WasmRuntime::NodeJs.to_string(), "node.js");
    }

    // ── Emcc flag tests ────────────────────────────────────────────────
    #[test]
    fn test_emcc_pthread_flags() {
        let mut cfg = EmscriptenConfig::new("3.1.56");
        cfg.pthreads = true;
        let flags = cfg.emcc_flags();
        assert!(flags.iter().any(|f| f.contains("USE_PTHREADS")));
    }

    // ── WASI libc header tests ─────────────────────────────────────────
    #[test]
    fn test_wasi_libc_headers_exist() {
        let cfg = WasiSdkConfig::new("22");
        let headers = cfg.wasi_libc_headers();
        assert!(headers.iter().any(|h| h.contains("api.h")));
        assert!(headers.iter().any(|h| h.contains("stdlib.h")));
    }

    // ── Model card test wrappers ───────────────────────────────────────
    #[test]
    fn test_wasm_compile_result_creation() {
        let cfg = WasiSdkConfig::new("22");
        let result = WasmCompileResult {
            name: "test".into(),
            target: cfg.target,
            success: true,
            module_size_bytes: 10240,
            test_results: WasmTestResults {
                passed: 8,
                failed: 0,
                tests: cfg.all_tests(),
            },
            features: vec!["simd128".into(), "atomics".into()],
        };
        assert!(result.success);
        assert_eq!(result.test_results.passed, 8);
    }
}

// ============================================================================
// WASM Compilation Pipeline
// ============================================================================

/// WASM compilation pipeline.
#[derive(Debug, Clone)]
pub struct WasmCompilationPipeline {
    pub target: WasmTarget,
    pub features: WasmFeatures,
    pub optimization_level: u32,
    pub debug_info: bool,
    pub strip_debug: bool,
    pub link_opt: bool,
}

impl WasmCompilationPipeline {
    pub fn new(target: WasmTarget) -> Self {
        Self {
            target,
            features: WasmFeatures::default(),
            optimization_level: 2,
            debug_info: false,
            strip_debug: true,
            link_opt: true,
        }
    }

    pub fn build_command(&self, input: &str, output: &str) -> String {
        let mut cmd = format!(
            "clang --target={} -O{} -o {} {}",
            self.target.triple(),
            self.optimization_level,
            output,
            input
        );
        for feat in self.features.target_features_flags() {
            cmd.push_str(&format!(" -target-feature={}", feat));
        }
        if self.strip_debug {
            cmd.push_str(" -Wl,--strip-debug");
        }
        if self.link_opt {
            cmd.push_str(" -Wl,-O2");
        }
        cmd
    }
}

// ============================================================================
// Tests for Compilation Pipeline
// ============================================================================

#[cfg(test)]
mod pipeline_tests {
    use super::*;

    #[test]
    fn test_pipeline_build_command() {
        let pipeline = WasmCompilationPipeline::new(WasmTarget::Wasm32Wasi);
        let cmd = pipeline.build_command("main.c", "main.wasm");
        assert!(cmd.contains("wasm32-wasi"));
        assert!(cmd.contains("-O2"));
    }

    #[test]
    fn test_pipeline_strip_debug() {
        let pipeline = WasmCompilationPipeline::new(WasmTarget::Wasm32Wasi);
        let cmd = pipeline.build_command("app.c", "app.wasm");
        assert!(cmd.contains("--strip-debug"));
    }

    #[test]
    fn test_pipeline_with_all_features() {
        let mut pipeline = WasmCompilationPipeline::new(WasmTarget::Wasm32Wasi);
        pipeline.features = WasmFeatures::all_features();
        let cmd = pipeline.build_command("test.c", "test.wasm");
        assert!(cmd.contains("simd128"));
        assert!(cmd.contains("memory64"));
    }
}

// EOF marker