ravenlang 0.5.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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
pub mod solver;

pub mod internal;

use crate::{
    parse_str_cbpv,
    render_cycle,
    Builder,
    CaseName,
    Comp,
    Cycle,
    IGen,
    Goal,
    Op,
    Quantifier,
    Sig,
    SolverConfig,
    TypeContext,
    Val,
    Ident,
    VType
};
use easy_smt::Response;

use rayon::prelude::*;

#[cfg(test)]
mod tests; 

#[derive(Debug, PartialEq, Eq)]
pub enum RvnResponse {
    Verified,
    Falsified(Vec<CaseName>),
    SortCycles(Vec<Cycle>, CaseName),
    Unknown,
}

impl RvnResponse {
    pub fn verified() -> Self {
        Self::Verified
    }
    pub fn falsified(names: Vec<CaseName>) -> Self {
        Self::Falsified(names)
    }
    pub fn unknown() -> Self {
        Self::Unknown
    }
}

#[derive(Clone)]
pub struct CheckedSig(pub Sig);

impl CheckedSig {
    pub fn check_goal(&self, goal: Goal, solver_config: &SolverConfig) -> Result<(), String> {
        let Goal{title, tas, condition, should_be_valid} = goal;
        match query_negative_c(condition, self, tas, solver_config) {
            RvnResponse::Verified if should_be_valid => Ok(()),
            RvnResponse::Verified =>
                Err(format!("Failed to falsify '{}': solver did not find counterexample", title)),
            RvnResponse::Falsified(_cases) if !should_be_valid => Ok(()),
            RvnResponse::Falsified(cases) =>
                Err(format!("Failed to verify '{}': solver found counterexamples in cases {}", title, CaseName::render_vec(&cases))),
            RvnResponse::Unknown if should_be_valid =>
                Err(format!("Failed to verify '{}': solver returned UNKNOWN (this is probably a bug)", title)),
            RvnResponse::Unknown =>
                Err(format!("Failed to falsify '{}': solver returned UNKNOWN (this is probably a bug)", title)),
            RvnResponse::SortCycles(cycles, case_name) => {
                if cycles.len() == 1 {
                    Err(format!("Cannot check '{}': sort cycle {} in case {}", title, render_cycle(&cycles[0]), case_name))
                } else if cycles.len() > 1 {
                    Err(format!("Cannot check '{}': multiple sort cycles, including {}, in case {}", title, render_cycle(&cycles[0]), case_name))
                } else {
                    panic!("Sort cycle reported, but not found (this is a bug)")
                }
            }
        }
    }

    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<T: ToString>(&self, title: &str, s: T) {
        assert_invalid_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,Vec<&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, [], None, def);
    }
    pub fn add_fun_tas<S1: ToString, S2: ToString, const N1: usize>(
        &mut self,
        name: S1,
        tas: [&str; N1],
        output: Option<&str>,
        def: S2,
    ) {
        let tas: Vec<String> = tas.iter().map(|s| s.to_string()).collect();
        // let inputs: Vec<VType> = inputs.into_iter().map(|i| {
        //     let t = VType::from_pat_type(i).expect("should be able to parse an input argument type as a VType");
        //     t.expand_aliases(&self.0.type_aliases)
        // }).collect();

        let mut unshadowed_aliases = self.0.type_aliases();
        for a in tas.iter() {
            unshadowed_aliases.remove(a);
        }
        // let output: VType = VType::from_string(output)
        //     .expect("should be able to parse an input argument type as a VType")
        //     .expand_aliases(&unshadowed_aliases);

        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,
            ),
        };
        // println!("Adding fun {} with def: {:?}", name.to_string(), &fun);
        let tc = TypeContext::new_types(self.0.clone(), tas.clone());
        match fun.type_of(tc) {
            Ok(ct) => match ct.clone().unwrap_fun_v() {
                Some((_,out)) => match output {
                    Some(output) => {
                        let output: VType = VType::from_string(output)
                            .expect("should be able to parse an input argument type as a VType")
                            .expand_aliases(&unshadowed_aliases);
                        assert!(
                            output == out,
                            "
Error in type-checking definition of '{}':
output type should be '{}', but body had type '{}'",
                            name.to_string(),
                            output.render(),
                            out.render(),
                        );
                    }
                    None => {}
                }
                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);
    }
    // TODO: remove this; it's only used for old tests.
    pub fn add_checked_annotation(&mut self, title: &str, name: &str, body: &str) {
        let solver_config = SolverConfig::default();
        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 = IGen::new();
        op.def.advance_igen(&mut gn);
        for a in &op.axioms {
            a.advance_igen(&mut gn);
        }
        let mut input_args: Vec<Val> = Vec::new();
        let mut q_sig: Vec<(Ident, 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_igen(move |x| {
                Builder::lift(op.axioms[op.axioms.len() - 1].clone())
                    .apply_rt(input_args)
                    .apply_rt(vec![x])
            })
            .into_quantifier(Quantifier::Forall, q_sig)
            .build_with(&mut gn);

        let v_sig = CheckedSig(v_sig);
        match query_negative_c(m, &v_sig, Vec::new(), &solver_config) {
            RvnResponse::Verified => {},
            RvnResponse::Falsified(cases) => {
                panic!(
                    "Annotation '{}' on recursive function '{}' is invalid in cases {}",
                    title,
                    name.to_string(),
                    CaseName::render_vec(&cases),
                )
            }
            RvnResponse::Unknown => {
                panic!(
                    "Verification of '{}' for '{}' cannot proceed",
                    title,
                    name.to_string(),
                )
            }
            RvnResponse::SortCycles(cycles, _) => {
                panic!(
                    "Cannot check '{}' for '{}': sort cycle {}",
                    title,
                    name.to_string(),
                    render_cycle(&cycles[0]),
                )
            }
        }

        self.0 = potential_sig;        
    }
    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)
    }
    // TODO: remove this; it's only used for tests.
    pub fn add_op_rec<S1: ToString + Clone, S2: ToString, S3: ToString>(
        &mut self,
        name: S1,
        axiom: S2,
        def: S3,
    ) {
        let solver_config = SolverConfig::default();
        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 = IGen::new();
        op.def.advance_igen(&mut gn);
        for a in &op.axioms {
            a.advance_igen(&mut gn);
        }
        let mut input_args: Vec<Val> = Vec::new();
        let mut q_sig: Vec<(Ident, 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_igen(move |x| {
                Builder::lift(op.axioms[0].clone())
                    .apply_rt(input_args)
                    .apply_rt(vec![x])
            })
            .into_quantifier(Quantifier::Forall, q_sig)
            .build_with(&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, Vec::new(), &solver_config) {
            RvnResponse::Verified => {},
            RvnResponse::Falsified(cases) => {
                panic!(
                    "The annotation on recursive function \"{}\" is invalid for cases {}",
                    name.clone().to_string(),
                    CaseName::render_vec(&cases)
                )
            }
            RvnResponse::Unknown => {
                panic!(
                    "Verification of \"{}\" cannot proceed: solver returned UNKNOWN (this is probably a bug)",
                    name.clone().to_string(),
                )
            }
            RvnResponse::SortCycles(cycles, case_name) => {
                if case_name.is_root() {
                    panic!(
                        "Cannot check '{}': sort cycle {}",
                        name.to_string(),
                        render_cycle(&cycles[0]),
                    )
                } else {
                    panic!(
                        "Cannot check '{}': sort cycle {} in case {}",
                        name.to_string(),
                        render_cycle(&cycles[0]),
                        case_name,
                    )
                }
            }                
        }
        // 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) -> RvnResponse {
    match parse_str_cbpv(&s.to_string()) {
        Ok(c) => query_negative_c(c, sig, Vec::new(), &SolverConfig::default()),
        Err(e) => panic!("Parse error: {}", e),
    }
}

fn query_negative_c(
    c: Comp,
    sig: &CheckedSig,
    tas: Vec<String>,
    solver_config: &SolverConfig
) -> RvnResponse {
    let mut sig = sig.clone();
    // Declare all type abstraction arguments as zero-arity
    // uninterpreted sorts.
    for s in tas {
        sig.0.sorts_insert(s, 0);
    }
    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 results: Vec<(CaseName, Result<Response, RvnResponse>)> =
        p.cases.into_par_iter()
        .map(|(name, case)| {
            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.clone() {
                //     println!("=> {}", render_cycle(&c));
                // }
                // println!("Query is undecidable due to sort cycles.");
                (name.clone(), Err(RvnResponse::SortCycles(cycles,name)))
            } else {
            // println!("--------------------------");
            // println!("Checking case: {}", name);
            // println!("--------------------------");
                (name, Ok(internal::check_sat_of_normal(&case, sig.inner_sig(), solver_config).unwrap()))
            }
        })
        .collect();

    let mut f_cases = Vec::new();
    for (name, resp) in results.into_iter() {
        match resp {
            Ok(Response::Sat) => {
                println!("Got SAT for case [{}]", &name);
                f_cases.push(name);
            }
            Ok(Response::Unsat) => {},
            Ok(Response::Unknown) => {
                println!("Got UNKNOWN for case [{}]", &name);
                return RvnResponse::unknown()
            }
            Err(r) => return r,
        }
    }

    if f_cases.len() == 0 {
        // If we made it here, the overall answer is UNSAT.
        RvnResponse::verified()
    } else {
        // Check combined query, for completeness.

        let g = sig.inner_sig().sort_graph_combined(&p.single_case);
        let cycles = g.get_cycles();
        if cycles.len() > 0 {
            println!("Sort cycles detected in combined case");
            for c in cycles.clone() {
                println!("=> {}", render_cycle(&c));
            }
            println!("Query is undecidable due to sort cycles.");
            return RvnResponse::SortCycles(cycles,CaseName::root())
        }
        println!("--------------------------");
        println!("Checking combined case");
        println!("--------------------------");
        match internal::check_sat_of_normal(&p.single_case, sig.inner_sig(), solver_config).unwrap() {
            Response::Sat => {
                println!("Got SAT for combined case");
                // We return the previously-identified specific
                // falsified cases.
                RvnResponse::falsified(f_cases)
            }
            Response::Unsat => {
                RvnResponse::verified()
            }
            Response::Unknown => {
                println!("Got UNKNOWN for combined case");
                return RvnResponse::unknown()
            }
        }

        
    }
}

pub fn assert_valid_with<T: ToString>(sig: &CheckedSig, s: T) {
    match query_negative(s, sig) {
        RvnResponse::Verified => {},
        RvnResponse::Falsified(_cases) => panic!("
verification conditions are not valid, counterexample was found"
        ),
        RvnResponse::Unknown => panic!("
verification could not be completed (this is probably a bug)"
        ),
        _ => panic!()
    }
    // 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) {
        RvnResponse::Verified => {},
        RvnResponse::Falsified(_) => panic!("verification goal {} is invalid", title),
        RvnResponse::Unknown => panic!("verification goal {} could not be checked (sort cycle?)", title),
        _ => panic!()
    }
    // assert_eq!(query_negative(s, sig), Response::Unsat);
}

pub fn assert_invalid_with_t<T: ToString>(sig: &CheckedSig, title: &str, s: T) {
    match query_negative(s, sig) {
        RvnResponse::Verified => panic!("falsification goal {} is actually valid", title),
        RvnResponse::Falsified(_) => {},
        RvnResponse::Unknown => panic!("falsification goal {} could not be checked (sort cycle?)", title),
        _ => panic!()
    }
}

pub fn assert_invalid_with<T: ToString>(sig: &CheckedSig, s: T) {
    match query_negative(s, sig) {
        RvnResponse::Falsified(_) => {},
        r => panic!("{:?}", r),
    }
}

pub fn assert_unknown_with<T: ToString>(sig: &CheckedSig, s: T) {
    match query_negative(s, sig) {
        RvnResponse::SortCycles(_,_) => {},
        r => panic!("Expected SortCycles, got {:?}", r)
    }
}