ravenlang 0.2.0

Language core for ravencheck.
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
use crate::{
    Binder1,
    BinderN,
    BType,
    Comp,
    CType,
    Literal,
    LogOpN,
    Op,
    OpCode,
    Sig,
    Val,
    VName,
    VType,
    Pattern,
};

use std::collections::HashMap;

#[derive(Clone,Debug)]
pub struct TypeContext {
    bindings: HashMap<VName, VType>,
    type_bindings: Vec<String>,
    sig: Sig,
}

impl TypeContext {
    pub fn new(sig: Sig) -> Self {
        TypeContext{
            bindings: HashMap::new(),
            type_bindings: Vec::new(),
            sig,
        }
    }
    pub fn new_types(sig: Sig, type_bindings: Vec<String>) -> Self {
        TypeContext{
            bindings: HashMap::new(),
            type_bindings,
            sig,
        }
    }
    fn plus(mut self, x: VName, t: VType) -> Self {
        self.bindings.insert(x,t);
        self
    }
    fn append(mut self, c: Vec<(VName,VType)>) -> Self {
        self.bindings.extend(c.into_iter());
        self
    }
    fn get(&self, x: &VName) -> Result<VType, TypeError> {
        match self.bindings.get(x) {
            Some(t) => Ok(t.clone()),
            None => Err(format!("Unbound identifier {:?}", x)),
        }
    }
}

type TypeError = String;

fn unwrap_one<T: Clone>(v: &Vec<T>) -> Result<T, TypeError> {
    if v.len() != 1 {
        Err(format!("Got multi-binder or multi-return"))
    } else {
        Ok(v[0].clone())
    }
}

impl Comp {
    pub fn type_check(&self, t: &CType, sig: &Sig) -> Result<(), TypeError> {
        let inferred = self.type_of(TypeContext::new(sig.clone()))?;
        if t == &inferred {
            Ok(())
        } else {
            Err(format!("Expected type {}, got {}", t.render(), inferred.render()))
        }
    }
    pub fn type_check_r(&self, t: &CType, tc: TypeContext) -> Result<(), TypeError>
    {
        let ct = self.type_of(tc)?;
        if t == &ct {
            Ok(())
        } else {
            Err(format!("Expected type {}, got {}", t.render(), ct.render()))
        }
    }
    pub fn type_of(&self, mut tc: TypeContext) -> Result<CType, TypeError> {
        match self {
            Self::Apply(m, _targs, vs) => match m.type_of(tc.clone())? {
                CType::Fun(ts, ct) => {
                    if ts.len() != vs.len() {
                        return Err(format!(
                            "Function expected {} arg(s) of type {:?}, but was applied to {} value(s).",
                            ts.len(),
                            ts,
                            vs.len(),
                        ))
                    }
                    for (v,t) in vs.iter().zip(ts) {
                        let vt = v.type_of(tc.clone())?;
                        if vt != t {
                            return Err(format!(
                                "Function expected {:?}, but value {:?} has type {:?}",
                                t,
                                v,
                                vt,
                            ))
                        }
                    }
                    Ok(*ct)
                }
                ct => Err(format!(
                    "Non-fun {:?} applied as function",
                    ct,
                )),
            }
            Self::Bind1(Binder1::Eq(_, args1, args2), x, m) => {
                assert!(args1.len() == 1);
                assert!(args2.len() == 1);
                let t1 = args1[0].type_of(tc.clone())?;
                let t2 = args2[0].type_of(tc.clone())?;
                if t1 != t2 {
                    Err(format!("Tried to Eq {:?} against {:?}", t1, t2))
                } else if t1.contains_thunk() {
                    Err(format!("Cannot Eq values that contain thunks: {:?}", t1))
                } else {
                    m.type_of(tc.plus(x.clone(), VType::prop()))
                }
            }
            Self::Bind1(Binder1::LogNot(v), x, m) => {
                v.type_check_r(&VType::prop(), tc.clone())?;
                m.type_of(tc.plus(x.clone(), VType::prop()))
            }
            Self::Bind1(Binder1::LogOpN(op, vs), x, m) => {
                match op {
                    LogOpN::And | LogOpN::Or => {
                        for v in vs {
                            v.type_check_r(&VType::prop(), tc.clone())?;
                        }
                        m.type_of(tc.plus(x.clone(), VType::prop()))
                    }
                    op => panic!("Unexpected op in type_check: {:?}", op),
                }
            }
            Self::Bind1(Binder1::LogQuantifier(_q, xs, body), x, m) => {
                for (_,vt) in xs {
                    let () = vt.validate(&tc.sig, &tc.type_bindings)?;
                }
                body.type_check_r(
                    &CType::return_prop(),
                    tc.clone().append(xs.clone()),
                )?;
                m.type_of(
                    tc.plus(x.clone(), VType::prop()),
                )
            }
            Self::BindN(BinderN::Call(_oc, _args), _xs, _m) => {
                panic!(
                    "BinderN::Call should only appear in phases after type_check"
                )
            }
            Self::BindN(BinderN::Seq(m1), ps, m) => {
                let p = unwrap_one(ps)?;
                let vt = m1.type_of(tc.clone())?.unwrap_return()?;
                let ct2 = p.bindings(vt)?;
                m.type_of(tc.append(ct2))
            }
            Self::Force(v) => {
                match v.type_of(tc)? {
                    VType::Thunk(ct) => Ok(*ct),
                    vt => Err(format!(
                        "Non-thunk {:?} with type {:?} in Force position.",
                        v,
                        vt,
                    ))
                }
            }
            Self::Fun(xs, m) => {
                let mut ts = Vec::new();
                for (x,o) in xs.clone().into_iter() {
                    match o {
                        Some(t) => {
                            let () = t.validate(&tc.sig, &tc.type_bindings)?;
                            ts.push(t.clone());
                            tc = tc.plus(x, t);
                        }
                        None => {
                            return Err(format!(
                                "No type annotation for {:?}",
                                x,
                            ))
                        }
                    }
                }
                Ok(CType::fun(ts, m.type_of(tc)?))
            }
            Self::Ite(cond, then_b, else_b) => {
                cond.type_check_r(&VType::prop(), tc.clone())?;
                let then_t = then_b.type_of(tc.clone())?;
                let else_t = else_b.type_of(tc)?;
                if then_t == else_t {
                    Ok(then_t)
                } else {
                    Err(format!(
                        "
if-then-else has branches with mismatched types: {:?} vs. {:?}",
                        then_t,
                        else_t,
                    ))
                }
            }
            Self::Return(vs) => {
                if vs.len() == 1 {
                    Ok(CType::Return(vs[0].type_of(tc)?))
                } else {
                    Err(format!("Multi-return {:?}", vs))
                }
            }
        }
    }
}

impl CType {
    fn unwrap_return(self) -> Result<VType, TypeError> {
        match self {
            CType::Return(t) => Ok(t),
            ct => Err(format!("Expected Return(..), got {:?}", ct)),
        }
    }
}

impl Pattern {
    fn bindings(self, t: VType) -> Result<Vec<(VName,VType)>, TypeError> {
        match (self, t) {
            (Pattern::NoBind, _) => Ok(Vec::new()),
            (Pattern::Atom(x), t) => Ok(vec![(x,t)]),
            (Pattern::Tuple(ps), VType::Tuple(ts)) => {
                if ps.len() == ts.len() {
                    let mut out = Vec::new();
                    for (p,t) in ps.into_iter().zip(ts) {
                        out.append(&mut p.bindings(t)?);
                    }
                    Ok(out)
                } else {
                    Err(format!(
                        "Pattern tuple size mismatch: {:?} vs. {:?}",
                        ps,
                        ts,
                    ))
                }
            }
            (p,t) => {
                Err(format!(
                    "Pattern {:?} does not match value {:?}",
                    p,
                    t,
                ))
            }
        }
    }
}

impl Sig {
    fn get_type(&self, oc: &OpCode, tas: Vec<String>) -> Result<VType, TypeError> {
        match self.get_applied_op(oc) {
            Ok(op) => match op {
                Op::Const(op) => {
                    return Ok(op.vtype)
                }
                Op::Direct(m) => {
                    match m.type_of(TypeContext::new_types(self.clone(), tas))? {
                        CType::Return(t) => return Ok(t),
                        _ => return Err(format!(
                            "signature function \"{}\" did not have a computation type",
                            oc,
                        )),
                    }
                }
                Op::Fun(op) => {
                    return Ok(VType::fun_v(
                        op.inputs,
                        op.output,
                    ))
                },
                Op::Pred(op) => {
                    return Ok(VType::fun_v(
                        op.inputs,
                        VType::prop(),
                    ))
                },
                Op::Rec(op) => {
                    return Ok(VType::fun_v(
                        op.inputs,
                        op.output,
                    ))
                }
                Op::Symbol(op) => {
                    return Ok(VType::fun_v(
                        op.inputs,
                        VType::prop(),
                    ))
                }
            }
            Err(e) => Err(e),
        }
//         for (name, _, op) in self.ops.clone() {
//             if name == s {
//                 match op {
//                     Op::Const(op) => {
//                         return Ok(op.vtype)
//                     }
//                     Op::Direct(m) => {
//                         match m.type_of(TypeContext::new(self.clone()))? {
//                             CType::Return(t) => return Ok(t),
//                             _ => return Err(format!(
//                                 "
// signature function \"{}\" did not have a computation type",
//                                 s,
//                             )),
//                         }
//                     }
//                     Op::Fun(op) => {
//                         return Ok(VType::fun_v(
//                             op.inputs,
//                             op.output,
//                         ))
//                     },
//                     Op::Pred(op) => {
//                         return Ok(VType::fun_v(
//                             op.inputs,
//                             VType::prop(),
//                         ))
//                     },
//                     Op::Rec(op) => {
//                         return Ok(VType::fun_v(
//                             op.inputs,
//                             op.output,
//                         ))
//                     }
//                     Op::Symbol(op) => {
//                         return Ok(VType::fun_v(
//                             op.inputs,
//                             VType::prop(),
//                         ))
//                     },
//                 }
//             }
//         }
//         Err(format!("Identifier {:?} is not bound or declared as a primitive operation. The following operations are declared: {:?}", s, self.all_op_names()))
    }
}

impl Val {
    fn type_check_r(&self, t: &VType, tc: TypeContext) -> Result<(), TypeError>
    {
        let vt = self.type_of(tc)?;
        if t == &vt {
            Ok(())
        } else {
            Err(format!("Expected type {:?}, got {:?}", t, vt))
        }
    }
    fn type_of(&self, tc: TypeContext) -> Result<VType, TypeError> {
        match self {
            Self::Literal(l) => match l {
                Literal::LogTrue => Ok(VType::prop()),
                Literal::LogFalse => Ok(VType::prop()),
            }
            Self::OpCode(om, oc) => panic!(
                "OpCode values ({:?}, {:?}) should not exist at type-check time.", om, oc
            ),
            Self::Thunk(m) => Ok(VType::Thunk(Box::new(m.type_of(tc)?))),
            Self::Tuple(vs) => {
                let mut ts = Vec::new();
                for v in vs {
                    ts.push(v.type_of(tc.clone())?);
                }
                Ok(VType::Tuple(ts))
            }
            Self::Var(x, types) => {
                match tc.get(x) {
                    Ok(t) => Ok(t),
                    Err(_) => match x {
                        VName::Manual(s) => {
                            let oc = OpCode {
                                ident: s.clone(),
                                types: types.clone(),
                            };
                            tc.sig.get_type(&oc, tc.type_bindings.clone())
                        }
                        VName::Auto(_n) => panic!("Unbound auto var {:?}", x),
                    }
                }
            }
        }
    }
}

impl BType {
    pub fn validate(&self, sig: &Sig, type_bindings: &Vec<String>) -> Result<(), TypeError> {
        match self {
            Self::Prop => Ok(()),
            Self::UI(name, args) => {
                match sig.sort_arity(name) {
                    Some(n) if n == args.len() => {
                        for a in args {
                            match a.validate(sig, type_bindings) {
                                Ok(()) => {},
                                Err(e) => return Err(e),
                            }
                        }
                        Ok(())
                    }
                    Some(n) => {
                        Err(format!("Type constructor '{}' expects {} types, but was applied to {} types instead in '{}'", name, n, args.len(), Self::UI(name.clone(),args.clone())))
                    }
                    None if args.len() == 0 && type_bindings.contains(name) => {
                        Ok(())
                    }
                    None => Err(format!("Type '{}' has not been declared in {:?} + {:?}", name, sig, type_bindings)),
                }
            }
        }
    }
}

impl CType {
    pub fn validate(&self, sig: &Sig, type_bindings: &Vec<String>) -> Result<(), TypeError> {
        match self {
            Self::Fun(ts, ct) => {
                for t in ts {
                    match t.validate(sig, type_bindings) {
                        Ok(()) => {},
                        Err(e) => return Err(e),
                    }
                }
                ct.validate(sig, type_bindings)
            }
            Self::Return(vt) => vt.validate(sig, type_bindings),
        }
    }
}

impl VType {
    pub fn validate(&self, sig: &Sig, type_bindings: &Vec<String>) -> Result<(), TypeError> {
        match self {
            Self::Base(bt) => bt.validate(sig, type_bindings),
            Self::Thunk(ct) => ct.validate(sig, type_bindings),
            Self::Tuple(ts) => {
                for t in ts {
                    match t.validate(sig, type_bindings) {
                        Ok(()) => {},
                        Err(e) => return Err(e),
                    }
                }
                Ok(())
            }
        }
        // match self {
        //     Self::Atom(Sort::Prop) => Ok(()),
        //     Self::Atom(Sort::UI(s)) => {
        //         match sig.sort_arity(s) {
        //             Some(0) => Ok(()),
        //             Some(n) => Err(format!("Found {} with no type-args, should have {} type-args.", s, n)),
        //             None if sig.is_abstract(s) => Ok(()),
        //             None => {
        //                 Err(format!("Sort {} is undeclared", s))
        //             }
        //         }
        //     }
        //     Self::Thunk(ct) => {
        //         ct.validate(sig)
        //     }
        //     Self::Tuple(ts) => {
        //         for t in ts {
        //             match t.validate(sig) {
        //                 Ok(()) => {},
        //                 Err(e) => return Err(e),
        //             }
        //         }
        //         Ok(())
        //     }
        // }
    }
}