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
26use std::{any::Any, collections::HashMap, fs, io::Read as _, str::FromStr};
27
28use camino::Utf8PathBuf;
29use compact_str::{CompactString, ToCompactString as _};
30use eyre::{Context as _, ContextCompat};
31use itertools::Itertools;
32use walrus::MemoryId;
33
34use crate::{
35    args::{self, TargetMemoryType},
36    compile,
37    config_checker::TomlRestorers,
38    fallback_command,
39    unique_name::UniqueName,
40    util::{
41        CaminoUtilModule as _, ResultUtil, WalrusFID as _, WalrusUtilExport as _, WalrusUtilModule,
42        WasmName, WasmNameHolder,
43    },
44};
45
46/// Represents the generation context, holding configuration arguments and targeted module info.
47#[derive(Debug)]
48pub struct GeneratorCtx {
49    /// The name of the VFS module.
50    pub vfs_name: WasmName,
51    /// The names of the target modules.
52    pub target_names: Box<[WasmName]>,
53    /// Including one's own WASI ABI
54    pub target_names_with_self: Box<[WasmName]>,
55    /// only pre_vfs, post_combine, post_lower_memory
56    pub vfs_used_memory_id: Option<MemoryId>,
57    /// only post_combine
58    pub vfs_used_global_id: Option<Box<[walrus::GlobalId]>>,
59    /// only pre_target, post_combine, post_lower_memory
60    pub target_used_memory_id: Option<HashMap<WasmName, MemoryId>>,
61    /// only post_combine
62    pub target_used_global_id: Option<HashMap<WasmName, Box<[walrus::GlobalId]>>>,
63    /// not start section.
64    /// only post_combine.
65    pub start_func_id: Option<HashMap<WasmName, walrus::FunctionId>>,
66    /// The memory type of the target modules (Single or Multi).
67    pub target_memory_type: TargetMemoryType,
68    /// Whether to print unstable debug information.
69    pub unstable_print_debug: bool,
70    /// Whether to include DWARF debug information.
71    pub dwarf: bool,
72    /// Whether to enable multi-threading support.
73    pub threads: bool,
74    /// Whether to adjust the ABI for standard environments.
75    pub adjust_abi: bool,
76    /// Whether to keep intermediate build artifacts.
77    pub keep_build_artifacts: bool,
78    pub starts: starts::FnInStarts,
79}
80
81/// Sub-context for extracting and storing component variables during execution.
82#[derive(Debug, Default)]
83pub struct ComponentCtx {
84    /// Optional name of the VFS module.
85    vfs_name: Option<WasmName>,
86    /// Optional names of the target modules.
87    target_names: Option<Box<[WasmName]>>,
88    /// Optional memory type of the target modules.
89    target_memory_type: Option<TargetMemoryType>,
90    /// Optional flag for unstable debug printing.
91    unstable_print_debug: Option<bool>,
92    /// Flag for including DWARF debug information.
93    dwarf: bool,
94    /// Optional flag for multi-threading support.
95    threads: Option<bool>,
96    /// Flag for ABI adjustment.
97    adjust_abi: bool,
98}
99
100struct CompressNames {
101    names: Box<[String]>,
102}
103
104impl ToString for CompressNames {
105    fn to_string(&self) -> String {
106        self.names
107            .iter()
108            .map(|s| {
109                let len = s.len();
110                let len_len = len.to_string().len();
111                format!("{:09}{}{}", len_len, len, s)
112            })
113            .join("")
114    }
115}
116
117impl FromStr for CompressNames {
118    type Err = eyre::Report;
119
120    fn from_str(s: &str) -> Result<Self, Self::Err> {
121        let mut names = Vec::new();
122        let mut rest = s;
123        while !rest.is_empty() {
124            let len_len = &rest[0..9];
125            let len_len: usize = len_len[len_len
126                .chars()
127                .position(|c| c != '0')
128                .unwrap_or(len_len.chars().count() - 1)..]
129                .parse()
130                .wrap_err_with(|| format!("Failed to parse length of length: {len_len}"))?;
131            rest = rest.get(9..).unwrap();
132            let len: usize = rest
133                .get(0..len_len)
134                .ok_or_else(|| eyre::eyre!("Failed to get length"))?
135                .parse()
136                .wrap_err_with(|| format!("Failed to parse length: {rest}"))?;
137            rest = rest.get(len_len..).unwrap();
138            let name = rest
139                .get(0..len)
140                .ok_or_else(|| eyre::eyre!("Failed to get name"))?;
141            names.push(name.to_string());
142            rest = rest.get(len..).unwrap();
143        }
144        Ok(Self {
145            names: names.into_boxed_slice(),
146        })
147    }
148}
149
150/// A generator acting as a visitor that propagates component contextual data.
151#[derive(Debug, Default)]
152pub struct ComponentCtxVisitor {
153    vfs_name: Option<CompactString>,
154    target_names: Option<Box<[CompactString]>>,
155    target_memory_type: Option<TargetMemoryType>,
156    unstable_print_debug: Option<bool>,
157    dwarf: Option<bool>,
158    threads: Option<bool>,
159    adjust_abi: bool,
160}
161
162impl ComponentCtxVisitor {
163    /// Creates a new `ComponentCtxVisitor` with the specified context parameters.
164    pub fn new(
165        vfs_name: WasmName,
166        target_names: Box<[WasmName]>,
167        target_memory_type: TargetMemoryType,
168        unstable_print_debug: bool,
169        dwarf: bool,
170        threads: bool,
171        adjust_abi: bool,
172    ) -> Self {
173        Self {
174            vfs_name: Some(vfs_name.to_compact_string()),
175            target_names: Some(
176                target_names
177                    .into_iter()
178                    .map(|s| s.to_compact_string())
179                    .collect(),
180            ),
181            target_memory_type: Some(target_memory_type),
182            unstable_print_debug: Some(unstable_print_debug),
183            dwarf: Some(dwarf),
184            threads: Some(threads),
185            adjust_abi,
186        }
187    }
188}
189
190impl Generator for ComponentCtxVisitor {
191    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
192        let vfs_name = ctx.vfs_name.to_compact_string();
193        let target_names = CompressNames {
194            names: ctx
195                .target_names
196                .iter()
197                .map(|s| s.to_string())
198                .collect::<Box<_>>(),
199        };
200        let GeneratorCtx {
201            vfs_name: _,
202            target_names: _,
203            target_memory_type,
204            unstable_print_debug,
205            dwarf,
206            threads,
207            adjust_abi,
208            target_names_with_self: _,
209            vfs_used_memory_id: _,
210            vfs_used_global_id: _,
211            target_used_memory_id: _,
212            target_used_global_id: _,
213            start_func_id: _,
214            keep_build_artifacts: _,
215            starts: _,
216        } = ctx;
217        module.save_info("vfs_name", vfs_name.to_string())?;
218        module.save_info("target_names", target_names)?;
219        module.save_info("target_memory_type", *target_memory_type)?;
220        module.save_info("unstable_print_debug", *unstable_print_debug)?;
221        module.save_info("dwarf", *dwarf)?;
222        module.save_info("threads", *threads)?;
223        module.save_info("adjust_abi", *adjust_abi)?;
224        Ok(())
225    }
226
227    fn post_components(
228        &mut self,
229        module: &mut walrus::Module,
230        _: &ComponentCtx,
231    ) -> eyre::Result<()> {
232        let vfs_name = module.load_info::<String>("vfs_name")?;
233        let target_names = module.load_info::<CompressNames>("target_names")?;
234        let target_memory_type = module.load_info::<TargetMemoryType>("target_memory_type")?;
235        let unstable_print_debug = module.load_info::<bool>("unstable_print_debug")?;
236        let dwarf = module.load_info::<bool>("dwarf")?;
237        let threads = module.load_info::<bool>("threads")?;
238        let adjust_abi = module.load_info::<bool>("adjust_abi")?;
239        self.vfs_name = Some(vfs_name.to_compact_string());
240        self.target_names = Some(
241            target_names
242                .names
243                .into_iter()
244                .map(|s| s.to_compact_string())
245                .collect(),
246        );
247        self.target_memory_type = Some(target_memory_type);
248        self.unstable_print_debug = Some(unstable_print_debug);
249        self.dwarf = Some(dwarf);
250        self.threads = Some(threads);
251        self.adjust_abi = adjust_abi;
252
253        Ok(())
254    }
255}
256
257impl ComponentCtx {
258    /// Creates a new `ComponentCtx` with the specified context parameters.
259    pub fn new(
260        vfs_name: WasmName,
261        target_names: Box<[WasmName]>,
262        target_memory_type: TargetMemoryType,
263        unstable_print_debug: bool,
264        dwarf: bool,
265        threads: bool,
266        adjust_abi: bool,
267    ) -> Self {
268        Self {
269            vfs_name: Some(vfs_name),
270            target_names: Some(target_names),
271            target_memory_type: Some(target_memory_type),
272            unstable_print_debug: Some(unstable_print_debug),
273            dwarf,
274            threads: Some(threads),
275            adjust_abi,
276        }
277    }
278
279    /// Returns the name of the VFS module.
280    pub fn vfs_name(&self) -> &WasmName {
281        self.vfs_name.as_ref().unwrap()
282    }
283
284    /// Returns the names of the target modules.
285    pub fn target_names(&self) -> &Box<[WasmName]> {
286        self.target_names.as_ref().unwrap()
287    }
288
289    /// Returns the memory type of the target modules.
290    pub fn target_memory_type(&self) -> TargetMemoryType {
291        self.target_memory_type.unwrap()
292    }
293
294    /// Returns whether to print unstable debug information.
295    pub fn unstable_print_debug(&self) -> bool {
296        self.unstable_print_debug.unwrap()
297    }
298
299    /// Returns whether to include DWARF debug information.
300    pub fn dwarf(&self) -> bool {
301        self.dwarf
302    }
303
304    /// Returns whether to enable multi-threading support.
305    pub fn threads(&self) -> bool {
306        self.threads.unwrap()
307    }
308}
309
310/// Defines the core trait for WASM transformations, hooks, and component optimizations over the build lifecycle.
311pub trait Generator: std::fmt::Debug + Any {
312    /// Operations performed on the built VFS module.
313    #[allow(unused_variables)]
314    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
315        Ok(())
316    }
317
318    /// Operations performed on the target module.
319    #[allow(unused_variables)]
320    fn pre_target(
321        &mut self,
322        module: &mut walrus::Module,
323        ctx: &GeneratorCtx,
324        external: &ModuleExternal,
325    ) -> eyre::Result<()> {
326        Ok(())
327    }
328
329    /// Operations performed on the combined module.
330    #[allow(unused_variables)]
331    fn post_combine(
332        &mut self,
333        module: &mut walrus::Module,
334        ctx: &GeneratorCtx,
335    ) -> eyre::Result<()> {
336        Ok(())
337    }
338
339    /// Operations performed after lowerings memory operations.
340    /// Only called if the target memory type is `Single`.
341    #[allow(unused_variables)]
342    fn post_lower_memory(
343        &mut self,
344        module: &mut walrus::Module,
345        ctx: &GeneratorCtx,
346    ) -> eyre::Result<()> {
347        Ok(())
348    }
349
350    /// Operations performed after components.
351    #[allow(unused_variables)]
352    fn post_components(
353        &mut self,
354        module: &mut walrus::Module,
355        ctx: &ComponentCtx,
356    ) -> eyre::Result<()> {
357        Ok(())
358    }
359
360    /// Operations performed after last optimizations.
361    /// Generating debug functions is a delicate process,
362    /// so in this case, output once per structure.
363    /// Return true if there are changes.
364    #[allow(unused_variables)]
365    fn post_all_optimize(
366        &mut self,
367        module: &mut walrus::Module,
368        ctx: &ComponentCtx,
369    ) -> eyre::Result<bool> {
370        Ok(false)
371    }
372}
373impl<T: std::fmt::Debug + Any + Generator> Generator for [T] {
374    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
375        for generator in self {
376            generator.pre_vfs(module, ctx).wrap_err_with(|| {
377                eyre::eyre!(format!("Failed to run pre_vfs for {generator:?}"))
378            })?;
379        }
380        Ok(())
381    }
382
383    fn pre_target(
384        &mut self,
385        module: &mut walrus::Module,
386        ctx: &GeneratorCtx,
387        external: &ModuleExternal,
388    ) -> eyre::Result<()> {
389        for generator in self {
390            generator
391                .pre_target(module, ctx, external)
392                .wrap_err_with(|| {
393                    eyre::eyre!(format!("Failed to run pre_target for {generator:?}"))
394                })?;
395        }
396        Ok(())
397    }
398
399    fn post_combine(
400        &mut self,
401        module: &mut walrus::Module,
402        ctx: &GeneratorCtx,
403    ) -> eyre::Result<()> {
404        for generator in self {
405            generator.post_combine(module, ctx).wrap_err_with(|| {
406                eyre::eyre!(format!("Failed to run post_combine for {generator:?}"))
407            })?;
408        }
409        Ok(())
410    }
411
412    fn post_lower_memory(
413        &mut self,
414        module: &mut walrus::Module,
415        ctx: &GeneratorCtx,
416    ) -> eyre::Result<()> {
417        for generator in self {
418            generator.post_lower_memory(module, ctx).wrap_err_with(|| {
419                eyre::eyre!(format!("Failed to run post_lower_memory for {generator:?}"))
420            })?;
421        }
422        Ok(())
423    }
424
425    fn post_components(
426        &mut self,
427        module: &mut walrus::Module,
428        ctx: &ComponentCtx,
429    ) -> eyre::Result<()> {
430        for generator in self {
431            generator.post_components(module, ctx).wrap_err_with(|| {
432                eyre::eyre!(format!("Failed to run post_components for {generator:?}"))
433            })?;
434        }
435        Ok(())
436    }
437
438    fn post_all_optimize(
439        &mut self,
440        module: &mut walrus::Module,
441        ctx: &ComponentCtx,
442    ) -> eyre::Result<bool> {
443        let mut changed = false;
444        for generator in self {
445            changed |= generator.post_all_optimize(module, ctx).wrap_err_with(|| {
446                eyre::eyre!(format!("Failed to run post_all_optimize for {generator:?}"))
447            })?;
448        }
449        Ok(changed)
450    }
451}
452impl Generator for Box<dyn Generator + 'static> {
453    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
454        (**self).pre_vfs(module, ctx)
455    }
456
457    fn pre_target(
458        &mut self,
459        module: &mut walrus::Module,
460        ctx: &GeneratorCtx,
461        external: &ModuleExternal,
462    ) -> eyre::Result<()> {
463        (**self).pre_target(module, ctx, external)
464    }
465
466    fn post_combine(
467        &mut self,
468        module: &mut walrus::Module,
469        ctx: &GeneratorCtx,
470    ) -> eyre::Result<()> {
471        (**self).post_combine(module, ctx)
472    }
473
474    fn post_lower_memory(
475        &mut self,
476        module: &mut walrus::Module,
477        ctx: &GeneratorCtx,
478    ) -> eyre::Result<()> {
479        (**self).post_lower_memory(module, ctx)
480    }
481
482    fn post_components(
483        &mut self,
484        module: &mut walrus::Module,
485        ctx: &ComponentCtx,
486    ) -> eyre::Result<()> {
487        (**self).post_components(module, ctx)
488    }
489
490    fn post_all_optimize(
491        &mut self,
492        module: &mut walrus::Module,
493        ctx: &ComponentCtx,
494    ) -> eyre::Result<bool> {
495        (**self).post_all_optimize(module, ctx)
496    }
497}
498impl<'a> Generator for &'a mut (dyn Generator + 'a) {
499    fn pre_vfs(&mut self, module: &mut walrus::Module, ctx: &GeneratorCtx) -> eyre::Result<()> {
500        (**self).pre_vfs(module, ctx)
501    }
502
503    fn pre_target(
504        &mut self,
505        module: &mut walrus::Module,
506        ctx: &GeneratorCtx,
507        external: &ModuleExternal,
508    ) -> eyre::Result<()> {
509        (**self).pre_target(module, ctx, external)
510    }
511
512    fn post_combine(
513        &mut self,
514        module: &mut walrus::Module,
515        ctx: &GeneratorCtx,
516    ) -> eyre::Result<()> {
517        (**self).post_combine(module, ctx)
518    }
519
520    fn post_lower_memory(
521        &mut self,
522        module: &mut walrus::Module,
523        ctx: &GeneratorCtx,
524    ) -> eyre::Result<()> {
525        (**self).post_lower_memory(module, ctx)
526    }
527
528    fn post_components(
529        &mut self,
530        module: &mut walrus::Module,
531        ctx: &ComponentCtx,
532    ) -> eyre::Result<()> {
533        (**self).post_components(module, ctx)
534    }
535
536    fn post_all_optimize(
537        &mut self,
538        module: &mut walrus::Module,
539        ctx: &ComponentCtx,
540    ) -> eyre::Result<bool> {
541        (**self).post_all_optimize(module, ctx)
542    }
543}
544
545/// Stores the identity of an external loaded Wasm target.
546#[derive(Debug)]
547pub struct ModuleExternal {
548    /// The name of the external module.
549    pub name: WasmName,
550}
551
552impl ModuleExternal {
553    /// Creates a new `ModuleExternal` with the specified name.
554    pub fn new(name: &WasmName) -> Self {
555        Self { name: name.clone() }
556    }
557}
558
559/// Coordinates iterating over registered generators and merging external module logic into the VFS.
560#[derive(Debug)]
561pub struct GeneratorRunner {
562    /// The checkers used to validate the module.
563    pub checkers: Vec<Box<dyn Generator + 'static>>,
564    /// The generators used to transform the module.
565    pub generators: Vec<Box<dyn Generator + 'static>>,
566    /// The context used during generation.
567    pub ctx: GeneratorCtx,
568    /// The path to the WASM module.
569    pub path: WasmPath,
570    /// The paths to the target WASM modules.
571    pub targets: Box<[WasmPath]>,
572    /// Options for building the VFS module.
573    pub vfs_build_opts: args::VfsBuildOptions,
574    /// Options for building the target WASM modules.
575    pub target_vfs_build_opts: Box<[args::VfsBuildOptions]>,
576    /// The TOML restorers used to reset configuration files.
577    pub toml_restorers: Option<TomlRestorers>,
578    /// Memory hints for the target modules.
579    pub memory_hint: HashMap<WasmName, usize>,
580    /// Holder for the names of the WASM modules.
581    pub wasm_name_holder: WasmNameHolder,
582}
583
584/// A runner that coordinates the generation of a WebAssembly component.
585#[derive(Debug)]
586pub struct ComponentRunner {
587    /// The generators used to transform the component.
588    pub generators: Vec<Box<dyn Generator + 'static>>,
589    /// Encapsulates contextual settings across all generator components during transpilation.
590    pub ctx: Option<ComponentCtx>,
591    /// Specifies the target active WASM module destination.
592    pub path: WasmPath,
593    /// Manages dynamically generated and globally referenced named functions.
594    pub wasm_name_holder: Option<WasmNameHolder>,
595}
596
597pub(crate) trait WrapRunner<T> {
598    #[allow(unused_variables)]
599    fn wrap_run(
600        self,
601        path: &mut WasmPath,
602        dwarf: bool,
603        keep_build_artifacts: bool,
604    ) -> eyre::Result<T>
605    where
606        Self: Sized;
607}
608
609impl<T, F: FnOnce(&mut walrus::Module) -> eyre::Result<T>> WrapRunner<T> for F {
610    fn wrap_run(
611        self,
612        path: &mut WasmPath,
613        dwarf: bool,
614        keep_build_artifacts: bool,
615    ) -> eyre::Result<T> {
616        let old_path = path.path()?.clone();
617        let module =
618            &mut walrus::Module::load(&old_path, dwarf).wrap_err("Failed to load Wasm module")?;
619
620        let result = (self)(module)?;
621
622        let new_path = old_path.with_extension("adjusted.wasm");
623
624        if fs::metadata(&new_path).is_ok() {
625            fs::remove_file(&new_path)
626                .wrap_err_with(|| format!("Failed to remove existing file {new_path}"))?;
627        }
628
629        module
630            .emit_wasm_file(&new_path)
631            .to_eyre()
632            .wrap_err_with(|| format!("Failed to write adjusted Wasm to {new_path}"))?;
633
634        if !keep_build_artifacts && !path.is_original(&old_path) {
635            std::fs::remove_file(&old_path)
636                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
637        }
638
639        path.set_path(new_path)?;
640
641        Ok(result)
642    }
643}
644
645pub(crate) trait EndWithOpt<T> {
646    #[allow(unused_variables)]
647    fn with_opt(
648        self,
649        path: &mut WasmPath,
650        dwarf: bool,
651        keep_build_artifacts: bool,
652    ) -> eyre::Result<T>
653    where
654        Self: Sized;
655
656    #[allow(dead_code)]
657    fn with_opt_args(
658        self,
659        path: &mut WasmPath,
660        args: &[&str],
661        require_update: bool,
662        dwarf: bool,
663        keep_build_artifacts: bool,
664    ) -> eyre::Result<T>
665    where
666        Self: Sized;
667}
668
669impl<T, F: FnOnce(&mut WasmPath) -> eyre::Result<T>> EndWithOpt<T> for F {
670    fn with_opt(
671        self,
672        path: &mut WasmPath,
673        dwarf: bool,
674        keep_build_artifacts: bool,
675    ) -> eyre::Result<T>
676    where
677        Self: Sized,
678    {
679        let result = (self)(path).wrap_err("Failed to run with with_opt")?;
680
681        println!("Optimizing Wasm...");
682        let old_path = path.path()?.clone();
683        let new_path = compile::optimize_wasm(&old_path, &[], false, dwarf)
684            .wrap_err("Failed to optimize Wasm")?;
685
686        if !keep_build_artifacts && old_path != new_path && !path.is_original(&old_path) {
687            std::fs::remove_file(&old_path)
688                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
689        }
690
691        path.set_path(new_path)?;
692
693        Ok(result)
694    }
695
696    fn with_opt_args(
697        self,
698        path: &mut WasmPath,
699        args: &[&str],
700        require_update: bool,
701        dwarf: bool,
702        keep_build_artifacts: bool,
703    ) -> eyre::Result<T>
704    where
705        Self: Sized,
706    {
707        let result = (self)(path).wrap_err("Failed to run with with_opt_args")?;
708
709        println!("Optimizing Wasm... with args: {}", args.iter().join(" "));
710        let old_path = path.path()?.clone();
711        let new_path = compile::optimize_wasm(&old_path, args, require_update, dwarf)
712            .wrap_err("Failed to optimize Wasm")?;
713
714        if !keep_build_artifacts && old_path != new_path && !path.is_original(&old_path) {
715            std::fs::remove_file(&old_path)
716                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
717        }
718
719        path.set_path(new_path)?;
720
721        Ok(result)
722    }
723}
724
725impl GeneratorRunner {
726    /// Initializes a `GeneratorRunner` capturing all parameters needed for complete application-level transpilation mapping.
727    pub fn new(
728        path: WasmPath,
729        targets: Box<[WasmPath]>,
730        threads: bool,
731        dwarf: bool,
732        unstable_print_debug: bool,
733        adjust_abi: bool,
734        keep_build_artifacts: bool,
735        memory_type: TargetMemoryType,
736        vfs_build_opts: args::VfsBuildOptions,
737        target_vfs_build_opts: Box<[args::VfsBuildOptions]>,
738        toml_restorers: TomlRestorers,
739        memory_hint: Box<[Option<usize>]>,
740    ) -> eyre::Result<Self> {
741        let target_names_with_self = core::iter::once(Ok(path.name()?.to_compact_string()))
742            .chain(targets.iter().map(|t| Ok(t.name()?.to_compact_string())))
743            .collect::<eyre::Result<Box<_>>>()?;
744
745        let wasm_name_holder = WasmNameHolder::new(target_names_with_self);
746        let mut wasm_name_holder_iter = wasm_name_holder.iter();
747        let vfs_name = wasm_name_holder_iter
748            .next()
749            .ok_or_else(|| eyre::eyre!("Failed to get VFS name"))?;
750
751        let target_names = wasm_name_holder_iter.collect::<Box<_>>();
752
753        let starts = starts::FnInStarts::new(&target_names);
754
755        // log targeting info
756        for name in target_names.iter() {
757            log::info!("Targeting module: {name}");
758        }
759        log::info!("VFS module: {vfs_name}");
760
761        let target_names_with_self = target_names
762            .iter()
763            .cloned()
764            .chain(core::iter::once(vfs_name.clone()))
765            .collect::<Box<_>>();
766
767        let memory_hint = memory_hint
768            .into_iter()
769            .zip(target_names.iter().cloned())
770            .filter_map(|(hint, name)| hint.map(|h| (name, h)))
771            .collect::<HashMap<_, _>>();
772
773        Ok(Self {
774            checkers: Vec::new(),
775            generators: Vec::new(),
776            ctx: GeneratorCtx {
777                vfs_name,
778                target_names,
779                target_names_with_self,
780                target_memory_type: memory_type,
781                unstable_print_debug,
782                dwarf,
783                threads,
784                adjust_abi,
785                keep_build_artifacts,
786                vfs_used_memory_id: None,
787                vfs_used_global_id: None,
788                target_used_memory_id: None,
789                target_used_global_id: None,
790                start_func_id: None,
791                starts,
792            },
793            path,
794            targets,
795            vfs_build_opts,
796            target_vfs_build_opts,
797            toml_restorers: Some(toml_restorers),
798            memory_hint,
799            wasm_name_holder,
800        })
801    }
802
803    /// Registers a custom generator to be applied sequentially during transformation phases.
804    pub fn add_generator<G: Generator + 'static>(&mut self, generator: G) {
805        self.generators.push(Box::new(generator));
806    }
807
808    /// Registers a diagnostic validation checker resolving pre or post-conditions automatically.
809    pub fn checker(&mut self, checker: impl Generator + 'static) {
810        self.checkers.push(Box::new(checker));
811    }
812
813    /// Resolves and retrieves a shared reference to a specific structured generator dynamically at runtime.
814    pub fn get_generator_ref<T: Generator + 'static>(&self) -> eyre::Result<&T> {
815        fn downcast_ref<T: 'static>(b: &dyn Any) -> Option<&'_ T> {
816            if b.is::<T>() {
817                Some(b.downcast_ref::<T>().unwrap())
818            } else {
819                None
820            }
821        }
822
823        self.generators
824            .iter()
825            .map(|g| g.as_ref())
826            .find_map(|g| downcast_ref::<T>(g))
827            .wrap_err_with(|| {
828                eyre::eyre!("Failed to get generator: {}", core::any::type_name::<T>())
829            })
830            .wrap_err_with(|| eyre::eyre!("Available generators: {:?}", self.generators))
831    }
832
833    #[deprecated(
834        note = "Ensure this function is self-contained. This is a temporary measure for debugging purposes."
835    )]
836    /// Provides direct immutable access tracking the primary target structural path configuration.
837    pub const fn path(&self) -> &WasmPath {
838        &self.path
839    }
840
841    #[deprecated(
842        note = "Ensure this function is self-contained. This is a temporary measure for debugging purposes."
843    )]
844    /// Directly evaluates currently linked ancillary wasm dependencies.
845    pub const fn targets(&self) -> &Box<[WasmPath]> {
846        &self.targets
847    }
848
849    /// Securely uncovers operational variables tracking internal generational properties dynamically.
850    pub const fn ctx(&self) -> &GeneratorCtx {
851        &self.ctx
852    }
853
854    /// Confirms mapping configurations and statically evaluates lazy initializations strictly allocating paths.
855    pub fn definitely(&mut self) -> eyre::Result<()> {
856        self.path
857            .definitely(self.ctx.threads, &self.vfs_build_opts)?;
858        for (i, target) in self.targets.iter_mut().enumerate() {
859            target.definitely(self.ctx.threads, &self.target_vfs_build_opts[i])?;
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;