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                    mem_id_visitor
1064                        .post_lower_memory(module, &self.ctx)
1065                        .wrap_err("Failed in post_lower_memory")?;
1066
1067                    self.ctx.vfs_used_memory_id = mem_id_visitor.used_vfs_memory_id.take();
1068                    self.ctx.target_used_memory_id = mem_id_visitor.used_target_memory_id.take();
1069
1070                    self.generators
1071                        .post_lower_memory(module, &self.ctx)
1072                        .wrap_err("Failed in run_post_lower_memory")?;
1073
1074                    start_section_generator
1075                        .take()
1076                        .unwrap()
1077                        .build(module, &self.ctx)?;
1078
1079                    Ok(())
1080                })
1081                .wrap_run(path, dwarf, keep_build_artifacts)
1082            })
1083            .with_opt(&mut self.path, dwarf, keep_build_artifacts)?;
1084        }
1085
1086        println!("Translating Wasm to Component...");
1087        let old_path = self.path.path()?.clone();
1088        let component = compile::wasm_to_component(&old_path, &self.ctx.target_names)
1089            .wrap_err("Failed to translate Wasm to Component")?;
1090        if !keep_build_artifacts {
1091            std::fs::remove_file(&old_path)
1092                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
1093        }
1094
1095        let new_component = format!("{out_dir}/{}.component.wasm", self.ctx.vfs_name);
1096        std::fs::rename(&component, &new_component)
1097            .wrap_err_with(|| format!("Failed to rename file {component} to {new_component}"))?;
1098
1099        self.path.set_path(Utf8PathBuf::from(new_component))?;
1100
1101        Ok(ComponentRunner::with_generators(self.path, self.generators))
1102    }
1103}
1104
1105impl ComponentRunner {
1106    /// Instantiates a fresh `ComponentRunner` targeting a specific underlying WebAssembly structure.
1107    pub fn new(path: WasmPath) -> Self {
1108        Self {
1109            generators: Vec::new(),
1110            ctx: None,
1111            path,
1112            wasm_name_holder: None,
1113        }
1114    }
1115
1116    /// Installs a specific invariant-checking generator executing without altering primary execution pathways.
1117    pub fn checker(&mut self, checker: impl Generator + 'static) {
1118        self.generators.push(Box::new(checker));
1119    }
1120
1121    /// Quickly constructs a runner wrapping a pre-defined array containing generator strategies.
1122    pub fn with_generators(path: WasmPath, generators: Vec<Box<dyn Generator + 'static>>) -> Self {
1123        Self {
1124            generators,
1125            ctx: None,
1126            path,
1127            wasm_name_holder: None,
1128        }
1129    }
1130
1131    /// Queues an advanced generative instruction step executed successively upon evaluation.
1132    pub fn add_generator<G: Generator + 'static>(&mut self, generator: G) {
1133        self.generators.push(Box::new(generator));
1134    }
1135
1136    /// Allows querying the internal generator stack dynamically retrieving explicitly modeled type structures.
1137    pub fn get_generator_ref<T: Generator + 'static>(&self) -> eyre::Result<&T> {
1138        fn downcast_ref<T: 'static>(b: &dyn Any) -> Option<&'_ T> {
1139            if b.is::<T>() {
1140                Some(b.downcast_ref::<T>().unwrap())
1141            } else {
1142                None
1143            }
1144        }
1145
1146        self.generators
1147            .iter()
1148            .map(|g| g.as_ref())
1149            .find_map(|g| downcast_ref::<T>(g))
1150            .wrap_err_with(|| {
1151                eyre::eyre!("Failed to get generator: {}", core::any::type_name::<T>())
1152            })
1153            .wrap_err_with(|| eyre::eyre!("Available generators: {:?}", self.generators))
1154    }
1155
1156    /// return is_threads, core_name, mem_size
1157    pub fn component_to_files(
1158        &mut self,
1159        parsed_args: &(impl args::PostBuildContext + ?Sized),
1160        dwarf: bool,
1161        only_core: bool,
1162    ) -> eyre::Result<(bool, CompactString, HashMap<CompactString, (u64, u64)>)> {
1163        let out_dir = parsed_args.out_dir();
1164
1165        let name = self.path.name()?;
1166
1167        println!("Translating Component to JS...");
1168        let core_wasm_path = (|path: &mut WasmPath| {
1169            let old_path = path.path()?.clone();
1170            let binary = std::fs::read(&old_path).wrap_err("Failed to read component")?;
1171            let transpiled = parsed_args
1172                .transpile_to_js(&binary, &name)
1173                .wrap_err("Failed to transpile to JS")?;
1174
1175            let mut core_wasm = None;
1176            for (name, data) in transpiled.files.iter() {
1177                let name = camino::Utf8PathBuf::from(name);
1178                let file_name = out_dir.join(&name);
1179                if std::fs::metadata(&file_name).is_ok() {
1180                    std::fs::remove_file(&file_name).wrap_err_with(|| {
1181                        eyre::eyre!("Failed to remove existing file: {file_name}")
1182                    })?;
1183                }
1184                if name.as_str().ends_with(".core.wasm") {
1185                    let file_name = camino::Utf8PathBuf::from(file_name);
1186                    std::fs::write(&file_name, &data).wrap_err_with(|| {
1187                        eyre::eyre!("Failed to write core wasm file: {file_name}")
1188                    })?;
1189                    core_wasm = Some(file_name);
1190                } else {
1191                    if let Some(parent) = name.parent() {
1192                        if !parent.as_str().is_empty() {
1193                            let dir = name.ancestors().nth(1).wrap_err_with(|| {
1194                                eyre::eyre!("Failed to get parent directory: {}", name)
1195                            })?;
1196                            let joined_dir = out_dir.join(dir);
1197                            if !std::fs::metadata(&joined_dir).is_ok() {
1198                                if dir.as_str() != "interfaces" {
1199                                    log::warn!("Creating directory: {joined_dir}");
1200                                }
1201                                if only_core {
1202                                    continue;
1203                                }
1204                                std::fs::create_dir_all(&joined_dir).wrap_err_with(|| {
1205                                    eyre::eyre!("Failed to create directory: {joined_dir}")
1206                                })?;
1207                            }
1208                        }
1209                    }
1210                    if only_core {
1211                        continue;
1212                    }
1213                    std::fs::write(&file_name, &data).wrap_err_with(|| {
1214                        eyre::eyre!("Failed to write transpiled file: {file_name}")
1215                    })?;
1216                }
1217            }
1218
1219            let core_wasm = core_wasm
1220                .as_ref()
1221                .ok_or_else(|| eyre::eyre!("Failed to find core wasm"))?;
1222
1223            if !parsed_args.keep_build_artifacts() {
1224                std::fs::remove_file(&old_path)
1225                    .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
1226            }
1227            path.set_path(core_wasm.clone())?;
1228
1229            Ok(core_wasm.clone())
1230        })
1231        .with_opt(&mut self.path, dwarf, parsed_args.keep_build_artifacts())?;
1232
1233        let mem_size_visitor = MemorySizeVisitor::default();
1234        self.generators.push(Box::new(mem_size_visitor));
1235
1236        println!("Adjusting component Merged Wasm...");
1237        (|path: &mut WasmPath| {
1238            (|module: &mut walrus::Module| {
1239                let mut visitor = ComponentCtxVisitor::default();
1240                visitor
1241                    .post_components(
1242                        module,
1243                        &ComponentCtx {
1244                            dwarf,
1245                            ..Default::default()
1246                        },
1247                    )
1248                    .wrap_err("Failed in post_components")?;
1249                let wasm_name_holder = WasmNameHolder::new(
1250                    visitor
1251                        .target_names
1252                        .unwrap()
1253                        .into_iter()
1254                        .chain(core::iter::once(visitor.vfs_name.unwrap()))
1255                        .collect::<Box<_>>(),
1256                );
1257                self.wasm_name_holder = Some(wasm_name_holder);
1258                let mut wasm_name_holder_iter = self.wasm_name_holder.as_ref().unwrap().iter();
1259                self.ctx = Some(ComponentCtx {
1260                    vfs_name: Some(wasm_name_holder_iter.next().unwrap()),
1261                    target_names: Some(wasm_name_holder_iter.collect::<Box<_>>()),
1262                    target_memory_type: Some(visitor.target_memory_type.unwrap()),
1263                    unstable_print_debug: Some(visitor.unstable_print_debug.unwrap()),
1264                    dwarf: visitor.dwarf.unwrap(),
1265                    threads: Some(visitor.threads.unwrap()),
1266                    adjust_abi: visitor.adjust_abi,
1267                });
1268
1269                self.generators
1270                    .post_components(module, self.ctx.as_ref().unwrap())
1271                    .wrap_err("Failed in run_post_components")
1272            })
1273            .wrap_run(path, dwarf, parsed_args.keep_build_artifacts())
1274        })
1275        .with_opt(&mut self.path, dwarf, parsed_args.keep_build_artifacts())?;
1276
1277        let dwarf = {
1278            let new_dwarf = self.ctx.as_ref().unwrap().dwarf;
1279            if dwarf && !new_dwarf {
1280                log::warn!(
1281                    "Dwarf was disabled in component processing, you should re-run with --dwarf"
1282                );
1283            }
1284            new_dwarf
1285        };
1286
1287        println!("Final optimizing Merged Wasm...");
1288        let mut i = 0;
1289        while i < self.generators.len() {
1290            (|module: &mut walrus::Module| {
1291                loop {
1292                    if self.generators[i]
1293                        .post_all_optimize(module, self.ctx.as_ref().unwrap())
1294                        .wrap_err("Failed in post_all_optimize")?
1295                    {
1296                        i += 1;
1297                        return Ok(());
1298                    }
1299                    i += 1;
1300                    if i >= self.generators.len() {
1301                        return Ok(());
1302                    }
1303                }
1304            })
1305            .wrap_run(&mut self.path, dwarf, parsed_args.keep_build_artifacts())?;
1306        }
1307
1308        std::fs::rename(self.path.path()?, &core_wasm_path).wrap_err_with(|| {
1309            eyre::eyre!(
1310                "Failed to rename final wasm from {} to {}",
1311                self.path.path().unwrap(),
1312                core_wasm_path
1313            )
1314        })?;
1315
1316        Ok((
1317            self.ctx.as_ref().unwrap().threads(),
1318            core_wasm_path
1319                .get_file_main_name()
1320                .ok_or_else(|| eyre::eyre!("Failed to get file name"))?,
1321            self.get_generator_ref::<MemorySizeVisitor>()?
1322                .mem_size
1323                .clone()
1324                .unwrap(),
1325        ))
1326    }
1327}
1328
1329#[derive(Debug, Default, Clone)]
1330struct MemoryIDVisitor {
1331    pub memory_hint: HashMap<WasmName, usize>,
1332    pub used_vfs_memory_id: Option<MemoryId>,
1333    pub used_target_memory_id: Option<HashMap<WasmName, MemoryId>>,
1334}
1335
1336impl Generator for MemoryIDVisitor {
1337    fn pre_vfs(
1338        &mut self,
1339        module: &mut walrus::Module,
1340        _: &crate::generator::GeneratorCtx,
1341    ) -> eyre::Result<()> {
1342        println!("Finding VFS memory id...");
1343
1344        let id = module
1345            .get_memory_anchor("vfs", false)
1346            .wrap_err("Failed to get target memory id")?;
1347        self.used_vfs_memory_id = Some(id);
1348        Ok(())
1349    }
1350
1351    fn pre_target(
1352        &mut self,
1353        module: &mut walrus::Module,
1354        _: &crate::generator::GeneratorCtx,
1355        external: &ModuleExternal,
1356    ) -> eyre::Result<()> {
1357        let id = module
1358            .find_used_memory_id(self.memory_hint.get(&external.name).copied())
1359            .wrap_err("Failed to find used memory id")?;
1360        module
1361            .create_memory_anchor(&external.name, id)
1362            .wrap_err("Failed to create memory anchor")?;
1363        self.used_target_memory_id
1364            .get_or_insert_default()
1365            .insert(external.name.clone(), id);
1366        Ok(())
1367    }
1368
1369    fn post_combine(
1370        &mut self,
1371        module: &mut walrus::Module,
1372        ctx: &GeneratorCtx,
1373    ) -> eyre::Result<()> {
1374        let id = module
1375            .get_memory_anchor("vfs", true)
1376            .wrap_err("Failed to find used memory id after combine")?;
1377        self.used_vfs_memory_id = Some(id);
1378
1379        self.used_target_memory_id.get_or_insert_default().clear();
1380        for wasm in &ctx.target_names {
1381            let id = module
1382                .get_memory_anchor(wasm, true)
1383                .wrap_err("Failed to find used memory id after combine")?;
1384            self.used_target_memory_id
1385                .as_mut()
1386                .unwrap()
1387                .insert(wasm.clone(), id);
1388        }
1389
1390        Ok(())
1391    }
1392
1393    fn post_lower_memory(
1394        &mut self,
1395        module: &mut walrus::Module,
1396        _: &GeneratorCtx,
1397    ) -> eyre::Result<()> {
1398        let id = module
1399            .get_memory_id()
1400            .to_eyre()
1401            .wrap_err("Failed to get single memory id after lowering")?;
1402        self.used_vfs_memory_id = Some(id);
1403        self.used_target_memory_id = None;
1404
1405        Ok(())
1406    }
1407}
1408
1409#[derive(Debug, Default, Clone)]
1410struct MemorySizeVisitor {
1411    mem_size: Option<HashMap<CompactString, (u64, u64)>>,
1412}
1413
1414impl Generator for MemorySizeVisitor {
1415    fn post_components(
1416        &mut self,
1417        module: &mut walrus::Module,
1418        _: &ComponentCtx,
1419    ) -> eyre::Result<()> {
1420        let mem_size = module
1421            .memories
1422            .iter()
1423            .filter(|mem| mem.import.is_some())
1424            .map(|mem| {
1425                (
1426                    module
1427                        .imports
1428                        .get(mem.import.unwrap())
1429                        .name
1430                        .to_compact_string(),
1431                    (
1432                        mem.initial as u64,
1433                        mem.maximum.unwrap_or(mem.initial) as u64,
1434                    ),
1435                )
1436            })
1437            .collect::<HashMap<_, _>>();
1438        self.mem_size = Some(mem_size);
1439
1440        Ok(())
1441    }
1442}
1443
1444#[derive(Debug, Default)]
1445struct GlobalIdVisitor {
1446    vfs_global_id: Option<Box<[walrus::GlobalId]>>,
1447    global_id: Option<HashMap<WasmName, Box<[walrus::GlobalId]>>>,
1448}
1449impl Generator for GlobalIdVisitor {
1450    fn pre_vfs(&mut self, module: &mut walrus::Module, _: &GeneratorCtx) -> eyre::Result<()> {
1451        module
1452            .create_global_anchor("vfs")
1453            .wrap_err("Failed to create global anchor")?;
1454
1455        Ok(())
1456    }
1457
1458    fn pre_target(
1459        &mut self,
1460        module: &mut walrus::Module,
1461        _: &GeneratorCtx,
1462        external: &ModuleExternal,
1463    ) -> eyre::Result<()> {
1464        module
1465            .create_global_anchor(&external.name)
1466            .wrap_err("Failed to create global anchor")?;
1467
1468        Ok(())
1469    }
1470
1471    fn post_combine(
1472        &mut self,
1473        module: &mut walrus::Module,
1474        ctx: &GeneratorCtx,
1475    ) -> eyre::Result<()> {
1476        self.global_id = Some(HashMap::new());
1477
1478        let vfs_globals = module
1479            .get_global_anchor("vfs")
1480            .wrap_err("Failed to get global anchor for vfs")?;
1481        self.vfs_global_id = Some(vfs_globals);
1482
1483        for wasm in &ctx.target_names {
1484            let globals = module
1485                .get_global_anchor(wasm)
1486                .wrap_err_with(|| format!("Failed to get global anchor for {wasm}"))?;
1487            self.global_id
1488                .as_mut()
1489                .unwrap()
1490                .insert(wasm.clone(), globals);
1491        }
1492
1493        Ok(())
1494    }
1495}
1496
1497/// To be used from both `special_func`'s `main_void` and `start`,
1498/// it must be prepared in `ctx`.
1499#[derive(Debug, Default)]
1500struct StartFuncIdVisitor {
1501    start_func_id: Option<HashMap<WasmName, walrus::FunctionId>>,
1502}
1503
1504impl Generator for StartFuncIdVisitor {
1505    fn post_combine(
1506        &mut self,
1507        module: &mut walrus::Module,
1508        ctx: &GeneratorCtx,
1509    ) -> eyre::Result<()> {
1510        for wasm in &ctx.target_names {
1511            // NOTE: wasm-merge preserves the package name with dashes for some exports,
1512            // but the __start_anchor from the Rust macros has underscores.
1513            let normalized_wasm = wasm.as_ref().replace('-', "_");
1514            // let export_name = format!("__wasip1_vfs_{wasm}__start");
1515
1516            let export = format!("__wasip1_vfs_{wasm}__start").get_fid(&module.exports)?;
1517            self.start_func_id
1518                .get_or_insert_default()
1519                .insert(wasm.clone(), export);
1520
1521            // NOTE: Don't erase the __start export - it's needed for StartFunc
1522            // to find it as an import or to redirect calls to it.
1523
1524            // The anchor export was created by import_wasm! macro and uses underscores
1525            module.exports.erase_with(
1526                &format!("__wasip1_vfs_{normalized_wasm}__start_anchor"),
1527                ctx.unstable_print_debug,
1528            )?;
1529        }
1530
1531        Ok(())
1532    }
1533}
1534
1535/// Represents the resolution state and file format targeting for manipulating WebAssembly modules intelligently.
1536#[derive(Debug, Clone)]
1537pub enum WasmPath {
1538    /// Indicates the target still needs compilation through standard cargo dependencies.
1539    Maybe {
1540        /// Fully resolved physical path to the corresponding Cargo.toml manifest definition.
1541        manifest_path: Utf8PathBuf,
1542        /// Specified internal crate package identifier.
1543        package: String,
1544    },
1545    /// A strictly resolved raw WebAssembly binary file ready for patching operations.
1546    Definitely(Utf8PathBuf),
1547    /// A completed explicitly transpiled WebAssembly Component standard architecture module.
1548    Component(Utf8PathBuf),
1549    /// A user-provided raw WebAssembly binary file that should never be deleted.
1550    /// The inner path tracks the original file location.
1551    Original {
1552        /// The current working path (may change as transformations produce new files).
1553        current: Utf8PathBuf,
1554        /// The original user-provided path that must be preserved.
1555        original: Utf8PathBuf,
1556    },
1557}
1558
1559impl FromStr for WasmPath {
1560    type Err = eyre::Error;
1561
1562    /// manifest_path :: package
1563    fn from_str(s: &str) -> Result<Self, Self::Err> {
1564        fn parse_path_and_package(s: &str) -> eyre::Result<Option<WasmPath>> {
1565            let split = s.split("::").collect::<Vec<_>>();
1566            if split.len() == 2 {
1567                let manifest_path = Utf8PathBuf::from_str(split[0])
1568                    .wrap_err_with(|| format!("Failed to parse manifest path: {}", split[0]))?;
1569                let package = split[1].to_string();
1570                return Ok(Some(WasmPath::Maybe {
1571                    manifest_path,
1572                    package,
1573                }));
1574            }
1575            Ok(None)
1576        }
1577
1578        if let Some(wasm_path) =
1579            parse_path_and_package(s).wrap_err("Failed to parse path and package")?
1580        {
1581            return Ok(wasm_path);
1582        }
1583
1584        if s.ends_with(".wasm") {
1585            let path = Utf8PathBuf::from_str(s)
1586                .wrap_err_with(|| format!("Failed to parse wasm path: {s}"))?;
1587            return WasmPath::with_wasm(path);
1588        }
1589
1590        if s.ends_with("Cargo.toml") {
1591            let manifest_path = Utf8PathBuf::from_str(s)
1592                .wrap_err_with(|| format!("Failed to parse manifest path: {s}"))?;
1593            return WasmPath::with_maybe_only_manifest(manifest_path);
1594        }
1595
1596        WasmPath::with_maybe_only_package(s.to_string())
1597            .wrap_err_with(|| format!("Failed to parse package name: {s}"))
1598    }
1599}
1600
1601impl WasmPath {
1602    /// Computes the unique short name used during module linking and identification.
1603    pub fn name(&self) -> eyre::Result<CompactString> {
1604        match self {
1605            WasmPath::Maybe { package, .. } => Ok(package.to_compact_string()),
1606            WasmPath::Definitely(path)
1607            | WasmPath::Component(path)
1608            | WasmPath::Original { current: path, .. } => path
1609                .get_file_main_name()
1610                .ok_or_else(|| eyre::eyre!("Failed to get file name from {path}")),
1611        }
1612    }
1613
1614    /// Exposes the manifest path conditionally if the dependency is unresolved logically.
1615    pub fn manifest_path(&self) -> Option<&Utf8PathBuf> {
1616        match self {
1617            WasmPath::Maybe { manifest_path, .. } => Some(manifest_path),
1618            WasmPath::Definitely(_) | WasmPath::Component(_) | WasmPath::Original { .. } => None,
1619        }
1620    }
1621
1622    /// Calculates the overarching workspace root via dependency graphing context implicitly.
1623    pub fn root_manifest_path(&self) -> Option<Utf8PathBuf> {
1624        match self {
1625            WasmPath::Maybe { manifest_path, .. } => {
1626                let cargo_metadata = {
1627                    let mut metadata_command = cargo_metadata::MetadataCommand::new();
1628                    metadata_command.manifest_path(&manifest_path);
1629                    metadata_command.exec().unwrap()
1630                };
1631                Some(cargo_metadata.workspace_root.join("Cargo.toml"))
1632            }
1633            WasmPath::Definitely(_) | WasmPath::Component(_) | WasmPath::Original { .. } => None,
1634        }
1635    }
1636
1637    /// Statically assigns an unresolved target using defined package specifications.
1638    pub const fn with_maybe(manifest_path: Utf8PathBuf, package: String) -> Self {
1639        Self::Maybe {
1640            manifest_path,
1641            package,
1642        }
1643    }
1644
1645    /// Constructs an unresolved dependency resolving package tracking inherently from a file manifest dynamically.
1646    pub fn with_maybe_only_manifest(manifest_path: Utf8PathBuf) -> eyre::Result<Self> {
1647        let cargo_metadata = {
1648            let mut metadata_command = cargo_metadata::MetadataCommand::new();
1649            metadata_command.manifest_path(&manifest_path);
1650            metadata_command.exec().unwrap()
1651        };
1652        let building_crate = compile::get_building_crate(&cargo_metadata, &None)?;
1653
1654        Ok(Self::Maybe {
1655            manifest_path,
1656            package: building_crate.name.to_string(),
1657        })
1658    }
1659
1660    /// Assesses global cargo metadata configuring definitions matching solely the provided string identifier.
1661    pub fn with_maybe_only_package(package: String) -> eyre::Result<Self> {
1662        let cargo_metadata = {
1663            let metadata_command = cargo_metadata::MetadataCommand::new();
1664            metadata_command.exec().unwrap()
1665        };
1666        let building_crate = compile::get_building_crate(&cargo_metadata, &Some(package.clone()))?;
1667
1668        Ok(Self::Maybe {
1669            manifest_path: building_crate.manifest_path,
1670            package: building_crate.name.to_string(),
1671        })
1672    }
1673
1674    /// Loads an unresolved dependency using current environment cargo bounds natively.
1675    pub fn with_maybe_none() -> eyre::Result<Self> {
1676        let cargo_metadata = {
1677            let metadata_command = cargo_metadata::MetadataCommand::new();
1678            metadata_command.exec().unwrap()
1679        };
1680        let building_crate = compile::get_building_crate(&cargo_metadata, &None)?;
1681
1682        Ok(Self::Maybe {
1683            manifest_path: building_crate.manifest_path,
1684            package: building_crate.name.to_string(),
1685        })
1686    }
1687
1688    /// Scans an exact provided `.wasm` artifact verifying magic byte signatures correctly to assign a resolution state.
1689    /// User-provided `.wasm` files are wrapped in `Original` to prevent deletion of the original file.
1690    pub fn with_wasm(path: Utf8PathBuf) -> eyre::Result<Self> {
1691        if path.extension() != Some("wasm") {
1692            eyre::bail!("Wasm file does not have .wasm extension: {path}");
1693        }
1694        if !fs::metadata(&path).is_ok() {
1695            eyre::bail!("Wasm file does not exist: {path}");
1696        }
1697
1698        let mut file =
1699            fs::File::open(&path).wrap_err_with(|| format!("Failed to open wasm file: {path}"))?;
1700        let mut magic = [0u8; 8];
1701        file.read_exact(&mut magic)
1702            .wrap_err_with(|| format!("Failed to read magic number from wasm file: {path}"))?;
1703        if !magic.starts_with(b"\0asm") {
1704            eyre::bail!("Wasm file does not have valid magic number: {path}");
1705        }
1706        let version = &magic[4..8];
1707        // https://github.com/WebAssembly/component-model/blob/main/design/mvp/Binary.md#component-definitions
1708        if version == [0x0D, 0x00, 0x01, 0x00] {
1709            return Ok(Self::Component(path));
1710        }
1711        // https://webassembly.github.io/spec/core/binary/modules.html#binary-module
1712        if version != [0x01, 0x00, 0x00, 0x00] {
1713            eyre::bail!("Wasm file does not have valid version: {path}");
1714        }
1715
1716        Ok(Self::Original {
1717            current: path.clone(),
1718            original: path,
1719        })
1720    }
1721
1722    /// Forcefully invokes internal compiling mechanisms translating a declarative specification down into an executable binary structurally.
1723    pub fn definitely(&mut self, threads: bool) -> eyre::Result<()> {
1724        if let WasmPath::Maybe {
1725            manifest_path,
1726            package,
1727        } = self
1728        {
1729            let cargo_metadata = {
1730                let mut metadata_command = cargo_metadata::MetadataCommand::new();
1731                metadata_command.manifest_path(&manifest_path);
1732                metadata_command.exec().unwrap()
1733            };
1734            let building_crate =
1735                compile::get_building_crate(&cargo_metadata, &Some(package.clone()))?;
1736            let vfs_name = building_crate.name.to_string();
1737
1738            let path =
1739                compile::build_vfs(Some(&manifest_path.to_string()), &building_crate, threads)
1740                    .wrap_err_with(|| eyre::eyre!("Failed to build VFS: {vfs_name}"))?;
1741            *self = WasmPath::Definitely(path);
1742        }
1743
1744        // Original variant is already resolved, no action needed.
1745
1746        Ok(())
1747    }
1748
1749    /// Returns the path to the WASM module.
1750    pub fn path(&self) -> eyre::Result<&Utf8PathBuf> {
1751        match self {
1752            WasmPath::Maybe { .. } => {
1753                eyre::bail!("WasmPath is not definitely set: {self:?}")
1754            }
1755            WasmPath::Definitely(p)
1756            | WasmPath::Component(p)
1757            | WasmPath::Original { current: p, .. } => Ok(p),
1758        }
1759    }
1760
1761    /// Returns `true` if the given path is the original user-provided file that should be preserved.
1762    pub fn is_original(&self, path: &Utf8PathBuf) -> bool {
1763        matches!(self, WasmPath::Original { original, .. } if original == path)
1764    }
1765
1766    /// Forcefully overrides the explicitly resolved file path for definite path targets.
1767    /// For `Original` variants, preserves the original path tracking.
1768    pub fn set_path(&mut self, path: Utf8PathBuf) -> eyre::Result<()> {
1769        match self {
1770            WasmPath::Maybe { .. } => {
1771                eyre::bail!("WasmPath is not definitely set: {path}")
1772            }
1773            WasmPath::Original { current, .. } => {
1774                // Keep the original path, only update current
1775                *current = path;
1776            }
1777            _ => {
1778                *self = WasmPath::Definitely(path);
1779            }
1780        }
1781        Ok(())
1782    }
1783}
1784
1785/// Coordinates the underlying binary `wasm-merge` utility invocations to bundle outputs physically.
1786pub fn merge(
1787    vfs: &Utf8PathBuf,
1788    wasm: &[impl AsRef<std::path::Path>],
1789    output: impl AsRef<std::path::Path>,
1790    _threads: bool,
1791    dwarf: bool,
1792) -> eyre::Result<()> {
1793    let custom_section = {
1794        let mut vfs_module = walrus::Module::load(vfs, dwarf)?;
1795        let custom_section_names = vfs_module
1796            .customs
1797            .iter()
1798            .map(|(_, section)| section.name().to_string())
1799            .filter(|name| name.starts_with("component-type:"))
1800            .collect::<Vec<_>>();
1801        // let custom_section = vfs_module
1802        //     .customs.delete(custom_section_names)
1803        let custom_section = custom_section_names
1804            .iter()
1805            .map(|id| {
1806                let section = vfs_module.customs.remove_raw(id);
1807                section.unwrap()
1808            })
1809            .collect::<Vec<_>>();
1810
1811        custom_section
1812    };
1813
1814    let mut merge_cmd = fallback_command::get_fallback_command("wasm-merge");
1815
1816    // if threads {
1817    //     merge_cmd.arg("--enable-threads");
1818    // }
1819
1820    if dwarf {
1821        merge_cmd.arg("--debuginfo");
1822    }
1823
1824    merge_cmd.arg(vfs).arg(UniqueName::WASIP1_ABI_MODULE);
1825
1826    for wasm in wasm {
1827        merge_cmd
1828            .arg(wasm.as_ref().as_os_str().to_str().unwrap())
1829            .arg(format!(
1830                "wasip1_vfs_{}",
1831                wasm.as_ref().get_file_main_name().unwrap()
1832            ));
1833    }
1834
1835    merge_cmd
1836        .arg("--output")
1837        .arg(output.as_ref().as_os_str().to_str().unwrap())
1838        // .arg("--rename-export-conflicts")
1839        .arg("--enable-multimemory")
1840        .arg("--enable-threads");
1841
1842    let result = merge_cmd
1843        .spawn()
1844        .map_err(|e| match e.kind() {
1845            std::io::ErrorKind::NotFound => eyre::eyre!(
1846                "wasm-merge command not found. Please install wasm-merge from https://github.com/WebAssembly/binaryen/releases/latest"
1847            ),
1848            _ => e.into(),
1849        })?
1850        .wait_with_output()
1851        .wrap_err("Failed to wait for wasm-merge process")?;
1852
1853    if !result.success {
1854        return Err(eyre::eyre!("wasm-merge command failed"));
1855    }
1856
1857    let mut module = walrus::Module::load(output.as_ref(), dwarf)?;
1858    for section in custom_section {
1859        module.customs.add(section);
1860    }
1861
1862    // to output
1863    fs::remove_file(output.as_ref()).expect("Failed to remove existing file");
1864
1865    module
1866        .emit_wasm_file(output.as_ref())
1867        .expect("Failed to emit wasm file");
1868
1869    Ok(())
1870}
1871
1872macro_rules! _add_generators_by_type {
1873    ($runner:expr, $($ty:ty),* $(,)?) => {
1874        $(
1875            if let Some(_) = $runner.get_generator_ref::<$ty>().ok() {
1876                panic!("Generator of type {} already exists", std::any::type_name::<$ty>());
1877            }
1878            $runner.add_generator(<$ty>::default());
1879        )*
1880    };
1881}
1882pub(crate) use _add_generators_by_type as add_generators_by_type;