Skip to main content

wasi_virt_layer_cli/generator/
mod.rs

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