summaryrefslogtreecommitdiff
path: root/serde_dhall/src/deserialize.rs
blob: cccadadcadb3541f5e159a08246165a15ac48741 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
use serde::de::value::{
    MapAccessDeserializer, MapDeserializer, SeqDeserializer,
};
use std::borrow::Cow;

use dhall::syntax::NumKind;

use crate::simple::{ValKind, Value as SimpleValue};
use crate::{Error, Result, Value};

pub trait Sealed {}

/// A data structure that can be deserialized from a Dhall expression
///
/// This is automatically implemented for any type that [serde][serde]
/// can deserialize.
///
/// This trait cannot be implemented manually.
///
/// TODO
pub trait Deserialize: Sealed + Sized {
    #[doc(hidden)]
    fn from_dhall(v: &Value) -> Result<Self>;
}

impl<'a, T> Sealed for T where T: serde::Deserialize<'a> {}

struct Deserializer<'a>(Cow<'a, SimpleValue>);

impl<'a, T> Deserialize for T
where
    T: serde::Deserialize<'a>,
{
    fn from_dhall(v: &Value) -> Result<Self> {
        let sval = v.to_simple_value().ok_or_else(|| {
            Error::Deserialize(format!(
                "this cannot be deserialized into the serde data model: {}",
                v
            ))
        })?;
        T::deserialize(Deserializer(Cow::Owned(sval)))
    }
}

impl<'de: 'a, 'a> serde::de::IntoDeserializer<'de, Error> for Deserializer<'a> {
    type Deserializer = Deserializer<'a>;
    fn into_deserializer(self) -> Self::Deserializer {
        self
    }
}

impl<'de: 'a, 'a> serde::Deserializer<'de> for Deserializer<'a> {
    type Error = Error;

    fn deserialize_any<V>(self, visitor: V) -> Result<V::Value>
    where
        V: serde::de::Visitor<'de>,
    {
        use std::convert::TryInto;
        use NumKind::*;
        use ValKind::*;

        let val = |x| Deserializer(Cow::Borrowed(x));
        match self.0.kind() {
            Num(Bool(x)) => visitor.visit_bool(*x),
            Num(Natural(x)) => {
                if let Ok(x64) = (*x).try_into() {
                    visitor.visit_u64(x64)
                } else if let Ok(x32) = (*x).try_into() {
                    visitor.visit_u32(x32)
                } else {
                    unimplemented!()
                }
            }
            Num(Integer(x)) => {
                if let Ok(x64) = (*x).try_into() {
                    visitor.visit_i64(x64)
                } else if let Ok(x32) = (*x).try_into() {
                    visitor.visit_i32(x32)
                } else {
                    unimplemented!()
                }
            }
            Num(Double(x)) => visitor.visit_f64((*x).into()),
            Text(x) => visitor.visit_str(x),
            List(xs) => {
                visitor.visit_seq(SeqDeserializer::new(xs.iter().map(val)))
            }
            Optional(None) => visitor.visit_none(),
            Optional(Some(x)) => visitor.visit_some(val(x)),
            Record(m) => visitor.visit_map(MapDeserializer::new(
                m.iter().map(|(k, v)| (k.as_ref(), val(v))),
            )),
            Union(field_name, Some(x)) => visitor.visit_enum(
                MapAccessDeserializer::new(MapDeserializer::new(
                    Some((field_name.as_str(), val(x))).into_iter(),
                )),
            ),
            Union(field_name, None) => visitor.visit_enum(
                MapAccessDeserializer::new(MapDeserializer::new(
                    Some((field_name.as_str(), ())).into_iter(),
                )),
            ),
        }
    }

    fn deserialize_tuple<V>(self, _: usize, visitor: V) -> Result<V::Value>
    where
        V: serde::de::Visitor<'de>,
    {
        let val = |x| Deserializer(Cow::Borrowed(x));
        match self.0.kind() {
            // Blindly takes keys in sorted order.
            ValKind::Record(m) => visitor
                .visit_seq(SeqDeserializer::new(m.iter().map(|(_, v)| val(v)))),
            _ => self.deserialize_any(visitor),
        }
    }

    serde::forward_to_deserialize_any! {
        bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string
        bytes byte_buf option unit unit_struct newtype_struct seq
        tuple_struct map struct enum identifier ignored_any
    }
}