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