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()?.clone();
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 && !path.is_original(&old_path) {
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 && !path.is_original(&old_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 && !path.is_original(&old_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                for target in self.targets.iter() {
984                    if let Ok(target_path) = target.path() {
985                        if !target.is_original(target_path) {
986                            std::fs::remove_file(target_path).unwrap_or_else(|e| {
987                                log::warn!("Failed to remove intermediate target file {target_path}: {e}");
988                            });
989                        }
990                    }
991                }
992            }
993
994            path.set_path(output.into())
995        })
996        .with_opt(&mut self.path, dwarf, keep_build_artifacts)?;
997
998        println!("Adjusting Merged Wasm...");
999        (|path: &mut WasmPath| {
1000            (|module: &mut walrus::Module| {
1001                mem_id_visitor
1002                    .post_combine(module, &self.ctx)
1003                    .wrap_err("Failed in post_combine")?;
1004                global_id_visitor
1005                    .post_combine(module, &self.ctx)
1006                    .wrap_err("Failed in post_combine")?;
1007                let mut start_func_id_visitor = StartFuncIdVisitor::default();
1008                start_func_id_visitor
1009                    .post_combine(module, &self.ctx)
1010                    .wrap_err("Failed in post_combine")?;
1011
1012                self.ctx.vfs_used_memory_id = mem_id_visitor.used_vfs_memory_id.take();
1013                self.ctx.target_used_memory_id = mem_id_visitor.used_target_memory_id.take();
1014
1015                self.ctx.vfs_used_global_id = global_id_visitor.vfs_global_id.take();
1016                self.ctx.target_used_global_id = global_id_visitor.global_id.take();
1017
1018                self.ctx.start_func_id = start_func_id_visitor.start_func_id.take();
1019
1020                self.generators.post_combine(module, &self.ctx)?;
1021
1022                if self.ctx.target_memory_type == TargetMemoryType::Multi {
1023                    start_section_generator
1024                        .take()
1025                        .unwrap()
1026                        .build(module, &self.ctx)?;
1027                }
1028
1029                Ok(())
1030            })
1031            .wrap_run(path, dwarf, keep_build_artifacts)
1032        })
1033        .with_opt(&mut self.path, dwarf, keep_build_artifacts)?;
1034
1035        self.ctx.vfs_used_memory_id = None;
1036        self.ctx.target_used_memory_id = None;
1037
1038        self.ctx.vfs_used_global_id = None;
1039        self.ctx.target_used_global_id = None;
1040
1041        self.ctx.start_func_id = None;
1042
1043        if self.ctx.target_memory_type == TargetMemoryType::Single {
1044            let old_path = self.path.path()?.clone();
1045
1046            println!("Generating single memory Merged Wasm...");
1047            let optimized_path =
1048                compile::optimize_wasm(&old_path, &["--multi-memory-lowering"], true, dwarf)?;
1049
1050            if !keep_build_artifacts {
1051                std::fs::remove_file(&old_path)
1052                    .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
1053            }
1054
1055            self.path.set_path(optimized_path)?;
1056
1057            (|path: &mut WasmPath| {
1058                (|module: &mut walrus::Module| {
1059                    mem_id_visitor
1060                        .post_lower_memory(module, &self.ctx)
1061                        .wrap_err("Failed in post_lower_memory")?;
1062
1063                    self.ctx.vfs_used_memory_id = mem_id_visitor.used_vfs_memory_id.take();
1064                    self.ctx.target_used_memory_id = mem_id_visitor.used_target_memory_id.take();
1065
1066                    self.generators
1067                        .post_lower_memory(module, &self.ctx)
1068                        .wrap_err("Failed in run_post_lower_memory")?;
1069
1070                    start_section_generator
1071                        .take()
1072                        .unwrap()
1073                        .build(module, &self.ctx)?;
1074
1075                    Ok(())
1076                })
1077                .wrap_run(path, dwarf, keep_build_artifacts)
1078            })
1079            .with_opt(&mut self.path, dwarf, keep_build_artifacts)?;
1080        }
1081
1082        println!("Translating Wasm to Component...");
1083        let old_path = self.path.path()?.clone();
1084        let component = compile::wasm_to_component(&old_path, &self.ctx.target_names)
1085            .wrap_err("Failed to translate Wasm to Component")?;
1086        if !keep_build_artifacts {
1087            std::fs::remove_file(&old_path)
1088                .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
1089        }
1090
1091        let new_component = format!("{out_dir}/{}.component.wasm", self.ctx.vfs_name);
1092        std::fs::rename(&component, &new_component)
1093            .wrap_err_with(|| format!("Failed to rename file {component} to {new_component}"))?;
1094
1095        self.path.set_path(Utf8PathBuf::from(new_component))?;
1096
1097        Ok(ComponentRunner::with_generators(self.path, self.generators))
1098    }
1099}
1100
1101impl ComponentRunner {
1102    /// Instantiates a fresh `ComponentRunner` targeting a specific underlying WebAssembly structure.
1103    pub fn new(path: WasmPath) -> Self {
1104        Self {
1105            generators: Vec::new(),
1106            ctx: None,
1107            path,
1108            wasm_name_holder: None,
1109        }
1110    }
1111
1112    /// Installs a specific invariant-checking generator executing without altering primary execution pathways.
1113    pub fn checker(&mut self, checker: impl Generator + 'static) {
1114        self.generators.push(Box::new(checker));
1115    }
1116
1117    /// Quickly constructs a runner wrapping a pre-defined array containing generator strategies.
1118    pub fn with_generators(path: WasmPath, generators: Vec<Box<dyn Generator + 'static>>) -> Self {
1119        Self {
1120            generators,
1121            ctx: None,
1122            path,
1123            wasm_name_holder: None,
1124        }
1125    }
1126
1127    /// Queues an advanced generative instruction step executed successively upon evaluation.
1128    pub fn add_generator<G: Generator + 'static>(&mut self, generator: G) {
1129        self.generators.push(Box::new(generator));
1130    }
1131
1132    /// Allows querying the internal generator stack dynamically retrieving explicitly modeled type structures.
1133    pub fn get_generator_ref<T: Generator + 'static>(&self) -> eyre::Result<&T> {
1134        fn downcast_ref<T: 'static>(b: &dyn Any) -> Option<&'_ T> {
1135            if b.is::<T>() {
1136                Some(b.downcast_ref::<T>().unwrap())
1137            } else {
1138                None
1139            }
1140        }
1141
1142        self.generators
1143            .iter()
1144            .map(|g| g.as_ref())
1145            .find_map(|g| downcast_ref::<T>(g))
1146            .wrap_err_with(|| {
1147                eyre::eyre!("Failed to get generator: {}", core::any::type_name::<T>())
1148            })
1149            .wrap_err_with(|| eyre::eyre!("Available generators: {:?}", self.generators))
1150    }
1151
1152    /// return is_threads, core_name, mem_size
1153    pub fn component_to_files(
1154        &mut self,
1155        parsed_args: &(impl args::PostBuildContext + ?Sized),
1156        dwarf: bool,
1157        only_core: bool,
1158    ) -> eyre::Result<(bool, CompactString, HashMap<CompactString, (u64, u64)>)> {
1159        let out_dir = parsed_args.out_dir();
1160
1161        let name = self.path.name()?;
1162
1163        println!("Translating Component to JS...");
1164        let core_wasm_path = (|path: &mut WasmPath| {
1165            let old_path = path.path()?.clone();
1166            let binary = std::fs::read(&old_path).wrap_err("Failed to read component")?;
1167            let transpiled = parsed_args
1168                .transpile_to_js(&binary, &name)
1169                .wrap_err("Failed to transpile to JS")?;
1170
1171            let mut core_wasm = None;
1172            for (name, data) in transpiled.files.iter() {
1173                let name = camino::Utf8PathBuf::from(name);
1174                let file_name = out_dir.join(&name);
1175                if std::fs::metadata(&file_name).is_ok() {
1176                    std::fs::remove_file(&file_name).wrap_err_with(|| {
1177                        eyre::eyre!("Failed to remove existing file: {file_name}")
1178                    })?;
1179                }
1180                if name.as_str().ends_with(".core.wasm") {
1181                    let file_name = camino::Utf8PathBuf::from(file_name);
1182                    std::fs::write(&file_name, &data).wrap_err_with(|| {
1183                        eyre::eyre!("Failed to write core wasm file: {file_name}")
1184                    })?;
1185                    core_wasm = Some(file_name);
1186                } else {
1187                    if let Some(parent) = name.parent() {
1188                        if !parent.as_str().is_empty() {
1189                            let dir = name.ancestors().nth(1).wrap_err_with(|| {
1190                                eyre::eyre!("Failed to get parent directory: {}", name)
1191                            })?;
1192                            let joined_dir = out_dir.join(dir);
1193                            if !std::fs::metadata(&joined_dir).is_ok() {
1194                                if dir.as_str() != "interfaces" {
1195                                    log::warn!("Creating directory: {joined_dir}");
1196                                }
1197                                if only_core {
1198                                    continue;
1199                                }
1200                                std::fs::create_dir_all(&joined_dir).wrap_err_with(|| {
1201                                    eyre::eyre!("Failed to create directory: {joined_dir}")
1202                                })?;
1203                            }
1204                        }
1205                    }
1206                    if only_core {
1207                        continue;
1208                    }
1209                    std::fs::write(&file_name, &data).wrap_err_with(|| {
1210                        eyre::eyre!("Failed to write transpiled file: {file_name}")
1211                    })?;
1212                }
1213            }
1214
1215            let core_wasm = core_wasm
1216                .as_ref()
1217                .ok_or_else(|| eyre::eyre!("Failed to find core wasm"))?;
1218
1219            if !parsed_args.keep_build_artifacts() {
1220                std::fs::remove_file(&old_path)
1221                    .wrap_err_with(|| format!("Failed to remove existing file {old_path}"))?;
1222            }
1223            path.set_path(core_wasm.clone())?;
1224
1225            Ok(core_wasm.clone())
1226        })
1227        .with_opt(&mut self.path, dwarf, parsed_args.keep_build_artifacts())?;
1228
1229        let mem_size_visitor = MemorySizeVisitor::default();
1230        self.generators.push(Box::new(mem_size_visitor));
1231
1232        println!("Adjusting component Merged Wasm...");
1233        (|path: &mut WasmPath| {
1234            (|module: &mut walrus::Module| {
1235                let mut visitor = ComponentCtxVisitor::default();
1236                visitor
1237                    .post_components(
1238                        module,
1239                        &ComponentCtx {
1240                            dwarf,
1241                            ..Default::default()
1242                        },
1243                    )
1244                    .wrap_err("Failed in post_components")?;
1245                let wasm_name_holder = WasmNameHolder::new(
1246                    visitor
1247                        .target_names
1248                        .unwrap()
1249                        .into_iter()
1250                        .chain(core::iter::once(visitor.vfs_name.unwrap()))
1251                        .collect::<Box<_>>(),
1252                );
1253                self.wasm_name_holder = Some(wasm_name_holder);
1254                let mut wasm_name_holder_iter = self.wasm_name_holder.as_ref().unwrap().iter();
1255                self.ctx = Some(ComponentCtx {
1256                    vfs_name: Some(wasm_name_holder_iter.next().unwrap()),
1257                    target_names: Some(wasm_name_holder_iter.collect::<Box<_>>()),
1258                    target_memory_type: Some(visitor.target_memory_type.unwrap()),
1259                    unstable_print_debug: Some(visitor.unstable_print_debug.unwrap()),
1260                    dwarf: visitor.dwarf.unwrap(),
1261                    threads: Some(visitor.threads.unwrap()),
1262                    adjust_abi: visitor.adjust_abi,
1263                });
1264
1265                self.generators
1266                    .post_components(module, self.ctx.as_ref().unwrap())
1267                    .wrap_err("Failed in run_post_components")
1268            })
1269            .wrap_run(path, dwarf, parsed_args.keep_build_artifacts())
1270        })
1271        .with_opt(&mut self.path, dwarf, parsed_args.keep_build_artifacts())?;
1272
1273        let dwarf = {
1274            let new_dwarf = self.ctx.as_ref().unwrap().dwarf;
1275            if dwarf && !new_dwarf {
1276                log::warn!(
1277                    "Dwarf was disabled in component processing, you should re-run with --dwarf"
1278                );
1279            }
1280            new_dwarf
1281        };
1282
1283        println!("Final optimizing Merged Wasm...");
1284        let mut i = 0;
1285        while i < self.generators.len() {
1286            (|module: &mut walrus::Module| {
1287                loop {
1288                    if self.generators[i]
1289                        .post_all_optimize(module, self.ctx.as_ref().unwrap())
1290                        .wrap_err("Failed in post_all_optimize")?
1291                    {
1292                        i += 1;
1293                        return Ok(());
1294                    }
1295                    i += 1;
1296                    if i >= self.generators.len() {
1297                        return Ok(());
1298                    }
1299                }
1300            })
1301            .wrap_run(&mut self.path, dwarf, parsed_args.keep_build_artifacts())?;
1302        }
1303
1304        std::fs::rename(self.path.path()?, &core_wasm_path).wrap_err_with(|| {
1305            eyre::eyre!(
1306                "Failed to rename final wasm from {} to {}",
1307                self.path.path().unwrap(),
1308                core_wasm_path
1309            )
1310        })?;
1311
1312        Ok((
1313            self.ctx.as_ref().unwrap().threads(),
1314            core_wasm_path
1315                .get_file_main_name()
1316                .ok_or_else(|| eyre::eyre!("Failed to get file name"))?,
1317            self.get_generator_ref::<MemorySizeVisitor>()?
1318                .mem_size
1319                .clone()
1320                .unwrap(),
1321        ))
1322    }
1323}
1324
1325#[derive(Debug, Default, Clone)]
1326struct MemoryIDVisitor {
1327    pub memory_hint: HashMap<WasmName, usize>,
1328    pub used_vfs_memory_id: Option<MemoryId>,
1329    pub used_target_memory_id: Option<HashMap<WasmName, MemoryId>>,
1330}
1331
1332impl Generator for MemoryIDVisitor {
1333    fn pre_vfs(
1334        &mut self,
1335        module: &mut walrus::Module,
1336        _: &crate::generator::GeneratorCtx,
1337    ) -> eyre::Result<()> {
1338        println!("Finding VFS memory id...");
1339
1340        let id = module
1341            .get_memory_anchor("vfs", false)
1342            .wrap_err("Failed to get target memory id")?;
1343        self.used_vfs_memory_id = Some(id);
1344        Ok(())
1345    }
1346
1347    fn pre_target(
1348        &mut self,
1349        module: &mut walrus::Module,
1350        _: &crate::generator::GeneratorCtx,
1351        external: &ModuleExternal,
1352    ) -> eyre::Result<()> {
1353        let id = module
1354            .find_used_memory_id(self.memory_hint.get(&external.name).copied())
1355            .wrap_err("Failed to find used memory id")?;
1356        module
1357            .create_memory_anchor(&external.name, id)
1358            .wrap_err("Failed to create memory anchor")?;
1359        self.used_target_memory_id
1360            .get_or_insert_default()
1361            .insert(external.name.clone(), id);
1362        Ok(())
1363    }
1364
1365    fn post_combine(
1366        &mut self,
1367        module: &mut walrus::Module,
1368        ctx: &GeneratorCtx,
1369    ) -> eyre::Result<()> {
1370        let id = module
1371            .get_memory_anchor("vfs", true)
1372            .wrap_err("Failed to find used memory id after combine")?;
1373        self.used_vfs_memory_id = Some(id);
1374
1375        self.used_target_memory_id.get_or_insert_default().clear();
1376        for wasm in &ctx.target_names {
1377            let id = module
1378                .get_memory_anchor(wasm, true)
1379                .wrap_err("Failed to find used memory id after combine")?;
1380            self.used_target_memory_id
1381                .as_mut()
1382                .unwrap()
1383                .insert(wasm.clone(), id);
1384        }
1385
1386        Ok(())
1387    }
1388
1389    fn post_lower_memory(
1390        &mut self,
1391        module: &mut walrus::Module,
1392        _: &GeneratorCtx,
1393    ) -> eyre::Result<()> {
1394        let id = module
1395            .get_memory_id()
1396            .to_eyre()
1397            .wrap_err("Failed to get single memory id after lowering")?;
1398        self.used_vfs_memory_id = Some(id);
1399        self.used_target_memory_id = None;
1400
1401        Ok(())
1402    }
1403}
1404
1405#[derive(Debug, Default, Clone)]
1406struct MemorySizeVisitor {
1407    mem_size: Option<HashMap<CompactString, (u64, u64)>>,
1408}
1409
1410impl Generator for MemorySizeVisitor {
1411    fn post_components(
1412        &mut self,
1413        module: &mut walrus::Module,
1414        _: &ComponentCtx,
1415    ) -> eyre::Result<()> {
1416        let mem_size = module
1417            .memories
1418            .iter()
1419            .filter(|mem| mem.import.is_some())
1420            .map(|mem| {
1421                (
1422                    module
1423                        .imports
1424                        .get(mem.import.unwrap())
1425                        .name
1426                        .to_compact_string(),
1427                    (
1428                        mem.initial as u64,
1429                        mem.maximum.unwrap_or(mem.initial) as u64,
1430                    ),
1431                )
1432            })
1433            .collect::<HashMap<_, _>>();
1434        self.mem_size = Some(mem_size);
1435
1436        Ok(())
1437    }
1438}
1439
1440#[derive(Debug, Default)]
1441struct GlobalIdVisitor {
1442    vfs_global_id: Option<Box<[walrus::GlobalId]>>,
1443    global_id: Option<HashMap<WasmName, Box<[walrus::GlobalId]>>>,
1444}
1445impl Generator for GlobalIdVisitor {
1446    fn pre_vfs(&mut self, module: &mut walrus::Module, _: &GeneratorCtx) -> eyre::Result<()> {
1447        module
1448            .create_global_anchor("vfs")
1449            .wrap_err("Failed to create global anchor")?;
1450
1451        Ok(())
1452    }
1453
1454    fn pre_target(
1455        &mut self,
1456        module: &mut walrus::Module,
1457        _: &GeneratorCtx,
1458        external: &ModuleExternal,
1459    ) -> eyre::Result<()> {
1460        module
1461            .create_global_anchor(&external.name)
1462            .wrap_err("Failed to create global anchor")?;
1463
1464        Ok(())
1465    }
1466
1467    fn post_combine(
1468        &mut self,
1469        module: &mut walrus::Module,
1470        ctx: &GeneratorCtx,
1471    ) -> eyre::Result<()> {
1472        self.global_id = Some(HashMap::new());
1473
1474        let vfs_globals = module
1475            .get_global_anchor("vfs")
1476            .wrap_err("Failed to get global anchor for vfs")?;
1477        self.vfs_global_id = Some(vfs_globals);
1478
1479        for wasm in &ctx.target_names {
1480            let globals = module
1481                .get_global_anchor(wasm)
1482                .wrap_err_with(|| format!("Failed to get global anchor for {wasm}"))?;
1483            self.global_id
1484                .as_mut()
1485                .unwrap()
1486                .insert(wasm.clone(), globals);
1487        }
1488
1489        Ok(())
1490    }
1491}
1492
1493/// To be used from both `special_func`'s `main_void` and `start`,
1494/// it must be prepared in `ctx`.
1495#[derive(Debug, Default)]
1496struct StartFuncIdVisitor {
1497    start_func_id: Option<HashMap<WasmName, walrus::FunctionId>>,
1498}
1499
1500impl Generator for StartFuncIdVisitor {
1501    fn post_combine(
1502        &mut self,
1503        module: &mut walrus::Module,
1504        ctx: &GeneratorCtx,
1505    ) -> eyre::Result<()> {
1506        for wasm in &ctx.target_names {
1507            let export = format!("__wasip1_vfs_{wasm}__start").get_fid(&module.exports)?;
1508            self.start_func_id
1509                .get_or_insert_default()
1510                .insert(wasm.clone(), export);
1511
1512            module
1513                .exports
1514                .erase_with(export, ctx.unstable_print_debug)?;
1515
1516            module.exports.erase_with(
1517                &format!("__wasip1_vfs_{wasm}__start_anchor"),
1518                ctx.unstable_print_debug,
1519            )?;
1520        }
1521
1522        Ok(())
1523    }
1524}
1525
1526/// Represents the resolution state and file format targeting for manipulating WebAssembly modules intelligently.
1527#[derive(Debug, Clone)]
1528pub enum WasmPath {
1529    /// Indicates the target still needs compilation through standard cargo dependencies.
1530    Maybe {
1531        /// Fully resolved physical path to the corresponding Cargo.toml manifest definition.
1532        manifest_path: Utf8PathBuf,
1533        /// Specified internal crate package identifier.
1534        package: String,
1535    },
1536    /// A strictly resolved raw WebAssembly binary file ready for patching operations.
1537    Definitely(Utf8PathBuf),
1538    /// A completed explicitly transpiled WebAssembly Component standard architecture module.
1539    Component(Utf8PathBuf),
1540    /// A user-provided raw WebAssembly binary file that should never be deleted.
1541    /// The inner path tracks the original file location.
1542    Original {
1543        /// The current working path (may change as transformations produce new files).
1544        current: Utf8PathBuf,
1545        /// The original user-provided path that must be preserved.
1546        original: Utf8PathBuf,
1547    },
1548}
1549
1550impl FromStr for WasmPath {
1551    type Err = eyre::Error;
1552
1553    /// manifest_path :: package
1554    fn from_str(s: &str) -> Result<Self, Self::Err> {
1555        fn parse_path_and_package(s: &str) -> eyre::Result<Option<WasmPath>> {
1556            let split = s.split("::").collect::<Vec<_>>();
1557            if split.len() == 2 {
1558                let manifest_path = Utf8PathBuf::from_str(split[0])
1559                    .wrap_err_with(|| format!("Failed to parse manifest path: {}", split[0]))?;
1560                let package = split[1].to_string();
1561                return Ok(Some(WasmPath::Maybe {
1562                    manifest_path,
1563                    package,
1564                }));
1565            }
1566            Ok(None)
1567        }
1568
1569        if let Some(wasm_path) =
1570            parse_path_and_package(s).wrap_err("Failed to parse path and package")?
1571        {
1572            return Ok(wasm_path);
1573        }
1574
1575        if s.ends_with(".wasm") {
1576            let path = Utf8PathBuf::from_str(s)
1577                .wrap_err_with(|| format!("Failed to parse wasm path: {s}"))?;
1578            return WasmPath::with_wasm(path);
1579        }
1580
1581        if s.ends_with("Cargo.toml") {
1582            let manifest_path = Utf8PathBuf::from_str(s)
1583                .wrap_err_with(|| format!("Failed to parse manifest path: {s}"))?;
1584            return WasmPath::with_maybe_only_manifest(manifest_path);
1585        }
1586
1587        WasmPath::with_maybe_only_package(s.to_string())
1588            .wrap_err_with(|| format!("Failed to parse package name: {s}"))
1589    }
1590}
1591
1592impl WasmPath {
1593    /// Computes the unique short name used during module linking and identification.
1594    pub fn name(&self) -> eyre::Result<CompactString> {
1595        match self {
1596            WasmPath::Maybe { package, .. } => Ok(package.to_compact_string()),
1597            WasmPath::Definitely(path)
1598            | WasmPath::Component(path)
1599            | WasmPath::Original { current: path, .. } => path
1600                .get_file_main_name()
1601                .ok_or_else(|| eyre::eyre!("Failed to get file name from {path}")),
1602        }
1603    }
1604
1605    /// Exposes the manifest path conditionally if the dependency is unresolved logically.
1606    pub fn manifest_path(&self) -> Option<&Utf8PathBuf> {
1607        match self {
1608            WasmPath::Maybe { manifest_path, .. } => Some(manifest_path),
1609            WasmPath::Definitely(_) | WasmPath::Component(_) | WasmPath::Original { .. } => None,
1610        }
1611    }
1612
1613    /// Calculates the overarching workspace root via dependency graphing context implicitly.
1614    pub fn root_manifest_path(&self) -> Option<Utf8PathBuf> {
1615        match self {
1616            WasmPath::Maybe { manifest_path, .. } => {
1617                let cargo_metadata = {
1618                    let mut metadata_command = cargo_metadata::MetadataCommand::new();
1619                    metadata_command.manifest_path(&manifest_path);
1620                    metadata_command.exec().unwrap()
1621                };
1622                Some(cargo_metadata.workspace_root.join("Cargo.toml"))
1623            }
1624            WasmPath::Definitely(_) | WasmPath::Component(_) | WasmPath::Original { .. } => None,
1625        }
1626    }
1627
1628    /// Statically assigns an unresolved target using defined package specifications.
1629    pub const fn with_maybe(manifest_path: Utf8PathBuf, package: String) -> Self {
1630        Self::Maybe {
1631            manifest_path,
1632            package,
1633        }
1634    }
1635
1636    /// Constructs an unresolved dependency resolving package tracking inherently from a file manifest dynamically.
1637    pub fn with_maybe_only_manifest(manifest_path: Utf8PathBuf) -> eyre::Result<Self> {
1638        let cargo_metadata = {
1639            let mut metadata_command = cargo_metadata::MetadataCommand::new();
1640            metadata_command.manifest_path(&manifest_path);
1641            metadata_command.exec().unwrap()
1642        };
1643        let building_crate = compile::get_building_crate(&cargo_metadata, &None)?;
1644
1645        Ok(Self::Maybe {
1646            manifest_path,
1647            package: building_crate.name.to_string(),
1648        })
1649    }
1650
1651    /// Assesses global cargo metadata configuring definitions matching solely the provided string identifier.
1652    pub fn with_maybe_only_package(package: String) -> eyre::Result<Self> {
1653        let cargo_metadata = {
1654            let metadata_command = cargo_metadata::MetadataCommand::new();
1655            metadata_command.exec().unwrap()
1656        };
1657        let building_crate = compile::get_building_crate(&cargo_metadata, &Some(package.clone()))?;
1658
1659        Ok(Self::Maybe {
1660            manifest_path: building_crate.manifest_path,
1661            package: building_crate.name.to_string(),
1662        })
1663    }
1664
1665    /// Loads an unresolved dependency using current environment cargo bounds natively.
1666    pub fn with_maybe_none() -> eyre::Result<Self> {
1667        let cargo_metadata = {
1668            let metadata_command = cargo_metadata::MetadataCommand::new();
1669            metadata_command.exec().unwrap()
1670        };
1671        let building_crate = compile::get_building_crate(&cargo_metadata, &None)?;
1672
1673        Ok(Self::Maybe {
1674            manifest_path: building_crate.manifest_path,
1675            package: building_crate.name.to_string(),
1676        })
1677    }
1678
1679    /// Scans an exact provided `.wasm` artifact verifying magic byte signatures correctly to assign a resolution state.
1680    /// User-provided `.wasm` files are wrapped in `Original` to prevent deletion of the original file.
1681    pub fn with_wasm(path: Utf8PathBuf) -> eyre::Result<Self> {
1682        if path.extension() != Some("wasm") {
1683            eyre::bail!("Wasm file does not have .wasm extension: {path}");
1684        }
1685        if !fs::metadata(&path).is_ok() {
1686            eyre::bail!("Wasm file does not exist: {path}");
1687        }
1688
1689        let mut file =
1690            fs::File::open(&path).wrap_err_with(|| format!("Failed to open wasm file: {path}"))?;
1691        let mut magic = [0u8; 8];
1692        file.read_exact(&mut magic)
1693            .wrap_err_with(|| format!("Failed to read magic number from wasm file: {path}"))?;
1694        if !magic.starts_with(b"\0asm") {
1695            eyre::bail!("Wasm file does not have valid magic number: {path}");
1696        }
1697        let version = &magic[4..8];
1698        // https://github.com/WebAssembly/component-model/blob/main/design/mvp/Binary.md#component-definitions
1699        if version == [0x0D, 0x00, 0x01, 0x00] {
1700            return Ok(Self::Component(path));
1701        }
1702        // https://webassembly.github.io/spec/core/binary/modules.html#binary-module
1703        if version != [0x01, 0x00, 0x00, 0x00] {
1704            eyre::bail!("Wasm file does not have valid version: {path}");
1705        }
1706
1707        Ok(Self::Original {
1708            current: path.clone(),
1709            original: path,
1710        })
1711    }
1712
1713    /// Forcefully invokes internal compiling mechanisms translating a declarative specification down into an executable binary structurally.
1714    pub fn definitely(&mut self, threads: bool) -> eyre::Result<()> {
1715        if let WasmPath::Maybe {
1716            manifest_path,
1717            package,
1718        } = self
1719        {
1720            let cargo_metadata = {
1721                let mut metadata_command = cargo_metadata::MetadataCommand::new();
1722                metadata_command.manifest_path(&manifest_path);
1723                metadata_command.exec().unwrap()
1724            };
1725            let building_crate =
1726                compile::get_building_crate(&cargo_metadata, &Some(package.clone()))?;
1727            let vfs_name = building_crate.name.to_string();
1728
1729            let path =
1730                compile::build_vfs(Some(&manifest_path.to_string()), &building_crate, threads)
1731                    .wrap_err_with(|| eyre::eyre!("Failed to build VFS: {vfs_name}"))?;
1732            *self = WasmPath::Definitely(path);
1733        }
1734
1735        // Original variant is already resolved, no action needed.
1736
1737        Ok(())
1738    }
1739
1740    /// Returns the path to the WASM module.
1741    pub fn path(&self) -> eyre::Result<&Utf8PathBuf> {
1742        match self {
1743            WasmPath::Maybe { .. } => {
1744                eyre::bail!("WasmPath is not definitely set: {self:?}")
1745            }
1746            WasmPath::Definitely(p)
1747            | WasmPath::Component(p)
1748            | WasmPath::Original { current: p, .. } => Ok(p),
1749        }
1750    }
1751
1752    /// Returns `true` if the given path is the original user-provided file that should be preserved.
1753    pub fn is_original(&self, path: &Utf8PathBuf) -> bool {
1754        matches!(self, WasmPath::Original { original, .. } if original == path)
1755    }
1756
1757    /// Forcefully overrides the explicitly resolved file path for definite path targets.
1758    /// For `Original` variants, preserves the original path tracking.
1759    pub fn set_path(&mut self, path: Utf8PathBuf) -> eyre::Result<()> {
1760        match self {
1761            WasmPath::Maybe { .. } => {
1762                eyre::bail!("WasmPath is not definitely set: {path}")
1763            }
1764            WasmPath::Original { current, .. } => {
1765                // Keep the original path, only update current
1766                *current = path;
1767            }
1768            _ => {
1769                *self = WasmPath::Definitely(path);
1770            }
1771        }
1772        Ok(())
1773    }
1774}
1775
1776/// Coordinates the underlying binary `wasm-merge` utility invocations to bundle outputs physically.
1777pub fn merge(
1778    vfs: &Utf8PathBuf,
1779    wasm: &[impl AsRef<std::path::Path>],
1780    output: impl AsRef<std::path::Path>,
1781    _threads: bool,
1782    dwarf: bool,
1783) -> eyre::Result<()> {
1784    let custom_section = {
1785        let mut vfs_module = walrus::Module::load(vfs, dwarf)?;
1786        let custom_section_names = vfs_module
1787            .customs
1788            .iter()
1789            .map(|(_, section)| section.name().to_string())
1790            .filter(|name| name.starts_with("component-type:"))
1791            .collect::<Vec<_>>();
1792        // let custom_section = vfs_module
1793        //     .customs.delete(custom_section_names)
1794        let custom_section = custom_section_names
1795            .iter()
1796            .map(|id| {
1797                let section = vfs_module.customs.remove_raw(id);
1798                section.unwrap()
1799            })
1800            .collect::<Vec<_>>();
1801
1802        custom_section
1803    };
1804
1805    let mut merge_cmd = fallback_command::get_fallback_command("wasm-merge");
1806
1807    // if threads {
1808    //     merge_cmd.arg("--enable-threads");
1809    // }
1810
1811    if dwarf {
1812        merge_cmd.arg("--debuginfo");
1813    }
1814
1815    merge_cmd.arg(vfs).arg(UniqueName::WASIP1_ABI_MODULE);
1816
1817    for wasm in wasm {
1818        merge_cmd
1819            .arg(wasm.as_ref().as_os_str().to_str().unwrap())
1820            .arg(format!(
1821                "wasip1_vfs_{}",
1822                wasm.as_ref().get_file_main_name().unwrap()
1823            ));
1824    }
1825
1826    merge_cmd
1827        .arg("--output")
1828        .arg(output.as_ref().as_os_str().to_str().unwrap())
1829        // .arg("--rename-export-conflicts")
1830        .arg("--enable-multimemory")
1831        .arg("--enable-threads");
1832
1833    let result = merge_cmd
1834        .spawn()
1835        .map_err(|e| match e.kind() {
1836            std::io::ErrorKind::NotFound => eyre::eyre!(
1837                "wasm-merge command not found. Please install wasm-merge from https://github.com/WebAssembly/binaryen/releases/latest"
1838            ),
1839            _ => e.into(),
1840        })?
1841        .wait_with_output()
1842        .wrap_err("Failed to wait for wasm-merge process")?;
1843
1844    if !result.success {
1845        return Err(eyre::eyre!("wasm-merge command failed"));
1846    }
1847
1848    let mut module = walrus::Module::load(output.as_ref(), dwarf)?;
1849    for section in custom_section {
1850        module.customs.add(section);
1851    }
1852
1853    // to output
1854    fs::remove_file(output.as_ref()).expect("Failed to remove existing file");
1855
1856    module
1857        .emit_wasm_file(output.as_ref())
1858        .expect("Failed to emit wasm file");
1859
1860    Ok(())
1861}
1862
1863macro_rules! _add_generators_by_type {
1864    ($runner:expr, $($ty:ty),* $(,)?) => {
1865        $(
1866            if let Some(_) = $runner.get_generator_ref::<$ty>().ok() {
1867                panic!("Generator of type {} already exists", std::any::type_name::<$ty>());
1868            }
1869            $runner.add_generator(<$ty>::default());
1870        )*
1871    };
1872}
1873pub(crate) use _add_generators_by_type as add_generators_by_type;