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
pub mod internal;

use crate::{
    parse_str_cbpv,
    Builder,
    Comp,
    Gen,
    Op,
    Quantifier,
    Sig,
    TypeContext,
    Val,
    VName,
    VType
};
use easy_smt::Response;

#[cfg(test)]
mod tests; 

pub struct CheckedSig(Sig);

impl CheckedSig {
    pub fn assert_valid<T: ToString>(&self, s: T) {
        assert_valid_with(self, s)
    }
    pub fn assert_valid_t<T: ToString>(&self, title: &str, s: T) {
        assert_valid_with_t(self, title, s)
    }
    pub fn assert_invalid<T: ToString>(&self, s: T) {
        assert_invalid_with(self, s)
    }
    pub fn assert_undecidable<T: ToString>(&self, s: T) {
        assert_unknown_with(self, s)
    }
    pub fn inner_sig(&self) -> &Sig {
        &self.0
    }

    pub fn empty() -> Self {
        let mut sig = Self(Sig::empty());
        sig.add_fun("implies", "|x:bool, y:bool| !x || y");
        sig
    }
    pub fn add_sort<S: ToString>(&mut self, s: S) -> VType {
        let t = VType::ui(s.to_string());
        self.0.add_sort(s);
        t
    }
    pub fn add_type_con<S: ToString>(&mut self, s: S, arity: usize) {
        self.0.add_type_con(s, arity);
    }
    pub fn add_alias<S1: ToString>(&mut self, s: S1, t: VType) -> VType {
        self.0.add_alias(s, t.clone());
        t
    }
    pub fn add_alias_from_string<S1: ToString, S2: ToString>(
        &mut self,
        alias: S1,
        ty_string: S2,
    ) {
        self.0.add_alias_from_string(alias, ty_string);
    }
    pub fn add_constant<S1: ToString, S2: ToString>(
        &mut self,
        name: S1,
        sort: S2,
    ) {
        self.0.add_constant(name, sort)
    }
    pub fn add_relation<S1: ToString, S2: ToString, const N: usize>(
        &mut self,
        name: S1,
        inputs: [S2; N],
    ) {
        self.0.add_relation(name, inputs)
    }
    pub fn add_relation_t<S1: ToString, const N: usize>(
        &mut self,
        name: S1,
        inputs: [VType; N],
    ) {
        self.0.add_relation_t(name, inputs)
    }
    pub fn add_axiom<S1: ToString>(&mut self, axiom: S1) {
        self.0.add_axiom(axiom)
    }
    pub fn add_axiom2<const N1: usize, const N2: usize>(
        &mut self,
        def: &str,
        tas: [&str; N1],
        inst_rules: [(&str,&str); N2],
    ) {
        self.0.add_axiom2(def, tas, inst_rules)
    }
    pub fn add_fun<S1: ToString, S2: ToString>(
        &mut self,
        name: S1,
        def: S2,
    ) {
        self.add_fun_tas(name, [], def);
    }
    pub fn add_fun_tas<S1: ToString, S2: ToString, const N1: usize>(
        &mut self,
        name: S1,
        tas: [&str; N1],
        def: S2,
    ) {
        let tas: Vec<String> = tas.iter().map(|s| s.to_string()).collect();

        let mut unshadowed_aliases = self.0.type_aliases.clone();
        for a in tas.iter() {
            unshadowed_aliases.remove(a);
        }

        let fun = match parse_str_cbpv(&def.to_string()) {
            Ok(m) => m.expand_types(&unshadowed_aliases),
            Err(e) => panic!(
                "
Error in parsing definition of \"{}\": {:?}",
                name.to_string(),
                e,
            ),
        };
        let tc = TypeContext::new_types(self.0.clone(), tas.clone());
        match fun.type_of(tc) {
            Ok(ct) => match ct.clone().unwrap_fun_v() {
                Some(_) => {},
                None => panic!(
                    "
Error in type-checking definition of \"{}\":
should have had a function type, instead had {:?}",
                    name.to_string(),
                    ct,
                ),
            }
            Err(e) => panic!(
                "
Error in type-checking definition of \"{}\": {:?}",
                name.to_string(),
                e,
            ),
        }
        self.0.ops.push((name.to_string(), tas, Op::Direct(fun)))
    }
    pub fn declare_op<S1: ToString, S3: ToString, const N1: usize, const N2: usize>(
        &mut self,
        name: S1,
        targs: [&str; N1],
        inputs: [&str; N2],
        output: S3,
    ) {
        self.0.declare_op(name, targs, inputs, output);
    }
    pub fn declare_const(&mut self, name: &str, output: &str) {
        self.0.declare_const(name, output);
    }
    pub fn add_annotation(&mut self, name: &str, body: &str) {
        self.0.add_annotation(name, body);
    }
    pub fn add_checked_annotation(&mut self, title: &str, name: &str, body: &str) {
        let mut potential_sig = self.0.clone();
        potential_sig.add_annotation(name, body);

        let (tas,op) = potential_sig
            .ops_map()
            .get(&name.to_string())
            .unwrap()
            .clone();

        let op = match op {
            Op::Rec(op) => op,
            _ => panic!(
                "Tried to add checked annotation to non-rec {}", name
            ),
        };

        // Add uninterpreted types for each type abstraction
        let mut v_sig = potential_sig.clone();
        let mut type_args = Vec::new();
        for t in &tas {
            v_sig.add_sort(t);
            type_args.push(VType::ui(t));
        }

        let mut gn = Gen::new();
        op.def.advance_gen(&mut gn);
        for a in &op.axioms {
            a.advance_gen(&mut gn);
        }
        let mut input_args: Vec<Val> = Vec::new();
        let mut q_sig: Vec<(VName, VType)> = Vec::new();
        for i in op.inputs {
            let x = gn.next();
            input_args.push(x.clone().val());
            q_sig.push((x, i.clone()))
        }
        let m =
            Builder::lift(op.def.clone())
            .apply_rt(input_args.clone())
            .seq_gen(move |x| {
                Builder::lift(op.axioms[op.axioms.len() - 1].clone())
                    .apply_rt(input_args)
                    .apply_rt(vec![x])
            })
            .quant(Quantifier::Forall, q_sig)
            .build(&mut gn);

        let v_sig = CheckedSig(v_sig);
        match query_negative_c(m, &v_sig) {
            Response::Unsat => {},
            Response::Sat => {
                panic!(
                    "Annotation '{}' on recursive function '{}' is invalid",
                    title,
                    name.to_string(),
                )
            }
            Response::Unknown => {
                panic!(
                    "Verification of '{}' for '{}' cannot proceed",
                    title,
                    name.to_string(),
                )
            }
        }

        self.0 = potential_sig;
        
        // todo!("add_checked_annotation")
    }
    pub fn add_op_pred<S1: ToString, S2: ToString>(
        &mut self,
        name: S1,
        def: S2,
    ) {
        self.0.add_op_pred(name, def)
    }
    pub fn add_op_fun<S1: ToString, S2: ToString>(
        &mut self,
        name: S1,
        axiom: S2,
    ) {
        self.0.add_op_fun(name, axiom)
    }
    pub fn add_op_rec<S1: ToString + Clone, S2: ToString, S3: ToString>(
        &mut self,
        name: S1,
        axiom: S2,
        def: S3,
    ) {
        let mut potential_sig = self.0.clone();
        potential_sig.add_op_rec(
            name.clone(),
            axiom,
            def,
        );
        let op = potential_sig
            .ops_map()
            .get(&name.to_string())
            .unwrap()
            .clone();
        let op = match op {
            (_, Op::Rec(op)) => op,
            _ => panic!(),
        };
        let mut gn = Gen::new();
        op.def.advance_gen(&mut gn);
        for a in &op.axioms {
            a.advance_gen(&mut gn);
        }
        let mut input_args: Vec<Val> = Vec::new();
        let mut q_sig: Vec<(VName, VType)> = Vec::new();
        for i in op.inputs {
            let x = gn.next();
            input_args.push(x.clone().val());
            q_sig.push((x, i.clone()))
        }
        let m =
            Builder::lift(op.def.clone())
            .apply_rt(input_args.clone())
            .seq_gen(move |x| {
                Builder::lift(op.axioms[0].clone())
                    .apply_rt(input_args)
                    .apply_rt(vec![x])
            })
            .quant(Quantifier::Forall, q_sig)
            .build(&mut gn);
        // Build assertion body: for all inputs, apply the definition to
        // get the output, and then check that the inputs and output
        // are related by the annotation.
        self.0 = potential_sig;
        match query_negative_c(m, &self) {
            Response::Unsat => {},
            Response::Sat => {
                panic!(
                    "The annotation on recursive function \"{}\" is invalid",
                    name.clone().to_string(),
                )
            }
            Response::Unknown => {
                panic!(
                    "Verification of \"{}\" cannot proceed",
                    name.clone().to_string(),
                )
            }
        }
        // self.0.add_op_rec(name, axiom, def, term_arg, term_relation)
    }

    pub fn define_op_rec<S1: ToString + Clone, S2: ToString, S3: ToString, S4: ToString, const N1: usize, const N2: usize>(
        &mut self,
        name: S1,
        tas: [&str; N1],
        inputs: [S2; N2],
        output: S3,
        def: S4,
    ) {
        self.0.define_op_rec(name, tas, inputs, output, def);

//         let tas: Vec<String> = tas.iter().map(|s| s.to_string()).collect();

//         let mut unshadowed_aliases = self.0.type_aliases.clone();
//         for a in tas.iter() {
//             unshadowed_aliases.remove(a);
//         }

//         let def = match parse_str_cbpv(&def.to_string()) {
//             Ok(m) => m.expand_types(&unshadowed_aliases),
//             Err(e) => panic!(
//                 "
// Error in parsing definition of \"{}\": {:?}",
//                 name.to_string(),
//                 e,
//             ),
//         };
//         let self_op = Op::Fun(FunOp{
//             inputs: inputs.clone()
//         });

//         let tc = TypeContext::new_types(self.0.clone(), tas.clone());
//         match def.type_of(tc) {
//             Ok(ct) => match ct.clone().unwrap_fun_v() {
//                 Some(_) => {},
//                 None => panic!(
//                     "
// Error in type-checking definition of \"{}\":
// should have had a function type, instead had {:?}",
//                     name.to_string(),
//                     ct,
//                 ),
//             }
//             Err(e) => panic!(
//                 "
// Error in type-checking definition of \"{}\": {:?}",
//                 name.to_string(),
//                 e,
//             ),
//         }

    }
}


fn query_negative<T: ToString>(s: T, sig: &CheckedSig) -> Response {
    match parse_str_cbpv(&s.to_string()) {
        Ok(c) => query_negative_c(c, sig),
        Err(e) => panic!("Parse error: {}", e),
    }
}

fn query_negative_c(c: Comp, sig: &CheckedSig) -> Response {
    // let mut p = match Prop::parse(&s.to_string(), sig.inner_sig()) {
    //     Ok(p) => p,
    //     Err(e) => panic!("{}", e),
    // };
    let mut p = match c.as_prop(sig.inner_sig()) {
        Ok(p) => p,
        Err(e) => panic!("{}", e),
    };
    println!("Checking {} cases...", p.cases.len());
    assert!(p.is_single_case(), "Should only be single-case props so far.");
    p.negate(sig.inner_sig());
    // let sig_graph = sig.inner_sig().sort_graph();
    for (name, case) in p.cases {
        //let mut g = sig_graph.clone();
        // g.append(case.sort_graph());
        let g = sig.inner_sig().sort_graph_combined(&case);
        let cycles = g.get_cycles();
        if cycles.len() > 0 {
            println!("Sort cycles detected in case [{}]:", name);
            for c in cycles {
                if c.len() == 1 {
                    println!("=> self-loop on {:?}", c[0]);
                } else {
                    println!("=> {:?}", c);
                }
            }
            println!("Query is undecidable due to sort cycles.");
            return Response::Unknown
        }
        match internal::check_sat_of_normal(&case, sig.inner_sig()).unwrap() {
            Response::Sat => {
                println!("Got SAT for case [{}]", name);
                return Response::Sat
            }
            Response::Unsat => {},
            Response::Unknown => {
                println!("Got UNKNOWN for case [{}]", name);
                return Response::Unknown
            }
        }
    }

    // If we made it here, the overall answer is UNSAT.
    Response::Unsat
}

pub fn assert_valid_with<T: ToString>(sig: &CheckedSig, s: T) {
    match query_negative(s, sig) {
        Response::Unsat => {},
        Response::Sat => panic!("
verification conditions are not valid, counterexample was found"
        ),
        Response::Unknown => panic!("
verification could not be completed (sort cycle?)"
        ),
    }
    // assert_eq!(query_negative(s, sig), Response::Unsat);
}
pub fn assert_valid_with_t<T: ToString>(sig: &CheckedSig, title: &str, s: T) {
    match query_negative(s, sig) {
        Response::Unsat => {},
        Response::Sat => panic!("verification goal {} is invalid", title),
        Response::Unknown => panic!("verification goal {} could not be checked (sort cycle?)", title),
    }
    // assert_eq!(query_negative(s, sig), Response::Unsat);
}

pub fn assert_invalid_with<T: ToString>(sig: &CheckedSig, s: T) {
    assert_eq!(query_negative(s, sig), Response::Sat);
}

pub fn assert_unknown_with<T: ToString>(sig: &CheckedSig, s: T) {
    assert_eq!(query_negative(s, sig), Response::Unknown);
}