sigma-compiler-core 0.2.1

Core functionality for the macros in the sigma-compiler crate
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
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
//! This module creates and manipulates trees of basic statements
//! combined with `AND`, `OR`, and `THRESH`.

use super::types::*;
use quote::quote;
use std::collections::{HashMap, HashSet};
use syn::parse::Result;
use syn::visit::Visit;
use syn::{parse_quote, Expr, Ident};

/// For each [`Ident`](struct@syn::Ident) representing a private
/// `Scalar` (as listed in a [`VarDict`]) that appears in an [`Expr`],
/// call a given closure.
pub struct PrivScalarMap<'a> {
    /// The [`VarDict`] that maps variable names to their types
    pub vars: &'a VarDict,

    /// The closure that is called for each [`Ident`](struct@syn::Ident)
    /// found in the [`Expr`] (provided in the call to
    /// [`visit_expr`](PrivScalarMap::visit_expr)) that represents a
    /// private `Scalar`
    pub closure: &'a mut dyn FnMut(&syn::Ident) -> Result<()>,

    /// The accumulated result.  This will be the first
    /// [`Err`](Result::Err) returned from the closure, or
    /// [`Ok(())`](Result::Ok) if all calls to the closure succeeded.
    pub result: Result<()>,
}

impl<'a> Visit<'a> for PrivScalarMap<'a> {
    fn visit_path(&mut self, path: &'a syn::Path) {
        // Whenever we see a `Path`, check first if it's just a bare
        // `Ident`
        let Some(id) = path.get_ident() else {
            return;
        };
        // Then check if that `Ident` appears in the `VarDict`
        let Some(vartype) = self.vars.get(&id.to_string()) else {
            return;
        };
        // If so, and the `Ident` represents a private Scalar,
        // call the closure if we haven't seen an `Err` returned from
        // the closure yet.
        if let AExprType::Scalar { is_pub: false, .. } = vartype {
            if self.result.is_ok() {
                self.result = (self.closure)(id);
            }
        }
    }
}

/// The statements in the ZKP form a tree.  The leaves are basic
/// statements of various kinds; for example, equations or inequalities
/// about Scalars and Points.  The interior nodes are combiners: `And`,
/// `Or`, or `Thresh` (with a given constant threshold).  A leaf is true
/// if the basic statement it contains is true.  An `And` node is true
/// if all of its children are true.  An `Or` node is true if at least
/// one of its children is true.  A `Thresh` node (with threshold `k`) is
/// true if at least `k` of its children are true.

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum StatementTree {
    Leaf(Expr),
    And(Vec<StatementTree>),
    Or(Vec<StatementTree>),
    Thresh(usize, Vec<StatementTree>),
}

impl StatementTree {
    #[cfg(not(doctest))]
    /// Parse an [`Expr`] (which may contain nested `AND`, `OR`, or
    /// `THRESH`) into a [`StatementTree`].  For example, the
    /// [`Expr`] obtained from:
    /// ```
    /// parse_quote! {
    ///    AND (
    ///        C = c*B + r*A,
    ///        D = d*B + s*A,
    ///        OR (
    ///            AND (
    ///                C = c0*B + r0*A,
    ///                D = d0*B + s0*A,
    ///                c0 = d0,
    ///            ),
    ///            AND (
    ///                C = c1*B + r1*A,
    ///                D = d1*B + s1*A,
    ///                c1 = d1 + 1,
    ///            ),
    ///        )
    ///    )
    /// }
    /// ```
    ///
    /// would yield a [`StatementTree::And`] containing a 3-element
    /// vector.  The first two elements are [`StatementTree::Leaf`], and
    /// the third is [`StatementTree::Or`] containing a 2-element
    /// vector.  Each element is an [`StatementTree::And`] with a vector
    /// containing 3 [`StatementTree::Leaf`]s.
    ///
    /// Note that `AND`, `OR`, and `THRESH` in the expression are
    /// case-insensitive.
    pub fn parse(expr: &Expr) -> Result<Self> {
        // See if the expression describes a combiner
        if let Expr::Call(syn::ExprCall { func, args, .. }) = expr {
            if let Expr::Path(syn::ExprPath { path, .. }) = func.as_ref() {
                if let Some(funcname) = path.get_ident() {
                    match funcname.to_string().to_lowercase().as_str() {
                        "and" => {
                            let children: Result<Vec<StatementTree>> =
                                args.iter().map(Self::parse).collect();
                            return Ok(Self::And(children?));
                        }
                        "or" => {
                            let children: Result<Vec<StatementTree>> =
                                args.iter().map(Self::parse).collect();
                            return Ok(Self::Or(children?));
                        }
                        "thresh" => {
                            if let Some(Expr::Lit(syn::ExprLit {
                                lit: syn::Lit::Int(litint),
                                ..
                            })) = args.first()
                            {
                                let thresh = litint.base10_parse::<usize>()?;
                                // Remember that args.len() is one more
                                // than the number of expressions,
                                // because the first arg is the
                                // threshold
                                if thresh < 1 || thresh >= args.len() {
                                    return Err(syn::Error::new(
                                        litint.span(),
                                        "threshold out of range",
                                    ));
                                }
                                let children: Result<Vec<StatementTree>> =
                                    args.iter().skip(1).map(Self::parse).collect();
                                return Ok(Self::Thresh(thresh, children?));
                            }
                        }
                        _ => {}
                    }
                }
            }
        }
        Ok(StatementTree::Leaf(expr.clone()))
    }

    /// A convenience function that takes a list of [`Expr`]s, and
    /// returns the [`StatementTree`] that implicitly puts `AND` around
    /// the [`Expr`]s.  This is useful because a common thing to do is
    /// to just write a list of [`Expr`]s in the top-level macro
    /// invocation, having the semantics of "all of these must be true".
    pub fn parse_andlist(exprlist: &[Expr]) -> Result<Self> {
        let children: Result<Vec<StatementTree>> = exprlist.iter().map(Self::parse).collect();
        Ok(StatementTree::And(children?))
    }

    /// Return a vector of references to all of the leaf expressions in
    /// the [`StatementTree`]
    pub fn leaves(&self) -> Vec<&Expr> {
        match self {
            StatementTree::Leaf(ref e) => vec![e],
            StatementTree::And(v) | StatementTree::Or(v) | StatementTree::Thresh(_, v) => {
                v.iter().fold(Vec::<&Expr>::new(), |mut b, st| {
                    b.extend(st.leaves());
                    b
                })
            }
        }
    }

    /// Return a vector of mutable references to all of the leaf
    /// expressions in the [`StatementTree`]
    pub fn leaves_mut(&mut self) -> Vec<&mut Expr> {
        match self {
            StatementTree::Leaf(ref mut e) => vec![e],
            StatementTree::And(v) | StatementTree::Or(v) | StatementTree::Thresh(_, v) => {
                v.iter_mut().fold(Vec::<&mut Expr>::new(), |mut b, st| {
                    b.extend(st.leaves_mut());
                    b
                })
            }
        }
    }

    /// Return a vector of mutable references to all of the leaves in
    /// the [`StatementTree`]
    pub fn leaves_st_mut(&mut self) -> Vec<&mut StatementTree> {
        match self {
            StatementTree::Leaf(_) => vec![self],
            StatementTree::And(v) | StatementTree::Or(v) | StatementTree::Thresh(_, v) => v
                .iter_mut()
                .fold(Vec::<&mut StatementTree>::new(), |mut b, st| {
                    b.extend(st.leaves_st_mut());
                    b
                }),
        }
    }

    #[cfg(not(doctest))]
    /// Verify whether the [`StatementTree`] satisfies the disjunction
    /// invariant.
    ///
    /// A _disjunction node_ is an [`Or`](StatementTree::Or) or
    /// [`Thresh`](StatementTree::Thresh) node in the [`StatementTree`].
    ///
    /// A _disjunction branch_ is a subtree rooted at a non-disjunction
    /// node that is the child of a disjunction node or at the root of
    /// the [`StatementTree`].
    ///
    /// The _disjunction invariant_ is that a private variable (which is
    /// necessarily a `Scalar` since there are no private `Point`
    /// variables) that appears in a disjunction branch cannot also
    /// appear outside of that disjunction branch.
    ///
    /// For example, if all of the lowercase variables are private
    /// `Scalar`s, the [`StatementTree`] created from:
    ///
    /// ```
    ///    AND (
    ///        C = c*B + r*A,
    ///        D = d*B + s*A,
    ///        OR (
    ///            AND (
    ///                C = c0*B + r0*A,
    ///                D = d0*B + s0*A,
    ///                c0 = d0,
    ///            ),
    ///            AND (
    ///                C = c1*B + r1*A,
    ///                D = d1*B + s1*A,
    ///                c1 = d1 + 1,
    ///            ),
    ///        )
    ///    )
    /// ```
    ///
    /// satisfies the disjunction invariant, but
    ///
    /// ```
    ///    AND (
    ///        C = c*B + r*A,
    ///        D = d*B + s*A,
    ///        OR (
    ///            AND (
    ///                D = d0*B + s0*A,
    ///                c = d0,
    ///            ),
    ///            AND (
    ///                C = c1*B + r1*A,
    ///                D = d1*B + s1*A,
    ///                c1 = d1 + 1,
    ///            ),
    ///        )
    ///    )
    /// ```
    ///
    /// does not, because `c` appears in the first child of the `OR` and
    /// also outside of the `OR` entirely.  Indeed, the reason to write
    /// the first expression above rather than the more natural
    ///
    /// ```
    ///    AND (
    ///        C = c*B + r*A,
    ///        D = d*B + s*A,
    ///        OR (
    ///            c = d,
    ///            c = d + 1,
    ///        )
    ///    )
    /// ```
    ///
    /// is exactly that the invariant must be satisfied.
    ///
    /// If you don't know that your [`StatementTree`] already satisfies
    /// the invariant, call
    /// [`enforce_disjunction_invariant`](super::super::enforce_disjunction_invariant),
    /// which will transform the [`StatementTree`] so that it does (and
    /// also call this
    /// [`check_disjunction_invariant`](StatementTree::check_disjunction_invariant)
    /// function as a sanity check).
    pub fn check_disjunction_invariant(&self, vars: &VarDict) -> Result<()> {
        let mut disjunct_map: HashMap<String, usize> = HashMap::new();

        // If the recursive call returns Err, return that Err.
        // Otherwise, we don't care about the Ok(usize) returned, so
        // just return Ok(())
        self.check_disjunction_invariant_rec(vars, &mut disjunct_map, 0, 0)?;
        Ok(())
    }

    /// Internal recursive helper for
    /// [`check_disjunction_invariant`](StatementTree::check_disjunction_invariant).
    ///
    /// The `disjunct_map` is a [`HashMap`] that maps the names of
    /// variables to an identifier of which child of a disjunction node
    /// the variable appears in (or the root if none).  In the case of
    /// nested disjunction node, the closest one to the leaf is what
    /// matters.  Nodes are numbered in pre-order fashion, starting at 0
    /// for the root, 1 for the first child of the root, 2 for the first
    /// child of node 1, etc.  `cur_node` is the node id of `self`, and
    /// `cur_disjunct_child` is the node id of the closest child of a
    /// disjunction node (or 0 for the root if none).  Returns the next
    /// node id to use in the preorder traversal.
    fn check_disjunction_invariant_rec(
        &self,
        vars: &VarDict,
        disjunct_map: &mut HashMap<String, usize>,
        cur_node: usize,
        cur_disjunct_child: usize,
    ) -> Result<usize> {
        let mut next_node = cur_node;
        match self {
            Self::And(v) => {
                for st in v {
                    next_node = st.check_disjunction_invariant_rec(
                        vars,
                        disjunct_map,
                        next_node + 1,
                        cur_disjunct_child,
                    )?;
                }
            }
            Self::Or(v) | Self::Thresh(_, v) => {
                for st in v {
                    next_node = st.check_disjunction_invariant_rec(
                        vars,
                        disjunct_map,
                        next_node + 1,
                        next_node + 1,
                    )?;
                }
            }
            Self::Leaf(e) => {
                let mut psmap = PrivScalarMap {
                    vars,
                    closure: &mut |ident| {
                        let varname = ident.to_string();
                        if let Some(dis_id) = disjunct_map.get(&varname) {
                            if *dis_id != cur_disjunct_child {
                                return Err(syn::Error::new(
                                    ident.span(),
                                    "Disjunction invariant violation: a private variable cannot appear both inside and outside a single term of an OR or THRESH"));
                            }
                        } else {
                            disjunct_map.insert(varname, cur_disjunct_child);
                        }
                        Ok(())
                    },
                    result: Ok(()),
                };
                psmap.visit_expr(e);
                psmap.result?;
            }
        }
        Ok(next_node)
    }

    /// Call the supplied closure for each [disjunction branch] of the
    /// given [`StatementTree`] (including the root, if the root is a
    /// non-disjunction node).
    ///
    /// The calls are in preorder traversal (parents before children).
    /// The given `closure` will be called with the root of each
    /// [disjunction branch] as well as a slice of [`usize`] indicating
    /// the path through the [`StatementTree`] to that disjunction
    /// branch.  The disjunction branch at the root has path `[]`.
    /// The disjunction branch rooted at, say, the 2nd child of an `Or`
    /// node in the root disjunction branch will have path `[2]`.  The
    /// disjunction branch rooted at the 1st child of an `Or` node in
    /// that disjunction branch will have path `[2,1]`, and so on.
    ///
    /// Abort and return `Err` if any call to the closure returns `Err`.
    ///
    /// [disjunction branch]: StatementTree::check_disjunction_invariant
    pub fn for_each_disjunction_branch(
        &mut self,
        closure: &mut dyn FnMut(&mut StatementTree, &[usize]) -> Result<()>,
    ) -> Result<()> {
        let mut path: Vec<usize> = Vec::new();
        self.for_each_disjunction_branch_rec(closure, &mut path, 0, true)?;
        Ok(())
    }

    /// Internal recursive helper for
    /// [`for_each_disjunction_branch`](StatementTree::for_each_disjunction_branch).
    ///
    ///   - `path` is the path to this disjunction branch
    ///   - `last_index` is the last index used for a child of this
    ///     disjunction branch
    ///   - `is_new_branch` is `true` if this node is the start of a new
    ///     disjunction branch
    ///
    /// The return value (if `Ok`) is the updated value of `last_index`.
    fn for_each_disjunction_branch_rec(
        &mut self,
        closure: &mut dyn FnMut(&mut StatementTree, &[usize]) -> Result<()>,
        path: &mut Vec<usize>,
        mut last_index: usize,
        is_new_branch: bool,
    ) -> Result<usize> {
        // We're starting a new branch (and should call the closure) if
        // and only if both is_new_branch is true, and also we're at a
        // non-disjunction node
        match self {
            StatementTree::Leaf(_) | StatementTree::And(_) => {
                if is_new_branch {
                    (closure)(self, path)?;
                }
            }
            _ => {}
        }
        match self {
            StatementTree::Leaf(_) => {}
            StatementTree::And(stvec) => {
                stvec.iter_mut().try_for_each(|st| -> Result<()> {
                    last_index =
                        st.for_each_disjunction_branch_rec(closure, path, last_index, false)?;
                    Ok(())
                })?;
            }
            StatementTree::Or(stvec) | StatementTree::Thresh(_, stvec) => {
                path.push(last_index);
                let pathlen = path.len();
                stvec.iter_mut().try_for_each(|st| -> Result<()> {
                    last_index += 1;
                    path[pathlen - 1] = last_index;
                    st.for_each_disjunction_branch_rec(closure, path, 0, true)?;
                    Ok(())
                })?;
                path.pop();
            }
        }
        Ok(last_index)
    }

    /// Call the supplied closure for each [`StatementTree::Leaf`] of
    /// the given [disjunction branch].
    ///
    /// Abort and return `Err` if any call to the closure returns `Err`.
    ///
    /// [disjunction branch]: StatementTree::check_disjunction_invariant
    pub fn for_each_disjunction_branch_leaf(
        &mut self,
        closure: &mut dyn FnMut(&mut StatementTree) -> Result<()>,
    ) -> Result<()> {
        match self {
            StatementTree::Leaf(_) => {
                (closure)(self)?;
            }
            StatementTree::And(stvec) => {
                stvec
                    .iter_mut()
                    .try_for_each(|st| st.for_each_disjunction_branch_leaf(closure))?;
            }
            StatementTree::Or(_) | StatementTree::Thresh(_, _) => {
                // Don't recurse into Or or Thresh nodes, since the
                // children of those nodes are in different disjunction
                // branches.
            }
        }
        Ok(())
    }

    /// Produce a [`HashSet`] of the private Scalars that appear in any
    /// leaf of the given [disjunction branch].
    ///
    /// [disjunction branch]: StatementTree::check_disjunction_invariant
    pub fn disjunction_branch_priv_scalars(&mut self, vars: &VarDict) -> HashSet<Ident> {
        let mut priv_scalars: HashSet<Ident> = HashSet::new();
        self.for_each_disjunction_branch_leaf(&mut |leaf| {
            if let StatementTree::Leaf(leafexpr) = leaf {
                let mut psmap = PrivScalarMap {
                    vars,
                    closure: &mut |ident| {
                        priv_scalars.insert(ident.clone());
                        Ok(())
                    },
                    result: Ok(()),
                };
                psmap.visit_expr(leafexpr);
            }
            Ok(())
        })
        .unwrap();
        priv_scalars
    }

    #[cfg(not(doctest))]
    /// Flatten nested `And` nodes in a [`StatementTree`].
    ///
    /// The underlying `sigma-proofs` crate can share `Scalars` across
    /// statements that are direct children of the same `And` node, but
    /// not in nested `And` nodes.
    ///
    /// So a [`StatementTree`] like this:
    ///
    /// ```
    ///    AND (
    ///        C = x*B + r*A,
    ///        AND (
    ///            D = x*B + s*A,
    ///            E = x*B + t*A,
    ///        ),
    ///    )
    /// ```
    ///
    /// Needs to be flattened to:
    ///
    /// ```
    ///    AND (
    ///        C = x*B + r*A,
    ///        D = x*B + s*A,
    ///        E = x*B + t*A,
    ///    )
    /// ```
    pub fn flatten_ands(&mut self) {
        match self {
            StatementTree::Leaf(_) => {}
            StatementTree::Or(svec) | StatementTree::Thresh(_, svec) => {
                // Flatten each child
                svec.iter_mut().for_each(|st| st.flatten_ands());
            }
            StatementTree::And(svec) => {
                // Flatten each child, and if any of the children are
                // `And`s, replace that child with the list of its
                // children
                let old_svec = std::mem::take(svec);
                let mut new_svec: Vec<StatementTree> = Vec::new();
                for mut st in old_svec {
                    st.flatten_ands();
                    match st {
                        StatementTree::And(mut child_svec) => {
                            new_svec.append(&mut child_svec);
                        }
                        _ => {
                            new_svec.push(st);
                        }
                    }
                }
                *self = StatementTree::And(new_svec);
            }
        }
    }

    /// Produce a [`StatementTree`] that represents the constant `true`
    pub fn leaf_true() -> StatementTree {
        StatementTree::Leaf(parse_quote! { true })
    }

    /// Test if the given [`StatementTree`] represents the constant `true`
    pub fn is_leaf_true(&self) -> bool {
        if let StatementTree::Leaf(Expr::Lit(exprlit)) = self {
            if let syn::Lit::Bool(syn::LitBool { value: true, .. }) = exprlit.lit {
                return true;
            }
        }
        false
    }

    fn dump_int(&self, depth: usize) {
        match self {
            StatementTree::Leaf(e) => {
                println!(
                    "{:1$}{2},",
                    "",
                    depth * 2,
                    quote! { #e }.to_string().replace('\n', " ")
                )
            }
            StatementTree::And(v) => {
                println!("{:1$}And (", "", depth * 2);
                v.iter().for_each(|n| n.dump_int(depth + 1));
                println!("{:1$})", "", depth * 2);
            }
            StatementTree::Or(v) => {
                println!("{:1$}Or (", "", depth * 2);
                v.iter().for_each(|n| n.dump_int(depth + 1));
                println!("{:1$})", "", depth * 2);
            }
            StatementTree::Thresh(thresh, v) => {
                println!("{:1$}Thresh ({2}", "", depth * 2, thresh);
                v.iter().for_each(|n| n.dump_int(depth + 1));
                println!("{:1$})", "", depth * 2);
            }
        }
    }

    pub fn dump(&self) {
        self.dump_int(0);
    }
}

#[cfg(test)]
mod test {
    use super::StatementTree::*;
    use super::*;
    use quote::quote;

    #[test]
    fn leaf_true_test() {
        assert!(StatementTree::leaf_true().is_leaf_true());
        assert!(!StatementTree::Leaf(parse_quote! { false }).is_leaf_true());
        assert!(!StatementTree::Leaf(parse_quote! { 1 }).is_leaf_true());
        assert!(!StatementTree::parse(&parse_quote! {
            OR(1=1, a=b)
        })
        .unwrap()
        .is_leaf_true());
    }

    #[test]
    fn combiners_simple_test() {
        let exprlist: Vec<Expr> = vec![
            parse_quote! { C = c*B + r*A },
            parse_quote! { D = d*B + s*A },
            parse_quote! { c = d },
        ];

        let statementtree = StatementTree::parse_andlist(&exprlist).unwrap();
        let And(v) = statementtree else {
            panic!("Incorrect result");
        };
        let [Leaf(l0), Leaf(l1), Leaf(l2)] = v.as_slice() else {
            panic!("Incorrect result");
        };
        assert_eq!(quote! {#l0}.to_string(), "C = c * B + r * A");
        assert_eq!(quote! {#l1}.to_string(), "D = d * B + s * A");
        assert_eq!(quote! {#l2}.to_string(), "c = d");
    }

    #[test]
    fn combiners_nested_test() {
        let exprlist: Vec<Expr> = vec![
            parse_quote! { C = c*B + r*A },
            parse_quote! { D = d*B + s*A },
            parse_quote! {
            OR (
                AND (
                    C = c0*B + r0*A,
                    D = d0*B + s0*A,
                    c0 = d0,
                ),
                AND (
                    C = c1*B + r1*A,
                    D = d1*B + s1*A,
                    c1 = d1 + 1,
                ),
            ) },
        ];

        let statementtree = StatementTree::parse_andlist(&exprlist).unwrap();
        let And(v0) = statementtree else {
            panic!("Incorrect result");
        };
        let [Leaf(l0), Leaf(l1), Or(v1)] = v0.as_slice() else {
            panic!("Incorrect result");
        };
        assert_eq!(quote! {#l0}.to_string(), "C = c * B + r * A");
        assert_eq!(quote! {#l1}.to_string(), "D = d * B + s * A");
        let [And(v2), And(v3)] = v1.as_slice() else {
            panic!("Incorrect result");
        };
        let [Leaf(l20), Leaf(l21), Leaf(l22)] = v2.as_slice() else {
            panic!("Incorrect result");
        };
        assert_eq!(quote! {#l20}.to_string(), "C = c0 * B + r0 * A");
        assert_eq!(quote! {#l21}.to_string(), "D = d0 * B + s0 * A");
        assert_eq!(quote! {#l22}.to_string(), "c0 = d0");
        let [Leaf(l30), Leaf(l31), Leaf(l32)] = v3.as_slice() else {
            panic!("Incorrect result");
        };
        assert_eq!(quote! {#l30}.to_string(), "C = c1 * B + r1 * A");
        assert_eq!(quote! {#l31}.to_string(), "D = d1 * B + s1 * A");
        assert_eq!(quote! {#l32}.to_string(), "c1 = d1 + 1");
    }

    #[test]
    fn combiners_thresh_test() {
        let exprlist: Vec<Expr> = vec![
            parse_quote! { C = c*B + r*A },
            parse_quote! { D = d*B + s*A },
            parse_quote! {
            THRESH (1,
                AND (
                    C = c0*B + r0*A,
                    D = d0*B + s0*A,
                    c0 = d0,
                ),
                AND (
                    C = c1*B + r1*A,
                    D = d1*B + s1*A,
                    c1 = d1 + 1,
                ),
            ) },
        ];

        let statementtree = StatementTree::parse_andlist(&exprlist).unwrap();
        let And(v0) = statementtree else {
            panic!("Incorrect result");
        };
        let [Leaf(l0), Leaf(l1), Thresh(thresh, v1)] = v0.as_slice() else {
            panic!("Incorrect result");
        };
        assert_eq!(*thresh, 1);
        assert_eq!(quote! {#l0}.to_string(), "C = c * B + r * A");
        assert_eq!(quote! {#l1}.to_string(), "D = d * B + s * A");
        let [And(v2), And(v3)] = v1.as_slice() else {
            panic!("Incorrect result");
        };
        let [Leaf(l20), Leaf(l21), Leaf(l22)] = v2.as_slice() else {
            panic!("Incorrect result");
        };
        assert_eq!(quote! {#l20}.to_string(), "C = c0 * B + r0 * A");
        assert_eq!(quote! {#l21}.to_string(), "D = d0 * B + s0 * A");
        assert_eq!(quote! {#l22}.to_string(), "c0 = d0");
        let [Leaf(l30), Leaf(l31), Leaf(l32)] = v3.as_slice() else {
            panic!("Incorrect result");
        };
        assert_eq!(quote! {#l30}.to_string(), "C = c1 * B + r1 * A");
        assert_eq!(quote! {#l31}.to_string(), "D = d1 * B + s1 * A");
        assert_eq!(quote! {#l32}.to_string(), "c1 = d1 + 1");
    }

    #[test]
    #[should_panic]
    fn combiners_bad_thresh_test() {
        // The threshold is out of range
        let exprlist: Vec<Expr> = vec![
            parse_quote! { C = c*B + r*A },
            parse_quote! { D = d*B + s*A },
            parse_quote! {
            THRESH (3,
                AND (
                    C = c0*B + r0*A,
                    D = d0*B + s0*A,
                    c0 = d0,
                ),
                AND (
                    C = c1*B + r1*A,
                    D = d1*B + s1*A,
                    c1 = d1 + 1,
                ),
            ) },
        ];

        StatementTree::parse_andlist(&exprlist).unwrap();
    }

    #[test]
    // Test the disjunction invariant checker
    fn disjunction_invariant_test() {
        let vars: VarDict = vardict_from_strs(&[
            ("c", "S"),
            ("d", "S"),
            ("c0", "S"),
            ("c1", "S"),
            ("d0", "S"),
            ("d1", "S"),
            ("A", "pP"),
            ("B", "pP"),
            ("C", "pP"),
            ("D", "pP"),
        ]);
        // This one is OK
        let st_ok = StatementTree::parse(&parse_quote! {
           AND (
               C = c*B + r*A,
               D = d*B + s*A,
               OR (
                   AND (
                       C = c0*B + r0*A,
                       D = d0*B + s0*A,
                       c0 = d0,
                   ),
                   AND (
                       C = c1*B + r1*A,
                       D = d1*B + s1*A,
                       c1 = d1 + 1,
                   ),
               )
           )
        })
        .unwrap();
        // not OK: c0 appears in two branches of the OR
        let st_nok1 = StatementTree::parse(&parse_quote! {
           AND (
               C = c*B + r*A,
               D = d*B + s*A,
               OR (
                   AND (
                       C = c0*B + r0*A,
                       D = d0*B + s0*A,
                       c0 = d0,
                   ),
                   AND (
                       C = c0*B + r0*A,
                       D = d1*B + s1*A,
                       c0 = d1 + 1,
                   ),
               )
           )
        })
        .unwrap();
        // not OK: c appears in one branch of the OR and also outside
        // the OR
        let st_nok2 = StatementTree::parse(&parse_quote! {
           AND (
               C = c*B + r*A,
               D = d*B + s*A,
               OR (
                   AND (
                       D = d0*B + s0*A,
                       c = d0,
                   ),
                   AND (
                       C = c1*B + r1*A,
                       D = d1*B + s1*A,
                       c1 = d1 + 1,
                   ),
               )
           )
        })
        .unwrap();
        // not OK: c and d appear in both branches of the OR, and also
        // outside it
        let st_nok3 = StatementTree::parse(&parse_quote! {
           AND (
               C = c*B + r*A,
               D = d*B + s*A,
               OR (
                   c = d,
                   c = d + 1,
               )
           )
        })
        .unwrap();
        st_ok.check_disjunction_invariant(&vars).unwrap();
        st_nok1.check_disjunction_invariant(&vars).unwrap_err();
        st_nok2.check_disjunction_invariant(&vars).unwrap_err();
        st_nok3.check_disjunction_invariant(&vars).unwrap_err();
    }

    fn disjunction_branch_tester(e: Expr, expected: Vec<(Vec<usize>, Expr)>) {
        let mut output: Vec<(Vec<usize>, StatementTree)> = Vec::new();
        let expected_st: Vec<(Vec<usize>, StatementTree)> = expected
            .iter()
            .map(|(path, ex)| (path.clone(), StatementTree::parse(ex).unwrap()))
            .collect();
        let mut st = StatementTree::parse(&e).unwrap();
        st.for_each_disjunction_branch(&mut |db, path| {
            output.push((path.to_vec(), db.clone()));
            Ok(())
        })
        .unwrap();
        assert_eq!(output, expected_st);
    }

    fn disjunction_branch_abort_tester(e: Expr, expected: Vec<(Vec<usize>, Expr)>) {
        let mut output: Vec<(Vec<usize>, StatementTree)> = Vec::new();
        let expected_st: Vec<(Vec<usize>, StatementTree)> = expected
            .iter()
            .map(|(path, ex)| (path.clone(), StatementTree::parse(ex).unwrap()))
            .collect();
        let mut st = StatementTree::parse(&e).unwrap();
        st.for_each_disjunction_branch(&mut |st, path| {
            if st.is_leaf_true() {
                return Err(syn::Error::new(proc_macro2::Span::call_site(), "true leaf"));
            }
            output.push((path.to_vec(), st.clone()));
            Ok(())
        })
        .unwrap_err();
        assert_eq!(output, expected_st);
    }

    #[test]
    fn disjunction_branch_test() {
        disjunction_branch_tester(
            parse_quote! {
                C = c*B + r*A
            },
            vec![(
                vec![],
                parse_quote! {
                    C = c*B + r*A
                },
            )],
        );

        disjunction_branch_tester(
            parse_quote! {
               AND (
                   C = c*B + r*A,
                   D = d*B + s*A,
                   OR (
                       c = d,
                       c = d + 1,
                   )
               )
            },
            vec![
                (
                    vec![],
                    parse_quote! {
                       AND (
                           C = c*B + r*A,
                           D = d*B + s*A,
                           OR (
                               c = d,
                               c = d + 1,
                           )
                       )
                    },
                ),
                (
                    vec![1],
                    parse_quote! {
                        c = d
                    },
                ),
                (
                    vec![2],
                    parse_quote! {
                        c = d + 1
                    },
                ),
            ],
        );

        disjunction_branch_tester(
            parse_quote! {
                OR (
                    C = c*B + r*A,
                    D = c*B + r*A,
                )
            },
            vec![
                (vec![1], parse_quote! { C = c*B + r*A }),
                (vec![2], parse_quote! { D = c*B + r*A }),
            ],
        );

        disjunction_branch_tester(
            parse_quote! {
                AND (
                    C = c*B + r*A,
                    D = d*B + s*A,
                    OR (
                        AND (
                            c = d,
                            D = a*B + b*A,
                            OR (
                                d = 5,
                                d = 6,
                            )
                        ),
                        c = d + 1,
                    )
                )
            },
            vec![
                (
                    vec![],
                    parse_quote! {
                        AND (
                            C = c*B + r*A,
                            D = d*B + s*A,
                            OR (
                                AND (
                                    c = d,
                                    D = a*B + b*A,
                                    OR (
                                        d = 5,
                                        d = 6,
                                    )
                                ),
                                c = d + 1,
                            )
                        )
                    },
                ),
                (
                    vec![1],
                    parse_quote! {
                        AND (
                            c = d,
                            D = a*B + b*A,
                            OR (
                                d = 5,
                                d = 6,
                            )
                        )
                    },
                ),
                (
                    vec![1, 1],
                    parse_quote! {
                        d = 5
                    },
                ),
                (
                    vec![1, 2],
                    parse_quote! {
                        d = 6
                    },
                ),
                (
                    vec![2],
                    parse_quote! {
                        c = d + 1
                    },
                ),
            ],
        );

        disjunction_branch_tester(
            parse_quote! {
                AND (
                    C = c*B + r*A,
                    D = d*B + s*A,
                    AND (
                        c = d + 1,
                        AND (
                            s = r,
                            OR (
                                d = 1,
                                AND (
                                    d = 2,
                                    s = 1,
                                )
                            )
                        )
                    ),
                    OR (
                        AND (
                            c = d,
                            D = a*B + b*A,
                            OR (
                                d = 5,
                                d = 6,
                            )
                        ),
                        c = d + 1,
                    )
                )
            },
            vec![
                (
                    vec![],
                    parse_quote! {
                        AND (
                            C = c*B + r*A,
                            D = d*B + s*A,
                            AND (
                                c = d + 1,
                                AND (
                                    s = r,
                                    OR (
                                        d = 1,
                                        AND (
                                            d = 2,
                                            s = 1,
                                        )
                                    )
                                )
                            ),
                            OR (
                                AND (
                                    c = d,
                                    D = a*B + b*A,
                                    OR (
                                        d = 5,
                                        d = 6,
                                    )
                                ),
                                c = d + 1,
                            )
                        )
                    },
                ),
                (vec![1], parse_quote! { d = 1 }),
                (
                    vec![2],
                    parse_quote! {
                        AND (
                            d = 2,
                            s = 1,
                        )
                    },
                ),
                (
                    vec![3],
                    parse_quote! {
                        AND (
                            c = d,
                            D = a*B + b*A,
                            OR (
                                d = 5,
                                d = 6,
                            )
                        )
                    },
                ),
                (
                    vec![3, 1],
                    parse_quote! {
                        d = 5
                    },
                ),
                (
                    vec![3, 2],
                    parse_quote! {
                        d = 6
                    },
                ),
                (
                    vec![4],
                    parse_quote! {
                        c = d + 1
                    },
                ),
            ],
        );

        disjunction_branch_abort_tester(
            parse_quote! {
                AND (
                    C = c*B + r*A,
                    D = d*B + s*A,
                    OR (
                        AND (
                            c = d,
                            D = a*B + b*A,
                            OR (
                                d = 5,
                                true,
                                d = 6,
                            )
                        ),
                        c = d + 1,
                    )
                )
            },
            vec![
                (
                    vec![],
                    parse_quote! {
                        AND (
                            C = c*B + r*A,
                            D = d*B + s*A,
                            OR (
                                AND (
                                    c = d,
                                    D = a*B + b*A,
                                    OR (
                                        d = 5,
                                        true,
                                        d = 6,
                                    )
                                ),
                                c = d + 1,
                            )
                        )
                    },
                ),
                (
                    vec![1],
                    parse_quote! {
                        AND (
                            c = d,
                            D = a*B + b*A,
                            OR (
                                d = 5,
                                true,
                                d = 6,
                            )
                        )
                    },
                ),
                (
                    vec![1, 1],
                    parse_quote! {
                        d = 5
                    },
                ),
            ],
        );
    }

    fn disjunction_branch_leaf_tester(e: Expr, expected: Vec<(Vec<usize>, Vec<Expr>)>) {
        let mut output: Vec<(Vec<usize>, Vec<StatementTree>)> = Vec::new();
        let expected_st: Vec<(Vec<usize>, Vec<StatementTree>)> = expected
            .iter()
            .map(|(path, vex)| {
                (
                    path.clone(),
                    vex.iter()
                        .map(|ex| StatementTree::parse(ex).unwrap())
                        .collect(),
                )
            })
            .collect();
        let mut st = StatementTree::parse(&e).unwrap();
        st.for_each_disjunction_branch(&mut |db, path| {
            let mut dis_branch_output: Vec<StatementTree> = Vec::new();
            db.for_each_disjunction_branch_leaf(&mut |leaf| {
                dis_branch_output.push(leaf.clone());
                Ok(())
            })
            .unwrap();
            output.push((path.to_vec(), dis_branch_output));
            Ok(())
        })
        .unwrap();
        assert_eq!(output, expected_st);
    }

    fn disjunction_branch_leaf_abort_tester(e: Expr, expected: Vec<(Vec<usize>, Vec<Expr>)>) {
        let mut output: Vec<(Vec<usize>, Vec<StatementTree>)> = Vec::new();
        let expected_st: Vec<(Vec<usize>, Vec<StatementTree>)> = expected
            .iter()
            .map(|(path, vex)| {
                (
                    path.clone(),
                    vex.iter()
                        .map(|ex| StatementTree::parse(ex).unwrap())
                        .collect(),
                )
            })
            .collect();
        let mut st = StatementTree::parse(&e).unwrap();
        st.for_each_disjunction_branch(&mut |db, path| {
            let mut dis_branch_output: Vec<StatementTree> = Vec::new();
            db.for_each_disjunction_branch_leaf(&mut |leaf| {
                if leaf.is_leaf_true() {
                    return Err(syn::Error::new(proc_macro2::Span::call_site(), "true leaf"));
                }
                dis_branch_output.push(leaf.clone());
                Ok(())
            })?;
            output.push((path.to_vec(), dis_branch_output));
            Ok(())
        })
        .unwrap_err();
        assert_eq!(output, expected_st);
    }

    #[test]
    fn disjunction_branch_leaf_test() {
        disjunction_branch_leaf_tester(
            parse_quote! {
                C = c*B + r*A
            },
            vec![(vec![], vec![parse_quote! { C = c*B + r*A }])],
        );

        disjunction_branch_leaf_tester(
            parse_quote! {
               AND (
                   C = c*B + r*A,
                   D = d*B + s*A,
                   OR (
                       c = d,
                       c = d + 1,
                   )
               )
            },
            vec![
                (
                    vec![],
                    vec![
                        parse_quote! { C = c*B + r*A },
                        parse_quote! { D = d*B + s*A },
                    ],
                ),
                (vec![1], vec![parse_quote! { c = d }]),
                (vec![2], vec![parse_quote! { c = d + 1 }]),
            ],
        );

        disjunction_branch_leaf_tester(
            parse_quote! {
               AND (
                   C = c*B + r*A,
                   D = d*B + s*A,
                   OR (
                       c = d,
                       OR (
                           c = d + 1,
                           c = d + 2,
                        )
                   )
               )
            },
            vec![
                (
                    vec![],
                    vec![
                        parse_quote! { C = c*B + r*A },
                        parse_quote! { D = d*B + s*A },
                    ],
                ),
                (vec![1], vec![parse_quote! { c = d }]),
                (vec![2, 1], vec![parse_quote! { c = d + 1 }]),
                (vec![2, 2], vec![parse_quote! { c = d + 2 }]),
            ],
        );

        disjunction_branch_leaf_tester(
            parse_quote! {
                AND (
                    C = c*B + r*A,
                    D = d*B + s*A,
                    OR (
                        AND (
                            c = d,
                            D = a*B + b*A,
                            OR (
                                d = 5,
                                d = 6,
                            )
                        ),
                        c = d + 1,
                    )
                )
            },
            vec![
                (
                    vec![],
                    vec![
                        parse_quote! { C = c*B + r*A },
                        parse_quote! { D = d*B + s*A },
                    ],
                ),
                (
                    vec![1],
                    vec![
                        parse_quote! { c = d },
                        parse_quote! { D
                        = a*B + b*A },
                    ],
                ),
                (vec![1, 1], vec![parse_quote! { d = 5 }]),
                (vec![1, 2], vec![parse_quote! { d = 6 }]),
                (vec![2], vec![parse_quote! { c = d + 1 }]),
            ],
        );

        disjunction_branch_leaf_abort_tester(
            parse_quote! {
                AND (
                    C = c*B + r*A,
                    D = d*B + s*A,
                    OR (
                        AND (
                            c = d,
                            D = a*B + b*A,
                            OR (
                                d = 5,
                                true,
                                d = 6,
                            )
                        ),
                        c = d + 1,
                    )
                )
            },
            vec![
                (
                    vec![],
                    vec![
                        parse_quote! { C = c*B + r*A },
                        parse_quote! { D = d*B + s*A },
                    ],
                ),
                (
                    vec![1],
                    vec![
                        parse_quote! { c = d },
                        parse_quote! { D
                        = a*B + b*A },
                    ],
                ),
                (vec![1, 1], vec![parse_quote! { d = 5 }]),
            ],
        );
    }

    fn flatten_ands_tester(e: Expr, flattened_e: Expr) {
        let mut st = StatementTree::parse(&e).unwrap();
        st.flatten_ands();
        assert_eq!(st, StatementTree::parse(&flattened_e).unwrap());
    }

    #[test]
    // Test flatten_ands
    fn flatten_ands_test() {
        flatten_ands_tester(
            parse_quote! {
                C = x*B + r*A
            },
            parse_quote! {
                C = x*B + r*A
            },
        );

        flatten_ands_tester(
            parse_quote! {
                AND (
                    C = x*B + r*A,
                    AND (
                        D = x*B + s*A,
                        E = x*B + t*A,
                    ),
                )
            },
            parse_quote! {
                AND (
                    C = x*B + r*A,
                    D = x*B + s*A,
                    E = x*B + t*A,
                )
            },
        );

        flatten_ands_tester(
            parse_quote! {
                AND (
                    AND (
                        OR (
                            D = B + s*A,
                            D = s*A,
                        ),
                        D = x*B + t*A,
                    ),
                    C = x*B + r*A,
                )
            },
            parse_quote! {
                AND (
                    OR (
                        D = B + s*A,
                        D = s*A,
                    ),
                    D = x*B + t*A,
                    C = x*B + r*A,
                )
            },
        );

        flatten_ands_tester(
            parse_quote! {
                AND (
                    AND (
                        OR (
                            D = B + s*A,
                            AND (
                                D = s*A,
                                AND (
                                    E = s*B,
                                    F = s*C,
                                ),
                            ),
                        ),
                        D = x*B + t*A,
                    ),
                    C = x*B + r*A,
                )
            },
            parse_quote! {
                AND (
                    OR (
                        D = B + s*A,
                        AND (
                            D = s*A,
                            E = s*B,
                            F = s*C,
                        )
                    ),
                    D = x*B + t*A,
                    C = x*B + r*A,
                )
            },
        );
    }
}