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