use indexmap::IndexMap;
use rust_decimal::Decimal;
use rust_decimal::prelude::ToPrimitive;
use scrusted_feel::serde_value::{self, HOST_TOKEN};
use scrusted_feel::{HostError, HostFn, HostValue, Map, Value};
use serde::de::DeserializeOwned;
use std::marker::PhantomData;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Vars(pub Map);
impl Vars {
pub fn new() -> Self {
Vars(Map::new())
}
pub fn from_serialize<T: serde::Serialize + ?Sized>(input: &T) -> Result<Vars, serde_value::Error> {
match serde_value::to_value(input)? {
Value::Map(m) => Ok(Vars((*m).clone())),
Value::Null => Ok(Vars::new()),
other => {
Err(serde_value::Error(format!("variables come from a map or a struct, not {}", scrusted_feel::value::type_name(&other))))
}
}
}
pub fn set(mut self, name: &str, value: impl Into<Value>) -> Self {
self.0.insert(name.into(), value.into());
self
}
}
impl Deref for Vars {
type Target = Map;
fn deref(&self) -> &Map {
&self.0
}
}
impl DerefMut for Vars {
fn deref_mut(&mut self) -> &mut Map {
&mut self.0
}
}
pub trait AsVars {
fn as_vars(&self) -> ⤅
}
impl AsVars for Vars {
fn as_vars(&self) -> &Map {
&self.0
}
}
impl AsVars for Map {
fn as_vars(&self) -> &Map {
self
}
}
impl From<Vars> for Map {
fn from(v: Vars) -> Map {
v.0
}
}
impl From<Map> for Vars {
fn from(map: Map) -> Self {
Vars(map)
}
}
pub trait FromValue: Sized {
fn from_value(value: &Value) -> Result<Self, String>;
}
pub trait IntoValue {
fn into_value(self) -> Value;
}
fn got(v: &Value) -> String {
match v {
Value::Null => "null".into(),
Value::String(s) => format!("\"{s}\""),
other => other.to_feel_string(),
}
}
impl FromValue for Value {
fn from_value(value: &Value) -> Result<Self, String> {
Ok(value.clone())
}
}
impl FromValue for String {
fn from_value(value: &Value) -> Result<Self, String> {
value.as_str().map(str::to_string).ok_or_else(|| format!("must be text, got {}", got(value)))
}
}
impl FromValue for bool {
fn from_value(value: &Value) -> Result<Self, String> {
value.as_bool().ok_or_else(|| format!("must be true or false, got {}", got(value)))
}
}
impl FromValue for Decimal {
fn from_value(value: &Value) -> Result<Self, String> {
value.as_number().ok_or_else(|| format!("must be a number, got {}", got(value)))
}
}
impl FromValue for f64 {
fn from_value(value: &Value) -> Result<Self, String> {
value.to_f64().ok_or_else(|| format!("must be a number, got {}", got(value)))
}
}
macro_rules! integer {
($($t:ty => $m:ident),*) => {$(
impl FromValue for $t {
fn from_value(value: &Value) -> Result<Self, String> {
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)))
}
}
impl IntoValue for $t {
fn into_value(self) -> Value {
Value::Number(Decimal::from(self))
}
}
)*};
}
integer!(i32 => to_i32, i64 => to_i64, u32 => to_u32, u64 => to_u64, usize => to_usize);
impl<T: FromValue> FromValue for Option<T> {
fn from_value(value: &Value) -> Result<Self, String> {
if value.is_null() { Ok(None) } else { T::from_value(value).map(Some) }
}
}
impl<T: FromValue> FromValue for Vec<T> {
fn from_value(value: &Value) -> Result<Self, String> {
match value {
Value::List(items) => items.iter().map(T::from_value).collect(),
other => Err(format!("must be a list, got {}", got(other))),
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Typed<T>(pub T);
impl<T: DeserializeOwned> FromValue for Typed<T> {
fn from_value(value: &Value) -> Result<Self, String> {
serde_value::from_value(value.clone()).map(Typed).map_err(|e| e.0)
}
}
impl<T: serde::Serialize> IntoValue for Typed<T> {
fn into_value(self) -> Value {
serde_value::to_value(&self.0).unwrap_or(Value::Null)
}
}
impl IntoValue for Value {
fn into_value(self) -> Value {
self
}
}
impl IntoValue for String {
fn into_value(self) -> Value {
Value::from(self)
}
}
impl IntoValue for &str {
fn into_value(self) -> Value {
Value::from(self)
}
}
impl IntoValue for bool {
fn into_value(self) -> Value {
Value::Bool(self)
}
}
impl IntoValue for Decimal {
fn into_value(self) -> Value {
Value::Number(self.normalize())
}
}
impl IntoValue for f64 {
fn into_value(self) -> Value {
Value::from_f64(self)
}
}
impl IntoValue for () {
fn into_value(self) -> Value {
Value::Null
}
}
impl<T: IntoValue> IntoValue for Option<T> {
fn into_value(self) -> Value {
self.map(IntoValue::into_value).unwrap_or(Value::Null)
}
}
impl<T: IntoValue> IntoValue for Vec<T> {
fn into_value(self) -> Value {
Value::from(self.into_iter().map(IntoValue::into_value).collect::<Vec<_>>())
}
}
pub trait HostFunction<Args>: Send + Sync + 'static {
fn wrap(self, name: &str) -> HostFn;
}
macro_rules! arity {
($($a:ident),*) => {
impl<F, R, $($a,)*> HostFunction<($($a,)*)> for F
where
F: Fn($($a),*) -> Result<R, HostError> + Send + Sync + 'static,
R: IntoValue,
$($a: FromValue,)*
{
#[allow(non_snake_case, unused_mut, unused_variables)]
fn wrap(self, name: &str) -> HostFn {
let name = name.to_string();
Arc::new(move |args: &[Value]| {
let mut index = 0usize;
$(
let $a = {
let value = args.get(index).cloned().unwrap_or(Value::Null);
index += 1;
$a::from_value(&value).map_err(|why| HostError(format!("the function \"{name}\": parameter {index} {why}")))?
};
)*
self($($a),*).map(IntoValue::into_value)
})
}
}
};
}
arity!();
arity!(A1);
arity!(A1, A2);
arity!(A1, A2, A3);
arity!(A1, A2, A3, A4);
arity!(A1, A2, A3, A4, A5);
#[derive(Clone, Default)]
pub struct Functions(pub IndexMap<String, HostFn>);
impl Functions {
pub fn new() -> Self {
Functions::default()
}
pub fn add<Args>(mut self, name: &str, f: impl HostFunction<Args>) -> Self {
let wrapped = f.wrap(name);
self.0.insert(name.to_string(), wrapped);
self
}
pub fn add_raw(mut self, name: &str, f: impl Fn(&[Value]) -> Result<Value, HostError> + Send + Sync + 'static) -> Self {
self.0.insert(name.to_string(), Arc::new(f));
self
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl std::fmt::Debug for Functions {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_list().entries(self.0.keys()).finish()
}
}
pub struct Marked<T: HostValue> {
value: Arc<T>,
}
impl<T: HostValue> Marked<T> {
pub fn get(&self) -> &T {
&self.value
}
pub fn arc(&self) -> Arc<T> {
self.value.clone()
}
}
impl<T: HostValue> Clone for Marked<T> {
fn clone(&self) -> Self {
Marked { value: self.value.clone() }
}
}
impl<T: HostValue> Deref for Marked<T> {
type Target = T;
fn deref(&self) -> &T {
&self.value
}
}
impl<T: HostValue> std::fmt::Debug for Marked<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.value.fmt(f)
}
}
impl<'de, T: HostValue> serde::Deserialize<'de> for Marked<T> {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct V<T>(PhantomData<T>);
impl<'de, T: HostValue> serde::de::Visitor<'de> for V<T> {
type Value = Marked<T>;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "a marked value of type {}", std::any::type_name::<T>())
}
fn visit_u64<E: serde::de::Error>(self, slot: u64) -> Result<Marked<T>, E> {
let host = serde_value::take_host(slot).ok_or_else(|| E::custom("the marked value is gone"))?;
let any: Arc<dyn std::any::Any + Send + Sync> = host;
any.downcast::<T>()
.map(|value| Marked { value })
.map_err(|_| E::custom(format!("the marked value is not a {}", std::any::type_name::<T>())))
}
}
deserializer.deserialize_newtype_struct(HOST_TOKEN, V(PhantomData))
}
}