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    /// Export-stack isolation settings.
275    #[command(flatten)]
276    pub stack_options: StackOptions,
277}
278
279impl BuildArgs {
280    /// Returns the memory hints for each target module.
281    pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
282        self.wasm_memory_hint
283            .iter()
284            .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
285            .chain(std::iter::repeat(None))
286            .take(self.wasm.len())
287            .collect::<Box<_>>()
288    }
289
290    /// Returns the unwind configuration for each target module.
291    pub fn get_wasm_unwinds(&self) -> Box<[bool]> {
292        self.wasm_unwind
293            .iter()
294            .copied()
295            .chain(std::iter::repeat(false))
296            .take(self.wasm.len())
297            .collect::<Box<_>>()
298    }
299
300    /// Resolves and returns the path to the WASM package.
301    pub fn get_package(&self) -> eyre::Result<WasmPath> {
302        let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
303            if let Some(ref manifest) = self.manifest_path {
304                WasmPath::with_maybe_only_manifest(manifest.clone())
305            } else {
306                WasmPath::with_maybe_none()
307            }
308        })?;
309        if let Some(ref manifest) = self.manifest_path {
310            if let WasmPath::Maybe { manifest_path, .. } = &mut p {
311                *manifest_path = manifest.clone();
312            }
313        }
314        Ok(p)
315    }
316
317    /// Gets the list of wasm targets, applying the manifest path if specified.
318    pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
319        let mut paths = self.wasm.clone();
320        if let Some(ref manifest) = self.manifest_path {
321            for p in &mut paths {
322                if let WasmPath::Maybe { manifest_path, .. } = p {
323                    *manifest_path = manifest.clone();
324                }
325            }
326        }
327        paths.into_boxed_slice()
328    }
329}
330
331impl PostBuildContext for BuildArgs {
332    fn out_dir(&self) -> &Utf8PathBuf {
333        &self.out_dir
334    }
335
336    fn keep_build_artifacts(&self) -> bool {
337        self.keep_build_artifacts
338    }
339
340    fn adjust_abi(&self) -> bool {
341        self.adjust_abi
342    }
343
344    fn transpile_to_js(
345        &self,
346        component: &[u8],
347        name: impl AsRef<str>,
348    ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
349        self.transpile_opts.transpile_to_js(component, name)
350    }
351
352    fn dev(&self) -> bool {
353        self.dev
354    }
355
356    fn validate(&self) -> bool {
357        self.validate
358    }
359}
360
361#[derive(Parser, Debug)]
362#[clap(author, version, about, long_about = None, help_template = "
363{name} {version}
364{author}
365{about}
366
367{usage-heading} {usage}
368
369{all-args}")]
370/// Arguments for the `prebuild` command.
371pub struct PreBuildArgs {
372    /// Path to the wasip1 wasm file
373    /// This allow 4 patterns:
374    /// 1. only manifest path, like `./Cargo.toml` or `./some/dir/Cargo.toml`
375    /// 2. only package name, like `my_package`
376    /// 3. manifest path and package name, like `./Cargo.toml::my_package` or `./some/dir/Cargo.toml::my_package`
377    /// 4. direct path to wasm file, like `./target/wasm32-wasi/release/my_crate.wasm`
378    pub wasm: Vec<WasmPath>,
379
380    /// Path to the primary package.
381    #[arg(short, long)]
382    package: Option<WasmPath>,
383
384    /// Path to Cargo.toml
385    #[arg(long)]
386    pub manifest_path: Option<Utf8PathBuf>,
387
388    /// Memory hints for the WASM files, used if automatic detection fails.
389    #[arg(long)]
390    wasm_memory_hint: Vec<isize>,
391
392    /// Enable unwind for the target WASM modules.
393    #[arg(long = "wasm-unwind")]
394    pub wasm_unwind: Vec<bool>,
395
396    /// Output directory for the generated Component WASM
397    #[arg(long, default_value = "./dist")]
398    pub out_dir: Utf8PathBuf,
399
400    /// Target memory type
401    /// Change crate feature flags based on the target memory type
402    #[arg(short, long)]
403    pub target_memory_type: Option<TargetMemoryType>,
404
405    /// If wasm run on multiple threads, enable thread support
406    /// This will change the crate feature flags to enable multi-threading.
407    #[arg(long)]
408    pub threads: Option<bool>,
409
410    /// Enable dwarf
411    /// This is broken currently.
412    /// See https://github.com/wasm-bindgen/walrus/issues/258
413    #[arg(long)]
414    pub dwarf: Option<bool>,
415
416    /// Finally, align the ABI with wasip1-threads.
417    /// Only WASM will be generated.
418    #[arg(long, default_value = "false")]
419    pub adjust_abi: bool,
420
421    /// Keep all intermediate build artifacts instead of deleting them.
422    #[arg(long, default_value = "false")]
423    pub keep_build_artifacts: bool,
424
425    /// Enable development mode (skips Wasm optimization).
426    #[arg(long, default_value = "false")]
427    pub dev: bool,
428
429    /// Validate the generated Wasm modules.
430    #[arg(long, default_value = "false")]
431    pub validate: bool,
432
433    /// Options for building the VFS module.
434    #[command(flatten)]
435    pub vfs_build_opts: VfsBuildOptions,
436
437    /// Options for building target Wasm modules.
438    #[arg(skip)]
439    pub target_vfs_build_opts: Option<Box<[VfsBuildOptions]>>,
440
441    /// Enable own-memory mode.
442    #[arg(long, default_value = "false")]
443    pub own_memory: bool,
444
445    /// Export-stack isolation settings.
446    #[command(flatten)]
447    pub stack_options: StackOptions,
448}
449
450impl PreBuildArgs {
451    /// Returns the memory hints for each target module.
452    pub fn get_wasm_memory_hints(&self) -> Box<[Option<usize>]> {
453        self.wasm_memory_hint
454            .iter()
455            .map(|&hint| if hint < 0 { None } else { Some(hint as usize) })
456            .chain(std::iter::repeat(None))
457            .take(self.wasm.len())
458            .collect::<Box<_>>()
459    }
460
461    /// Returns the unwind configuration for each target module.
462    pub fn get_wasm_unwinds(&self) -> Box<[bool]> {
463        self.wasm_unwind
464            .iter()
465            .copied()
466            .chain(std::iter::repeat(false))
467            .take(self.wasm.len())
468            .collect::<Box<_>>()
469    }
470
471    /// Resolves and returns the path to the WASM package.
472    pub fn get_package(&self) -> eyre::Result<WasmPath> {
473        let mut p = Ok(self.package.clone()).transpose().unwrap_or_else(|| {
474            if let Some(ref manifest) = self.manifest_path {
475                WasmPath::with_maybe_only_manifest(manifest.clone())
476            } else {
477                WasmPath::with_maybe_none()
478            }
479        })?;
480        if let Some(ref manifest) = self.manifest_path {
481            if let WasmPath::Maybe { manifest_path, .. } = &mut p {
482                *manifest_path = manifest.clone();
483            }
484        }
485        Ok(p)
486    }
487
488    /// Gets the list of wasm targets, applying the manifest path if specified.
489    pub fn get_wasm_paths(&self) -> Box<[WasmPath]> {
490        let mut paths = self.wasm.clone();
491        if let Some(ref manifest) = self.manifest_path {
492            for p in &mut paths {
493                if let WasmPath::Maybe { manifest_path, .. } = p {
494                    *manifest_path = manifest.clone();
495                }
496            }
497        }
498        paths.into_boxed_slice()
499    }
500}
501
502#[derive(Parser, Debug)]
503#[clap(author, version, about, long_about = None, help_template = "
504{name} {version}
505{author}
506{about}
507
508{usage-heading} {usage}
509
510{all-args}")]
511/// Arguments for the `postbuild` command.
512pub struct PostBuildArgs {
513    /// Path to the Component WASM file to transpile.
514    #[arg(short, long)]
515    pub package: WasmPath,
516
517    /// Output directory for the generated files
518    #[arg(long, default_value = "./dist")]
519    pub out_dir: Utf8PathBuf,
520
521    /// Options for transpiling to JavaScript.
522    #[command(flatten)]
523    pub transpile_opts: TranspileOpts,
524
525    /// Enable dwarf
526    #[arg(long)]
527    pub dwarf: Option<bool>,
528
529    /// Finally, align the ABI with wasip1-threads.
530    /// Only WASM will be generated.
531    #[arg(long, default_value = "false")]
532    pub adjust_abi: bool,
533
534    /// Keep all intermediate build artifacts instead of deleting them.
535    #[arg(long, default_value = "false")]
536    pub keep_build_artifacts: bool,
537
538    /// Enable development mode (skips Wasm optimization).
539    #[arg(long, default_value = "false")]
540    pub dev: bool,
541
542    /// Validate the generated Wasm modules.
543    #[arg(long, default_value = "false")]
544    pub validate: bool,
545}
546
547impl PostBuildContext for PostBuildArgs {
548    fn out_dir(&self) -> &Utf8PathBuf {
549        &self.out_dir
550    }
551
552    fn keep_build_artifacts(&self) -> bool {
553        self.keep_build_artifacts
554    }
555
556    fn adjust_abi(&self) -> bool {
557        self.adjust_abi
558    }
559
560    fn transpile_to_js(
561        &self,
562        component: &[u8],
563        name: impl AsRef<str>,
564    ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
565        self.transpile_opts.transpile_to_js(component, name)
566    }
567
568    fn dev(&self) -> bool {
569        self.dev
570    }
571
572    fn validate(&self) -> bool {
573        self.validate
574    }
575}
576
577/// Options for transpiling WebAssembly components into JavaScript.
578#[derive(Parser, Debug)]
579#[clap(author, version, about, long_about = None, help_template = "
580{name} {version}
581{author}
582{about}
583
584{usage-heading} {usage}
585
586{all-args}")]
587pub struct TranspileOpts {
588    /// Disables generation of *.d.ts files and instead only generates *.js source files.
589    #[arg(long, default_value = "false")]
590    no_typescript: bool,
591
592    /// Provide a custom JS instantiation API for the component instead of the direct importable native ESM output.
593    /// Sync, Async, Normal, Default is Async.
594    #[arg(long, value_parser = analysis::analysis_instantiation, default_value = "CustomInstantiationMode(None)")]
595    instantiation: CustomInstantiationMode,
596
597    /// Configure how import bindings are provided, as high-level JS bindings, or as hybrid optimized bindings.
598    #[arg(long, value_parser = analysis::analysis_import_bindings)]
599    import_bindings: Option<js_component_bindgen::BindingsMode>,
600
601    /// Comma-separated list of "from-specifier=./to-specifier.js" mappings of component import specifiers to JS import specifiers.
602    #[arg(long, value_delimiter = ',', value_parser = analysis::parse_mapping, action = clap::ArgAction::Append)]
603    map: Vec<(String, String)>,
604
605    /// Disables compatibility in Node.js without a fetch global.
606    #[arg(long, default_value = "false")]
607    no_nodejs_compat: bool,
608
609    /// Set the cutoff byte size for base64 inlining core Wasm in instantiation mode (set to 0 to disable all base64 inlining)
610    #[arg(long, default_value = "0")]
611    base64_cutoff: usize,
612
613    /// Enables compatibility for JS environments without top-level await support via an async $init promise export to wait for instead.
614    #[arg(long, default_value = "false")]
615    tla_compat: bool,
616
617    /// Disable verification of component Wasm data structures when lifting as a production optimization
618    #[arg(long, default_value = "false")]
619    valid_lifting_optimization: bool,
620
621    /// Whether or not to emit tracing calls on function entry/exit.
622    #[arg(long, default_value = "false")]
623    tracing: bool,
624
625    /// Whether to generate namespaced exports like foo as "local:package/foo ". These exports can break typescript builds.
626    #[arg(long, default_value = "false")]
627    no_namespaced_exports: bool,
628
629    /// Whether to generate types for a guest module using module declarations.
630    #[arg(long, default_value = "false")]
631    pub guest: bool,
632}
633
634impl TranspileOpts {
635    /// Transpiles the given WebAssembly component into JavaScript source files.
636    pub fn transpile_to_js(
637        &self,
638        component: &[u8],
639        name: impl AsRef<str>,
640    ) -> Result<js_component_bindgen::Transpiled, eyre::Error> {
641        js_component_bindgen::transpile(
642            component,
643            js_component_bindgen::TranspileOpts {
644                name: name.as_ref().to_string(),
645                no_typescript: self.no_typescript,
646                instantiation_mode: self.instantiation.clone().0,
647                import_bindings: self.import_bindings.clone(),
648                map: if !self.map.is_empty() {
649                    Some(self.map.iter().cloned().collect())
650                } else {
651                    None
652                },
653                nodejs_compat_disabled: self.no_nodejs_compat,
654                base64_cutoff: self.base64_cutoff,
655                tla_compat: self.tla_compat,
656                valid_lifting_optimization: self.valid_lifting_optimization,
657                tracing: self.tracing,
658                no_namespaced_exports: self.no_namespaced_exports,
659                multi_memory: true,
660                guest: self.guest,
661                async_mode: None,
662                strict: false,
663                asmjs: false,
664            },
665        )
666        .to_eyre()
667        .wrap_err("Failed to transpile to JS.")
668    }
669}
670
671/// Represents a custom instantiation mode for the generated JavaScript.
672#[derive(Clone, Debug)]
673pub struct CustomInstantiationMode(Option<js_component_bindgen::InstantiationMode>);
674
675pub(super) mod analysis {
676    use js_component_bindgen::{BindingsMode, InstantiationMode};
677
678    use super::CustomInstantiationMode;
679
680    pub fn analysis_instantiation(s: &str) -> Result<CustomInstantiationMode, clap::Error> {
681        match s {
682            "Sync" => Ok(CustomInstantiationMode(Some(InstantiationMode::Sync))),
683            "Async" => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
684            "Normal" => Ok(CustomInstantiationMode(None)),
685            _ => Ok(CustomInstantiationMode(Some(InstantiationMode::Async))),
686        }
687    }
688
689    pub fn analysis_import_bindings(s: &str) -> Result<Option<BindingsMode>, clap::Error> {
690        match s {
691            "Hybrid" => Ok(Some(BindingsMode::Hybrid)),
692            "Js" => Ok(Some(BindingsMode::Js)),
693            "Optimized" => Ok(Some(BindingsMode::Optimized)),
694            "DirectOptimized" => Ok(Some(BindingsMode::DirectOptimized)),
695            _ => Ok(None),
696        }
697    }
698
699    pub fn parse_mapping(s: &str) -> Result<(String, String), String> {
700        let parts: Vec<&str> = s.splitn(2, '=').collect();
701        if parts.len() != 2 {
702            return Err(format!("Invalid mapping format: '{}'", s));
703        }
704        Ok((parts[0].to_string(), parts[1].to_string()))
705    }
706}
707
708/// Specifies the memory architecture of the target WebAssembly module.
709#[derive(
710    Debug,
711    Clone,
712    Copy,
713    PartialEq,
714    strum::EnumString,
715    strum::Display,
716    serde::Serialize,
717    serde::Deserialize,
718)]
719pub enum TargetMemoryType {
720    /// Traditional single memory environment.
721    #[strum(ascii_case_insensitive)]
722    Single,
723    /// Multi-memory environment where modules have their own address spaces.
724    #[strum(ascii_case_insensitive)]
725    Multi,
726}
727
728impl TargetMemoryType {
729    /// Returns `true` if this memory type is `Multi`.
730    pub fn is_multi(&self) -> bool {
731        matches!(self, TargetMemoryType::Multi)
732    }
733
734    /// Returns `true` if this memory type is `Single`.
735    pub fn is_single(&self) -> bool {
736        matches!(self, TargetMemoryType::Single)
737    }
738}
739
740/// Options for building the VFS module.
741#[derive(Parser, Debug, Clone, Default)]
742pub struct VfsBuildOptions {
743    /// Space or comma separated list of features to activate for the VFS module.
744    #[arg(long, action = clap::ArgAction::Append)]
745    pub features: Vec<String>,
746
747    /// Do not activate the `default` feature of the VFS module.
748    #[arg(long, action = clap::ArgAction::Count)]
749    pub no_default_features: u8,
750
751    /// Enable unwind for the module.
752    #[arg(long = "vfs-unwind", default_value = "false")]
753    pub unwind: bool,
754
755    /// Disable optimization for this specific module.
756    #[arg(long, action = clap::ArgAction::Count)]
757    pub no_opt: u8,
758
759    /// Disable all optimizations for this module and subsequent merged modules.
760    #[arg(long, action = clap::ArgAction::Count)]
761    pub no_opt_all: u8,
762}