summaryrefslogtreecommitdiff
path: root/dhall/src/expr.rs
blob: b0b6215f6a11624f504f9d55aaae6513085d7199 (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
use crate::imports::ImportRoot;
use crate::normalize::{Thunk, Value};
use dhall_syntax::*;
use std::marker::PhantomData;

macro_rules! derive_other_traits {
    ($ty:ident) => {
        impl<'a> std::cmp::PartialEq for $ty<'a> {
            fn eq(&self, other: &Self) -> bool {
                self.0 == other.0
            }
        }

        impl<'a> std::cmp::Eq for $ty<'a> {}

        impl<'a> std::fmt::Display for $ty<'a> {
            fn fmt(
                &self,
                f: &mut std::fmt::Formatter,
            ) -> Result<(), std::fmt::Error> {
                self.0.fmt(f)
            }
        }
    };
}

#[derive(Debug, Clone)]
pub(crate) struct Parsed<'a>(
    pub(crate) SubExpr<Span<'a>, Import>,
    pub(crate) ImportRoot,
);
derive_other_traits!(Parsed);

#[derive(Debug, Clone)]
pub(crate) struct Resolved<'a>(
    pub(crate) SubExpr<Span<'a>, Normalized<'static>>,
);
derive_other_traits!(Resolved);

pub(crate) use self::typed::TypedInternal;

#[derive(Debug, Clone)]
pub(crate) struct Typed<'a>(
    pub(crate) TypedInternal,
    pub(crate) PhantomData<&'a ()>,
);

#[derive(Debug, Clone)]
pub(crate) struct Normalized<'a>(
    pub(crate) TypedInternal,
    pub(crate) PhantomData<&'a ()>,
);

impl<'a> std::cmp::PartialEq for Normalized<'a> {
    fn eq(&self, other: &Self) -> bool {
        self.to_expr() == other.to_expr()
    }
}

impl<'a> std::cmp::Eq for Normalized<'a> {}

impl<'a> std::fmt::Display for Normalized<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        self.to_expr().fmt(f)
    }
}

mod typed {
    use super::{Type, Typed};
    use crate::normalize::{Thunk, Value};
    use crate::typecheck::{
        TypeError, TypeInternal, TypeMessage, TypecheckContext,
    };
    use dhall_syntax::{Const, Label, SubExpr, V, X};
    use std::borrow::Cow;
    use std::marker::PhantomData;

    #[derive(Debug, Clone)]
    pub(crate) enum TypedInternal {
        // The `Sort` higher-kinded type doesn't have a type
        Sort,
        // Any other value, along with its type
        Value(Thunk, Option<Type<'static>>),
    }

    impl TypedInternal {
        pub(crate) fn from_thunk_and_type(th: Thunk, t: Type<'static>) -> Self {
            TypedInternal::Value(th, Some(t))
        }

        pub(crate) fn from_thunk_untyped(th: Thunk) -> Self {
            TypedInternal::Value(th, None)
        }

        // TODO: Avoid cloning if possible
        pub(crate) fn to_value(&self) -> Value {
            match self {
                TypedInternal::Value(th, _) => th.to_value(),
                TypedInternal::Sort => Value::Const(Const::Sort),
            }
        }

        pub(crate) fn to_expr(&self) -> SubExpr<X, X> {
            self.to_value().normalize_to_expr()
        }

        pub(crate) fn to_thunk(&self) -> Thunk {
            match self {
                TypedInternal::Value(th, _) => th.clone(),
                TypedInternal::Sort => {
                    Thunk::from_value(Value::Const(Const::Sort))
                }
            }
        }

        pub(crate) fn to_type(&self) -> Type<'static> {
            match self {
                TypedInternal::Sort => Type(TypeInternal::Const(Const::Sort)),
                TypedInternal::Value(th, _) => match &*th.as_value() {
                    Value::Const(c) => Type(TypeInternal::Const(*c)),
                    _ => Type(TypeInternal::Typed(Box::new(Typed(
                        self.clone(),
                        PhantomData,
                    )))),
                },
            }
        }

        pub(crate) fn get_type(
            &self,
        ) -> Result<Cow<'_, Type<'static>>, TypeError> {
            match self {
                TypedInternal::Value(_, Some(t)) => Ok(Cow::Borrowed(t)),
                TypedInternal::Value(_, None) => Err(TypeError::new(
                    &TypecheckContext::new(),
                    TypeMessage::Untyped,
                )),
                TypedInternal::Sort => Err(TypeError::new(
                    &TypecheckContext::new(),
                    TypeMessage::Sort,
                )),
            }
        }

        pub(crate) fn shift(&self, delta: isize, var: &V<Label>) -> Self {
            match self {
                TypedInternal::Value(th, t) => TypedInternal::Value(
                    th.shift(delta, var),
                    t.as_ref().map(|x| x.shift(delta, var)),
                ),
                TypedInternal::Sort => TypedInternal::Sort,
            }
        }

        pub(crate) fn subst_shift(
            &self,
            var: &V<Label>,
            val: &Typed<'static>,
        ) -> Self {
            match self {
                TypedInternal::Value(th, t) => TypedInternal::Value(
                    th.subst_shift(var, val),
                    t.as_ref().map(|x| x.subst_shift(var, val)),
                ),
                TypedInternal::Sort => TypedInternal::Sort,
            }
        }
    }
}

/// A Dhall expression representing a simple type.
///
/// This captures what is usually simply called a "type", like
/// `Bool`, `{ x: Integer }` or `Natural -> Text`.
///
/// For a more general notion of "type", see [Type].
#[derive(Debug, Clone)]
pub struct SimpleType<'a>(
    pub(crate) SubExpr<X, X>,
    pub(crate) PhantomData<&'a ()>,
);
derive_other_traits!(SimpleType);

pub(crate) use crate::typecheck::TypeInternal;

/// A Dhall expression representing a (possibly higher-kinded) type.
///
/// This includes [SimpleType]s but also higher-kinded expressions like
/// `Type`, `Kind` and `{ x: Type }`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Type<'a>(pub(crate) TypeInternal<'a>);

impl<'a> std::fmt::Display for Type<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
        self.to_normalized().fmt(f)
    }
}

// Exposed for the macros
#[doc(hidden)]
impl<'a> From<SimpleType<'a>> for SubExpr<X, X> {
    fn from(x: SimpleType<'a>) -> SubExpr<X, X> {
        x.0
    }
}

// Exposed for the macros
#[doc(hidden)]
impl<'a> From<SubExpr<X, X>> for SimpleType<'a> {
    fn from(x: SubExpr<X, X>) -> SimpleType<'a> {
        SimpleType(x, PhantomData)
    }
}

// Exposed for the macros
#[doc(hidden)]
impl<'a> From<Normalized<'a>> for Typed<'a> {
    fn from(x: Normalized<'a>) -> Typed<'a> {
        Typed(x.0, x.1)
    }
}

impl<'a> Normalized<'a> {
    pub(crate) fn from_thunk_and_type(th: Thunk, t: Type<'static>) -> Self {
        Normalized(TypedInternal::from_thunk_and_type(th, t), PhantomData)
    }
    // Deprecated
    pub(crate) fn as_expr(&self) -> SubExpr<X, X> {
        self.0.to_expr()
    }
    pub(crate) fn to_expr(&self) -> SubExpr<X, X> {
        self.0.to_expr()
    }
    pub(crate) fn to_value(&self) -> Value {
        self.0.to_value()
    }
    #[allow(dead_code)]
    pub(crate) fn unnote<'b>(self) -> Normalized<'b> {
        Normalized(self.0, PhantomData)
    }
}

impl<'a> Typed<'a> {
    pub(crate) fn from_thunk_and_type(th: Thunk, t: Type<'static>) -> Self {
        Typed(TypedInternal::from_thunk_and_type(th, t), PhantomData)
    }
    pub(crate) fn from_thunk_untyped(th: Thunk) -> Self {
        Typed(TypedInternal::from_thunk_untyped(th), PhantomData)
    }
    pub(crate) fn const_sort() -> Self {
        Typed(TypedInternal::Sort, PhantomData)
    }
}