Skip to main content

wasi_virt_layer_cli/generator/
mod.rs

1/// Module for ABI connection generation and overrides.
2pub mod abi_connect;
3/// Utilities for handling anonymous and generic WASM rewrites.
4pub mod anonymous;
5/// Type-checking routines for imported/exported functions.
6pub mod check;
7/// Internal debug formatting and trace generators.
8pub mod debug;
9/// Generates and bridges memory copy, trap, and related VFS interactions.
10pub mod memory;
11/// Routines for stripping or patching unused WASM components.
12pub mod patch_component;
13/// Embeds module metadata.
14pub mod producer;
15/// Low-level multi-threading global locks and shared allocations.
16pub mod shared_global;
17/// Bridges custom initializers, `_start`, `main_void`, and reset routines.
18pub mod special_func;
19pub mod starts;
20/// Internal logic for rewriting WASI threads spawn imports to the VFS.
21pub mod threads;
22/// Handles logic for rewriting unreachable instructions to prevent Wasm execution traps.
23pub mod wrap_unreachable;
24pub mod vfs_host;
25/// Generates the atomic wait implementation for `WaitPoll` timeout handling.
26pub mod poll;
27/// Reimplementation of binaryen's `--multi-memory-lowering` pass using walrus.
28pub mod multi_memory_lowering;
29
30use std::{any::Any, collections::HashMap, fs, io::Read as _, str::FromStr};
31
32use camino::Utf8PathBuf;
33use compact_str::{CompactString, ToCompactString as _};
34use eyre::{Context as _, ContextCompat};
35use itertools::Itertools;
36use walrus::MemoryId;
37
38use crate::{
39    args::{self, TargetMemoryType},
40    compile,
41    config_checker::TomlRestorers,
42    fallback_command,
43    unique_name::UniqueName,
44    util::{
45        CaminoUtilModule as _, ResultUtil, WalrusFID as _, WalrusUtilExport as _, WalrusUtilModule,
46        WasmName, WasmNameHolder,
47    },
48};
49
50/// Represents the generation context, holding configuration arguments and targeted module info.
51#[derive(Debug)]
52pub struct GeneratorCtx {
53    /// The name of the VFS module.
54    pub vfs_name: WasmName,
55    /// The names of the target modules.
56    pub target_names: Box<[WasmName]>,
57    /// Including one's own WASI ABI
58    pub target_names_with_self: Box<[WasmName]>,
59    /// only pre_vfs, post_combine, post_lower_memory
60    pub vfs_used_memory_id: Option<MemoryId>,
61    /// only post_combine
62    pub vfs_used_global_id: Option<Box<[walrus::GlobalId]>>,
63    /// only pre_target, post_combine, post_lower_memory
64    pub target_used_memory_id: Option<HashMap<WasmName, MemoryId>>,
65    /// only post_combine
66    pub target_used_global_id: Option<HashMap<WasmName, Box<[walrus::GlobalId]>>>,
67    /// not start section.
68    /// only post_combine.
69    pub start_func_id: Option<HashMap<WasmName, walrus::FunctionId>>,
70    /// The memory type of the target modules (Single or Multi).
71    pub target_memory_type: TargetMemoryType,
72    /// Whether to print unstable debug information.
73    pub unstable_print_debug: bool,
74    /// Whether to include DWARF debug information.
75    pub dwarf: bool,
76    /// Whether to enable multi-threading support.
77    pub threads: bool,
78    /// Whether to adjust the ABI for standard environments.
79    pub adjust_abi: bool,
80    /// Whether to keep intermediate build artifacts.
81    pub keep_build_artifacts: bool,
82    /// Whether the VFS module is a library (has no start section / `_start` export).
83    /// Detected during `pre_vfs`; when `true`, the VFS start slot in the
84    /// combined start chain is skipped entirely.
85    pub vfs_is_library: bool,
86    pub starts: starts::FnInStarts,
87}
88
89/// Sub-context for extracting and storing component variables during execution.
90#[derive(Debug, Default)]
91pub struct ComponentCtx {
92    /// Optional name of the VFS module.
93    vfs_name: Option<WasmName>,
94    /// Optional names of the target modules.
95    target_names: Option<Box<[WasmName]>>,
96    /// Optional memory type of the target modules.
97    target_memory_type: Option<TargetMemoryType>,
98    /// Optional flag for unstable debug printing.
99    unstable_print_debug: Option<bool>,
100    /// Flag for including DWARF debug information.
101    dwarf: bool,
102    /// Optional flag for multi-threading support.
103    threads: Option<bool>,
104    /// Flag for ABI adjustment.
105    adjust_abi: bool,
106}
107
108struct CompressNames {
109    names: Box<[String]>,
110}
111
112impl ToString for CompressNames {
113    fn to_string(&self) -> String {
114        self.names
115            .iter()
116            .map(|s| {
117                let len = s.len();
118                let len_len = len.to_string().len();
119                format!("{:09}{}{}", len_len, len, s)
120            })
121            .join("")
122    }
123}
124
125impl FromStr for CompressNames {
126    type Err = eyre::Report;
127
128    fn from_str(s: &str) -> Result<Self, Self::Err> {
129        let mut names = Vec::new();
130        let mut rest = s;
131        while !rest.is_empty() {
132            let len_len = &rest[0..9];
133            let len_len: usize = len_len[len_len
134                .chars()
135                .position(|c| c != '0')
136                .unwrap_or(len_len.chars().count() - 1)..]
137                .parse()
138                .wrap_err_with(|| format!("Failed to parse length of length: {len_len}"))?;
139            rest = rest.get(9..).unwrap();
140            let len: usize = rest
141                .get(0..len_len)
142                .ok_or_else(|| eyre::eyre!("Failed to get length"))?
143                .parse()
144                .wrap_err_with(|| format!("Failed to parse length: {rest}"))?;
145            rest = rest.get(len_len..).unwrap();
146            let name = rest
147                .get(0..len)
148                .ok_or_else(|| eyre::eyre!("Failed to get name"))?;
149            names.push(name.to_string());
150            rest = rest.get(len..).unwrap();
151        }
152        Ok(Self {
153            names: names.into_boxed_slice(),
154        })
155    }
156}
157
158/// A generator acting as a visitor that propagates component contextual data.
159#[derive(Debug, Default)]
160pub struct ComponentCtxVisitor {
161    vfs_name: Option<CompactString>,
162    target_names: Option<Box<[CompactString]>>,
163    target_memory_type: Option<TargetMemoryType>,
164    unstable_print_debug: Option<bool>,
165    dwarf: Option<bool>,
166    threads: Option<bool>,
167    adjust_abi: bool,
168}
169
170impl ComponentCtxVisitor {
171    /// Creates a new `ComponentCtxVisitor` with the specified context parameters.
172    pub fn new(
173        vfs_name: WasmName,
174        target_names: Box<[WasmName]>,
175        target_memory_type: TargetMemoryType,
176        unstable_print_debug: bool,
177        dwarf: bool,
178        threads: bool,
179        adjust_abi: bool,
180    ) -> Self {
181        Self {
182            vfs_name: Some(vfs_name.to_compact_string()),
183            target_names: Some(
184                target_names
185                    .into_iter()
186                    .map(|s| s.to_compact_string())
187                    .collect(),
188            ),
189            target_memory_type: Some(target_memory_type),
190            unstable_print_debug: Some(unstable_print_debug),
191            dwarf: Some(dwarf),
192            threads: Some(threads),
193            adjust_abi,
194        }
195    }
196}
197
198impl Generator for ComponentCtxVisitor {
199    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
200        let vfs_name = ctx.vfs_name.to_compact_string();
201        let target_names = CompressNames {
202            names: ctx
203                .target_names
204                .iter()
205                .map(|s| s.to_string())
206                .collect::<Box<_>>(),
207        };
208        let GeneratorCtx {
209            vfs_name: _,
210            target_names: _,
211            target_memory_type,
212            unstable_print_debug,
213            dwarf,
214            threads,
215            adjust_abi,
216            target_names_with_self: _,
217            vfs_used_memory_id: _,
218            vfs_used_global_id: _,
219            target_used_memory_id: _,
220            target_used_global_id: _,
221            start_func_id: _,
222            keep_build_artifacts: _,
223            vfs_is_library: _,
224            starts: _,
225        } = ctx;
226        module.save_info("vfs_name", vfs_name.to_string())?;
227        module.save_info("target_names", target_names)?;
228        module.save_info("target_memory_type", *target_memory_type)?;
229        module.save_info("unstable_print_debug", *unstable_print_debug)?;
230        module.save_info("dwarf", *dwarf)?;
231        module.save_info("threads", *threads)?;
232        module.save_info("adjust_abi", *adjust_abi)?;
233        Ok(())
234    }
235
236    fn post_components(
237        &mut self,
238        module: &mut walrus::Module,
239        _: &ComponentCtx,
240    ) -> eyre::Result<()> {
241        let vfs_name = module.load_info::<String>("vfs_name")?;
242        let target_names = module.load_info::<CompressNames>("target_names")?;
243        let target_memory_type = module.load_info::<TargetMemoryType>("target_memory_type")?;
244        let unstable_print_debug = module.load_info::<bool>("unstable_print_debug")?;
245        let dwarf = module.load_info::<bool>("dwarf")?;
246        let threads = module.load_info::<bool>("threads")?;
247        let adjust_abi = module.load_info::<bool>("adjust_abi")?;
248        self.vfs_name = Some(vfs_name.to_compact_string());
249        self.target_names = Some(
250            target_names
251                .names
252                .into_iter()
253                .map(|s| s.to_compact_string())
254                .collect(),
255        );
256        self.target_memory_type = Some(target_memory_type);
257        self.unstable_print_debug = Some(unstable_print_debug);
258        self.dwarf = Some(dwarf);
259        self.threads = Some(threads);
260        self.adjust_abi = adjust_abi;
261
262        Ok(())
263    }
264}
265
266impl ComponentCtx {
267    /// Creates a new `ComponentCtx` with the specified context parameters.
268    pub fn new(
269        vfs_name: WasmName,
270        target_names: Box<[WasmName]>,
271        target_memory_type: TargetMemoryType,
272        unstable_print_debug: bool,
273        dwarf: bool,
274        threads: bool,
275        adjust_abi: bool,
276    ) -> Self {
277        Self {
278            vfs_name: Some(vfs_name),
279            target_names: Some(target_names),
280            target_memory_type: Some(target_memory_type),
281            unstable_print_debug: Some(unstable_print_debug),
282            dwarf,
283            threads: Some(threads),
284            adjust_abi,
285        }
286    }
287
288    /// Returns the name of the VFS module.
289    pub fn vfs_name(&self) -> &WasmName {
290        self.vfs_name.as_ref().unwrap()
291    }
292
293    /// Returns the names of the target modules.
294    pub fn target_names(&self) -> &Box<[WasmName]> {
295        self.target_names.as_ref().unwrap()
296    }
297
298    /// Returns the memory type of the target modules.
299    pub fn target_memory_type(&self) -> TargetMemoryType {
300        self.target_memory_type.unwrap()
301    }
302
303    /// Returns whether to print unstable debug information.
304    pub fn unstable_print_debug(&self) -> bool {
305        self.unstable_print_debug.unwrap()
306    }
307
308    /// Returns whether to include DWARF debug information.
309    pub fn dwarf(&self) -> bool {
310        self.dwarf
311    }
312
313    /// Returns whether to enable multi-threading support.
314    pub fn threads(&self) -> bool {
315        self.threads.unwrap()
316    }
317}
318
319/// Defines the core trait for WASM transformations, hooks, and component optimizations over the build lifecycle.
320pub trait Generator: std::fmt::Debug + Any {
321    /// Operations performed on the built VFS module.
322    #[allow(unused_variables)]
323    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
324        Ok(())
325    }
326
327    /// Operations performed on the target module.
328    #[allow(unused_variables)]
329    fn pre_target(
330        &mut self,
331        module: &mut walrus::Module,
332        ctx: &GeneratorCtx,
333        external: &ModuleExternal,
334    ) -> eyre::Result<()> {
335        Ok(())
336    }
337
338    /// Operations performed on the combined module.
339    #[allow(unused_variables)]
340    fn post_combine(
341        &mut self,
342        module: &mut walrus::Module,
343        ctx: &GeneratorCtx,
344    ) -> eyre::Result<()> {
345        Ok(())
346    }
347
348    /// Operations performed after lowerings memory operations.
349    /// Only called if the target memory type is `Single`.
350    #[allow(unused_variables)]
351    fn post_lower_memory(
352        &mut self,
353        module: &mut walrus::Module,
354        ctx: &GeneratorCtx,
355    ) -> eyre::Result<()> {
356        Ok(())
357    }
358
359    /// Operations performed after components.
360    #[allow(unused_variables)]
361    fn post_components(
362        &mut self,
363        module: &mut walrus::Module,
364        ctx: &ComponentCtx,
365    ) -> eyre::Result<()> {
366        Ok(())
367    }
368
369    /// Operations performed after last optimizations.
370    /// Generating debug functions is a delicate process,
371    /// so in this case, output once per structure.
372    /// Return true if there are changes.
373    #[allow(unused_variables)]
374    fn post_all_optimize(
375        &mut self,
376        module: &mut walrus::Module,
377        ctx: &ComponentCtx,
378    ) -> eyre::Result<bool> {
379        Ok(false)
380    }
381}
382impl<T: std::fmt::Debug + Any + Generator> Generator for [T] {
383    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
384        for generator in self {
385            generator.pre_vfs(module, ctx).wrap_err_with(|| {
386                eyre::eyre!(format!("Failed to run pre_vfs for {generator:?}"))
387            })?;
388        }
389        Ok(())
390    }
391
392    fn pre_target(
393        &mut self,
394        module: &mut walrus::Module,
395        ctx: &GeneratorCtx,
396        external: &ModuleExternal,
397    ) -> eyre::Result<()> {
398        for generator in self {
399            generator
400                .pre_target(module, ctx, external)
401                .wrap_err_with(|| {
402                    eyre::eyre!(format!("Failed to run pre_target for {generator:?}"))
403                })?;
404        }
405        Ok(())
406    }
407
408    fn post_combine(
409        &mut self,
410        module: &mut walrus::Module,
411        ctx: &GeneratorCtx,
412    ) -> eyre::Result<()> {
413        for generator in self {
414            generator.post_combine(module, ctx).wrap_err_with(|| {
415                eyre::eyre!(format!("Failed to run post_combine for {generator:?}"))
416            })?;
417        }
418        Ok(())
419    }
420
421    fn post_lower_memory(
422        &mut self,
423        module: &mut walrus::Module,
424        ctx: &GeneratorCtx,
425    ) -> eyre::Result<()> {
426        for generator in self {
427            generator.post_lower_memory(module, ctx).wrap_err_with(|| {
428                eyre::eyre!(format!("Failed to run post_lower_memory for {generator:?}"))
429            })?;
430        }
431        Ok(())
432    }
433
434    fn post_components(
435        &mut self,
436        module: &mut walrus::Module,
437        ctx: &ComponentCtx,
438    ) -> eyre::Result<()> {
439        for generator in self {
440            generator.post_components(module, ctx).wrap_err_with(|| {
441                eyre::eyre!(format!("Failed to run post_components for {generator:?}"))
442            })?;
443        }
444        Ok(())
445    }
446
447    fn post_all_optimize(
448        &mut self,
449        module: &mut walrus::Module,
450        ctx: &ComponentCtx,
451    ) -> eyre::Result<bool> {
452        let mut changed = false;
453        for generator in self {
454            changed |= generator.post_all_optimize(module, ctx).wrap_err_with(|| {
455                eyre::eyre!(format!("Failed to run post_all_optimize for {generator:?}"))
456            })?;
457        }
458        Ok(changed)
459    }
460}
461impl Generator for Box<dyn Generator + 'static> {
462    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
463        (**self).pre_vfs(module, ctx)
464    }
465
466    fn pre_target(
467        &mut self,
468        module: &mut walrus::Module,
469        ctx: &GeneratorCtx,
470        external: &ModuleExternal,
471    ) -> eyre::Result<()> {
472        (**self).pre_target(module, ctx, external)
473    }
474
475    fn post_combine(
476        &mut self,
477        module: &mut walrus::Module,
478        ctx: &GeneratorCtx,
479    ) -> eyre::Result<()> {
480        (**self).post_combine(module, ctx)
481    }
482
483    fn post_lower_memory(
484        &mut self,
485        module: &mut walrus::Module,
486        ctx: &GeneratorCtx,
487    ) -> eyre::Result<()> {
488        (**self).post_lower_memory(module, ctx)
489    }
490
491    fn post_components(
492        &mut self,
493        module: &mut walrus::Module,
494        ctx: &ComponentCtx,
495    ) -> eyre::Result<()> {
496        (**self).post_components(module, ctx)
497    }
498
499    fn post_all_optimize(
500        &mut self,
501        module: &mut walrus::Module,
502        ctx: &ComponentCtx,
503    ) -> eyre::Result<bool> {
504        (**self).post_all_optimize(module, ctx)
505    }
506}
507impl<'a> Generator for &'a mut (dyn Generator + 'a) {
508    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
509        (**self).pre_vfs(module, ctx)
510    }
511
512    fn pre_target(
513        &mut self,
514        module: &mut walrus::Module,
515        ctx: &GeneratorCtx,
516        external: &ModuleExternal,
517    ) -> eyre::Result<()> {
518        (**self).pre_target(module, ctx, external)
519    }
520
521    fn post_combine(
522        &mut self,
523        module: &mut walrus::Module,
524        ctx: &GeneratorCtx,
525    ) -> eyre::Result<()> {
526        (**self).post_combine(module, ctx)
527    }
528
529    fn post_lower_memory(
530        &mut self,
531        module: &mut walrus::Module,
532        ctx: &GeneratorCtx,
533    ) -> eyre::Result<()> {
534        (**self).post_lower_memory(module, ctx)
535    }
536
537    fn post_components(
538        &mut self,
539        module: &mut walrus::Module,
540        ctx: &ComponentCtx,
541    ) -> eyre::Result<()> {
542        (**self).post_components(module, ctx)
543    }
544
545    fn post_all_optimize(
546        &mut self,
547        module: &mut walrus::Module,
548        ctx: &ComponentCtx,
549    ) -> eyre::Result<bool> {
550        (**self).post_all_optimize(module, ctx)
551    }
552}
553
554/// Stores the identity of an external loaded Wasm target.
555#[derive(Debug)]
556pub struct ModuleExternal {
557    /// The name of the external module.
558    pub name: WasmName,
559}
560
561impl ModuleExternal {
562    /// Creates a new `ModuleExternal` with the specified name.
563    pub fn new(name: &WasmName) -> Self {
564        Self { name: name.clone() }
565    }
566}
567
568/// Coordinates iterating over registered generators and merging external module logic into the VFS.
569#[derive(Debug)]
570pub struct GeneratorRunner {
571    /// The checkers used to validate the module.
572    pub checkers: Vec<Box<dyn Generator + 'static>>,
573    /// The generators used to transform the module.
574    pub generators: Vec<Box<dyn Generator + 'static>>,
575    /// The context used during generation.
576    pub ctx: GeneratorCtx,
577    /// The path to the WASM module.
578    pub path: WasmPath,
579    /// The paths to the target WASM modules.
580    pub targets: Box<[WasmPath]>,
581    /// Options for building the VFS module.
582    pub vfs_build_opts: args::VfsBuildOptions,
583    /// Options for building the target WASM modules.
584    pub target_vfs_build_opts: Box<[args::VfsBuildOptions]>,
585    /// The TOML restorers used to reset configuration files.
586    pub toml_restorers: Option<TomlRestorers>,
587    /// Memory hints for the target modules.
588    pub memory_hint: HashMap<WasmName, usize>,
589    /// Holder for the names of the WASM modules.
590    pub wasm_name_holder: WasmNameHolder,
591}
592
593/// A runner that coordinates the generation of a WebAssembly component.
594#[derive(Debug)]
595pub struct ComponentRunner {
596    /// The generators used to transform the component.
597    pub generators: Vec<Box<dyn Generator + 'static>>,
598    /// Encapsulates contextual settings across all generator components during transpilation.
599    pub ctx: Option<ComponentCtx>,
600    /// Specifies the target active WASM module destination.
601    pub path: WasmPath,
602    /// Manages dynamically generated and globally referenced named functions.
603    pub wasm_name_holder: Option<WasmNameHolder>,
604}
605
606pub(crate) trait WrapRunner<T> {
607    #[allow(unused_variables)]
608    fn wrap_run(
609        self,
610        path: &mut WasmPath,
611        dwarf: bool,
612        keep_build_artifacts: bool,
613    ) -> eyre::Result<T>
614    where
615        Self: Sized;
616}
617
618impl<T, F: FnOnce(&mut walrus::Module) -> eyre::Result<T>> WrapRunner<T> for F {
619    fn wrap_run(
620        self,
621        path: &mut WasmPath,
622        dwarf: bool,
623        keep_build_artifacts: bool,
624    ) -> eyre::Result<T> {
625        let old_path = path.path()?.clone();
626        let module =
627            &mut walrus::Module::load(&old_path, dwarf).wrap_err("Failed to load Wasm module")?;
628
629        let result = (self)(module)?;
630
631        let new_path = old_path.with_extension("adjusted.wasm");
632
633        if fs::metadata(&new_path).is_ok() {
634            fs::remove_file(&new_path)
635                .wrap_err_with(|| format!("Failed to remove existing file {new_path}"))?;
636        }
637
638        module
639            .emit_wasm_file(&new_path)
640            .to_eyre()
641            .wrap_err_with(|| format!("Failed to write adjusted Wasm to {new_path}"))?;
642
643        if !keep_build_artifacts && !path.is_original(&old_path) {
644            std::fs::remove_file(&old_path)
645                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
646        }
647
648        path.set_path(new_path)?;
649
650        Ok(result)
651    }
652}
653
654pub(crate) trait EndWithOpt<T> {
655    #[allow(unused_variables)]
656    fn with_opt(
657        self,
658        path: &mut WasmPath,
659        dwarf: bool,
660        keep_build_artifacts: bool,
661        skip_opt: bool,
662    ) -> eyre::Result<T>
663    where
664        Self: Sized;
665
666    #[allow(dead_code)]
667    fn with_opt_args(
668        self,
669        path: &mut WasmPath,
670        args: &[&str],
671        require_update: bool,
672        dwarf: bool,
673        keep_build_artifacts: bool,
674        skip_opt: bool,
675    ) -> eyre::Result<T>
676    where
677        Self: Sized;
678}
679
680impl<T, F: FnOnce(&mut WasmPath) -> eyre::Result<T>> EndWithOpt<T> for F {
681    fn with_opt(
682        self,
683        path: &mut WasmPath,
684        dwarf: bool,
685        keep_build_artifacts: bool,
686        skip_opt: bool,
687    ) -> eyre::Result<T>
688    where
689        Self: Sized,
690    {
691        let result = (self)(path).wrap_err("Failed to run with with_opt")?;
692
693        if skip_opt {
694            println!("Skipping Wasm optimization...");
695            return Ok(result);
696        }
697
698        println!("Optimizing Wasm...");
699        let old_path = path.path()?.clone();
700        let new_path = compile::optimize_wasm(&old_path, &[], false, dwarf)
701            .wrap_err("Failed to optimize Wasm")?;
702
703        if !keep_build_artifacts && old_path != new_path && !path.is_original(&old_path) {
704            std::fs::remove_file(&old_path)
705                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
706        }
707
708        path.set_path(new_path)?;
709
710        Ok(result)
711    }
712
713    fn with_opt_args(
714        self,
715        path: &mut WasmPath,
716        args: &[&str],
717        require_update: bool,
718        dwarf: bool,
719        keep_build_artifacts: bool,
720        skip_opt: bool,
721    ) -> eyre::Result<T>
722    where
723        Self: Sized,
724    {
725        let result = (self)(path).wrap_err("Failed to run with with_opt_args")?;
726
727        if skip_opt {
728            println!("Skipping Wasm optimization...");
729            return Ok(result);
730        }
731
732        println!("Optimizing Wasm... with args: {}", args.iter().join(" "));
733        let old_path = path.path()?.clone();
734        let new_path = compile::optimize_wasm(&old_path, args, require_update, dwarf)
735            .wrap_err("Failed to optimize Wasm")?;
736
737        if !keep_build_artifacts && old_path != new_path && !path.is_original(&old_path) {
738            std::fs::remove_file(&old_path)
739                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
740        }
741
742        path.set_path(new_path)?;
743
744        Ok(result)
745    }
746}
747
748impl GeneratorRunner {
749    /// Initializes a `GeneratorRunner` capturing all parameters needed for complete application-level transpilation mapping.
750    pub fn new(
751        path: WasmPath,
752        targets: Box<[WasmPath]>,
753        threads: bool,
754        dwarf: bool,
755        unstable_print_debug: bool,
756        adjust_abi: bool,
757        keep_build_artifacts: bool,
758        memory_type: TargetMemoryType,
759        vfs_build_opts: args::VfsBuildOptions,
760        target_vfs_build_opts: Box<[args::VfsBuildOptions]>,
761        toml_restorers: TomlRestorers,
762        memory_hint: Box<[Option<usize>]>,
763    ) -> eyre::Result<Self> {
764        let target_names_with_self = core::iter::once(Ok(path.name()?.to_compact_string()))
765            .chain(targets.iter().map(|t| Ok(t.name()?.to_compact_string())))
766            .collect::<eyre::Result<Box<_>>>()?;
767
768        let wasm_name_holder = WasmNameHolder::new(target_names_with_self);
769        let mut wasm_name_holder_iter = wasm_name_holder.iter();
770        let vfs_name = wasm_name_holder_iter
771            .next()
772            .ok_or_else(|| eyre::eyre!("Failed to get VFS name"))?;
773
774        let target_names = wasm_name_holder_iter.collect::<Box<_>>();
775
776        let starts = starts::FnInStarts::new(&target_names);
777
778        // log targeting info
779        for name in target_names.iter() {
780            log::info!("Targeting module: {name}");
781        }
782        log::info!("VFS module: {vfs_name}");
783
784        let target_names_with_self = target_names
785            .iter()
786            .cloned()
787            .chain(core::iter::once(vfs_name.clone()))
788            .collect::<Box<_>>();
789
790        let memory_hint = memory_hint
791            .into_iter()
792            .zip(target_names.iter().cloned())
793            .filter_map(|(hint, name)| hint.map(|h| (name, h)))
794            .collect::<HashMap<_, _>>();
795
796        Ok(Self {
797            checkers: Vec::new(),
798            generators: Vec::new(),
799            ctx: GeneratorCtx {
800                vfs_name,
801                target_names,
802                target_names_with_self,
803                target_memory_type: memory_type,
804                unstable_print_debug,
805                dwarf,
806                threads,
807                adjust_abi,
808                keep_build_artifacts,
809                vfs_used_memory_id: None,
810                vfs_used_global_id: None,
811                target_used_memory_id: None,
812                target_used_global_id: None,
813                start_func_id: None,
814                vfs_is_library: false,
815                starts,
816            },
817            path,
818            targets,
819            vfs_build_opts,
820            target_vfs_build_opts,
821            toml_restorers: Some(toml_restorers),
822            memory_hint,
823            wasm_name_holder,
824        })
825    }
826
827    /// Registers a custom generator to be applied sequentially during transformation phases.
828    pub fn add_generator<G: Generator + 'static>(&mut self, generator: G) {
829        self.generators.push(Box::new(generator));
830    }
831
832    /// Registers a diagnostic validation checker resolving pre or post-conditions automatically.
833    pub fn checker(&mut self, checker: impl Generator + 'static) {
834        self.checkers.push(Box::new(checker));
835    }
836
837    /// Resolves and retrieves a shared reference to a specific structured generator dynamically at runtime.
838    pub fn get_generator_ref<T: Generator + 'static>(&self) -> eyre::Result<&T> {
839        fn downcast_ref<T: 'static>(b: &dyn Any) -> Option<&'_ T> {
840            if b.is::<T>() {
841                Some(b.downcast_ref::<T>().unwrap())
842            } else {
843                None
844            }
845        }
846
847        self.generators
848            .iter()
849            .map(|g| g.as_ref())
850            .find_map(|g| downcast_ref::<T>(g))
851            .wrap_err_with(|| {
852                eyre::eyre!("Failed to get generator: {}", core::any::type_name::<T>())
853            })
854            .wrap_err_with(|| eyre::eyre!("Available generators: {:?}", self.generators))
855    }
856
857    #[deprecated(
858        note = "Ensure this function is self-contained. This is a temporary measure for debugging purposes."
859    )]
860    /// Provides direct immutable access tracking the primary target structural path configuration.
861    pub const fn path(&self) -> &WasmPath {
862        &self.path
863    }
864
865    #[deprecated(
866        note = "Ensure this function is self-contained. This is a temporary measure for debugging purposes."
867    )]
868    /// Directly evaluates currently linked ancillary wasm dependencies.
869    pub const fn targets(&self) -> &Box<[WasmPath]> {
870        &self.targets
871    }
872
873    /// Securely uncovers operational variables tracking internal generational properties dynamically.
874    pub const fn ctx(&self) -> &GeneratorCtx {
875        &self.ctx
876    }
877
878    /// Confirms mapping configurations and statically evaluates lazy initializations strictly allocating paths.
879    pub fn definitely(&mut self) -> eyre::Result<()> {
880        self.path
881            .definitely(self.ctx.threads, &self.vfs_build_opts)?;
882        for (i, target) in self.targets.iter_mut().enumerate() {
883            target.definitely(self.ctx.threads, &self.target_vfs_build_opts[i])?;
884        }
885        Ok(())
886    }
887
888    /// Primary operation chaining logic seamlessly running structural modifiers across all layered stages sequentially terminating out into WebAssembly components.
889    pub fn run_layers_to_component(
890        mut self,
891        out_dir: &Utf8PathBuf,
892        keep_build_artifacts: bool,
893    ) -> eyre::Result<ComponentRunner> {
894        self.definitely()?;
895
896        let toml_restorers = self
897            .toml_restorers
898            .take()
899            .ok_or_else(|| eyre::eyre!("TomlRestorers already taken"))?;
900
901        toml_restorers
902            .restore()
903            .wrap_err("Failed to restore toml files")?;
904
905        let mut mem_id_visitor = MemoryIDVisitor {
906            memory_hint: self.memory_hint.clone(),
907            used_vfs_memory_id: None,
908            used_target_memory_id: None,
909        };
910        let mut global_id_visitor = GlobalIdVisitor {
911            vfs_global_id: None,
912            global_id: None,
913        };
914        let dwarf = self.ctx.dwarf;
915
916        println!("Remove existing output directory...");
917        if std::fs::metadata(&out_dir).is_ok() {
918            std::fs::remove_dir_all(&out_dir).expect("Failed to remove existing directory");
919        }
920        std::fs::create_dir_all(&out_dir).expect("Failed to create output directory");
921
922        let mut component_ctx_visitor = ComponentCtxVisitor::new(
923            self.ctx.vfs_name.clone(),
924            self.ctx.target_names.clone(),
925            self.ctx.target_memory_type,
926            self.ctx.unstable_print_debug,
927            self.ctx.dwarf,
928            self.ctx.threads,
929            self.ctx.adjust_abi,
930        );
931
932        println!("Adjusting VFS Wasm...");
933        let skip_vfs_opt = self.vfs_build_opts.no_opt > 0 || self.vfs_build_opts.no_opt_all > 0;
934        (|path: &mut WasmPath| {
935            (|module: &mut walrus::Module| {
936                self.checkers
937                    .pre_vfs(module, &self.ctx)
938                    .wrap_err("Failed to run checkers in pre_vfs")?;
939
940                mem_id_visitor
941                    .pre_vfs(module, &self.ctx)
942                    .wrap_err("Failed in pre_vfs")?;
943                global_id_visitor
944                    .pre_vfs(module, &self.ctx)
945                    .wrap_err("Failed in pre_vfs")?;
946
947                self.ctx.vfs_used_memory_id = mem_id_visitor.used_vfs_memory_id;
948
949                // Detect VFS library mode: if the VFS module has no start section,
950                // it is a library and has no initialization entry point.
951                self.ctx.vfs_is_library = module.start.is_none();
952                if self.ctx.vfs_is_library {
953                    log::info!(
954                        "VFS module `{}` has no start section — treating as a library.",
955                        self.ctx.vfs_name
956                    );
957                }
958
959                component_ctx_visitor
960                    .pre_vfs(module, &self.ctx)
961                    .wrap_err("Failed in pre_vfs")?;
962
963                self.generators
964                    .pre_vfs(module, &self.ctx)
965                    .wrap_err("Failed in run_pre_vfs")
966            })
967            .wrap_run(path, dwarf, keep_build_artifacts)
968        })
969        .with_opt(&mut self.path, dwarf, keep_build_artifacts, skip_vfs_opt)?;
970
971        println!("Adjusting target Wasm...");
972        self.ctx.vfs_used_memory_id = None;
973        for (i, (target, target_name)) in self.targets.iter_mut().zip(self.ctx.target_names.clone()).enumerate() {
974            let skip_target_opt = self.vfs_build_opts.no_opt_all > 0 || self.target_vfs_build_opts[i].no_opt > 0 || self.target_vfs_build_opts[i].no_opt_all > 0;
975            (|path: &mut WasmPath| {
976                (|module: &mut walrus::Module| {
977                    let external = ModuleExternal::new(&target_name);
978                    mem_id_visitor
979                        .pre_target(module, &self.ctx, &external)
980                        .wrap_err("Failed in pre_target")?;
981                    global_id_visitor
982                        .pre_target(module, &self.ctx, &external)
983                        .wrap_err("Failed in pre_target")?;
984
985                    self.ctx.target_used_memory_id = mem_id_visitor.used_target_memory_id.clone();
986
987                    self.generators
988                        .pre_target(module, &self.ctx, &external)
989                        .wrap_err("Failed in run_pre_target")
990                })
991                .wrap_run(path, dwarf, keep_build_artifacts)
992            })
993            .with_opt(target, dwarf, keep_build_artifacts, skip_target_opt)?;
994        }
995
996        let skip_all_opt = self.vfs_build_opts.no_opt_all > 0
997            || self.target_vfs_build_opts.iter().any(|opts| opts.no_opt_all > 0);
998
999        println!("Combining Wasm modules...");
1000        self.ctx.vfs_used_memory_id = None;
1001        self.ctx.target_used_memory_id = None;
1002        let output = format!("{out_dir}/merged.wasm");
1003        (|path: &mut WasmPath| {
1004            let old_path = path.path()?.clone();
1005            merge(
1006                &old_path,
1007                &self
1008                    .targets
1009                    .iter()
1010                    .map(|t| t.path())
1011                    .collect::<eyre::Result<Vec<_>>>()?,
1012                &output,
1013                self.ctx.threads,
1014                dwarf,
1015            )
1016            .wrap_err("Failed to combine Wasm modules")?;
1017
1018            if !keep_build_artifacts {
1019                std::fs::remove_file(&old_path)
1020                    .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
1021                for target in self.targets.iter() {
1022                    if let Ok(target_path) = target.path() {
1023                        if !target.is_original(target_path) {
1024                            std::fs::remove_file(target_path).unwrap_or_else(|e| {
1025                                log::warn!(
1026                                    "Failed to remove intermediate target file {target_path}: {e}"
1027                                );
1028                            });
1029                        }
1030                    }
1031                }
1032            }
1033
1034            path.set_path(output.into())
1035        })
1036        .with_opt(&mut self.path, dwarf, keep_build_artifacts, skip_all_opt)?;
1037
1038        println!("Adjusting Merged Wasm...");
1039        (|path: &mut WasmPath| {
1040            (|module: &mut walrus::Module| {
1041                mem_id_visitor
1042                    .post_combine(module, &self.ctx)
1043                    .wrap_err("Failed in post_combine")?;
1044                global_id_visitor
1045                    .post_combine(module, &self.ctx)
1046                    .wrap_err("Failed in post_combine")?;
1047                let mut start_func_id_visitor = StartFuncIdVisitor::default();
1048                start_func_id_visitor
1049                    .post_combine(module, &self.ctx)
1050                    .wrap_err("Failed in post_combine")?;
1051
1052                self.ctx.vfs_used_memory_id = mem_id_visitor.used_vfs_memory_id.take();
1053                self.ctx.target_used_memory_id = mem_id_visitor.used_target_memory_id.take();
1054
1055                self.ctx.vfs_used_global_id = global_id_visitor.vfs_global_id.take();
1056                self.ctx.target_used_global_id = global_id_visitor.global_id.take();
1057
1058                self.ctx.start_func_id = start_func_id_visitor.start_func_id.take();
1059
1060                self.generators.post_combine(module, &self.ctx)?;
1061
1062                Ok(())
1063            })
1064            .wrap_run(path, dwarf, keep_build_artifacts)
1065        })
1066        .with_opt(&mut self.path, dwarf, keep_build_artifacts, skip_all_opt)?;
1067
1068        self.ctx.vfs_used_memory_id = None;
1069        self.ctx.target_used_memory_id = None;
1070
1071        self.ctx.vfs_used_global_id = None;
1072        self.ctx.target_used_global_id = None;
1073
1074        self.ctx.start_func_id = None;
1075
1076        if self.ctx.target_memory_type == TargetMemoryType::Single {
1077            println!("Generating single memory Merged Wasm (walrus lowering)...");
1078
1079            (|path: &mut WasmPath| {
1080                (|module: &mut walrus::Module| {
1081                    // Run walrus-based multi-memory lowering
1082                    let mut mml = multi_memory_lowering::MultiMemoryLowering::new();
1083                    mml.lower_memory(module, &self.ctx)
1084                        .wrap_err("Failed in MultiMemoryLowering")?;
1085
1086                    mem_id_visitor
1087                        .post_lower_memory(module, &self.ctx)
1088                        .wrap_err("Failed in post_lower_memory")?;
1089
1090                    self.ctx.vfs_used_memory_id = mem_id_visitor.used_vfs_memory_id.take();
1091                    self.ctx.target_used_memory_id = mem_id_visitor.used_target_memory_id.take();
1092
1093                    self.generators
1094                        .post_lower_memory(module, &self.ctx)
1095                        .wrap_err("Failed in run_post_lower_memory")?;
1096
1097                    Ok(())
1098                })
1099                .wrap_run(path, dwarf, keep_build_artifacts)
1100            })
1101            .with_opt(&mut self.path, dwarf, keep_build_artifacts, skip_all_opt)?;
1102        }
1103
1104        println!("Translating Wasm to Component...");
1105        let old_path = self.path.path()?.clone();
1106        let component = compile::wasm_to_component(&old_path, &self.ctx.target_names)
1107            .wrap_err("Failed to translate Wasm to Component")?;
1108        if !keep_build_artifacts {
1109            std::fs::remove_file(&old_path)
1110                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
1111        }
1112
1113        let new_component = format!("{out_dir}/{}.component.wasm", self.ctx.vfs_name);
1114        std::fs::rename(&component, &new_component)
1115            .wrap_err_with(|| format!("Failed to rename file {component} to {new_component}"))?;
1116
1117        self.path.set_path(Utf8PathBuf::from(new_component))?;
1118
1119        Ok(ComponentRunner::with_generators(self.path, self.generators))
1120    }
1121}
1122
1123impl ComponentRunner {
1124    /// Instantiates a fresh `ComponentRunner` targeting a specific underlying WebAssembly structure.
1125    pub fn new(path: WasmPath) -> Self {
1126        Self {
1127            generators: Vec::new(),
1128            ctx: None,
1129            path,
1130            wasm_name_holder: None,
1131        }
1132    }
1133
1134    /// Installs a specific invariant-checking generator executing without altering primary execution pathways.
1135    pub fn checker(&mut self, checker: impl Generator + 'static) {
1136        self.generators.push(Box::new(checker));
1137    }
1138
1139    /// Quickly constructs a runner wrapping a pre-defined array containing generator strategies.
1140    pub fn with_generators(path: WasmPath, generators: Vec<Box<dyn Generator + 'static>>) -> Self {
1141        Self {
1142            generators,
1143            ctx: None,
1144            path,
1145            wasm_name_holder: None,
1146        }
1147    }
1148
1149    /// Queues an advanced generative instruction step executed successively upon evaluation.
1150    pub fn add_generator<G: Generator + 'static>(&mut self, generator: G) {
1151        self.generators.push(Box::new(generator));
1152    }
1153
1154    /// Allows querying the internal generator stack dynamically retrieving explicitly modeled type structures.
1155    pub fn get_generator_ref<T: Generator + 'static>(&self) -> eyre::Result<&T> {
1156        fn downcast_ref<T: 'static>(b: &dyn Any) -> Option<&'_ T> {
1157            if b.is::<T>() {
1158                Some(b.downcast_ref::<T>().unwrap())
1159            } else {
1160                None
1161            }
1162        }
1163
1164        self.generators
1165            .iter()
1166            .map(|g| g.as_ref())
1167            .find_map(|g| downcast_ref::<T>(g))
1168            .wrap_err_with(|| {
1169                eyre::eyre!("Failed to get generator: {}", core::any::type_name::<T>())
1170            })
1171            .wrap_err_with(|| eyre::eyre!("Available generators: {:?}", self.generators))
1172    }
1173
1174    /// return is_threads, core_name, mem_size
1175    pub fn component_to_files(
1176        &mut self,
1177        parsed_args: &(impl args::PostBuildContext + ?Sized),
1178        dwarf: bool,
1179        only_core: bool,
1180    ) -> eyre::Result<(bool, CompactString, HashMap<CompactString, (u64, u64)>)> {
1181        let out_dir = parsed_args.out_dir();
1182
1183        let name = self.path.name()?;
1184
1185        println!("Translating Component to JS...");
1186        let core_wasm_path = (|path: &mut WasmPath| {
1187            let old_path = path.path()?.clone();
1188            let binary = std::fs::read(&old_path).wrap_err("Failed to read component")?;
1189            let transpiled = parsed_args
1190                .transpile_to_js(&binary, &name)
1191                .wrap_err("Failed to transpile to JS")?;
1192
1193            let mut core_wasm = None;
1194            for (name, data) in transpiled.files.iter() {
1195                let name = camino::Utf8PathBuf::from(name);
1196                let file_name = out_dir.join(&name);
1197                if std::fs::metadata(&file_name).is_ok() {
1198                    std::fs::remove_file(&file_name).wrap_err_with(|| {
1199                        eyre::eyre!("Failed to remove existing file: {file_name}")
1200                    })?;
1201                }
1202                if name.as_str().ends_with(".core.wasm") {
1203                    let file_name = camino::Utf8PathBuf::from(file_name);
1204                    std::fs::write(&file_name, &data).wrap_err_with(|| {
1205                        eyre::eyre!("Failed to write core wasm file: {file_name}")
1206                    })?;
1207                    core_wasm = Some(file_name);
1208                } else {
1209                    if let Some(parent) = name.parent() {
1210                        if !parent.as_str().is_empty() {
1211                            let dir = name.ancestors().nth(1).wrap_err_with(|| {
1212                                eyre::eyre!("Failed to get parent directory: {}", name)
1213                            })?;
1214                            let joined_dir = out_dir.join(dir);
1215                            if !std::fs::metadata(&joined_dir).is_ok() {
1216                                if dir.as_str() != "interfaces" {
1217                                    log::warn!("Creating directory: {joined_dir}");
1218                                }
1219                                if only_core {
1220                                    continue;
1221                                }
1222                                std::fs::create_dir_all(&joined_dir).wrap_err_with(|| {
1223                                    eyre::eyre!("Failed to create directory: {joined_dir}")
1224                                })?;
1225                            }
1226                        }
1227                    }
1228                    if only_core {
1229                        continue;
1230                    }
1231                    std::fs::write(&file_name, &data).wrap_err_with(|| {
1232                        eyre::eyre!("Failed to write transpiled file: {file_name}")
1233                    })?;
1234                }
1235            }
1236
1237            let core_wasm = core_wasm
1238                .as_ref()
1239                .ok_or_else(|| eyre::eyre!("Failed to find core wasm"))?;
1240
1241            if !parsed_args.keep_build_artifacts() {
1242                std::fs::remove_file(&old_path)
1243                    .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
1244            }
1245            path.set_path(core_wasm.clone())?;
1246
1247            Ok(core_wasm.clone())
1248        })
1249        .with_opt(&mut self.path, dwarf, parsed_args.keep_build_artifacts(), parsed_args.dev())?;
1250
1251        let mem_size_visitor = MemorySizeVisitor::default();
1252        self.generators.push(Box::new(mem_size_visitor));
1253
1254        println!("Adjusting component Merged Wasm...");
1255        (|path: &mut WasmPath| {
1256            (|module: &mut walrus::Module| {
1257                let mut visitor = ComponentCtxVisitor::default();
1258                visitor
1259                    .post_components(
1260                        module,
1261                        &ComponentCtx {
1262                            dwarf,
1263                            ..Default::default()
1264                        },
1265                    )
1266                    .wrap_err("Failed in post_components")?;
1267                let wasm_name_holder = WasmNameHolder::new(
1268                    visitor
1269                        .target_names
1270                        .unwrap()
1271                        .into_iter()
1272                        .chain(core::iter::once(visitor.vfs_name.unwrap()))
1273                        .collect::<Box<_>>(),
1274                );
1275                self.wasm_name_holder = Some(wasm_name_holder);
1276                let mut wasm_name_holder_iter = self.wasm_name_holder.as_ref().unwrap().iter();
1277                self.ctx = Some(ComponentCtx {
1278                    vfs_name: Some(wasm_name_holder_iter.next().unwrap()),
1279                    target_names: Some(wasm_name_holder_iter.collect::<Box<_>>()),
1280                    target_memory_type: Some(visitor.target_memory_type.unwrap()),
1281                    unstable_print_debug: Some(visitor.unstable_print_debug.unwrap()),
1282                    dwarf: visitor.dwarf.unwrap(),
1283                    threads: Some(visitor.threads.unwrap()),
1284                    adjust_abi: visitor.adjust_abi,
1285                });
1286
1287                self.generators
1288                    .post_components(module, self.ctx.as_ref().unwrap())
1289                    .wrap_err("Failed in run_post_components")
1290            })
1291            .wrap_run(path, dwarf, parsed_args.keep_build_artifacts())
1292        })
1293        .with_opt(&mut self.path, dwarf, parsed_args.keep_build_artifacts(), parsed_args.dev())?;
1294
1295        let dwarf = {
1296            let new_dwarf = self.ctx.as_ref().unwrap().dwarf;
1297            if dwarf && !new_dwarf {
1298                log::warn!(
1299                    "Dwarf was disabled in component processing, you should re-run with --dwarf"
1300                );
1301            }
1302            new_dwarf
1303        };
1304
1305        println!("Final optimizing Merged Wasm...");
1306        let mut i = 0;
1307        while i < self.generators.len() {
1308            (|module: &mut walrus::Module| {
1309                loop {
1310                    if self.generators[i]
1311                        .post_all_optimize(module, self.ctx.as_ref().unwrap())
1312                        .wrap_err("Failed in post_all_optimize")?
1313                    {
1314                        i += 1;
1315                        return Ok(());
1316                    }
1317                    i += 1;
1318                    if i >= self.generators.len() {
1319                        return Ok(());
1320                    }
1321                }
1322            })
1323            .wrap_run(&mut self.path, dwarf, parsed_args.keep_build_artifacts())?;
1324        }
1325
1326        std::fs::rename(self.path.path()?, &core_wasm_path).wrap_err_with(|| {
1327            eyre::eyre!(
1328                "Failed to rename final wasm from {} to {}",
1329                self.path.path().unwrap(),
1330                core_wasm_path
1331            )
1332        })?;
1333
1334        Ok((
1335            self.ctx.as_ref().unwrap().threads(),
1336            core_wasm_path
1337                .get_file_main_name()
1338                .ok_or_else(|| eyre::eyre!("Failed to get file name"))?,
1339            self.get_generator_ref::<MemorySizeVisitor>()?
1340                .mem_size
1341                .clone()
1342                .unwrap(),
1343        ))
1344    }
1345}
1346
1347#[derive(Debug, Default, Clone)]
1348struct MemoryIDVisitor {
1349    pub memory_hint: HashMap<WasmName, usize>,
1350    pub used_vfs_memory_id: Option<MemoryId>,
1351    pub used_target_memory_id: Option<HashMap<WasmName, MemoryId>>,
1352}
1353
1354impl Generator for MemoryIDVisitor {
1355    fn pre_vfs(
1356        &mut self,
1357        module: &mut walrus::Module,
1358        _: &crate::generator::GeneratorCtx,
1359    ) -> eyre::Result<()> {
1360        println!("Finding VFS memory id...");
1361
1362        let id = module
1363            .get_memory_anchor("vfs", false)
1364            .wrap_err("Failed to get target memory id")?;
1365        self.used_vfs_memory_id = Some(id);
1366        Ok(())
1367    }
1368
1369    fn pre_target(
1370        &mut self,
1371        module: &mut walrus::Module,
1372        _: &crate::generator::GeneratorCtx,
1373        external: &ModuleExternal,
1374    ) -> eyre::Result<()> {
1375        let id = module
1376            .find_used_memory_id(self.memory_hint.get(&external.name).copied())
1377            .wrap_err("Failed to find used memory id")?;
1378        module
1379            .create_memory_anchor(&external.name, id)
1380            .wrap_err("Failed to create memory anchor")?;
1381        self.used_target_memory_id
1382            .get_or_insert_default()
1383            .insert(external.name.clone(), id);
1384        Ok(())
1385    }
1386
1387    fn post_combine(
1388        &mut self,
1389        module: &mut walrus::Module,
1390        ctx: &GeneratorCtx,
1391    ) -> eyre::Result<()> {
1392        let id = module
1393            .get_memory_anchor("vfs", true)
1394            .wrap_err("Failed to find used memory id after combine")?;
1395        self.used_vfs_memory_id = Some(id);
1396
1397        self.used_target_memory_id.get_or_insert_default().clear();
1398        for wasm in &ctx.target_names {
1399            let id = module
1400                .get_memory_anchor(wasm, true)
1401                .wrap_err("Failed to find used memory id after combine")?;
1402            self.used_target_memory_id
1403                .as_mut()
1404                .unwrap()
1405                .insert(wasm.clone(), id);
1406        }
1407
1408        Ok(())
1409    }
1410
1411    fn post_lower_memory(
1412        &mut self,
1413        module: &mut walrus::Module,
1414        _: &GeneratorCtx,
1415    ) -> eyre::Result<()> {
1416        let id = module
1417            .get_memory_id()
1418            .to_eyre()
1419            .wrap_err("Failed to get single memory id after lowering")?;
1420        self.used_vfs_memory_id = Some(id);
1421        self.used_target_memory_id = None;
1422
1423        Ok(())
1424    }
1425}
1426
1427#[derive(Debug, Default, Clone)]
1428struct MemorySizeVisitor {
1429    mem_size: Option<HashMap<CompactString, (u64, u64)>>,
1430}
1431
1432impl Generator for MemorySizeVisitor {
1433    fn post_components(
1434        &mut self,
1435        module: &mut walrus::Module,
1436        _: &ComponentCtx,
1437    ) -> eyre::Result<()> {
1438        let mem_size = module
1439            .memories
1440            .iter()
1441            .filter(|mem| mem.import.is_some())
1442            .map(|mem| {
1443                (
1444                    module
1445                        .imports
1446                        .get(mem.import.unwrap())
1447                        .name
1448                        .to_compact_string(),
1449                    (
1450                        mem.initial as u64,
1451                        mem.maximum.unwrap_or(mem.initial) as u64,
1452                    ),
1453                )
1454            })
1455            .collect::<HashMap<_, _>>();
1456        self.mem_size = Some(mem_size);
1457
1458        Ok(())
1459    }
1460}
1461
1462#[derive(Debug, Default)]
1463struct GlobalIdVisitor {
1464    vfs_global_id: Option<Box<[walrus::GlobalId]>>,
1465    global_id: Option<HashMap<WasmName, Box<[walrus::GlobalId]>>>,
1466}
1467impl Generator for GlobalIdVisitor {
1468    fn pre_vfs(&mut self, module: &mut walrus::Module, _: &GeneratorCtx) -> eyre::Result<()> {
1469        module
1470            .create_global_anchor("vfs")
1471            .wrap_err("Failed to create global anchor")?;
1472
1473        Ok(())
1474    }
1475
1476    fn pre_target(
1477        &mut self,
1478        module: &mut walrus::Module,
1479        _: &GeneratorCtx,
1480        external: &ModuleExternal,
1481    ) -> eyre::Result<()> {
1482        module
1483            .create_global_anchor(&external.name)
1484            .wrap_err("Failed to create global anchor")?;
1485
1486        Ok(())
1487    }
1488
1489    fn post_combine(
1490        &mut self,
1491        module: &mut walrus::Module,
1492        ctx: &GeneratorCtx,
1493    ) -> eyre::Result<()> {
1494        self.global_id = Some(HashMap::new());
1495
1496        let vfs_globals = module
1497            .get_global_anchor("vfs")
1498            .wrap_err("Failed to get global anchor for vfs")?;
1499        self.vfs_global_id = Some(vfs_globals);
1500
1501        for wasm in &ctx.target_names {
1502            let globals = module
1503                .get_global_anchor(wasm)
1504                .wrap_err_with(|| format!("Failed to get global anchor for {wasm}"))?;
1505            self.global_id
1506                .as_mut()
1507                .unwrap()
1508                .insert(wasm.clone(), globals);
1509        }
1510
1511        Ok(())
1512    }
1513}
1514
1515/// To be used from both `special_func`'s `main_void` and `start`,
1516/// it must be prepared in `ctx`.
1517#[derive(Debug, Default)]
1518struct StartFuncIdVisitor {
1519    start_func_id: Option<HashMap<WasmName, walrus::FunctionId>>,
1520}
1521
1522impl Generator for StartFuncIdVisitor {
1523    fn post_combine(
1524        &mut self,
1525        module: &mut walrus::Module,
1526        ctx: &GeneratorCtx,
1527    ) -> eyre::Result<()> {
1528        for wasm in &ctx.target_names {
1529            // NOTE: wasm-merge preserves the package name with dashes for some exports,
1530            // but the __start_anchor from the Rust macros has underscores.
1531            let normalized_wasm = wasm.as_ref().replace('-', "_");
1532            // let export_name = format!("__wasip1_vfs_{wasm}__start");
1533
1534            let export = format!("__wasip1_vfs_{wasm}__start").get_fid(&module.exports)?;
1535            self.start_func_id
1536                .get_or_insert_default()
1537                .insert(wasm.clone(), export);
1538
1539            // NOTE: Don't erase the __start export - it's needed for StartFunc
1540            // to find it as an import or to redirect calls to it.
1541
1542            // The anchor export was created by import_wasm! macro and uses underscores
1543            module.exports.erase_with(
1544                &format!("__wasip1_vfs_{normalized_wasm}__start_anchor"),
1545                ctx.unstable_print_debug,
1546            )?;
1547        }
1548
1549        Ok(())
1550    }
1551}
1552
1553/// Represents the resolution state and file format targeting for manipulating WebAssembly modules intelligently.
1554#[derive(Debug, Clone, Hash)]
1555pub enum WasmPath {
1556    /// Indicates the target still needs compilation through standard cargo dependencies.
1557    Maybe {
1558        /// Fully resolved physical path to the corresponding Cargo.toml manifest definition.
1559        manifest_path: Utf8PathBuf,
1560        /// Specified internal crate package identifier.
1561        package: String,
1562    },
1563    /// A strictly resolved raw WebAssembly binary file ready for patching operations.
1564    Definitely(Utf8PathBuf),
1565    /// A completed explicitly transpiled WebAssembly Component standard architecture module.
1566    Component(Utf8PathBuf),
1567    /// A user-provided raw WebAssembly binary file that should never be deleted.
1568    /// The inner path tracks the original file location.
1569    Original {
1570        /// The current working path (may change as transformations produce new files).
1571        current: Utf8PathBuf,
1572        /// The original user-provided path that must be preserved.
1573        original: Utf8PathBuf,
1574    },
1575}
1576
1577impl FromStr for WasmPath {
1578    type Err = eyre::Error;
1579
1580    /// manifest_path :: package
1581    fn from_str(s: &str) -> Result<Self, Self::Err> {
1582        fn parse_path_and_package(s: &str) -> eyre::Result<Option<WasmPath>> {
1583            let split = s.split("::").collect::<Vec<_>>();
1584            if split.len() == 2 {
1585                let manifest_path = Utf8PathBuf::from_str(split[0])
1586                    .wrap_err_with(|| format!("Failed to parse manifest path: {}", split[0]))?;
1587                let package = split[1].to_string();
1588                return Ok(Some(WasmPath::Maybe {
1589                    manifest_path,
1590                    package,
1591                }));
1592            }
1593            Ok(None)
1594        }
1595
1596        if let Some(wasm_path) =
1597            parse_path_and_package(s).wrap_err("Failed to parse path and package")?
1598        {
1599            return Ok(wasm_path);
1600        }
1601
1602        if s.ends_with(".wasm") {
1603            let path = Utf8PathBuf::from_str(s)
1604                .wrap_err_with(|| format!("Failed to parse wasm path: {s}"))?;
1605            return WasmPath::with_wasm(path);
1606        }
1607
1608        if s.ends_with("Cargo.toml") {
1609            let manifest_path = Utf8PathBuf::from_str(s)
1610                .wrap_err_with(|| format!("Failed to parse manifest path: {s}"))?;
1611            return WasmPath::with_maybe_only_manifest(manifest_path);
1612        }
1613
1614        WasmPath::with_maybe_only_package(s.to_string())
1615            .wrap_err_with(|| format!("Failed to parse package name: {s}"))
1616    }
1617}
1618
1619impl WasmPath {
1620    /// Computes the unique short name used during module linking and identification.
1621    pub fn name(&self) -> eyre::Result<CompactString> {
1622        match self {
1623            WasmPath::Maybe { package, .. } => {
1624                // Normalize package name by replacing hyphens with underscores
1625                // This is necessary because Rust package names can have hyphens (e.g., "test-package")
1626                // but they are converted to underscores in module identifiers (e.g., "test_package")
1627                let normalized = package.replace('-', "_");
1628                Ok(normalized.to_compact_string())
1629            }
1630            WasmPath::Definitely(path)
1631            | WasmPath::Component(path)
1632            | WasmPath::Original { current: path, .. } => path
1633                .get_file_main_name()
1634                .ok_or_else(|| eyre::eyre!("Failed to get file name from {path}")),
1635        }
1636    }
1637
1638    /// Exposes the manifest path conditionally if the dependency is unresolved logically.
1639    pub fn manifest_path(&self) -> Option<&Utf8PathBuf> {
1640        match self {
1641            WasmPath::Maybe { manifest_path, .. } => Some(manifest_path),
1642            WasmPath::Definitely(_) | WasmPath::Component(_) | WasmPath::Original { .. } => None,
1643        }
1644    }
1645
1646    /// Calculates the overarching workspace root via dependency graphing context implicitly.
1647    pub fn root_manifest_path(&self) -> Option<Utf8PathBuf> {
1648        match self {
1649            WasmPath::Maybe { manifest_path, .. } => {
1650                let cargo_metadata = {
1651                    let mut metadata_command = cargo_metadata::MetadataCommand::new();
1652                    metadata_command.manifest_path(&manifest_path);
1653                    metadata_command.exec().unwrap()
1654                };
1655                Some(cargo_metadata.workspace_root.join("Cargo.toml"))
1656            }
1657            WasmPath::Definitely(_) | WasmPath::Component(_) | WasmPath::Original { .. } => None,
1658        }
1659    }
1660
1661    /// Statically assigns an unresolved target using defined package specifications.
1662    pub const fn with_maybe(manifest_path: Utf8PathBuf, package: String) -> Self {
1663        Self::Maybe {
1664            manifest_path,
1665            package,
1666        }
1667    }
1668
1669    /// Constructs an unresolved dependency resolving package tracking inherently from a file manifest dynamically.
1670    pub fn with_maybe_only_manifest(manifest_path: Utf8PathBuf) -> eyre::Result<Self> {
1671        let cargo_metadata = {
1672            let mut metadata_command = cargo_metadata::MetadataCommand::new();
1673            metadata_command.manifest_path(&manifest_path);
1674            metadata_command.exec().unwrap()
1675        };
1676        let building_crate = compile::get_building_crate(&cargo_metadata, &None)?;
1677
1678        Ok(Self::Maybe {
1679            manifest_path,
1680            package: building_crate.name.to_string(),
1681        })
1682    }
1683
1684    /// Assesses global cargo metadata configuring definitions matching solely the provided string identifier.
1685    pub fn with_maybe_only_package(package: String) -> eyre::Result<Self> {
1686        let cargo_metadata = {
1687            let metadata_command = cargo_metadata::MetadataCommand::new();
1688            metadata_command.exec().unwrap()
1689        };
1690        let building_crate = compile::get_building_crate(&cargo_metadata, &Some(package.clone()))?;
1691
1692        Ok(Self::Maybe {
1693            manifest_path: building_crate.manifest_path,
1694            package: building_crate.name.to_string(),
1695        })
1696    }
1697
1698    /// Loads an unresolved dependency using current environment cargo bounds natively.
1699    pub fn with_maybe_none() -> eyre::Result<Self> {
1700        let cargo_metadata = {
1701            let metadata_command = cargo_metadata::MetadataCommand::new();
1702            metadata_command.exec().unwrap()
1703        };
1704        let building_crate = compile::get_building_crate(&cargo_metadata, &None)?;
1705
1706        Ok(Self::Maybe {
1707            manifest_path: building_crate.manifest_path,
1708            package: building_crate.name.to_string(),
1709        })
1710    }
1711
1712    /// Scans an exact provided `.wasm` artifact verifying magic byte signatures correctly to assign a resolution state.
1713    /// User-provided `.wasm` files are wrapped in `Original` to prevent deletion of the original file.
1714    pub fn with_wasm(path: Utf8PathBuf) -> eyre::Result<Self> {
1715        if path.extension() != Some("wasm") {
1716            eyre::bail!("Wasm file does not have .wasm extension: {path}");
1717        }
1718        if !fs::metadata(&path).is_ok() {
1719            eyre::bail!("Wasm file does not exist: {path}");
1720        }
1721
1722        let mut file =
1723            fs::File::open(&path).wrap_err_with(|| format!("Failed to open wasm file: {path}"))?;
1724        let mut magic = [0u8; 8];
1725        file.read_exact(&mut magic)
1726            .wrap_err_with(|| format!("Failed to read magic number from wasm file: {path}"))?;
1727        if !magic.starts_with(b"\0asm") {
1728            eyre::bail!("Wasm file does not have valid magic number: {path}");
1729        }
1730        let version = &magic[4..8];
1731        // https://github.com/WebAssembly/component-model/blob/main/design/mvp/Binary.md#component-definitions
1732        if version == [0x0D, 0x00, 0x01, 0x00] {
1733            return Ok(Self::Component(path));
1734        }
1735        // https://webassembly.github.io/spec/core/binary/modules.html#binary-module
1736        if version != [0x01, 0x00, 0x00, 0x00] {
1737            eyre::bail!("Wasm file does not have valid version: {path}");
1738        }
1739
1740        Ok(Self::Original {
1741            current: path.clone(),
1742            original: path,
1743        })
1744    }
1745
1746    /// Forcefully invokes internal compiling mechanisms translating a declarative specification down into an executable binary structurally.
1747    pub fn definitely(
1748        &mut self,
1749        threads: bool,
1750        vfs_build_opts: &args::VfsBuildOptions,
1751    ) -> eyre::Result<()> {
1752        if let WasmPath::Maybe {
1753            manifest_path,
1754            package,
1755        } = self
1756        {
1757            let cargo_metadata = {
1758                let mut metadata_command = cargo_metadata::MetadataCommand::new();
1759                metadata_command.manifest_path(&manifest_path);
1760                metadata_command.exec().unwrap()
1761            };
1762            let building_crate =
1763                compile::get_building_crate(&cargo_metadata, &Some(package.clone()))?;
1764            let vfs_name = building_crate.name.to_string();
1765
1766            let path = compile::build_vfs(
1767                Some(&manifest_path.to_string()),
1768                &building_crate,
1769                threads,
1770                vfs_build_opts,
1771            )
1772            .wrap_err_with(|| eyre::eyre!("Failed to build VFS: {vfs_name}"))?;
1773            *self = WasmPath::Definitely(path);
1774        }
1775
1776        // Original variant is already resolved, no action needed.
1777
1778        Ok(())
1779    }
1780
1781    /// Returns the path to the WASM module.
1782    pub fn path(&self) -> eyre::Result<&Utf8PathBuf> {
1783        match self {
1784            WasmPath::Maybe { .. } => {
1785                eyre::bail!("WasmPath is not definitely set: {self:?}")
1786            }
1787            WasmPath::Definitely(p)
1788            | WasmPath::Component(p)
1789            | WasmPath::Original { current: p, .. } => Ok(p),
1790        }
1791    }
1792
1793    /// Returns `true` if the given path is the original user-provided file that should be preserved.
1794    pub fn is_original(&self, path: &Utf8PathBuf) -> bool {
1795        matches!(self, WasmPath::Original { original, .. } if original == path)
1796    }
1797
1798    /// Forcefully overrides the explicitly resolved file path for definite path targets.
1799    /// For `Original` variants, preserves the original path tracking.
1800    pub fn set_path(&mut self, path: Utf8PathBuf) -> eyre::Result<()> {
1801        match self {
1802            WasmPath::Maybe { .. } => {
1803                eyre::bail!("WasmPath is not definitely set: {path}")
1804            }
1805            WasmPath::Original { current, .. } => {
1806                // Keep the original path, only update current
1807                *current = path;
1808            }
1809            _ => {
1810                *self = WasmPath::Definitely(path);
1811            }
1812        }
1813        Ok(())
1814    }
1815}
1816
1817/// Coordinates the underlying binary `wasm-merge` utility invocations to bundle outputs physically.
1818pub fn merge(
1819    vfs: &Utf8PathBuf,
1820    wasm: &[impl AsRef<std::path::Path>],
1821    output: impl AsRef<std::path::Path>,
1822    _threads: bool,
1823    dwarf: bool,
1824) -> eyre::Result<()> {
1825    let custom_section = {
1826        let mut vfs_module = walrus::Module::load(vfs, dwarf)?;
1827        let custom_section_names = vfs_module
1828            .customs
1829            .iter()
1830            .map(|(_, section)| section.name().to_string())
1831            .filter(|name| name.starts_with("component-type:"))
1832            .collect::<Vec<_>>();
1833        // let custom_section = vfs_module
1834        //     .customs.delete(custom_section_names)
1835        let custom_section = custom_section_names
1836            .iter()
1837            .map(|id| {
1838                let section = vfs_module.customs.remove_raw(id);
1839                section.unwrap()
1840            })
1841            .collect::<Vec<_>>();
1842
1843        custom_section
1844    };
1845
1846    let mut merge_cmd = fallback_command::get_fallback_command("wasm-merge");
1847
1848    // if threads {
1849    //     merge_cmd.arg("--enable-threads");
1850    // }
1851
1852    if dwarf {
1853        merge_cmd.arg("--debuginfo");
1854    }
1855
1856    merge_cmd.arg(vfs).arg(UniqueName::WASIP1_ABI_MODULE);
1857
1858    for wasm in wasm {
1859        merge_cmd
1860            .arg(wasm.as_ref().as_os_str().to_str().unwrap())
1861            .arg(format!(
1862                "wasip1_vfs_{}",
1863                wasm.as_ref().get_file_main_name().unwrap()
1864            ));
1865    }
1866
1867    merge_cmd
1868        .arg("--output")
1869        .arg(output.as_ref().as_os_str().to_str().unwrap())
1870        // .arg("--rename-export-conflicts")
1871        .arg("--enable-multimemory")
1872        .arg("--enable-threads");
1873
1874    let result = merge_cmd
1875        .spawn()
1876        .map_err(|e| match e.kind() {
1877            std::io::ErrorKind::NotFound => eyre::eyre!(
1878                "wasm-merge command not found. Please install wasm-merge from https://github.com/WebAssembly/binaryen/releases/latest"
1879            ),
1880            _ => e.into(),
1881        })?
1882        .wait_with_output()
1883        .wrap_err("Failed to wait for wasm-merge process")?;
1884
1885    if !result.success {
1886        let error_message = String::from_utf8_lossy(&result.stdout);
1887
1888        return Err(eyre::eyre!("wasm-merge command failed: {error_message}"));
1889    }
1890
1891    let mut module = walrus::Module::load(output.as_ref(), dwarf)?;
1892    for section in custom_section {
1893        module.customs.add(section);
1894    }
1895
1896    // to output
1897    fs::remove_file(output.as_ref()).expect("Failed to remove existing file");
1898
1899    module
1900        .emit_wasm_file(output.as_ref())
1901        .expect("Failed to emit wasm file");
1902
1903    Ok(())
1904}
1905
1906macro_rules! _add_generators_by_type {
1907    ($runner:expr, $($ty:ty),* $(,)?) => {
1908        $(
1909            if let Some(_) = $runner.get_generator_ref::<$ty>().ok() {
1910                panic!("Generator of type {} already exists", std::any::type_name::<$ty>());
1911            }
1912            $runner.add_generator(<$ty>::default());
1913        )*
1914    };
1915}
1916pub(crate) use _add_generators_by_type as add_generators_by_type;