Skip to main content

wasi_virt_layer_cli/generator/
mod.rs

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