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