Skip to main content

wasi_virt_layer_cli/
args.rs

1use camino::Utf8PathBuf;
2use clap::{Args as ClapArgs, Parser, Subcommand};
3use eyre::Context as _;
4use std::str::FromStr;
5
6use crate::{generator::WasmPath, util::ResultUtil as _};
7
8/// A module-specific byte size supplied as `MODULE=SIZE`.
9#[derive(Clone, Debug, Eq, PartialEq)]
10pub struct ModuleStackSize {
11    /// Module name, or the special alias `vfs`.
12    pub module: String,
13    /// Stack size in bytes.
14    pub bytes: u32,
15}
16
17impl FromStr for ModuleStackSize {
18    type Err = String;
19
20    fn from_str(value: &str) -> Result<Self, Self::Err> {
21        let (module, size) = value
22            .split_once('=')
23            .ok_or_else(|| "expected MODULE=SIZE".to_string())?;
24        if module.is_empty() {
25            return Err("module name must not be empty".to_string());
26        }
27
28        let size = size.trim();
29        let (digits, multiplier) = if let Some(digits) = size.strip_suffix("MiB") {
30            (digits, 1024_u64 * 1024)
31        } else if let Some(digits) = size.strip_suffix("KiB") {
32            (digits, 1024)
33        } else if let Some(digits) = size.strip_suffix("M") {
34            (digits, 1024_u64 * 1024)
35        } else if let Some(digits) = size.strip_suffix("K") {
36            (digits, 1024)
37        } else {
38            (size, 1)
39        };
40        let bytes = digits
41            .parse::<u64>()
42            .map_err(|_| format!("invalid stack size `{size}`"))?
43            .checked_mul(multiplier)
44            .ok_or_else(|| format!("stack size `{size}` overflows"))?;
45        let bytes = u32::try_from(bytes)
46            .map_err(|_| format!("stack size `{size}` exceeds the wasm32 address space"))?;
47        if bytes == 0 {
48            return Err("stack size must be greater than zero".to_string());
49        }
50
51        Ok(Self {
52            module: module.to_string(),
53            bytes,
54        })
55    }
56}
57
58/// A module-specific slot count supplied as `MODULE=COUNT`.
59#[derive(Clone, Debug, Eq, PartialEq)]
60pub struct ModuleStackSlots {
61    /// Target module name.
62    pub module: String,
63    /// Number of fixed stack slots.
64    pub slots: u32,
65}
66
67impl FromStr for ModuleStackSlots {
68    type Err = String;
69
70    fn from_str(value: &str) -> Result<Self, Self::Err> {
71        let (module, slots) = value
72            .split_once('=')
73            .ok_or_else(|| "expected MODULE=COUNT".to_string())?;
74        if module.is_empty() {
75            return Err("module name must not be empty".to_string());
76        }
77        let slots = slots
78            .parse::<u32>()
79            .map_err(|_| format!("invalid stack slot count `{slots}`"))?;
80        if slots == 0 {
81            return Err("stack slot count must be greater than zero".to_string());
82        }
83        Ok(Self {
84            module: module.to_string(),
85            slots,
86        })
87    }
88}
89
90/// Export-stack isolation settings.
91#[derive(ClapArgs, Clone, Debug, Default)]
92pub struct StackOptions {
93    /// Enable export-stack isolation for a module and set its stack size.
94    ///
95    /// Accepts bytes or binary suffixes, for example `vfs=1MiB` or
96    /// `worker=512KiB`. May be repeated.
97    #[arg(long = "stack-size", value_name = "MODULE=SIZE")]
98    pub sizes: Vec<ModuleStackSize>,
99
100    /// Set the fixed slot count for a multi-memory target.
101    ///
102    /// This option is invalid for the VFS and for single-memory builds.
103    #[arg(long = "stack-slots", value_name = "MODULE=COUNT")]
104    pub slots: Vec<ModuleStackSlots>,
105}
106
107/// Common interface for post-build (transpilation) arguments.
108pub trait PostBuildContext {
109    /// Returns the output directory path.
110    fn out_dir(&self) -> &Utf8PathBuf;
111    /// Returns whether to keep intermediate build artifacts.
112    fn keep_build_artifacts(&self) -> bool;
113    /// Returns whether to adjust the ABI.
114    fn adjust_abi(&self) -> bool;
115    /// Transpiles the given WebAssembly component into JavaScript source files.
116    fn transpile_to_js(
117        &self,
118        component: &[u8],
119        name: impl AsRef<str>,
120    ) -> Result<js_component_bindgen::Transpiled, eyre::Error>;
121    /// Returns whether to skip Wasm optimization (dev mode).
122    fn dev(&self) -> bool;
123    /// Returns whether to validate generated Wasm modules.
124    fn validate(&self) -> bool;
125}
126
127/// The main command-line interface for `wasi_virt_layer-cli`.
128#[derive(Parser, Debug)]
129#[clap(author, version, about, long_about = None, help_template = "
130{name} {version}
131{author}
132{about}
133
134{usage-heading} {usage}
135
136{all-args}")]
137#[clap(propagate_version = true)]
138pub struct Cli {
139    /// The command to execute.
140    #[clap(subcommand)]
141    pub command: Command,
142}
143
144#[derive(Subcommand, Debug)]
145#[clap(author, version, about, long_about = None, help_template = "
146{name} {version}
147{author}
148{about}
149
150{usage-heading} {usage}
151
152{all-args}")]
153/// Supported subcommands for the CLI.
154pub enum Command {
155    /// Builds a virtualized WASM module (prebuild + postbuild combined).
156    Build(BuildArgs),
157    /// Generates a Component WASM from VFS and target WASM modules.
158    Prebuild(PreBuildArgs),
159    /// Transpiles a Component WASM into JavaScript files.
160    Postbuild(PostBuildArgs),
161    /// Initializes a new WASI Virt Layer project.
162    New(NewArgs),
163}
164
165#[derive(Parser, Debug)]
166#[clap(author, version, about, long_about = None, help_template = "
167{name} {version}
168{author}
169{about}
170
171{usage-heading} {usage}
172
173{all-args}")]
174/// Arguments for the `new` command.
175pub struct NewArgs {
176    /// The path where the new project will be created.
177    #[arg(value_name = "PATH")]
178    pub path: Utf8PathBuf,
179
180    /// Whether to enable multi-threading support in the new project.
181    #[arg(long, default_value = "false")]
182    pub threads: bool,
183}
184
185#[derive(Parser, Debug)]
186#[clap(author, version, about, long_about = None, help_template = "
187{name} {version}
188{author}
189{about}
190
191{usage-heading} {usage}
192
193{all-args}")]
194/// Arguments for the `build` command.
195pub struct BuildArgs {
196    /// Path to the wasip1 wasm file
197    /// This allow 4 patterns:
198    /// 1. only manifest path, like `./Cargo.toml` or `./some/dir/Cargo.toml`
199    /// 2. only package name, like `my_package`
200    /// 3. manifest path and package name, like `./Cargo.toml::my_package` or `./some/dir/Cargo.toml::my_package`
201    /// 4. direct path to wasm file, like `./target/wasm32-wasi/release/my_crate.wasm`
202    pub wasm: Vec<WasmPath>,
203
204    /// Path to the primary package; used for single-package mode or component translation.
205    #[arg(short, long)]
206    package: Option<WasmPath>,
207
208    /// Path to Cargo.toml
209    #[arg(long)]
210    pub manifest_path: Option<Utf8PathBuf>,
211
212    /// Memory hints for the WASM files, used if automatic detection fails.
213    #[arg(long)]
214    wasm_memory_hint: Vec<isize>,
215
216    /// Enable unwind for the target WASM modules.
217    #[arg(long = "wasm-unwind")]
218    pub wasm_unwind: Vec<bool>,
219
220    /// Output directory for the generated files
221    #[arg(long, default_value = "./dist")]
222    pub out_dir: Utf8PathBuf,
223
224    /// Target memory type
225    /// Change crate feature flags based on the target memory type
226    #[arg(short, long)]
227    pub target_memory_type: Option<TargetMemoryType>,
228
229    // transpile options
230    /// Options for transpiling to JavaScript.
231    #[command(flatten)]
232    pub transpile_opts: TranspileOpts,
233
234    /// If wasm run on multiple threads, enable thread support
235    /// This will change the crate feature flags to enable multi-threading.
236    #[arg(long)]
237    pub threads: Option<bool>,
238
239    /// Enable dwarf
240    /// This is broken currently.
241    /// See <https://github.com/wasm-bindgen/walrus/issues/258>
242    #[arg(long)]
243    pub dwarf: Option<bool>,
244
245    /// Finally, align the ABI with wasip1-threads.
246    /// Only WASM will be generated.
247    #[arg(long, default_value = "false")]
248    pub adjust_abi: bool,
249
250    /// Keep all intermediate build artifacts instead of deleting them.
251    #[arg(long, default_value = "false")]
252    pub keep_build_artifacts: bool,
253
254    /// Enable development mode (skips Wasm optimization).
255    #[arg(long, default_value = "false")]
256    pub dev: bool,
257
258    /// Validate the generated Wasm modules.
259    #[arg(long, default_value = "false")]
260    pub validate: bool,
261
262    /// Options for building the VFS module.
263    #[command(flatten)]
264    pub vfs_build_opts: VfsBuildOptions,
265
266    /// Options for building target Wasm modules.
267    #[arg(skip)]
268    pub target_vfs_build_opts: Option<Box<[VfsBuildOptions]>>,
269
270    /// Enable own-memory mode.
271    #[arg(long, default_value = "false")]
272    pub own_memory: bool,
273
274    /// Enable atomic wait deadlock detection for threaded builds.
275    #[arg(long, default_value = "false")]
276    pub detect_deadlock: bool,
277
278    /// Export-stack isolation settings.
279    #[command(flatten)]
280    pub stack_options: StackOptions,
281}
282
283impl BuildArgs {
284    /// Returns the memory hints for each target module.
285    pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
286        self.wasm_memory_hint
287            .iter()
288            .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
289            .chain(std::iter::repeat(None))
290            .take(self.wasm.len())
291            .collect::<Box<_>>()
292    }
293
294    /// Returns the unwind configuration for each target module.
295    pub fn get_wasm_unwinds(&self) -> Box<[bool]> {
296        self.wasm_unwind
297            .iter()
298            .copied()
299            .chain(std::iter::repeat(false))
300            .take(self.wasm.len())
301            .collect::<Box<_>>()
302    }
303
304    /// Resolves and returns the path to the WASM package.
305    pub fn get_package(&self) -> eyre::Result<WasmPath> {
306        let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
307            if let Some(ref manifest) = self.manifest_path {
308                WasmPath::with_maybe_only_manifest(manifest.clone())
309            } else {
310                WasmPath::with_maybe_none()
311            }
312        })?;
313        if let Some(ref manifest) = self.manifest_path {
314            if let WasmPath::Maybe { manifest_path, .. } = &mut p {
315                *manifest_path = manifest.clone();
316            }
317        }
318        Ok(p)
319    }
320
321    /// Gets the list of wasm targets, applying the manifest path if specified.
322    pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
323        let mut paths = self.wasm.clone();
324        if let Some(ref manifest) = self.manifest_path {
325            for p in &mut paths {
326                if let WasmPath::Maybe { manifest_path, .. } = p {
327                    *manifest_path = manifest.clone();
328                }
329            }
330        }
331        paths.into_boxed_slice()
332    }
333}
334
335impl PostBuildContext for BuildArgs {
336    fn out_dir(&self) -> &Utf8PathBuf {
337        &self.out_dir
338    }
339
340    fn keep_build_artifacts(&self) -> bool {
341        self.keep_build_artifacts
342    }
343
344    fn adjust_abi(&self) -> bool {
345        self.adjust_abi
346    }
347
348    fn transpile_to_js(
349        &self,
350        component: &[u8],
351        name: impl AsRef<str>,
352    ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
353        self.transpile_opts.transpile_to_js(component, name)
354    }
355
356    fn dev(&self) -> bool {
357        self.dev
358    }
359
360    fn validate(&self) -> bool {
361        self.validate
362    }
363}
364
365#[derive(Parser, Debug)]
366#[clap(author, version, about, long_about = None, help_template = "
367{name} {version}
368{author}
369{about}
370
371{usage-heading} {usage}
372
373{all-args}")]
374/// Arguments for the `prebuild` command.
375pub struct PreBuildArgs {
376    /// Path to the wasip1 wasm file
377    /// This allow 4 patterns:
378    /// 1. only manifest path, like `./Cargo.toml` or `./some/dir/Cargo.toml`
379    /// 2. only package name, like `my_package`
380    /// 3. manifest path and package name, like `./Cargo.toml::my_package` or `./some/dir/Cargo.toml::my_package`
381    /// 4. direct path to wasm file, like `./target/wasm32-wasi/release/my_crate.wasm`
382    pub wasm: Vec<WasmPath>,
383
384    /// Path to the primary package.
385    #[arg(short, long)]
386    package: Option<WasmPath>,
387
388    /// Path to Cargo.toml
389    #[arg(long)]
390    pub manifest_path: Option<Utf8PathBuf>,
391
392    /// Memory hints for the WASM files, used if automatic detection fails.
393    #[arg(long)]
394    wasm_memory_hint: Vec<isize>,
395
396    /// Enable unwind for the target WASM modules.
397    #[arg(long = "wasm-unwind")]
398    pub wasm_unwind: Vec<bool>,
399
400    /// Output directory for the generated Component WASM
401    #[arg(long, default_value = "./dist")]
402    pub out_dir: Utf8PathBuf,
403
404    /// Target memory type
405    /// Change crate feature flags based on the target memory type
406    #[arg(short, long)]
407    pub target_memory_type: Option<TargetMemoryType>,
408
409    /// If wasm run on multiple threads, enable thread support
410    /// This will change the crate feature flags to enable multi-threading.
411    #[arg(long)]
412    pub threads: Option<bool>,
413
414    /// Enable dwarf
415    /// This is broken currently.
416    /// See <https://github.com/wasm-bindgen/walrus/issues/258>
417    #[arg(long)]
418    pub dwarf: Option<bool>,
419
420    /// Finally, align the ABI with wasip1-threads.
421    /// Only WASM will be generated.
422    #[arg(long, default_value = "false")]
423    pub adjust_abi: bool,
424
425    /// Keep all intermediate build artifacts instead of deleting them.
426    #[arg(long, default_value = "false")]
427    pub keep_build_artifacts: bool,
428
429    /// Enable development mode (skips Wasm optimization).
430    #[arg(long, default_value = "false")]
431    pub dev: bool,
432
433    /// Validate the generated Wasm modules.
434    #[arg(long, default_value = "false")]
435    pub validate: bool,
436
437    /// Options for building the VFS module.
438    #[command(flatten)]
439    pub vfs_build_opts: VfsBuildOptions,
440
441    /// Options for building target Wasm modules.
442    #[arg(skip)]
443    pub target_vfs_build_opts: Option<Box<[VfsBuildOptions]>>,
444
445    /// Enable own-memory mode.
446    #[arg(long, default_value = "false")]
447    pub own_memory: bool,
448
449    /// Enable atomic wait deadlock detection for threaded builds.
450    #[arg(long, default_value = "false")]
451    pub detect_deadlock: bool,
452
453    /// Export-stack isolation settings.
454    #[command(flatten)]
455    pub stack_options: StackOptions,
456}
457
458impl PreBuildArgs {
459    /// Returns the memory hints for each target module.
460    pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
461        self.wasm_memory_hint
462            .iter()
463            .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
464            .chain(std::iter::repeat(None))
465            .take(self.wasm.len())
466            .collect::<Box<_>>()
467    }
468
469    /// Returns the unwind configuration for each target module.
470    pub fn get_wasm_unwinds(&self) -> Box<[bool]> {
471        self.wasm_unwind
472            .iter()
473            .copied()
474            .chain(std::iter::repeat(false))
475            .take(self.wasm.len())
476            .collect::<Box<_>>()
477    }
478
479    /// Resolves and returns the path to the WASM package.
480    pub fn get_package(&self) -> eyre::Result<WasmPath> {
481        let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
482            if let Some(ref manifest) = self.manifest_path {
483                WasmPath::with_maybe_only_manifest(manifest.clone())
484            } else {
485                WasmPath::with_maybe_none()
486            }
487        })?;
488        if let Some(ref manifest) = self.manifest_path {
489            if let WasmPath::Maybe { manifest_path, .. } = &mut p {
490                *manifest_path = manifest.clone();
491            }
492        }
493        Ok(p)
494    }
495
496    /// Gets the list of wasm targets, applying the manifest path if specified.
497    pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
498        let mut paths = self.wasm.clone();
499        if let Some(ref manifest) = self.manifest_path {
500            for p in &mut paths {
501                if let WasmPath::Maybe { manifest_path, .. } = p {
502                    *manifest_path = manifest.clone();
503                }
504            }
505        }
506        paths.into_boxed_slice()
507    }
508}
509
510#[derive(Parser, Debug)]
511#[clap(author, version, about, long_about = None, help_template = "
512{name} {version}
513{author}
514{about}
515
516{usage-heading} {usage}
517
518{all-args}")]
519/// Arguments for the `postbuild` command.
520pub struct PostBuildArgs {
521    /// Path to the Component WASM file to transpile.
522    #[arg(short, long)]
523    pub package: WasmPath,
524
525    /// Output directory for the generated files
526    #[arg(long, default_value = "./dist")]
527    pub out_dir: Utf8PathBuf,
528
529    /// Options for transpiling to JavaScript.
530    #[command(flatten)]
531    pub transpile_opts: TranspileOpts,
532
533    /// Enable dwarf
534    #[arg(long)]
535    pub dwarf: Option<bool>,
536
537    /// Finally, align the ABI with wasip1-threads.
538    /// Only WASM will be generated.
539    #[arg(long, default_value = "false")]
540    pub adjust_abi: bool,
541
542    /// Keep all intermediate build artifacts instead of deleting them.
543    #[arg(long, default_value = "false")]
544    pub keep_build_artifacts: bool,
545
546    /// Enable development mode (skips Wasm optimization).
547    #[arg(long, default_value = "false")]
548    pub dev: bool,
549
550    /// Validate the generated Wasm modules.
551    #[arg(long, default_value = "false")]
552    pub validate: bool,
553}
554
555impl PostBuildContext for PostBuildArgs {
556    fn out_dir(&self) -> &Utf8PathBuf {
557        &self.out_dir
558    }
559
560    fn keep_build_artifacts(&self) -> bool {
561        self.keep_build_artifacts
562    }
563
564    fn adjust_abi(&self) -> bool {
565        self.adjust_abi
566    }
567
568    fn transpile_to_js(
569        &self,
570        component: &[u8],
571        name: impl AsRef<str>,
572    ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
573        self.transpile_opts.transpile_to_js(component, name)
574    }
575
576    fn dev(&self) -> bool {
577        self.dev
578    }
579
580    fn validate(&self) -> bool {
581        self.validate
582    }
583}
584
585/// Options for transpiling WebAssembly components into JavaScript.
586#[derive(Parser, Debug)]
587#[clap(author, version, about, long_about = None, help_template = "
588{name} {version}
589{author}
590{about}
591
592{usage-heading} {usage}
593
594{all-args}")]
595pub struct TranspileOpts {
596    /// Disables generation of *.d.ts files and instead only generates *.js source files.
597    #[arg(long, default_value = "false")]
598    no_typescript: bool,
599
600    /// Provide a custom JS instantiation API for the component instead of the direct importable native ESM output.
601    /// Sync, Async, Normal, Default is Async.
602    #[arg(long, value_parser = analysis::analysis_instantiation, default_value = "CustomInstantiationMode(None)")]
603    instantiation: CustomInstantiationMode,
604
605    /// Configure how import bindings are provided, as high-level JS bindings, or as hybrid optimized bindings.
606    #[arg(long, value_parser = analysis::analysis_import_bindings)]
607    import_bindings: Option<js_component_bindgen::BindingsMode>,
608
609    /// Comma-separated list of "from-specifier=./to-specifier.js" mappings of component import specifiers to JS import specifiers.
610    #[arg(long, value_delimiter = ',', value_parser = analysis::parse_mapping, action = clap::ArgAction::Append)]
611    map: Vec<(String, String)>,
612
613    /// Disables compatibility in Node.js without a fetch global.
614    #[arg(long, default_value = "false")]
615    no_nodejs_compat: bool,
616
617    /// Set the cutoff byte size for base64 inlining core Wasm in instantiation mode (set to 0 to disable all base64 inlining)
618    #[arg(long, default_value = "0")]
619    base64_cutoff: usize,
620
621    /// Enables compatibility for JS environments without top-level await support via an async $init promise export to wait for instead.
622    #[arg(long, default_value = "false")]
623    tla_compat: bool,
624
625    /// Disable verification of component Wasm data structures when lifting as a production optimization
626    #[arg(long, default_value = "false")]
627    valid_lifting_optimization: bool,
628
629    /// Whether or not to emit tracing calls on function entry/exit.
630    #[arg(long, default_value = "false")]
631    tracing: bool,
632
633    /// Whether to generate namespaced exports like foo as "local:package/foo ". These exports can break typescript builds.
634    #[arg(long, default_value = "false")]
635    no_namespaced_exports: bool,
636
637    /// Whether to generate types for a guest module using module declarations.
638    #[arg(long, default_value = "false")]
639    pub guest: bool,
640}
641
642impl TranspileOpts {
643    /// Transpiles the given WebAssembly component into JavaScript source files.
644    pub fn transpile_to_js(
645        &self,
646        component: &[u8],
647        name: impl AsRef<str>,
648    ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
649        js_component_bindgen::transpile(
650            component,
651            js_component_bindgen::TranspileOpts {
652                name: name.as_ref().to_string(),
653                no_typescript: self.no_typescript,
654                instantiation_mode: self.instantiation.clone().0,
655                import_bindings: self.import_bindings.clone(),
656                map: if !self.map.is_empty() {
657                    Some(self.map.iter().cloned().collect())
658                } else {
659                    None
660                },
661                nodejs_compat_disabled: self.no_nodejs_compat,
662                base64_cutoff: self.base64_cutoff,
663                tla_compat: self.tla_compat,
664                valid_lifting_optimization: self.valid_lifting_optimization,
665                tracing: self.tracing,
666                no_namespaced_exports: self.no_namespaced_exports,
667                multi_memory: true,
668                guest: self.guest,
669                async_mode: None,
670                strict: false,
671                asmjs: false,
672            },
673        )
674        .to_eyre()
675        .wrap_err("Failed to transpile to JS.")
676    }
677}
678
679/// Represents a custom instantiation mode for the generated JavaScript.
680#[derive(Clone, Debug)]
681pub struct CustomInstantiationMode(Option<js_component_bindgen::InstantiationMode>);
682
683pub(super) mod analysis {
684    use js_component_bindgen::{BindingsMode, InstantiationMode};
685
686    use super::CustomInstantiationMode;
687
688    pub fn analysis_instantiation(s: &str) -> Result<CustomInstantiationMode, clap::Error> {
689        match s {
690            "Sync" => Ok(CustomInstantiationMode(Some(InstantiationMode::Sync))),
691            "Async" => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
692            "Normal" => Ok(CustomInstantiationMode(None)),
693            _ => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
694        }
695    }
696
697    pub fn analysis_import_bindings(s: &str) -> Result<Option<BindingsMode>, clap::Error> {
698        match s {
699            "Hybrid" => Ok(Some(BindingsMode::Hybrid)),
700            "Js" => Ok(Some(BindingsMode::Js)),
701            "Optimized" => Ok(Some(BindingsMode::Optimized)),
702            "DirectOptimized" => Ok(Some(BindingsMode::DirectOptimized)),
703            _ => Ok(None),
704        }
705    }
706
707    pub fn parse_mapping(s: &str) -> Result<(String, String), String> {
708        let parts: Vec<&str> = s.splitn(2, '=').collect();
709        if parts.len() != 2 {
710            return Err(format!("Invalid mapping format: '{}'", s));
711        }
712        Ok((parts[0].to_string(), parts[1].to_string()))
713    }
714}
715
716/// Specifies the memory architecture of the target WebAssembly module.
717#[derive(
718    Debug,
719    Clone,
720    Copy,
721    PartialEq,
722    strum::EnumString,
723    strum::Display,
724    serde::Serialize,
725    serde::Deserialize,
726)]
727pub enum TargetMemoryType {
728    /// Traditional single memory environment.
729    #[strum(ascii_case_insensitive)]
730    Single,
731    /// Multi-memory environment where modules have their own address spaces.
732    #[strum(ascii_case_insensitive)]
733    Multi,
734}
735
736impl TargetMemoryType {
737    /// Returns `true` if this memory type is `Multi`.
738    pub fn is_multi(&self) -> bool {
739        matches!(self, TargetMemoryType::Multi)
740    }
741
742    /// Returns `true` if this memory type is `Single`.
743    pub fn is_single(&self) -> bool {
744        matches!(self, TargetMemoryType::Single)
745    }
746}
747
748/// Options for building the VFS module.
749#[derive(Parser, Debug, Clone, Default)]
750pub struct VfsBuildOptions {
751    /// Space or comma separated list of features to activate for the VFS module.
752    #[arg(long, action = clap::ArgAction::Append)]
753    pub features: Vec<String>,
754
755    /// Do not activate the `default` feature of the VFS module.
756    #[arg(long, action = clap::ArgAction::Count)]
757    pub no_default_features: u8,
758
759    /// Enable unwind for the module.
760    #[arg(long = "vfs-unwind", default_value = "false")]
761    pub unwind: bool,
762
763    /// Disable optimization for this specific module.
764    #[arg(long, action = clap::ArgAction::Count)]
765    pub no_opt: u8,
766
767    /// Disable all optimizations for this module and subsequent merged modules.
768    #[arg(long, action = clap::ArgAction::Count)]
769    pub no_opt_all: u8,
770}