xur-runtime 0.1.8

Values, native-function registry and facet conversions for the Xur language
Documentation
//! Traits for converting between Rust types and Xur [`Value`]s.
//!
//! [`FromValue`] and [`IntoXurValue`] decouple the typed function API
//! from [`Facet`]: any type that implements `Facet` automatically gets
//! both traits via blanket impls, while types like `Value`, `XurList`
//! and `XurBytes` provide their own custom conversions.

mod dynamic;
mod type_desc;
mod wrappers;

use facet::{Facet, Shape};

use crate::RunResult;
use crate::RuntimeError;
use crate::Value;
use crate::convert::{self, ConvertCx};

pub use dynamic::{Describe, Dyn, desc};
pub use type_desc::TypeDesc;
pub use wrappers::{XurBytes, XurList, XurPtr, XurStr};

/// Extract a Rust value from a Xur [`Value`].
pub trait FromValue: Sized + Send + 'static {
    const SHAPE: Option<&'static Shape> = None;
    /// The type as people should see it (docs, hovers).
    fn type_desc() -> TypeDesc {
        TypeDesc::of_shape(Self::SHAPE)
    }
    fn from_value(cx: &dyn ConvertCx, value: &Value) -> RunResult<Self>;
}

/// Convert a Rust value into a Xur [`Value`].
pub trait IntoXurValue: Send + 'static {
    const SHAPE: Option<&'static Shape> = None;
    /// The type as people should see it (docs, hovers).
    fn type_desc() -> TypeDesc {
        TypeDesc::of_shape(Self::SHAPE)
    }
    fn into_xur_value(self, cx: &dyn ConvertCx) -> RunResult<Value>;
}

impl<T: Facet<'static> + Send + 'static> FromValue for T {
    const SHAPE: Option<&'static Shape> = Some(T::SHAPE);
    fn from_value(cx: &dyn ConvertCx, value: &Value) -> RunResult<Self> {
        convert::from_value::<T>(cx, value)
    }
}

impl<T: Facet<'static> + Send + 'static> IntoXurValue for T {
    const SHAPE: Option<&'static Shape> = Some(T::SHAPE);
    fn into_xur_value(self, cx: &dyn ConvertCx) -> RunResult<Value> {
        convert::into_value(cx, self)
    }
}

impl FromValue for Value {
    fn type_desc() -> TypeDesc {
        TypeDesc::ANY
    }
    fn from_value(_cx: &dyn ConvertCx, value: &Value) -> RunResult<Self> {
        Ok(value.clone())
    }
}

impl IntoXurValue for Value {
    fn type_desc() -> TypeDesc {
        TypeDesc::ANY
    }
    fn into_xur_value(self, _cx: &dyn ConvertCx) -> RunResult<Value> {
        Ok(self)
    }
}

/// How a positional argument is produced from the call's values, including
/// whether it may be absent. Every [`FromValue`] type is a *required* argument
/// via the blanket impl; [`OptionalArg`] overrides it to allow a missing
/// trailing argument. The typed-function machinery binds each parameter through
/// this trait.
pub trait FromArg: Sized + Send + 'static {
    const SHAPE: Option<&'static Shape> = None;
    /// Whether the caller must supply this argument.
    const REQUIRED: bool = true;
    /// The parameter's type as people should see it (docs, hovers).
    fn type_desc() -> TypeDesc {
        TypeDesc::of_shape(Self::SHAPE)
    }
    fn from_arg(cx: &dyn ConvertCx, value: Option<&Value>) -> RunResult<Self>;
}

impl<T: FromValue> FromArg for T {
    const SHAPE: Option<&'static Shape> = <T as FromValue>::SHAPE;
    fn type_desc() -> TypeDesc {
        <T as FromValue>::type_desc()
    }
    fn from_arg(cx: &dyn ConvertCx, value: Option<&Value>) -> RunResult<Self> {
        match value {
            Some(value) => T::from_value(cx, value),
            None => Err(RuntimeError::new("missing a required argument")),
        }
    }
}

/// An optional **trailing** typed argument: `OptionalArg(None)` when the caller
/// omits it, `OptionalArg(Some(..))` otherwise. Lets a `.function`/`.method`
/// have optional parameters instead of hand-matching arg counts in a
/// `raw_function`. Optional parameters must come after all required ones.
pub struct OptionalArg<T>(pub Option<T>);

impl<T: FromValue> FromArg for OptionalArg<T> {
    const SHAPE: Option<&'static Shape> = <T as FromValue>::SHAPE;
    const REQUIRED: bool = false;
    fn type_desc() -> TypeDesc {
        <T as FromValue>::type_desc()
    }
    fn from_arg(cx: &dyn ConvertCx, value: Option<&Value>) -> RunResult<Self> {
        match value {
            Some(value) => Ok(OptionalArg(Some(T::from_value(cx, value)?))),
            None => Ok(OptionalArg(None)),
        }
    }
}

/// A typed-function return that **raises** on `Err`: the `RuntimeError`
/// propagates as a runtime error (unwinding the script) instead of becoming a
/// Xur value.
///
/// Choose the error channel by whether a *script* is expected to handle it:
///
/// * **Runtime errors** — bugs and broken invariants the script should not
///   recover from (a wrong type, an out-of-range index). Return `Raise<T>`.
/// * **Recoverable errors** — expected failures a script handles (not found, a
///   parse failure, a resource that isn't ready). Return a plain
///   `Result<T, String>`, which becomes a Xur `Result` value.
///
/// A function can have **both**: return `Raise<Result<T, String>>` to raise on a
/// runtime error *and* hand back a `Result` value for a recoverable one
/// (`self.0?` raises, then the inner `Result<T, String>` converts to a value).
///
/// (A bare `Result<T, RuntimeError>` can't carry this itself — it collides with
/// the `Facet` blanket impl — so this newtype does.) The declared return type
/// is `T`'s.
pub struct Raise<T>(pub RunResult<T>);

impl<T: IntoXurValue> IntoXurValue for Raise<T> {
    const SHAPE: Option<&'static Shape> = T::SHAPE;
    fn type_desc() -> TypeDesc {
        T::type_desc()
    }
    fn into_xur_value(self, cx: &dyn ConvertCx) -> RunResult<Value> {
        self.0?.into_xur_value(cx)
    }
}

impl<T> From<RunResult<T>> for Raise<T> {
    fn from(result: RunResult<T>) -> Self {
        Raise(result)
    }
}

/// A typed-function return of an optional **dynamic** value, built as the
/// prelude's `Some`/`None`. `Option<T>` works directly when `T: Facet`, but
/// `Option<Value>` can't (same coherence collision), so this newtype carries it
/// — e.g. `list.get` -> `Opt<Value>`.
pub struct Opt<T>(pub Option<T>);

impl<T: IntoXurValue> IntoXurValue for Opt<T> {
    fn type_desc() -> TypeDesc {
        TypeDesc::Generic("Option", vec![T::type_desc()])
    }
    fn into_xur_value(self, cx: &dyn ConvertCx) -> RunResult<Value> {
        let lang = cx.lang();
        Ok(match self.0 {
            Some(value) => Value::adt(lang.some, vec![value.into_xur_value(cx)?]),
            None => Value::adt(lang.none, Vec::new()),
        })
    }
}

impl<T> From<Option<T>> for Opt<T> {
    fn from(option: Option<T>) -> Self {
        Opt(option)
    }
}

/// A typed-function return of a recoverable **dynamic** `Result`, built as the
/// prelude's `Ok`/`Err`. `Result<T, String>` works directly when `T: Facet`, but
/// `Result<Value, String>` can't (the same coherence collision as [`Opt`]), so
/// this newtype carries it — e.g. `layout.read` -> `Res<Value>`. The `Err` is a
/// string message; see the `Raise` docs for runtime-vs-recoverable guidance.
pub struct Res<T>(pub Result<T, String>);

impl<T: IntoXurValue> IntoXurValue for Res<T> {
    fn type_desc() -> TypeDesc {
        TypeDesc::Generic("Result", vec![T::type_desc(), TypeDesc::STR])
    }
    fn into_xur_value(self, cx: &dyn ConvertCx) -> RunResult<Value> {
        let lang = cx.lang();
        Ok(match self.0 {
            Ok(value) => Value::adt(lang.ok, vec![value.into_xur_value(cx)?]),
            Err(message) => Value::adt(lang.err, vec![Value::str(&message)]),
        })
    }
}

impl<T> From<Result<T, String>> for Res<T> {
    fn from(result: Result<T, String>) -> Self {
        Res(result)
    }
}

/// A typed-function **argument** that accepts a value of one of several types.
///
/// `E` is an enum (defined with the [`one_of!`](crate::one_of) macro) whose
/// variants each hold a [`FromValue`] type. `OneOf<E>` tries them in order and
/// builds the first that matches, so a `.function`/`.method` can take a union
/// argument — e.g. a key that is an int index or a string name — instead of
/// hand-matching `Value` variants in a `raw_function`.
pub struct OneOf<E>(pub E);

/// Builds one of several typed variants from a runtime value, for [`OneOf`].
/// Implemented by the [`one_of!`](crate::one_of) macro, not by hand.
pub trait OneOfVariants: Sized + Send + 'static {
    /// The enum's name, which docs use for a long union.
    const NAME: &'static str = "";
    /// The variants' types, in the order they are tried.
    fn type_descs() -> Vec<TypeDesc> {
        Vec::new()
    }
    fn try_from_value(cx: &dyn ConvertCx, value: &Value) -> RunResult<Self>;
}

impl<E: OneOfVariants> FromValue for OneOf<E> {
    fn type_desc() -> TypeDesc {
        if E::NAME.is_empty() {
            TypeDesc::Union(E::type_descs())
        } else {
            TypeDesc::Alias(E::NAME, E::type_descs())
        }
    }
    fn from_value(cx: &dyn ConvertCx, value: &Value) -> RunResult<Self> {
        Ok(OneOf(E::try_from_value(cx, value)?))
    }
}

/// Defines an enum for use as a [`OneOf`](crate::OneOf) union argument.
///
/// Each variant holds one [`FromValue`](crate::FromValue) type; at the call site
/// `OneOf<Name>` tries the variants top-to-bottom and builds the first whose
/// type matches the runtime value, so put the most specific types first.
///
/// ```ignore
/// one_of! {
///     /// A CLI key: a positional index or a flag name.
///     pub enum ArgKey {
///         Index(i64),
///         Name(XurStr),
///     }
/// }
/// // fn arg(&self, key: OneOf<ArgKey>) -> ... { match key.0 { ArgKey::Index(i) => .., ArgKey::Name(n) => .. } }
/// ```
///
/// Docs show a union with more than a few options by its name; give it a
/// friendlier one with `as`: `pub enum TypeNameArg as "TypeName" { .. }`.
#[macro_export]
macro_rules! one_of {
    (
        $(#[$meta:meta])*
        $vis:vis enum $name:ident as $shown:literal {
            $( $(#[$vmeta:meta])* $variant:ident($ty:ty) ),+ $(,)?
        }
    ) => {
        $crate::one_of!(@impl $shown; $(#[$meta])* $vis enum $name { $( $(#[$vmeta])* $variant($ty) ),+ });
    };
    (
        $(#[$meta:meta])*
        $vis:vis enum $name:ident {
            $( $(#[$vmeta:meta])* $variant:ident($ty:ty) ),+ $(,)?
        }
    ) => {
        $crate::one_of!(@impl stringify!($name); $(#[$meta])* $vis enum $name { $( $(#[$vmeta])* $variant($ty) ),+ });
    };
    (@impl $shown:expr;
        $(#[$meta:meta])*
        $vis:vis enum $name:ident {
            $( $(#[$vmeta:meta])* $variant:ident($ty:ty) ),+
        }
    ) => {
        $(#[$meta])*
        $vis enum $name {
            $( $(#[$vmeta])* $variant($ty) ),+
        }

        impl $crate::OneOfVariants for $name {
            const NAME: &'static str = $shown;
            fn type_descs() -> ::std::vec::Vec<$crate::TypeDesc> {
                ::std::vec![$( <$ty as $crate::FromValue>::type_desc() ),+]
            }
            fn try_from_value(
                cx: &dyn $crate::convert::ConvertCx,
                value: &$crate::Value,
            ) -> $crate::RunResult<Self> {
                $(
                    if let Ok(v) = <$ty as $crate::FromValue>::from_value(cx, value) {
                        return Ok(Self::$variant(v));
                    }
                )+
                Err($crate::RuntimeError::new(concat!(
                    "expected one of the types accepted by `",
                    stringify!($name),
                    "`"
                )))
            }
        }
    };
}