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