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