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
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL
//! The first-order part of a session: the instances its goals hold past
//! the forest's occurrences, the eigenvariables its `∀` steps made, and
//! the witnesses its `∃` steps left open as metavariables, with what the
//! axioms and the search bound them to.
//!
//! An undone step takes back the bindings it made, which the trail
//! records with the step's number, and drops the entries it made, from
//! the mark it took before them. Equal instances, frames and closed terms
//! are one entry each, so that a member stands for one instance and a
//! step done again names the members it named before.
use crate::hash::HashMap;
use crate::linear::Instances;
use crate::linear::occurrences::instances::{FrameId, Terms};
use crate::linear::occurrences::{Forest, Member, OccId};
use crate::linear::sequents::{Eigen, FoTerm, FoTermId, Symbol};
/// A metavariable: the witness of an `∃` step left open.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct Meta {
/// Its term in the table.
pub(super) term: FoTermId,
/// How many eigenvariables were made before it, lowered by every
/// binding of a metavariable it occurs in to that one's: a binding may
/// name only eigenvariables numbered below, or constants. An
/// eigenvariable made later belongs to a `∀` step above the `∃` step
/// that made the metavariable, or on another branch, and in its
/// witness would stand in that `∀` step's conclusion or outside its
/// subtree.
pub(super) level: u32,
/// Its level when it was made, before any binding lowered it.
pub(super) made: u32,
/// What a later axiom or the search bound it to.
pub(super) bound: Option<FoTermId>,
}
/// What a step did that its undo takes back.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Trailed {
/// A metavariable was bound.
Bound(u32),
/// A metavariable's level was lowered from the one given.
Lowered(u32, u32),
}
/// Why two terms do not unify.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Clash {
/// The symbols differ, or a metavariable would occur in its own
/// binding.
Terms,
/// A binding would name an eigenvariable made after the metavariable.
Eigen(Eigen),
}
/// A closed term by what it is, for hash-consing.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
enum Key {
/// A symbol applied to closed terms.
App(Symbol, Box<[FoTermId]>),
/// An eigenvariable.
Eigen(Eigen),
}
/// The first-order part of a session.
#[derive(Clone, Debug)]
pub(super) struct Quantified {
/// The instances as made: members, frames and terms, metavariables
/// among the terms.
pub(super) table: Instances,
/// The same instances with every bound metavariable replaced by what
/// it is bound to: what the views print and the proof is made of.
/// Members and frames keep their numbers. Made again ([`show`](Self::show))
/// after every change of the session, before anything reads it.
pub(super) shown: Instances,
/// Every member past the forest by its occurrence and frame.
members: HashMap<(OccId, FrameId), Member>,
/// Every frame by its parent and term.
frames: HashMap<(Option<FrameId>, FoTermId), FrameId>,
/// Every closed term without a metavariable by what it is, the
/// sequent's own closed terms among them.
terms: HashMap<Key, FoTermId>,
/// The metavariables, by number.
pub(super) metas: Vec<Meta>,
/// How many eigenvariables were made: the next one's number. Each is
/// a term of the table, as is each metavariable, so both together are
/// fewer than the table's terms, which a `u32` numbers.
pub(super) eigens: u32,
/// The eigenvariables that are constants: made by the search for a
/// witness nothing constrained, introduced by no `∀` step, and so
/// free to stand in any binding.
pub(super) constants: Vec<Eigen>,
/// The bindings and lowerings made, in order, each with the number of
/// the step that made it.
trail: Vec<(u32, Trailed)>,
/// Where the table, the metavariables, the eigenvariables and the
/// constants stood before each step that made entries, with the step's
/// number: what its undo truncates to. A session's JSON carries them,
/// so a session read back undoes as the one written would.
marks: Vec<(u32, Mark)>,
/// The most terms a term of the session may unfold to: `limits.terms`
/// of the session's start.
pub(super) limit: Option<u64>,
/// The most terms a shown term unfolds to, or the table's entries
/// (members, frames and terms) where they are more, as
/// [`show`](Self::show) last counted: what the reader bounds too.
pub(super) largest: u64,
}
/// Where a session's first-order part stood before a step.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Mark {
/// The members.
members: usize,
/// The frames.
frames: usize,
/// The terms past the sequent's.
terms: usize,
/// The arguments of the table's lists.
args: usize,
/// The table's lists.
lists: usize,
/// The metavariables.
metas: usize,
/// The eigenvariables made.
eigens: u32,
/// The constants.
constants: usize,
/// The trail.
trail: usize,
}
impl Quantified {
/// Returns the empty first-order part of a session over `forest`.
pub(super) fn new(forest: &Forest) -> Self {
let table = Instances::new(forest);
let fo = &forest.sequent().fo;
let loose = fo.loose();
let mut terms = HashMap::default();
for (n, term) in fo.terms.iter().enumerate() {
if let FoTerm::App(f, args) = *term
&& loose[n] == 0
{
// The sequent's arena has fewer terms than a `u32` counts.
let id = FoTermId::new(n as u32);
terms.insert(Key::App(f, fo.list(args).into()), id);
}
}
Self {
shown: table.clone(),
table,
members: HashMap::default(),
frames: HashMap::default(),
terms,
metas: Vec::new(),
eigens: 0,
constants: Vec::new(),
trail: Vec::new(),
marks: Vec::new(),
limit: Some(crate::Limits::DEFAULT_TERMS),
largest: 0,
}
}
/// Returns where everything stands now, for a step to go back to.
pub(super) fn mark(&self) -> Mark {
Mark {
members: self.table.members.len(),
frames: self.table.frames.len(),
terms: self.table.terms.len(),
args: self.table.args.len(),
lists: self.table.lists.len(),
metas: self.metas.len(),
eigens: self.eigens,
constants: self.constants.len(),
trail: self.trail.len(),
}
}
/// Goes back to `mark`: what the trail holds past it taken back, and
/// every entry, metavariable, eigenvariable and constant made since
/// dropped, none of which a member, frame or term before it names.
pub(super) fn back_to(&mut self, mark: Mark) {
self.undo_to(mark.trail);
let (occurrences, base) = (self.table.occurrences, self.table.base_terms);
self.table.members.truncate(mark.members);
self.table.frames.truncate(mark.frames);
self.table.terms.truncate(mark.terms);
self.table.args.truncate(mark.args);
self.table.lists.truncate(mark.lists);
self.metas.truncate(mark.metas);
self.eigens = mark.eigens;
self.constants.truncate(mark.constants);
// The ids below the mark fit a `u32`, as the table made them.
self.members
.retain(|_, m| (m.get() - occurrences) < mark.members as u32);
self.frames.retain(|_, f| f.get() < mark.frames as u32);
self.terms
.retain(|_, t| t.get() < base || t.get() - base < mark.terms as u32);
}
/// Moves the first-order part from `old` onto `new`, the session's
/// forest rebuilt with a cut formula added or taken back: `new`'s
/// occurrences are `old`'s and then the cut formulas', its arena holds
/// `old`'s terms (found again by what they are) and the cut formula's.
/// Every member past `old` moves past `new` (`shifted` maps a member
/// of the session), every term of the table is renumbered past `new`'s
/// arena, and the closed terms `new` adds are found where the table
/// has no equal one. The table's lengths stay, and so do the marks.
pub(super) fn rebase(&mut self, old: &Forest, new: &Forest) {
let (of, nf) = (&old.sequent().fo, &new.sequent().fo);
let symbol: HashMap<&str, Symbol> = nf
.symbols
.iter()
.enumerate()
// A sequent has fewer symbols than a `u32` numbers.
.map(|(i, (name, _))| (name.as_str(), Symbol::new(i as u32)))
.collect();
let symbol_of = |f: Symbol| symbol[of.symbols[f.index()].0.as_str()];
// The new arena's terms by what they are, to find the old ones.
let mut found: HashMap<(Option<Symbol>, u32, Vec<FoTermId>), FoTermId> = HashMap::default();
for (n, &term) in nf.terms.iter().enumerate() {
let key = match term {
FoTerm::Bound(i) => (None, i, Vec::new()),
FoTerm::App(f, args) => (Some(f), 0, nf.list(args).to_vec()),
FoTerm::Eigen(_) | FoTerm::Meta(_) => {
unreachable!("a sequent's arena holds no eigenvariable or metavariable")
}
};
// The arena has fewer terms than a `u32` numbers.
found.entry(key).or_insert(FoTermId::new(n as u32));
}
// Each old term in the new arena, or `None` for one of a cut
// formula taken back, which the table no longer names.
let mut moved: Vec<Option<FoTermId>> = Vec::with_capacity(of.terms.len());
for &term in &of.terms {
let key = match term {
FoTerm::Bound(i) => Some((None, i, Vec::new())),
FoTerm::App(f, args) => {
let args: Option<Vec<FoTermId>> =
of.list(args).iter().map(|a| moved[a.index()]).collect();
symbol
.get(of.symbols[f.index()].0.as_str())
.zip(args)
.map(|(&f, args)| (Some(f), 0, args))
}
FoTerm::Eigen(_) | FoTerm::Meta(_) => {
unreachable!("a sequent's arena holds no eigenvariable or metavariable")
}
};
moved.push(key.and_then(|key| found.get(&key).copied()));
}
let (old_base, new_base) = (self.table.base_terms, nf.terms.len() as u32);
let kept = |t: FoTermId| {
if t.get() < old_base {
moved[t.index()]
} else {
Some(FoTermId::new(t.get() - old_base + new_base))
}
};
let term = |t: FoTermId| kept(t).expect("the table names only terms both arenas hold");
let mut table = Instances::new(new);
for &t in &self.table.terms {
match t {
FoTerm::App(f, args) => {
let items: Vec<FoTermId> = self
.terms(old)
.list(args)
.iter()
.map(|&a| term(a))
.collect();
table.apply(symbol_of(f), &items);
}
FoTerm::Eigen(_) | FoTerm::Meta(_) => {
table.push_term(t);
}
FoTerm::Bound(_) => unreachable!("a table's term is closed"),
}
}
for &(parent, t) in &self.table.frames {
table.frame(parent, term(t));
}
for &(o, f) in &self.table.members {
table.member(o, f);
}
let (from, to) = (old.len() as u32, new.len() as u32);
for m in self.members.values_mut() {
*m = Member::new(m.get() - from + to);
}
self.frames = std::mem::take(&mut self.frames)
.into_iter()
.map(|((parent, t), f)| ((parent, term(t)), f))
.collect();
self.terms = std::mem::take(&mut self.terms)
.into_iter()
.filter_map(|(key, t)| {
let key = match key {
Key::App(f, args) => Key::App(
*symbol.get(of.symbols[f.index()].0.as_str())?,
args.iter().map(|&a| kept(a)).collect::<Option<_>>()?,
),
eigen @ Key::Eigen(_) => eigen,
};
Some((key, kept(t)?))
})
.collect();
let loose = nf.loose();
for (n, t) in nf.terms.iter().enumerate() {
if let FoTerm::App(f, args) = *t
&& loose[n] == 0
{
self.terms
.entry(Key::App(f, nf.list(args).into()))
.or_insert(FoTermId::new(n as u32));
}
}
for meta in &mut self.metas {
meta.term = term(meta.term);
meta.bound = meta.bound.map(term);
}
self.table = table;
self.show(new);
}
/// Returns how many of the sequent's arena terms the table names: one
/// past the last that a term's arguments, a frame or a binding names.
pub(super) fn arena_reach(&self) -> usize {
let base = self.table.base_terms;
let below = |t: FoTermId| if t.get() < base { t.index() + 1 } else { 0 };
let args = self.table.args.iter().map(|&t| below(t));
let frames = self.table.frames.iter().map(|&(_, t)| below(t));
let bound = self.metas.iter().filter_map(|m| m.bound).map(below);
args.chain(frames).chain(bound).max().unwrap_or(0)
}
/// Records that the step numbered `step` made entries from `mark` on,
/// for its undo.
pub(super) fn made(&mut self, step: u32, mark: Mark) {
self.marks.push((step, mark));
}
/// Returns the occurrence and frame a member stands for: no frame for
/// an occurrence of the forest.
pub(super) fn instance(&self, m: Member) -> (OccId, Option<FrameId>) {
self.table
.instance(m)
.map_or((m.occ(), None), |(o, f)| (o, Some(f)))
}
/// Returns the member of occurrence `o` under `frame`: the occurrence
/// itself without one.
pub(super) fn member(&mut self, o: OccId, frame: Option<FrameId>) -> Member {
let Some(frame) = frame else {
return Member::from(o);
};
if let Some(&m) = self.members.get(&(o, frame)) {
return m;
}
let m = self.table.member(o, frame);
self.members.insert((o, frame), m);
m
}
/// Returns the member of occurrence `o` under `frame` where the table
/// has it: the occurrence itself without a frame.
pub(super) fn find(&self, o: OccId, frame: Option<FrameId>) -> Option<Member> {
match frame {
None => Some(Member::from(o)),
Some(frame) => self.members.get(&(o, frame)).copied(),
}
}
/// Returns the shown table with every open witness a fresh constant:
/// the metavariable `k` the eigenvariable numbered `eigens + k`, which
/// no `∀` step introduces. Refused past the numbers a `u32` holds.
pub(super) fn closed_table(&self) -> Result<Instances, crate::Error> {
let mut table = self.shown.clone();
for term in &mut table.terms {
if let FoTerm::Meta(k) = *term {
let Some(n) = self.eigens.checked_add(k) else {
return Err(crate::Error::Refused(crate::Refusal::Index {
what: crate::limits::Space::Term,
count: u64::from(self.eigens) + u64::from(k),
most: u64::from(u32::MAX),
}));
};
*term = FoTerm::Eigen(Eigen::new(n));
}
}
Ok(table)
}
/// Returns the frame that pushes `term` onto `parent`.
pub(super) fn frame(&mut self, parent: Option<FrameId>, term: FoTermId) -> FrameId {
if let Some(&f) = self.frames.get(&(parent, term)) {
return f;
}
let f = self.table.frame(parent, term);
self.frames.insert((parent, term), f);
f
}
/// Returns the closed term `key`, made once.
fn closed(&mut self, key: Key) -> FoTermId {
if let Some(&t) = self.terms.get(&key) {
return t;
}
let t = match &key {
Key::App(f, args) => self.table.apply(*f, args),
&Key::Eigen(a) => self.table.eigen(a),
};
self.terms.insert(key, t);
t
}
/// Returns the term of symbol `f` applied to `args`, closed terms.
pub(super) fn apply(&mut self, f: Symbol, args: &[FoTermId]) -> FoTermId {
self.closed(Key::App(f, args.into()))
}
/// Returns the term of the eigenvariable `a`.
pub(super) fn eigen_term(&mut self, a: Eigen) -> FoTermId {
self.closed(Key::Eigen(a))
}
/// Makes a fresh eigenvariable and returns it with its term, or `None`
/// past the numbers a `u32` holds.
pub(super) fn fresh_eigen(&mut self) -> Option<(Eigen, FoTermId)> {
let a = Eigen::new(self.eigens);
self.eigens = self.eigens.checked_add(1)?;
Some((a, self.eigen_term(a)))
}
/// Makes a fresh metavariable at the level of the eigenvariables made
/// so far and returns its term.
pub(super) fn fresh_meta(&mut self) -> FoTermId {
// Fewer metavariables than the table's terms, which a `u32` numbers.
let k = self.metas.len() as u32;
let term = self.table.push_term(FoTerm::Meta(k));
self.metas.push(Meta {
term,
level: self.eigens,
made: self.eigens,
bound: None,
});
term
}
/// Returns the terms of both arenas.
pub(super) fn terms<'a>(&'a self, forest: &'a Forest) -> Terms<'a> {
Terms {
fo: &forest.sequent().fo,
table: &self.table,
}
}
/// Returns `t` with the bindings of the metavariables at its top
/// followed.
pub(super) fn resolve(&self, forest: &Forest, mut t: FoTermId) -> FoTermId {
let terms = self.terms(forest);
while let FoTerm::Meta(k) = terms.term(t)
&& let Some(b) = self.metas[k as usize].bound
{
t = b;
}
t
}
/// Returns the frame's terms, the innermost binder's first; none for no
/// frame.
pub(super) fn frame_terms(&self, frame: Option<FrameId>) -> Vec<FoTermId> {
frame.map_or_else(Vec::new, |f| self.table.frame_terms(f))
}
/// Returns the term of the sequent's arena `t`, whose loose bound
/// variables the frame's terms (innermost first) close, as a closed
/// term of both arenas, made where it is not one already.
pub(super) fn close(&mut self, forest: &Forest, t: FoTermId, frame: &[FoTermId]) -> FoTermId {
let fo = &forest.sequent().fo;
// A walk with a stack of its own, children before their term.
let mut done: HashMap<FoTermId, FoTermId> = HashMap::default();
let mut stack = vec![(t, false)];
while let Some((u, expanded)) = stack.pop() {
if done.contains_key(&u) {
continue;
}
match fo.terms[u.index()] {
FoTerm::Bound(i) => {
// The sequent's check keeps every bound index below
// its occurrence's binders, and a frame holds a term
// for each.
done.insert(u, frame[i as usize]);
}
FoTerm::App(f, args) if expanded => {
let items: Vec<FoTermId> = fo.list(args).iter().map(|c| done[c]).collect();
let closed = self.apply(f, &items);
done.insert(u, closed);
}
FoTerm::App(_, args) => {
stack.push((u, true));
stack.extend(fo.list(args).iter().map(|&c| (c, false)));
}
FoTerm::Eigen(_) | FoTerm::Meta(_) => {
unreachable!("a sequent's arena holds no eigenvariable or metavariable")
}
}
}
done[&t]
}
/// Returns the predicate and the closed arguments of the literal a
/// member stands for; `None` for a nullary atom of a sequent whose
/// atoms have no tables, whose identity is its atom.
pub(super) fn literal(
&mut self,
forest: &Forest,
m: Member,
) -> Option<(Symbol, Vec<FoTermId>)> {
let (o, frame) = self.instance(m);
let atom = forest.atom(o).expect("a literal has an atom");
let fo = &forest.sequent().fo;
let &(symbol, args) = fo.atoms.get(atom.index())?;
let frame = self.frame_terms(frame);
let args: Vec<FoTermId> = fo.list(args).to_vec();
Some((
symbol,
args.into_iter()
.map(|t| self.close(forest, t, &frame))
.collect(),
))
}
/// Unifies the pairs of closed terms, binding metavariables with the
/// occurs check and the levels; the bindings are trailed under `step`.
/// On a clash nothing is left bound.
pub(super) fn unify(
&mut self,
forest: &Forest,
pairs: Vec<(FoTermId, FoTermId)>,
step: u32,
) -> Result<(), Clash> {
let mark = self.trail.len();
let result = self.unify_pairs(forest, pairs, step);
if result.is_err() {
self.undo_to(mark);
}
result
}
/// Unifies the pairs, leaving what it bound before a clash.
fn unify_pairs(
&mut self,
forest: &Forest,
mut pairs: Vec<(FoTermId, FoTermId)>,
step: u32,
) -> Result<(), Clash> {
// A pair met before is unified already: shared terms are walked
// once, not once per path to them.
let mut met: std::collections::HashSet<(FoTermId, FoTermId)> = Default::default();
while let Some((x, y)) = pairs.pop() {
let (x, y) = (self.resolve(forest, x), self.resolve(forest, y));
if x == y || !met.insert((x, y)) {
continue;
}
let terms = self.terms(forest);
match (terms.term(x), terms.term(y)) {
(FoTerm::Meta(k), _) => self.bind(forest, k, y, step)?,
(_, FoTerm::Meta(k)) => self.bind(forest, k, x, step)?,
(FoTerm::App(f, a), FoTerm::App(g, b)) if f == g => {
pairs.extend(
terms
.list(a)
.iter()
.copied()
.zip(terms.list(b).iter().copied()),
);
}
// Distinct eigenvariables, an eigenvariable against an
// application, or two symbols.
_ => return Err(Clash::Terms),
}
}
Ok(())
}
/// Binds the unbound metavariable `k` to `t`, refusing a `t` that holds
/// `k` or an eigenvariable at or above `k`'s level that is no
/// constant, and lowering the levels of the metavariables `t` holds to
/// `k`'s.
pub(super) fn bind(
&mut self,
forest: &Forest,
k: u32,
t: FoTermId,
step: u32,
) -> Result<(), Clash> {
let level = self.metas[k as usize].level;
let mut lowered = Vec::new();
{
let terms = self.terms(forest);
let mut seen: std::collections::HashSet<FoTermId> = Default::default();
let mut stack = vec![t];
while let Some(u) = stack.pop() {
let u = self.resolve(forest, u);
if !seen.insert(u) {
continue;
}
match terms.term(u) {
FoTerm::Meta(j) if j == k => return Err(Clash::Terms),
FoTerm::Meta(j) => {
if self.metas[j as usize].level > level {
lowered.push(j);
}
}
FoTerm::Eigen(a) => {
if a.get() >= level && !self.constants.contains(&a) {
return Err(Clash::Eigen(a));
}
}
FoTerm::App(_, args) => stack.extend_from_slice(terms.list(args)),
FoTerm::Bound(_) => unreachable!("a closed term has no bound variable"),
}
}
}
for j in lowered {
let meta = &mut self.metas[j as usize];
self.trail.push((step, Trailed::Lowered(j, meta.level)));
meta.level = level;
}
self.metas[k as usize].bound = Some(t);
self.trail.push((step, Trailed::Bound(k)));
Ok(())
}
/// Takes back what the steps numbered `step` and later bound and
/// lowered, and drops what they made where their marks say.
pub(super) fn undo(&mut self, step: u32) {
let keep = self.trail.partition_point(|&(s, _)| s < step);
self.undo_to(keep);
while let Some(&(s, mark)) = self.marks.last()
&& s >= step
{
self.marks.pop();
self.back_to(mark);
}
}
/// Takes back the trail past its first `len` entries, last first.
fn undo_to(&mut self, len: usize) {
while self.trail.len() > len {
let (_, trailed) = self.trail.pop().expect("longer than len");
match trailed {
Trailed::Bound(k) => self.metas[k as usize].bound = None,
Trailed::Lowered(k, level) => self.metas[k as usize].level = level,
}
}
}
/// Returns the bindings in force in the order made, each the
/// metavariable, its term and the step that made it.
#[cfg(feature = "serialize")]
pub(super) fn bindings(&self) -> impl Iterator<Item = (u32, FoTermId, u32)> + '_ {
self.trail
.iter()
.filter_map(|&(step, trailed)| match trailed {
Trailed::Bound(k) => Some((
k,
self.metas[k as usize]
.bound
.expect("a trailed binding holds"),
step,
)),
Trailed::Lowered(..) => None,
})
}
/// Rebuilds the first-order part of a session over `forest` from its
/// written form: the table's members, frames and terms, the level
/// each metavariable was made at, the eigenvariables made and the
/// constants among them; and replays the bindings in the order made.
/// Refuses a table a session could not have made: an entry naming one
/// after it or out of range, a frame of another length than its
/// occurrence's binders, an entry made twice, a term of a predicate or
/// of the wrong arity, a binding the occurs check or the levels
/// refuse, a step out of order.
#[cfg(feature = "serialize")]
pub(super) fn from_parts(
forest: &Forest,
parts: Parts,
steps: usize,
limit: Option<u64>,
) -> Result<Self, crate::Error> {
let bad = |reason: &'static str| crate::Error::InconsistentSession { reason };
let mut q = Self::new(forest);
q.eigens = parts.eigens;
q.limit = limit;
let fo = &forest.sequent().fo;
let loose = fo.loose();
let predicates: Vec<Symbol> = fo.atoms.iter().map(|&(p, _)| p).collect();
let base = q.table.base_terms as usize;
let closed = |t: u32, before: usize| {
(t as usize) < before && (t as usize >= base || loose.get(t as usize) == Some(&0))
};
for (n, term) in parts.terms.iter().enumerate() {
let id = base + n;
match *term {
PartTerm::App(f, ref args) => {
let Some(&(_, arity)) = fo.symbols.get(f as usize) else {
return Err(bad("a term names no symbol of the sequent"));
};
let f = Symbol::new(f);
if predicates.contains(&f) || arity as usize != args.len() {
return Err(bad(
"a term applies a predicate, or a symbol to the wrong number of arguments",
));
}
if !args.iter().all(|&a| closed(a, id)) {
return Err(bad("a term's argument is not a closed term before it"));
}
let args: Vec<FoTermId> = args.iter().map(|&a| FoTermId::new(a)).collect();
// A term may equal one of the sequent's, which a cut
// brought into the arena after the term was made.
if q.terms
.get(&Key::App(f, args.clone().into()))
.is_some_and(|t| t.get() >= q.table.base_terms)
{
return Err(bad("a term repeats another"));
}
let t = q.table.apply(f, &args);
q.terms.insert(Key::App(f, args.into()), t);
}
PartTerm::Eigen(a) => {
let a = Eigen::new(a);
if a.get() >= q.eigens || q.terms.contains_key(&Key::Eigen(a)) {
return Err(bad("an eigenvariable repeats or is past those made"));
}
let t = q.table.eigen(a);
q.terms.insert(Key::Eigen(a), t);
}
PartTerm::Meta(k) => {
let Some(&made) = parts.metas.get(q.metas.len()) else {
return Err(bad("a metavariable has no level"));
};
if k as usize != q.metas.len() || made > q.eigens {
return Err(bad(
"the metavariables are not numbered in order, or a level is past the eigenvariables made",
));
}
let term = q.table.push_term(FoTerm::Meta(k));
q.metas.push(Meta {
term,
level: made,
made,
bound: None,
});
}
}
}
if q.metas.len() != parts.metas.len() {
return Err(bad("a level has no metavariable"));
}
let all = base + parts.terms.len();
let mut lengths: Vec<u32> = Vec::with_capacity(parts.frames.len());
for (n, &(parent, t)) in parts.frames.iter().enumerate() {
if parent.is_some_and(|p| p as usize >= n) || !closed(t, all) {
return Err(bad("a frame names a frame after it or a term out of range"));
}
let parent = parent.map(FrameId::new);
let t = FoTermId::new(t);
if q.frames.contains_key(&(parent, t)) {
return Err(bad("a frame repeats another"));
}
let f = q.table.frame(parent, t);
q.frames.insert((parent, t), f);
lengths.push(parent.map_or(1, |p| lengths[p.index()] + 1));
}
let depth = crate::linear::occurrences::instances::binders(forest);
for &(o, f) in &parts.members {
let fits = depth
.get(o as usize)
.zip(lengths.get(f as usize))
.is_some_and(|(d, l)| d == l);
if !fits {
return Err(bad(
"a member's frame is not as long as its occurrence's binders",
));
}
let (o, f) = (OccId::new(o), FrameId::new(f));
if q.members.contains_key(&(o, f)) {
return Err(bad("a member repeats another"));
}
let m = q.table.member(o, f);
q.members.insert((o, f), m);
}
for &a in &parts.constants {
if a >= q.eigens {
return Err(bad("a constant is past the eigenvariables made"));
}
q.constants.push(Eigen::new(a));
}
let mut last = 0;
for &(k, t, step) in &parts.bindings {
// A step binds a metavariable to a term whose top is no bound
// metavariable: unification follows the bindings first.
let ok = step >= last
&& (step as usize) < steps
&& q.metas.get(k as usize).is_some_and(|m| m.bound.is_none())
&& closed(t, all)
&& q.resolve(forest, FoTermId::new(t)) == FoTermId::new(t);
if !ok || q.bind(forest, k, FoTermId::new(t), step).is_err() {
return Err(bad(
"a binding is out of order, of no open metavariable, or one the occurs check or the levels refuse",
));
}
last = step;
}
q.show(forest);
if let Some(limit) = q.limit
&& q.too_large()
{
return Err(crate::Error::Refused(crate::Refusal::Terms {
terms: q.largest,
limit,
}));
}
Ok(q)
}
/// Reads the marks of a session's written form, each step's with the
/// table's lengths before it, and derives what the table's order
/// fixes: its argument lists and metavariables, which every term
/// before the mark made, and the trail, the steps before it. Refuses
/// marks of steps out of order or past the history, lengths that fall
/// or pass the table's, and a mark that would drop what an entry
/// before it, a binding of an earlier step or a level names; the
/// inferences' members are [`marked_members`](Self::marked_members)'
/// to check.
#[cfg(feature = "serialize")]
pub(super) fn read_marks(
&mut self,
written: &[(u32, u32, u32, u32, u32, u32)],
steps: usize,
) -> Result<(), crate::Error> {
let bad = || crate::Error::InconsistentSession {
reason: "a mark is out of order, past the table, or drops what a step before it made",
};
let base = self.table.base_terms;
// How many of the table's terms a term reaches into: none for the
// sequent's own.
let reach = |t: FoTermId| t.get().checked_sub(base).map_or(0, |n| n as usize + 1);
let frames = prefix_max(self.table.members.iter().map(|&(_, f)| f.index() + 1));
let terms = prefix_max(self.table.frames.iter().map(|&(_, t)| reach(t)));
// Per prefix of the terms: the eigenvariables its terms and its
// metavariables' levels need made, its metavariables, arguments
// and lists.
let (mut eigens, mut metas, mut args, mut lists) = (vec![0], vec![0], vec![0], vec![0]);
let mut made = 0;
for term in &self.table.terms {
let (mut m, mut a, mut l) = (
*metas.last().expect("never empty"),
*args.last().expect("never empty"),
*lists.last().expect("never empty"),
);
match *term {
FoTerm::Eigen(e) => made = made.max(e.get() as usize + 1),
FoTerm::Meta(k) => {
made = made.max(self.metas[k as usize].made as usize);
m += 1;
}
FoTerm::App(_, list) => {
let (_, len) = self.table.lists[(list.get() - self.table.base_lists) as usize];
a += len as usize;
l += 1;
}
FoTerm::Bound(_) => unreachable!("a table's term is closed"),
}
eigens.push(made);
metas.push(m);
args.push(a);
lists.push(l);
}
let constants = prefix_max(self.constants.iter().map(|a| a.get() as usize + 1));
// What a mark drops is made after it, so numbered from its
// eigenvariables on: per suffix, the least eigenvariable its terms
// and constants hold.
let dropped_terms = suffix_min(self.table.terms.iter().map(|t| match *t {
FoTerm::Eigen(e) => e.get() as usize,
FoTerm::App(..) | FoTerm::Meta(_) | FoTerm::Bound(_) => usize::MAX,
}));
let dropped_constants = suffix_min(self.constants.iter().map(|a| a.get() as usize));
let bound = prefix_max(self.trail.iter().map(|&(_, trailed)| match trailed {
Trailed::Bound(k) => {
let meta = &self.metas[k as usize];
reach(meta.term).max(meta.bound.map_or(0, reach))
}
Trailed::Lowered(k, _) => reach(self.metas[k as usize].term),
}));
let mut marks = Vec::with_capacity(written.len());
let mut last: Option<(u32, Mark)> = None;
for &(step, members, frame_count, term_count, eigen_count, constant_count) in written {
let (m, f, t, c) = (
members as usize,
frame_count as usize,
term_count as usize,
constant_count as usize,
);
let trail = self.trail.partition_point(|&(s, _)| s < step);
let fits = (step as usize) < steps
&& m <= self.table.members.len()
&& f <= self.table.frames.len()
&& t <= self.table.terms.len()
&& eigen_count <= self.eigens
&& c <= self.constants.len()
&& frames[m] <= f
&& terms[f] <= t
&& bound[trail] <= t
&& eigens[t] <= eigen_count as usize
&& constants[c] <= eigen_count as usize
&& dropped_terms[t] >= eigen_count as usize
&& dropped_constants[c] >= eigen_count as usize;
let after = last.is_none_or(|(s, before)| {
s < step
&& before.members <= m
&& before.frames <= f
&& before.terms <= t
&& before.eigens <= eigen_count
&& before.constants <= c
});
if !fits || !after {
return Err(bad());
}
let mark = Mark {
members: m,
frames: f,
terms: t,
args: args[t],
lists: lists[t],
metas: metas[t],
eigens: eigen_count,
constants: c,
trail,
};
marks.push((step, mark));
last = Some((step, mark));
}
self.marks = marks;
Ok(())
}
/// Returns each mark's step with the members before it: what the
/// inferences before that step may name past the forest.
#[cfg(feature = "serialize")]
pub(super) fn marked_members(&self) -> impl Iterator<Item = (u32, usize)> + '_ {
self.marks.iter().map(|&(step, mark)| (step, mark.members))
}
/// Returns the written form of the first-order part.
#[cfg(feature = "serialize")]
pub(super) fn parts(&self, forest: &Forest) -> Parts {
let terms = self.terms(forest);
Parts {
members: self
.table
.members
.iter()
.map(|&(o, f)| (o.get(), f.get()))
.collect(),
frames: self
.table
.frames
.iter()
.map(|&(p, t)| (p.map(FrameId::get), t.get()))
.collect(),
terms: self
.table
.terms
.iter()
.map(|&t| match t {
FoTerm::App(f, args) => {
PartTerm::App(f.get(), terms.list(args).iter().map(|a| a.get()).collect())
}
FoTerm::Eigen(a) => PartTerm::Eigen(a.get()),
FoTerm::Meta(k) => PartTerm::Meta(k),
FoTerm::Bound(_) => unreachable!("a table's term is closed"),
})
.collect(),
metas: self.metas.iter().map(|m| m.made).collect(),
eigens: self.eigens,
constants: self.constants.iter().map(|a| a.get()).collect(),
bindings: self
.bindings()
.map(|(k, t, step)| (k, t.get(), step))
.collect(),
// The table's lengths fit a `u32`, as its ids do.
marks: self
.marks
.iter()
.map(|&(step, m)| {
(
step,
m.members as u32,
m.frames as u32,
m.terms as u32,
m.eigens,
m.constants as u32,
)
})
.collect(),
}
}
/// Returns whether two literals stand for the same atom under the
/// bindings, as instances: one predicate, equal arguments; read in the
/// shown table, where the bindings are followed already, building
/// nothing, binding nothing.
pub(super) fn same_atom(&self, forest: &Forest, x: Member, y: Member) -> bool {
let fo = &forest.sequent().fo;
let shown = |m: Member| {
self.shown
.instance(m)
.map_or((m.occ(), None), |(o, f)| (o, Some(f)))
};
let ((ox, fx), (oy, fy)) = (shown(x), shown(y));
let (ax, ay) = (forest.atom(ox), forest.atom(oy));
let (Some(&(p, a)), Some(&(r, b))) = (
ax.and_then(|a| fo.atoms.get(a.index())),
ay.and_then(|a| fo.atoms.get(a.index())),
) else {
return ax == ay;
};
if p != r {
return false;
}
let frame = |f: Option<FrameId>| f.map_or_else(Vec::new, |f| self.shown.frame_terms(f));
let (fx, fy) = (frame(fx), frame(fy));
let loose = fo.loose();
let terms = Terms {
fo,
table: &self.shown,
};
// A term is the sequent's under its side's frame, or closed.
let side = |t: FoTermId, frame: &[FoTermId], open: bool| match fo.terms.get(t.index()) {
Some(&FoTerm::Bound(i)) if open => (frame[i as usize], false),
_ if open && loose[t.index()] == 0 => (t, false),
_ => (t, open),
};
let term = |u: FoTermId, open: bool| {
if open {
fo.terms[u.index()]
} else {
terms.term(u)
}
};
let list = |args, open: bool| {
if open {
fo.list(args)
} else {
terms.list(args)
}
};
let mut pairs: Vec<((FoTermId, bool), (FoTermId, bool))> = fo
.list(a)
.iter()
.zip(fo.list(b))
.map(|(&s, &t)| ((s, true), (t, true)))
.collect();
// A pair met before is equal already: shared terms are compared
// once, not once per path to them.
let mut met: std::collections::HashSet<((FoTermId, bool), (FoTermId, bool))> =
Default::default();
while let Some(((s, so), (t, to))) = pairs.pop() {
let (s, t) = (side(s, &fx, so), side(t, &fy, to));
if (!s.1 && !t.1 && s.0 == t.0) || !met.insert((s, t)) {
continue;
}
match (term(s.0, s.1), term(t.0, t.1)) {
(FoTerm::App(f, a), FoTerm::App(g, b)) if f == g => pairs.extend(
list(a, s.1)
.iter()
.zip(list(b, t.1))
.map(|(&u, &v)| ((u, s.1), (v, t.1))),
),
_ => return false,
}
}
true
}
/// Returns the eigenvariables and the unbound metavariables a closed
/// term holds under the bindings.
pub(super) fn variables(&self, forest: &Forest, t: FoTermId) -> (Vec<Eigen>, Vec<u32>) {
let terms = self.terms(forest);
let (mut eigens, mut metas) = (Vec::new(), Vec::new());
let mut seen: std::collections::HashSet<FoTermId> = Default::default();
let mut stack = vec![t];
while let Some(u) = stack.pop() {
let u = self.resolve(forest, u);
if !seen.insert(u) {
continue;
}
match terms.term(u) {
FoTerm::Eigen(a) => eigens.push(a),
FoTerm::Meta(k) => metas.push(k),
FoTerm::App(_, args) => stack.extend_from_slice(terms.list(args)),
FoTerm::Bound(_) => unreachable!("a closed term has no bound variable"),
}
}
(eigens, metas)
}
/// Makes the shown table again from the table and the bindings in
/// force: every extension term with its bound metavariables replaced,
/// the frames over those terms, the members as they are.
pub(super) fn show(&mut self, forest: &Forest) {
let base = self.table.base_terms;
let mut shown = Instances::new(forest);
let mut at: HashMap<FoTermId, FoTermId> = HashMap::default();
let terms = self.terms(forest);
for n in 0..self.table.terms.len() {
// The table's ids are below `u32::MAX`, as `Instances` makes
// them.
let t = FoTermId::new(base + n as u32);
// A walk with a stack of its own: a binding names terms made
// after the metavariable.
let mut stack = vec![(t, false)];
while let Some((u, expanded)) = stack.pop() {
if u.get() < base || at.contains_key(&u) {
continue;
}
let made = match terms.term(u) {
FoTerm::Meta(k) => match self.metas[k as usize].bound {
Some(b) if expanded => self.mapped(b, &at),
Some(b) => {
stack.push((u, true));
stack.push((b, false));
continue;
}
None => shown.push_term(FoTerm::Meta(k)),
},
FoTerm::App(f, args) if expanded => {
let items: Vec<FoTermId> = terms
.list(args)
.iter()
.map(|&c| self.mapped(c, &at))
.collect();
shown.apply(f, &items)
}
FoTerm::App(_, args) => {
stack.push((u, true));
stack.extend(terms.list(args).iter().map(|&c| (c, false)));
continue;
}
FoTerm::Eigen(a) => shown.eigen(a),
FoTerm::Bound(_) => unreachable!("a table's term is closed"),
};
at.insert(u, made);
}
}
shown.frames = self
.table
.frames
.iter()
.map(|&(parent, t)| (parent, self.mapped(t, &at)))
.collect();
shown.members.clone_from(&self.table.members);
// How many terms each shown term unfolds to, arguments first.
let unfolded = forest.sequent().fo.unfolded();
let mut sizes: Vec<u64> = Vec::with_capacity(shown.terms.len());
let size = |sizes: &[u64], t: FoTermId| {
if t.get() < base {
unfolded[t.index()]
} else {
sizes[(t.get() - base) as usize]
}
};
for &term in &shown.terms {
let n = match term {
FoTerm::App(_, args) => {
let start = (args.get() - shown.base_lists) as usize;
let (from, len) = shown.lists[start];
shown.args[from as usize..(from + len) as usize]
.iter()
.fold(1u64, |sum, &a| sum.saturating_add(size(&sizes, a)))
}
FoTerm::Eigen(_) | FoTerm::Meta(_) | FoTerm::Bound(_) => 1,
};
sizes.push(n);
}
let entries = (shown.members.len() as u64)
.saturating_add(shown.frames.len() as u64)
.saturating_add(shown.terms.len() as u64);
self.largest = sizes.iter().copied().max().unwrap_or(0).max(entries);
self.shown = shown;
}
/// Returns whether a shown term unfolds past the session's limit.
pub(super) fn too_large(&self) -> bool {
self.limit.is_some_and(|limit| self.largest > limit)
}
/// Returns the shown term of a term of either arena: the sequent's own
/// as it is, the table's by `at`.
fn mapped(&self, t: FoTermId, at: &HashMap<FoTermId, FoTermId>) -> FoTermId {
if t.get() < self.table.base_terms {
t
} else {
at[&t]
}
}
}
/// A term of a session's table as its written form holds it.
#[cfg(feature = "serialize")]
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum PartTerm {
/// A symbol applied to closed terms, by their ids.
App(u32, Vec<u32>),
/// An eigenvariable by its number.
Eigen(u32),
/// A metavariable by its number.
Meta(u32),
}
/// The written form of a session's first-order part.
#[cfg(feature = "serialize")]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Parts {
/// The members past the forest: occurrence and frame.
pub(crate) members: Vec<(u32, u32)>,
/// The frames: parent and term.
pub(crate) frames: Vec<(Option<u32>, u32)>,
/// The terms past the sequent's.
pub(crate) terms: Vec<PartTerm>,
/// The level each metavariable was made at.
pub(crate) metas: Vec<u32>,
/// How many eigenvariables were made.
pub(crate) eigens: u32,
/// The eigenvariables that are constants.
pub(crate) constants: Vec<u32>,
/// The bindings in the order made: metavariable, term, step.
pub(crate) bindings: Vec<(u32, u32, u32)>,
/// Where the table stood before each step that made entries: step,
/// members, frames, terms, eigenvariables, constants.
pub(crate) marks: Vec<(u32, u32, u32, u32, u32, u32)>,
}
/// Returns, for each suffix of `values`, the least of them: entry `i`
/// for the values from `i` on, `usize::MAX` for none.
#[cfg(feature = "serialize")]
fn suffix_min(values: impl DoubleEndedIterator<Item = usize> + ExactSizeIterator) -> Vec<usize> {
let mut minima = vec![usize::MAX; values.len() + 1];
for (i, v) in values.enumerate().rev() {
minima[i] = minima[i + 1].min(v);
}
minima
}
/// Returns, for each prefix of `reach`, the largest of its values: entry
/// `i` for the first `i` values, `0` for none.
#[cfg(feature = "serialize")]
pub(super) fn prefix_max(reach: impl Iterator<Item = usize>) -> Vec<usize> {
let mut maxima = vec![0];
for r in reach {
let last = *maxima.last().expect("never empty");
maxima.push(last.max(r));
}
maxima
}