Skip to main content

wasi_virt_layer_cli/generator/
mod.rs

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