Skip to main content

wasi_virt_layer_cli/generator/
mod.rs

1/// Module for ABI connection generation and overrides.
2pub mod abi_connect;
3/// Utilities for handling anonymous and generic WASM rewrites.
4pub mod anonymous;
5/// Type-checking routines for imported/exported functions.
6pub mod check;
7/// Internal debug formatting and trace generators.
8pub mod debug;
9/// Generates and bridges memory copy, trap, and related VFS interactions.
10pub mod memory;
11/// Routines for stripping or patching unused WASM components.
12pub mod patch_component;
13/// Embeds module metadata.
14pub mod producer;
15/// Low-level multi-threading global locks and shared allocations.
16pub mod shared_global;
17/// Bridges custom initializers, `_start`, `main_void`, and reset routines.
18pub mod special_func;
19pub mod starts;
20/// Internal logic for rewriting WASI threads spawn imports to the VFS.
21pub mod threads;
22/// Handles logic for rewriting unreachable instructions to prevent Wasm execution traps.
23pub mod wrap_unreachable;
24pub mod vfs_host;
25/// Generates the atomic wait implementation for `WaitPoll` timeout handling.
26pub mod poll;
27
28use std::{any::Any, collections::HashMap, fs, io::Read as _, str::FromStr};
29
30use camino::Utf8PathBuf;
31use compact_str::{CompactString, ToCompactString as _};
32use eyre::{Context as _, ContextCompat};
33use itertools::Itertools;
34use walrus::MemoryId;
35
36use crate::{
37    args::{self, TargetMemoryType},
38    compile,
39    config_checker::TomlRestorers,
40    fallback_command,
41    unique_name::UniqueName,
42    util::{
43        CaminoUtilModule as _, ResultUtil, WalrusFID as _, WalrusUtilExport as _, WalrusUtilModule,
44        WasmName, WasmNameHolder,
45    },
46};
47
48/// Represents the generation context, holding configuration arguments and targeted module info.
49#[derive(Debug)]
50pub struct GeneratorCtx {
51    /// The name of the VFS module.
52    pub vfs_name: WasmName,
53    /// The names of the target modules.
54    pub target_names: Box<[WasmName]>,
55    /// Including one's own WASI ABI
56    pub target_names_with_self: Box<[WasmName]>,
57    /// only pre_vfs, post_combine, post_lower_memory
58    pub vfs_used_memory_id: Option<MemoryId>,
59    /// only post_combine
60    pub vfs_used_global_id: Option<Box<[walrus::GlobalId]>>,
61    /// only pre_target, post_combine, post_lower_memory
62    pub target_used_memory_id: Option<HashMap<WasmName, MemoryId>>,
63    /// only post_combine
64    pub target_used_global_id: Option<HashMap<WasmName, Box<[walrus::GlobalId]>>>,
65    /// not start section.
66    /// only post_combine.
67    pub start_func_id: Option<HashMap<WasmName, walrus::FunctionId>>,
68    /// The memory type of the target modules (Single or Multi).
69    pub target_memory_type: TargetMemoryType,
70    /// Whether to print unstable debug information.
71    pub unstable_print_debug: bool,
72    /// Whether to include DWARF debug information.
73    pub dwarf: bool,
74    /// Whether to enable multi-threading support.
75    pub threads: bool,
76    /// Whether to adjust the ABI for standard environments.
77    pub adjust_abi: bool,
78    /// Whether to keep intermediate build artifacts.
79    pub keep_build_artifacts: bool,
80    pub starts: starts::FnInStarts,
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            starts: _,
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    /// Options for building the VFS module.
575    pub vfs_build_opts: args::VfsBuildOptions,
576    /// Options for building the target WASM modules.
577    pub target_vfs_build_opts: Box<[args::VfsBuildOptions]>,
578    /// The TOML restorers used to reset configuration files.
579    pub toml_restorers: Option<TomlRestorers>,
580    /// Memory hints for the target modules.
581    pub memory_hint: HashMap<WasmName, usize>,
582    /// Holder for the names of the WASM modules.
583    pub wasm_name_holder: WasmNameHolder,
584}
585
586/// A runner that coordinates the generation of a WebAssembly component.
587#[derive(Debug)]
588pub struct ComponentRunner {
589    /// The generators used to transform the component.
590    pub generators: Vec<Box<dyn Generator + 'static>>,
591    /// Encapsulates contextual settings across all generator components during transpilation.
592    pub ctx: Option<ComponentCtx>,
593    /// Specifies the target active WASM module destination.
594    pub path: WasmPath,
595    /// Manages dynamically generated and globally referenced named functions.
596    pub wasm_name_holder: Option<WasmNameHolder>,
597}
598
599pub(crate) trait WrapRunner<T> {
600    #[allow(unused_variables)]
601    fn wrap_run(
602        self,
603        path: &mut WasmPath,
604        dwarf: bool,
605        keep_build_artifacts: bool,
606    ) -> eyre::Result<T>
607    where
608        Self: Sized;
609}
610
611impl<T, F: FnOnce(&mut walrus::Module) -> eyre::Result<T>> WrapRunner<T> for F {
612    fn wrap_run(
613        self,
614        path: &mut WasmPath,
615        dwarf: bool,
616        keep_build_artifacts: bool,
617    ) -> eyre::Result<T> {
618        let old_path = path.path()?.clone();
619        let module =
620            &mut walrus::Module::load(&old_path, dwarf).wrap_err("Failed to load Wasm module")?;
621
622        let result = (self)(module)?;
623
624        let new_path = old_path.with_extension("adjusted.wasm");
625
626        if fs::metadata(&new_path).is_ok() {
627            fs::remove_file(&new_path)
628                .wrap_err_with(|| format!("Failed to remove existing file {new_path}"))?;
629        }
630
631        module
632            .emit_wasm_file(&new_path)
633            .to_eyre()
634            .wrap_err_with(|| format!("Failed to write adjusted Wasm to {new_path}"))?;
635
636        if !keep_build_artifacts && !path.is_original(&old_path) {
637            std::fs::remove_file(&old_path)
638                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
639        }
640
641        path.set_path(new_path)?;
642
643        Ok(result)
644    }
645}
646
647pub(crate) trait EndWithOpt<T> {
648    #[allow(unused_variables)]
649    fn with_opt(
650        self,
651        path: &mut WasmPath,
652        dwarf: bool,
653        keep_build_artifacts: bool,
654    ) -> eyre::Result<T>
655    where
656        Self: Sized;
657
658    #[allow(dead_code)]
659    fn with_opt_args(
660        self,
661        path: &mut WasmPath,
662        args: &[&str],
663        require_update: bool,
664        dwarf: bool,
665        keep_build_artifacts: bool,
666    ) -> eyre::Result<T>
667    where
668        Self: Sized;
669}
670
671impl<T, F: FnOnce(&mut WasmPath) -> eyre::Result<T>> EndWithOpt<T> for F {
672    fn with_opt(
673        self,
674        path: &mut WasmPath,
675        dwarf: bool,
676        keep_build_artifacts: bool,
677    ) -> eyre::Result<T>
678    where
679        Self: Sized,
680    {
681        let result = (self)(path).wrap_err("Failed to run with with_opt")?;
682
683        println!("Optimizing Wasm...");
684        let old_path = path.path()?.clone();
685        let new_path = compile::optimize_wasm(&old_path, &[], false, dwarf)
686            .wrap_err("Failed to optimize Wasm")?;
687
688        if !keep_build_artifacts && old_path != new_path && !path.is_original(&old_path) {
689            std::fs::remove_file(&old_path)
690                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
691        }
692
693        path.set_path(new_path)?;
694
695        Ok(result)
696    }
697
698    fn with_opt_args(
699        self,
700        path: &mut WasmPath,
701        args: &[&str],
702        require_update: bool,
703        dwarf: bool,
704        keep_build_artifacts: bool,
705    ) -> eyre::Result<T>
706    where
707        Self: Sized,
708    {
709        let result = (self)(path).wrap_err("Failed to run with with_opt_args")?;
710
711        println!("Optimizing Wasm... with args: {}", args.iter().join(" "));
712        let old_path = path.path()?.clone();
713        let new_path = compile::optimize_wasm(&old_path, args, require_update, dwarf)
714            .wrap_err("Failed to optimize Wasm")?;
715
716        if !keep_build_artifacts && old_path != new_path && !path.is_original(&old_path) {
717            std::fs::remove_file(&old_path)
718                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
719        }
720
721        path.set_path(new_path)?;
722
723        Ok(result)
724    }
725}
726
727impl GeneratorRunner {
728    /// Initializes a `GeneratorRunner` capturing all parameters needed for complete application-level transpilation mapping.
729    pub fn new(
730        path: WasmPath,
731        targets: Box<[WasmPath]>,
732        threads: bool,
733        dwarf: bool,
734        unstable_print_debug: bool,
735        adjust_abi: bool,
736        keep_build_artifacts: bool,
737        memory_type: TargetMemoryType,
738        vfs_build_opts: args::VfsBuildOptions,
739        target_vfs_build_opts: Box<[args::VfsBuildOptions]>,
740        toml_restorers: TomlRestorers,
741        memory_hint: Box<[Option<usize>]>,
742    ) -> eyre::Result<Self> {
743        let target_names_with_self = core::iter::once(Ok(path.name()?.to_compact_string()))
744            .chain(targets.iter().map(|t| Ok(t.name()?.to_compact_string())))
745            .collect::<eyre::Result<Box<_>>>()?;
746
747        let wasm_name_holder = WasmNameHolder::new(target_names_with_self);
748        let mut wasm_name_holder_iter = wasm_name_holder.iter();
749        let vfs_name = wasm_name_holder_iter
750            .next()
751            .ok_or_else(|| eyre::eyre!("Failed to get VFS name"))?;
752
753        let target_names = wasm_name_holder_iter.collect::<Box<_>>();
754
755        let starts = starts::FnInStarts::new(&target_names);
756
757        // log targeting info
758        for name in target_names.iter() {
759            log::info!("Targeting module: {name}");
760        }
761        log::info!("VFS module: {vfs_name}");
762
763        let target_names_with_self = target_names
764            .iter()
765            .cloned()
766            .chain(core::iter::once(vfs_name.clone()))
767            .collect::<Box<_>>();
768
769        let memory_hint = memory_hint
770            .into_iter()
771            .zip(target_names.iter().cloned())
772            .filter_map(|(hint, name)| hint.map(|h| (name, h)))
773            .collect::<HashMap<_, _>>();
774
775        Ok(Self {
776            checkers: Vec::new(),
777            generators: Vec::new(),
778            ctx: GeneratorCtx {
779                vfs_name,
780                target_names,
781                target_names_with_self,
782                target_memory_type: memory_type,
783                unstable_print_debug,
784                dwarf,
785                threads,
786                adjust_abi,
787                keep_build_artifacts,
788                vfs_used_memory_id: None,
789                vfs_used_global_id: None,
790                target_used_memory_id: None,
791                target_used_global_id: None,
792                start_func_id: None,
793                starts,
794            },
795            path,
796            targets,
797            vfs_build_opts,
798            target_vfs_build_opts,
799            toml_restorers: Some(toml_restorers),
800            memory_hint,
801            wasm_name_holder,
802        })
803    }
804
805    /// Registers a custom generator to be applied sequentially during transformation phases.
806    pub fn add_generator<G: Generator + 'static>(&mut self, generator: G) {
807        self.generators.push(Box::new(generator));
808    }
809
810    /// Registers a diagnostic validation checker resolving pre or post-conditions automatically.
811    pub fn checker(&mut self, checker: impl Generator + 'static) {
812        self.checkers.push(Box::new(checker));
813    }
814
815    /// Resolves and retrieves a shared reference to a specific structured generator dynamically at runtime.
816    pub fn get_generator_ref<T: Generator + 'static>(&self) -> eyre::Result<&T> {
817        fn downcast_ref<T: 'static>(b: &dyn Any) -> Option<&'_ T> {
818            if b.is::<T>() {
819                Some(b.downcast_ref::<T>().unwrap())
820            } else {
821                None
822            }
823        }
824
825        self.generators
826            .iter()
827            .map(|g| g.as_ref())
828            .find_map(|g| downcast_ref::<T>(g))
829            .wrap_err_with(|| {
830                eyre::eyre!("Failed to get generator: {}", core::any::type_name::<T>())
831            })
832            .wrap_err_with(|| eyre::eyre!("Available generators: {:?}", self.generators))
833    }
834
835    #[deprecated(
836        note = "Ensure this function is self-contained. This is a temporary measure for debugging purposes."
837    )]
838    /// Provides direct immutable access tracking the primary target structural path configuration.
839    pub const fn path(&self) -> &WasmPath {
840        &self.path
841    }
842
843    #[deprecated(
844        note = "Ensure this function is self-contained. This is a temporary measure for debugging purposes."
845    )]
846    /// Directly evaluates currently linked ancillary wasm dependencies.
847    pub const fn targets(&self) -> &Box<[WasmPath]> {
848        &self.targets
849    }
850
851    /// Securely uncovers operational variables tracking internal generational properties dynamically.
852    pub const fn ctx(&self) -> &GeneratorCtx {
853        &self.ctx
854    }
855
856    /// Confirms mapping configurations and statically evaluates lazy initializations strictly allocating paths.
857    pub fn definitely(&mut self) -> eyre::Result<()> {
858        self.path
859            .definitely(self.ctx.threads, &self.vfs_build_opts)?;
860        for (i, target) in self.targets.iter_mut().enumerate() {
861            target.definitely(self.ctx.threads, &self.target_vfs_build_opts[i])?;
862        }
863        Ok(())
864    }
865
866    /// Primary operation chaining logic seamlessly running structural modifiers across all layered stages sequentially terminating out into WebAssembly components.
867    pub fn run_layers_to_component(
868        mut self,
869        out_dir: &Utf8PathBuf,
870        keep_build_artifacts: bool,
871    ) -> eyre::Result<ComponentRunner> {
872        self.definitely()?;
873
874        let toml_restorers = self
875            .toml_restorers
876            .take()
877            .ok_or_else(|| eyre::eyre!("TomlRestorers already taken"))?;
878
879        toml_restorers
880            .restore()
881            .wrap_err("Failed to restore toml files")?;
882
883        let mut mem_id_visitor = MemoryIDVisitor {
884            memory_hint: self.memory_hint.clone(),
885            used_vfs_memory_id: None,
886            used_target_memory_id: None,
887        };
888        let mut global_id_visitor = GlobalIdVisitor {
889            vfs_global_id: None,
890            global_id: None,
891        };
892        let dwarf = self.ctx.dwarf;
893
894        println!("Remove existing output directory...");
895        if std::fs::metadata(&out_dir).is_ok() {
896            std::fs::remove_dir_all(&out_dir).expect("Failed to remove existing directory");
897        }
898        std::fs::create_dir_all(&out_dir).expect("Failed to create output directory");
899
900        let mut component_ctx_visitor = ComponentCtxVisitor::new(
901            self.ctx.vfs_name.clone(),
902            self.ctx.target_names.clone(),
903            self.ctx.target_memory_type,
904            self.ctx.unstable_print_debug,
905            self.ctx.dwarf,
906            self.ctx.threads,
907            self.ctx.adjust_abi,
908        );
909
910        println!("Adjusting VFS Wasm...");
911        (|path: &mut WasmPath| {
912            (|module: &mut walrus::Module| {
913                self.checkers
914                    .pre_vfs(module, &self.ctx)
915                    .wrap_err("Failed to run checkers in pre_vfs")?;
916
917                mem_id_visitor
918                    .pre_vfs(module, &self.ctx)
919                    .wrap_err("Failed in pre_vfs")?;
920                global_id_visitor
921                    .pre_vfs(module, &self.ctx)
922                    .wrap_err("Failed in pre_vfs")?;
923
924                self.ctx.vfs_used_memory_id = mem_id_visitor.used_vfs_memory_id;
925
926                component_ctx_visitor
927                    .pre_vfs(module, &self.ctx)
928                    .wrap_err("Failed in pre_vfs")?;
929
930                self.generators
931                    .pre_vfs(module, &self.ctx)
932                    .wrap_err("Failed in run_pre_vfs")
933            })
934            .wrap_run(path, dwarf, keep_build_artifacts)
935        })
936        .with_opt(&mut self.path, dwarf, keep_build_artifacts)?;
937
938        println!("Adjusting target Wasm...");
939        self.ctx.vfs_used_memory_id = None;
940        for (target, target_name) in self.targets.iter_mut().zip(self.ctx.target_names.clone()) {
941            (|path: &mut WasmPath| {
942                (|module: &mut walrus::Module| {
943                    let external = ModuleExternal::new(&target_name);
944                    mem_id_visitor
945                        .pre_target(module, &self.ctx, &external)
946                        .wrap_err("Failed in pre_target")?;
947                    global_id_visitor
948                        .pre_target(module, &self.ctx, &external)
949                        .wrap_err("Failed in pre_target")?;
950
951                    self.ctx.target_used_memory_id = mem_id_visitor.used_target_memory_id.clone();
952
953                    self.generators
954                        .pre_target(module, &self.ctx, &external)
955                        .wrap_err("Failed in run_pre_target")
956                })
957                .wrap_run(path, dwarf, keep_build_artifacts)
958            })
959            .with_opt(target, dwarf, keep_build_artifacts)?;
960        }
961
962        println!("Combining Wasm modules...");
963        self.ctx.vfs_used_memory_id = None;
964        self.ctx.target_used_memory_id = None;
965        let output = format!("{out_dir}/merged.wasm");
966        (|path: &mut WasmPath| {
967            let old_path = path.path()?.clone();
968            merge(
969                &old_path,
970                &self
971                    .targets
972                    .iter()
973                    .map(|t| t.path())
974                    .collect::<eyre::Result<Vec<_>>>()?,
975                &output,
976                self.ctx.threads,
977                dwarf,
978            )
979            .wrap_err("Failed to combine Wasm modules")?;
980
981            if !keep_build_artifacts {
982                std::fs::remove_file(&old_path)
983                    .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
984                for target in self.targets.iter() {
985                    if let Ok(target_path) = target.path() {
986                        if !target.is_original(target_path) {
987                            std::fs::remove_file(target_path).unwrap_or_else(|e| {
988                                log::warn!(
989                                    "Failed to remove intermediate target file {target_path}: {e}"
990                                );
991                            });
992                        }
993                    }
994                }
995            }
996
997            path.set_path(output.into())
998        })
999        .with_opt(&mut self.path, dwarf, keep_build_artifacts)?;
1000
1001        println!("Adjusting Merged Wasm...");
1002        (|path: &mut WasmPath| {
1003            (|module: &mut walrus::Module| {
1004                mem_id_visitor
1005                    .post_combine(module, &self.ctx)
1006                    .wrap_err("Failed in post_combine")?;
1007                global_id_visitor
1008                    .post_combine(module, &self.ctx)
1009                    .wrap_err("Failed in post_combine")?;
1010                let mut start_func_id_visitor = StartFuncIdVisitor::default();
1011                start_func_id_visitor
1012                    .post_combine(module, &self.ctx)
1013                    .wrap_err("Failed in post_combine")?;
1014
1015                self.ctx.vfs_used_memory_id = mem_id_visitor.used_vfs_memory_id.take();
1016                self.ctx.target_used_memory_id = mem_id_visitor.used_target_memory_id.take();
1017
1018                self.ctx.vfs_used_global_id = global_id_visitor.vfs_global_id.take();
1019                self.ctx.target_used_global_id = global_id_visitor.global_id.take();
1020
1021                self.ctx.start_func_id = start_func_id_visitor.start_func_id.take();
1022
1023                self.generators.post_combine(module, &self.ctx)?;
1024
1025                Ok(())
1026            })
1027            .wrap_run(path, dwarf, keep_build_artifacts)
1028        })
1029        .with_opt(&mut self.path, dwarf, keep_build_artifacts)?;
1030
1031        self.ctx.vfs_used_memory_id = None;
1032        self.ctx.target_used_memory_id = None;
1033
1034        self.ctx.vfs_used_global_id = None;
1035        self.ctx.target_used_global_id = None;
1036
1037        self.ctx.start_func_id = None;
1038
1039        if self.ctx.target_memory_type == TargetMemoryType::Single {
1040            let old_path = self.path.path()?.clone();
1041
1042            println!("Generating single memory Merged Wasm...");
1043            let optimized_path =
1044                compile::optimize_wasm(&old_path, &["--multi-memory-lowering"], true, dwarf)?;
1045
1046            if !keep_build_artifacts {
1047                std::fs::remove_file(&old_path)
1048                    .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
1049            }
1050
1051            self.path.set_path(optimized_path)?;
1052
1053            (|path: &mut WasmPath| {
1054                (|module: &mut walrus::Module| {
1055                    // module.flatten_tables()?;
1056
1057                    mem_id_visitor
1058                        .post_lower_memory(module, &self.ctx)
1059                        .wrap_err("Failed in post_lower_memory")?;
1060
1061                    self.ctx.vfs_used_memory_id = mem_id_visitor.used_vfs_memory_id.take();
1062                    self.ctx.target_used_memory_id = mem_id_visitor.used_target_memory_id.take();
1063
1064                    self.generators
1065                        .post_lower_memory(module, &self.ctx)
1066                        .wrap_err("Failed in run_post_lower_memory")?;
1067
1068                    Ok(())
1069                })
1070                .wrap_run(path, dwarf, keep_build_artifacts)
1071            })
1072            .with_opt(&mut self.path, dwarf, keep_build_artifacts)?;
1073        }
1074
1075        println!("Translating Wasm to Component...");
1076        let old_path = self.path.path()?.clone();
1077        let component = compile::wasm_to_component(&old_path, &self.ctx.target_names)
1078            .wrap_err("Failed to translate Wasm to Component")?;
1079        if !keep_build_artifacts {
1080            std::fs::remove_file(&old_path)
1081                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
1082        }
1083
1084        let new_component = format!("{out_dir}/{}.component.wasm", self.ctx.vfs_name);
1085        std::fs::rename(&component, &new_component)
1086            .wrap_err_with(|| format!("Failed to rename file {component} to {new_component}"))?;
1087
1088        self.path.set_path(Utf8PathBuf::from(new_component))?;
1089
1090        Ok(ComponentRunner::with_generators(self.path, self.generators))
1091    }
1092}
1093
1094impl ComponentRunner {
1095    /// Instantiates a fresh `ComponentRunner` targeting a specific underlying WebAssembly structure.
1096    pub fn new(path: WasmPath) -> Self {
1097        Self {
1098            generators: Vec::new(),
1099            ctx: None,
1100            path,
1101            wasm_name_holder: None,
1102        }
1103    }
1104
1105    /// Installs a specific invariant-checking generator executing without altering primary execution pathways.
1106    pub fn checker(&mut self, checker: impl Generator + 'static) {
1107        self.generators.push(Box::new(checker));
1108    }
1109
1110    /// Quickly constructs a runner wrapping a pre-defined array containing generator strategies.
1111    pub fn with_generators(path: WasmPath, generators: Vec<Box<dyn Generator + 'static>>) -> Self {
1112        Self {
1113            generators,
1114            ctx: None,
1115            path,
1116            wasm_name_holder: None,
1117        }
1118    }
1119
1120    /// Queues an advanced generative instruction step executed successively upon evaluation.
1121    pub fn add_generator<G: Generator + 'static>(&mut self, generator: G) {
1122        self.generators.push(Box::new(generator));
1123    }
1124
1125    /// Allows querying the internal generator stack dynamically retrieving explicitly modeled type structures.
1126    pub fn get_generator_ref<T: Generator + 'static>(&self) -> eyre::Result<&T> {
1127        fn downcast_ref<T: 'static>(b: &dyn Any) -> Option<&'_ T> {
1128            if b.is::<T>() {
1129                Some(b.downcast_ref::<T>().unwrap())
1130            } else {
1131                None
1132            }
1133        }
1134
1135        self.generators
1136            .iter()
1137            .map(|g| g.as_ref())
1138            .find_map(|g| downcast_ref::<T>(g))
1139            .wrap_err_with(|| {
1140                eyre::eyre!("Failed to get generator: {}", core::any::type_name::<T>())
1141            })
1142            .wrap_err_with(|| eyre::eyre!("Available generators: {:?}", self.generators))
1143    }
1144
1145    /// return is_threads, core_name, mem_size
1146    pub fn component_to_files(
1147        &mut self,
1148        parsed_args: &(impl args::PostBuildContext + ?Sized),
1149        dwarf: bool,
1150        only_core: bool,
1151    ) -> eyre::Result<(bool, CompactString, HashMap<CompactString, (u64, u64)>)> {
1152        let out_dir = parsed_args.out_dir();
1153
1154        let name = self.path.name()?;
1155
1156        println!("Translating Component to JS...");
1157        let core_wasm_path = (|path: &mut WasmPath| {
1158            let old_path = path.path()?.clone();
1159            let binary = std::fs::read(&old_path).wrap_err("Failed to read component")?;
1160            let transpiled = parsed_args
1161                .transpile_to_js(&binary, &name)
1162                .wrap_err("Failed to transpile to JS")?;
1163
1164            let mut core_wasm = None;
1165            for (name, data) in transpiled.files.iter() {
1166                let name = camino::Utf8PathBuf::from(name);
1167                let file_name = out_dir.join(&name);
1168                if std::fs::metadata(&file_name).is_ok() {
1169                    std::fs::remove_file(&file_name).wrap_err_with(|| {
1170                        eyre::eyre!("Failed to remove existing file: {file_name}")
1171                    })?;
1172                }
1173                if name.as_str().ends_with(".core.wasm") {
1174                    let file_name = camino::Utf8PathBuf::from(file_name);
1175                    std::fs::write(&file_name, &data).wrap_err_with(|| {
1176                        eyre::eyre!("Failed to write core wasm file: {file_name}")
1177                    })?;
1178                    core_wasm = Some(file_name);
1179                } else {
1180                    if let Some(parent) = name.parent() {
1181                        if !parent.as_str().is_empty() {
1182                            let dir = name.ancestors().nth(1).wrap_err_with(|| {
1183                                eyre::eyre!("Failed to get parent directory: {}", name)
1184                            })?;
1185                            let joined_dir = out_dir.join(dir);
1186                            if !std::fs::metadata(&joined_dir).is_ok() {
1187                                if dir.as_str() != "interfaces" {
1188                                    log::warn!("Creating directory: {joined_dir}");
1189                                }
1190                                if only_core {
1191                                    continue;
1192                                }
1193                                std::fs::create_dir_all(&joined_dir).wrap_err_with(|| {
1194                                    eyre::eyre!("Failed to create directory: {joined_dir}")
1195                                })?;
1196                            }
1197                        }
1198                    }
1199                    if only_core {
1200                        continue;
1201                    }
1202                    std::fs::write(&file_name, &data).wrap_err_with(|| {
1203                        eyre::eyre!("Failed to write transpiled file: {file_name}")
1204                    })?;
1205                }
1206            }
1207
1208            let core_wasm = core_wasm
1209                .as_ref()
1210                .ok_or_else(|| eyre::eyre!("Failed to find core wasm"))?;
1211
1212            if !parsed_args.keep_build_artifacts() {
1213                std::fs::remove_file(&old_path)
1214                    .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
1215            }
1216            path.set_path(core_wasm.clone())?;
1217
1218            Ok(core_wasm.clone())
1219        })
1220        .with_opt(&mut self.path, dwarf, parsed_args.keep_build_artifacts())?;
1221
1222        let mem_size_visitor = MemorySizeVisitor::default();
1223        self.generators.push(Box::new(mem_size_visitor));
1224
1225        println!("Adjusting component Merged Wasm...");
1226        (|path: &mut WasmPath| {
1227            (|module: &mut walrus::Module| {
1228                let mut visitor = ComponentCtxVisitor::default();
1229                visitor
1230                    .post_components(
1231                        module,
1232                        &ComponentCtx {
1233                            dwarf,
1234                            ..Default::default()
1235                        },
1236                    )
1237                    .wrap_err("Failed in post_components")?;
1238                let wasm_name_holder = WasmNameHolder::new(
1239                    visitor
1240                        .target_names
1241                        .unwrap()
1242                        .into_iter()
1243                        .chain(core::iter::once(visitor.vfs_name.unwrap()))
1244                        .collect::<Box<_>>(),
1245                );
1246                self.wasm_name_holder = Some(wasm_name_holder);
1247                let mut wasm_name_holder_iter = self.wasm_name_holder.as_ref().unwrap().iter();
1248                self.ctx = Some(ComponentCtx {
1249                    vfs_name: Some(wasm_name_holder_iter.next().unwrap()),
1250                    target_names: Some(wasm_name_holder_iter.collect::<Box<_>>()),
1251                    target_memory_type: Some(visitor.target_memory_type.unwrap()),
1252                    unstable_print_debug: Some(visitor.unstable_print_debug.unwrap()),
1253                    dwarf: visitor.dwarf.unwrap(),
1254                    threads: Some(visitor.threads.unwrap()),
1255                    adjust_abi: visitor.adjust_abi,
1256                });
1257
1258                self.generators
1259                    .post_components(module, self.ctx.as_ref().unwrap())
1260                    .wrap_err("Failed in run_post_components")
1261            })
1262            .wrap_run(path, dwarf, parsed_args.keep_build_artifacts())
1263        })
1264        .with_opt(&mut self.path, dwarf, parsed_args.keep_build_artifacts())?;
1265
1266        let dwarf = {
1267            let new_dwarf = self.ctx.as_ref().unwrap().dwarf;
1268            if dwarf && !new_dwarf {
1269                log::warn!(
1270                    "Dwarf was disabled in component processing, you should re-run with --dwarf"
1271                );
1272            }
1273            new_dwarf
1274        };
1275
1276        println!("Final optimizing Merged Wasm...");
1277        let mut i = 0;
1278        while i < self.generators.len() {
1279            (|module: &mut walrus::Module| {
1280                loop {
1281                    if self.generators[i]
1282                        .post_all_optimize(module, self.ctx.as_ref().unwrap())
1283                        .wrap_err("Failed in post_all_optimize")?
1284                    {
1285                        i += 1;
1286                        return Ok(());
1287                    }
1288                    i += 1;
1289                    if i >= self.generators.len() {
1290                        return Ok(());
1291                    }
1292                }
1293            })
1294            .wrap_run(&mut self.path, dwarf, parsed_args.keep_build_artifacts())?;
1295        }
1296
1297        std::fs::rename(self.path.path()?, &core_wasm_path).wrap_err_with(|| {
1298            eyre::eyre!(
1299                "Failed to rename final wasm from {} to {}",
1300                self.path.path().unwrap(),
1301                core_wasm_path
1302            )
1303        })?;
1304
1305        Ok((
1306            self.ctx.as_ref().unwrap().threads(),
1307            core_wasm_path
1308                .get_file_main_name()
1309                .ok_or_else(|| eyre::eyre!("Failed to get file name"))?,
1310            self.get_generator_ref::<MemorySizeVisitor>()?
1311                .mem_size
1312                .clone()
1313                .unwrap(),
1314        ))
1315    }
1316}
1317
1318#[derive(Debug, Default, Clone)]
1319struct MemoryIDVisitor {
1320    pub memory_hint: HashMap<WasmName, usize>,
1321    pub used_vfs_memory_id: Option<MemoryId>,
1322    pub used_target_memory_id: Option<HashMap<WasmName, MemoryId>>,
1323}
1324
1325impl Generator for MemoryIDVisitor {
1326    fn pre_vfs(
1327        &mut self,
1328        module: &mut walrus::Module,
1329        _: &crate::generator::GeneratorCtx,
1330    ) -> eyre::Result<()> {
1331        println!("Finding VFS memory id...");
1332
1333        let id = module
1334            .get_memory_anchor("vfs", false)
1335            .wrap_err("Failed to get target memory id")?;
1336        self.used_vfs_memory_id = Some(id);
1337        Ok(())
1338    }
1339
1340    fn pre_target(
1341        &mut self,
1342        module: &mut walrus::Module,
1343        _: &crate::generator::GeneratorCtx,
1344        external: &ModuleExternal,
1345    ) -> eyre::Result<()> {
1346        let id = module
1347            .find_used_memory_id(self.memory_hint.get(&external.name).copied())
1348            .wrap_err("Failed to find used memory id")?;
1349        module
1350            .create_memory_anchor(&external.name, id)
1351            .wrap_err("Failed to create memory anchor")?;
1352        self.used_target_memory_id
1353            .get_or_insert_default()
1354            .insert(external.name.clone(), id);
1355        Ok(())
1356    }
1357
1358    fn post_combine(
1359        &mut self,
1360        module: &mut walrus::Module,
1361        ctx: &GeneratorCtx,
1362    ) -> eyre::Result<()> {
1363        let id = module
1364            .get_memory_anchor("vfs", true)
1365            .wrap_err("Failed to find used memory id after combine")?;
1366        self.used_vfs_memory_id = Some(id);
1367
1368        self.used_target_memory_id.get_or_insert_default().clear();
1369        for wasm in &ctx.target_names {
1370            let id = module
1371                .get_memory_anchor(wasm, true)
1372                .wrap_err("Failed to find used memory id after combine")?;
1373            self.used_target_memory_id
1374                .as_mut()
1375                .unwrap()
1376                .insert(wasm.clone(), id);
1377        }
1378
1379        Ok(())
1380    }
1381
1382    fn post_lower_memory(
1383        &mut self,
1384        module: &mut walrus::Module,
1385        _: &GeneratorCtx,
1386    ) -> eyre::Result<()> {
1387        let id = module
1388            .get_memory_id()
1389            .to_eyre()
1390            .wrap_err("Failed to get single memory id after lowering")?;
1391        self.used_vfs_memory_id = Some(id);
1392        self.used_target_memory_id = None;
1393
1394        Ok(())
1395    }
1396}
1397
1398#[derive(Debug, Default, Clone)]
1399struct MemorySizeVisitor {
1400    mem_size: Option<HashMap<CompactString, (u64, u64)>>,
1401}
1402
1403impl Generator for MemorySizeVisitor {
1404    fn post_components(
1405        &mut self,
1406        module: &mut walrus::Module,
1407        _: &ComponentCtx,
1408    ) -> eyre::Result<()> {
1409        let mem_size = module
1410            .memories
1411            .iter()
1412            .filter(|mem| mem.import.is_some())
1413            .map(|mem| {
1414                (
1415                    module
1416                        .imports
1417                        .get(mem.import.unwrap())
1418                        .name
1419                        .to_compact_string(),
1420                    (
1421                        mem.initial as u64,
1422                        mem.maximum.unwrap_or(mem.initial) as u64,
1423                    ),
1424                )
1425            })
1426            .collect::<HashMap<_, _>>();
1427        self.mem_size = Some(mem_size);
1428
1429        Ok(())
1430    }
1431}
1432
1433#[derive(Debug, Default)]
1434struct GlobalIdVisitor {
1435    vfs_global_id: Option<Box<[walrus::GlobalId]>>,
1436    global_id: Option<HashMap<WasmName, Box<[walrus::GlobalId]>>>,
1437}
1438impl Generator for GlobalIdVisitor {
1439    fn pre_vfs(&mut self, module: &mut walrus::Module, _: &GeneratorCtx) -> eyre::Result<()> {
1440        module
1441            .create_global_anchor("vfs")
1442            .wrap_err("Failed to create global anchor")?;
1443
1444        Ok(())
1445    }
1446
1447    fn pre_target(
1448        &mut self,
1449        module: &mut walrus::Module,
1450        _: &GeneratorCtx,
1451        external: &ModuleExternal,
1452    ) -> eyre::Result<()> {
1453        module
1454            .create_global_anchor(&external.name)
1455            .wrap_err("Failed to create global anchor")?;
1456
1457        Ok(())
1458    }
1459
1460    fn post_combine(
1461        &mut self,
1462        module: &mut walrus::Module,
1463        ctx: &GeneratorCtx,
1464    ) -> eyre::Result<()> {
1465        self.global_id = Some(HashMap::new());
1466
1467        let vfs_globals = module
1468            .get_global_anchor("vfs")
1469            .wrap_err("Failed to get global anchor for vfs")?;
1470        self.vfs_global_id = Some(vfs_globals);
1471
1472        for wasm in &ctx.target_names {
1473            let globals = module
1474                .get_global_anchor(wasm)
1475                .wrap_err_with(|| format!("Failed to get global anchor for {wasm}"))?;
1476            self.global_id
1477                .as_mut()
1478                .unwrap()
1479                .insert(wasm.clone(), globals);
1480        }
1481
1482        Ok(())
1483    }
1484}
1485
1486/// To be used from both `special_func`'s `main_void` and `start`,
1487/// it must be prepared in `ctx`.
1488#[derive(Debug, Default)]
1489struct StartFuncIdVisitor {
1490    start_func_id: Option<HashMap<WasmName, walrus::FunctionId>>,
1491}
1492
1493impl Generator for StartFuncIdVisitor {
1494    fn post_combine(
1495        &mut self,
1496        module: &mut walrus::Module,
1497        ctx: &GeneratorCtx,
1498    ) -> eyre::Result<()> {
1499        for wasm in &ctx.target_names {
1500            // NOTE: wasm-merge preserves the package name with dashes for some exports,
1501            // but the __start_anchor from the Rust macros has underscores.
1502            let normalized_wasm = wasm.as_ref().replace('-', "_");
1503            // let export_name = format!("__wasip1_vfs_{wasm}__start");
1504
1505            let export = format!("__wasip1_vfs_{wasm}__start").get_fid(&module.exports)?;
1506            self.start_func_id
1507                .get_or_insert_default()
1508                .insert(wasm.clone(), export);
1509
1510            // NOTE: Don't erase the __start export - it's needed for StartFunc
1511            // to find it as an import or to redirect calls to it.
1512
1513            // The anchor export was created by import_wasm! macro and uses underscores
1514            module.exports.erase_with(
1515                &format!("__wasip1_vfs_{normalized_wasm}__start_anchor"),
1516                ctx.unstable_print_debug,
1517            )?;
1518        }
1519
1520        Ok(())
1521    }
1522}
1523
1524/// Represents the resolution state and file format targeting for manipulating WebAssembly modules intelligently.
1525#[derive(Debug, Clone, Hash)]
1526pub enum WasmPath {
1527    /// Indicates the target still needs compilation through standard cargo dependencies.
1528    Maybe {
1529        /// Fully resolved physical path to the corresponding Cargo.toml manifest definition.
1530        manifest_path: Utf8PathBuf,
1531        /// Specified internal crate package identifier.
1532        package: String,
1533    },
1534    /// A strictly resolved raw WebAssembly binary file ready for patching operations.
1535    Definitely(Utf8PathBuf),
1536    /// A completed explicitly transpiled WebAssembly Component standard architecture module.
1537    Component(Utf8PathBuf),
1538    /// A user-provided raw WebAssembly binary file that should never be deleted.
1539    /// The inner path tracks the original file location.
1540    Original {
1541        /// The current working path (may change as transformations produce new files).
1542        current: Utf8PathBuf,
1543        /// The original user-provided path that must be preserved.
1544        original: Utf8PathBuf,
1545    },
1546}
1547
1548impl FromStr for WasmPath {
1549    type Err = eyre::Error;
1550
1551    /// manifest_path :: package
1552    fn from_str(s: &str) -> Result<Self, Self::Err> {
1553        fn parse_path_and_package(s: &str) -> eyre::Result<Option<WasmPath>> {
1554            let split = s.split("::").collect::<Vec<_>>();
1555            if split.len() == 2 {
1556                let manifest_path = Utf8PathBuf::from_str(split[0])
1557                    .wrap_err_with(|| format!("Failed to parse manifest path: {}", split[0]))?;
1558                let package = split[1].to_string();
1559                return Ok(Some(WasmPath::Maybe {
1560                    manifest_path,
1561                    package,
1562                }));
1563            }
1564            Ok(None)
1565        }
1566
1567        if let Some(wasm_path) =
1568            parse_path_and_package(s).wrap_err("Failed to parse path and package")?
1569        {
1570            return Ok(wasm_path);
1571        }
1572
1573        if s.ends_with(".wasm") {
1574            let path = Utf8PathBuf::from_str(s)
1575                .wrap_err_with(|| format!("Failed to parse wasm path: {s}"))?;
1576            return WasmPath::with_wasm(path);
1577        }
1578
1579        if s.ends_with("Cargo.toml") {
1580            let manifest_path = Utf8PathBuf::from_str(s)
1581                .wrap_err_with(|| format!("Failed to parse manifest path: {s}"))?;
1582            return WasmPath::with_maybe_only_manifest(manifest_path);
1583        }
1584
1585        WasmPath::with_maybe_only_package(s.to_string())
1586            .wrap_err_with(|| format!("Failed to parse package name: {s}"))
1587    }
1588}
1589
1590impl WasmPath {
1591    /// Computes the unique short name used during module linking and identification.
1592    pub fn name(&self) -> eyre::Result<CompactString> {
1593        match self {
1594            WasmPath::Maybe { package, .. } => {
1595                // Normalize package name by replacing hyphens with underscores
1596                // This is necessary because Rust package names can have hyphens (e.g., "test-package")
1597                // but they are converted to underscores in module identifiers (e.g., "test_package")
1598                let normalized = package.replace('-', "_");
1599                Ok(normalized.to_compact_string())
1600            }
1601            WasmPath::Definitely(path)
1602            | WasmPath::Component(path)
1603            | WasmPath::Original { current: path, .. } => path
1604                .get_file_main_name()
1605                .ok_or_else(|| eyre::eyre!("Failed to get file name from {path}")),
1606        }
1607    }
1608
1609    /// Exposes the manifest path conditionally if the dependency is unresolved logically.
1610    pub fn manifest_path(&self) -> Option<&Utf8PathBuf> {
1611        match self {
1612            WasmPath::Maybe { manifest_path, .. } => Some(manifest_path),
1613            WasmPath::Definitely(_) | WasmPath::Component(_) | WasmPath::Original { .. } => None,
1614        }
1615    }
1616
1617    /// Calculates the overarching workspace root via dependency graphing context implicitly.
1618    pub fn root_manifest_path(&self) -> Option<Utf8PathBuf> {
1619        match self {
1620            WasmPath::Maybe { manifest_path, .. } => {
1621                let cargo_metadata = {
1622                    let mut metadata_command = cargo_metadata::MetadataCommand::new();
1623                    metadata_command.manifest_path(&manifest_path);
1624                    metadata_command.exec().unwrap()
1625                };
1626                Some(cargo_metadata.workspace_root.join("Cargo.toml"))
1627            }
1628            WasmPath::Definitely(_) | WasmPath::Component(_) | WasmPath::Original { .. } => None,
1629        }
1630    }
1631
1632    /// Statically assigns an unresolved target using defined package specifications.
1633    pub const fn with_maybe(manifest_path: Utf8PathBuf, package: String) -> Self {
1634        Self::Maybe {
1635            manifest_path,
1636            package,
1637        }
1638    }
1639
1640    /// Constructs an unresolved dependency resolving package tracking inherently from a file manifest dynamically.
1641    pub fn with_maybe_only_manifest(manifest_path: Utf8PathBuf) -> eyre::Result<Self> {
1642        let cargo_metadata = {
1643            let mut metadata_command = cargo_metadata::MetadataCommand::new();
1644            metadata_command.manifest_path(&manifest_path);
1645            metadata_command.exec().unwrap()
1646        };
1647        let building_crate = compile::get_building_crate(&cargo_metadata, &None)?;
1648
1649        Ok(Self::Maybe {
1650            manifest_path,
1651            package: building_crate.name.to_string(),
1652        })
1653    }
1654
1655    /// Assesses global cargo metadata configuring definitions matching solely the provided string identifier.
1656    pub fn with_maybe_only_package(package: String) -> eyre::Result<Self> {
1657        let cargo_metadata = {
1658            let metadata_command = cargo_metadata::MetadataCommand::new();
1659            metadata_command.exec().unwrap()
1660        };
1661        let building_crate = compile::get_building_crate(&cargo_metadata, &Some(package.clone()))?;
1662
1663        Ok(Self::Maybe {
1664            manifest_path: building_crate.manifest_path,
1665            package: building_crate.name.to_string(),
1666        })
1667    }
1668
1669    /// Loads an unresolved dependency using current environment cargo bounds natively.
1670    pub fn with_maybe_none() -> eyre::Result<Self> {
1671        let cargo_metadata = {
1672            let metadata_command = cargo_metadata::MetadataCommand::new();
1673            metadata_command.exec().unwrap()
1674        };
1675        let building_crate = compile::get_building_crate(&cargo_metadata, &None)?;
1676
1677        Ok(Self::Maybe {
1678            manifest_path: building_crate.manifest_path,
1679            package: building_crate.name.to_string(),
1680        })
1681    }
1682
1683    /// Scans an exact provided `.wasm` artifact verifying magic byte signatures correctly to assign a resolution state.
1684    /// User-provided `.wasm` files are wrapped in `Original` to prevent deletion of the original file.
1685    pub fn with_wasm(path: Utf8PathBuf) -> eyre::Result<Self> {
1686        if path.extension() != Some("wasm") {
1687            eyre::bail!("Wasm file does not have .wasm extension: {path}");
1688        }
1689        if !fs::metadata(&path).is_ok() {
1690            eyre::bail!("Wasm file does not exist: {path}");
1691        }
1692
1693        let mut file =
1694            fs::File::open(&path).wrap_err_with(|| format!("Failed to open wasm file: {path}"))?;
1695        let mut magic = [0u8; 8];
1696        file.read_exact(&mut magic)
1697            .wrap_err_with(|| format!("Failed to read magic number from wasm file: {path}"))?;
1698        if !magic.starts_with(b"\0asm") {
1699            eyre::bail!("Wasm file does not have valid magic number: {path}");
1700        }
1701        let version = &magic[4..8];
1702        // https://github.com/WebAssembly/component-model/blob/main/design/mvp/Binary.md#component-definitions
1703        if version == [0x0D, 0x00, 0x01, 0x00] {
1704            return Ok(Self::Component(path));
1705        }
1706        // https://webassembly.github.io/spec/core/binary/modules.html#binary-module
1707        if version != [0x01, 0x00, 0x00, 0x00] {
1708            eyre::bail!("Wasm file does not have valid version: {path}");
1709        }
1710
1711        Ok(Self::Original {
1712            current: path.clone(),
1713            original: path,
1714        })
1715    }
1716
1717    /// Forcefully invokes internal compiling mechanisms translating a declarative specification down into an executable binary structurally.
1718    pub fn definitely(
1719        &mut self,
1720        threads: bool,
1721        vfs_build_opts: &args::VfsBuildOptions,
1722    ) -> eyre::Result<()> {
1723        if let WasmPath::Maybe {
1724            manifest_path,
1725            package,
1726        } = self
1727        {
1728            let cargo_metadata = {
1729                let mut metadata_command = cargo_metadata::MetadataCommand::new();
1730                metadata_command.manifest_path(&manifest_path);
1731                metadata_command.exec().unwrap()
1732            };
1733            let building_crate =
1734                compile::get_building_crate(&cargo_metadata, &Some(package.clone()))?;
1735            let vfs_name = building_crate.name.to_string();
1736
1737            let path = compile::build_vfs(
1738                Some(&manifest_path.to_string()),
1739                &building_crate,
1740                threads,
1741                vfs_build_opts,
1742            )
1743            .wrap_err_with(|| eyre::eyre!("Failed to build VFS: {vfs_name}"))?;
1744            *self = WasmPath::Definitely(path);
1745        }
1746
1747        // Original variant is already resolved, no action needed.
1748
1749        Ok(())
1750    }
1751
1752    /// Returns the path to the WASM module.
1753    pub fn path(&self) -> eyre::Result<&Utf8PathBuf> {
1754        match self {
1755            WasmPath::Maybe { .. } => {
1756                eyre::bail!("WasmPath is not definitely set: {self:?}")
1757            }
1758            WasmPath::Definitely(p)
1759            | WasmPath::Component(p)
1760            | WasmPath::Original { current: p, .. } => Ok(p),
1761        }
1762    }
1763
1764    /// Returns `true` if the given path is the original user-provided file that should be preserved.
1765    pub fn is_original(&self, path: &Utf8PathBuf) -> bool {
1766        matches!(self, WasmPath::Original { original, .. } if original == path)
1767    }
1768
1769    /// Forcefully overrides the explicitly resolved file path for definite path targets.
1770    /// For `Original` variants, preserves the original path tracking.
1771    pub fn set_path(&mut self, path: Utf8PathBuf) -> eyre::Result<()> {
1772        match self {
1773            WasmPath::Maybe { .. } => {
1774                eyre::bail!("WasmPath is not definitely set: {path}")
1775            }
1776            WasmPath::Original { current, .. } => {
1777                // Keep the original path, only update current
1778                *current = path;
1779            }
1780            _ => {
1781                *self = WasmPath::Definitely(path);
1782            }
1783        }
1784        Ok(())
1785    }
1786}
1787
1788/// Coordinates the underlying binary `wasm-merge` utility invocations to bundle outputs physically.
1789pub fn merge(
1790    vfs: &Utf8PathBuf,
1791    wasm: &[impl AsRef<std::path::Path>],
1792    output: impl AsRef<std::path::Path>,
1793    _threads: bool,
1794    dwarf: bool,
1795) -> eyre::Result<()> {
1796    let custom_section = {
1797        let mut vfs_module = walrus::Module::load(vfs, dwarf)?;
1798        let custom_section_names = vfs_module
1799            .customs
1800            .iter()
1801            .map(|(_, section)| section.name().to_string())
1802            .filter(|name| name.starts_with("component-type:"))
1803            .collect::<Vec<_>>();
1804        // let custom_section = vfs_module
1805        //     .customs.delete(custom_section_names)
1806        let custom_section = custom_section_names
1807            .iter()
1808            .map(|id| {
1809                let section = vfs_module.customs.remove_raw(id);
1810                section.unwrap()
1811            })
1812            .collect::<Vec<_>>();
1813
1814        custom_section
1815    };
1816
1817    let mut merge_cmd = fallback_command::get_fallback_command("wasm-merge");
1818
1819    // if threads {
1820    //     merge_cmd.arg("--enable-threads");
1821    // }
1822
1823    if dwarf {
1824        merge_cmd.arg("--debuginfo");
1825    }
1826
1827    merge_cmd.arg(vfs).arg(UniqueName::WASIP1_ABI_MODULE);
1828
1829    for wasm in wasm {
1830        merge_cmd
1831            .arg(wasm.as_ref().as_os_str().to_str().unwrap())
1832            .arg(format!(
1833                "wasip1_vfs_{}",
1834                wasm.as_ref().get_file_main_name().unwrap()
1835            ));
1836    }
1837
1838    merge_cmd
1839        .arg("--output")
1840        .arg(output.as_ref().as_os_str().to_str().unwrap())
1841        // .arg("--rename-export-conflicts")
1842        .arg("--enable-multimemory")
1843        .arg("--enable-threads");
1844
1845    let result = merge_cmd
1846        .spawn()
1847        .map_err(|e| match e.kind() {
1848            std::io::ErrorKind::NotFound => eyre::eyre!(
1849                "wasm-merge command not found. Please install wasm-merge from https://github.com/WebAssembly/binaryen/releases/latest"
1850            ),
1851            _ => e.into(),
1852        })?
1853        .wait_with_output()
1854        .wrap_err("Failed to wait for wasm-merge process")?;
1855
1856    if !result.success {
1857        let error_message = String::from_utf8_lossy(&result.stdout);
1858
1859        return Err(eyre::eyre!("wasm-merge command failed: {error_message}"));
1860    }
1861
1862    let mut module = walrus::Module::load(output.as_ref(), dwarf)?;
1863    for section in custom_section {
1864        module.customs.add(section);
1865    }
1866
1867    // to output
1868    fs::remove_file(output.as_ref()).expect("Failed to remove existing file");
1869
1870    module
1871        .emit_wasm_file(output.as_ref())
1872        .expect("Failed to emit wasm file");
1873
1874    Ok(())
1875}
1876
1877macro_rules! _add_generators_by_type {
1878    ($runner:expr, $($ty:ty),* $(,)?) => {
1879        $(
1880            if let Some(_) = $runner.get_generator_ref::<$ty>().ok() {
1881                panic!("Generator of type {} already exists", std::any::type_name::<$ty>());
1882            }
1883            $runner.add_generator(<$ty>::default());
1884        )*
1885    };
1886}
1887pub(crate) use _add_generators_by_type as add_generators_by_type;