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
//! This module implements the data structures of a proof.

use crate::circuits::{
    berkeley_columns::Column,
    gate::GateType,
    lookup::lookups::LookupPattern,
    wires::{COLUMNS, PERMUTS},
};
use ark_ec::AffineRepr;
use ark_ff::{FftField, One, Zero};
use ark_poly::univariate::DensePolynomial;
use o1_utils::ExtendedDensePolynomial;
use poly_commitment::commitment::{b_poly, b_poly_coefficients, PolyComm};
use serde::{Deserialize, Serialize};
use serde_with::serde_as;
use std::array;

//~ spec:startcode
/// Evaluations of a polynomial at 2 points
#[serde_as]
#[derive(Copy, Clone, Serialize, Deserialize, Default, Debug, PartialEq)]
#[cfg_attr(
    feature = "ocaml_types",
    derive(ocaml::IntoValue, ocaml::FromValue, ocaml_gen::Struct)
)]
#[serde(bound(
    serialize = "Vec<o1_utils::serialization::SerdeAs>: serde_with::SerializeAs<Evals>",
    deserialize = "Vec<o1_utils::serialization::SerdeAs>: serde_with::DeserializeAs<'de, Evals>"
))]
pub struct PointEvaluations<Evals> {
    /// Evaluation at the challenge point zeta.
    #[serde_as(as = "Vec<o1_utils::serialization::SerdeAs>")]
    pub zeta: Evals,
    /// Evaluation at `zeta . omega`, the product of the challenge point and the group generator.
    #[serde_as(as = "Vec<o1_utils::serialization::SerdeAs>")]
    pub zeta_omega: Evals,
}

// TODO: this should really be vectors here, perhaps create another type for chunked evaluations?
/// Polynomial evaluations contained in a `ProverProof`.
/// - **Chunked evaluations** `Field` is instantiated with vectors with a length
/// that equals the length of the chunk
/// - **Non chunked evaluations** `Field` is instantiated with a field, so they
/// are single-sized#[serde_as]
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ProofEvaluations<Evals> {
    /// public input polynomials
    pub public: Option<Evals>,
    /// witness polynomials
    pub w: [Evals; COLUMNS],
    /// permutation polynomial
    pub z: Evals,
    /// permutation polynomials
    /// (PERMUTS-1 evaluations because the last permutation is only used in
    /// commitment form)
    pub s: [Evals; PERMUTS - 1],
    /// coefficient polynomials
    pub coefficients: [Evals; COLUMNS],
    /// evaluation of the generic selector polynomial
    pub generic_selector: Evals,
    /// evaluation of the poseidon selector polynomial
    pub poseidon_selector: Evals,
    /// evaluation of the elliptic curve addition selector polynomial
    pub complete_add_selector: Evals,
    /// evaluation of the elliptic curve variable base scalar multiplication
    /// selector polynomial
    pub mul_selector: Evals,
    /// evaluation of the endoscalar multiplication selector polynomial
    pub emul_selector: Evals,
    /// evaluation of the endoscalar multiplication scalar computation selector
    /// polynomial
    pub endomul_scalar_selector: Evals,

    // Optional gates
    /// evaluation of the RangeCheck0 selector polynomial
    pub range_check0_selector: Option<Evals>,
    /// evaluation of the RangeCheck1 selector polynomial
    pub range_check1_selector: Option<Evals>,
    /// evaluation of the ForeignFieldAdd selector polynomial
    pub foreign_field_add_selector: Option<Evals>,
    /// evaluation of the ForeignFieldMul selector polynomial
    pub foreign_field_mul_selector: Option<Evals>,
    /// evaluation of the Xor selector polynomial
    pub xor_selector: Option<Evals>,
    /// evaluation of the Rot selector polynomial
    pub rot_selector: Option<Evals>,

    // lookup-related evaluations
    /// evaluation of lookup aggregation polynomial
    pub lookup_aggregation: Option<Evals>,
    /// evaluation of lookup table polynomial
    pub lookup_table: Option<Evals>,
    /// evaluation of lookup sorted polynomials
    pub lookup_sorted: [Option<Evals>; 5],
    /// evaluation of runtime lookup table polynomial
    pub runtime_lookup_table: Option<Evals>,

    // lookup selectors
    /// evaluation of the runtime lookup table selector polynomial
    pub runtime_lookup_table_selector: Option<Evals>,
    /// evaluation of the Xor range check pattern selector polynomial
    pub xor_lookup_selector: Option<Evals>,
    /// evaluation of the Lookup range check pattern selector polynomial
    pub lookup_gate_lookup_selector: Option<Evals>,
    /// evaluation of the RangeCheck range check pattern selector polynomial
    pub range_check_lookup_selector: Option<Evals>,
    /// evaluation of the ForeignFieldMul range check pattern selector
    /// polynomial
    pub foreign_field_mul_lookup_selector: Option<Evals>,
}

/// Commitments linked to the lookup feature
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(bound = "G: ark_serialize::CanonicalDeserialize + ark_serialize::CanonicalSerialize")]
pub struct LookupCommitments<G: AffineRepr> {
    /// Commitments to the sorted lookup table polynomial (may have chunks)
    pub sorted: Vec<PolyComm<G>>,
    /// Commitment to the lookup aggregation polynomial
    pub aggreg: PolyComm<G>,
    /// Optional commitment to concatenated runtime tables
    pub runtime: Option<PolyComm<G>>,
}

/// All the commitments that the prover creates as part of the proof.
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(bound = "G: ark_serialize::CanonicalDeserialize + ark_serialize::CanonicalSerialize")]
pub struct ProverCommitments<G: AffineRepr> {
    /// The commitments to the witness (execution trace)
    pub w_comm: [PolyComm<G>; COLUMNS],
    /// The commitment to the permutation polynomial
    pub z_comm: PolyComm<G>,
    /// The commitment to the quotient polynomial
    pub t_comm: PolyComm<G>,
    /// Commitments related to the lookup argument
    pub lookup: Option<LookupCommitments<G>>,
}

/// The proof that the prover creates from a
/// [ProverIndex](super::prover_index::ProverIndex) and a `witness`.
#[serde_as]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(bound = "G: ark_serialize::CanonicalDeserialize + ark_serialize::CanonicalSerialize")]
pub struct ProverProof<G: AffineRepr, OpeningProof> {
    /// All the polynomial commitments required in the proof
    pub commitments: ProverCommitments<G>,

    /// batched commitment opening proof
    #[serde(bound(
        serialize = "OpeningProof: Serialize",
        deserialize = "OpeningProof: Deserialize<'de>"
    ))]
    pub proof: OpeningProof,

    /// Two evaluations over a number of committed polynomials
    pub evals: ProofEvaluations<PointEvaluations<Vec<G::ScalarField>>>,

    /// Required evaluation for [Maller's
    /// optimization](https://o1-labs.github.io/proof-systems/kimchi/maller_15.html#the-evaluation-of-l)
    #[serde_as(as = "o1_utils::serialization::SerdeAs")]
    pub ft_eval1: G::ScalarField,

    /// The challenges underlying the optional polynomials folded into the proof
    pub prev_challenges: Vec<RecursionChallenge<G>>,
}

/// A struct to store the challenges inside a `ProverProof`
#[serde_as]
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq)]
#[serde(bound = "G: ark_serialize::CanonicalDeserialize + ark_serialize::CanonicalSerialize")]
pub struct RecursionChallenge<G>
where
    G: AffineRepr,
{
    /// Vector of scalar field elements
    #[serde_as(as = "Vec<o1_utils::serialization::SerdeAs>")]
    pub chals: Vec<G::ScalarField>,
    /// Polynomial commitment
    pub comm: PolyComm<G>,
}

//~ spec:endcode

impl<Evals> PointEvaluations<Evals> {
    pub fn map<Evals2, FN: Fn(Evals) -> Evals2>(self, f: &FN) -> PointEvaluations<Evals2> {
        let PointEvaluations { zeta, zeta_omega } = self;
        PointEvaluations {
            zeta: f(zeta),
            zeta_omega: f(zeta_omega),
        }
    }

    pub fn map_ref<Evals2, FN: Fn(&Evals) -> Evals2>(&self, f: &FN) -> PointEvaluations<Evals2> {
        let PointEvaluations { zeta, zeta_omega } = self;
        PointEvaluations {
            zeta: f(zeta),
            zeta_omega: f(zeta_omega),
        }
    }
}

impl<Eval> ProofEvaluations<Eval> {
    pub fn map<Eval2, FN: Fn(Eval) -> Eval2>(self, f: &FN) -> ProofEvaluations<Eval2> {
        let ProofEvaluations {
            public,
            w,
            z,
            s,
            coefficients,
            generic_selector,
            poseidon_selector,
            complete_add_selector,
            mul_selector,
            emul_selector,
            endomul_scalar_selector,
            range_check0_selector,
            range_check1_selector,
            foreign_field_add_selector,
            foreign_field_mul_selector,
            xor_selector,
            rot_selector,
            lookup_aggregation,
            lookup_table,
            lookup_sorted,
            runtime_lookup_table,
            runtime_lookup_table_selector,
            xor_lookup_selector,
            lookup_gate_lookup_selector,
            range_check_lookup_selector,
            foreign_field_mul_lookup_selector,
        } = self;
        ProofEvaluations {
            public: public.map(f),
            w: w.map(f),
            z: f(z),
            s: s.map(f),
            coefficients: coefficients.map(f),
            generic_selector: f(generic_selector),
            poseidon_selector: f(poseidon_selector),
            complete_add_selector: f(complete_add_selector),
            mul_selector: f(mul_selector),
            emul_selector: f(emul_selector),
            endomul_scalar_selector: f(endomul_scalar_selector),
            range_check0_selector: range_check0_selector.map(f),
            range_check1_selector: range_check1_selector.map(f),
            foreign_field_add_selector: foreign_field_add_selector.map(f),
            foreign_field_mul_selector: foreign_field_mul_selector.map(f),
            xor_selector: xor_selector.map(f),
            rot_selector: rot_selector.map(f),
            lookup_aggregation: lookup_aggregation.map(f),
            lookup_table: lookup_table.map(f),
            lookup_sorted: lookup_sorted.map(|x| x.map(f)),
            runtime_lookup_table: runtime_lookup_table.map(f),
            runtime_lookup_table_selector: runtime_lookup_table_selector.map(f),
            xor_lookup_selector: xor_lookup_selector.map(f),
            lookup_gate_lookup_selector: lookup_gate_lookup_selector.map(f),
            range_check_lookup_selector: range_check_lookup_selector.map(f),
            foreign_field_mul_lookup_selector: foreign_field_mul_lookup_selector.map(f),
        }
    }

    pub fn map_ref<Eval2, FN: Fn(&Eval) -> Eval2>(&self, f: &FN) -> ProofEvaluations<Eval2> {
        let ProofEvaluations {
            public,
            w: [w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14],
            z,
            s: [s0, s1, s2, s3, s4, s5],
            coefficients: [c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14],
            generic_selector,
            poseidon_selector,
            complete_add_selector,
            mul_selector,
            emul_selector,
            endomul_scalar_selector,
            range_check0_selector,
            range_check1_selector,
            foreign_field_add_selector,
            foreign_field_mul_selector,
            xor_selector,
            rot_selector,
            lookup_aggregation,
            lookup_table,
            lookup_sorted,
            runtime_lookup_table,
            runtime_lookup_table_selector,
            xor_lookup_selector,
            lookup_gate_lookup_selector,
            range_check_lookup_selector,
            foreign_field_mul_lookup_selector,
        } = self;
        ProofEvaluations {
            public: public.as_ref().map(f),
            w: [
                f(w0),
                f(w1),
                f(w2),
                f(w3),
                f(w4),
                f(w5),
                f(w6),
                f(w7),
                f(w8),
                f(w9),
                f(w10),
                f(w11),
                f(w12),
                f(w13),
                f(w14),
            ],
            z: f(z),
            s: [f(s0), f(s1), f(s2), f(s3), f(s4), f(s5)],
            coefficients: [
                f(c0),
                f(c1),
                f(c2),
                f(c3),
                f(c4),
                f(c5),
                f(c6),
                f(c7),
                f(c8),
                f(c9),
                f(c10),
                f(c11),
                f(c12),
                f(c13),
                f(c14),
            ],
            generic_selector: f(generic_selector),
            poseidon_selector: f(poseidon_selector),
            complete_add_selector: f(complete_add_selector),
            mul_selector: f(mul_selector),
            emul_selector: f(emul_selector),
            endomul_scalar_selector: f(endomul_scalar_selector),
            range_check0_selector: range_check0_selector.as_ref().map(f),
            range_check1_selector: range_check1_selector.as_ref().map(f),
            foreign_field_add_selector: foreign_field_add_selector.as_ref().map(f),
            foreign_field_mul_selector: foreign_field_mul_selector.as_ref().map(f),
            xor_selector: xor_selector.as_ref().map(f),
            rot_selector: rot_selector.as_ref().map(f),
            lookup_aggregation: lookup_aggregation.as_ref().map(f),
            lookup_table: lookup_table.as_ref().map(f),
            lookup_sorted: array::from_fn(|i| lookup_sorted[i].as_ref().map(f)),
            runtime_lookup_table: runtime_lookup_table.as_ref().map(f),
            runtime_lookup_table_selector: runtime_lookup_table_selector.as_ref().map(f),
            xor_lookup_selector: xor_lookup_selector.as_ref().map(f),
            lookup_gate_lookup_selector: lookup_gate_lookup_selector.as_ref().map(f),
            range_check_lookup_selector: range_check_lookup_selector.as_ref().map(f),
            foreign_field_mul_lookup_selector: foreign_field_mul_lookup_selector.as_ref().map(f),
        }
    }
}

impl<G: AffineRepr> RecursionChallenge<G> {
    pub fn new(chals: Vec<G::ScalarField>, comm: PolyComm<G>) -> RecursionChallenge<G> {
        RecursionChallenge { chals, comm }
    }

    pub fn evals(
        &self,
        max_poly_size: usize,
        evaluation_points: &[G::ScalarField],
        powers_of_eval_points_for_chunks: &[G::ScalarField],
    ) -> Vec<Vec<G::ScalarField>> {
        let RecursionChallenge { chals, comm: _ } = self;
        // No need to check the correctness of poly explicitly. Its correctness is assured by the
        // checking of the inner product argument.
        let b_len = 1 << chals.len();
        let mut b: Option<Vec<G::ScalarField>> = None;

        (0..2)
            .map(|i| {
                let full = b_poly(chals, evaluation_points[i]);
                if max_poly_size == b_len {
                    return vec![full];
                }
                let mut betaacc = G::ScalarField::one();
                let diff = (max_poly_size..b_len)
                    .map(|j| {
                        let b_j = match &b {
                            None => {
                                let t = b_poly_coefficients(chals);
                                let res = t[j];
                                b = Some(t);
                                res
                            }
                            Some(b) => b[j],
                        };

                        let ret = betaacc * b_j;
                        betaacc *= &evaluation_points[i];
                        ret
                    })
                    .fold(G::ScalarField::zero(), |x, y| x + y);
                vec![full - (diff * powers_of_eval_points_for_chunks[i]), diff]
            })
            .collect()
    }
}

impl<F: Zero + Copy> ProofEvaluations<PointEvaluations<F>> {
    pub fn dummy_with_witness_evaluations(
        curr: [F; COLUMNS],
        next: [F; COLUMNS],
    ) -> ProofEvaluations<PointEvaluations<F>> {
        let pt = |curr, next| PointEvaluations {
            zeta: curr,
            zeta_omega: next,
        };
        ProofEvaluations {
            public: Some(pt(F::zero(), F::zero())),
            w: array::from_fn(|i| pt(curr[i], next[i])),
            z: pt(F::zero(), F::zero()),
            s: array::from_fn(|_| pt(F::zero(), F::zero())),
            coefficients: array::from_fn(|_| pt(F::zero(), F::zero())),
            generic_selector: pt(F::zero(), F::zero()),
            poseidon_selector: pt(F::zero(), F::zero()),
            complete_add_selector: pt(F::zero(), F::zero()),
            mul_selector: pt(F::zero(), F::zero()),
            emul_selector: pt(F::zero(), F::zero()),
            endomul_scalar_selector: pt(F::zero(), F::zero()),
            range_check0_selector: None,
            range_check1_selector: None,
            foreign_field_add_selector: None,
            foreign_field_mul_selector: None,
            xor_selector: None,
            rot_selector: None,
            lookup_aggregation: None,
            lookup_table: None,
            lookup_sorted: array::from_fn(|_| None),
            runtime_lookup_table: None,
            runtime_lookup_table_selector: None,
            xor_lookup_selector: None,
            lookup_gate_lookup_selector: None,
            range_check_lookup_selector: None,
            foreign_field_mul_lookup_selector: None,
        }
    }
}

impl<F: FftField> ProofEvaluations<PointEvaluations<Vec<F>>> {
    pub fn combine(&self, pt: &PointEvaluations<F>) -> ProofEvaluations<PointEvaluations<F>> {
        self.map_ref(&|evals| PointEvaluations {
            zeta: DensePolynomial::eval_polynomial(&evals.zeta, pt.zeta),
            zeta_omega: DensePolynomial::eval_polynomial(&evals.zeta_omega, pt.zeta_omega),
        })
    }
}

impl<F> ProofEvaluations<F> {
    pub fn get_column(&self, col: Column) -> Option<&F> {
        match col {
            Column::Witness(i) => Some(&self.w[i]),
            Column::Z => Some(&self.z),
            Column::LookupSorted(i) => self.lookup_sorted[i].as_ref(),
            Column::LookupAggreg => self.lookup_aggregation.as_ref(),
            Column::LookupTable => self.lookup_table.as_ref(),
            Column::LookupKindIndex(LookupPattern::Xor) => self.xor_lookup_selector.as_ref(),
            Column::LookupKindIndex(LookupPattern::Lookup) => {
                self.lookup_gate_lookup_selector.as_ref()
            }
            Column::LookupKindIndex(LookupPattern::RangeCheck) => {
                self.range_check_lookup_selector.as_ref()
            }
            Column::LookupKindIndex(LookupPattern::ForeignFieldMul) => {
                self.foreign_field_mul_lookup_selector.as_ref()
            }
            Column::LookupRuntimeSelector => self.runtime_lookup_table_selector.as_ref(),
            Column::LookupRuntimeTable => self.runtime_lookup_table.as_ref(),
            Column::Index(GateType::Generic) => Some(&self.generic_selector),
            Column::Index(GateType::Poseidon) => Some(&self.poseidon_selector),
            Column::Index(GateType::CompleteAdd) => Some(&self.complete_add_selector),
            Column::Index(GateType::VarBaseMul) => Some(&self.mul_selector),
            Column::Index(GateType::EndoMul) => Some(&self.emul_selector),
            Column::Index(GateType::EndoMulScalar) => Some(&self.endomul_scalar_selector),
            Column::Index(GateType::RangeCheck0) => self.range_check0_selector.as_ref(),
            Column::Index(GateType::RangeCheck1) => self.range_check1_selector.as_ref(),
            Column::Index(GateType::ForeignFieldAdd) => self.foreign_field_add_selector.as_ref(),
            Column::Index(GateType::ForeignFieldMul) => self.foreign_field_mul_selector.as_ref(),
            Column::Index(GateType::Xor16) => self.xor_selector.as_ref(),
            Column::Index(GateType::Rot64) => self.rot_selector.as_ref(),
            Column::Index(_) => None,
            Column::Coefficient(i) => Some(&self.coefficients[i]),
            Column::Permutation(i) => Some(&self.s[i]),
        }
    }
}

//
// OCaml types
//

#[cfg(feature = "ocaml_types")]
pub mod caml {
    use super::*;
    use poly_commitment::commitment::caml::CamlPolyComm;

    //
    // CamlRecursionChallenge<CamlG, CamlF>
    //

    #[derive(Clone, ocaml::IntoValue, ocaml::FromValue, ocaml_gen::Struct)]
    pub struct CamlRecursionChallenge<CamlG, CamlF> {
        pub chals: Vec<CamlF>,
        pub comm: CamlPolyComm<CamlG>,
    }

    //
    // CamlRecursionChallenge<CamlG, CamlF> <-> RecursionChallenge<G>
    //

    impl<G, CamlG, CamlF> From<RecursionChallenge<G>> for CamlRecursionChallenge<CamlG, CamlF>
    where
        G: AffineRepr,
        CamlG: From<G>,
        CamlF: From<G::ScalarField>,
    {
        fn from(ch: RecursionChallenge<G>) -> Self {
            Self {
                chals: ch.chals.into_iter().map(Into::into).collect(),
                comm: ch.comm.into(),
            }
        }
    }

    impl<G, CamlG, CamlF> From<CamlRecursionChallenge<CamlG, CamlF>> for RecursionChallenge<G>
    where
        G: AffineRepr + From<CamlG>,
        G::ScalarField: From<CamlF>,
    {
        fn from(caml_ch: CamlRecursionChallenge<CamlG, CamlF>) -> RecursionChallenge<G> {
            RecursionChallenge {
                chals: caml_ch.chals.into_iter().map(Into::into).collect(),
                comm: caml_ch.comm.into(),
            }
        }
    }

    //
    // CamlProofEvaluations<CamlF>
    //

    #[allow(clippy::type_complexity)]
    #[derive(Clone, ocaml::IntoValue, ocaml::FromValue, ocaml_gen::Struct)]
    pub struct CamlProofEvaluations<CamlF> {
        pub w: (
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
        ),
        pub z: PointEvaluations<Vec<CamlF>>,
        pub s: (
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
        ),
        pub coefficients: (
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
            PointEvaluations<Vec<CamlF>>,
        ),

        pub generic_selector: PointEvaluations<Vec<CamlF>>,
        pub poseidon_selector: PointEvaluations<Vec<CamlF>>,
        pub complete_add_selector: PointEvaluations<Vec<CamlF>>,
        pub mul_selector: PointEvaluations<Vec<CamlF>>,
        pub emul_selector: PointEvaluations<Vec<CamlF>>,
        pub endomul_scalar_selector: PointEvaluations<Vec<CamlF>>,

        pub range_check0_selector: Option<PointEvaluations<Vec<CamlF>>>,
        pub range_check1_selector: Option<PointEvaluations<Vec<CamlF>>>,
        pub foreign_field_add_selector: Option<PointEvaluations<Vec<CamlF>>>,
        pub foreign_field_mul_selector: Option<PointEvaluations<Vec<CamlF>>>,
        pub xor_selector: Option<PointEvaluations<Vec<CamlF>>>,
        pub rot_selector: Option<PointEvaluations<Vec<CamlF>>>,
        pub lookup_aggregation: Option<PointEvaluations<Vec<CamlF>>>,
        pub lookup_table: Option<PointEvaluations<Vec<CamlF>>>,
        pub lookup_sorted: Vec<Option<PointEvaluations<Vec<CamlF>>>>,
        pub runtime_lookup_table: Option<PointEvaluations<Vec<CamlF>>>,

        pub runtime_lookup_table_selector: Option<PointEvaluations<Vec<CamlF>>>,
        pub xor_lookup_selector: Option<PointEvaluations<Vec<CamlF>>>,
        pub lookup_gate_lookup_selector: Option<PointEvaluations<Vec<CamlF>>>,
        pub range_check_lookup_selector: Option<PointEvaluations<Vec<CamlF>>>,
        pub foreign_field_mul_lookup_selector: Option<PointEvaluations<Vec<CamlF>>>,
    }

    //
    // ProofEvaluations<Vec<F>> <-> CamlProofEvaluations<CamlF>
    //

    impl<F, CamlF> From<ProofEvaluations<PointEvaluations<Vec<F>>>>
        for (
            Option<PointEvaluations<Vec<CamlF>>>,
            CamlProofEvaluations<CamlF>,
        )
    where
        F: Clone,
        CamlF: From<F>,
    {
        fn from(pe: ProofEvaluations<PointEvaluations<Vec<F>>>) -> Self {
            let first = pe.public.map(|x: PointEvaluations<Vec<F>>| {
                // map both fields of each evaluation.
                x.map(&|x: Vec<F>| {
                    let y: Vec<CamlF> = x.into_iter().map(Into::into).collect();
                    y
                })
            });
            let w = (
                pe.w[0]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.w[1]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.w[2]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.w[3]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.w[4]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.w[5]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.w[6]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.w[7]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.w[8]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.w[9]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.w[10]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.w[11]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.w[12]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.w[13]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.w[14]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
            );
            let coefficients = (
                pe.coefficients[0]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.coefficients[1]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.coefficients[2]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.coefficients[3]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.coefficients[4]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.coefficients[5]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.coefficients[6]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.coefficients[7]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.coefficients[8]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.coefficients[9]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.coefficients[10]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.coefficients[11]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.coefficients[12]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.coefficients[13]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.coefficients[14]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
            );
            let s = (
                pe.s[0]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.s[1]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.s[2]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.s[3]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.s[4]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                pe.s[5]
                    .clone()
                    .map(&|x| x.into_iter().map(Into::into).collect()),
            );

            let second = CamlProofEvaluations {
                w,
                coefficients,
                z: pe.z.map(&|x| x.into_iter().map(Into::into).collect()),
                s,
                generic_selector: pe
                    .generic_selector
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                poseidon_selector: pe
                    .poseidon_selector
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                complete_add_selector: pe
                    .complete_add_selector
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                mul_selector: pe
                    .mul_selector
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                emul_selector: pe
                    .emul_selector
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                endomul_scalar_selector: pe
                    .endomul_scalar_selector
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                range_check0_selector: pe
                    .range_check0_selector
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                range_check1_selector: pe
                    .range_check1_selector
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                foreign_field_add_selector: pe
                    .foreign_field_add_selector
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                foreign_field_mul_selector: pe
                    .foreign_field_mul_selector
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                xor_selector: pe
                    .xor_selector
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                rot_selector: pe
                    .rot_selector
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                lookup_aggregation: pe
                    .lookup_aggregation
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                lookup_table: pe
                    .lookup_table
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                lookup_sorted: pe
                    .lookup_sorted
                    .iter()
                    .map(|x| {
                        x.as_ref().map(|x| {
                            x.map_ref(&|x| x.clone().into_iter().map(Into::into).collect())
                        })
                    })
                    .collect::<Vec<_>>(),
                runtime_lookup_table: pe
                    .runtime_lookup_table
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                runtime_lookup_table_selector: pe
                    .runtime_lookup_table_selector
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                xor_lookup_selector: pe
                    .xor_lookup_selector
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                lookup_gate_lookup_selector: pe
                    .lookup_gate_lookup_selector
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                range_check_lookup_selector: pe
                    .range_check_lookup_selector
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                foreign_field_mul_lookup_selector: pe
                    .foreign_field_mul_lookup_selector
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
            };

            (first, second)
        }
    }

    impl<F, CamlF>
        From<(
            Option<PointEvaluations<Vec<CamlF>>>,
            CamlProofEvaluations<CamlF>,
        )> for ProofEvaluations<PointEvaluations<Vec<F>>>
    where
        F: Clone,
        CamlF: Clone,
        F: From<CamlF>,
    {
        fn from(
            (public, cpe): (
                Option<PointEvaluations<Vec<CamlF>>>,
                CamlProofEvaluations<CamlF>,
            ),
        ) -> Self {
            let w = [
                cpe.w.0.map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.w.1.map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.w.2.map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.w.3.map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.w.4.map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.w.5.map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.w.6.map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.w.7.map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.w.8.map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.w.9.map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.w.10.map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.w.11.map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.w.12.map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.w.13.map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.w.14.map(&|x| x.into_iter().map(Into::into).collect()),
            ];
            let coefficients = [
                cpe.coefficients
                    .0
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.coefficients
                    .1
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.coefficients
                    .2
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.coefficients
                    .3
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.coefficients
                    .4
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.coefficients
                    .5
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.coefficients
                    .6
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.coefficients
                    .7
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.coefficients
                    .8
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.coefficients
                    .9
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.coefficients
                    .10
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.coefficients
                    .11
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.coefficients
                    .12
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.coefficients
                    .13
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.coefficients
                    .14
                    .map(&|x| x.into_iter().map(Into::into).collect()),
            ];
            let s = [
                cpe.s.0.map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.s.1.map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.s.2.map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.s.3.map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.s.4.map(&|x| x.into_iter().map(Into::into).collect()),
                cpe.s.5.map(&|x| x.into_iter().map(Into::into).collect()),
            ];

            Self {
                public: public.map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                w,
                coefficients,
                z: cpe.z.map(&|x| x.into_iter().map(Into::into).collect()),
                s,
                generic_selector: cpe
                    .generic_selector
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                poseidon_selector: cpe
                    .poseidon_selector
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                complete_add_selector: cpe
                    .complete_add_selector
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                mul_selector: cpe
                    .mul_selector
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                emul_selector: cpe
                    .emul_selector
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                endomul_scalar_selector: cpe
                    .endomul_scalar_selector
                    .map(&|x| x.into_iter().map(Into::into).collect()),
                range_check0_selector: cpe
                    .range_check0_selector
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                range_check1_selector: cpe
                    .range_check1_selector
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                foreign_field_add_selector: cpe
                    .foreign_field_add_selector
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                foreign_field_mul_selector: cpe
                    .foreign_field_mul_selector
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                xor_selector: cpe
                    .xor_selector
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                rot_selector: cpe
                    .rot_selector
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                lookup_aggregation: cpe
                    .lookup_aggregation
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                lookup_table: cpe
                    .lookup_table
                    .map(|x| x.map(&|x| x.into_iter().map(Into::into).collect())),
                lookup_sorted: {
                    assert_eq!(cpe.lookup_sorted.len(), 5); // Invalid proof
                    array::from_fn(|i| {
                        cpe.lookup_sorted[i]
                            .as_ref()
                            .map(|x| x.clone().map(&|x| x.into_iter().map(Into::into).collect()))
                    })
                },
                runtime_lookup_table: cpe
                    .runtime_lookup_table
                    .map(|x| x.map(&|x| x.iter().map(|x| x.clone().into()).collect())),
                runtime_lookup_table_selector: cpe
                    .runtime_lookup_table_selector
                    .map(|x| x.map(&|x| x.iter().map(|x| x.clone().into()).collect())),
                xor_lookup_selector: cpe
                    .xor_lookup_selector
                    .map(|x| x.map(&|x| x.iter().map(|x| x.clone().into()).collect())),
                lookup_gate_lookup_selector: cpe
                    .lookup_gate_lookup_selector
                    .map(|x| x.map(&|x| x.iter().map(|x| x.clone().into()).collect())),
                range_check_lookup_selector: cpe
                    .range_check_lookup_selector
                    .map(|x| x.map(&|x| x.iter().map(|x| x.clone().into()).collect())),
                foreign_field_mul_lookup_selector: cpe
                    .foreign_field_mul_lookup_selector
                    .map(|x| x.map(&|x| x.iter().map(|x| x.clone().into()).collect())),
            }
        }
    }
}