aver-cert 0.1.7

Independent artifact certificate engine and verifier for Aver WebAssembly
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
// ---- the one-grammar plan (schema 9) --------------------------------------
//
// A Rust mirror of `Grammar.lean`: the plan IS the optimized MIR function
// body, printed 1:1 by the compiler (`src/codegen/cert/plan_from_mir.rs`).
// This file only holds the data and its Lean rendering; nothing here decides
// anything the wall does not re-derive.

/// `Grammar.Ty`.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum PlanTy {
    Int,
    Bool,
    Record(u32),
    Sum(u32),
    Option(Box<PlanTy>),
    Result(Box<PlanTy>, Box<PlanTy>),
    Eqref,
    Float,
    Str,
    Vec(Box<PlanTy>),
    List(Box<PlanTy>),
    Opaque(u32),
    /// `Bytes`: the packed `(array (mut i8))` of its octets
    /// (`Schema.TypeTable.bytesArr`).
    Bytes,
    /// A raw `i64` local: only the `Int` tree's machine-word temporaries.
    Word,
}

/// `Grammar.Lit`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PlanLit {
    Int(i64),
    Bool(bool),
    Float(u64),
    Str(Vec<u8>),
}

/// `Grammar.BinOp` (`ast::BinOp` without `Div`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlanBinOp {
    Add,
    Sub,
    Mul,
    Eq,
    Neq,
    Lt,
    Gt,
    Lte,
    Gte,
}

/// `Grammar.Builtin`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlanBuiltin {
    BoolAnd,
    BoolOr,
    BoolNot,
    ListPrepend,
    VecGet,
    /// `Int.div` / `Int.mod`, admitted only fused under `Result.withDefault`
    /// with an Int literal default.
    IntDiv,
    IntMod,
    /// `List.len` / `reverse` / `concat` / `take` / `drop` / `contains`: a
    /// call of the per-instantiation helper the type table declares
    /// (`Grammar.MCtx.listHelper`).
    ListLen,
    ListReverse,
    ListConcat,
    ListTake,
    ListDrop,
    ListContains,
    /// The packed `Bytes` operations (`Grammar.Builtin.bytesOfList` ...):
    /// MIR's `Bytes(values = xs)` (pack), `bytes.values` (unpack),
    /// `List.len(bytes.values)` (inline `array.len`), and a construction over
    /// `List.concat` / `take` / `drop` of projections (the preserving helpers).
    BytesOfList,
    BytesValues,
    BytesLen,
    BytesConcat,
    BytesTake,
    BytesDrop,
    /// `Grammar.Builtin.strFromInt`: an `Int` interpolation part, a call of
    /// the `String.fromInt` helper (`Schema.TypeTable.strFromInt`).
    StrFromInt,
}

/// `Grammar.BytesRole`: the per-type helpers of the packed `Bytes` array.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum PlanBytesRole {
    Pack,
    Unpack,
    Concat,
    Take,
    Drop,
}

impl PlanBytesRole {
    pub fn lean(self) -> &'static str {
        match self {
            PlanBytesRole::Pack => ".pack",
            PlanBytesRole::Unpack => ".unpack",
            PlanBytesRole::Concat => ".concat",
            PlanBytesRole::Take => ".take",
            PlanBytesRole::Drop => ".drop",
        }
    }
}

impl PlanBuiltin {
    /// `Grammar.Builtin.isBytes`.
    pub fn is_bytes(self) -> bool {
        matches!(
            self,
            PlanBuiltin::BytesOfList
                | PlanBuiltin::BytesValues
                | PlanBuiltin::BytesLen
                | PlanBuiltin::BytesConcat
                | PlanBuiltin::BytesTake
                | PlanBuiltin::BytesDrop
        )
    }

    /// The `Bytes` helper a `Bytes` builtin calls (`BytesLen` calls none).
    pub fn bytes_role(self) -> Option<PlanBytesRole> {
        Some(match self {
            PlanBuiltin::BytesOfList => PlanBytesRole::Pack,
            PlanBuiltin::BytesValues => PlanBytesRole::Unpack,
            PlanBuiltin::BytesConcat => PlanBytesRole::Concat,
            PlanBuiltin::BytesTake => PlanBytesRole::Take,
            PlanBuiltin::BytesDrop => PlanBytesRole::Drop,
            _ => return None,
        })
    }

    /// The List helper a List builtin calls.
    pub fn list_role(self) -> Option<PlanListRole> {
        Some(match self {
            PlanBuiltin::ListLen => PlanListRole::Len,
            PlanBuiltin::ListReverse => PlanListRole::Reverse,
            PlanBuiltin::ListConcat => PlanListRole::Concat,
            PlanBuiltin::ListTake => PlanListRole::Take,
            PlanBuiltin::ListDrop => PlanListRole::Drop,
            PlanBuiltin::ListContains => PlanListRole::Contains,
            _ => return None,
        })
    }
}

/// `Grammar.ListRole`: the per-instantiation `List<T>` runtime helpers.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum PlanListRole {
    Len,
    Reverse,
    Concat,
    Take,
    Drop,
    Contains,
}

impl PlanListRole {
    pub fn lean(self) -> &'static str {
        match self {
            PlanListRole::Len => ".len",
            PlanListRole::Reverse => ".reverse",
            PlanListRole::Concat => ".concat",
            PlanListRole::Take => ".take",
            PlanListRole::Drop => ".drop",
            PlanListRole::Contains => ".contains",
        }
    }
}

/// `Grammar.Intrinsic`: the resolver's Euclidean discharge of `Int.div` /
/// `Int.mod` by a nonzero literal divisor.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlanIntrinsic {
    IntDivEuclid,
    IntModEuclid,
}

/// `Grammar.LazyBuiltin`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlanLazy {
    OptWithDefault,
    ResWithDefault,
}

/// `Grammar.PickBuiltin`: `Int.min` / `Int.max`, whose emitter evaluates the
/// operand it picks a second time.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlanPick {
    IntMin,
    IntMax,
}

/// `Grammar.BitwiseBuiltin`: `Bits.and` / `Bits.or` / `Bits.xor`, one call of
/// `__aint_bitwise` with the selector 0 / 1 / 2.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlanBitwise {
    And,
    Or,
    Xor,
}

impl PlanBitwise {
    /// `Grammar.BitwiseBuiltin.flag`, the emitter's `bitwise_selector`.
    pub fn flag(self) -> i64 {
        match self {
            PlanBitwise::And => 0,
            PlanBitwise::Or => 1,
            PlanBitwise::Xor => 2,
        }
    }
}

/// `Grammar.MirCallee`; `Fn` carries the callee's wasm function index.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlanCallee {
    Fn(u32),
    Builtin(PlanBuiltin),
    Lazy(PlanLazy),
    Intrinsic(PlanIntrinsic),
    Pick(PlanPick),
    Bitwise(PlanBitwise),
}

/// `Grammar.CtorTag`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PlanCtor {
    User(u32, u32),
    Some,
    None,
    Ok,
    Err,
}

/// The resolver's slot for an ignored binder (`Grammar.noSlot`).
pub const PLAN_NO_SLOT: u32 = 65535;

/// `Grammar.Pat`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PlanPat {
    Wild,
    LitInt(i64),
    LitBool(bool),
    Bind(u32),
    Ctor(PlanCtor, Vec<u32>),
    LitStr(Vec<u8>),
    Tuple(Vec<u32>),
    /// `[]`.
    EmptyList,
    /// `[head, ..tail]`: the head and tail slots.
    Cons(u32, u32),
}

/// `Grammar.Expr`; `Match` arms are `Grammar.Arms` in source order.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PlanExpr {
    Literal(PlanLit),
    Local(u32),
    Let(u32, Box<PlanExpr>, Box<PlanExpr>),
    Call(PlanCallee, Vec<PlanExpr>),
    TailCall(u32, Vec<PlanExpr>),
    BinOp(PlanBinOp, Box<PlanExpr>, Box<PlanExpr>),
    Neg(Box<PlanExpr>),
    If(Box<PlanExpr>, Box<PlanExpr>, Box<PlanExpr>),
    RecordCreate(u32, Vec<PlanExpr>),
    Project(u32, u32, Box<PlanExpr>),
    Match(Box<PlanExpr>, Vec<(PlanPat, PlanExpr)>),
    Construct(PlanCtor, PlanTy, Vec<PlanExpr>),
    Interp(Vec<PlanExpr>),
    List(PlanTy, Vec<PlanExpr>),
    /// `Grammar.Expr.try_`: `e?` with the enclosing function's return type.
    Try(Box<PlanExpr>, PlanTy),
    /// `Grammar.Expr.scope`: a body whose `?` returns land here.
    Scope(Box<PlanExpr>),
    /// `Grammar.Expr.intWord`: an `Int` tree computed on the machine word
    /// first, its operations parking words in the locals `w`, `w + 1` and
    /// `w + 2`.
    IntWord(PlanWTree, u32),
    /// `Grammar.Expr.intCmp`: two `Int` trees compared by the operation on
    /// the machine word first, their operations parking words in the locals
    /// `w`, `w + 1` and `w + 2`.
    IntCmp(PlanBinOp, PlanWTree, PlanWTree, u32),
}

/// `Grammar.WLeaf`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PlanWLeaf {
    /// An `Int` local, read where it is.
    Local(u32),
    /// Field `field` of the record of type `tid` held in local `base`, read
    /// once ahead into the local `slot`.
    Field {
        tid: u32,
        field: u32,
        base: u32,
        slot: u32,
    },
    /// The `Int` of the word record of type `tid` held in local `base` (an
    /// `i64`), read once ahead into the `i64` local `slot`.
    Word { tid: u32, base: u32, slot: u32 },
}

/// `Grammar.WTree`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum PlanWTree {
    Leaf(PlanWLeaf),
    Op(PlanBinOp, Box<PlanWTree>, Box<PlanWTree>),
    /// An `Int` literal: an immediate word on the machine path.
    Lit(i64),
    /// `Int.min` / `Int.max` of two trees.
    Pick(PlanPick, Box<PlanWTree>, Box<PlanWTree>),
    /// A product by the literal `k`, written first when the flag is set.
    MulLit(i64, bool, Box<PlanWTree>),
    /// `Int.div` by the literal (not `0` or `-1`).
    DivLit(i64, Box<PlanWTree>),
    /// `Int.mod` by the literal (not `0`).
    ModLit(i64, Box<PlanWTree>),
}

impl PlanWLeaf {
    /// `Grammar.WLeaf.loc`: the local both paths read the leaf from.
    pub fn loc(&self) -> u32 {
        match self {
            PlanWLeaf::Local(i) => *i,
            PlanWLeaf::Field { slot, .. } | PlanWLeaf::Word { slot, .. } => *slot,
        }
    }

    fn lean(&self) -> String {
        match self {
            PlanWLeaf::Local(i) => format!("(.local {i})"),
            PlanWLeaf::Field {
                tid,
                field,
                base,
                slot,
            } => format!("(.field {tid} {field} {base} {slot})"),
            PlanWLeaf::Word { tid, base, slot } => format!("(.word {tid} {base} {slot})"),
        }
    }
}

impl PlanWTree {
    /// The tree `a + b`, as `Grammar.cmpWordOk` reads the two sides of a
    /// comparison.
    pub fn pair(a: &PlanWTree, b: &PlanWTree) -> PlanWTree {
        PlanWTree::Op(PlanBinOp::Add, Box::new(a.clone()), Box::new(b.clone()))
    }

    /// `Grammar.WTree.leaves`.
    pub fn leaves(&self) -> Vec<&PlanWLeaf> {
        match self {
            PlanWTree::Leaf(l) => vec![l],
            PlanWTree::Op(_, a, b) | PlanWTree::Pick(_, a, b) => {
                let mut out = a.leaves();
                out.extend(b.leaves());
                out
            }
            PlanWTree::Lit(_) => vec![],
            PlanWTree::MulLit(_, _, a) | PlanWTree::DivLit(_, a) | PlanWTree::ModLit(_, a) => {
                a.leaves()
            }
        }
    }

    /// `Grammar.WTree.slots`.
    pub fn slots(&self) -> Vec<u32> {
        self.leaves()
            .into_iter()
            .filter_map(|l| match l {
                PlanWLeaf::Field { slot, .. } | PlanWLeaf::Word { slot, .. } => Some(*slot),
                PlanWLeaf::Local(_) => None,
            })
            .collect()
    }

    pub fn write_lean(&self, out: &mut String) {
        match self {
            PlanWTree::Leaf(l) => {
                out.push_str("(.leaf ");
                out.push_str(&l.lean());
                out.push(')');
            }
            PlanWTree::Op(op, a, b) => {
                out.push_str(&format!("(.op {} ", op.lean()));
                a.write_lean(out);
                out.push(' ');
                b.write_lean(out);
                out.push(')');
            }
            PlanWTree::Lit(k) => out.push_str(&format!("(.lit ({k}))")),
            PlanWTree::MulLit(k, lit_first, a) => {
                out.push_str(&format!("(.mulLit ({k}) {lit_first} "));
                a.write_lean(out);
                out.push(')');
            }
            PlanWTree::DivLit(k, a) => {
                out.push_str(&format!("(.divLit ({k}) "));
                a.write_lean(out);
                out.push(')');
            }
            PlanWTree::ModLit(k, a) => {
                out.push_str(&format!("(.modLit ({k}) "));
                a.write_lean(out);
                out.push(')');
            }
            PlanWTree::Pick(p, a, b) => {
                out.push_str(match p {
                    PlanPick::IntMin => "(.pick .intMin ",
                    PlanPick::IntMax => "(.pick .intMax ",
                });
                a.write_lean(out);
                out.push(' ');
                b.write_lean(out);
                out.push(')');
            }
        }
    }
}

/// `Grammar.FnPlan`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FnPlan {
    pub params: Vec<PlanTy>,
    pub ret: PlanTy,
    /// Resolver slot count (parameters and every binder).
    pub nslots: u32,
    /// Declared locals past the parameters, as the emitter declares them.
    pub locals: Vec<PlanTy>,
    pub body: PlanExpr,
    /// `Grammar.FnPlan.selfLoop`: the function's self tail calls run as one
    /// loop (`MirFnRepr::self_tail_loop`).
    pub self_loop: bool,
}

/// `Schema.RecordDecl`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlanRecordDecl {
    pub tid: u32,
    pub struct_idx: u32,
    pub fields: Vec<PlanTy>,
}

/// `Schema.SumDecl`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlanSumDecl {
    pub tid: u32,
    pub root: u32,
    pub ctors: Vec<(u32, Vec<PlanTy>)>,
}

/// `Schema.TypeTable`: declared layout, confirmed by the wall against the
/// type and data sections.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PlanTypeTable {
    pub carrier: Option<u32>,
    pub mag: Option<u32>,
    pub str_: Option<u32>,
    pub str_vec: Option<u32>,
    pub records: Vec<PlanRecordDecl>,
    pub sums: Vec<PlanSumDecl>,
    pub options: Vec<(PlanTy, u32)>,
    pub results: Vec<(PlanTy, PlanTy, u32)>,
    pub vecs: Vec<(PlanTy, u32)>,
    pub lists: Vec<(PlanTy, u32)>,
    pub opaques: Vec<(u32, u32)>,
    pub str_segs: Vec<(Vec<u8>, u32)>,
    /// The cons helper of each `List<T>` a non-empty literal builds
    /// (`Schema.TypeTable.listCons`): the function the literal calls once per
    /// item, whose plan must be exactly [`FnPlan::cons`].
    pub list_cons: Vec<(PlanTy, u32)>,
    /// The List helpers the plans' List builtins call
    /// (`Schema.TypeTable.listHelpers`): element type, role, function index.
    /// The acceptance pins each body to the wall's template.
    pub list_helpers: Vec<(PlanTy, PlanListRole, u32)>,
    /// `__aint_to_i64_sat`, which a `List.take` / `List.drop` count goes
    /// through (`Schema.TypeTable.intSat`), pinned to its template.
    pub int_sat: Option<u32>,
    /// The packed `Bytes` array type (`Schema.TypeTable.bytesArr`), confirmed
    /// as `(array (mut i8))`.
    pub bytes_arr: Option<u32>,
    /// The `Bytes` helpers the plans' `Bytes` builtins call
    /// (`Schema.TypeTable.bytesHelpers`), by role. The acceptance pins each
    /// body to the wall's template.
    pub bytes_helpers: Vec<(PlanBytesRole, u32)>,
    /// `__aint_to_i64_checked`, which `pack` calls
    /// (`Schema.TypeTable.intChk`), pinned to its template.
    pub int_chk: Option<u32>,
    /// `String.fromInt`, which an `Int` interpolation part calls
    /// (`Schema.TypeTable.strFromInt`), pinned to its template.
    pub str_from_int: Option<u32>,
    /// The one-field records whose value is the machine word of their `Int`
    /// (`Schema.TypeTable.words`): an eligible carrier the emitter erases to
    /// `i64`. Each names a record declared with fields `[Int]`.
    pub words: Vec<u32>,
}

/// One user function as the compiler printed it: its wasm function index, its
/// source name (diagnostics only), and its plan or the reason it has none.
#[derive(Clone, Debug)]
pub struct PlannedFn {
    pub name: String,
    pub func_idx: u32,
    pub plan: Result<FnPlan, String>,
}

/// Everything the compiler hands the certificate producer: one entry per
/// emitted user function, the type table the plans' type ids refer to, and
/// the `__aint_eq` helper's function index (the helper is pinned by template,
/// so the index is producer data the wall confirms).
#[derive(Clone, Debug, Default)]
pub struct ModulePlans {
    pub fns: Vec<PlannedFn>,
    pub types: PlanTypeTable,
    pub aint_eq_idx: Option<u32>,
}

// ---- Lean rendering ---------------------------------------------------------

fn lean_nat_list(xs: &[u32]) -> String {
    format!(
        "[{}]",
        xs.iter().map(u32::to_string).collect::<Vec<_>>().join(", ")
    )
}

fn lean_bytes(xs: &[u8]) -> String {
    format!(
        "[{}]",
        xs.iter().map(u8::to_string).collect::<Vec<_>>().join(", ")
    )
}

fn lean_int(k: i64) -> String {
    if k < 0 {
        format!("({k})")
    } else {
        k.to_string()
    }
}

impl PlanTy {
    pub fn lean(&self) -> String {
        match self {
            PlanTy::Int => ".int".into(),
            PlanTy::Bool => ".bool".into(),
            PlanTy::Record(t) => format!("(.record {t})"),
            PlanTy::Sum(t) => format!("(.sum {t})"),
            PlanTy::Option(t) => format!("(.option {})", t.lean()),
            PlanTy::Result(t, e) => format!("(.result {} {})", t.lean(), e.lean()),
            PlanTy::Eqref => ".eqref".into(),
            PlanTy::Float => ".float".into(),
            PlanTy::Str => ".string".into(),
            PlanTy::Vec(t) => format!("(.vec {})", t.lean()),
            PlanTy::List(t) => format!("(.list {})", t.lean()),
            PlanTy::Opaque(t) => format!("(.opaque {t})"),
            PlanTy::Bytes => ".bytes".into(),
            PlanTy::Word => ".word".into(),
        }
    }
}

fn lean_ty_list(ts: &[PlanTy]) -> String {
    format!(
        "[{}]",
        ts.iter().map(PlanTy::lean).collect::<Vec<_>>().join(", ")
    )
}

impl PlanLit {
    fn lean(&self) -> String {
        match self {
            PlanLit::Int(k) => format!("(.int {})", lean_int(*k)),
            PlanLit::Bool(b) => format!("(.bool {b})"),
            PlanLit::Float(bits) => format!("(.float {bits})"),
            PlanLit::Str(bytes) => format!("(.str {})", lean_bytes(bytes)),
        }
    }
}

impl PlanBinOp {
    fn lean(self) -> &'static str {
        match self {
            PlanBinOp::Add => ".add",
            PlanBinOp::Sub => ".sub",
            PlanBinOp::Mul => ".mul",
            PlanBinOp::Eq => ".eq",
            PlanBinOp::Neq => ".neq",
            PlanBinOp::Lt => ".lt",
            PlanBinOp::Gt => ".gt",
            PlanBinOp::Lte => ".lte",
            PlanBinOp::Gte => ".gte",
        }
    }
}

impl PlanCallee {
    fn lean(self) -> String {
        match self {
            PlanCallee::Fn(f) => format!("(.fn {f})"),
            PlanCallee::Builtin(b) => format!(
                "(.builtin {})",
                match b {
                    PlanBuiltin::BoolAnd => ".boolAnd",
                    PlanBuiltin::BoolOr => ".boolOr",
                    PlanBuiltin::BoolNot => ".boolNot",
                    PlanBuiltin::ListPrepend => ".listPrepend",
                    PlanBuiltin::VecGet => ".vecGet",
                    PlanBuiltin::IntDiv => ".intDiv",
                    PlanBuiltin::IntMod => ".intMod",
                    PlanBuiltin::ListLen => ".listLen",
                    PlanBuiltin::ListReverse => ".listReverse",
                    PlanBuiltin::ListConcat => ".listConcat",
                    PlanBuiltin::ListTake => ".listTake",
                    PlanBuiltin::ListDrop => ".listDrop",
                    PlanBuiltin::ListContains => ".listContains",
                    PlanBuiltin::BytesOfList => ".bytesOfList",
                    PlanBuiltin::BytesValues => ".bytesValues",
                    PlanBuiltin::BytesLen => ".bytesLen",
                    PlanBuiltin::BytesConcat => ".bytesConcat",
                    PlanBuiltin::BytesTake => ".bytesTake",
                    PlanBuiltin::BytesDrop => ".bytesDrop",
                    PlanBuiltin::StrFromInt => ".strFromInt",
                }
            ),
            PlanCallee::Intrinsic(i) => format!(
                "(.intrinsic {})",
                match i {
                    PlanIntrinsic::IntDivEuclid => ".intDivEuclid",
                    PlanIntrinsic::IntModEuclid => ".intModEuclid",
                }
            ),
            PlanCallee::Lazy(l) => format!(
                "(.lazy {})",
                match l {
                    PlanLazy::OptWithDefault => ".optWithDefault",
                    PlanLazy::ResWithDefault => ".resWithDefault",
                }
            ),
            PlanCallee::Pick(p) => format!(
                "(.pick {})",
                match p {
                    PlanPick::IntMin => ".intMin",
                    PlanPick::IntMax => ".intMax",
                }
            ),
            PlanCallee::Bitwise(b) => format!(
                "(.bitwise {})",
                match b {
                    PlanBitwise::And => ".bitsAnd",
                    PlanBitwise::Or => ".bitsOr",
                    PlanBitwise::Xor => ".bitsXor",
                }
            ),
        }
    }
}

impl PlanCtor {
    fn lean(self) -> String {
        match self {
            PlanCtor::User(t, c) => format!("(.user {t} {c})"),
            PlanCtor::Some => ".some".into(),
            PlanCtor::None => ".none".into(),
            PlanCtor::Ok => ".ok".into(),
            PlanCtor::Err => ".err".into(),
        }
    }
}

impl PlanPat {
    fn lean(&self) -> String {
        match self {
            PlanPat::Wild => ".wild".into(),
            PlanPat::LitInt(k) => format!("(.litInt {})", lean_int(*k)),
            PlanPat::LitBool(b) => format!("(.litBool {b})"),
            PlanPat::Bind(s) => format!("(.bind {s})"),
            PlanPat::Ctor(c, bs) => format!("(.ctor {} {})", c.lean(), lean_nat_list(bs)),
            PlanPat::LitStr(bytes) => format!("(.litStr {})", lean_bytes(bytes)),
            PlanPat::Tuple(bs) => format!("(.tuple {})", lean_nat_list(bs)),
            PlanPat::EmptyList => ".emptyList".into(),
            PlanPat::Cons(h, t) => format!("(.cons {h} {t})"),
        }
    }
}

impl PlanExpr {
    pub fn lean(&self) -> String {
        let mut out = String::new();
        self.write_lean(&mut out);
        out
    }

    fn write_list(items: &[PlanExpr], out: &mut String) {
        out.push('[');
        for (i, item) in items.iter().enumerate() {
            if i > 0 {
                out.push_str(", ");
            }
            item.write_lean(out);
        }
        out.push(']');
    }

    fn write_lean(&self, out: &mut String) {
        match self {
            PlanExpr::Literal(l) => {
                out.push_str("(.literal ");
                out.push_str(&l.lean());
                out.push(')');
            }
            PlanExpr::Local(i) => out.push_str(&format!("(.local {i})")),
            PlanExpr::Let(b, v, body) => {
                out.push_str(&format!("(.let_ {b} "));
                v.write_lean(out);
                out.push(' ');
                body.write_lean(out);
                out.push(')');
            }
            PlanExpr::Call(c, args) => {
                out.push_str(&format!("(.call {} ", c.lean()));
                Self::write_list(args, out);
                out.push(')');
            }
            PlanExpr::TailCall(f, args) => {
                out.push_str(&format!("(.tailCall {f} "));
                Self::write_list(args, out);
                out.push(')');
            }
            PlanExpr::BinOp(op, l, r) => {
                out.push_str(&format!("(.binOp {} ", op.lean()));
                l.write_lean(out);
                out.push(' ');
                r.write_lean(out);
                out.push(')');
            }
            PlanExpr::Neg(e) => {
                out.push_str("(.neg ");
                e.write_lean(out);
                out.push(')');
            }
            PlanExpr::If(c, t, e) => {
                out.push_str("(.ifThenElse ");
                c.write_lean(out);
                out.push(' ');
                t.write_lean(out);
                out.push(' ');
                e.write_lean(out);
                out.push(')');
            }
            PlanExpr::RecordCreate(tid, fs) => {
                out.push_str(&format!("(.recordCreate {tid} "));
                Self::write_list(fs, out);
                out.push(')');
            }
            PlanExpr::Project(tid, i, b) => {
                out.push_str(&format!("(.project {tid} {i} "));
                b.write_lean(out);
                out.push(')');
            }
            PlanExpr::IntWord(t, w) => {
                out.push_str("(.intWord ");
                t.write_lean(out);
                out.push_str(&format!(" {w})"));
            }
            PlanExpr::IntCmp(op, a, b, w) => {
                out.push_str(&format!("(.intCmp {} ", op.lean()));
                a.write_lean(out);
                out.push(' ');
                b.write_lean(out);
                out.push_str(&format!(" {w})"));
            }
            PlanExpr::Match(s, arms) => {
                out.push_str("(.match_ ");
                s.write_lean(out);
                out.push(' ');
                for (p, b) in arms {
                    out.push_str(&format!("(.cons {} ", p.lean()));
                    b.write_lean(out);
                    out.push(' ');
                }
                out.push_str(".nil");
                for _ in arms {
                    out.push(')');
                }
                out.push(')');
            }
            PlanExpr::Construct(c, ty, args) => {
                out.push_str(&format!("(.construct {} {} ", c.lean(), ty.lean()));
                Self::write_list(args, out);
                out.push(')');
            }
            PlanExpr::Interp(parts) => {
                out.push_str("(.interp ");
                Self::write_list(parts, out);
                out.push(')');
            }
            PlanExpr::List(t, items) => {
                out.push_str(&format!("(.list {} ", t.lean()));
                Self::write_list(items, out);
                out.push(')');
            }
            PlanExpr::Try(e, ret) => {
                out.push_str("(.try_ ");
                e.write_lean(out);
                out.push_str(&format!(" {})", ret.lean()));
            }
            PlanExpr::Scope(e) => {
                out.push_str("(.scope ");
                e.write_lean(out);
                out.push(')');
            }
        }
    }
}

impl FnPlan {
    /// `Grammar.isConsPlan`'s plan: the cons helper of `List<t>`, one
    /// `List.prepend` over its two parameters and no declared local.
    pub fn cons(t: &PlanTy) -> FnPlan {
        FnPlan {
            params: vec![t.clone(), PlanTy::List(Box::new(t.clone()))],
            ret: PlanTy::List(Box::new(t.clone())),
            nslots: 2,
            self_loop: false,
            locals: Vec::new(),
            body: PlanExpr::Call(
                PlanCallee::Builtin(PlanBuiltin::ListPrepend),
                vec![PlanExpr::Local(0), PlanExpr::Local(1)],
            ),
        }
    }

    /// The Lean `Grammar.FnPlan` term.
    pub fn lean(&self) -> String {
        format!(
            "{{ sig := ⟨{}, {}⟩, nslots := {}, locals := {},{}\n    body := {} }}",
            lean_ty_list(&self.params),
            self.ret.lean(),
            self.nslots,
            lean_ty_list(&self.locals),
            if self.self_loop { " selfLoop := true," } else { "" },
            self.body.lean()
        )
    }
}

fn lean_opt_nat(v: Option<u32>) -> String {
    match v {
        Some(v) => format!("some {v}"),
        None => "none".into(),
    }
}

/// The longest list literal the type table writes in one piece. Lean
/// elaborates a list literal as one nested `List.cons` term, and a term deeper
/// than `maxRecDepth` (512 by default) fails to elaborate; btc-listener's
/// string segments (151 entries, the longest 570 bytes) went past it. A longer
/// list is written as literals of at most this many elements joined by `++`.
pub const LEAN_LIST_CHUNK: usize = 64;

/// The most rendered text one producer declaration carries in a list field.
/// Elaboration is paid per declaration (`maxHeartbeats`), so a field longer
/// than this, or with more than [`LEAN_LIST_CHUNK`] entries, is split into
/// its own declarations of at most this much text each, which the table joins
/// with `++`. The split denotes the same list: the wall reads the value, never
/// the spelling, and `decide`/`rfl` reduce the append.
pub const LEAN_TABLE_PIECE_CHARS: usize = 4096;

/// Rendered elements as one Lean list term, split by `++` into literals of at
/// most [`LEAN_LIST_CHUNK`] elements. A short list is the plain literal.
fn lean_list_chunked(items: &[String], separator: &str) -> String {
    if items.is_empty() {
        return "[]".into();
    }
    items
        .chunks(LEAN_LIST_CHUNK)
        .map(|chunk| format!("[{}]", chunk.join(separator)))
        .collect::<Vec<_>>()
        .join(" ++ ")
}

/// Split rendered list entries into pieces of at most [`LEAN_LIST_CHUNK`]
/// entries and [`LEAN_TABLE_PIECE_CHARS`] of text; an entry longer than the
/// text budget is a piece of its own.
fn table_pieces(items: &[String]) -> Vec<&[String]> {
    let mut pieces = Vec::new();
    let mut start = 0;
    let mut chars = 0;
    for (i, item) in items.iter().enumerate() {
        let full = i - start == LEAN_LIST_CHUNK || chars + item.len() > LEAN_TABLE_PIECE_CHARS;
        if i > start && full {
            pieces.push(&items[start..i]);
            start = i;
            chars = 0;
        }
        chars += item.len();
    }
    if start < items.len() {
        pieces.push(&items[start..]);
    }
    pieces
}

/// A list of rendered Lean terms of type `ty`, as the term that denotes it:
/// the plain literal when it fits one piece (see [`LEAN_TABLE_PIECE_CHARS`]),
/// else the `++` of declarations `{prefix}_{k}`, one per piece, which are
/// appended to `decls`.
pub(crate) fn lean_list_in_pieces(
    decls: &mut String,
    prefix: &str,
    ty: &str,
    items: &[String],
) -> String {
    let pieces = table_pieces(items);
    if pieces.len() <= 1 {
        return format!("[{}]", items.join(", "));
    }
    pieces
        .iter()
        .enumerate()
        .map(|(k, piece)| {
            let piece_name = format!("{prefix}_{k}");
            decls.push_str(&format!(
                "def {piece_name} : List ({ty}) :=\n  [{}]\n\n",
                piece.join(",\n   ")
            ));
            piece_name
        })
        .collect::<Vec<_>>()
        .join(" ++ ")
}

impl PlanTypeTable {
    /// The Lean declaration `def {name} : Schema.TypeTable`, preceded by the
    /// declarations `{name}_{field}_{k}` of every list field too big to write
    /// inline (see [`LEAN_TABLE_PIECE_CHARS`]); every byte list longer than
    /// [`LEAN_LIST_CHUNK`] is written in `++`-joined literals.
    pub fn lean_decls(&self, name: &str) -> String {
        self.lean_decls_and_pieces(name).0
    }

    /// The names of the piece declarations [`Self::lean_decls`] writes before
    /// `def {name}`, in order. A proof that unfolds the table by `simp` must
    /// unfold these too, or a field written in pieces stays opaque.
    pub fn lean_piece_names(&self, name: &str) -> Vec<String> {
        self.lean_decls_and_pieces(name).1
    }

    fn lean_decls_and_pieces(&self, name: &str) -> (String, Vec<String>) {
        let records = self
            .records
            .iter()
            .map(|r| format!("⟨{}, {}, {}⟩", r.tid, r.struct_idx, lean_ty_list(&r.fields)))
            .collect::<Vec<_>>();
        let sums = self
            .sums
            .iter()
            .map(|s| {
                format!(
                    "⟨{}, {}, [{}]⟩",
                    s.tid,
                    s.root,
                    s.ctors
                        .iter()
                        .map(|(idx, fs)| format!("({idx}, {})", lean_ty_list(fs)))
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            })
            .collect::<Vec<_>>();
        let pairs = |xs: &[(PlanTy, u32)]| {
            xs.iter()
                .map(|(t, i)| format!("({}, {i})", t.lean()))
                .collect::<Vec<_>>()
        };
        let results = self
            .results
            .iter()
            .map(|(t, e, i)| format!("({}, {}, {i})", t.lean(), e.lean()))
            .collect::<Vec<_>>();
        let opaques = self
            .opaques
            .iter()
            .map(|(t, i)| format!("({t}, {i})"))
            .collect::<Vec<_>>();
        let segs = self
            .str_segs
            .iter()
            .map(|(b, i)| {
                let bytes = b.iter().map(u8::to_string).collect::<Vec<_>>();
                format!("({}, {i})", lean_list_chunked(&bytes, ", "))
            })
            .collect::<Vec<_>>();

        let mut decls = String::new();
        let mut field = |field: &str, ty: &str, items: &[String]| -> String {
            lean_list_in_pieces(&mut decls, &format!("{name}_{field}"), ty, items)
        };
        let records = field("records", "RecordDecl", &records);
        let sums = field("sums", "SumDecl", &sums);
        let options = field("options", "Ty × Nat", &pairs(&self.options));
        let results = field("results", "Ty × Ty × Nat", &results);
        let vecs = field("vecs", "Ty × Nat", &pairs(&self.vecs));
        let lists = field("lists", "Ty × Nat", &pairs(&self.lists));
        let opaques = field("opaques", "Nat × Nat", &opaques);
        let segs = field("strSegs", "List Nat × Nat", &segs);
        // Written only when present: the wall's default is the empty list,
        // so a module without list literals renders as before.
        let cons = if self.list_cons.is_empty() {
            String::new()
        } else {
            format!(
                ",\n    listCons := {}",
                field("listCons", "Ty × Nat", &pairs(&self.list_cons))
            )
        };
        let helpers = if self.list_helpers.is_empty() {
            String::new()
        } else {
            let items = self
                .list_helpers
                .iter()
                .map(|(t, r, i)| format!("({}, {}, {i})", t.lean(), r.lean()))
                .collect::<Vec<_>>();
            format!(
                ",\n    listHelpers := {}",
                field("listHelpers", "Ty × ListRole × Nat", &items)
            )
        };
        let sat = match self.int_sat {
            Some(i) => format!(",\n    intSat := some {i}"),
            None => String::new(),
        };
        let bytes = {
            let mut out = String::new();
            if let Some(i) = self.bytes_arr {
                out.push_str(&format!(",\n    bytesArr := some {i}"));
            }
            if !self.bytes_helpers.is_empty() {
                let items = self
                    .bytes_helpers
                    .iter()
                    .map(|(r, i)| format!("({}, {i})", r.lean()))
                    .collect::<Vec<_>>();
                out.push_str(&format!(",\n    bytesHelpers := [{}]", items.join(", ")));
            }
            if let Some(i) = self.int_chk {
                out.push_str(&format!(",\n    intChk := some {i}"));
            }
            if let Some(i) = self.str_from_int {
                out.push_str(&format!(",\n    strFromInt := some {i}"));
            }
            if !self.words.is_empty() {
                let items = self.words.iter().map(u32::to_string).collect::<Vec<_>>();
                out.push_str(&format!(",\n    words := [{}]", items.join(", ")));
            }
            out
        };
        let pieces = decls
            .lines()
            .filter_map(|line| line.strip_prefix("def "))
            .filter_map(|rest| rest.split_once(" :").map(|(n, _)| n.to_string()))
            .collect();
        let text = format!(
            "{decls}def {name} : TypeTable :=\n  {{ carrier := {}, mag := {}, str := {}, strVec := {},\n    records := {records},\n    sums := {sums},\n    options := {options}, results := {results},\n    vecs := {vecs}, lists := {lists}, opaques := {opaques},\n    strSegs := {segs}{cons}{helpers}{sat}{bytes} }}\n\n",
            lean_opt_nat(self.carrier),
            lean_opt_nat(self.mag),
            lean_opt_nat(self.str_),
            lean_opt_nat(self.str_vec),
        );
        (text, pieces)
    }
}

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

    /// Every list literal in `text`, as the count of its top-level elements.
    fn literal_lengths(text: &str) -> Vec<usize> {
        // Per open `[`: (commas at its own level, saw an element, open
        // parentheses/anonymous constructors inside it).
        let mut open: Vec<(usize, bool, usize)> = Vec::new();
        let mut lengths = Vec::new();
        for c in text.chars() {
            match c {
                '[' => {
                    if let Some(top) = open.last_mut() {
                        top.1 = true;
                    }
                    open.push((0, false, 0));
                }
                ']' => {
                    let (commas, any, _) = open.pop().expect("balanced brackets");
                    lengths.push(if any { commas + 1 } else { 0 });
                }
                '(' | '⟨' => {
                    if let Some(top) = open.last_mut() {
                        top.1 = true;
                        top.2 += 1;
                    }
                }
                ')' | '⟩' => {
                    if let Some(top) = open.last_mut() {
                        top.2 -= 1;
                    }
                }
                ',' => {
                    if let Some(top) = open.last_mut()
                        && top.2 == 0
                    {
                        top.0 += 1;
                    }
                }
                c if !c.is_whitespace() => {
                    if let Some(top) = open.last_mut() {
                        top.1 = true;
                    }
                }
                _ => {}
            }
        }
        lengths
    }

    /// The numerals of `text` in order.
    fn numerals(text: &str) -> Vec<u64> {
        text.split(|c: char| !c.is_ascii_digit())
            .filter(|s| !s.is_empty())
            .map(|s| s.parse().unwrap())
            .collect()
    }

    /// The bodies of the piece declarations of one field, in order.
    fn piece_bodies(text: &str, field: &str) -> Vec<String> {
        let prefix = format!("def types_{field}_");
        text.split("\n\n")
            .filter(|d| d.starts_with(&prefix))
            .map(|d| d.split_once(":=").unwrap().1.to_string())
            .collect()
    }

    /// Regression: btc-listener's type table (151 string segments, the
    /// longest 570 bytes) was one list literal past Lean's `maxRecDepth` and
    /// one declaration past `maxHeartbeats`. A table far bigger than that is
    /// written with no literal longer than `LEAN_LIST_CHUNK`, no piece longer
    /// than `LEAN_TABLE_PIECE_CHARS` beyond its one oversized entry, and the
    /// same value: `++` only concatenates, so every numeral appears once and
    /// in the original order.
    #[test]
    fn a_big_type_table_is_written_in_pieces_with_the_same_value() {
        let segs: Vec<(Vec<u8>, u32)> = (0..300u32)
            .map(|i| {
                let len = (i * 7 % 900) as usize;
                ((0..len).map(|b| (b % 251) as u8).collect(), i)
            })
            .collect();
        let records: Vec<PlanRecordDecl> = (0..200u32)
            .map(|tid| PlanRecordDecl {
                tid,
                struct_idx: tid + 1000,
                fields: vec![PlanTy::Int, PlanTy::Str],
            })
            .collect();
        let tt = PlanTypeTable {
            records: records.clone(),
            str_segs: segs.clone(),
            ..PlanTypeTable::default()
        };
        let text = tt.lean_decls("types");

        let longest = literal_lengths(&text).into_iter().max().unwrap_or(0);
        assert!(longest <= LEAN_LIST_CHUNK, "a literal has {longest} elements");

        let seg_pieces = piece_bodies(&text, "strSegs");
        assert!(seg_pieces.len() > 1);
        for body in &seg_pieces {
            let entries = body.matches("),\n").count() + 1;
            assert!(
                body.len() <= LEAN_TABLE_PIECE_CHARS + 16 || entries == 1,
                "a piece of {entries} entries has {} chars",
                body.len()
            );
        }
        let expected: Vec<u64> = segs
            .iter()
            .flat_map(|(bytes, idx)| bytes.iter().map(|b| *b as u64).chain([*idx as u64]))
            .collect();
        assert_eq!(numerals(&seg_pieces.concat()), expected);

        let join = text
            .lines()
            .find_map(|l| l.trim_start().strip_prefix("strSegs := "))
            .unwrap();
        let joined: Vec<&str> = join.trim_end_matches(" }").split(" ++ ").collect();
        let declared: Vec<String> = (0..seg_pieces.len())
            .map(|k| format!("types_strSegs_{k}"))
            .collect();
        assert_eq!(joined, declared);

        let expected: Vec<u64> = records
            .iter()
            .flat_map(|r| [r.tid as u64, r.struct_idx as u64])
            .collect();
        assert_eq!(numerals(&piece_bodies(&text, "records").concat()), expected);

        // The piece names are exactly the declarations written before the
        // table, so a proof unfolding the table can name every one of them.
        let names = tt.lean_piece_names("types");
        let defs: Vec<String> = text
            .lines()
            .filter_map(|l| l.strip_prefix("def "))
            .filter_map(|l| l.split_once(" :").map(|(n, _)| n.to_string()))
            .filter(|n| n != "types")
            .collect();
        assert_eq!(names, defs);
        assert!(names.iter().any(|n| n.starts_with("types_records_")));
    }

    /// A table that fits one piece is written as one declaration with one
    /// inline literal per field.
    #[test]
    fn a_small_type_table_is_one_declaration() {
        let tt = PlanTypeTable {
            carrier: Some(3),
            records: vec![PlanRecordDecl {
                tid: 0,
                struct_idx: 5,
                fields: vec![PlanTy::Int, PlanTy::Bool],
            }],
            str_segs: vec![(b"hi".to_vec(), 2)],
            ..PlanTypeTable::default()
        };
        assert_eq!(
            tt.lean_decls("types"),
            "def types : TypeTable :=\n  { carrier := some 3, mag := none, str := none, strVec := none,\n    \
             records := [⟨0, 5, [.int, .bool]⟩],\n    sums := [],\n    options := [], results := [],\n    \
             vecs := [], lists := [], opaques := [],\n    strSegs := [([104, 105], 2)] }\n\n"
        );
    }
}

/// `AcceptedArtifact.callTargets`.
pub fn call_targets(e: &PlanExpr, out: &mut Vec<u32>) {
    match e {
        PlanExpr::Literal(_) | PlanExpr::Local(_) => {}
        PlanExpr::Let(_, v, b) => {
            call_targets(v, out);
            call_targets(b, out);
        }
        PlanExpr::Call(PlanCallee::Fn(f), args) | PlanExpr::TailCall(f, args) => {
            out.push(*f);
            args.iter().for_each(|a| call_targets(a, out));
        }
        PlanExpr::Call(_, args)
        | PlanExpr::RecordCreate(_, args)
        | PlanExpr::Construct(_, _, args)
        | PlanExpr::Interp(args)
        | PlanExpr::List(_, args) => args.iter().for_each(|a| call_targets(a, out)),
        PlanExpr::BinOp(_, l, r) => {
            call_targets(l, out);
            call_targets(r, out);
        }
        PlanExpr::Neg(x)
        | PlanExpr::Project(_, _, x)
        | PlanExpr::Try(x, _)
        | PlanExpr::Scope(x) => call_targets(x, out),
        PlanExpr::IntWord(..) | PlanExpr::IntCmp(..) => {}
        PlanExpr::If(c, t, el) => {
            call_targets(c, out);
            call_targets(t, out);
            call_targets(el, out);
        }
        PlanExpr::Match(s, arms) => {
            call_targets(s, out);
            arms.iter().for_each(|(_, b)| call_targets(b, out));
        }
    }
}