use std::marker::PhantomData;
use super::{FromValue, IntoXurValue, TypeDesc};
use crate::convert::ConvertCx;
use crate::{RunResult, Value};
pub trait Describe {
fn type_desc() -> TypeDesc;
}
pub struct Dyn<D>(pub Value, PhantomData<fn() -> D>);
impl<D> Dyn<D> {
pub fn new(value: Value) -> Self {
Self(value, PhantomData)
}
}
impl<D: Describe + 'static> FromValue for Dyn<D> {
fn type_desc() -> TypeDesc {
D::type_desc()
}
fn from_value(_cx: &dyn ConvertCx, value: &Value) -> RunResult<Self> {
Ok(Self::new(value.clone()))
}
}
impl<D: Describe + 'static> IntoXurValue for Dyn<D> {
fn type_desc() -> TypeDesc {
D::type_desc()
}
fn into_xur_value(self, _cx: &dyn ConvertCx) -> RunResult<Value> {
Ok(self.0)
}
}
pub mod desc {
use std::marker::PhantomData;
use super::{Describe, TypeDesc};
macro_rules! params {
($($name:ident: $doc:literal),*) => {$(
#[doc = $doc]
pub struct $name;
impl Describe for $name {
fn type_desc() -> TypeDesc {
TypeDesc::Name(stringify!($name))
}
}
)*};
}
params! {
T: "The receiver's element type: a list's items, a cell's value.",
U: "A second type parameter, chosen by the caller (what a closure returns).",
K: "A map's key type.",
V: "A map's value type."
}
pub struct Any;
impl Describe for Any {
fn type_desc() -> TypeDesc {
TypeDesc::ANY
}
}
pub struct Number;
impl Describe for Number {
fn type_desc() -> TypeDesc {
TypeDesc::Union(vec![TypeDesc::Name("int"), TypeDesc::Name("float")])
}
}
pub struct ListOf<D>(PhantomData<fn() -> D>);
impl<D: Describe> Describe for ListOf<D> {
fn type_desc() -> TypeDesc {
TypeDesc::Generic("list", vec![D::type_desc()])
}
}
pub struct MapOf<K, V>(PhantomData<fn() -> (K, V)>);
impl<K: Describe, V: Describe> Describe for MapOf<K, V> {
fn type_desc() -> TypeDesc {
TypeDesc::Generic("map", vec![K::type_desc(), V::type_desc()])
}
}
pub struct Tuple2<A, B>(PhantomData<fn() -> (A, B)>);
impl<A: Describe, B: Describe> Describe for Tuple2<A, B> {
fn type_desc() -> TypeDesc {
TypeDesc::Tuple(vec![A::type_desc(), B::type_desc()])
}
}
pub struct Str;
impl Describe for Str {
fn type_desc() -> TypeDesc {
TypeDesc::STR
}
}
pub struct Int;
impl Describe for Int {
fn type_desc() -> TypeDesc {
TypeDesc::Name("i64")
}
}
}