-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy patheval.rs
308 lines (280 loc) · 10 KB
/
eval.rs
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
//! The evaluator, based on normalisation by evaluation.
//!
//! Thanks to the following people for providing helpful material in that
//! direction:
//!
//! - [Normalisation by Evaluation] by David Christiansen
//! - [Building Fast Functional Languages Fast] by Edward Kmett
//! - Gabriella Gonzalez's fantastic [Fall-from-Grace] project
//!
//! [Normalisation by Evaluation]: https://www.youtube.com/watch?v=CpADWJa-f28&pp=ygUbbm9ybWFsaXNhdGlvbiBieSBldmFsdWF0aW9u
//! [Building Fast Functional Languages Fast]: https://www.youtube.com/watch?v=gbmURWs_SaU&pp=ygUiYnVpbGRpbmcgZnVuY3Rpb25hbCBsYW5ndWFnZXMgZmFzdA%3D%3D
//! [Fall-From-Grace]: https://github.com/Gabriella439/grace
use std::{collections::BTreeMap, error::Error, fmt::Display};
use self::stdlib::Builtin;
use crate::{expr::{app, de_bruijn::{DBEnv, DBVar}, if_then_else, λ, Const, Expr}, r#type::expr::TCExpr, util::style};
pub mod stdlib;
#[cfg(test)]
pub mod test;
impl TCExpr {
/// Evaluate a type-checked expression into its normal form.
pub fn eval(&self, env: &BTreeMap<&str, Builtin>) -> Result<Expr, EvalError> {
self
.expr
.to_sem(&DBEnv::from_iter_with(env.clone(), Sem::SBuiltin))?
.reify()
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum EvalError {
WrongIndex(String, Expr),
}
impl Error for EvalError {}
impl Display for EvalError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
EvalError::WrongIndex(ix, e) => write!(
f,
"index {} out of scope in expression {}",
style(ix),
style(e)
),
}
}
}
macro_rules! eval_err {
(WrongIndex, $ix:expr, $x:expr $(,)?) => {
EvalError::WrongIndex($ix.to_string(), $x.reify()?)
};
}
fn num_vars(names: &[String], var: &str) -> isize {
names.iter().filter(|&v| v == var).count() as isize
}
/// Summon a new variable from the void.
fn fresh(var: &str, names: &[String]) -> Sem {
Sem::Var(DBVar::from_pair(var, num_vars(names, var)))
}
/// A semantic representation of a term.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum Sem {
Var(DBVar),
SConst(Const),
Closure(DBEnv<Sem>, String, Box<Expr>),
App(Box<Sem>, Box<Sem>),
Arr(Vec<Sem>),
Obj(BTreeMap<Sem, Sem>),
IfThenElse(Box<Sem>, Box<Sem>, Box<Sem>),
SBuiltin(Builtin),
}
impl Sem {
fn app(&self, s2: &Sem) -> Sem {
Sem::App(Box::new(self.clone()), Box::new(s2.clone()))
}
fn str(s: &str) -> Self { Self::SConst(Const::String(s.to_string())) }
fn is_truthy(&self) -> bool {
!matches!(
self,
Sem::SConst(Const::Bool(false)) | Sem::SConst(Const::Null)
)
}
}
impl Expr {
/// Convert an expression into a semantic version of itself; i.e., evaluate
/// the expression, but leave it in the semantic representation.
fn to_sem(&self, env: &DBEnv<Sem>) -> Result<Sem, EvalError> {
match self {
Expr::Const(c) => Ok(Sem::SConst(c.clone())),
Expr::Lam(h, b) => Ok(Sem::Closure(env.clone(), h.to_string(), b.clone())),
Expr::App(f, x) => f.to_sem(env)?.apply(&x.to_sem(env)?),
Expr::Arr(xs) => Ok(Sem::Arr(xs.iter().flat_map(|x| x.to_sem(env)).collect())),
Expr::Obj(ob) => Ok(Sem::Obj(
ob.iter()
.flat_map(|(k, v)| -> Result<(Sem, Sem), EvalError> {
try { (k.to_sem(env)?, v.to_sem(env)?) }
})
.collect(),
)),
Expr::Builtin(f) => Ok(Sem::SBuiltin(*f)),
Expr::Var(v) => Ok(env.lookup_var(v).expect(
"Variable {v} not in scope—you've hit a bug in the type checker! Please report \
this to the appropriate places.",
)),
Expr::IfThenElse(i, t, e) => match i.to_sem(env) {
Err(_) | Ok(Sem::SConst(Const::Bool(false))) | Ok(Sem::SConst(Const::Null)) => {
e.to_sem(env)
},
Ok(Sem::SConst(_)) => t.to_sem(env),
Ok(isem) => Ok(Sem::IfThenElse(
Box::new(isem), // Evaluate further
Box::new(t.to_sem(env)?),
Box::new(e.to_sem(env)?),
)),
},
// Let's hope that type-checking was successful! XXX: Perhaps it is
// better overall to have a desugared expression type in which there
// simply is no annotation variant.
Expr::Ann(e, _) => e.to_sem(env),
}
}
}
impl Sem {
/// Apply self to x. This includes evaluating closures, as well as builtin
/// functions.
fn apply(&self, x: &Sem) -> Result<Sem, EvalError> {
use Builtin::*;
use Sem::*;
match (self, x) {
// Closure
(Closure(env, v, b), _) => {
env.add_mut(v, x); // Associate bound variable v to x.
b.to_sem(env)
},
// Small builtin
(SBuiltin(Id), _) => Ok(x.clone()),
(SBuiltin(_), _) => Ok(self.app(x)),
(App(box SBuiltin(BConst), this), _) => Ok(*this.clone()),
// Get
(App(box SBuiltin(Get), box SConst(Const::Num(i))), Arr(xs)) => xs
.get(**i as usize)
.ok_or(eval_err!(WrongIndex, i, x))
.cloned(),
(App(box SBuiltin(Get), box SConst(Const::String(s))), Obj(ob)) => ob
.get(&Sem::str(s))
.ok_or(eval_err!(WrongIndex, s, x))
.cloned(),
// Set
(App(box App(box SBuiltin(Set), box SConst(Const::Num(i))), box to), Arr(xs)) => {
let mut ys = xs.clone();
*ys
.get_mut(**i as usize)
.ok_or(eval_err!(WrongIndex, i, x))? = to.clone();
Ok(Arr(ys))
},
(
App(box App(box SBuiltin(Set), box SConst(Const::String(s))), box to),
Obj(ob),
) => {
let mut res = ob.clone();
*res
.get_mut(&Sem::str(s))
.ok_or(eval_err!(WrongIndex, s, x))? = to.clone();
Ok(Obj(res))
},
// Map
(App(box SBuiltin(Map), closure), Arr(xs)) => {
Ok(Arr(xs.iter().flat_map(|x| closure.apply(x)).collect()))
},
(App(box SBuiltin(Map), closure), Obj(ob)) => Ok(Obj(
ob.iter()
.flat_map(|(k, v)| -> Result<(Sem, Sem), EvalError> {
try { (k.clone(), closure.apply(v)?) }
})
.collect(),
)),
// Filter
(App(box SBuiltin(Filter), closure), Arr(xs)) => Ok(Arr(
xs.iter()
.filter_map(|x| {
if closure.apply(x).ok()?.is_truthy() {
Some(x.clone())
} else {
None
}
})
.collect(),
)),
(App(box SBuiltin(Filter), closure), Obj(ob)) => Ok(Obj(
ob.iter()
.filter_map(|(k, v)| {
if closure.apply(v).ok()?.is_truthy() {
Some((k.clone(), v.clone()))
} else {
None
}
})
.collect(),
)),
// Foldl
(App(box App(box SBuiltin(Fold), closure), init), Arr(xs)) => xs
.iter()
.try_fold(*init.clone(), |acc, x| closure.apply(&acc)?.apply(x)),
(App(box App(box SBuiltin(Fold), closure), init), Obj(ob)) => ob
.iter()
.try_fold(*init.clone(), |acc, (_, v)| closure.apply(&acc)?.apply(v)),
// Binary operators
(App(box SBuiltin(Add), box SConst(Const::Num(n))), SConst(Const::Num(m))) => {
Ok(SConst(Const::Num(*n + *m)))
},
(
App(box SBuiltin(Add), box SConst(Const::String(s))),
SConst(Const::String(t)),
) => Ok(SConst(Const::String(s.clone() + t.as_str()))),
(App(box SBuiltin(Sub), box SConst(Const::Num(n))), SConst(Const::Num(m))) => {
Ok(SConst(Const::Num(*n - *m)))
},
(App(box SBuiltin(Mul), box SConst(Const::Num(n))), SConst(Const::Num(m))) => {
Ok(SConst(Const::Num(*n * *m)))
},
(App(box SBuiltin(Div), box SConst(Const::Num(n))), SConst(Const::Num(m))) => {
Ok(SConst(Const::Num(*n / *m)))
},
(App(box SBuiltin(Eq), a), b) => Ok(SConst(Const::Bool(**a == *b))),
(App(box SBuiltin(Neq), a), b) => Ok(SConst(Const::Bool(**a != *b))),
(App(box SBuiltin(Le), a), b) => Ok(SConst(Const::Bool(**a < *b))),
(App(box SBuiltin(Leq), a), b) => Ok(SConst(Const::Bool(**a <= *b))),
(App(box SBuiltin(Ge), a), b) => Ok(SConst(Const::Bool(**a > *b))),
(App(box SBuiltin(Geq), a), b) => Ok(SConst(Const::Bool(**a >= *b))),
// Otherwise
_ => Ok(self.app(x)),
}
}
/// Reify a semantic expression.
fn reify(&self) -> Result<Expr, EvalError> {
fn go(names: &mut Vec<String>, sem: &Sem) -> Result<Expr, EvalError> {
match sem {
Sem::Var(DBVar { name, level }) => Ok(Expr::Var(
// Since we are type-checked, this is never smaller than 0.
// Also see [Note closure var counts]
DBVar::from_pair(name.as_str(), num_vars(names, name) - level),
)),
Sem::SConst(c) => Ok(Expr::Const(c.clone())),
Sem::Closure(env, v, b) => {
names.push(v.clone());
env.add_mut(v, &fresh(v, names)); // See [Note closure var counts]
Ok(λ(v, go(names, &b.to_sem(env)?)?))
},
Sem::App(f, x) => Ok(app(go(names, f)?, go(names, x)?)),
Sem::Arr(xs) => Ok(Expr::Arr(xs.iter().flat_map(|x| go(names, x)).collect())),
Sem::Obj(ob) => Ok(Expr::Obj(
ob.iter()
.flat_map(|(k, v)| -> Result<(Expr, Expr), EvalError> {
try { (go(names, k)?, go(names, v)?) }
})
.collect(),
)),
Sem::IfThenElse(i, t, e) => {
Ok(if_then_else(go(names, i)?, go(names, t)?, go(names, e)?))
},
Sem::SBuiltin(f) => Ok(Expr::Builtin(*f)),
}
}
go(&mut Vec::new(), self)
}
}
/* [Note closure var counts]
Given the expression
names.push(v.clone());
env.add_mut(v, &fresh(v, names));
in a closure semantic expression, we already count the name of the inner
bound variable towards its index in the environment. This means that the
accompanying retransformation for the variable looks like
num_vars(names, name) - level
If we instead turned this around and had
let freshv = fresh(v, names);
names.push(v.clone());
env.add_mut(v, &freshv);
then we do *not* do that and would need a different retransformation:
num_vars(names, name) - level - 1
Note: I hope I never run into the kinds of troubles where this information
is necessary.
*/