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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
//! Translation from Rust syntax (represented using the `syn` package)
//! into the Raven IR (RIR).

use syn::{
    AngleBracketedGenericArguments,
    BinOp,
    Block,
    Expr,
    ExprBinary,
    ExprBlock,
    ExprCall,
    ExprClosure,
    ExprIf,
    ExprLit,
    ExprMacro,
    ExprMethodCall,
    ExprParen,
    ExprUnary,
    FnArg,
    Ident as SynIdent,
    ItemFn,
    GenericArgument,
    GenericParam,
    Lit,
    LitBool,
    ParenthesizedGenericArguments,
    Pat,
    PatIdent,
    PatType,
    PathArguments,
    PathSegment,
    Macro,
    ReturnType,
    Signature,
    Stmt,
    Token,
    Type,
    TypeImplTrait,
    TypeParamBound,
    UnOp,
};
use quote::ToTokens;
use syn::parse::{Parse, ParseStream};

use crate::{
    Builder,
    BType,
    Comp,
    InstRule,
    IGen,
    HypotheticalCall,
    LogOpN,
    MatchArm,
    OpCode,
    Pattern,
    Quantifier,
    Val,
    Ident as RirIdent,
    VType,
};

type Error = String;

fn mk_err<A,T: ToString>(s: T) -> Result<A,Error> {
    Err(s.to_string())
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct HypotheticalCallSyntax {
    pub call: ExprCall,
    pub arrow: Token![=>],
    pub output: SynIdent,
}

impl Parse for HypotheticalCallSyntax {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        Ok(Self {
            call: input.parse()?,
            arrow: input.parse()?,
            output: input.parse()?,
        })
    }
}

impl HypotheticalCallSyntax {
    pub fn into_rir(self) -> Result<HypotheticalCall, Error> {
        let HypotheticalCallSyntax {call, output, ..} = self;
        let ExprCall{func, args, ..} = call;
        match *func {
            Expr::Path(p) => {
                assert!(p.path.segments.len() == 1);
                let PathSegment{ident, arguments} =
                    p.path.segments.first().unwrap().clone();
                let types = match arguments {
                    PathArguments::None => Vec::new(),
                    PathArguments::AngleBracketed(a) => {
                        a.args.into_pairs().map(|pr| {
                            match pr.into_value() {
                                GenericArgument::Type(t) =>
                                    VType::from_syn(t).unwrap(),
                                a => panic!("Can't handle this generic argument: {:?}", a),
                            }
                        }).collect()
                    }
                    PathArguments::Parenthesized(args) => {
                        panic!("Can't handle parenthesized path arguments: {:?}", args)
                    }
                };
                let types: Vec<String> = types
                    .into_iter()
                    .map(|t| match t.unwrap_base() {
                        Ok(BType::UI(s, ts)) if ts.len() == 0 => Ok(s),
                        Ok(b) => Err(format!("type args in #[assume(..)] or #[assert(..)] must be simple identifiers, instead got {}", b)),
                        Err(t) => Err(format!("type args in #[assume(..)] or #[assert(..)] must be simple identifiers, instead got {}", t.render())),
                    })
                    .collect::<Result<Vec<_>, _>>()?;

                let ident = ident.to_string();
                let inputs = args
                    .iter()
                    .map(|i| match i {
                        Expr::Path(p) => {
                            p.path.segments
                                .first()
                                .unwrap()
                                .clone()
                                .ident.to_string()
                        }
                        _ => panic!("Inputs must be simple identifiers"),
                    })
                    .collect();
                let output = output.to_string();
                Ok(HypotheticalCall{ident, tas: types, inputs, output})
            }
            _ => Err(format!("In #[assume_for(..)], called function must be by name, not an arbitrary expression.")),
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub struct InstRuleSyntax {
    pub left: Type,
    pub arrow: Token![=>],
    pub right: AngleBracketedGenericArguments,
}

impl Parse for InstRuleSyntax {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        Ok(Self {
            left: input.parse()?,
            arrow: input.parse()?,
            right: input.parse()?,
        })
    }
}

impl InstRule {
    pub fn from_syn(
        InstRuleSyntax{left,right,..}: InstRuleSyntax
    ) -> Result<Self, Error> {
        let left = match VType::from_syn(left)?.unwrap_base() {
            Ok(bt) => Ok(bt),
            Err(vt) => Err(format!("inst rule left-side should be a base type, but it was '{}'", vt.render())),
        }?;
        let right: Vec<VType> = right
            .args
            .into_pairs()
            .map(|p| p.into_value())
            .map(|ga| match ga {
                GenericArgument::Type(t) => t,
                ga => panic!("Can't handle type argument of form {:?}", ga),
            })
            .map(|t| VType::from_syn(t))
            .collect::<Result<Vec<_>, _>>()?;
        Ok(InstRule{left, right})
    }
}

pub fn block_to_builder(block: Block) -> Result<Builder, Error> {
    let mut stmts = block.stmts;
    stmts.reverse();
    match stmts.pop() {
        Some(s) => stmts_to_builder(s, stmts),
        None => mk_err("Empty block"),
    }
}

fn stmts_to_builder(stmt: Stmt, mut rem: Vec<Stmt>) -> Result<Builder,Error> {
    match stmt {
        Stmt::Local(l) => {
            let x = Pattern::from_pat(l.clone().pat)?.0;
            let body = match l.clone().init {
                Some(local_init) => *local_init.expr,
                None => return mk_err("let-bindings must have inits"),
            };
            let m = syn_to_builder(body)?;

            match rem.pop() {
                Some(next) => {
                    let n = stmts_to_builder(next,rem)?;
                    Ok(m.seq_pattern(x,n))
                }
                None => mk_err(format!("The last item in a block cannot be a let-binding: {}", l.to_token_stream())),
            }
        }
        Stmt::Expr(expr,_) => {
            // Attempt to translate expr first, so that if it's
            // totally invalid then that is the first error the user
            // will see.
            let e = syn_to_builder(expr.clone())?;

            // Only if it is a valid expr, then check that it is the
            // last item in the block.
            if rem.len() != 0 {
                mk_err(format!(
                    "This expr should only be used as the last item in a block: {}",
                    expr.to_token_stream(),
                ))
            } else {
                Ok(e)
            }
        }
        s => todo!("block stmt {:?}", s),
    }
}

impl From<PatIdent> for RirIdent {
    fn from(p: PatIdent) -> Self {
        RirIdent::new(p.ident)
    }
}

impl BType {
    pub fn from_string<S: ToString>(s: S) -> Result<Self, Error> {
        let vt = VType::from_string(s)?;
        match vt.unwrap_base() {
            Ok(bt) => Ok(bt),
            Err(vt) => Err(format!("{} is not a base type", vt.render())),
        }
    }
}

fn get_fn_from_impl(mut t: TypeImplTrait) -> Option<(Vec<VType>, VType)> {
    if t.bounds.len() != 1 {
        return None;
    }
    match t.bounds.pop().unwrap().into_value() {
        TypeParamBound::Trait(mut t) => {
            if t.path.segments.len() != 1 {
                return None;
            }
            let seg = t.path.segments.pop().unwrap().into_value();
            match seg.ident.to_string().as_str() {
                "Fn" | "FnMut" | "FnOnce" => match seg.arguments {
                    PathArguments::Parenthesized(ParenthesizedGenericArguments{inputs, output: ReturnType::Type(_, output), ..}) => {
                        let inputs = inputs
                            .into_pairs()
                            .map(|i| VType::from_syn(i.into_value()).unwrap())
                            .collect();
                        match VType::from_syn(*output) {
                            Ok(output) => Some((inputs, output)),
                            Err(_) => None,
                        }

                    }
                    _ => None
                }
                _ => None
            }
        }
        _ => None
    }

}

impl VType {
    pub fn from_pat_type<S: ToString>(s: S) -> Result<Self, Error> {
        let pt: PatType = match syn::parse_str(&s.to_string()) {
            Ok(t) => t,
            Err(e) => panic!(
                "Could not parse \"{}\" as a typed pattern: {}",
                s.to_string(),
                e,
            ),
        };
        Self::from_syn(*pt.ty)
    }
    pub fn from_string<S: ToString>(s: S) -> Result<Self, Error> {
        let t: Type = match syn::parse_str(&s.to_string()) {
            Ok(t) => t,
            Err(e) => panic!(
                "Could not parse \"{}\" as a type: {}",
                s.to_string(),
                e,
            ),
        };
        Self::from_syn(t)
    }
    pub fn from_syn(t: Type) -> Result<Self, Error> {
        match t {
            Type::BareFn(t) => {
                let mut input_types = Vec::new();
                for arg in t.inputs.into_iter() {
                    input_types.push(VType::from_syn(arg.ty)?);
                }
                let output_type = match t.output {
                    ReturnType::Default => VType::unit(),
                    ReturnType::Type(_,t) => VType::from_syn(*t)?,
                };
                Ok(VType::fun_v(input_types, output_type))
            }
            Type::ImplTrait(t) => {
                match get_fn_from_impl(t.clone()) {
                    Some((inputs, output)) =>
                        Ok(VType::fun_v(inputs, output)),
                    None => panic!(
                        "impl should be a closure trait with output: {:?}",
                        t,
                    ),
                }
            }
            Type::Path(mut p) => {
                if p.path.segments.len() == 1 {
                    let seg = p.path.segments.pop().unwrap().into_value();
                    if &seg.ident == "bool" {
                        Ok(VType::prop())
                    } else {
                        let mut args = match seg.arguments {
                            PathArguments::None => Vec::new(),
                            PathArguments::AngleBracketed(bs) => {
                                bs
                                    .args
                                    .into_pairs()
                                    .map(|p| p.into_value())
                                    .map(|ga| match ga {
                                        GenericArgument::Type(t) => t,
                                        ga => panic!("Can't handle type argument of form {:?}", ga),
                                    })
                                    .map(|t| VType::from_syn(t).unwrap())
                                    .collect()
                            }
                            PathArguments::Parenthesized(..) => return Err(format!("Can't handle parenthesized type arguments")),
                        };
                        if &seg.ident == "Box" {
                            assert!(args.len() == 1, "Box<_> should have 1 type arg, but it was given {} type args", args.len());
                            Ok(args.pop().unwrap())
                        } else {
                            Ok(VType::Base(BType::UI(seg.ident.to_string(), args)))
                        }
                    }
                } else {
                    Err(format!("Can't handle type path {:?}, since it does not have exactly 1 segment.", p))
                }
            }
            Type::Reference(t) => Self::from_syn(*t.elem),
            Type::Tuple(p) => {
                let mut ts = Vec::new();
                for t in p.elems.into_iter() {
                    ts.push(Self::from_syn(t)?);
                }
                Ok(VType::Tuple(ts))
            }
            t => Err(format!("Can't handle type {:?}", t)),
        }
    }
}

impl Pattern {
    pub fn from_pat(p: Pat) -> Result<(Self, Option<VType>), Error> {
        pat_to_rir_pattern(p)
    }
    pub fn from_pat_type(pt: PatType) -> Result<(Self, VType), Error> {
        let (p,t) = pat_to_rir_pattern(Pat::Type(pt))?;
        Ok((p, t.unwrap()))
    }
}

fn pat_to_rir_pattern(p: Pat) -> Result<(Pattern, Option<VType>), Error> {
    match p {
        Pat::Ident(p) => Ok((Pattern::Atom(p.into()), None)),
        Pat::Tuple(p) => {
            let mut ps = Vec::new();
            for sub_p in p.elems.into_iter() {
                ps.push(pat_to_rir_pattern(sub_p)?.0);
            }
            Ok((Pattern::Tuple(ps), None))
        }
        Pat::Type(p) => {
            let (x,_) = pat_to_rir_pattern(*p.pat)?;
            let t = VType::from_syn(*p.ty)?;
            Ok((x,Some(t)))
        }
        Pat::Wild(..) => {
            Ok((Pattern::NoBind, None))
        }
        p => Err(format!("Can't handle binding Pat {:?}", p)),
    }
}

fn q_body(quantifier: Quantifier, expr: Expr) -> Result<Builder, Error> {
    match expr {
        Expr::Closure(ExprClosure{inputs,body,..}) => {
            assert!(
                inputs.len() >= 1,
                "Quantifiers must bind at least one variable"
            );
            let mut q_sig = Vec::new();
            for i in inputs.into_iter() {
                match Pattern::from_pat(i)? {
                    (x,Some(t)) => {
                        let x = match x.clone().unwrap_atom() {
                            Some(x) => x,
                            None => return Err(format!(
                                "Must not use tuple pattern in quantifier signature: {:?}",
                                x,
                            )),
                        };
                        q_sig.push((x, t)); }
                    (x,None) => {
                        return Err(format!(
                            "Quantified {:?} needs type annotation.",
                            x,
                        ))
                    }
                }
            }
            Ok(syn_to_builder(*body)?
               .into_quantifier(quantifier, q_sig))
        }
        e => {
            Err(format!(
                "Quantifier contained non-closure: {:?}",
                e,
            ))
        }
    }
}

fn def_and_eq(left: Expr, right: Expr) -> Result<Builder, Error> {
    match left {
        Expr::Call(ExprCall{ func, args, .. }) => {
            let f = syn_to_builder(*func)?.build_no_context();
            match f {
                Comp::Return(mut vs) => {
                    match vs.pop().unwrap() {
                        Val::Var(RirIdent::Manual(s), types, path, true) => {
                            let oc = OpCode { ident: s.clone(), types, path };
                            let f = oc.as_rel_abs().force().builder();
                            let mut cs = Vec::new();
                            for arg in args {
                                cs.push(syn_to_builder(arg)?);
                            }
                            cs.push(syn_to_builder(right)?);
                            Ok(f.apply(cs))
                            // todo!("make a relabs node from the opcode")
                        }
                        _ => panic!(),
                    }
                }
                c => Err(format!("first arg to def_and_eq should be a call to a declared (or recursive) function, got {:?}", c)),
            }
        }
        _ => todo!()
    }
}

fn get_cloned_expr(e: ExprMethodCall) -> Result<Expr, Error> {
    match e.method.to_string().as_str() {
        "clone" => Ok(*e.receiver),
        m => Err(format!("only 'clone' should be used as a method call, found '{}'", m)),
    }
}

pub fn syn_to_builder(e: Expr) -> Result<Builder, Error> {
    match e {
        Expr::Assign(e) => {
            mk_err(format!("Assign statements are not supported by Ravencheck, use a `let` binding instead of {}", e.to_token_stream()))
        }
        Expr::Binary(ExprBinary{ left, op, right, .. }) => {
            let c1 = syn_to_builder(*left)?;
            let c2 = syn_to_builder(*right)?;
            Ok(match op {
                BinOp::And(_) => Builder::log_op(LogOpN::And, [c1,c2]),
                BinOp::Or(_) => Builder::log_op(LogOpN::Or, [c1,c2]),
                BinOp::Eq(_) => c1.eq_ne(true, c2),
                BinOp::Ne(_) => c1.eq_ne(false, c2),
                op => return mk_err(format!("Unhandled op: {:?}", op)),
            })
        }
        Expr::Block(ExprBlock{ block, .. }) => {
            let mut stmts = block.stmts;
            stmts.reverse();
            match stmts.pop() {
                Some(s) => stmts_to_builder(s, stmts),
                None => mk_err("Empty block"),
            }
        }
        Expr::If(ExprIf{ cond, mut then_branch, else_branch, .. }) => {
            let cond = syn_to_builder(*cond)?;
            then_branch.stmts.reverse();
            let then_branch = match then_branch.stmts.pop() {
                Some(s) => stmts_to_builder(s, then_branch.stmts)?,
                None => Builder::return_(Val::unit()),
            };
            let else_branch = match else_branch {
                Some((_,b)) => syn_to_builder(*b)?,
                None => Builder::return_(Val::unit()),
            };
            Ok(cond.ite(then_branch, else_branch))
        }
        Expr::Lit(ExprLit{ lit, .. }) => match lit {
            Lit::Bool(LitBool{ value, .. }) => {
                if value {
                    Ok(Builder::return_(Val::true_()))
                } else {
                    Ok(Builder::return_(Val::false_()))
                }
            }
            lit => mk_err(format!("Unhandled lit: {:?}", lit)),
        }
        Expr::MethodCall(e) => syn_to_builder(get_cloned_expr(e)?),
        Expr::Call(ExprCall{ func, mut args, .. }) => {
            let func = *func;
            if is_box_new(&func) {
                if args.len() == 1 {
                    syn_to_builder(args.pop().unwrap().into_value())
                } else {
                    Err(format!(
                        "Box::new(..) should take one argument but it has {}",
                        args.len(),
                    ))
                }
            } else {
                match func {
                    Expr::Path(p) if p.path.segments.len() == 1 && p.path.segments.first().unwrap().ident.to_string().as_str() == "forall" => {
                        assert!(
                            args.len() == 1,
                            "forall must take single closure as its only argument, got {:?}",
                            args,
                        );
                        q_body(Quantifier::Forall, args.pop().unwrap().into_value())
                    }
                    Expr::Path(p) if p.path.segments.len() == 1 && p.path.segments.first().unwrap().ident.to_string().as_str() == "exists" => {
                        assert!(
                            args.len() == 1,
                            "exists must take single closure as its only argument, got {:?}",
                            args,
                        );
                        q_body(Quantifier::Exists, args.pop().unwrap().into_value())
                    }
                    Expr::Path(p) if p.path.segments.len() == 1 && p.path.segments.first().unwrap().ident.to_string().as_str() == "def_and_eq" => {
                        assert!(
                            args.len() == 2,
                            "def_and_eq takes two arguments",
                        );
                        let right = args.pop().unwrap().into_value();
                        let left = args.pop().unwrap().into_value();
                        def_and_eq(left, right)
                    }
                    Expr::Path(p) if p.path.segments.len() == 1 && p.path.segments.first().unwrap().ident.to_string().as_str() == "no_unroll" => {
                        assert!(args.len() == 1, "no_unroll takes 1 argument");
                        match args.pop().unwrap().into_value() {
                            Expr::Call(ExprCall{ func, args, .. }) => {
                                let func = *func;
                                let f = syn_to_builder(func)?;
                                let mut cs = Vec::new();
                                for arg in args {
                                    cs.push(syn_to_builder(arg)?);
                                }
                                Ok(f.flatten().apply_no_unroll(cs))
                            }
                            _ => panic!("no_unroll must wrap a function call"),
                        }
                    }
                    func => {
                        let f = syn_to_builder(func)?;
                        let mut cs = Vec::new();
                        for arg in args {
                            cs.push(syn_to_builder(arg)?);
                        }
            
                        // Note: this orders the Seq, Apply, and Force nodes
                        // differently than the previous algorithm, and
                        // differently to the CPBV algorithm. But it seems to be
                        // equivalent.
                        Ok(f.flatten().apply(cs))
                    }
                }
            }
        }


        Expr::Closure(ExprClosure { inputs, body, .. }) => {
            let body_builder = syn_to_builder(*body)?;

            // Got patterns and types
            let pats_and_types: Vec<(Pattern, VType)> = inputs
                .into_iter()
                .map(|i| {
                    let (p, t_opt) = pat_to_rir_pattern(i)?;
                    match t_opt {
                        Some(t) => Ok((p, t)),
                        None => Err(format!("Closure arguments must have type annotations.")),
                    }
                })
                .collect::<Result<_, _>>()?;


            // Generates n fresh id's with with_x_many
            let body_builder = Builder::with_x_many(pats_and_types.len(), move |fresh_idents: Vec<RirIdent>| {
                let mut xs: Vec<(RirIdent, VType)> = Vec::new();
                let mut bb = body_builder;

                for ((p, t), tmp_ident) in pats_and_types.into_iter().zip(fresh_idents.into_iter()) {
                    // Add fresh ident and it's type
                    xs.push((tmp_ident.clone(), t.clone()));

                    // Bind fresh idents with seq_pattern
                    bb = Builder::var(tmp_ident).seq_pattern(p, bb);
                }

                // Return into_fun(xs)
                bb.into_fun(xs)
            });

            Ok(Builder::return_thunk(body_builder))
        }




        Expr::Macro(ExprMacro{ mac: Macro{ path, tokens, .. }, .. }) => {
            // match 'path' into the quantifier
            let quantifier = match path.segments.first() {
                Some(s) => match s.ident.to_string().as_str() {
                    "forall" => Quantifier::Forall,
                    "exists" => Quantifier::Exists,
                    s => return Err(format!(
                        "Can't handle call to unknown macro '{}', expected only 'forall' or 'exists' in this context",
                        s,
                    )),
                }
                None => return Err(format!(
                    "Can't handle call to unknown macro '{:?}', expected only 'forall' or 'exists' in this context",
                    path,
                )),
            };

            // parse the tokens, then match result as a closure
            let expr: Expr = syn::parse(tokens.into()).unwrap();
            q_body(quantifier, expr)
        }

        Expr::Match(expr) => {
            let target = syn_to_builder(*expr.expr)?;
            let arms: Vec<(MatchArm, Builder)> = expr.arms
                .into_iter()
                .map(|arm| {
                    match arm.pat {
                        Pat::TupleStruct(pat) => {
                            assert!(
                                pat.path.segments.len() == 2,
                                "match arm path should have 2 segments",
                            );
                            let segments: Vec<&PathSegment> =
                                pat.path.segments.iter().collect();
                            let ty_seg = segments[0].clone();
                            let ty: String =
                                ty_seg.ident.to_string();
                            let targs: Vec<VType> = type_args_from_seg(ty_seg)?;
                            let constructor: String =
                                segments[1].clone().ident.to_string();
                            let code = OpCode {
                                ident: constructor,
                                path: Some(ty),
                                types: targs,
                            };

                            let binders: Vec<Pattern> = pat.elems
                                .iter()
                                .map(|p| {
                                    Pattern::from_pat(p.clone()).map(|tup|tup.0)
                                })
                                .collect::<Result<Vec<_>, _>>()?;

                            let comp = syn_to_builder(*arm.body)?;
                            Ok((MatchArm{code, binders}, comp))
                        }
                        Pat::Path(pat) => {
                            assert!(
                                pat.path.segments.len() == 2,
                                "match arm path should have 2 segments",
                            );
                            let segments: Vec<&PathSegment> =
                                pat.path.segments.iter().collect();
                            let ty_seg = segments[0].clone();
                            let ty: String =
                                ty_seg.ident.to_string();
                            let targs: Vec<VType> = type_args_from_seg(ty_seg)?;
                            let constructor: String =
                                segments[1].clone().ident.to_string();
                            let code = OpCode {
                                ident: constructor,
                                path: Some(ty),
                                types: targs,
                            };

                            let comp = syn_to_builder(*arm.body)?;
                            Ok((MatchArm{
                                code,
                                binders: Vec::new()
                            }, comp))
                        }
                        p => panic!("can't parse match arm from {:?}", p),
                    }
                })
                .collect::<Result<Vec<_>, Error>>()?;
            Ok(target.mat(arms))
        }

        Expr::Paren(ExprParen{expr,..}) => syn_to_builder(*expr),

        Expr::Path(mut ep) => {
            if ep.path.segments.len() == 1 {
                let PathSegment{ident,arguments} =
                    ep.path.segments.pop().unwrap().into_value();
                let types = match arguments {
                    PathArguments::None => Vec::new(),
                    PathArguments::AngleBracketed(a) => {
                        a.args.into_pairs().map(|pr| {
                            match pr.into_value() {
                                GenericArgument::Type(t) =>
                                    VType::from_syn(t).unwrap(),
                                a => panic!("Can't handle this generic argument: {:?}", a),
                            }
                        }).collect()
                    }
                    PathArguments::Parenthesized(args) => {
                        panic!("Can't handle parenthesized path arguments: {:?}", args)
                    }
                };
                // This could be either a primitive function call
                // (with type args) or a variable (which cannot have
                // type args). For now, we do not distinguish here.
                let code = OpCode::fun_types(ident, types);
                Ok(code.as_fun().builder())
            } else if ep.path.segments.len() == 2 {
                let PathSegment{ident: ident2, arguments: arguments2} =
                    ep.path.segments.pop().unwrap().into_value();
                let PathSegment{ident: ident1, arguments: arguments1} =
                    ep.path.segments.pop().unwrap().into_value();
                // Get the type arguments from the first path seg
                let types = match arguments1 {
                    PathArguments::None => Vec::new(),
                    PathArguments::AngleBracketed(a) => {
                        a.args.into_pairs().map(|pr| {
                            match pr.into_value() {
                                GenericArgument::Type(t) =>
                                    VType::from_syn(t).unwrap(),
                                a => panic!("Can't handle this generic argument: {:?}", a),
                            }
                        }).collect()
                    }
                    PathArguments::Parenthesized(args) => {
                        panic!("Can't handle parenthesized path arguments: {:?}", args)
                    }
                };
                assert!(
                    arguments2 == PathArguments::None,
                    "2-segment paths should not have type args on second seg: {:?}",
                    ep.path,
                );
                let code = OpCode::enum_con(ident1, types, ident2);
                Ok(code.as_fun().builder())
                // Ok(Builder::return_(Val::Var(RirIdent::new(ident2), types, Some(ident1.to_string()))))
            } else {
                panic!("Got path with more than 2 segments: {:?}", ep.path)
            }
        }

        Expr::Reference(e) => syn_to_builder(*e.expr),

        Expr::Tuple(t) => {
            let mut bs = Vec::new();
            for e in t.elems.into_iter() {
                bs.push(syn_to_builder(e)?);
            }
            Ok(Builder::tuple(bs))
        }
        Expr::Unary(ExprUnary{op,expr,..}) => {
            let b = syn_to_builder(*expr)?;
            match op {
                UnOp::Not(_) => Ok(b.not()),
                UnOp::Deref(_) => Ok(b),
                op => Err(format!("Unhandled unary op {:?}", op)),
            }
        }

        e => mk_err(format!("This form of expression is not supported by Ravencheck, and thus can only be used in the body of a #[declare] item: {}", e.to_token_stream())),
    }
}

#[derive(Clone)]
pub struct RirFnSig {
    pub ident: String,
    pub tas: Vec<String>,
    pub inputs: Vec<(Pattern, VType)>,
    pub output: VType,
}

impl RirFnSig {
    pub fn from_syn(sig: Signature) -> Result<Self, Error> {
        let Signature{ident, generics, inputs, output, ..} = sig;
        let ident = ident.to_string();
        let tas = generics.params
            .into_pairs()
            .filter_map(|p| match p.into_value() {
                GenericParam::Type(tp) => Some(tp.ident.to_string()),
                _ => None,
            })
            .collect();
        let inputs = inputs
            .into_pairs()
            .map(|p| match p.into_value() {
                FnArg::Typed(pt) => Pattern::from_pat_type(pt),
                FnArg::Receiver(_) => Err(format!("function '{}' should not take a 'self' input", &ident)),
            })
            .collect::<Result<Vec<_>, _>>()?;
        let output = match output {
            ReturnType::Default => Err(format!("function '{}' has unspecified return type", &ident)),
            ReturnType::Type(_, t) => VType::from_syn(*t),
        }?;
        Ok(RirFnSig{ident, tas, inputs, output})
    }
    pub fn input_types(&self) -> Vec<VType> {
        self.inputs.iter().map(|(_,t)| t.clone()).collect()
    }
}

#[derive(Clone)]
pub struct RirFn {
    pub sig: RirFnSig,
    pub body: Comp,
}

impl RirFn {
    /// Return a `Builder` that uses the fn item's arguments
    /// as the signature of a universal quantifier.
    ///
    /// Advance the given `IGen` using the body.
    pub fn into_uni_formula(
        self,
        igen: &mut IGen,
    ) -> Result<(String, Vec<String>, Builder), String> {
        let Self{sig, body} = self;

        body.advance_igen(igen);

        // The output type is expected to be bool, but we don't
        // check/enforce that here.
        let RirFnSig{ident, tas, inputs, ..} = sig;
        // If there are arguments to quantify, then wrap the fn item's
        // body in a universal quantifier that quantifies them.
        //
        // Otherwise, just convert the unchanged body into a
        // `Builder`.
        let body = if inputs.len() > 0 {
            let inputs = inputs
                .into_iter()
                .map(|(p,t)| Ok((p.unwrap_vname()?, t)))
                .collect::<Result<Vec<_>,String>>()?;
            Builder::lift(body).into_quantifier(
                Quantifier::Forall,
                inputs,
            )
        } else {
            Builder::lift(body)
        };
        Ok((ident, tas, body))
    }

    pub fn from_syn(
        ItemFn{sig, block, ..}: ItemFn,
    ) -> Result<Self, Error> {
        let sig = RirFnSig::from_syn(sig)?;
        let body = match block_to_builder(*block) {
            Ok(b) => Ok(b.build_with(&mut IGen::new())),
            Err(e) => Err(e),
        }?;
        Ok(RirFn{sig, body})
    }
}

fn type_args_from_seg(seg: PathSegment) -> Result<Vec<VType>, String> {
    match seg.arguments {
        PathArguments::None => Ok(Vec::new()),
        PathArguments::AngleBracketed(bs) => {
            bs
                .args
                .into_pairs()
                .map(|p| p.into_value())
                .map(|ga| match ga {
                    GenericArgument::Type(t) =>
                        VType::from_syn(t),
                    ga => Err(format!("Can't handle type argument of form {:?}", ga)),
                })
                // .map(|t| VType::from_syn(t).unwrap())
                .collect::<Result<Vec<_>, _>>()
        }
        PathArguments::Parenthesized(..) => Err(format!("Can't handle parenthesized type arguments")),
    }
}

fn is_box_new(expr: &Expr) -> bool {
    match expr {
        Expr::Path(expr) => {
            let segs = &expr.path.segments;
            segs.len() == 2 && &segs[0].ident == "Box" && &segs[1].ident == "new"
        }
        _ => false,
    }
}