Skip to main content

scrusted_yaml/
api.rs

1//! The typed side of the API (SPEC 5.6–5.8): variables from serde, results into any
2//! `Deserialize`, typed host functions, and marked values by type.
3
4use indexmap::IndexMap;
5use rust_decimal::Decimal;
6use rust_decimal::prelude::ToPrimitive;
7use scrusted_feel::serde_value::{self, HOST_TOKEN};
8use scrusted_feel::{HostError, HostFn, HostValue, Map, Value};
9use serde::de::DeserializeOwned;
10use std::marker::PhantomData;
11use std::ops::{Deref, DerefMut};
12use std::sync::Arc;
13
14/// The variables of one resolve, by name.
15#[derive(Debug, Clone, Default, PartialEq)]
16pub struct Vars(pub Map);
17
18impl Vars {
19    /// No variables.
20    pub fn new() -> Self {
21        Vars(Map::new())
22    }
23
24    /// Variables from a struct or a map that serializes: each field is a variable.
25    pub fn from_serialize<T: serde::Serialize + ?Sized>(input: &T) -> Result<Vars, serde_value::Error> {
26        match serde_value::to_value(input)? {
27            Value::Map(m) => Ok(Vars((*m).clone())),
28            Value::Null => Ok(Vars::new()),
29            other => {
30                Err(serde_value::Error(format!("variables come from a map or a struct, not {}", scrusted_feel::value::type_name(&other))))
31            }
32        }
33    }
34
35    /// Sets one variable.
36    pub fn set(mut self, name: &str, value: impl Into<Value>) -> Self {
37        self.0.insert(name.into(), value.into());
38        self
39    }
40}
41
42impl Deref for Vars {
43    type Target = Map;
44    fn deref(&self) -> &Map {
45        &self.0
46    }
47}
48
49impl DerefMut for Vars {
50    fn deref_mut(&mut self) -> &mut Map {
51        &mut self.0
52    }
53}
54
55/// Anything that holds variables by name: [`Vars`] or a [`Map`].
56pub trait AsVars {
57    /// The variables.
58    fn as_vars(&self) -> &Map;
59}
60
61impl AsVars for Vars {
62    fn as_vars(&self) -> &Map {
63        &self.0
64    }
65}
66
67impl AsVars for Map {
68    fn as_vars(&self) -> &Map {
69        self
70    }
71}
72
73impl From<Vars> for Map {
74    fn from(v: Vars) -> Map {
75        v.0
76    }
77}
78
79impl From<Map> for Vars {
80    fn from(map: Map) -> Self {
81        Vars(map)
82    }
83}
84
85/// A value converted from a formula's value, for a host function's parameter (SPEC 5.8).
86pub trait FromValue: Sized {
87    /// The conversion; Err says what was expected.
88    fn from_value(value: &Value) -> Result<Self, String>;
89}
90
91/// A host function's result as a formula's value.
92pub trait IntoValue {
93    /// The conversion.
94    fn into_value(self) -> Value;
95}
96
97fn got(v: &Value) -> String {
98    match v {
99        Value::Null => "null".into(),
100        Value::String(s) => format!("\"{s}\""),
101        other => other.to_feel_string(),
102    }
103}
104
105impl FromValue for Value {
106    fn from_value(value: &Value) -> Result<Self, String> {
107        Ok(value.clone())
108    }
109}
110
111impl FromValue for String {
112    fn from_value(value: &Value) -> Result<Self, String> {
113        value.as_str().map(str::to_string).ok_or_else(|| format!("must be text, got {}", got(value)))
114    }
115}
116
117impl FromValue for bool {
118    fn from_value(value: &Value) -> Result<Self, String> {
119        value.as_bool().ok_or_else(|| format!("must be true or false, got {}", got(value)))
120    }
121}
122
123impl FromValue for Decimal {
124    fn from_value(value: &Value) -> Result<Self, String> {
125        value.as_number().ok_or_else(|| format!("must be a number, got {}", got(value)))
126    }
127}
128
129impl FromValue for f64 {
130    fn from_value(value: &Value) -> Result<Self, String> {
131        value.to_f64().ok_or_else(|| format!("must be a number, got {}", got(value)))
132    }
133}
134
135macro_rules! integer {
136    ($($t:ty => $m:ident),*) => {$(
137        impl FromValue for $t {
138            fn from_value(value: &Value) -> Result<Self, String> {
139                value.as_number().filter(|n| n.fract().is_zero()).and_then(|n| n.$m()).ok_or_else(|| format!("must be a whole number, got {}", got(value)))
140            }
141        }
142        impl IntoValue for $t {
143            fn into_value(self) -> Value {
144                Value::Number(Decimal::from(self))
145            }
146        }
147    )*};
148}
149
150integer!(i32 => to_i32, i64 => to_i64, u32 => to_u32, u64 => to_u64, usize => to_usize);
151
152impl<T: FromValue> FromValue for Option<T> {
153    fn from_value(value: &Value) -> Result<Self, String> {
154        if value.is_null() { Ok(None) } else { T::from_value(value).map(Some) }
155    }
156}
157
158impl<T: FromValue> FromValue for Vec<T> {
159    fn from_value(value: &Value) -> Result<Self, String> {
160        match value {
161            Value::List(items) => items.iter().map(T::from_value).collect(),
162            other => Err(format!("must be a list, got {}", got(other))),
163        }
164    }
165}
166
167/// Any `Deserialize` as a parameter, through serde.
168#[derive(Debug, Clone, PartialEq)]
169pub struct Typed<T>(pub T);
170
171impl<T: DeserializeOwned> FromValue for Typed<T> {
172    fn from_value(value: &Value) -> Result<Self, String> {
173        serde_value::from_value(value.clone()).map(Typed).map_err(|e| e.0)
174    }
175}
176
177impl<T: serde::Serialize> IntoValue for Typed<T> {
178    fn into_value(self) -> Value {
179        serde_value::to_value(&self.0).unwrap_or(Value::Null)
180    }
181}
182
183impl IntoValue for Value {
184    fn into_value(self) -> Value {
185        self
186    }
187}
188
189impl IntoValue for String {
190    fn into_value(self) -> Value {
191        Value::from(self)
192    }
193}
194
195impl IntoValue for &str {
196    fn into_value(self) -> Value {
197        Value::from(self)
198    }
199}
200
201impl IntoValue for bool {
202    fn into_value(self) -> Value {
203        Value::Bool(self)
204    }
205}
206
207impl IntoValue for Decimal {
208    fn into_value(self) -> Value {
209        Value::Number(self.normalize())
210    }
211}
212
213impl IntoValue for f64 {
214    fn into_value(self) -> Value {
215        Value::from_f64(self)
216    }
217}
218
219impl IntoValue for () {
220    fn into_value(self) -> Value {
221        Value::Null
222    }
223}
224
225impl<T: IntoValue> IntoValue for Option<T> {
226    fn into_value(self) -> Value {
227        self.map(IntoValue::into_value).unwrap_or(Value::Null)
228    }
229}
230
231impl<T: IntoValue> IntoValue for Vec<T> {
232    fn into_value(self) -> Value {
233        Value::from(self.into_iter().map(IntoValue::into_value).collect::<Vec<_>>())
234    }
235}
236
237/// A Rust closure usable as a host function: `Fn(A, B, …) -> Result<R, HostError>`.
238pub trait HostFunction<Args>: Send + Sync + 'static {
239    /// Wraps it, naming the function in conversion errors.
240    fn wrap(self, name: &str) -> HostFn;
241}
242
243macro_rules! arity {
244    ($($a:ident),*) => {
245        impl<F, R, $($a,)*> HostFunction<($($a,)*)> for F
246        where
247            F: Fn($($a),*) -> Result<R, HostError> + Send + Sync + 'static,
248            R: IntoValue,
249            $($a: FromValue,)*
250        {
251            #[allow(non_snake_case, unused_mut, unused_variables)]
252            fn wrap(self, name: &str) -> HostFn {
253                let name = name.to_string();
254                Arc::new(move |args: &[Value]| {
255                    let mut index = 0usize;
256                    $(
257                        let $a = {
258                            let value = args.get(index).cloned().unwrap_or(Value::Null);
259                            index += 1;
260                            $a::from_value(&value).map_err(|why| HostError(format!("the function \"{name}\": parameter {index} {why}")))?
261                        };
262                    )*
263                    self($($a),*).map(IntoValue::into_value)
264                })
265            }
266        }
267    };
268}
269
270arity!();
271arity!(A1);
272arity!(A1, A2);
273arity!(A1, A2, A3);
274arity!(A1, A2, A3, A4);
275arity!(A1, A2, A3, A4, A5);
276
277/// The functions a file declares under `$functions` without `!`, passed to `resolve` (SPEC 5.8).
278#[derive(Clone, Default)]
279pub struct Functions(pub IndexMap<String, HostFn>);
280
281impl Functions {
282    /// No functions.
283    pub fn new() -> Self {
284        Functions::default()
285    }
286
287    /// A typed function: parameters convert with [`FromValue`], the result with [`IntoValue`].
288    pub fn add<Args>(mut self, name: &str, f: impl HostFunction<Args>) -> Self {
289        let wrapped = f.wrap(name);
290        self.0.insert(name.to_string(), wrapped);
291        self
292    }
293
294    /// A function on values as they are.
295    pub fn add_raw(mut self, name: &str, f: impl Fn(&[Value]) -> Result<Value, HostError> + Send + Sync + 'static) -> Self {
296        self.0.insert(name.to_string(), Arc::new(f));
297        self
298    }
299
300    /// True when no function is passed.
301    pub fn is_empty(&self) -> bool {
302        self.0.is_empty()
303    }
304}
305
306impl std::fmt::Debug for Functions {
307    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
308        f.debug_list().entries(self.0.keys()).finish()
309    }
310}
311
312/// A marked value in a typed result: what the marker function returned, as its own type (SPEC 5.7).
313pub struct Marked<T: HostValue> {
314    value: Arc<T>,
315}
316
317impl<T: HostValue> Marked<T> {
318    /// The value.
319    pub fn get(&self) -> &T {
320        &self.value
321    }
322
323    /// The shared value.
324    pub fn arc(&self) -> Arc<T> {
325        self.value.clone()
326    }
327}
328
329impl<T: HostValue> Clone for Marked<T> {
330    fn clone(&self) -> Self {
331        Marked { value: self.value.clone() }
332    }
333}
334
335impl<T: HostValue> Deref for Marked<T> {
336    type Target = T;
337    fn deref(&self) -> &T {
338        &self.value
339    }
340}
341
342impl<T: HostValue> std::fmt::Debug for Marked<T> {
343    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
344        self.value.fmt(f)
345    }
346}
347
348impl<'de, T: HostValue> serde::Deserialize<'de> for Marked<T> {
349    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
350        struct V<T>(PhantomData<T>);
351        impl<'de, T: HostValue> serde::de::Visitor<'de> for V<T> {
352            type Value = Marked<T>;
353            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
354                write!(f, "a marked value of type {}", std::any::type_name::<T>())
355            }
356            fn visit_u64<E: serde::de::Error>(self, slot: u64) -> Result<Marked<T>, E> {
357                let host = serde_value::take_host(slot).ok_or_else(|| E::custom("the marked value is gone"))?;
358                let any: Arc<dyn std::any::Any + Send + Sync> = host;
359                any.downcast::<T>()
360                    .map(|value| Marked { value })
361                    .map_err(|_| E::custom(format!("the marked value is not a {}", std::any::type_name::<T>())))
362            }
363        }
364        deserializer.deserialize_newtype_struct(HOST_TOKEN, V(PhantomData))
365    }
366}