summaryrefslogtreecommitdiff
path: root/dhall/src/traits/deserialize.rs
blob: 43eb2ac2d454c668727308d7f1daea00563c8a43 (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
use crate::error::*;
use crate::expr::*;

/// 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.
pub trait Deserialize<'de>: Sized {
    /// See [dhall::de::from_str][crate::de::from_str]
    fn from_str(s: &'de str, ty: Option<&Type>) -> Result<Self>;
}

impl<'de: 'a, 'a> Deserialize<'de> for Parsed<'a> {
    /// Simply parses the provided string. Ignores the
    /// provided type.
    fn from_str(s: &'de str, _: Option<&Type>) -> Result<Self> {
        Ok(Parsed::parse_str(s)?)
    }
}

impl<'de: 'a, 'a> Deserialize<'de> for Resolved<'a> {
    /// Parses and resolves the provided string. Ignores the
    /// provided type.
    fn from_str(s: &'de str, ty: Option<&Type>) -> Result<Self> {
        Ok(Parsed::from_str(s, ty)?.resolve()?)
    }
}

impl<'de: 'a, 'a> Deserialize<'de> for Typed<'a> {
    /// Parses, resolves and typechecks the provided string.
    fn from_str(s: &'de str, ty: Option<&Type>) -> Result<Self> {
        let resolved = Resolved::from_str(s, ty)?;
        match ty {
            None => Ok(resolved.typecheck()?),
            Some(t) => Ok(resolved.typecheck_with(t)?),
        }
    }
}

impl<'de: 'a, 'a> Deserialize<'de> for Normalized<'a> {
    /// Parses, resolves, typechecks and normalizes the provided string.
    fn from_str(s: &'de str, ty: Option<&Type>) -> Result<Self> {
        Ok(Typed::from_str(s, ty)?.normalize())
    }
}

impl<'de: 'a, 'a> Deserialize<'de> for Type<'a> {
    fn from_str(s: &'de str, ty: Option<&Type>) -> Result<Self> {
        Ok(Normalized::from_str(s, ty)?.into_type())
    }
}