mest-core 0.1.0

Core language library for the Mest programming language
Documentation
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
use bumpalo::Bump;
use chumsky::span::SimpleSpan;
use lasso::{Rodeo, Spur};
use std::{cell::RefCell, ops::Deref, rc::Rc};

use crate::thunk::Thunk;

#[derive(Debug, Clone)]
pub enum Literal {
    Int(i64),
    Float(f64),
    Bool(bool),
}

#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
pub struct Ident(pub Spur);

#[derive(Debug, Clone)]
pub enum BinOp {
    Eq,
    NotEq,
    Lt,
    Gt,
    Le,
    Ge,
    And,
    Or,
    Add,
    Sub,
    Mul,
    Div,
    Pow,
}

#[derive(Debug, Clone)]
pub enum UnaryOp {
    Neg,
    Not,
}

#[derive(Debug, Clone)]
pub enum Pat<'bump> {
    Wildcard,
    Var(Ident),
    Lit(Literal),
    Or(&'bump Pat<'bump>, &'bump Pat<'bump>),
}

#[derive(Debug, Clone, Copy)]
pub struct Expr<'bump> {
    pub kind: &'bump ExprKind<'bump>,
    pub span: SimpleSpan,
}

impl<'bump> Deref for Expr<'bump> {
    type Target = ExprKind<'bump>;

    fn deref(&self) -> &Self::Target {
        &self.kind
    }
}

#[derive(Debug, Clone)]
pub enum ExprKind<'bump> {
    Literal(Literal),
    Ident(Ident),
    If {
        cond: Expr<'bump>,
        then_expr: Expr<'bump>,
        else_expr: Expr<'bump>,
    },
    BinOp {
        op: BinOp,
        lhs: Expr<'bump>,
        rhs: Expr<'bump>,
    },
    UnaryOp {
        op: UnaryOp,
        rhs: Expr<'bump>,
    },
    Let {
        name: Ident,
        value: Expr<'bump>,
        body: Expr<'bump>,
        rec: bool,
    },
    Match {
        scrutinee: Expr<'bump>,
        arms: &'bump [(Pat<'bump>, Expr<'bump>)],
    },
    Abs {
        param: Ident,
        body: Expr<'bump>,
    },
    App {
        func: Expr<'bump>,
        arg: Expr<'bump>,
    },
}

pub type Env<'bump> = im::HashMap<Ident, Thunk<'bump>>;

#[derive(Debug, Clone)]
pub enum Value<'bump> {
    Int(i64),
    Float(f64),
    Bool(bool),
    Closure {
        param: Ident,
        body: Expr<'bump>,
        env: Env<'bump>,
    },
}

impl std::fmt::Display for Value<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Value::Int(n) => write!(f, "{n}"),
            Value::Float(n) => write!(f, "{n}"),
            Value::Bool(b) => write!(f, "{b}"),
            Value::Closure { .. } => write!(f, "<closure>"),
        }
    }
}

#[derive(Debug, Clone)]
pub enum EvalError {
    UnboundVariable(String),
    TypeMismatch {
        expected: &'static str,
        got: &'static str,
    },
    DivisionByZero,
    NotAFunction,
    NonExhaustiveMatch,
}

impl std::fmt::Display for EvalError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            EvalError::NonExhaustiveMatch => write!(f, "non-exhaustive match"),
            EvalError::UnboundVariable(name) => write!(f, "unbound variable `{name}`"),
            EvalError::TypeMismatch { expected, got } => {
                write!(f, "type mismatch: expected {expected}, got {got}")
            }
            EvalError::DivisionByZero => write!(f, "division by zero"),
            EvalError::NotAFunction => write!(f, "applied a non-function value"),
        }
    }
}

fn type_name(v: &Value) -> &'static str {
    match v {
        Value::Int(_) => "int",
        Value::Float(_) => "float",
        Value::Bool(_) => "bool",
        Value::Closure { .. } => "closure",
    }
}

impl<'bump> ExprKind<'bump> {
    fn node(expr: &'bump ExprKind<'bump>, span: SimpleSpan) -> Expr<'bump> {
        Expr { kind: expr, span }
    }

    pub fn literal(bump: &'bump Bump, span: SimpleSpan, lit: Literal) -> Expr<'bump> {
        Self::node(bump.alloc(ExprKind::Literal(lit)), span)
    }

    pub fn ident(bump: &'bump Bump, span: SimpleSpan, name: Ident) -> Expr<'bump> {
        Self::node(bump.alloc(ExprKind::Ident(name)), span)
    }

    pub fn if_expr(
        bump: &'bump Bump,
        span: SimpleSpan,
        cond: Expr<'bump>,
        then_expr: Expr<'bump>,
        else_expr: Expr<'bump>,
    ) -> Expr<'bump> {
        Self::node(
            bump.alloc(ExprKind::If {
                cond,
                then_expr,
                else_expr,
            }),
            span,
        )
    }

    pub fn binop(
        bump: &'bump Bump,
        span: SimpleSpan,
        op: BinOp,
        lhs: Expr<'bump>,
        rhs: Expr<'bump>,
    ) -> Expr<'bump> {
        Self::node(bump.alloc(ExprKind::BinOp { op, lhs, rhs }), span)
    }

    pub fn unaryop(
        bump: &'bump Bump,
        span: SimpleSpan,
        op: UnaryOp,
        rhs: Expr<'bump>,
    ) -> Expr<'bump> {
        Self::node(bump.alloc(ExprKind::UnaryOp { op, rhs }), span)
    }

    pub fn let_expr(
        bump: &'bump Bump,
        span: SimpleSpan,
        name: Ident,
        value: Expr<'bump>,
        body: Expr<'bump>,
        rec: bool,
    ) -> Expr<'bump> {
        Self::node(
            bump.alloc(ExprKind::Let {
                name,
                value,
                body,
                rec,
            }),
            span,
        )
    }

    pub fn match_expr(
        bump: &'bump Bump,
        span: SimpleSpan,
        scrutinee: Expr<'bump>,
        arms: &'bump [(Pat<'bump>, Expr<'bump>)],
    ) -> Expr<'bump> {
        Self::node(bump.alloc(ExprKind::Match { scrutinee, arms }), span)
    }

    pub fn lambda(
        bump: &'bump Bump,
        span: SimpleSpan,
        param: Ident,
        body: Expr<'bump>,
    ) -> Expr<'bump> {
        Self::node(bump.alloc(ExprKind::Abs { param, body }), span)
    }

    pub fn app(
        bump: &'bump Bump,
        span: SimpleSpan,
        func: Expr<'bump>,
        arg: Expr<'bump>,
    ) -> Expr<'bump> {
        Self::node(bump.alloc(ExprKind::App { func, arg }), span)
    }
}

impl<'bump> ExprKind<'bump> {
    fn force(thunk: &Thunk<'bump>, rodeo: &Rodeo) -> Result<Value<'bump>, EvalError> {
        thunk.force(rodeo)
    }

    pub fn thunk(expr: &'bump ExprKind<'bump>, env: &Env<'bump>) -> Thunk<'bump> {
        Thunk::new(expr, env.clone())
    }

    pub fn eval_lazy(
        &'bump self,
        env: &Env<'bump>,
        rodeo: &Rodeo,
    ) -> Result<Value<'bump>, EvalError> {
        match self {
            ExprKind::Literal(Literal::Bool(b)) => Ok(Value::Bool(*b)),
            ExprKind::Literal(Literal::Int(v)) => Ok(Value::Int(*v)),
            ExprKind::Literal(Literal::Float(v)) => Ok(Value::Float(*v)),

            ExprKind::Ident(ident) => {
                let thunk = env.get(ident).ok_or_else(|| {
                    EvalError::UnboundVariable(rodeo.resolve(&ident.0).to_owned())
                })?;
                Self::force(thunk, rodeo)
            }

            ExprKind::UnaryOp { op, rhs } => {
                let rhs = rhs.kind.eval_lazy(env, rodeo)?;
                match (op, rhs) {
                    (UnaryOp::Neg, Value::Int(n)) => Ok(Value::Int(-n)),
                    (UnaryOp::Neg, Value::Float(f)) => Ok(Value::Float(-f)),
                    (UnaryOp::Not, Value::Bool(b)) => Ok(Value::Bool(!b)),
                    (UnaryOp::Neg, v) => Err(EvalError::TypeMismatch {
                        expected: "number",
                        got: type_name(&v),
                    }),
                    (UnaryOp::Not, v) => Err(EvalError::TypeMismatch {
                        expected: "bool",
                        got: type_name(&v),
                    }),
                }
            }

            ExprKind::BinOp { op, lhs, rhs } => {
                let lhs = lhs.kind.eval_lazy(env, rodeo)?;
                let rhs = rhs.kind.eval_lazy(env, rodeo)?;
                Self::eval_binop(op, lhs, rhs)
            }

            ExprKind::Let {
                name,
                value,
                body,
                rec: true,
            } => {
                let rec_env = Rc::new(RefCell::new(env.clone()));
                let thunk = Thunk::new_shared(value.kind, Rc::clone(&rec_env));
                rec_env.borrow_mut().insert(*name, thunk.clone());
                let mut body_env = env.clone();
                body_env.insert(*name, thunk);
                body.kind.eval_lazy(&body_env, rodeo)
            }

            ExprKind::Let {
                name,
                value,
                body,
                rec: false,
            } => {
                let mut env = env.clone();
                env.insert(*name, Self::thunk(value.kind, &env));
                body.kind.eval_lazy(&env, rodeo)
            }

            ExprKind::Match { scrutinee, arms } => {
                let scrutinee_thunk = Thunk::new(scrutinee.kind, env.clone());
                for (pat, body) in arms.iter() {
                    let mut arm_env = env.clone();
                    if Self::match_pat(pat, &scrutinee_thunk, &mut arm_env, rodeo)? {
                        return body.kind.eval_lazy(&arm_env, rodeo);
                    }
                }
                Err(EvalError::NonExhaustiveMatch)
            }

            ExprKind::If {
                cond,
                then_expr,
                else_expr,
            } => match cond.kind.eval_lazy(env, rodeo)? {
                Value::Bool(true) => then_expr.kind.eval_lazy(env, rodeo),
                Value::Bool(false) => else_expr.kind.eval_lazy(env, rodeo),
                v => Err(EvalError::TypeMismatch {
                    expected: "bool",
                    got: type_name(&v),
                }),
            },

            ExprKind::Abs { param, body } => Ok(Value::Closure {
                param: *param,
                body: *body,
                env: env.clone(),
            }),

            ExprKind::App { func, arg } => {
                let func = func.kind.eval_lazy(env, rodeo)?;
                match func {
                    Value::Closure {
                        param,
                        body,
                        env: mut closure_env,
                    } => {
                        closure_env.insert(param, Self::thunk(arg.kind, env));
                        body.kind.eval_lazy(&closure_env, rodeo)
                    }
                    _ => Err(EvalError::NotAFunction),
                }
            }
        }
    }

    fn match_pat(
        pat: &Pat<'bump>,
        thunk: &Thunk<'bump>,
        env: &mut Env<'bump>,
        rodeo: &Rodeo,
    ) -> Result<bool, EvalError> {
        match pat {
            Pat::Wildcard => Ok(true),
            Pat::Var(name) => {
                env.insert(*name, thunk.clone());
                Ok(true)
            }
            Pat::Lit(lit) => {
                let val = thunk.force(rodeo)?;
                Ok(match (lit, &val) {
                    (Literal::Int(a), Value::Int(b)) => a == b,
                    (Literal::Float(a), Value::Float(b)) => a == b,
                    (Literal::Bool(a), Value::Bool(b)) => a == b,
                    _ => false,
                })
            }
            Pat::Or(a, b) => {
                let mut env_a = env.clone();
                if Self::match_pat(a, thunk, &mut env_a, rodeo)? {
                    *env = env_a;
                    Ok(true)
                } else {
                    Self::match_pat(b, thunk, env, rodeo)
                }
            }
        }
    }

    fn eval_binop(
        op: &BinOp,
        lhs: Value<'bump>,
        rhs: Value<'bump>,
    ) -> Result<Value<'bump>, EvalError> {
        match (op, &lhs, &rhs) {
            (BinOp::And, Value::Bool(l), Value::Bool(r)) => return Ok(Value::Bool(*l && *r)),
            (BinOp::Or, Value::Bool(l), Value::Bool(r)) => return Ok(Value::Bool(*l || *r)),
            (BinOp::And, _, _) | (BinOp::Or, _, _) => {
                return Err(EvalError::TypeMismatch {
                    expected: "bool",
                    got: type_name(&lhs),
                });
            }
            _ => {}
        }

        match op {
            BinOp::Eq => return Ok(Value::Bool(Self::values_equal(&lhs, &rhs)?)),
            BinOp::NotEq => return Ok(Value::Bool(!Self::values_equal(&lhs, &rhs)?)),
            _ => {}
        }

        match (lhs, rhs) {
            (Value::Int(l), Value::Int(r)) => Self::eval_int_binop(op, l, r),
            (Value::Float(l), Value::Float(r)) => Self::eval_float_binop(op, l, r),
            (Value::Int(l), Value::Float(r)) => Self::eval_float_binop(op, l as f64, r),
            (Value::Float(l), Value::Int(r)) => Self::eval_float_binop(op, l, r as f64),
            (lhs, _) => Err(EvalError::TypeMismatch {
                expected: "number",
                got: type_name(&lhs),
            }),
        }
    }

    fn values_equal(lhs: &Value, rhs: &Value) -> Result<bool, EvalError> {
        match (lhs, rhs) {
            (Value::Int(l), Value::Int(r)) => Ok(l == r),
            (Value::Float(l), Value::Float(r)) => Ok(l == r),
            (Value::Bool(l), Value::Bool(r)) => Ok(l == r),
            (Value::Int(l), Value::Float(r)) => Ok((*l as f64) == *r),
            (Value::Float(l), Value::Int(r)) => Ok(*l == (*r as f64)),
            (l, r) => Err(EvalError::TypeMismatch {
                expected: type_name(l),
                got: type_name(r),
            }),
        }
    }

    fn eval_int_binop(op: &BinOp, lhs: i64, rhs: i64) -> Result<Value<'bump>, EvalError> {
        match op {
            BinOp::Lt => return Ok(Value::Bool(lhs < rhs)),
            BinOp::Gt => return Ok(Value::Bool(lhs > rhs)),
            BinOp::Le => return Ok(Value::Bool(lhs <= rhs)),
            BinOp::Ge => return Ok(Value::Bool(lhs >= rhs)),
            _ => {}
        }

        Ok(Value::Int(match op {
            BinOp::Add => lhs + rhs,
            BinOp::Sub => lhs - rhs,
            BinOp::Mul => lhs * rhs,
            BinOp::Div => {
                if rhs == 0 {
                    return Err(EvalError::DivisionByZero);
                }
                lhs / rhs
            }
            BinOp::Pow => lhs.pow(rhs as u32),
            _ => unreachable!(),
        }))
    }

    fn eval_float_binop(op: &BinOp, lhs: f64, rhs: f64) -> Result<Value<'bump>, EvalError> {
        match op {
            BinOp::Lt => return Ok(Value::Bool(lhs < rhs)),
            BinOp::Gt => return Ok(Value::Bool(lhs > rhs)),
            BinOp::Le => return Ok(Value::Bool(lhs <= rhs)),
            BinOp::Ge => return Ok(Value::Bool(lhs >= rhs)),
            _ => {}
        }

        Ok(Value::Float(match op {
            BinOp::Add => lhs + rhs,
            BinOp::Sub => lhs - rhs,
            BinOp::Mul => lhs * rhs,
            BinOp::Div => {
                if rhs == 0.0 {
                    return Err(EvalError::DivisionByZero);
                }
                lhs / rhs
            }
            BinOp::Pow => lhs.powf(rhs),
            _ => unreachable!(),
        }))
    }
}