summaryrefslogtreecommitdiff
path: root/serde_dhall/src/value.rs
blob: 0f0b25671d9b30b779f0752ab6837ca61b61caed (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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
use std::collections::{BTreeMap, HashMap};

use dhall::builtins::Builtin;
use dhall::operations::OpKind;
use dhall::semantics::{Hir, HirKind, Nir, NirKind};
use dhall::syntax::{Expr, ExprKind, NumKind, Span};

use crate::{Error, ErrorKind, FromDhall, Result, Sealed};

#[doc(hidden)]
/// An arbitrary Dhall value.
#[derive(Debug, Clone)]
pub struct Value {
    /// Invariant: in normal form
    hir: Hir,
    /// Cached conversions because they are annoying to construct from Hir.
    /// At most one of them will be `Some`.
    as_simple_val: Option<SimpleValue>,
    as_simple_ty: Option<SimpleType>,
}

/// A simple value of the kind that can be decoded with serde
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum SimpleValue {
    Num(NumKind),
    Text(String),
    Optional(Option<Box<SimpleValue>>),
    List(Vec<SimpleValue>),
    Record(BTreeMap<String, SimpleValue>),
    Union(String, Option<Box<SimpleValue>>),
}

/// The type of a value that can be decoded by `serde_dhall`, e.g. `{ x: Bool, y: List Natural }`.
///
/// A `SimpleType` is used when deserializing values to ensure they are of the expected type.
/// Rather than letting `serde` handle potential type mismatches, this uses the type-checking
/// capabilities of Dhall to catch errors early and cleanly indicate in the user's code where the
/// mismatch happened.
///
/// You would typically not manipulate `SimpleType`s by hand but rather let Rust infer it for your
/// datatype by deriving the [`StaticType`] trait, and using
/// [`Deserializer::static_type_annotation`]. If you need to supply a `SimpleType` manually, you
/// can either deserialize it like any other Dhall value, or construct it manually.
///
/// [`StaticType`]: trait.StaticType.html
/// [`Deserializer::static_type_annotation`]: options/struct.Deserializer.html#method.static_type_annotation
///
/// # Examples
///
/// ```rust
/// # fn main() -> serde_dhall::Result<()> {
/// use serde_dhall::{SimpleType, StaticType};
///
/// #[derive(StaticType)]
/// struct Foo {
///     x: bool,
///     y: Vec<u64>,
/// }
///
/// let ty: SimpleType =
///     serde_dhall::from_str("{ x: Bool, y: List Natural }").parse()?;
///
/// assert_eq!(Foo::static_type(), ty);
/// # Ok(())
/// # }
/// ```
///
/// ```rust
/// # fn main() -> serde_dhall::Result<()> {
/// use std::collections::HashMap;
/// use serde_dhall::SimpleType;
///
/// let ty: SimpleType =
///     serde_dhall::from_str("{ x: Natural, y: Natural }").parse()?;
///
/// let mut map = HashMap::new();
/// map.insert("x".to_string(), SimpleType::Natural);
/// map.insert("y".to_string(), SimpleType::Natural);
/// assert_eq!(ty, SimpleType::Record(map));
/// # Ok(())
/// # }
/// ```
///
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SimpleType {
    /// Corresponds to the Dhall type `Bool`
    Bool,
    /// Corresponds to the Dhall type `Natural`
    Natural,
    /// Corresponds to the Dhall type `Integer`
    Integer,
    /// Corresponds to the Dhall type `Double`
    Double,
    /// Corresponds to the Dhall type `Text`
    Text,
    /// Corresponds to the Dhall type `Optional T`
    Optional(Box<SimpleType>),
    /// Corresponds to the Dhall type `List T`
    List(Box<SimpleType>),
    /// Corresponds to the Dhall type `{ x : T, y : U }`
    Record(HashMap<String, SimpleType>),
    /// Corresponds to the Dhall type `< x : T | y : U >`
    Union(HashMap<String, Option<SimpleType>>),
}

impl Value {
    pub(crate) fn from_nir(x: &Nir) -> Self {
        Value {
            hir: x.to_hir_noenv(),
            as_simple_val: SimpleValue::from_nir(x),
            as_simple_ty: SimpleType::from_nir(x),
        }
    }

    pub(crate) fn as_hir(&self) -> &Hir {
        &self.hir
    }

    /// Converts a Value into a SimpleValue.
    pub(crate) fn to_simple_value(&self) -> Option<SimpleValue> {
        self.as_simple_val.clone()
    }

    /// Converts a Value into a SimpleType.
    pub(crate) fn to_simple_type(&self) -> Option<SimpleType> {
        self.as_simple_ty.clone()
    }

    /// Converts a value back to the corresponding AST expression.
    pub(crate) fn to_expr(&self) -> Expr {
        self.hir.to_expr(Default::default())
    }
}

impl SimpleValue {
    pub(crate) fn from_nir(nir: &Nir) -> Option<Self> {
        Some(match nir.kind() {
            NirKind::Num(lit) => SimpleValue::Num(lit.clone()),
            NirKind::TextLit(x) => SimpleValue::Text(
                x.as_text()
                    .expect("Normal form should ensure the text is a string"),
            ),
            NirKind::EmptyOptionalLit(_) => SimpleValue::Optional(None),
            NirKind::NEOptionalLit(x) => {
                SimpleValue::Optional(Some(Box::new(Self::from_nir(x)?)))
            }
            NirKind::EmptyListLit(t) => {
                // Detect and handle the special records that make assoc maps
                if let NirKind::RecordType(kts) = t.kind() {
                    if kts.len() == 2
                        && kts.contains_key("mapKey")
                        && kts.contains_key("mapValue")
                    {
                        return Some(SimpleValue::Record(Default::default()));
                    }
                }
                SimpleValue::List(vec![])
            }
            NirKind::NEListLit(xs) => {
                // Detect and handle the special records that make assoc maps
                if let NirKind::RecordLit(kvs) = xs[0].kind() {
                    if kvs.len() == 2
                        && kvs.contains_key("mapKey")
                        && kvs.contains_key("mapValue")
                    {
                        let convert_entry = |x: &Nir| match x.kind() {
                            NirKind::RecordLit(kvs) => {
                                let k = match kvs.get("mapKey").unwrap().kind()
                                {
                                    NirKind::TextLit(t)
                                        if t.as_text().is_some() =>
                                    {
                                        t.as_text().unwrap()
                                    }
                                    // TODO
                                    _ => panic!(
                                        "Expected `mapKey` to be a text \
                                         literal"
                                    ),
                                };
                                let v = Self::from_nir(
                                    kvs.get("mapValue").unwrap(),
                                )?;
                                Some((k, v))
                            }
                            _ => unreachable!("Internal type error"),
                        };
                        return Some(SimpleValue::Record(
                            xs.iter()
                                .map(convert_entry)
                                .collect::<Option<_>>()?,
                        ));
                    }
                }
                SimpleValue::List(
                    xs.iter().map(Self::from_nir).collect::<Option<_>>()?,
                )
            }
            NirKind::RecordLit(kvs) => SimpleValue::Record(
                kvs.iter()
                    .map(|(k, v)| Some((k.to_string(), Self::from_nir(v)?)))
                    .collect::<Option<_>>()?,
            ),
            NirKind::UnionLit(field, x, _) => SimpleValue::Union(
                field.into(),
                Some(Box::new(Self::from_nir(x)?)),
            ),
            NirKind::UnionConstructor(field, ty)
                if ty.get(field).map(|f| f.is_some()) == Some(false) =>
            {
                SimpleValue::Union(field.into(), None)
            }
            _ => return None,
        })
    }
}

impl SimpleType {
    pub(crate) fn from_nir(nir: &Nir) -> Option<Self> {
        Some(match nir.kind() {
            NirKind::BuiltinType(b) => match b {
                Builtin::Bool => SimpleType::Bool,
                Builtin::Natural => SimpleType::Natural,
                Builtin::Integer => SimpleType::Integer,
                Builtin::Double => SimpleType::Double,
                Builtin::Text => SimpleType::Text,
                _ => unreachable!(),
            },
            NirKind::OptionalType(t) => {
                SimpleType::Optional(Box::new(Self::from_nir(t)?))
            }
            NirKind::ListType(t) => {
                SimpleType::List(Box::new(Self::from_nir(t)?))
            }
            NirKind::RecordType(kts) => SimpleType::Record(
                kts.iter()
                    .map(|(k, v)| Some((k.into(), Self::from_nir(v)?)))
                    .collect::<Option<_>>()?,
            ),
            NirKind::UnionType(kts) => SimpleType::Union(
                kts.iter()
                    .map(|(k, v)| {
                        Some((
                            k.into(),
                            v.as_ref()
                                .map(|v| Ok(Self::from_nir(v)?))
                                .transpose()?,
                        ))
                    })
                    .collect::<Option<_>>()?,
            ),
            _ => return None,
        })
    }

    pub(crate) fn to_value(&self) -> Value {
        Value {
            hir: self.to_hir(),
            as_simple_val: None,
            as_simple_ty: Some(self.clone()),
        }
    }
    pub(crate) fn to_hir(&self) -> Hir {
        let hir = |k| Hir::new(HirKind::Expr(k), Span::Artificial);
        hir(match self {
            SimpleType::Bool => ExprKind::Builtin(Builtin::Bool),
            SimpleType::Natural => ExprKind::Builtin(Builtin::Natural),
            SimpleType::Integer => ExprKind::Builtin(Builtin::Integer),
            SimpleType::Double => ExprKind::Builtin(Builtin::Double),
            SimpleType::Text => ExprKind::Builtin(Builtin::Text),
            SimpleType::Optional(t) => ExprKind::Op(OpKind::App(
                hir(ExprKind::Builtin(Builtin::Optional)),
                t.to_hir(),
            )),
            SimpleType::List(t) => ExprKind::Op(OpKind::App(
                hir(ExprKind::Builtin(Builtin::List)),
                t.to_hir(),
            )),
            SimpleType::Record(kts) => ExprKind::RecordType(
                kts.iter()
                    .map(|(k, t)| (k.as_str().into(), t.to_hir()))
                    .collect(),
            ),
            SimpleType::Union(kts) => ExprKind::UnionType(
                kts.iter()
                    .map(|(k, t)| {
                        (k.as_str().into(), t.as_ref().map(|t| t.to_hir()))
                    })
                    .collect(),
            ),
        })
    }
}

impl Sealed for Value {}
impl Sealed for SimpleValue {}
impl Sealed for SimpleType {}

impl FromDhall for Value {
    fn from_dhall(v: &Value) -> Result<Self> {
        Ok(v.clone())
    }
}
impl FromDhall for SimpleValue {
    fn from_dhall(v: &Value) -> Result<Self> {
        v.to_simple_value().ok_or_else(|| {
            Error(ErrorKind::Deserialize(format!(
                "this cannot be deserialized into a simple type: {}",
                v
            )))
        })
    }
}
impl FromDhall for SimpleType {
    fn from_dhall(v: &Value) -> Result<Self> {
        v.to_simple_type().ok_or_else(|| {
            Error(ErrorKind::Deserialize(format!(
                "this cannot be deserialized into a simple type: {}",
                v
            )))
        })
    }
}

impl Eq for Value {}
impl PartialEq for Value {
    fn eq(&self, other: &Self) -> bool {
        self.hir == other.hir
    }
}
impl std::fmt::Display for Value {
    fn fmt(
        &self,
        f: &mut std::fmt::Formatter,
    ) -> std::result::Result<(), std::fmt::Error> {
        self.to_expr().fmt(f)
    }
}