Skip to main content

wasi_virt_layer_cli/generator/
mod.rs

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