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 dynamic;
9mod type_desc;
10mod wrappers;
11
12use facet::{Facet, Shape};
13
14use crate::RunResult;
15use crate::RuntimeError;
16use crate::Value;
17use crate::convert::{self, ConvertCx};
18
19pub use dynamic::{Describe, Dyn, desc};
20pub use type_desc::TypeDesc;
21pub use wrappers::{XurBytes, XurList, XurPtr, XurStr};
22
23/// Extract a Rust value from a Xur [`Value`].
24pub trait FromValue: Sized + Send + 'static {
25    const SHAPE: Option<&'static Shape> = None;
26    /// The type as people should see it (docs, hovers).
27    fn type_desc() -> TypeDesc {
28        TypeDesc::of_shape(Self::SHAPE)
29    }
30    fn from_value(cx: &dyn ConvertCx, value: &Value) -> RunResult<Self>;
31}
32
33/// Convert a Rust value into a Xur [`Value`].
34pub trait IntoXurValue: Send + 'static {
35    const SHAPE: Option<&'static Shape> = None;
36    /// The type as people should see it (docs, hovers).
37    fn type_desc() -> TypeDesc {
38        TypeDesc::of_shape(Self::SHAPE)
39    }
40    fn into_xur_value(self, cx: &dyn ConvertCx) -> RunResult<Value>;
41}
42
43impl<T: Facet<'static> + Send + 'static> FromValue for T {
44    const SHAPE: Option<&'static Shape> = Some(T::SHAPE);
45    fn from_value(cx: &dyn ConvertCx, value: &Value) -> RunResult<Self> {
46        convert::from_value::<T>(cx, value)
47    }
48}
49
50impl<T: Facet<'static> + Send + 'static> IntoXurValue for T {
51    const SHAPE: Option<&'static Shape> = Some(T::SHAPE);
52    fn into_xur_value(self, cx: &dyn ConvertCx) -> RunResult<Value> {
53        convert::into_value(cx, self)
54    }
55}
56
57impl FromValue for Value {
58    fn type_desc() -> TypeDesc {
59        TypeDesc::ANY
60    }
61    fn from_value(_cx: &dyn ConvertCx, value: &Value) -> RunResult<Self> {
62        Ok(value.clone())
63    }
64}
65
66impl IntoXurValue for Value {
67    fn type_desc() -> TypeDesc {
68        TypeDesc::ANY
69    }
70    fn into_xur_value(self, _cx: &dyn ConvertCx) -> RunResult<Value> {
71        Ok(self)
72    }
73}
74
75/// How a positional argument is produced from the call's values, including
76/// whether it may be absent. Every [`FromValue`] type is a *required* argument
77/// via the blanket impl; [`OptionalArg`] overrides it to allow a missing
78/// trailing argument. The typed-function machinery binds each parameter through
79/// this trait.
80pub trait FromArg: Sized + Send + 'static {
81    const SHAPE: Option<&'static Shape> = None;
82    /// Whether the caller must supply this argument.
83    const REQUIRED: bool = true;
84    /// The parameter's type as people should see it (docs, hovers).
85    fn type_desc() -> TypeDesc {
86        TypeDesc::of_shape(Self::SHAPE)
87    }
88    fn from_arg(cx: &dyn ConvertCx, value: Option<&Value>) -> RunResult<Self>;
89}
90
91impl<T: FromValue> FromArg for T {
92    const SHAPE: Option<&'static Shape> = <T as FromValue>::SHAPE;
93    fn type_desc() -> TypeDesc {
94        <T as FromValue>::type_desc()
95    }
96    fn from_arg(cx: &dyn ConvertCx, value: Option<&Value>) -> RunResult<Self> {
97        match value {
98            Some(value) => T::from_value(cx, value),
99            None => Err(RuntimeError::new("missing a required argument")),
100        }
101    }
102}
103
104/// An optional **trailing** typed argument: `OptionalArg(None)` when the caller
105/// omits it, `OptionalArg(Some(..))` otherwise. Lets a `.function`/`.method`
106/// have optional parameters instead of hand-matching arg counts in a
107/// `raw_function`. Optional parameters must come after all required ones.
108pub struct OptionalArg<T>(pub Option<T>);
109
110impl<T: FromValue> FromArg for OptionalArg<T> {
111    const SHAPE: Option<&'static Shape> = <T as FromValue>::SHAPE;
112    const REQUIRED: bool = false;
113    fn type_desc() -> TypeDesc {
114        <T as FromValue>::type_desc()
115    }
116    fn from_arg(cx: &dyn ConvertCx, value: Option<&Value>) -> RunResult<Self> {
117        match value {
118            Some(value) => Ok(OptionalArg(Some(T::from_value(cx, value)?))),
119            None => Ok(OptionalArg(None)),
120        }
121    }
122}
123
124/// A typed-function return that **raises** on `Err`: the `RuntimeError`
125/// propagates as a runtime error (unwinding the script) instead of becoming a
126/// Xur value.
127///
128/// Choose the error channel by whether a *script* is expected to handle it:
129///
130/// * **Runtime errors** — bugs and broken invariants the script should not
131///   recover from (a wrong type, an out-of-range index). Return `Raise<T>`.
132/// * **Recoverable errors** — expected failures a script handles (not found, a
133///   parse failure, a resource that isn't ready). Return a plain
134///   `Result<T, String>`, which becomes a Xur `Result` value.
135///
136/// A function can have **both**: return `Raise<Result<T, String>>` to raise on a
137/// runtime error *and* hand back a `Result` value for a recoverable one
138/// (`self.0?` raises, then the inner `Result<T, String>` converts to a value).
139///
140/// (A bare `Result<T, RuntimeError>` can't carry this itself — it collides with
141/// the `Facet` blanket impl — so this newtype does.) The declared return type
142/// is `T`'s.
143pub struct Raise<T>(pub RunResult<T>);
144
145impl<T: IntoXurValue> IntoXurValue for Raise<T> {
146    const SHAPE: Option<&'static Shape> = T::SHAPE;
147    fn type_desc() -> TypeDesc {
148        T::type_desc()
149    }
150    fn into_xur_value(self, cx: &dyn ConvertCx) -> RunResult<Value> {
151        self.0?.into_xur_value(cx)
152    }
153}
154
155impl<T> From<RunResult<T>> for Raise<T> {
156    fn from(result: RunResult<T>) -> Self {
157        Raise(result)
158    }
159}
160
161/// A typed-function return of an optional **dynamic** value, built as the
162/// prelude's `Some`/`None`. `Option<T>` works directly when `T: Facet`, but
163/// `Option<Value>` can't (same coherence collision), so this newtype carries it
164/// — e.g. `list.get` -> `Opt<Value>`.
165pub struct Opt<T>(pub Option<T>);
166
167impl<T: IntoXurValue> IntoXurValue for Opt<T> {
168    fn type_desc() -> TypeDesc {
169        TypeDesc::Generic("Option", vec![T::type_desc()])
170    }
171    fn into_xur_value(self, cx: &dyn ConvertCx) -> RunResult<Value> {
172        let lang = cx.lang();
173        Ok(match self.0 {
174            Some(value) => Value::adt(lang.some, vec![value.into_xur_value(cx)?]),
175            None => Value::adt(lang.none, Vec::new()),
176        })
177    }
178}
179
180impl<T> From<Option<T>> for Opt<T> {
181    fn from(option: Option<T>) -> Self {
182        Opt(option)
183    }
184}
185
186/// A typed-function return of a recoverable **dynamic** `Result`, built as the
187/// prelude's `Ok`/`Err`. `Result<T, String>` works directly when `T: Facet`, but
188/// `Result<Value, String>` can't (the same coherence collision as [`Opt`]), so
189/// this newtype carries it — e.g. `layout.read` -> `Res<Value>`. The `Err` is a
190/// string message; see the `Raise` docs for runtime-vs-recoverable guidance.
191pub struct Res<T>(pub Result<T, String>);
192
193impl<T: IntoXurValue> IntoXurValue for Res<T> {
194    fn type_desc() -> TypeDesc {
195        TypeDesc::Generic("Result", vec![T::type_desc(), TypeDesc::STR])
196    }
197    fn into_xur_value(self, cx: &dyn ConvertCx) -> RunResult<Value> {
198        let lang = cx.lang();
199        Ok(match self.0 {
200            Ok(value) => Value::adt(lang.ok, vec![value.into_xur_value(cx)?]),
201            Err(message) => Value::adt(lang.err, vec![Value::str(&message)]),
202        })
203    }
204}
205
206impl<T> From<Result<T, String>> for Res<T> {
207    fn from(result: Result<T, String>) -> Self {
208        Res(result)
209    }
210}
211
212/// A typed-function **argument** that accepts a value of one of several types.
213///
214/// `E` is an enum (defined with the [`one_of!`](crate::one_of) macro) whose
215/// variants each hold a [`FromValue`] type. `OneOf<E>` tries them in order and
216/// builds the first that matches, so a `.function`/`.method` can take a union
217/// argument — e.g. a key that is an int index or a string name — instead of
218/// hand-matching `Value` variants in a `raw_function`.
219pub struct OneOf<E>(pub E);
220
221/// Builds one of several typed variants from a runtime value, for [`OneOf`].
222/// Implemented by the [`one_of!`](crate::one_of) macro, not by hand.
223pub trait OneOfVariants: Sized + Send + 'static {
224    /// The enum's name, which docs use for a long union.
225    const NAME: &'static str = "";
226    /// The variants' types, in the order they are tried.
227    fn type_descs() -> Vec<TypeDesc> {
228        Vec::new()
229    }
230    fn try_from_value(cx: &dyn ConvertCx, value: &Value) -> RunResult<Self>;
231}
232
233impl<E: OneOfVariants> FromValue for OneOf<E> {
234    fn type_desc() -> TypeDesc {
235        if E::NAME.is_empty() {
236            TypeDesc::Union(E::type_descs())
237        } else {
238            TypeDesc::Alias(E::NAME, E::type_descs())
239        }
240    }
241    fn from_value(cx: &dyn ConvertCx, value: &Value) -> RunResult<Self> {
242        Ok(OneOf(E::try_from_value(cx, value)?))
243    }
244}
245
246/// Defines an enum for use as a [`OneOf`](crate::OneOf) union argument.
247///
248/// Each variant holds one [`FromValue`](crate::FromValue) type; at the call site
249/// `OneOf<Name>` tries the variants top-to-bottom and builds the first whose
250/// type matches the runtime value, so put the most specific types first.
251///
252/// ```ignore
253/// one_of! {
254///     /// A CLI key: a positional index or a flag name.
255///     pub enum ArgKey {
256///         Index(i64),
257///         Name(XurStr),
258///     }
259/// }
260/// // fn arg(&self, key: OneOf<ArgKey>) -> ... { match key.0 { ArgKey::Index(i) => .., ArgKey::Name(n) => .. } }
261/// ```
262///
263/// Docs show a union with more than a few options by its name; give it a
264/// friendlier one with `as`: `pub enum TypeNameArg as "TypeName" { .. }`.
265#[macro_export]
266macro_rules! one_of {
267    (
268        $(#[$meta:meta])*
269        $vis:vis enum $name:ident as $shown:literal {
270            $( $(#[$vmeta:meta])* $variant:ident($ty:ty) ),+ $(,)?
271        }
272    ) => {
273        $crate::one_of!(@impl $shown; $(#[$meta])* $vis enum $name { $( $(#[$vmeta])* $variant($ty) ),+ });
274    };
275    (
276        $(#[$meta:meta])*
277        $vis:vis enum $name:ident {
278            $( $(#[$vmeta:meta])* $variant:ident($ty:ty) ),+ $(,)?
279        }
280    ) => {
281        $crate::one_of!(@impl stringify!($name); $(#[$meta])* $vis enum $name { $( $(#[$vmeta])* $variant($ty) ),+ });
282    };
283    (@impl $shown:expr;
284        $(#[$meta:meta])*
285        $vis:vis enum $name:ident {
286            $( $(#[$vmeta:meta])* $variant:ident($ty:ty) ),+
287        }
288    ) => {
289        $(#[$meta])*
290        $vis enum $name {
291            $( $(#[$vmeta])* $variant($ty) ),+
292        }
293
294        impl $crate::OneOfVariants for $name {
295            const NAME: &'static str = $shown;
296            fn type_descs() -> ::std::vec::Vec<$crate::TypeDesc> {
297                ::std::vec![$( <$ty as $crate::FromValue>::type_desc() ),+]
298            }
299            fn try_from_value(
300                cx: &dyn $crate::convert::ConvertCx,
301                value: &$crate::Value,
302            ) -> $crate::RunResult<Self> {
303                $(
304                    if let Ok(v) = <$ty as $crate::FromValue>::from_value(cx, value) {
305                        return Ok(Self::$variant(v));
306                    }
307                )+
308                Err($crate::RuntimeError::new(concat!(
309                    "expected one of the types accepted by `",
310                    stringify!($name),
311                    "`"
312                )))
313            }
314        }
315    };
316}