Skip to main content

wasmtime_cli_flags/
opt.rs

1//! Support for parsing Wasmtime's `-O`, `-W`, etc "option groups"
2//!
3//! This builds up a clap-derive-like system where there's ideally a single
4//! macro `wasmtime_option_group!` which is invoked per-option which enables
5//! specifying options in a struct-like syntax where all other boilerplate about
6//! option parsing is contained exclusively within this module.
7
8use crate::{CompileTimeBuiltin, KeyValuePair, UnsafeIntrinsicsImport, WasiNnGraph};
9#[cfg(feature = "clap")]
10use clap::builder::{StringValueParser, TypedValueParser, ValueParserFactory};
11#[cfg(feature = "clap")]
12use clap::error::{Error, ErrorKind};
13#[cfg(feature = "serde")]
14use serde::de::{self, Visitor};
15use std::fmt;
16use std::num::{NonZeroU32, NonZeroUsize};
17use std::path::{Path, PathBuf};
18use std::str::FromStr;
19use std::time::Duration;
20use wasmtime::error::Context;
21use wasmtime::{Result, bail, format_err};
22
23/// Characters which can be safely ignored while parsing numeric options to wasmtime
24const IGNORED_NUMBER_CHARS: [char; 1] = ['_'];
25
26#[macro_export]
27macro_rules! wasmtime_option_group {
28    (
29        #[env = $env:tt]
30        $(#[$attr:meta])*
31        pub struct $opts:ident {
32            $(
33                $(#[doc = $doc:tt])*
34                $(#[doc($doc_attr:meta)])?
35                $(#[serde($serde_attr:meta)])*
36                pub $opt:ident: $container:ident<$payload:ty>,
37            )+
38
39            $(
40                #[prefixed = $prefix:tt]
41                $(#[serde($serde_attr2:meta)])*
42                $(#[doc = $prefixed_doc:tt])*
43                $(#[doc($prefixed_doc_attr:meta)])?
44                pub $prefixed:ident: Vec<(String, Option<String>)>,
45            )?
46        }
47        enum $option:ident {
48            ...
49        }
50    ) => {
51        #[derive(Default, Debug, PartialEq, Clone)]
52        #[cfg_attr(feature = "serde", derive(serde_derive::Deserialize, serde_derive::Serialize))]
53        #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case", deny_unknown_fields))]
54        $(#[$attr])*
55        pub struct $opts {
56            $(
57                $(#[cfg_attr(feature = "serde", serde($serde_attr))])*
58                $(#[doc($doc_attr)])?
59                pub $opt: $container<$payload>,
60            )+
61            $(
62                $(#[cfg_attr(feature = "serde", serde($serde_attr2))])*
63                pub $prefixed: Vec<(String, Option<String>)>,
64            )?
65        }
66
67        #[derive(Clone, PartialEq)]
68        #[expect(non_camel_case_types, reason = "macro-generated code")]
69        enum $option {
70            $(
71                $opt($payload),
72            )+
73            $(
74                $prefixed(String, Option<String>),
75            )?
76        }
77
78        impl $crate::opt::WasmtimeOption for $option {
79            const ENV_PREFIX: &'static str = concat!("WASMTIME_", $env);
80            const OPTIONS: &'static [$crate::opt::OptionDesc<$option>] = &[
81                $(
82                    $crate::opt::OptionDesc {
83                        name: $crate::opt::OptName::Name(stringify!($opt)),
84                        parse: |_, s| {
85                            Ok($option::$opt(
86                                $crate::opt::WasmtimeOptionValue::parse(s)?
87                            ))
88                        },
89                        val_help: <$payload as $crate::opt::WasmtimeOptionValue>::VAL_HELP,
90                        docs: concat!($($doc, "\n",)*),
91                    },
92                 )+
93                $(
94                    $crate::opt::OptionDesc {
95                        name: $crate::opt::OptName::Prefix($prefix),
96                        parse: |name, val| {
97                            Ok($option::$prefixed(
98                                name.to_string(),
99                                val.map(|v| v.to_string()),
100                            ))
101                        },
102                        val_help: "[=val]",
103                        docs: concat!($($prefixed_doc, "\n",)*),
104                    },
105                 )?
106            ];
107        }
108
109        impl core::fmt::Display for $option {
110            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
111                match self {
112                    $(
113                        $option::$opt(val) => {
114                            write!(f, "{}=", stringify!($opt).replace('_', "-"))?;
115                            $crate::opt::WasmtimeOptionValue::display(val, f)
116                        }
117                    )+
118                    $(
119                        $option::$prefixed(key, val) => {
120                            write!(f, "{}-{key}", stringify!($prefixed))?;
121                            if let Some(val) = val {
122                                write!(f, "={val}")?;
123                            }
124                            Ok(())
125                        }
126                    )?
127                }
128            }
129        }
130
131        impl $opts {
132            fn configure_with(
133                &mut self,
134                opts: &[$crate::opt::CommaSeparated<$option>],
135                env: bool,
136            ) -> Result<()> {
137                let env_opts = if env {
138                    <$option as $crate::opt::WasmtimeOption>::parse_env()?
139                } else {
140                    Vec::new()
141                };
142                for opt in env_opts.iter().chain(opts.iter().flat_map(|o| o.0.iter())) {
143                    self.configure(opt);
144                }
145                Ok(())
146            }
147
148            fn configure(&mut self, opt: &$option) {
149                match opt {
150                    $(
151                        $option::$opt(val) => {
152                            $crate::opt::OptionContainer::push(&mut self.$opt, val.clone());
153                        }
154                    )+
155                    $(
156                        $option::$prefixed(key, val) => self.$prefixed.push((key.clone(), val.clone())),
157                    )?
158                }
159            }
160
161            fn to_options(&self) -> Vec<$option> {
162                let mut ret = Vec::new();
163                $(
164                    for item in $crate::opt::OptionContainer::get(&self.$opt) {
165                        ret.push($option::$opt(item.clone()));
166                    }
167                )+
168                $(
169                    for (key,val) in self.$prefixed.iter() {
170                        ret.push($option::$prefixed(key.clone(), val.clone()));
171                    }
172                )?
173                ret
174            }
175        }
176    };
177}
178
179/// Parser registered with clap which handles parsing the `...` in `-O ...`.
180#[derive(Clone, Debug, PartialEq)]
181pub struct CommaSeparated<T>(pub Vec<T>);
182
183#[cfg(feature = "clap")]
184impl<T> ValueParserFactory for CommaSeparated<T>
185where
186    T: WasmtimeOption,
187{
188    type Parser = CommaSeparatedParser<T>;
189
190    fn value_parser() -> CommaSeparatedParser<T> {
191        CommaSeparatedParser(std::marker::PhantomData)
192    }
193}
194
195#[derive(Clone)]
196#[cfg(feature = "clap")]
197pub struct CommaSeparatedParser<T>(std::marker::PhantomData<T>);
198
199#[cfg(feature = "clap")]
200impl<T> TypedValueParser for CommaSeparatedParser<T>
201where
202    T: WasmtimeOption,
203{
204    type Value = CommaSeparated<T>;
205
206    fn parse_ref(
207        &self,
208        cmd: &clap::Command,
209        arg: Option<&clap::Arg>,
210        value: &std::ffi::OsStr,
211    ) -> Result<Self::Value, Error> {
212        let val = StringValueParser::new().parse_ref(cmd, arg, value)?;
213
214        let options = T::OPTIONS;
215        let arg = arg.expect("should always have an argument");
216        let arg_long = arg.get_long().expect("should have a long name specified");
217        let arg_short = arg.get_short().expect("should have a short name specified");
218
219        // Handle `-O help` which dumps all the `-O` options, their messages,
220        // and then exits.
221        if val == "help" {
222            let mut max = 0;
223            for d in options {
224                max = max.max(d.name.display_string().len() + d.val_help.len());
225            }
226            println!("Available {arg_long} options:\n");
227            for d in options {
228                print!(
229                    "  -{arg_short} {:>1$}",
230                    d.name.display_string(),
231                    max - d.val_help.len()
232                );
233                print!("{}", d.val_help);
234                print!(" --");
235                if val == "help" {
236                    for line in d.docs.lines().map(|s| s.trim()) {
237                        if line.is_empty() {
238                            break;
239                        }
240                        print!(" {line}");
241                    }
242                    println!();
243                } else {
244                    println!();
245                    for line in d.docs.lines().map(|s| s.trim()) {
246                        let line = line.trim();
247                        println!("        {line}");
248                    }
249                }
250            }
251            println!("\npass `-{arg_short} help-long` to see longer-form explanations");
252            std::process::exit(0);
253        }
254        if val == "help-long" {
255            println!("Available {arg_long} options:\n");
256            for d in options {
257                println!(
258                    "  -{arg_short} {}{} --",
259                    d.name.display_string(),
260                    d.val_help
261                );
262                println!();
263                for line in d.docs.lines().map(|s| s.trim()) {
264                    let line = line.trim();
265                    println!("        {line}");
266                }
267            }
268            std::process::exit(0);
269        }
270
271        T::parse_csv(&val).map(CommaSeparated).map_err(|e| {
272            Error::raw(
273                ErrorKind::InvalidValue,
274                format!("failed to parse -{arg_short} / --{arg_long} option: {e:?}\n"),
275            )
276        })
277    }
278}
279
280/// Helper trait used by `CommaSeparated` which contains a list of all options
281/// supported by the option group.
282pub trait WasmtimeOption: Sized + Send + Sync + Clone + 'static {
283    const OPTIONS: &'static [OptionDesc<Self>];
284    const ENV_PREFIX: &'static str;
285
286    /// Parse all environment variables that relate to this option, returning
287    /// all parsed variables as a list.
288    ///
289    /// Returns an error if any environment variable has invalid syntax and/or
290    /// failed to parse.
291    fn parse_env() -> Result<Vec<Self>> {
292        let mut ret = Vec::new();
293        if let Some(val) = std::env::var_os(Self::ENV_PREFIX) {
294            let val = match val.to_str() {
295                Some(s) => s,
296                None => bail!("env var `{}` is not valid UTF-8", Self::ENV_PREFIX),
297            };
298            ret.extend(
299                Self::parse_csv(&val)
300                    .with_context(|| format!("failed to parse env var `{}`", Self::ENV_PREFIX))?,
301            );
302        }
303
304        for option in Self::OPTIONS {
305            let key = match &option.name {
306                OptName::Name(s) => format!("{}_{}", Self::ENV_PREFIX, s.to_ascii_uppercase()),
307                OptName::Prefix(_) => continue,
308            };
309            let val = match std::env::var_os(&key) {
310                Some(val) => val,
311                None => continue,
312            };
313            let val = match val.to_str() {
314                Some(s) => s,
315                None => bail!("env var `{key}` is not valid UTF-8"),
316            };
317            ret.push(
318                (option.parse)(&key, Some(val))
319                    .with_context(|| format!("failed to parse env var `{key}`"))?,
320            );
321        }
322        Ok(ret)
323    }
324
325    /// Parses `val` as a comma-separated list of values for `Self::OPTIONS`.
326    fn parse_csv(val: &str) -> Result<Vec<Self>> {
327        let mut result = Vec::new();
328        for val in val.split(',') {
329            // Split `k=v` into `k` and `v` where `v` is optional
330            let mut iter = val.splitn(2, '=');
331            let key = iter.next().unwrap();
332            let key_val = iter.next();
333
334            // Find `key` within `T::OPTIONS`
335            let option = Self::OPTIONS
336                .iter()
337                .filter_map(|d| match d.name {
338                    OptName::Name(s) => {
339                        let s = s.replace('_', "-");
340                        if s == key { Some((d, s)) } else { None }
341                    }
342                    OptName::Prefix(s) => {
343                        let name = key.strip_prefix(s)?.strip_prefix("-")?;
344                        Some((d, name.to_string()))
345                    }
346                })
347                .next();
348
349            let (desc, key) = match option {
350                Some(pair) => pair,
351                None => bail!("unknown option: {key}\n"),
352            };
353
354            result.push(
355                (desc.parse)(&key, key_val)
356                    .with_context(|| format!("failed to parse option `{val}`"))?,
357            );
358        }
359        Ok(result)
360    }
361}
362
363pub struct OptionDesc<T> {
364    pub name: OptName,
365    pub docs: &'static str,
366    pub parse: fn(&str, Option<&str>) -> Result<T>,
367    pub val_help: &'static str,
368}
369
370pub enum OptName {
371    /// A named option. Note that the `str` here uses `_` instead of `-` because
372    /// it's derived from Rust syntax.
373    Name(&'static str),
374
375    /// A prefixed option which strips the specified `name`, then `-`.
376    Prefix(&'static str),
377}
378
379impl OptName {
380    #[cfg(feature = "clap")]
381    fn display_string(&self) -> String {
382        match self {
383            OptName::Name(s) => s.replace('_', "-"),
384            OptName::Prefix(s) => format!("{s}-<KEY>"),
385        }
386    }
387}
388
389/// A helper trait for all types of options that can be parsed. This is what
390/// actually parses the `=val` in `key=val`
391pub trait WasmtimeOptionValue: Sized {
392    /// Help text for the value to be specified.
393    const VAL_HELP: &'static str;
394
395    /// Parses the provided value, if given, returning an error on failure.
396    fn parse(val: Option<&str>) -> Result<Self>;
397
398    /// Write the value to `f` that would parse to `self`.
399    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
400}
401
402impl WasmtimeOptionValue for String {
403    const VAL_HELP: &'static str = "=val";
404    fn parse(val: Option<&str>) -> Result<Self> {
405        match val {
406            Some(val) => Ok(val.to_string()),
407            None => bail!("value must be specified with `key=val` syntax"),
408        }
409    }
410
411    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
412        f.write_str(self)
413    }
414}
415
416impl WasmtimeOptionValue for PathBuf {
417    const VAL_HELP: &'static str = "=path";
418    fn parse(val: Option<&str>) -> Result<Self> {
419        match val {
420            Some(val) => Ok(PathBuf::from_str(val)?),
421            None => bail!("value must be specified with key=val syntax"),
422        }
423    }
424
425    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
426        write!(f, "{self:?}")
427    }
428}
429
430impl WasmtimeOptionValue for u32 {
431    const VAL_HELP: &'static str = "=N";
432    fn parse(val: Option<&str>) -> Result<Self> {
433        let val = String::parse(val)?.replace(IGNORED_NUMBER_CHARS, "");
434        match val.strip_prefix("0x") {
435            Some(hex) => Ok(u32::from_str_radix(hex, 16)?),
436            None => Ok(val.parse()?),
437        }
438    }
439
440    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
441        write!(f, "{self}")
442    }
443}
444
445impl WasmtimeOptionValue for NonZeroU32 {
446    const VAL_HELP: &'static str = "=N";
447
448    fn parse(val: Option<&str>) -> Result<Self> {
449        let n = <u32 as WasmtimeOptionValue>::parse(val)?;
450        NonZeroU32::new(n).ok_or_else(|| format_err!("value must be non-zero"))
451    }
452
453    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
454        write!(f, "{self}")
455    }
456}
457
458impl WasmtimeOptionValue for NonZeroUsize {
459    const VAL_HELP: &'static str = "=N";
460
461    fn parse(val: Option<&str>) -> Result<Self> {
462        let n = <usize as WasmtimeOptionValue>::parse(val)?;
463        NonZeroUsize::new(n).ok_or_else(|| format_err!("value must be non-zero"))
464    }
465
466    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
467        write!(f, "{self}")
468    }
469}
470
471impl WasmtimeOptionValue for u64 {
472    const VAL_HELP: &'static str = "=N";
473    fn parse(val: Option<&str>) -> Result<Self> {
474        let val = String::parse(val)?.replace(IGNORED_NUMBER_CHARS, "");
475        match val.strip_prefix("0x") {
476            Some(hex) => Ok(u64::from_str_radix(hex, 16)?),
477            None => Ok(val.parse()?),
478        }
479    }
480
481    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
482        write!(f, "{self}")
483    }
484}
485
486impl WasmtimeOptionValue for usize {
487    const VAL_HELP: &'static str = "=N";
488    fn parse(val: Option<&str>) -> Result<Self> {
489        let val = String::parse(val)?.replace(IGNORED_NUMBER_CHARS, "");
490        match val.strip_prefix("0x") {
491            Some(hex) => Ok(usize::from_str_radix(hex, 16)?),
492            None => Ok(val.parse()?),
493        }
494    }
495
496    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
497        write!(f, "{self}")
498    }
499}
500
501impl WasmtimeOptionValue for bool {
502    const VAL_HELP: &'static str = "[=y|n]";
503    fn parse(val: Option<&str>) -> Result<Self> {
504        match val {
505            None | Some("y") | Some("yes") | Some("true") => Ok(true),
506            Some("n") | Some("no") | Some("false") => Ok(false),
507            Some(s) => bail!("unknown boolean flag `{s}`, only yes,no,<nothing> accepted"),
508        }
509    }
510
511    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
512        if *self {
513            f.write_str("y")
514        } else {
515            f.write_str("n")
516        }
517    }
518}
519
520/// A duration parsed from CLI options, rejecting zero.
521#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
522#[cfg_attr(
523    feature = "serde",
524    derive(serde_derive::Serialize, serde_derive::Deserialize),
525    serde(try_from = "Duration", into = "Duration")
526)]
527pub struct NonzeroDuration(Duration);
528
529impl NonzeroDuration {
530    /// Returns `None` if `duration` is zero.
531    pub fn new(duration: Duration) -> Option<Self> {
532        if duration.is_zero() {
533            None
534        } else {
535            Some(Self(duration))
536        }
537    }
538}
539
540impl TryFrom<Duration> for NonzeroDuration {
541    type Error = wasmtime::Error;
542
543    fn try_from(duration: Duration) -> Result<Self> {
544        Self::new(duration).ok_or_else(|| format_err!("duration must not be zero"))
545    }
546}
547
548impl From<NonzeroDuration> for Duration {
549    fn from(duration: NonzeroDuration) -> Duration {
550        duration.0
551    }
552}
553
554impl std::ops::Deref for NonzeroDuration {
555    type Target = Duration;
556
557    fn deref(&self) -> &Duration {
558        &self.0
559    }
560}
561
562impl WasmtimeOptionValue for NonzeroDuration {
563    const VAL_HELP: &'static str = "=N|Ns|Nms|..";
564
565    fn parse(val: Option<&str>) -> Result<Self> {
566        let duration = <Duration as WasmtimeOptionValue>::parse(val)?;
567        Self::try_from(duration)
568    }
569
570    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
571        <Duration as WasmtimeOptionValue>::display(&self.0, f)
572    }
573}
574
575impl WasmtimeOptionValue for Duration {
576    const VAL_HELP: &'static str = "=N|Ns|Nms|..";
577    fn parse(val: Option<&str>) -> Result<Duration> {
578        let s = String::parse(val)?;
579        // assume an integer without a unit specified is a number of seconds ...
580        if let Ok(val) = s.parse() {
581            return Ok(Duration::from_secs(val));
582        }
583
584        if let Some(num) = s.strip_suffix("s") {
585            if let Ok(val) = num.parse() {
586                return Ok(Duration::from_secs(val));
587            }
588        }
589        if let Some(num) = s.strip_suffix("ms") {
590            if let Ok(val) = num.parse() {
591                return Ok(Duration::from_millis(val));
592            }
593        }
594        if let Some(num) = s.strip_suffix("us").or(s.strip_suffix("μs")) {
595            if let Ok(val) = num.parse() {
596                return Ok(Duration::from_micros(val));
597            }
598        }
599        if let Some(num) = s.strip_suffix("ns") {
600            if let Ok(val) = num.parse() {
601                return Ok(Duration::from_nanos(val));
602            }
603        }
604
605        bail!("failed to parse duration: {s}")
606    }
607
608    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
609        let subsec = self.subsec_nanos();
610        if subsec == 0 {
611            write!(f, "{}s", self.as_secs())
612        } else if subsec % 1_000 == 0 {
613            write!(f, "{}μs", self.as_micros())
614        } else if subsec % 1_000_000 == 0 {
615            write!(f, "{}ms", self.as_millis())
616        } else {
617            write!(f, "{}ns", self.as_nanos())
618        }
619    }
620}
621
622impl WasmtimeOptionValue for wasmtime::OptLevel {
623    const VAL_HELP: &'static str = "=0|1|2|s";
624    fn parse(val: Option<&str>) -> Result<Self> {
625        match String::parse(val)?.as_str() {
626            "0" => Ok(wasmtime::OptLevel::None),
627            "1" => Ok(wasmtime::OptLevel::Speed),
628            "2" => Ok(wasmtime::OptLevel::Speed),
629            "s" => Ok(wasmtime::OptLevel::SpeedAndSize),
630            other => bail!("unknown optimization level `{other}`, only 0,1,2,s accepted"),
631        }
632    }
633
634    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
635        match *self {
636            wasmtime::OptLevel::None => f.write_str("0"),
637            wasmtime::OptLevel::Speed => f.write_str("2"),
638            wasmtime::OptLevel::SpeedAndSize => f.write_str("s"),
639            _ => unreachable!(),
640        }
641    }
642}
643
644impl WasmtimeOptionValue for wasmtime::RegallocAlgorithm {
645    const VAL_HELP: &'static str = "=backtracking|single-pass";
646    fn parse(val: Option<&str>) -> Result<Self> {
647        match String::parse(val)?.as_str() {
648            "backtracking" => Ok(wasmtime::RegallocAlgorithm::Backtracking),
649            "single-pass" => Ok(wasmtime::RegallocAlgorithm::SinglePass),
650            other => {
651                bail!("unknown regalloc algorithm`{other}`, only backtracking,single-pass accepted")
652            }
653        }
654    }
655
656    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
657        match *self {
658            wasmtime::RegallocAlgorithm::Backtracking => f.write_str("backtracking"),
659            wasmtime::RegallocAlgorithm::SinglePass => f.write_str("single-pass"),
660            _ => unreachable!(),
661        }
662    }
663}
664
665impl WasmtimeOptionValue for wasmtime::Strategy {
666    const VAL_HELP: &'static str = "=winch|cranelift";
667    fn parse(val: Option<&str>) -> Result<Self> {
668        match String::parse(val)?.as_str() {
669            "cranelift" => Ok(wasmtime::Strategy::Cranelift),
670            "winch" => Ok(wasmtime::Strategy::Winch),
671            other => bail!("unknown compiler `{other}` only `cranelift` and `winch` accepted",),
672        }
673    }
674
675    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
676        match *self {
677            wasmtime::Strategy::Cranelift => f.write_str("cranelift"),
678            wasmtime::Strategy::Winch => f.write_str("winch"),
679            _ => unreachable!(),
680        }
681    }
682}
683
684impl WasmtimeOptionValue for wasmtime::Collector {
685    const VAL_HELP: &'static str = "=drc|null|copying";
686    fn parse(val: Option<&str>) -> Result<Self> {
687        match String::parse(val)?.as_str() {
688            "drc" => Ok(wasmtime::Collector::DeferredReferenceCounting),
689            "null" => Ok(wasmtime::Collector::Null),
690            "copying" => Ok(wasmtime::Collector::Copying),
691            other => {
692                bail!("unknown collector `{other}` only `drc`, `null`, and `copying` accepted",)
693            }
694        }
695    }
696
697    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
698        match *self {
699            wasmtime::Collector::DeferredReferenceCounting => f.write_str("drc"),
700            wasmtime::Collector::Null => f.write_str("null"),
701            wasmtime::Collector::Copying => f.write_str("copying"),
702            _ => unreachable!(),
703        }
704    }
705}
706
707impl WasmtimeOptionValue for wasmtime::Enabled {
708    const VAL_HELP: &'static str = "[=y|n|auto]";
709    fn parse(val: Option<&str>) -> Result<Self> {
710        match val {
711            None | Some("y") | Some("yes") | Some("true") => Ok(wasmtime::Enabled::Yes),
712            Some("n") | Some("no") | Some("false") => Ok(wasmtime::Enabled::No),
713            Some("auto") => Ok(wasmtime::Enabled::Auto),
714            Some(s) => bail!("unknown flag `{s}`, only yes,no,auto,<nothing> accepted"),
715        }
716    }
717
718    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
719        match *self {
720            wasmtime::Enabled::Yes => f.write_str("y"),
721            wasmtime::Enabled::No => f.write_str("n"),
722            wasmtime::Enabled::Auto => f.write_str("auto"),
723        }
724    }
725}
726
727impl WasmtimeOptionValue for wasmtime::Inlining {
728    const VAL_HELP: &'static str = "[=y|n|gc|inter-module|intrinsics]";
729    fn parse(val: Option<&str>) -> Result<Self> {
730        match val {
731            None => Ok(wasmtime::Inlining::Yes),
732            Some(val) => val.parse(),
733        }
734    }
735
736    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
737        write!(f, "{self}")
738    }
739}
740
741impl WasmtimeOptionValue for WasiNnGraph {
742    const VAL_HELP: &'static str = "=<format>::<dir>";
743    fn parse(val: Option<&str>) -> Result<Self> {
744        let val = String::parse(val)?;
745        let mut parts = val.splitn(2, "::");
746        Ok(WasiNnGraph {
747            format: parts.next().unwrap().to_string(),
748            dir: match parts.next() {
749                Some(part) => part.into(),
750                None => bail!("graph does not contain `::` separator for directory"),
751            },
752        })
753    }
754
755    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
756        write!(f, "{}::{}", self.format, self.dir)
757    }
758}
759
760impl WasmtimeOptionValue for KeyValuePair {
761    const VAL_HELP: &'static str = "=<name>=<val>";
762    fn parse(val: Option<&str>) -> Result<Self> {
763        let val = String::parse(val)?;
764        let mut parts = val.splitn(2, "=");
765        Ok(KeyValuePair {
766            key: parts.next().unwrap().to_string(),
767            value: match parts.next() {
768                Some(part) => part.into(),
769                None => "".to_string(),
770            },
771        })
772    }
773
774    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
775        f.write_str(&self.key)?;
776        if !self.value.is_empty() {
777            f.write_str("=")?;
778            f.write_str(&self.value)?;
779        }
780        Ok(())
781    }
782}
783
784impl WasmtimeOptionValue for UnsafeIntrinsicsImport {
785    const VAL_HELP: &'static str = "[=name]";
786    fn parse(val: Option<&str>) -> Result<Self> {
787        match val {
788            None => Ok(UnsafeIntrinsicsImport("unsafe-intrinsics".to_string())),
789            Some("") => bail!("the unsafe intrinsics import name cannot be empty"),
790            Some(val) => Ok(UnsafeIntrinsicsImport(val.to_string())),
791        }
792    }
793
794    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
795        f.write_str(&self.0)
796    }
797}
798
799impl WasmtimeOptionValue for CompileTimeBuiltin {
800    const VAL_HELP: &'static str = "=[<name>=]<path>";
801    fn parse(val: Option<&str>) -> Result<Self> {
802        let val = String::parse(val)?;
803
804        if let Some((name, path)) = val.split_once('=') {
805            if name.is_empty() {
806                bail!("the compile-time builtin's name cannot be empty in `{val}`");
807            }
808            if path.is_empty() {
809                bail!("the compile-time builtin's path cannot be empty in `{val}`");
810            }
811            return Ok(CompileTimeBuiltin {
812                name: name.to_string(),
813                path: PathBuf::from(path),
814            });
815        }
816
817        // No `<name>` was given: derive it from the file name of `<path>`, with
818        // its extension removed.
819        let path = PathBuf::from(&val);
820        let name = path
821            .file_stem()
822            .ok_or_else(|| format_err!("cannot derive a compile-time builtin name from `{val}`"))?
823            .to_str()
824            .ok_or_else(|| {
825                format_err!("compile-time builtin name derived from `{val}` is not valid UTF-8")
826            })?
827            .to_string();
828        if name.is_empty() {
829            bail!("compile-time builtin name derived from `{val}` is empty");
830        }
831        Ok(CompileTimeBuiltin { name, path })
832    }
833
834    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
835        // Always write the canonical `<name>=<path>` form so that this
836        // round-trips back through `parse` regardless of the file name.
837        write!(f, "{}={}", self.name, Path::display(&self.path))
838    }
839}
840
841pub trait OptionContainer<T> {
842    fn push(&mut self, val: T);
843    fn get<'a>(&'a self) -> impl Iterator<Item = &'a T>
844    where
845        T: 'a;
846}
847
848impl<T> OptionContainer<T> for Option<T> {
849    fn push(&mut self, val: T) {
850        *self = Some(val);
851    }
852    fn get<'a>(&'a self) -> impl Iterator<Item = &'a T>
853    where
854        T: 'a,
855    {
856        self.iter()
857    }
858}
859
860impl<T> OptionContainer<T> for Vec<T> {
861    fn push(&mut self, val: T) {
862        Vec::push(self, val);
863    }
864    fn get<'a>(&'a self) -> impl Iterator<Item = &'a T>
865    where
866        T: 'a,
867    {
868        self.iter()
869    }
870}
871
872// Used to parse toml values into string so that we can reuse the `WasmtimeOptionValue::parse`
873// for parsing toml values the same way we parse command line values.
874//
875// Used for wasmtime::Strategy, wasmtime::Collector, wasmtime::OptLevel, wasmtime::RegallocAlgorithm
876#[cfg(feature = "serde")]
877struct ToStringVisitor {}
878
879#[cfg(feature = "serde")]
880impl<'de> Visitor<'de> for ToStringVisitor {
881    type Value = String;
882
883    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
884        write!(formatter, "&str, u64, or i64")
885    }
886
887    fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
888    where
889        E: de::Error,
890    {
891        Ok(s.to_owned())
892    }
893
894    fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
895    where
896        E: de::Error,
897    {
898        Ok(v.to_string())
899    }
900
901    fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
902    where
903        E: de::Error,
904    {
905        Ok(v.to_string())
906    }
907}
908
909// Deserializer that uses the `WasmtimeOptionValue::parse` to parse toml values
910#[cfg(feature = "serde")]
911pub(crate) fn deserialize_cli_parse_wrapper<'de, D, T>(
912    deserializer: D,
913) -> Result<Option<T>, D::Error>
914where
915    T: WasmtimeOptionValue,
916    D: serde::Deserializer<'de>,
917{
918    let to_string_visitor = ToStringVisitor {};
919    let str = deserializer.deserialize_any(to_string_visitor)?;
920
921    T::parse(Some(&str))
922        .map(Some)
923        .map_err(serde::de::Error::custom)
924}
925
926#[cfg(feature = "serde")]
927pub(crate) fn serialize_cli_parse_wrapper<S, T>(val: &Option<T>, ser: S) -> Result<S::Ok, S::Error>
928where
929    T: WasmtimeOptionValue,
930    S: serde::Serializer,
931{
932    match val {
933        Some(val) => ser.serialize_some(&fmt::from_fn(|f| val.display(f)).to_string()),
934        None => ser.serialize_none(),
935    }
936}
937
938#[cfg(test)]
939mod tests {
940    use super::{NonzeroDuration, WasmtimeOptionValue};
941    use std::time::Duration;
942
943    #[test]
944    fn numbers_with_underscores() {
945        assert!(<u32 as WasmtimeOptionValue>::parse(Some("123")).is_ok_and(|v| v == 123));
946        assert!(<u32 as WasmtimeOptionValue>::parse(Some("1_2_3")).is_ok_and(|v| v == 123));
947    }
948
949    #[test]
950    fn nonzero_durations() {
951        for (input, expected) in [
952            ("0", None),
953            ("0s", None),
954            ("0ms", None),
955            ("0us", None),
956            ("0ns", None),
957            ("1", Some(Duration::from_secs(1))),
958            ("1s", Some(Duration::from_secs(1))),
959            ("1ms", Some(Duration::from_millis(1))),
960            ("1us", Some(Duration::from_micros(1))),
961            ("1ns", Some(Duration::from_nanos(1))),
962        ] {
963            let actual = <NonzeroDuration as WasmtimeOptionValue>::parse(Some(input))
964                .ok()
965                .map(|d| *d);
966            assert_eq!(actual, expected, "input = {input}");
967        }
968    }
969}