Skip to main content

xur_runtime/marshal/
mod.rs

1//! Traits for converting between Rust types and Xur [`Value`]s.
2//!
3//! [`FromValue`] and [`IntoXurValue`] decouple the typed function API
4//! from [`Facet`]: any type that implements `Facet` automatically gets
5//! both traits via blanket impls, while types like `Value`, `XurList`
6//! and `XurBytes` provide their own custom conversions.
7
8mod wrappers;
9
10use facet::{Facet, Shape};
11
12use crate::RunResult;
13use crate::RuntimeError;
14use crate::Value;
15use crate::convert::{self, ConvertCx};
16
17pub use wrappers::{XurBytes, XurList, XurPtr, XurStr};
18
19/// Extract a Rust value from a Xur [`Value`].
20pub trait FromValue: Sized + Send + 'static {
21    const SHAPE: Option<&'static Shape> = None;
22    fn from_value(cx: &dyn ConvertCx, value: &Value) -> RunResult<Self>;
23}
24
25/// Convert a Rust value into a Xur [`Value`].
26pub trait IntoXurValue: Send + 'static {
27    const SHAPE: Option<&'static Shape> = None;
28    fn into_xur_value(self, cx: &dyn ConvertCx) -> RunResult<Value>;
29}
30
31impl<T: Facet<'static> + Send + 'static> FromValue for T {
32    const SHAPE: Option<&'static Shape> = Some(T::SHAPE);
33    fn from_value(cx: &dyn ConvertCx, value: &Value) -> RunResult<Self> {
34        convert::from_value::<T>(cx, value)
35    }
36}
37
38impl<T: Facet<'static> + Send + 'static> IntoXurValue for T {
39    const SHAPE: Option<&'static Shape> = Some(T::SHAPE);
40    fn into_xur_value(self, cx: &dyn ConvertCx) -> RunResult<Value> {
41        convert::into_value(cx, self)
42    }
43}
44
45impl FromValue for Value {
46    fn from_value(_cx: &dyn ConvertCx, value: &Value) -> RunResult<Self> {
47        Ok(value.clone())
48    }
49}
50
51impl IntoXurValue for Value {
52    fn into_xur_value(self, _cx: &dyn ConvertCx) -> RunResult<Value> {
53        Ok(self)
54    }
55}
56
57/// How a positional argument is produced from the call's values, including
58/// whether it may be absent. Every [`FromValue`] type is a *required* argument
59/// via the blanket impl; [`OptionalArg`] overrides it to allow a missing
60/// trailing argument. The typed-function machinery binds each parameter through
61/// this trait.
62pub trait FromArg: Sized + Send + 'static {
63    const SHAPE: Option<&'static Shape> = None;
64    /// Whether the caller must supply this argument.
65    const REQUIRED: bool = true;
66    fn from_arg(cx: &dyn ConvertCx, value: Option<&Value>) -> RunResult<Self>;
67}
68
69impl<T: FromValue> FromArg for T {
70    const SHAPE: Option<&'static Shape> = <T as FromValue>::SHAPE;
71    fn from_arg(cx: &dyn ConvertCx, value: Option<&Value>) -> RunResult<Self> {
72        match value {
73            Some(value) => T::from_value(cx, value),
74            None => Err(RuntimeError::new("missing a required argument")),
75        }
76    }
77}
78
79/// An optional **trailing** typed argument: `OptionalArg(None)` when the caller
80/// omits it, `OptionalArg(Some(..))` otherwise. Lets a `.function`/`.method`
81/// have optional parameters instead of hand-matching arg counts in a
82/// `raw_function`. Optional parameters must come after all required ones.
83pub struct OptionalArg<T>(pub Option<T>);
84
85impl<T: FromValue> FromArg for OptionalArg<T> {
86    const SHAPE: Option<&'static Shape> = <T as FromValue>::SHAPE;
87    const REQUIRED: bool = false;
88    fn from_arg(cx: &dyn ConvertCx, value: Option<&Value>) -> RunResult<Self> {
89        match value {
90            Some(value) => Ok(OptionalArg(Some(T::from_value(cx, value)?))),
91            None => Ok(OptionalArg(None)),
92        }
93    }
94}
95
96/// A typed-function return that **raises** on `Err`: the `RuntimeError`
97/// propagates as a runtime error (unwinding the script) instead of becoming a
98/// Xur value.
99///
100/// Choose the error channel by whether a *script* is expected to handle it:
101///
102/// * **Runtime errors** — bugs and broken invariants the script should not
103///   recover from (a wrong type, an out-of-range index). Return `Raise<T>`.
104/// * **Recoverable errors** — expected failures a script handles (not found, a
105///   parse failure, a resource that isn't ready). Return a plain
106///   `Result<T, String>`, which becomes a Xur `Result` value.
107///
108/// A function can have **both**: return `Raise<Result<T, String>>` to raise on a
109/// runtime error *and* hand back a `Result` value for a recoverable one
110/// (`self.0?` raises, then the inner `Result<T, String>` converts to a value).
111///
112/// (A bare `Result<T, RuntimeError>` can't carry this itself — it collides with
113/// the `Facet` blanket impl — so this newtype does.) The declared return type
114/// is `T`'s.
115pub struct Raise<T>(pub RunResult<T>);
116
117impl<T: IntoXurValue> IntoXurValue for Raise<T> {
118    const SHAPE: Option<&'static Shape> = T::SHAPE;
119    fn into_xur_value(self, cx: &dyn ConvertCx) -> RunResult<Value> {
120        self.0?.into_xur_value(cx)
121    }
122}
123
124impl<T> From<RunResult<T>> for Raise<T> {
125    fn from(result: RunResult<T>) -> Self {
126        Raise(result)
127    }
128}
129
130/// A typed-function return of an optional **dynamic** value, built as the
131/// prelude's `Some`/`None`. `Option<T>` works directly when `T: Facet`, but
132/// `Option<Value>` can't (same coherence collision), so this newtype carries it
133/// — e.g. `list.get` -> `Opt<Value>`.
134pub struct Opt<T>(pub Option<T>);
135
136impl<T: IntoXurValue> IntoXurValue for Opt<T> {
137    fn into_xur_value(self, cx: &dyn ConvertCx) -> RunResult<Value> {
138        let lang = cx.lang();
139        Ok(match self.0 {
140            Some(value) => Value::adt(lang.some, vec![value.into_xur_value(cx)?]),
141            None => Value::adt(lang.none, Vec::new()),
142        })
143    }
144}
145
146impl<T> From<Option<T>> for Opt<T> {
147    fn from(option: Option<T>) -> Self {
148        Opt(option)
149    }
150}
151
152/// A typed-function return of a recoverable **dynamic** `Result`, built as the
153/// prelude's `Ok`/`Err`. `Result<T, String>` works directly when `T: Facet`, but
154/// `Result<Value, String>` can't (the same coherence collision as [`Opt`]), so
155/// this newtype carries it — e.g. `layout.read` -> `Res<Value>`. The `Err` is a
156/// string message; see the `Raise` docs for runtime-vs-recoverable guidance.
157pub struct Res<T>(pub Result<T, String>);
158
159impl<T: IntoXurValue> IntoXurValue for Res<T> {
160    fn into_xur_value(self, cx: &dyn ConvertCx) -> RunResult<Value> {
161        let lang = cx.lang();
162        Ok(match self.0 {
163            Ok(value) => Value::adt(lang.ok, vec![value.into_xur_value(cx)?]),
164            Err(message) => Value::adt(lang.err, vec![Value::str(&message)]),
165        })
166    }
167}
168
169impl<T> From<Result<T, String>> for Res<T> {
170    fn from(result: Result<T, String>) -> Self {
171        Res(result)
172    }
173}
174
175/// A typed-function **argument** that accepts a value of one of several types.
176///
177/// `E` is an enum (defined with the [`one_of!`](crate::one_of) macro) whose
178/// variants each hold a [`FromValue`] type. `OneOf<E>` tries them in order and
179/// builds the first that matches, so a `.function`/`.method` can take a union
180/// argument — e.g. a key that is an int index or a string name — instead of
181/// hand-matching `Value` variants in a `raw_function`.
182pub struct OneOf<E>(pub E);
183
184/// Builds one of several typed variants from a runtime value, for [`OneOf`].
185/// Implemented by the [`one_of!`](crate::one_of) macro, not by hand.
186pub trait OneOfVariants: Sized + Send + 'static {
187    fn try_from_value(cx: &dyn ConvertCx, value: &Value) -> RunResult<Self>;
188}
189
190impl<E: OneOfVariants> FromValue for OneOf<E> {
191    fn from_value(cx: &dyn ConvertCx, value: &Value) -> RunResult<Self> {
192        Ok(OneOf(E::try_from_value(cx, value)?))
193    }
194}
195
196/// Defines an enum for use as a [`OneOf`](crate::OneOf) union argument.
197///
198/// Each variant holds one [`FromValue`](crate::FromValue) type; at the call site
199/// `OneOf<Name>` tries the variants top-to-bottom and builds the first whose
200/// type matches the runtime value, so put the most specific types first.
201///
202/// ```ignore
203/// one_of! {
204///     /// A CLI key: a positional index or a flag name.
205///     pub enum ArgKey {
206///         Index(i64),
207///         Name(XurStr),
208///     }
209/// }
210/// // fn arg(&self, key: OneOf<ArgKey>) -> ... { match key.0 { ArgKey::Index(i) => .., ArgKey::Name(n) => .. } }
211/// ```
212#[macro_export]
213macro_rules! one_of {
214    (
215        $(#[$meta:meta])*
216        $vis:vis enum $name:ident {
217            $( $(#[$vmeta:meta])* $variant:ident($ty:ty) ),+ $(,)?
218        }
219    ) => {
220        $(#[$meta])*
221        $vis enum $name {
222            $( $(#[$vmeta])* $variant($ty) ),+
223        }
224
225        impl $crate::OneOfVariants for $name {
226            fn try_from_value(
227                cx: &dyn $crate::convert::ConvertCx,
228                value: &$crate::Value,
229            ) -> $crate::RunResult<Self> {
230                $(
231                    if let Ok(v) = <$ty as $crate::FromValue>::from_value(cx, value) {
232                        return Ok(Self::$variant(v));
233                    }
234                )+
235                Err($crate::RuntimeError::new(concat!(
236                    "expected one of the types accepted by `",
237                    stringify!($name),
238                    "`"
239                )))
240            }
241        }
242    };
243}