Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

31.1 KB
Raw Blame
//! Support for parsing Wasmtime's `-O`, `-W`, etc "option groups"
//!
//! This builds up a clap-derive-like system where there's ideally a single
//! macro `wasmtime_option_group!` which is invoked per-option which enables
//! specifying options in a struct-like syntax where all other boilerplate about
//! option parsing is contained exclusively within this module.

use crate::{CompileTimeBuiltin, KeyValuePair, UnsafeIntrinsicsImport, WasiNnGraph};
#[cfg(feature = "clap")]
use clap::builder::{StringValueParser, TypedValueParser, ValueParserFactory};
#[cfg(feature = "clap")]
use clap::error::{Error, ErrorKind};
#[cfg(feature = "serde")]
use serde::de::{self, Visitor};
use std::fmt;
use std::num::{NonZeroU32, NonZeroUsize};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::Duration;
use wasmtime::error::Context;
use wasmtime::{Result, bail, format_err};

/// Characters which can be safely ignored while parsing numeric options to wasmtime
const IGNORED_NUMBER_CHARS: [char; 1] = ['_'];

#[macro_export]
macro_rules! wasmtime_option_group {
    (
        #[env = $env:tt]
        $(#[$attr:meta])*
        pub struct $opts:ident {
            $(
                $(#[doc = $doc:tt])*
                $(#[doc($doc_attr:meta)])?
                $(#[serde($serde_attr:meta)])*
                pub $opt:ident: $container:ident<$payload:ty>,
            )+

            $(
                #[prefixed = $prefix:tt]
                $(#[serde($serde_attr2:meta)])*
                $(#[doc = $prefixed_doc:tt])*
                $(#[doc($prefixed_doc_attr:meta)])?
                pub $prefixed:ident: Vec<(String, Option<String>)>,
            )?
        }
        enum $option:ident {
            ...
        }
    ) => {
        #[derive(Default, Debug, PartialEq, Clone)]
        #[cfg_attr(feature = "serde", derive(serde_derive::Deserialize, serde_derive::Serialize))]
        #[cfg_attr(feature = "serde", serde(rename_all = "kebab-case", deny_unknown_fields))]
        $(#[$attr])*
        pub struct $opts {
            $(
                $(#[cfg_attr(feature = "serde", serde($serde_attr))])*
                $(#[doc($doc_attr)])?
                pub $opt: $container<$payload>,
            )+
            $(
                $(#[cfg_attr(feature = "serde", serde($serde_attr2))])*
                pub $prefixed: Vec<(String, Option<String>)>,
            )?
        }

        #[derive(Clone, PartialEq)]
        #[expect(non_camel_case_types, reason = "macro-generated code")]
        enum $option {
            $(
                $opt($payload),
            )+
            $(
                $prefixed(String, Option<String>),
            )?
        }

        impl $crate::opt::WasmtimeOption for $option {
            const ENV_PREFIX: &'static str = concat!("WASMTIME_", $env);
            const OPTIONS: &'static [$crate::opt::OptionDesc<$option>] = &[
                $(
                    $crate::opt::OptionDesc {
                        name: $crate::opt::OptName::Name(stringify!($opt)),
                        parse: |_, s| {
                            Ok($option::$opt(
                                $crate::opt::WasmtimeOptionValue::parse(s)?
                            ))
                        },
                        val_help: <$payload as $crate::opt::WasmtimeOptionValue>::VAL_HELP,
                        docs: concat!($($doc, "\n",)*),
                    },
                 )+
                $(
                    $crate::opt::OptionDesc {
                        name: $crate::opt::OptName::Prefix($prefix),
                        parse: |name, val| {
                            Ok($option::$prefixed(
                                name.to_string(),
                                val.map(|v| v.to_string()),
                            ))
                        },
                        val_help: "[=val]",
                        docs: concat!($($prefixed_doc, "\n",)*),
                    },
                 )?
            ];
        }

        impl core::fmt::Display for $option {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                match self {
                    $(
                        $option::$opt(val) => {
                            write!(f, "{}=", stringify!($opt).replace('_', "-"))?;
                            $crate::opt::WasmtimeOptionValue::display(val, f)
                        }
                    )+
                    $(
                        $option::$prefixed(key, val) => {
                            write!(f, "{}-{key}", stringify!($prefixed))?;
                            if let Some(val) = val {
                                write!(f, "={val}")?;
                            }
                            Ok(())
                        }
                    )?
                }
            }
        }

        impl $opts {
            fn configure_with(
                &mut self,
                opts: &[$crate::opt::CommaSeparated<$option>],
                env: bool,
            ) -> Result<()> {
                let env_opts = if env {
                    <$option as $crate::opt::WasmtimeOption>::parse_env()?
                } else {
                    Vec::new()
                };
                for opt in env_opts.iter().chain(opts.iter().flat_map(|o| o.0.iter())) {
                    self.configure(opt);
                }
                Ok(())
            }

            fn configure(&mut self, opt: &$option) {
                match opt {
                    $(
                        $option::$opt(val) => {
                            $crate::opt::OptionContainer::push(&mut self.$opt, val.clone());
                        }
                    )+
                    $(
                        $option::$prefixed(key, val) => self.$prefixed.push((key.clone(), val.clone())),
                    )?
                }
            }

            fn to_options(&self) -> Vec<$option> {
                let mut ret = Vec::new();
                $(
                    for item in $crate::opt::OptionContainer::get(&self.$opt) {
                        ret.push($option::$opt(item.clone()));
                    }
                )+
                $(
                    for (key,val) in self.$prefixed.iter() {
                        ret.push($option::$prefixed(key.clone(), val.clone()));
                    }
                )?
                ret
            }
        }
    };
}

/// Parser registered with clap which handles parsing the `...` in `-O ...`.
#[derive(Clone, Debug, PartialEq)]
pub struct CommaSeparated<T>(pub Vec<T>);

#[cfg(feature = "clap")]
impl<T> ValueParserFactory for CommaSeparated<T>
where
    T: WasmtimeOption,
{
    type Parser = CommaSeparatedParser<T>;

    fn value_parser() -> CommaSeparatedParser<T> {
        CommaSeparatedParser(std::marker::PhantomData)
    }
}

#[derive(Clone)]
#[cfg(feature = "clap")]
pub struct CommaSeparatedParser<T>(std::marker::PhantomData<T>);

#[cfg(feature = "clap")]
impl<T> TypedValueParser for CommaSeparatedParser<T>
where
    T: WasmtimeOption,
{
    type Value = CommaSeparated<T>;

    fn parse_ref(
        &self,
        cmd: &clap::Command,
        arg: Option<&clap::Arg>,
        value: &std::ffi::OsStr,
    ) -> Result<Self::Value, Error> {
        let val = StringValueParser::new().parse_ref(cmd, arg, value)?;

        let options = T::OPTIONS;
        let arg = arg.expect("should always have an argument");
        let arg_long = arg.get_long().expect("should have a long name specified");
        let arg_short = arg.get_short().expect("should have a short name specified");

        // Handle `-O help` which dumps all the `-O` options, their messages,
        // and then exits.
        if val == "help" {
            let mut max = 0;
            for d in options {
                max = max.max(d.name.display_string().len() + d.val_help.len());
            }
            println!("Available {arg_long} options:\n");
            for d in options {
                print!(
                    "  -{arg_short} {:>1$}",
                    d.name.display_string(),
                    max - d.val_help.len()
                );
                print!("{}", d.val_help);
                print!(" --");
                if val == "help" {
                    for line in d.docs.lines().map(|s| s.trim()) {
                        if line.is_empty() {
                            break;
                        }
                        print!(" {line}");
                    }
                    println!();
                } else {
                    println!();
                    for line in d.docs.lines().map(|s| s.trim()) {
                        let line = line.trim();
                        println!("        {line}");
                    }
                }
            }
            println!("\npass `-{arg_short} help-long` to see longer-form explanations");
            std::process::exit(0);
        }
        if val == "help-long" {
            println!("Available {arg_long} options:\n");
            for d in options {
                println!(
                    "  -{arg_short} {}{} --",
                    d.name.display_string(),
                    d.val_help
                );
                println!();
                for line in d.docs.lines().map(|s| s.trim()) {
                    let line = line.trim();
                    println!("        {line}");
                }
            }
            std::process::exit(0);
        }

        T::parse_csv(&val).map(CommaSeparated).map_err(|e| {
            Error::raw(
                ErrorKind::InvalidValue,
                format!("failed to parse -{arg_short} / --{arg_long} option: {e:?}\n"),
            )
        })
    }
}

/// Helper trait used by `CommaSeparated` which contains a list of all options
/// supported by the option group.
pub trait WasmtimeOption: Sized + Send + Sync + Clone + 'static {
    const OPTIONS: &'static [OptionDesc<Self>];
    const ENV_PREFIX: &'static str;

    /// Parse all environment variables that relate to this option, returning
    /// all parsed variables as a list.
    ///
    /// Returns an error if any environment variable has invalid syntax and/or
    /// failed to parse.
    fn parse_env() -> Result<Vec<Self>> {
        let mut ret = Vec::new();
        if let Some(val) = std::env::var_os(Self::ENV_PREFIX) {
            let val = match val.to_str() {
                Some(s) => s,
                None => bail!("env var `{}` is not valid UTF-8", Self::ENV_PREFIX),
            };
            ret.extend(
                Self::parse_csv(&val)
                    .with_context(|| format!("failed to parse env var `{}`", Self::ENV_PREFIX))?,
            );
        }

        for option in Self::OPTIONS {
            let key = match &option.name {
                OptName::Name(s) => format!("{}_{}", Self::ENV_PREFIX, s.to_ascii_uppercase()),
                OptName::Prefix(_) => continue,
            };
            let val = match std::env::var_os(&key) {
                Some(val) => val,
                None => continue,
            };
            let val = match val.to_str() {
                Some(s) => s,
                None => bail!("env var `{key}` is not valid UTF-8"),
            };
            ret.push(
                (option.parse)(&key, Some(val))
                    .with_context(|| format!("failed to parse env var `{key}`"))?,
            );
        }
        Ok(ret)
    }

    /// Parses `val` as a comma-separated list of values for `Self::OPTIONS`.
    fn parse_csv(val: &str) -> Result<Vec<Self>> {
        let mut result = Vec::new();
        for val in val.split(',') {
            // Split `k=v` into `k` and `v` where `v` is optional
            let mut iter = val.splitn(2, '=');
            let key = iter.next().unwrap();
            let key_val = iter.next();

            // Find `key` within `T::OPTIONS`
            let option = Self::OPTIONS
                .iter()
                .filter_map(|d| match d.name {
                    OptName::Name(s) => {
                        let s = s.replace('_', "-");
                        if s == key { Some((d, s)) } else { None }
                    }
                    OptName::Prefix(s) => {
                        let name = key.strip_prefix(s)?.strip_prefix("-")?;
                        Some((d, name.to_string()))
                    }
                })
                .next();

            let (desc, key) = match option {
                Some(pair) => pair,
                None => bail!("unknown option: {key}\n"),
            };

            result.push(
                (desc.parse)(&key, key_val)
                    .with_context(|| format!("failed to parse option `{val}`"))?,
            );
        }
        Ok(result)
    }
}

pub struct OptionDesc<T> {
    pub name: OptName,
    pub docs: &'static str,
    pub parse: fn(&str, Option<&str>) -> Result<T>,
    pub val_help: &'static str,
}

pub enum OptName {
    /// A named option. Note that the `str` here uses `_` instead of `-` because
    /// it's derived from Rust syntax.
    Name(&'static str),

    /// A prefixed option which strips the specified `name`, then `-`.
    Prefix(&'static str),
}

impl OptName {
    #[cfg(feature = "clap")]
    fn display_string(&self) -> String {
        match self {
            OptName::Name(s) => s.replace('_', "-"),
            OptName::Prefix(s) => format!("{s}-<KEY>"),
        }
    }
}

/// A helper trait for all types of options that can be parsed. This is what
/// actually parses the `=val` in `key=val`
pub trait WasmtimeOptionValue: Sized {
    /// Help text for the value to be specified.
    const VAL_HELP: &'static str;

    /// Parses the provided value, if given, returning an error on failure.
    fn parse(val: Option<&str>) -> Result<Self>;

    /// Write the value to `f` that would parse to `self`.
    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
}

impl WasmtimeOptionValue for String {
    const VAL_HELP: &'static str = "=val";
    fn parse(val: Option<&str>) -> Result<Self> {
        match val {
            Some(val) => Ok(val.to_string()),
            None => bail!("value must be specified with `key=val` syntax"),
        }
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self)
    }
}

impl WasmtimeOptionValue for PathBuf {
    const VAL_HELP: &'static str = "=path";
    fn parse(val: Option<&str>) -> Result<Self> {
        match val {
            Some(val) => Ok(PathBuf::from_str(val)?),
            None => bail!("value must be specified with key=val syntax"),
        }
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self:?}")
    }
}

impl WasmtimeOptionValue for u32 {
    const VAL_HELP: &'static str = "=N";
    fn parse(val: Option<&str>) -> Result<Self> {
        let val = String::parse(val)?.replace(IGNORED_NUMBER_CHARS, "");
        match val.strip_prefix("0x") {
            Some(hex) => Ok(u32::from_str_radix(hex, 16)?),
            None => Ok(val.parse()?),
        }
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self}")
    }
}

impl WasmtimeOptionValue for NonZeroU32 {
    const VAL_HELP: &'static str = "=N";

    fn parse(val: Option<&str>) -> Result<Self> {
        let n = <u32 as WasmtimeOptionValue>::parse(val)?;
        NonZeroU32::new(n).ok_or_else(|| format_err!("value must be non-zero"))
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self}")
    }
}

impl WasmtimeOptionValue for NonZeroUsize {
    const VAL_HELP: &'static str = "=N";

    fn parse(val: Option<&str>) -> Result<Self> {
        let n = <usize as WasmtimeOptionValue>::parse(val)?;
        NonZeroUsize::new(n).ok_or_else(|| format_err!("value must be non-zero"))
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self}")
    }
}

impl WasmtimeOptionValue for u64 {
    const VAL_HELP: &'static str = "=N";
    fn parse(val: Option<&str>) -> Result<Self> {
        let val = String::parse(val)?.replace(IGNORED_NUMBER_CHARS, "");
        match val.strip_prefix("0x") {
            Some(hex) => Ok(u64::from_str_radix(hex, 16)?),
            None => Ok(val.parse()?),
        }
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self}")
    }
}

impl WasmtimeOptionValue for usize {
    const VAL_HELP: &'static str = "=N";
    fn parse(val: Option<&str>) -> Result<Self> {
        let val = String::parse(val)?.replace(IGNORED_NUMBER_CHARS, "");
        match val.strip_prefix("0x") {
            Some(hex) => Ok(usize::from_str_radix(hex, 16)?),
            None => Ok(val.parse()?),
        }
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self}")
    }
}

impl WasmtimeOptionValue for bool {
    const VAL_HELP: &'static str = "[=y|n]";
    fn parse(val: Option<&str>) -> Result<Self> {
        match val {
            None | Some("y") | Some("yes") | Some("true") => Ok(true),
            Some("n") | Some("no") | Some("false") => Ok(false),
            Some(s) => bail!("unknown boolean flag `{s}`, only yes,no,<nothing> accepted"),
        }
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if *self {
            f.write_str("y")
        } else {
            f.write_str("n")
        }
    }
}

/// A duration parsed from CLI options, rejecting zero.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(
    feature = "serde",
    derive(serde_derive::Serialize, serde_derive::Deserialize),
    serde(try_from = "Duration", into = "Duration")
)]
pub struct NonzeroDuration(Duration);

impl NonzeroDuration {
    /// Returns `None` if `duration` is zero.
    pub fn new(duration: Duration) -> Option<Self> {
        if duration.is_zero() {
            None
        } else {
            Some(Self(duration))
        }
    }
}

impl TryFrom<Duration> for NonzeroDuration {
    type Error = wasmtime::Error;

    fn try_from(duration: Duration) -> Result<Self> {
        Self::new(duration).ok_or_else(|| format_err!("duration must not be zero"))
    }
}

impl From<NonzeroDuration> for Duration {
    fn from(duration: NonzeroDuration) -> Duration {
        duration.0
    }
}

impl std::ops::Deref for NonzeroDuration {
    type Target = Duration;

    fn deref(&self) -> &Duration {
        &self.0
    }
}

impl WasmtimeOptionValue for NonzeroDuration {
    const VAL_HELP: &'static str = "=N|Ns|Nms|..";

    fn parse(val: Option<&str>) -> Result<Self> {
        let duration = <Duration as WasmtimeOptionValue>::parse(val)?;
        Self::try_from(duration)
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        <Duration as WasmtimeOptionValue>::display(&self.0, f)
    }
}

impl WasmtimeOptionValue for Duration {
    const VAL_HELP: &'static str = "=N|Ns|Nms|..";
    fn parse(val: Option<&str>) -> Result<Duration> {
        let s = String::parse(val)?;
        // assume an integer without a unit specified is a number of seconds ...
        if let Ok(val) = s.parse() {
            return Ok(Duration::from_secs(val));
        }

        if let Some(num) = s.strip_suffix("s") {
            if let Ok(val) = num.parse() {
                return Ok(Duration::from_secs(val));
            }
        }
        if let Some(num) = s.strip_suffix("ms") {
            if let Ok(val) = num.parse() {
                return Ok(Duration::from_millis(val));
            }
        }
        if let Some(num) = s.strip_suffix("us").or(s.strip_suffix("μs")) {
            if let Ok(val) = num.parse() {
                return Ok(Duration::from_micros(val));
            }
        }
        if let Some(num) = s.strip_suffix("ns") {
            if let Ok(val) = num.parse() {
                return Ok(Duration::from_nanos(val));
            }
        }

        bail!("failed to parse duration: {s}")
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let subsec = self.subsec_nanos();
        if subsec == 0 {
            write!(f, "{}s", self.as_secs())
        } else if subsec % 1_000 == 0 {
            write!(f, "{}μs", self.as_micros())
        } else if subsec % 1_000_000 == 0 {
            write!(f, "{}ms", self.as_millis())
        } else {
            write!(f, "{}ns", self.as_nanos())
        }
    }
}

impl WasmtimeOptionValue for wasmtime::OptLevel {
    const VAL_HELP: &'static str = "=0|1|2|s";
    fn parse(val: Option<&str>) -> Result<Self> {
        match String::parse(val)?.as_str() {
            "0" => Ok(wasmtime::OptLevel::None),
            "1" => Ok(wasmtime::OptLevel::Speed),
            "2" => Ok(wasmtime::OptLevel::Speed),
            "s" => Ok(wasmtime::OptLevel::SpeedAndSize),
            other => bail!("unknown optimization level `{other}`, only 0,1,2,s accepted"),
        }
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            wasmtime::OptLevel::None => f.write_str("0"),
            wasmtime::OptLevel::Speed => f.write_str("2"),
            wasmtime::OptLevel::SpeedAndSize => f.write_str("s"),
            _ => unreachable!(),
        }
    }
}

impl WasmtimeOptionValue for wasmtime::RegallocAlgorithm {
    const VAL_HELP: &'static str = "=backtracking|single-pass";
    fn parse(val: Option<&str>) -> Result<Self> {
        match String::parse(val)?.as_str() {
            "backtracking" => Ok(wasmtime::RegallocAlgorithm::Backtracking),
            "single-pass" => Ok(wasmtime::RegallocAlgorithm::SinglePass),
            other => {
                bail!("unknown regalloc algorithm`{other}`, only backtracking,single-pass accepted")
            }
        }
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            wasmtime::RegallocAlgorithm::Backtracking => f.write_str("backtracking"),
            wasmtime::RegallocAlgorithm::SinglePass => f.write_str("single-pass"),
            _ => unreachable!(),
        }
    }
}

impl WasmtimeOptionValue for wasmtime::Strategy {
    const VAL_HELP: &'static str = "=winch|cranelift";
    fn parse(val: Option<&str>) -> Result<Self> {
        match String::parse(val)?.as_str() {
            "cranelift" => Ok(wasmtime::Strategy::Cranelift),
            "winch" => Ok(wasmtime::Strategy::Winch),
            other => bail!("unknown compiler `{other}` only `cranelift` and `winch` accepted",),
        }
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            wasmtime::Strategy::Cranelift => f.write_str("cranelift"),
            wasmtime::Strategy::Winch => f.write_str("winch"),
            _ => unreachable!(),
        }
    }
}

impl WasmtimeOptionValue for wasmtime::Collector {
    const VAL_HELP: &'static str = "=drc|null|copying";
    fn parse(val: Option<&str>) -> Result<Self> {
        match String::parse(val)?.as_str() {
            "drc" => Ok(wasmtime::Collector::DeferredReferenceCounting),
            "null" => Ok(wasmtime::Collector::Null),
            "copying" => Ok(wasmtime::Collector::Copying),
            other => {
                bail!("unknown collector `{other}` only `drc`, `null`, and `copying` accepted",)
            }
        }
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            wasmtime::Collector::DeferredReferenceCounting => f.write_str("drc"),
            wasmtime::Collector::Null => f.write_str("null"),
            wasmtime::Collector::Copying => f.write_str("copying"),
            _ => unreachable!(),
        }
    }
}

impl WasmtimeOptionValue for wasmtime::Enabled {
    const VAL_HELP: &'static str = "[=y|n|auto]";
    fn parse(val: Option<&str>) -> Result<Self> {
        match val {
            None | Some("y") | Some("yes") | Some("true") => Ok(wasmtime::Enabled::Yes),
            Some("n") | Some("no") | Some("false") => Ok(wasmtime::Enabled::No),
            Some("auto") => Ok(wasmtime::Enabled::Auto),
            Some(s) => bail!("unknown flag `{s}`, only yes,no,auto,<nothing> accepted"),
        }
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            wasmtime::Enabled::Yes => f.write_str("y"),
            wasmtime::Enabled::No => f.write_str("n"),
            wasmtime::Enabled::Auto => f.write_str("auto"),
        }
    }
}

impl WasmtimeOptionValue for wasmtime::Inlining {
    const VAL_HELP: &'static str = "[=y|n|gc|inter-module|intrinsics]";
    fn parse(val: Option<&str>) -> Result<Self> {
        match val {
            None => Ok(wasmtime::Inlining::Yes),
            Some(val) => val.parse(),
        }
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self}")
    }
}

impl WasmtimeOptionValue for WasiNnGraph {
    const VAL_HELP: &'static str = "=<format>::<dir>";
    fn parse(val: Option<&str>) -> Result<Self> {
        let val = String::parse(val)?;
        let mut parts = val.splitn(2, "::");
        Ok(WasiNnGraph {
            format: parts.next().unwrap().to_string(),
            dir: match parts.next() {
                Some(part) => part.into(),
                None => bail!("graph does not contain `::` separator for directory"),
            },
        })
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}::{}", self.format, self.dir)
    }
}

impl WasmtimeOptionValue for KeyValuePair {
    const VAL_HELP: &'static str = "=<name>=<val>";
    fn parse(val: Option<&str>) -> Result<Self> {
        let val = String::parse(val)?;
        let mut parts = val.splitn(2, "=");
        Ok(KeyValuePair {
            key: parts.next().unwrap().to_string(),
            value: match parts.next() {
                Some(part) => part.into(),
                None => "".to_string(),
            },
        })
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.key)?;
        if !self.value.is_empty() {
            f.write_str("=")?;
            f.write_str(&self.value)?;
        }
        Ok(())
    }
}

impl WasmtimeOptionValue for UnsafeIntrinsicsImport {
    const VAL_HELP: &'static str = "[=name]";
    fn parse(val: Option<&str>) -> Result<Self> {
        match val {
            None => Ok(UnsafeIntrinsicsImport("unsafe-intrinsics".to_string())),
            Some("") => bail!("the unsafe intrinsics import name cannot be empty"),
            Some(val) => Ok(UnsafeIntrinsicsImport(val.to_string())),
        }
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl WasmtimeOptionValue for CompileTimeBuiltin {
    const VAL_HELP: &'static str = "=[<name>=]<path>";
    fn parse(val: Option<&str>) -> Result<Self> {
        let val = String::parse(val)?;

        if let Some((name, path)) = val.split_once('=') {
            if name.is_empty() {
                bail!("the compile-time builtin's name cannot be empty in `{val}`");
            }
            if path.is_empty() {
                bail!("the compile-time builtin's path cannot be empty in `{val}`");
            }
            return Ok(CompileTimeBuiltin {
                name: name.to_string(),
                path: PathBuf::from(path),
            });
        }

        // No `<name>` was given: derive it from the file name of `<path>`, with
        // its extension removed.
        let path = PathBuf::from(&val);
        let name = path
            .file_stem()
            .ok_or_else(|| format_err!("cannot derive a compile-time builtin name from `{val}`"))?
            .to_str()
            .ok_or_else(|| {
                format_err!("compile-time builtin name derived from `{val}` is not valid UTF-8")
            })?
            .to_string();
        if name.is_empty() {
            bail!("compile-time builtin name derived from `{val}` is empty");
        }
        Ok(CompileTimeBuiltin { name, path })
    }

    fn display(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Always write the canonical `<name>=<path>` form so that this
        // round-trips back through `parse` regardless of the file name.
        write!(f, "{}={}", self.name, Path::display(&self.path))
    }
}

pub trait OptionContainer<T> {
    fn push(&mut self, val: T);
    fn get<'a>(&'a self) -> impl Iterator<Item = &'a T>
    where
        T: 'a;
}

impl<T> OptionContainer<T> for Option<T> {
    fn push(&mut self, val: T) {
        *self = Some(val);
    }
    fn get<'a>(&'a self) -> impl Iterator<Item = &'a T>
    where
        T: 'a,
    {
        self.iter()
    }
}

impl<T> OptionContainer<T> for Vec<T> {
    fn push(&mut self, val: T) {
        Vec::push(self, val);
    }
    fn get<'a>(&'a self) -> impl Iterator<Item = &'a T>
    where
        T: 'a,
    {
        self.iter()
    }
}

// Used to parse toml values into string so that we can reuse the `WasmtimeOptionValue::parse`
// for parsing toml values the same way we parse command line values.
//
// Used for wasmtime::Strategy, wasmtime::Collector, wasmtime::OptLevel, wasmtime::RegallocAlgorithm
#[cfg(feature = "serde")]
struct ToStringVisitor {}

#[cfg(feature = "serde")]
impl<'de> Visitor<'de> for ToStringVisitor {
    type Value = String;

    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(formatter, "&str, u64, or i64")
    }

    fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
        Ok(s.to_owned())
    }

    fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
        Ok(v.to_string())
    }

    fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
    where
        E: de::Error,
    {
        Ok(v.to_string())
    }
}

// Deserializer that uses the `WasmtimeOptionValue::parse` to parse toml values
#[cfg(feature = "serde")]
pub(crate) fn deserialize_cli_parse_wrapper<'de, D, T>(
    deserializer: D,
) -> Result<Option<T>, D::Error>
where
    T: WasmtimeOptionValue,
    D: serde::Deserializer<'de>,
{
    let to_string_visitor = ToStringVisitor {};
    let str = deserializer.deserialize_any(to_string_visitor)?;

    T::parse(Some(&str))
        .map(Some)
        .map_err(serde::de::Error::custom)
}

#[cfg(feature = "serde")]
pub(crate) fn serialize_cli_parse_wrapper<S, T>(val: &Option<T>, ser: S) -> Result<S::Ok, S::Error>
where
    T: WasmtimeOptionValue,
    S: serde::Serializer,
{
    match val {
        Some(val) => ser.serialize_some(&fmt::from_fn(|f| val.display(f)).to_string()),
        None => ser.serialize_none(),
    }
}

#[cfg(test)]
mod tests {
    use super::{NonzeroDuration, WasmtimeOptionValue};
    use std::time::Duration;

    #[test]
    fn numbers_with_underscores() {
        assert!(<u32 as WasmtimeOptionValue>::parse(Some("123")).is_ok_and(|v| v == 123));
        assert!(<u32 as WasmtimeOptionValue>::parse(Some("1_2_3")).is_ok_and(|v| v == 123));
    }

    #[test]
    fn nonzero_durations() {
        for (input, expected) in [
            ("0", None),
            ("0s", None),
            ("0ms", None),
            ("0us", None),
            ("0ns", None),
            ("1", Some(Duration::from_secs(1))),
            ("1s", Some(Duration::from_secs(1))),
            ("1ms", Some(Duration::from_millis(1))),
            ("1us", Some(Duration::from_micros(1))),
            ("1ns", Some(Duration::from_nanos(1))),
        ] {
            let actual = <NonzeroDuration as WasmtimeOptionValue>::parse(Some(input))
                .ok()
                .map(|d| *d);
            assert_eq!(actual, expected, "input = {input}");
        }
    }
}