wasi_virt_layer-cli 0.2.2

CLI for the wasi_virt_layer crate
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
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
/// Module for ABI connection generation and overrides.
pub mod abi_connect;
/// Utilities for handling anonymous and generic WASM rewrites.
pub mod anonymous;
/// Type-checking routines for imported/exported functions.
pub mod check;
/// Internal debug formatting and trace generators.
pub mod debug;
/// Generates and bridges memory copy, trap, and related VFS interactions.
pub mod memory;
/// Routines for stripping or patching unused WASM components.
pub mod patch_component;
/// Embeds module metadata.
pub mod producer;
/// Low-level multi-threading global locks and shared allocations.
pub mod shared_global;
/// Bridges custom initializers, `_start`, `main_void`, and reset routines.
pub mod special_func;
/// Handles re-writing of the WASM start section routines.
pub mod start_section;
/// Internal logic for rewriting WASI threads spawn imports to the VFS.
pub mod threads;

use std::{any::Any, collections::HashMap, fs, io::Read as _, str::FromStr};

use camino::Utf8PathBuf;
use compact_str::{CompactString, ToCompactString as _};
use eyre::{Context as _, ContextCompat};
use itertools::Itertools;
use walrus::MemoryId;

use crate::{
    args::{self, TargetMemoryType}, compile, config_checker::TomlRestorers, fallback_command, generator::start_section::StartSectionGenerator, unique_name::UniqueName, util::{
        CaminoUtilModule as _, ResultUtil, WalrusFID as _, WalrusUtilExport as _, WalrusUtilModule,
        WasmName, WasmNameHolder,
    }
};

/// Represents the generation context, holding configuration arguments and targeted module info.
#[derive(Debug)]
pub struct GeneratorCtx {
    /// The name of the VFS module.
    pub vfs_name: WasmName,
    /// The names of the target modules.
    pub target_names: Box<[WasmName]>,
    /// Including one's own WASI ABI
    pub target_names_with_self: Box<[WasmName]>,
    /// only pre_vfs, post_combine, post_lower_memory
    pub vfs_used_memory_id: Option<MemoryId>,
    /// only post_combine
    pub vfs_used_global_id: Option<Box<[walrus::GlobalId]>>,
    /// only pre_target, post_combine, post_lower_memory
    pub target_used_memory_id: Option<HashMap<WasmName, MemoryId>>,
    /// only post_combine
    pub target_used_global_id: Option<HashMap<WasmName, Box<[walrus::GlobalId]>>>,
    /// not start section.
    /// only post_combine.
    pub start_func_id: Option<HashMap<WasmName, walrus::FunctionId>>,
    /// The memory type of the target modules (Single or Multi).
    pub target_memory_type: TargetMemoryType,
    /// Whether to print unstable debug information.
    pub unstable_print_debug: bool,
    /// Whether to include DWARF debug information.
    pub dwarf: bool,
    /// Whether to enable multi-threading support.
    pub threads: bool,
    /// Whether to adjust the ABI for standard environments.
    pub adjust_abi: bool,
    /// Whether to keep intermediate build artifacts.
    pub keep_build_artifacts: bool,
    /// Builder for the start section, if applicable.
    pub start_section_builder: Option<start_section::StartSectionBuilder>,
}

/// Sub-context for extracting and storing component variables during execution.
#[derive(Debug, Default)]
pub struct ComponentCtx {
    /// Optional name of the VFS module.
    vfs_name: Option<WasmName>,
    /// Optional names of the target modules.
    target_names: Option<Box<[WasmName]>>,
    /// Optional memory type of the target modules.
    target_memory_type: Option<TargetMemoryType>,
    /// Optional flag for unstable debug printing.
    unstable_print_debug: Option<bool>,
    /// Flag for including DWARF debug information.
    dwarf: bool,
    /// Optional flag for multi-threading support.
    threads: Option<bool>,
    /// Flag for ABI adjustment.
    adjust_abi: bool,
}

struct CompressNames {
    names: Box<[String]>,
}

impl ToString for CompressNames {
    fn to_string(&self) -> String {
        self.names
            .iter()
            .map(|s| {
                let len = s.len();
                let len_len = len.to_string().len();
                format!("{:09}{}{}", len_len, len, s)
            })
            .join("")
    }
}

impl FromStr for CompressNames {
    type Err = eyre::Report;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut names = Vec::new();
        let mut rest = s;
        while !rest.is_empty() {
            let len_len = &rest[0..9];
            let len_len: usize = len_len[len_len
                .chars()
                .position(|c| c != '0')
                .unwrap_or(len_len.chars().count() - 1)..]
                .parse()
                .wrap_err_with(|| format!("Failed to parse length of length: {len_len}"))?;
            rest = rest.get(9..).unwrap();
            let len: usize = rest
                .get(0..len_len)
                .ok_or_else(|| eyre::eyre!("Failed to get length"))?
                .parse()
                .wrap_err_with(|| format!("Failed to parse length: {rest}"))?;
            rest = rest.get(len_len..).unwrap();
            let name = rest
                .get(0..len)
                .ok_or_else(|| eyre::eyre!("Failed to get name"))?;
            names.push(name.to_string());
            rest = rest.get(len..).unwrap();
        }
        Ok(Self {
            names: names.into_boxed_slice(),
        })
    }
}

/// A generator acting as a visitor that propagates component contextual data.
#[derive(Debug, Default)]
pub struct ComponentCtxVisitor {
    vfs_name: Option<CompactString>,
    target_names: Option<Box<[CompactString]>>,
    target_memory_type: Option<TargetMemoryType>,
    unstable_print_debug: Option<bool>,
    dwarf: Option<bool>,
    threads: Option<bool>,
    adjust_abi: bool,
}

impl ComponentCtxVisitor {
    /// Creates a new `ComponentCtxVisitor` with the specified context parameters.
    pub fn new(
        vfs_name: WasmName,
        target_names: Box<[WasmName]>,
        target_memory_type: TargetMemoryType,
        unstable_print_debug: bool,
        dwarf: bool,
        threads: bool,
        adjust_abi: bool,
    ) -> Self {
        Self {
            vfs_name: Some(vfs_name.to_compact_string()),
            target_names: Some(
                target_names
                    .into_iter()
                    .map(|s| s.to_compact_string())
                    .collect(),
            ),
            target_memory_type: Some(target_memory_type),
            unstable_print_debug: Some(unstable_print_debug),
            dwarf: Some(dwarf),
            threads: Some(threads),
            adjust_abi,
        }
    }
}

impl Generator for ComponentCtxVisitor {
    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
        let vfs_name = ctx.vfs_name.to_compact_string();
        let target_names = CompressNames {
            names: ctx
                .target_names
                .iter()
                .map(|s| s.to_string())
                .collect::<Box<_>>(),
        };
        let GeneratorCtx {
            vfs_name: _,
            target_names: _,
            target_memory_type,
            unstable_print_debug,
            dwarf,
            threads,
            adjust_abi,
            target_names_with_self: _,
            vfs_used_memory_id: _,
            vfs_used_global_id: _,
            target_used_memory_id: _,
            target_used_global_id: _,
            start_func_id: _,
            keep_build_artifacts: _,
            start_section_builder: _,
        } = ctx;
        module.save_info("vfs_name", vfs_name.to_string())?;
        module.save_info("target_names", target_names)?;
        module.save_info("target_memory_type", *target_memory_type)?;
        module.save_info("unstable_print_debug", *unstable_print_debug)?;
        module.save_info("dwarf", *dwarf)?;
        module.save_info("threads", *threads)?;
        module.save_info("adjust_abi", *adjust_abi)?;
        Ok(())
    }

    fn post_components(
        &mut self,
        module: &mut walrus::Module,
        _: &ComponentCtx,
    ) -> eyre::Result<()> {
        let vfs_name = module.load_info::<String>("vfs_name")?;
        let target_names = module.load_info::<CompressNames>("target_names")?;
        let target_memory_type = module.load_info::<TargetMemoryType>("target_memory_type")?;
        let unstable_print_debug = module.load_info::<bool>("unstable_print_debug")?;
        let dwarf = module.load_info::<bool>("dwarf")?;
        let threads = module.load_info::<bool>("threads")?;
        let adjust_abi = module.load_info::<bool>("adjust_abi")?;
        self.vfs_name = Some(vfs_name.to_compact_string());
        self.target_names = Some(
            target_names
                .names
                .into_iter()
                .map(|s| s.to_compact_string())
                .collect(),
        );
        self.target_memory_type = Some(target_memory_type);
        self.unstable_print_debug = Some(unstable_print_debug);
        self.dwarf = Some(dwarf);
        self.threads = Some(threads);
        self.adjust_abi = adjust_abi;

        Ok(())
    }
}

impl ComponentCtx {
    /// Creates a new `ComponentCtx` with the specified context parameters.
    pub fn new(
        vfs_name: WasmName,
        target_names: Box<[WasmName]>,
        target_memory_type: TargetMemoryType,
        unstable_print_debug: bool,
        dwarf: bool,
        threads: bool,
        adjust_abi: bool,
    ) -> Self {
        Self {
            vfs_name: Some(vfs_name),
            target_names: Some(target_names),
            target_memory_type: Some(target_memory_type),
            unstable_print_debug: Some(unstable_print_debug),
            dwarf,
            threads: Some(threads),
            adjust_abi,
        }
    }

    /// Returns the name of the VFS module.
    pub fn vfs_name(&self) -> &WasmName {
        self.vfs_name.as_ref().unwrap()
    }

    /// Returns the names of the target modules.
    pub fn target_names(&self) -> &Box<[WasmName]> {
        self.target_names.as_ref().unwrap()
    }

    /// Returns the memory type of the target modules.
    pub fn target_memory_type(&self) -> TargetMemoryType {
        self.target_memory_type.unwrap()
    }

    /// Returns whether to print unstable debug information.
    pub fn unstable_print_debug(&self) -> bool {
        self.unstable_print_debug.unwrap()
    }

    /// Returns whether to include DWARF debug information.
    pub fn dwarf(&self) -> bool {
        self.dwarf
    }

    /// Returns whether to enable multi-threading support.
    pub fn threads(&self) -> bool {
        self.threads.unwrap()
    }
}

/// Defines the core trait for WASM transformations, hooks, and component optimizations over the build lifecycle.
pub trait Generator: std::fmt::Debug + Any {
    /// Operations performed on the built VFS module.
    #[allow(unused_variables)]
    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
        Ok(())
    }

    /// Operations performed on the target module.
    #[allow(unused_variables)]
    fn pre_target(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
        external: &ModuleExternal,
    ) -> eyre::Result<()> {
        Ok(())
    }

    /// Operations performed on the combined module.
    #[allow(unused_variables)]
    fn post_combine(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
    ) -> eyre::Result<()> {
        Ok(())
    }

    /// Operations performed after lowerings memory operations.
    /// Only called if the target memory type is `Single`.
    #[allow(unused_variables)]
    fn post_lower_memory(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
    ) -> eyre::Result<()> {
        Ok(())
    }

    /// Operations performed after components.
    #[allow(unused_variables)]
    fn post_components(
        &mut self,
        module: &mut walrus::Module,
        ctx: &ComponentCtx,
    ) -> eyre::Result<()> {
        Ok(())
    }

    /// Operations performed after last optimizations.
    /// Generating debug functions is a delicate process,
    /// so in this case, output once per structure.
    /// Return true if there are changes.
    #[allow(unused_variables)]
    fn post_all_optimize(
        &mut self,
        module: &mut walrus::Module,
        ctx: &ComponentCtx,
    ) -> eyre::Result<bool> {
        Ok(false)
    }
}
impl<T: std::fmt::Debug + Any + Generator> Generator for [T] {
    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
        for generator in self {
            generator.pre_vfs(module, ctx).wrap_err_with(|| {
                eyre::eyre!(format!("Failed to run pre_vfs for {generator:?}"))
            })?;
        }
        Ok(())
    }

    fn pre_target(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
        external: &ModuleExternal,
    ) -> eyre::Result<()> {
        for generator in self {
            generator
                .pre_target(module, ctx, external)
                .wrap_err_with(|| {
                    eyre::eyre!(format!("Failed to run pre_target for {generator:?}"))
                })?;
        }
        Ok(())
    }

    fn post_combine(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
    ) -> eyre::Result<()> {
        for generator in self {
            generator.post_combine(module, ctx).wrap_err_with(|| {
                eyre::eyre!(format!("Failed to run post_combine for {generator:?}"))
            })?;
        }
        Ok(())
    }

    fn post_lower_memory(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
    ) -> eyre::Result<()> {
        for generator in self {
            generator.post_lower_memory(module, ctx).wrap_err_with(|| {
                eyre::eyre!(format!("Failed to run post_lower_memory for {generator:?}"))
            })?;
        }
        Ok(())
    }

    fn post_components(
        &mut self,
        module: &mut walrus::Module,
        ctx: &ComponentCtx,
    ) -> eyre::Result<()> {
        for generator in self {
            generator.post_components(module, ctx).wrap_err_with(|| {
                eyre::eyre!(format!("Failed to run post_components for {generator:?}"))
            })?;
        }
        Ok(())
    }

    fn post_all_optimize(
        &mut self,
        module: &mut walrus::Module,
        ctx: &ComponentCtx,
    ) -> eyre::Result<bool> {
        let mut changed = false;
        for generator in self {
            changed |= generator.post_all_optimize(module, ctx).wrap_err_with(|| {
                eyre::eyre!(format!("Failed to run post_all_optimize for {generator:?}"))
            })?;
        }
        Ok(changed)
    }
}
impl Generator for Box<dyn Generator + 'static> {
    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
        (**self).pre_vfs(module, ctx)
    }

    fn pre_target(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
        external: &ModuleExternal,
    ) -> eyre::Result<()> {
        (**self).pre_target(module, ctx, external)
    }

    fn post_combine(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
    ) -> eyre::Result<()> {
        (**self).post_combine(module, ctx)
    }

    fn post_lower_memory(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
    ) -> eyre::Result<()> {
        (**self).post_lower_memory(module, ctx)
    }

    fn post_components(
        &mut self,
        module: &mut walrus::Module,
        ctx: &ComponentCtx,
    ) -> eyre::Result<()> {
        (**self).post_components(module, ctx)
    }

    fn post_all_optimize(
        &mut self,
        module: &mut walrus::Module,
        ctx: &ComponentCtx,
    ) -> eyre::Result<bool> {
        (**self).post_all_optimize(module, ctx)
    }
}
impl<'a> Generator for &'a mut (dyn Generator + 'a) {
    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
        (**self).pre_vfs(module, ctx)
    }

    fn pre_target(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
        external: &ModuleExternal,
    ) -> eyre::Result<()> {
        (**self).pre_target(module, ctx, external)
    }

    fn post_combine(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
    ) -> eyre::Result<()> {
        (**self).post_combine(module, ctx)
    }

    fn post_lower_memory(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
    ) -> eyre::Result<()> {
        (**self).post_lower_memory(module, ctx)
    }

    fn post_components(
        &mut self,
        module: &mut walrus::Module,
        ctx: &ComponentCtx,
    ) -> eyre::Result<()> {
        (**self).post_components(module, ctx)
    }

    fn post_all_optimize(
        &mut self,
        module: &mut walrus::Module,
        ctx: &ComponentCtx,
    ) -> eyre::Result<bool> {
        (**self).post_all_optimize(module, ctx)
    }
}

/// Stores the identity of an external loaded Wasm target.
#[derive(Debug)]
pub struct ModuleExternal {
    /// The name of the external module.
    pub name: WasmName,
}

impl ModuleExternal {
    /// Creates a new `ModuleExternal` with the specified name.
    pub fn new(name: &WasmName) -> Self {
        Self { name: name.clone() }
    }
}

/// Coordinates iterating over registered generators and merging external module logic into the VFS.
#[derive(Debug)]
pub struct GeneratorRunner {
    /// The checkers used to validate the module.
    pub checkers: Vec<Box<dyn Generator + 'static>>,
    /// The generators used to transform the module.
    pub generators: Vec<Box<dyn Generator + 'static>>,
    /// The context used during generation.
    pub ctx: GeneratorCtx,
    /// The path to the WASM module.
    pub path: WasmPath,
    /// The paths to the target WASM modules.
    pub targets: Box<[WasmPath]>,
    /// The TOML restorers used to reset configuration files.
    pub toml_restorers: Option<TomlRestorers>,
    /// Memory hints for the target modules.
    pub memory_hint: HashMap<WasmName, usize>,
    /// Holder for the names of the WASM modules.
    pub wasm_name_holder: WasmNameHolder,
}

/// A runner that coordinates the generation of a WebAssembly component.
#[derive(Debug)]
pub struct ComponentRunner {
    /// The generators used to transform the component.
    pub generators: Vec<Box<dyn Generator + 'static>>,
    /// Encapsulates contextual settings across all generator components during transpilation.
    pub ctx: Option<ComponentCtx>,
    /// Specifies the target active WASM module destination.
    pub path: WasmPath,
    /// Manages dynamically generated and globally referenced named functions.
    pub wasm_name_holder: Option<WasmNameHolder>,
}

pub(crate) trait WrapRunner<T> {
    #[allow(unused_variables)]
    fn wrap_run(
        self,
        path: &mut WasmPath,
        dwarf: bool,
        keep_build_artifacts: bool,
    ) -> eyre::Result<T>
    where
        Self: Sized;
}

impl<T, F: FnOnce(&mut walrus::Module) -> eyre::Result<T>> WrapRunner<T> for F {
    fn wrap_run(
        self,
        path: &mut WasmPath,
        dwarf: bool,
        keep_build_artifacts: bool,
    ) -> eyre::Result<T> {
        let old_path = path.path()?;
        let module =
            &mut walrus::Module::load(old_path, dwarf).wrap_err("Failed to load Wasm module")?;

        let result = (self)(module)?;

        let new_path = old_path.with_extension("adjusted.wasm");

        if fs::metadata(&new_path).is_ok() {
            fs::remove_file(&new_path)
                .wrap_err_with(|| format!("Failed to remove existing file {new_path}"))?;
        }

        module
            .emit_wasm_file(&new_path)
            .to_eyre()
            .wrap_err_with(|| format!("Failed to write adjusted Wasm to {new_path}"))?;

        if !keep_build_artifacts {
            std::fs::remove_file(old_path)
                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
        }

        path.set_path(new_path)?;

        Ok(result)
    }
}

pub(crate) trait EndWithOpt<T> {
    #[allow(unused_variables)]
    fn with_opt(
        self,
        path: &mut WasmPath,
        dwarf: bool,
        keep_build_artifacts: bool,
    ) -> eyre::Result<T>
    where
        Self: Sized;

    #[allow(dead_code)]
    fn with_opt_args(
        self,
        path: &mut WasmPath,
        args: &[&str],
        require_update: bool,
        dwarf: bool,
        keep_build_artifacts: bool,
    ) -> eyre::Result<T>
    where
        Self: Sized;
}

impl<T, F: FnOnce(&mut WasmPath) -> eyre::Result<T>> EndWithOpt<T> for F {
    fn with_opt(
        self,
        path: &mut WasmPath,
        dwarf: bool,
        keep_build_artifacts: bool,
    ) -> eyre::Result<T>
    where
        Self: Sized,
    {
        let result = (self)(path).wrap_err("Failed to run with with_opt")?;

        println!("Optimizing Wasm...");
        let old_path = path.path()?.clone();
        let new_path = compile::optimize_wasm(&old_path, &[], false, dwarf)
            .wrap_err("Failed to optimize Wasm")?;

        if !keep_build_artifacts && old_path != new_path {
            std::fs::remove_file(&old_path)
                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
        }

        path.set_path(new_path)?;

        Ok(result)
    }

    fn with_opt_args(
        self,
        path: &mut WasmPath,
        args: &[&str],
        require_update: bool,
        dwarf: bool,
        keep_build_artifacts: bool,
    ) -> eyre::Result<T>
    where
        Self: Sized,
    {
        let result = (self)(path).wrap_err("Failed to run with with_opt_args")?;

        println!("Optimizing Wasm... with args: {}", args.iter().join(" "));
        let old_path = path.path()?.clone();
        let new_path = compile::optimize_wasm(&old_path, args, require_update, dwarf)
            .wrap_err("Failed to optimize Wasm")?;

        if !keep_build_artifacts && old_path != new_path {
            std::fs::remove_file(&old_path)
                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
        }

        path.set_path(new_path)?;

        Ok(result)
    }
}

impl GeneratorRunner {
    /// Initializes a `GeneratorRunner` capturing all parameters needed for complete application-level transpilation mapping.
    pub fn new(
        path: WasmPath,
        targets: Box<[WasmPath]>,
        threads: bool,
        dwarf: bool,
        unstable_print_debug: bool,
        adjust_abi: bool,
        keep_build_artifacts: bool,
        memory_type: TargetMemoryType,
        toml_restorers: TomlRestorers,
        memory_hint: Box<[Option<usize>]>,
    ) -> eyre::Result<Self> {
        let target_names_with_self = core::iter::once(Ok(path.name()?.to_compact_string()))
            .chain(targets.iter().map(|t| Ok(t.name()?.to_compact_string())))
            .collect::<eyre::Result<Box<_>>>()?;

        let wasm_name_holder = WasmNameHolder::new(target_names_with_self);
        let mut wasm_name_holder_iter = wasm_name_holder.iter();
        let vfs_name = wasm_name_holder_iter
            .next()
            .ok_or_else(|| eyre::eyre!("Failed to get VFS name"))?;

        let target_names = wasm_name_holder_iter.collect::<Box<_>>();

        // log targeting info
        for name in target_names.iter() {
            log::info!("Targeting module: {name}");
        }
        log::info!("VFS module: {vfs_name}");

        let target_names_with_self = target_names
            .iter()
            .cloned()
            .chain(core::iter::once(vfs_name.clone()))
            .collect::<Box<_>>();

        let memory_hint = memory_hint
            .into_iter()
            .zip(target_names.iter().cloned())
            .filter_map(|(hint, name)| hint.map(|h| (name, h)))
            .collect::<HashMap<_, _>>();

        Ok(Self {
            checkers: Vec::new(),
            generators: Vec::new(),
            ctx: GeneratorCtx {
                vfs_name,
                target_names,
                target_names_with_self,
                target_memory_type: memory_type,
                unstable_print_debug,
                dwarf,
                threads,
                adjust_abi,
                keep_build_artifacts,
                vfs_used_memory_id: None,
                vfs_used_global_id: None,
                target_used_memory_id: None,
                target_used_global_id: None,
                start_func_id: None,
                start_section_builder: None,
            },
            path,
            targets,
            toml_restorers: Some(toml_restorers),
            memory_hint,
            wasm_name_holder,
        })
    }

    /// Registers a custom generator to be applied sequentially during transformation phases.
    pub fn add_generator<G: Generator + 'static>(&mut self, generator: G) {
        self.generators.push(Box::new(generator));
    }

    /// Registers a diagnostic validation checker resolving pre or post-conditions automatically.
    pub fn checker(&mut self, checker: impl Generator + 'static) {
        self.checkers.push(Box::new(checker));
    }

    /// Resolves and retrieves a shared reference to a specific structured generator dynamically at runtime.
    pub fn get_generator_ref<T: Generator + 'static>(&self) -> eyre::Result<&T> {
        fn downcast_ref<T: 'static>(b: &dyn Any) -> Option<&'_ T> {
            if b.is::<T>() {
                Some(b.downcast_ref::<T>().unwrap())
            } else {
                None
            }
        }

        self.generators
            .iter()
            .map(|g| g.as_ref())
            .find_map(|g| downcast_ref::<T>(g))
            .wrap_err_with(|| {
                eyre::eyre!("Failed to get generator: {}", core::any::type_name::<T>())
            })
            .wrap_err_with(|| eyre::eyre!("Available generators: {:?}", self.generators))
    }

    #[deprecated(
        note = "Ensure this function is self-contained. This is a temporary measure for debugging purposes."
    )]
    /// Provides direct immutable access tracking the primary target structural path configuration.
    pub const fn path(&self) -> &WasmPath {
        &self.path
    }

    #[deprecated(
        note = "Ensure this function is self-contained. This is a temporary measure for debugging purposes."
    )]
    /// Directly evaluates currently linked ancillary wasm dependencies.
    pub const fn targets(&self) -> &Box<[WasmPath]> {
        &self.targets
    }

    /// Securely uncovers operational variables tracking internal generational properties dynamically.
    pub const fn ctx(&self) -> &GeneratorCtx {
        &self.ctx
    }

    /// Confirms mapping configurations and statically evaluates lazy initializations strictly allocating paths.
    pub fn definitely(&mut self) -> eyre::Result<()> {
        self.path.definitely(self.ctx.threads)?;
        for target in &mut self.targets {
            target.definitely(self.ctx.threads)?;
        }
        Ok(())
    }

    /// Primary operation chaining logic seamlessly running structural modifiers across all layered stages sequentially terminating out into WebAssembly components.
    pub fn run_layers_to_component(
        mut self,
        out_dir: &Utf8PathBuf,
        keep_build_artifacts: bool,
    ) -> eyre::Result<ComponentRunner> {
        self.definitely()?;

        let toml_restorers = self
            .toml_restorers
            .take()
            .ok_or_else(|| eyre::eyre!("TomlRestorers already taken"))?;

        toml_restorers
            .restore()
            .wrap_err("Failed to restore toml files")?;

        let mut mem_id_visitor = MemoryIDVisitor {
            memory_hint: self.memory_hint.clone(),
            used_vfs_memory_id: None,
            used_target_memory_id: None,
        };
        let mut global_id_visitor = GlobalIdVisitor {
            vfs_global_id: None,
            global_id: None,
        };
        let mut start_section_generator = StartSectionGenerator::default();

        let dwarf = self.ctx.dwarf;

        println!("Remove existing output directory...");
        if std::fs::metadata(&out_dir).is_ok() {
            std::fs::remove_dir_all(&out_dir).expect("Failed to remove existing directory");
        }
        std::fs::create_dir_all(&out_dir).expect("Failed to create output directory");

        let mut component_ctx_visitor = ComponentCtxVisitor::new(
            self.ctx.vfs_name.clone(),
            self.ctx.target_names.clone(),
            self.ctx.target_memory_type,
            self.ctx.unstable_print_debug,
            self.ctx.dwarf,
            self.ctx.threads,
            self.ctx.adjust_abi,
        );

        println!("Adjusting VFS Wasm...");
        (|path: &mut WasmPath| {
            (|module: &mut walrus::Module| {
                self.checkers
                    .pre_vfs(module, &self.ctx)
                    .wrap_err("Failed to run checkers in pre_vfs")?;

                mem_id_visitor
                    .pre_vfs(module, &self.ctx)
                    .wrap_err("Failed in pre_vfs")?;
                global_id_visitor
                    .pre_vfs(module, &self.ctx)
                    .wrap_err("Failed in pre_vfs")?;

                self.ctx.vfs_used_memory_id = mem_id_visitor.used_vfs_memory_id;

                component_ctx_visitor
                    .pre_vfs(module, &self.ctx)
                    .wrap_err("Failed in pre_vfs")?;

                start_section_generator.init(
                    module,
                    self.ctx.vfs_name.clone(),
                    &self.ctx.target_names,
                );

                self.ctx.start_section_builder = Some(start_section_generator.builder());

                self.generators
                    .pre_vfs(module, &self.ctx)
                    .wrap_err("Failed in run_pre_vfs")
            })
            .wrap_run(path, dwarf, keep_build_artifacts)
        })
        .with_opt(&mut self.path, dwarf, keep_build_artifacts)?;

        let mut start_section_generator = Some(start_section_generator);

        println!("Adjusting target Wasm...");
        self.ctx.vfs_used_memory_id = None;
        for (target, target_name) in self.targets.iter_mut().zip(self.ctx.target_names.clone()) {
            (|path: &mut WasmPath| {
                (|module: &mut walrus::Module| {
                    let external = ModuleExternal::new(&target_name);
                    mem_id_visitor
                        .pre_target(module, &self.ctx, &external)
                        .wrap_err("Failed in pre_target")?;
                    global_id_visitor
                        .pre_target(module, &self.ctx, &external)
                        .wrap_err("Failed in pre_target")?;

                    self.ctx.target_used_memory_id = mem_id_visitor.used_target_memory_id.clone();

                    self.generators
                        .pre_target(module, &self.ctx, &external)
                        .wrap_err("Failed in run_pre_target")
                })
                .wrap_run(path, dwarf, keep_build_artifacts)
            })
            .with_opt(target, dwarf, keep_build_artifacts)?;
        }

        println!("Combining Wasm modules...");
        self.ctx.vfs_used_memory_id = None;
        self.ctx.target_used_memory_id = None;
        let output = format!("{out_dir}/merged.wasm");
        (|path: &mut WasmPath| {
            let old_path = path.path()?.clone();
            merge(
                &old_path,
                &self
                    .targets
                    .iter()
                    .map(|t| t.path())
                    .collect::<eyre::Result<Vec<_>>>()?,
                &output,
                self.ctx.threads,
                dwarf,
            )
            .wrap_err("Failed to combine Wasm modules")?;

            if !keep_build_artifacts {
                std::fs::remove_file(&old_path)
                    .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
            }

            path.set_path(output.into())
        })
        .with_opt(&mut self.path, dwarf, keep_build_artifacts)?;

        println!("Adjusting Merged Wasm...");
        (|path: &mut WasmPath| {
            (|module: &mut walrus::Module| {
                mem_id_visitor
                    .post_combine(module, &self.ctx)
                    .wrap_err("Failed in post_combine")?;
                global_id_visitor
                    .post_combine(module, &self.ctx)
                    .wrap_err("Failed in post_combine")?;
                let mut start_func_id_visitor = StartFuncIdVisitor::default();
                start_func_id_visitor
                    .post_combine(module, &self.ctx)
                    .wrap_err("Failed in post_combine")?;

                self.ctx.vfs_used_memory_id = mem_id_visitor.used_vfs_memory_id.take();
                self.ctx.target_used_memory_id = mem_id_visitor.used_target_memory_id.take();

                self.ctx.vfs_used_global_id = global_id_visitor.vfs_global_id.take();
                self.ctx.target_used_global_id = global_id_visitor.global_id.take();

                self.ctx.start_func_id = start_func_id_visitor.start_func_id.take();

                self.generators.post_combine(module, &self.ctx)?;

                if self.ctx.target_memory_type == TargetMemoryType::Multi {
                    start_section_generator
                        .take()
                        .unwrap()
                        .build(module, &self.ctx)?;
                }

                Ok(())
            })
            .wrap_run(path, dwarf, keep_build_artifacts)
        })
        .with_opt(&mut self.path, dwarf, keep_build_artifacts)?;

        self.ctx.vfs_used_memory_id = None;
        self.ctx.target_used_memory_id = None;

        self.ctx.vfs_used_global_id = None;
        self.ctx.target_used_global_id = None;

        self.ctx.start_func_id = None;

        if self.ctx.target_memory_type == TargetMemoryType::Single {
            let old_path = self.path.path()?.clone();

            println!("Generating single memory Merged Wasm...");
            let optimized_path =
                compile::optimize_wasm(&old_path, &["--multi-memory-lowering"], true, dwarf)?;

            if !keep_build_artifacts {
                std::fs::remove_file(&old_path)
                    .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
            }

            self.path.set_path(optimized_path)?;

            (|path: &mut WasmPath| {
                (|module: &mut walrus::Module| {
                    mem_id_visitor
                        .post_lower_memory(module, &self.ctx)
                        .wrap_err("Failed in post_lower_memory")?;

                    self.ctx.vfs_used_memory_id = mem_id_visitor.used_vfs_memory_id.take();
                    self.ctx.target_used_memory_id = mem_id_visitor.used_target_memory_id.take();

                    self.generators
                        .post_lower_memory(module, &self.ctx)
                        .wrap_err("Failed in run_post_lower_memory")?;

                    start_section_generator
                        .take()
                        .unwrap()
                        .build(module, &self.ctx)?;

                    Ok(())
                })
                .wrap_run(path, dwarf, keep_build_artifacts)
            })
            .with_opt(&mut self.path, dwarf, keep_build_artifacts)?;
        }

        println!("Translating Wasm to Component...");
        let old_path = self.path.path()?.clone();
        let component = compile::wasm_to_component(&old_path, &self.ctx.target_names)
            .wrap_err("Failed to translate Wasm to Component")?;
        if !keep_build_artifacts {
            std::fs::remove_file(&old_path)
                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
        }

        let new_component = format!("{out_dir}/{}.component.wasm", self.ctx.vfs_name);
        std::fs::rename(&component, &new_component)
            .wrap_err_with(|| format!("Failed to rename file {component} to {new_component}"))?;

        self.path.set_path(Utf8PathBuf::from(new_component))?;

        Ok(ComponentRunner::with_generators(self.path, self.generators))
    }
}

impl ComponentRunner {
    /// Instantiates a fresh `ComponentRunner` targeting a specific underlying WebAssembly structure.
    pub fn new(path: WasmPath) -> Self {
        Self {
            generators: Vec::new(),
            ctx: None,
            path,
            wasm_name_holder: None,
        }
    }

    /// Installs a specific invariant-checking generator executing without altering primary execution pathways.
    pub fn checker(&mut self, checker: impl Generator + 'static) {
        self.generators.push(Box::new(checker));
    }

    /// Quickly constructs a runner wrapping a pre-defined array containing generator strategies.
    pub fn with_generators(path: WasmPath, generators: Vec<Box<dyn Generator + 'static>>) -> Self {
        Self {
            generators,
            ctx: None,
            path,
            wasm_name_holder: None,
        }
    }

    /// Queues an advanced generative instruction step executed successively upon evaluation.
    pub fn add_generator<G: Generator + 'static>(&mut self, generator: G) {
        self.generators.push(Box::new(generator));
    }

    /// Allows querying the internal generator stack dynamically retrieving explicitly modeled type structures.
    pub fn get_generator_ref<T: Generator + 'static>(&self) -> eyre::Result<&T> {
        fn downcast_ref<T: 'static>(b: &dyn Any) -> Option<&'_ T> {
            if b.is::<T>() {
                Some(b.downcast_ref::<T>().unwrap())
            } else {
                None
            }
        }

        self.generators
            .iter()
            .map(|g| g.as_ref())
            .find_map(|g| downcast_ref::<T>(g))
            .wrap_err_with(|| {
                eyre::eyre!("Failed to get generator: {}", core::any::type_name::<T>())
            })
            .wrap_err_with(|| eyre::eyre!("Available generators: {:?}", self.generators))
    }

    /// return is_threads, core_name, mem_size
    pub fn component_to_files(
        &mut self,
        parsed_args: &(impl args::PostBuildContext + ?Sized),
        dwarf: bool,
        only_core: bool,
    ) -> eyre::Result<(bool, CompactString, HashMap<CompactString, (u64, u64)>)> {
        let out_dir = parsed_args.out_dir();

        let name = self.path.name()?;

        println!("Translating Component to JS...");
        let core_wasm_path = (|path: &mut WasmPath| {
            let old_path = path.path()?.clone();
            let binary = std::fs::read(&old_path).wrap_err("Failed to read component")?;
            let transpiled = parsed_args
                .transpile_to_js(&binary, &name)
                .wrap_err("Failed to transpile to JS")?;

            let mut core_wasm = None;
            for (name, data) in transpiled.files.iter() {
                let name = camino::Utf8PathBuf::from(name);
                let file_name = out_dir.join(&name);
                if std::fs::metadata(&file_name).is_ok() {
                    std::fs::remove_file(&file_name).wrap_err_with(|| {
                        eyre::eyre!("Failed to remove existing file: {file_name}")
                    })?;
                }
                if name.as_str().ends_with(".core.wasm") {
                    let file_name = camino::Utf8PathBuf::from(file_name);
                    std::fs::write(&file_name, &data).wrap_err_with(|| {
                        eyre::eyre!("Failed to write core wasm file: {file_name}")
                    })?;
                    core_wasm = Some(file_name);
                } else {
                    if let Some(parent) = name.parent() {
                        if !parent.as_str().is_empty() {
                            let dir = name.ancestors().nth(1).wrap_err_with(|| {
                                eyre::eyre!("Failed to get parent directory: {}", name)
                            })?;
                            let joined_dir = out_dir.join(dir);
                            if !std::fs::metadata(&joined_dir).is_ok() {
                                if dir.as_str() != "interfaces" {
                                    log::warn!("Creating directory: {joined_dir}");
                                }
                                if only_core {
                                    continue;
                                }
                                std::fs::create_dir_all(&joined_dir).wrap_err_with(|| {
                                    eyre::eyre!("Failed to create directory: {joined_dir}")
                                })?;
                            }
                        }
                    }
                    if only_core {
                        continue;
                    }
                    std::fs::write(&file_name, &data).wrap_err_with(|| {
                        eyre::eyre!("Failed to write transpiled file: {file_name}")
                    })?;
                }
            }

            let core_wasm = core_wasm
                .as_ref()
                .ok_or_else(|| eyre::eyre!("Failed to find core wasm"))?;

            if !parsed_args.keep_build_artifacts() {
                std::fs::remove_file(&old_path)
                    .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
            }
            path.set_path(core_wasm.clone())?;

            Ok(core_wasm.clone())
        })
        .with_opt(&mut self.path, dwarf, parsed_args.keep_build_artifacts())?;

        let mem_size_visitor = MemorySizeVisitor::default();
        self.generators.push(Box::new(mem_size_visitor));

        println!("Adjusting component Merged Wasm...");
        (|path: &mut WasmPath| {
            (|module: &mut walrus::Module| {
                let mut visitor = ComponentCtxVisitor::default();
                visitor
                    .post_components(
                        module,
                        &ComponentCtx {
                            dwarf,
                            ..Default::default()
                        },
                    )
                    .wrap_err("Failed in post_components")?;
                let wasm_name_holder = WasmNameHolder::new(
                    visitor
                        .target_names
                        .unwrap()
                        .into_iter()
                        .chain(core::iter::once(visitor.vfs_name.unwrap()))
                        .collect::<Box<_>>(),
                );
                self.wasm_name_holder = Some(wasm_name_holder);
                let mut wasm_name_holder_iter = self.wasm_name_holder.as_ref().unwrap().iter();
                self.ctx = Some(ComponentCtx {
                    vfs_name: Some(wasm_name_holder_iter.next().unwrap()),
                    target_names: Some(wasm_name_holder_iter.collect::<Box<_>>()),
                    target_memory_type: Some(visitor.target_memory_type.unwrap()),
                    unstable_print_debug: Some(visitor.unstable_print_debug.unwrap()),
                    dwarf: visitor.dwarf.unwrap(),
                    threads: Some(visitor.threads.unwrap()),
                    adjust_abi: visitor.adjust_abi,
                });

                self.generators
                    .post_components(module, self.ctx.as_ref().unwrap())
                    .wrap_err("Failed in run_post_components")
            })
            .wrap_run(path, dwarf, parsed_args.keep_build_artifacts())
        })
        .with_opt(&mut self.path, dwarf, parsed_args.keep_build_artifacts())?;

        let dwarf = {
            let new_dwarf = self.ctx.as_ref().unwrap().dwarf;
            if dwarf && !new_dwarf {
                log::warn!(
                    "Dwarf was disabled in component processing, you should re-run with --dwarf"
                );
            }
            new_dwarf
        };

        println!("Final optimizing Merged Wasm...");
        let mut i = 0;
        while i < self.generators.len() {
            (|module: &mut walrus::Module| {
                loop {
                    if self.generators[i]
                        .post_all_optimize(module, self.ctx.as_ref().unwrap())
                        .wrap_err("Failed in post_all_optimize")?
                    {
                        i += 1;
                        return Ok(());
                    }
                    i += 1;
                    if i >= self.generators.len() {
                        return Ok(());
                    }
                }
            })
            .wrap_run(&mut self.path, dwarf, parsed_args.keep_build_artifacts())?;
        }

        std::fs::rename(self.path.path()?, &core_wasm_path).wrap_err_with(|| {
            eyre::eyre!(
                "Failed to rename final wasm from {} to {}",
                self.path.path().unwrap(),
                core_wasm_path
            )
        })?;

        Ok((
            self.ctx.as_ref().unwrap().threads(),
            core_wasm_path
                .get_file_main_name()
                .ok_or_else(|| eyre::eyre!("Failed to get file name"))?,
            self.get_generator_ref::<MemorySizeVisitor>()?
                .mem_size
                .clone()
                .unwrap(),
        ))
    }
}

#[derive(Debug, Default, Clone)]
struct MemoryIDVisitor {
    pub memory_hint: HashMap<WasmName, usize>,
    pub used_vfs_memory_id: Option<MemoryId>,
    pub used_target_memory_id: Option<HashMap<WasmName, MemoryId>>,
}

impl Generator for MemoryIDVisitor {
    fn pre_vfs(
        &mut self,
        module: &mut walrus::Module,
        _: &crate::generator::GeneratorCtx,
    ) -> eyre::Result<()> {
        println!("Finding VFS memory id...");

        let id = module
            .get_memory_anchor("vfs", false)
            .wrap_err("Failed to get target memory id")?;
        self.used_vfs_memory_id = Some(id);
        Ok(())
    }

    fn pre_target(
        &mut self,
        module: &mut walrus::Module,
        _: &crate::generator::GeneratorCtx,
        external: &ModuleExternal,
    ) -> eyre::Result<()> {
        let id = module
            .find_used_memory_id(self.memory_hint.get(&external.name).copied())
            .wrap_err("Failed to find used memory id")?;
        module
            .create_memory_anchor(&external.name, id)
            .wrap_err("Failed to create memory anchor")?;
        self.used_target_memory_id
            .get_or_insert_default()
            .insert(external.name.clone(), id);
        Ok(())
    }

    fn post_combine(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
    ) -> eyre::Result<()> {
        let id = module
            .get_memory_anchor("vfs", true)
            .wrap_err("Failed to find used memory id after combine")?;
        self.used_vfs_memory_id = Some(id);

        self.used_target_memory_id.get_or_insert_default().clear();
        for wasm in &ctx.target_names {
            let id = module
                .get_memory_anchor(wasm, true)
                .wrap_err("Failed to find used memory id after combine")?;
            self.used_target_memory_id
                .as_mut()
                .unwrap()
                .insert(wasm.clone(), id);
        }

        Ok(())
    }

    fn post_lower_memory(
        &mut self,
        module: &mut walrus::Module,
        _: &GeneratorCtx,
    ) -> eyre::Result<()> {
        let id = module
            .get_memory_id()
            .to_eyre()
            .wrap_err("Failed to get single memory id after lowering")?;
        self.used_vfs_memory_id = Some(id);
        self.used_target_memory_id = None;

        Ok(())
    }
}

#[derive(Debug, Default, Clone)]
struct MemorySizeVisitor {
    mem_size: Option<HashMap<CompactString, (u64, u64)>>,
}

impl Generator for MemorySizeVisitor {
    fn post_components(
        &mut self,
        module: &mut walrus::Module,
        _: &ComponentCtx,
    ) -> eyre::Result<()> {
        let mem_size = module
            .memories
            .iter()
            .filter(|mem| mem.import.is_some())
            .map(|mem| {
                (
                    module
                        .imports
                        .get(mem.import.unwrap())
                        .name
                        .to_compact_string(),
                    (
                        mem.initial as u64,
                        mem.maximum.unwrap_or(mem.initial) as u64,
                    ),
                )
            })
            .collect::<HashMap<_, _>>();
        self.mem_size = Some(mem_size);

        Ok(())
    }
}

#[derive(Debug, Default)]
struct GlobalIdVisitor {
    vfs_global_id: Option<Box<[walrus::GlobalId]>>,
    global_id: Option<HashMap<WasmName, Box<[walrus::GlobalId]>>>,
}
impl Generator for GlobalIdVisitor {
    fn pre_vfs(&mut self, module: &mut walrus::Module, _: &GeneratorCtx) -> eyre::Result<()> {
        module
            .create_global_anchor("vfs")
            .wrap_err("Failed to create global anchor")?;

        Ok(())
    }

    fn pre_target(
        &mut self,
        module: &mut walrus::Module,
        _: &GeneratorCtx,
        external: &ModuleExternal,
    ) -> eyre::Result<()> {
        module
            .create_global_anchor(&external.name)
            .wrap_err("Failed to create global anchor")?;

        Ok(())
    }

    fn post_combine(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
    ) -> eyre::Result<()> {
        self.global_id = Some(HashMap::new());

        let vfs_globals = module
            .get_global_anchor("vfs")
            .wrap_err("Failed to get global anchor for vfs")?;
        self.vfs_global_id = Some(vfs_globals);

        for wasm in &ctx.target_names {
            let globals = module
                .get_global_anchor(wasm)
                .wrap_err_with(|| format!("Failed to get global anchor for {wasm}"))?;
            self.global_id
                .as_mut()
                .unwrap()
                .insert(wasm.clone(), globals);
        }

        Ok(())
    }
}

/// To be used from both `special_func`'s `main_void` and `start`,
/// it must be prepared in `ctx`.
#[derive(Debug, Default)]
struct StartFuncIdVisitor {
    start_func_id: Option<HashMap<WasmName, walrus::FunctionId>>,
}

impl Generator for StartFuncIdVisitor {
    fn post_combine(
        &mut self,
        module: &mut walrus::Module,
        ctx: &GeneratorCtx,
    ) -> eyre::Result<()> {
        for wasm in &ctx.target_names {
            let export = format!("__wasip1_vfs_{wasm}__start").get_fid(&module.exports)?;
            self.start_func_id
                .get_or_insert_default()
                .insert(wasm.clone(), export);

            module
                .exports
                .erase_with(export, ctx.unstable_print_debug)?;

            module.exports.erase_with(
                &format!("__wasip1_vfs_{wasm}__start_anchor"),
                ctx.unstable_print_debug,
            )?;
        }

        Ok(())
    }
}

/// Represents the resolution state and file format targeting for manipulating WebAssembly modules intelligently.
#[derive(Debug, Clone)]
pub enum WasmPath {
    /// Indicates the target still needs compilation through standard cargo dependencies.
    Maybe {
        /// Fully resolved physical path to the corresponding Cargo.toml manifest definition.
        manifest_path: Utf8PathBuf,
        /// Specified internal crate package identifier.
        package: String,
    },
    /// A strictly resolved raw WebAssembly binary file ready for patching operations.
    Definitely(Utf8PathBuf),
    /// A completed explicitly transpiled WebAssembly Component standard architecture module.
    Component(Utf8PathBuf),
}

impl FromStr for WasmPath {
    type Err = eyre::Error;

    /// manifest_path :: package
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        fn parse_path_and_package(s: &str) -> eyre::Result<Option<WasmPath>> {
            let split = s.split("::").collect::<Vec<_>>();
            if split.len() == 2 {
                let manifest_path = Utf8PathBuf::from_str(split[0])
                    .wrap_err_with(|| format!("Failed to parse manifest path: {}", split[0]))?;
                let package = split[1].to_string();
                return Ok(Some(WasmPath::Maybe {
                    manifest_path,
                    package,
                }));
            }
            Ok(None)
        }

        if let Some(wasm_path) =
            parse_path_and_package(s).wrap_err("Failed to parse path and package")?
        {
            return Ok(wasm_path);
        }

        if s.ends_with(".wasm") {
            let path = Utf8PathBuf::from_str(s)
                .wrap_err_with(|| format!("Failed to parse wasm path: {s}"))?;
            return WasmPath::with_wasm(path);
        }

        if s.ends_with("Cargo.toml") {
            let manifest_path = Utf8PathBuf::from_str(s)
                .wrap_err_with(|| format!("Failed to parse manifest path: {s}"))?;
            return WasmPath::with_maybe_only_manifest(manifest_path);
        }

        WasmPath::with_maybe_only_package(s.to_string())
            .wrap_err_with(|| format!("Failed to parse package name: {s}"))
    }
}

impl WasmPath {
    /// Computes the unique short name used during module linking and identification.
    pub fn name(&self) -> eyre::Result<CompactString> {
        match self {
            WasmPath::Maybe { package, .. } => Ok(package.to_compact_string()),
            WasmPath::Definitely(path) | WasmPath::Component(path) => path
                .get_file_main_name()
                .ok_or_else(|| eyre::eyre!("Failed to get file name from {path}")),
        }
    }

    /// Exposes the manifest path conditionally if the dependency is unresolved logically.
    pub fn manifest_path(&self) -> Option<&Utf8PathBuf> {
        match self {
            WasmPath::Maybe { manifest_path, .. } => Some(manifest_path),
            WasmPath::Definitely(_) | WasmPath::Component(_) => None,
        }
    }

    /// Calculates the overarching workspace root via dependency graphing context implicitly.
    pub fn root_manifest_path(&self) -> Option<Utf8PathBuf> {
        match self {
            WasmPath::Maybe { manifest_path, .. } => {
                let cargo_metadata = {
                    let mut metadata_command = cargo_metadata::MetadataCommand::new();
                    metadata_command.manifest_path(&manifest_path);
                    metadata_command.exec().unwrap()
                };
                Some(cargo_metadata.workspace_root.join("Cargo.toml"))
            }
            WasmPath::Definitely(_) | WasmPath::Component(_) => None,
        }
    }

    /// Statically assigns an unresolved target using defined package specifications.
    pub const fn with_maybe(manifest_path: Utf8PathBuf, package: String) -> Self {
        Self::Maybe {
            manifest_path,
            package,
        }
    }

    /// Constructs an unresolved dependency resolving package tracking inherently from a file manifest dynamically.
    pub fn with_maybe_only_manifest(manifest_path: Utf8PathBuf) -> eyre::Result<Self> {
        let cargo_metadata = {
            let mut metadata_command = cargo_metadata::MetadataCommand::new();
            metadata_command.manifest_path(&manifest_path);
            metadata_command.exec().unwrap()
        };
        let building_crate = compile::get_building_crate(&cargo_metadata, &None)?;

        Ok(Self::Maybe {
            manifest_path,
            package: building_crate.name.to_string(),
        })
    }

    /// Assesses global cargo metadata configuring definitions matching solely the provided string identifier.
    pub fn with_maybe_only_package(package: String) -> eyre::Result<Self> {
        let cargo_metadata = {
            let metadata_command = cargo_metadata::MetadataCommand::new();
            metadata_command.exec().unwrap()
        };
        let building_crate = compile::get_building_crate(&cargo_metadata, &Some(package.clone()))?;

        Ok(Self::Maybe {
            manifest_path: building_crate.manifest_path,
            package: building_crate.name.to_string(),
        })
    }

    /// Loads an unresolved dependency using current environment cargo bounds natively.
    pub fn with_maybe_none() -> eyre::Result<Self> {
        let cargo_metadata = {
            let metadata_command = cargo_metadata::MetadataCommand::new();
            metadata_command.exec().unwrap()
        };
        let building_crate = compile::get_building_crate(&cargo_metadata, &None)?;

        Ok(Self::Maybe {
            manifest_path: building_crate.manifest_path,
            package: building_crate.name.to_string(),
        })
    }

    /// Scans an exact provided `.wasm` artifact verifying magic byte signatures correctly to assign a resolution state.
    pub fn with_wasm(path: Utf8PathBuf) -> eyre::Result<Self> {
        if path.extension() != Some("wasm") {
            eyre::bail!("Wasm file does not have .wasm extension: {path}");
        }
        if !fs::metadata(&path).is_ok() {
            eyre::bail!("Wasm file does not exist: {path}");
        }

        let mut file =
            fs::File::open(&path).wrap_err_with(|| format!("Failed to open wasm file: {path}"))?;
        let mut magic = [0u8; 8];
        file.read_exact(&mut magic)
            .wrap_err_with(|| format!("Failed to read magic number from wasm file: {path}"))?;
        if !magic.starts_with(b"\0asm") {
            eyre::bail!("Wasm file does not have valid magic number: {path}");
        }
        let version = &magic[4..8];
        // https://github.com/WebAssembly/component-model/blob/main/design/mvp/Binary.md#component-definitions
        if version == [0x0D, 0x00, 0x01, 0x00] {
            return Ok(Self::Component(path));
        }
        // https://webassembly.github.io/spec/core/binary/modules.html#binary-module
        if version != [0x01, 0x00, 0x00, 0x00] {
            eyre::bail!("Wasm file does not have valid version: {path}");
        }

        Ok(Self::Definitely(path))
    }

    /// Forcefully invokes internal compiling mechanisms translating a declarative specification down into an executable binary structurally.
    pub fn definitely(&mut self, threads: bool) -> eyre::Result<()> {
        if let WasmPath::Maybe {
            manifest_path,
            package,
        } = self
        {
            let cargo_metadata = {
                let mut metadata_command = cargo_metadata::MetadataCommand::new();
                metadata_command.manifest_path(&manifest_path);
                metadata_command.exec().unwrap()
            };
            let building_crate =
                compile::get_building_crate(&cargo_metadata, &Some(package.clone()))?;
            let vfs_name = building_crate.name.to_string();

            let path =
                compile::build_vfs(Some(&manifest_path.to_string()), &building_crate, threads)
                    .wrap_err_with(|| eyre::eyre!("Failed to build VFS: {vfs_name}"))?;
            *self = WasmPath::Definitely(path);
        }

        Ok(())
    }

    /// Returns the path to the WASM module.
    pub fn path(&self) -> eyre::Result<&Utf8PathBuf> {
        match self {
            WasmPath::Maybe { .. } => {
                eyre::bail!("WasmPath is not definitely set: {self:?}")
            }
            WasmPath::Definitely(p) | WasmPath::Component(p) => Ok(p),
        }
    }

    /// Forcefully overrides the explicitly resolved file path for definite path targets.
    pub fn set_path(&mut self, path: Utf8PathBuf) -> eyre::Result<()> {
        if matches!(self, WasmPath::Maybe { .. }) {
            eyre::bail!("WasmPath is not definitely set: {path}")
        }
        *self = WasmPath::Definitely(path);
        Ok(())
    }
}

/// Coordinates the underlying binary `wasm-merge` utility invocations to bundle outputs physically.
pub fn merge(
    vfs: &Utf8PathBuf,
    wasm: &[impl AsRef<std::path::Path>],
    output: impl AsRef<std::path::Path>,
    _threads: bool,
    dwarf: bool,
) -> eyre::Result<()> {
    let custom_section = {
        let mut vfs_module = walrus::Module::load(vfs, dwarf)?;
        let custom_section_names = vfs_module
            .customs
            .iter()
            .map(|(_, section)| section.name().to_string())
            .filter(|name| name.starts_with("component-type:"))
            .collect::<Vec<_>>();
        // let custom_section = vfs_module
        //     .customs.delete(custom_section_names)
        let custom_section = custom_section_names
            .iter()
            .map(|id| {
                let section = vfs_module.customs.remove_raw(id);
                section.unwrap()
            })
            .collect::<Vec<_>>();

        custom_section
    };

    let mut merge_cmd = fallback_command::get_fallback_command("wasm-merge");

    // if threads {
    //     merge_cmd.arg("--enable-threads");
    // }

    if dwarf {
        merge_cmd.arg("--debuginfo");
    }

    merge_cmd.arg(vfs).arg(UniqueName::WASIP1_ABI_MODULE);

    for wasm in wasm {
        merge_cmd.arg(wasm.as_ref().as_os_str().to_str().unwrap()).arg(format!(
            "wasip1_vfs_{}",
            wasm.as_ref().get_file_main_name().unwrap()
        ));
    }

    merge_cmd
        .arg("--output")
        .arg(output.as_ref().as_os_str().to_str().unwrap())
        // .arg("--rename-export-conflicts")
        .arg("--enable-multimemory")
        .arg("--enable-threads");

    let result = merge_cmd
        .spawn()
        .map_err(|e| match e.kind() {
            std::io::ErrorKind::NotFound => eyre::eyre!(
                "wasm-merge command not found. Please install wasm-merge from https://github.com/WebAssembly/binaryen/releases/latest"
            ),
            _ => e.into(),
        })?
        .wait_with_output()
        .wrap_err("Failed to wait for wasm-merge process")?;

    if !result.success {
        return Err(eyre::eyre!("wasm-merge command failed"));
    }

    let mut module = walrus::Module::load(output.as_ref(), dwarf)?;
    for section in custom_section {
        module.customs.add(section);
    }

    // to output
    fs::remove_file(output.as_ref()).expect("Failed to remove existing file");

    module
        .emit_wasm_file(output.as_ref())
        .expect("Failed to emit wasm file");

    Ok(())
}

macro_rules! _add_generators_by_type {
    ($runner:expr, $($ty:ty),* $(,)?) => {
        $(
            if let Some(_) = $runner.get_generator_ref::<$ty>().ok() {
                panic!("Generator of type {} already exists", std::any::type_name::<$ty>());
            }
            $runner.add_generator(<$ty>::default());
        )*
    };
}
pub(crate) use _add_generators_by_type as add_generators_by_type;