deduxit 0.5.0

A collection of logic suites: decides, checks, proves step by step and exports sequents of linear logic and of classical, intuitionistic and minimal propositional logic, with checked proofs, Kripke countermodels and Rocq certificates.
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
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

// A new variant of an enum matched here must not fall into an existing
// arm unnoticed.
#![deny(clippy::wildcard_enum_match_arm)]

pub mod ill;
pub mod instances;
pub mod reading;
/// Bitsets over occurrence ids.
pub(crate) mod set;
pub mod written;

pub use ill::{IllSequent, IllSyntax, InputOptions};
pub use instances::{FrameId, Instances};
pub use reading::{IllConnective, IllFormula, Reading, ShapeError, Side};
pub(crate) use set::OccSet;
pub use written::{ClassicalSequent, Written};

use crate::Error;
use crate::limits::{Limits, Refusal, Space};
use crate::linear::sequents::{Atom, Formula, Kind, Sequent, TermId};
use std::ops::Not;

/// The index of a subformula occurrence in a [`Forest`]: the position of the
/// occurrence in a depth-first preorder walk over the root formulas.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct OccId(u32);

impl OccId {
    /// Wraps a raw occurrence index.
    pub const fn new(index: u32) -> Self {
        Self(index)
    }

    /// Returns the raw occurrence index.
    pub const fn get(self) -> u32 {
        self.0
    }

    /// Returns the index as a `usize`, for indexing per-occurrence arrays.
    pub const fn index(self) -> usize {
        self.0 as usize
    }
}

/// A member of a sequent held by a proof, a derivation, a session or a
/// goal.
///
/// A member below the forest's length is the occurrence with that id, so
/// it is the same number in every owner. The public API lists the members
/// of a sequent as `Member`s; [`Forest`] and [`Reading`] take
/// [`OccId`]s.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(
    feature = "serialize",
    derive(serde::Serialize, serde::Deserialize),
    serde(transparent)
)]
pub struct Member(u32);

impl Member {
    /// Wraps a raw member index.
    pub const fn new(raw: u32) -> Self {
        Self(raw)
    }

    /// Returns the raw member index.
    pub const fn get(self) -> u32 {
        self.0
    }

    /// Returns the index as a `usize`.
    pub const fn index(self) -> usize {
        self.0 as usize
    }

    /// Returns the occurrence this member is, or `None` when it is no
    /// occurrence of `forest`.
    pub fn occurrence(self, forest: &Forest) -> Option<OccId> {
        (self.index() < forest.len()).then_some(OccId(self.0))
    }

    /// Returns the occurrence with this member's number, unchecked: right
    /// for an owner without an instance table, whose members are all
    /// occurrences.
    pub(crate) const fn occ(self) -> OccId {
        OccId(self.0)
    }
}

impl From<OccId> for Member {
    /// The member that is the occurrence.
    fn from(o: OccId) -> Self {
        Self(o.0)
    }
}

const _: () = assert!(size_of::<Member>() == 4);

/// The raw index that stands for "no occurrence" in the forest's arrays.
const NONE: u32 = u32::MAX;

/// Which literal of an atom `a` an occurrence is: `a` itself or its negation
/// `~a`.
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Sign {
    /// The atom `a`, an `Atom` term.
    Atom,
    /// The negation `~a`, a `DualAtom` term.
    Dual,
}

impl Not for Sign {
    type Output = Self;

    /// The other literal of the same atom.
    fn not(self) -> Self {
        match self {
            Sign::Atom => Sign::Dual,
            Sign::Dual => Sign::Atom,
        }
    }
}

/// The polarity of a formula in focused proof search.
///
/// A rule is invertible when its premises are provable whenever its
/// conclusion is. The rules of the negative connectives (`⅋ ⊥ & ⊤ ? ∀`)
/// are invertible, so the search decomposes them at once. Those of the
/// positive connectives (`⊗ 1 ⊕ 0 ! ∃`) are not, so the search decomposes
/// them under focus. The search chooses a literal's polarity per atom, by
/// its [`Bias`](crate::linear::search::Bias).
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Polarity {
    /// `⊗ 1 ⊕ 0 ! ∃`, and the literals the bias makes positive.
    Positive,
    /// `⅋ ⊥ & ⊤ ? ∀`, and the literals the bias makes negative.
    Negative,
}

impl Not for Polarity {
    type Output = Self;

    /// The other polarity.
    fn not(self) -> Self {
        match self {
            Polarity::Positive => Polarity::Negative,
            Polarity::Negative => Polarity::Positive,
        }
    }
}

impl Kind {
    /// Returns the sign of a literal kind, or `None` for a connective.
    pub const fn sign(self) -> Option<Sign> {
        match self {
            Kind::Atom => Some(Sign::Atom),
            Kind::DualAtom => Some(Sign::Dual),
            Kind::One
            | Kind::Bot
            | Kind::Top
            | Kind::Zero
            | Kind::Tensor
            | Kind::Par
            | Kind::With
            | Kind::Plus
            | Kind::Bang
            | Kind::Quest
            | Kind::Forall
            | Kind::Exists => None,
        }
    }

    /// Returns the polarity of a connective, or `None` for a literal, whose
    /// polarity is a per-atom choice. `∃` is positive (its witness is a
    /// choice) and `∀` negative (its eigenvariable is fresh, so the rule
    /// is invertible).
    pub const fn polarity(self) -> Option<Polarity> {
        use Kind::*;
        match self {
            Atom | DualAtom => None,
            Tensor | One | Plus | Zero | Bang | Exists => Some(Polarity::Positive),
            Par | Bot | With | Top | Quest | Forall => Some(Polarity::Negative),
        }
    }
}

/// The subformula occurrences of a sequent, numbered so that every subtree
/// is a contiguous range of ids, with what proof search asks of each
/// occurrence and of each atom.
///
/// The numbering is a depth-first preorder walk: the roots in the order
/// [`Sequent::roots`] lists them, and below a connective its left subterm
/// before its right one. So:
/// - a root comes before everything below it;
/// - the left child of `o` is `o + 1`, and the right child follows the
///   left child's subtree;
/// - the subtree of `o` is exactly the ids `o .. o + size(o)`.
///
/// Two occurrences of one arena term are distinct ids that share a
/// [`TermId`].
///
/// A sequent with cut formulas ([`Sequent::cuts`]) has a tree for each
/// cut formula `A` and one for its dual `A⊥` after the roots' trees, in
/// the same preorder, `A` then `A⊥` per pair. [`roots`](Self::roots) is
/// still the conclusion, and [`ids`](Self::ids) is every occurrence.
/// [`cut_pairs`](Self::cut_pairs), [`dual`](Self::dual) and
/// [`is_conclusion`](Self::is_conclusion) tell the trees apart. The two
/// trees of a pair have one shape, so the occurrence of `A⊥` dual to `x`
/// in `A` is `x + size(A)`.
///
/// A forest owns a copy of its sequent, so it can print an occurrence as a
/// formula. Everything else it holds per occurrence is an array of `u32`
/// or smaller.
///
/// Every accessor that takes an [`OccId`] panics for an id past the
/// forest's end, such as one of another forest. [`Member::occurrence`] and
/// [`len`](Self::len) check an id first.
///
/// # Examples
///
#[cfg_attr(feature = "parse", doc = "```")]
#[cfg_attr(not(feature = "parse"), doc = "```ignore")]
/// use deduxit::linear::{Forest, Kind, Sequent, Sign};
///
/// // ⊢ ~A, A ⊗ ~B, B
/// let sequent: Sequent = "A, A -o B |- B".parse()?;
/// let forest = Forest::new(&sequent)?;
/// assert_eq!(forest.len(), 5);
///
/// let tensor = forest.roots()[1];
/// assert_eq!(forest.kind(tensor), Kind::Tensor);
/// assert_eq!(forest.size(tensor), 3);
/// let (left, right) = (forest.left(tensor).unwrap(), forest.right(tensor).unwrap());
/// assert_eq!(forest.formula(left).to_string(), "A");
/// assert_eq!(forest.formula(right).to_string(), "~B");
/// assert_eq!(forest.parent(right), Some(tensor));
/// assert_eq!(forest.lca(left, right), Some(tensor));
///
/// // Every literal of an atom, by sign, in id order.
/// let a = sequent.atom("A").unwrap();
/// assert_eq!(forest.literals(a, Sign::Atom), [left]);
/// assert_eq!(forest.literals(a, Sign::Dual), [forest.roots()[0]]);
/// # Ok::<(), deduxit::Error>(())
/// ```
#[derive(Clone, Debug)]
pub struct Forest {
    /// The sequent the occurrences are of.
    sequent: Sequent,
    /// The occurrence of each root formula, in the sequent's order.
    roots: Box<[OccId]>,
    /// The occurrence of each cut formula `A`, in the sequent's order;
    /// its dual's tree follows its own, so `A⊥` is at `a + size(a)`.
    cuts: Box<[OccId]>,
    /// Per occurrence, its arena term.
    term: Box<[TermId]>,
    /// Per occurrence, the kind of its term.
    kind: Box<[Kind]>,
    /// Per occurrence, its parent, or `NONE` for a root.
    parent: Box<[u32]>,
    /// Per occurrence, the root it lies below (itself for a root).
    root: Box<[OccId]>,
    /// Per occurrence, the number of occurrences in its subtree, itself
    /// included.
    size: Box<[u32]>,
    /// Per occurrence, the number of ancestors it has.
    depth: Box<[u32]>,
    /// Every literal occurrence, grouped by atom, then by sign (`Atom` first),
    /// in ascending id order within a group.
    literals: Box<[OccId]>,
    /// Where each group of `literals` starts: group `2a` holds the `Atom`
    /// literals of atom `a`, group `2a + 1` its `DualAtom` literals, and the
    /// last entry is the total.
    literal_start: Box<[u32]>,
}

impl Forest {
    /// The most occurrences a forest can hold: the ids are `u32`, and the
    /// last one stands for "no occurrence".
    pub(crate) const MOST: u64 = NONE as u64 - 1;

    /// Returns the bytes the forest's allocations take, the sequent's
    /// included: what a search over it holds besides its own structures.
    pub(crate) fn held_bytes(&self) -> usize {
        let sequent = &self.sequent;
        size_of_val(&*self.roots)
            + size_of_val(&*self.cuts)
            + size_of_val(&*self.term)
            + size_of_val(&*self.kind)
            + size_of_val(&*self.parent)
            + size_of_val(&*self.root)
            + size_of_val(&*self.size)
            + size_of_val(&*self.depth)
            + size_of_val(&*self.literals)
            + size_of_val(&*self.literal_start)
            + sequent.terms.capacity() * size_of::<crate::linear::sequents::Term>()
            + sequent.roots.capacity() * size_of::<TermId>()
            + sequent
                .atoms
                .iter()
                .map(|name| size_of::<String>() + name.capacity())
                .sum::<usize>()
    }

    /// Builds the forest of a sequent within the default
    /// [`Limits::occurrences`], keeping a copy of the sequent.
    ///
    /// A forest takes about 25 bytes per occurrence. An arena that shares
    /// its subterms can unfold to exponentially more occurrences than it
    /// has terms, so a sequent of a few hundred bytes can ask for
    /// gigabytes. The bound refuses such a sequent before anything of that
    /// size is built.
    ///
    /// # Errors
    ///
    /// [`Refusal::Occurrences`] past the bound, and [`Refusal::Index`] for
    /// more occurrences than a forest indexes (2³² − 2), whatever the
    /// bound.
    pub fn new(sequent: &Sequent) -> Result<Self, Error> {
        Self::within(sequent, &Limits::default())
    }

    /// Builds the forest of a sequent of at most `limits.occurrences`
    /// subformula occurrences ([`Sequent::occurrences`] counts them),
    /// keeping a copy of the sequent, as [`new`](Self::new) does.
    ///
    /// # Errors
    ///
    /// As [`new`](Self::new)'s, under `limits`.
    pub fn within(sequent: &Sequent, limits: &Limits) -> Result<Self, Error> {
        let sizes = Self::measure(sequent, limits)?;
        Ok(Self::build(sequent.clone(), &sizes))
    }

    /// Builds the forest of a sequent as [`within`](Self::within) does,
    /// taking the sequent instead of copying it, which saves memory on a
    /// sequent of millions of terms.
    ///
    /// # Errors
    ///
    /// As [`within`](Self::within)'s.
    pub fn from_owned(sequent: Sequent, limits: &Limits) -> Result<Self, Error> {
        let sizes = Self::measure(&sequent, limits)?;
        Ok(Self::build(sequent, &sizes))
    }

    /// Returns the number of occurrences below every arena term of a
    /// sequent, the term's own included, or the refusal when the sequent
    /// has more occurrences than the limits or a forest allow.
    fn measure(sequent: &Sequent, limits: &Limits) -> Result<Vec<u64>, Error> {
        let sizes = sequent.sizes();
        let occurrences = sequent.occurrences_of(&sizes);
        if let Some(limit) = limits.occurrences
            && occurrences > limit
        {
            return Err(Error::Refused(Refusal::Occurrences { occurrences, limit }));
        }
        if occurrences > Self::MOST {
            return Err(Error::Refused(Refusal::Index {
                what: Space::Occurrence,
                count: occurrences,
                most: Self::MOST,
            }));
        }
        Ok(sizes)
    }

    /// Returns the sequent the forest was built from.
    pub fn sequent(&self) -> &Sequent {
        &self.sequent
    }

    /// Returns the number of occurrences, which is the width of an
    /// occurrence set of this forest.
    pub fn len(&self) -> usize {
        self.term.len()
    }

    /// Returns whether the forest has no occurrence: the sequent has no
    /// formula and no cut formula.
    pub fn is_empty(&self) -> bool {
        self.term.is_empty()
    }

    /// Returns every occurrence id in ascending order.
    pub fn ids(&self) -> impl DoubleEndedIterator<Item = OccId> + ExactSizeIterator {
        (0..self.term.len() as u32).map(OccId::new)
    }

    /// Returns the roots as members, in the order the sequent lists them.
    #[cfg(any(feature = "latex", feature = "typst", feature = "svg"))]
    pub(crate) fn root_members(&self) -> Vec<Member> {
        self.roots().iter().copied().map(Member::from).collect()
    }

    /// Returns the occurrence of each root formula, in the order the sequent
    /// lists them.
    pub fn roots(&self) -> &[OccId] {
        &self.roots
    }

    /// Returns the cut pairs, in the order the sequent lists its cut
    /// formulas ([`Sequent::cuts`]): per pair the root occurrence of the
    /// formula `A` and that of its dual `A⊥`, numbered after the roots'
    /// trees, `A` then `A⊥`. Empty for a sequent without cuts.
    pub fn cut_pairs(&self) -> impl ExactSizeIterator<Item = (OccId, OccId)> + '_ {
        self.cuts
            .iter()
            .map(|&a| (a, OccId::new(a.get() + self.size(a))))
    }

    /// Returns whether any occurrence, cut formulas included, is a
    /// quantifier, `∀` or `∃`.
    pub fn has_binders(&self) -> bool {
        self.kind.iter().any(|k| k.is_binder())
    }

    /// Returns whether the sequent has cut formulas.
    pub fn has_cuts(&self) -> bool {
        !self.cuts.is_empty()
    }

    /// Returns whether an occurrence lies in a formula of the conclusion
    /// (below a root), not in a cut formula or its dual.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    pub fn is_conclusion(&self, o: OccId) -> bool {
        self.cuts.first().is_none_or(|&first| self.root(o) < first)
    }

    /// Returns the occurrence dual to `o` across a cut pair: for an
    /// occurrence of a cut formula `A`, the one at the same place in `A⊥`,
    /// and the other way round. Returns `None` for an occurrence of the
    /// conclusion.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    pub fn dual(&self, o: OccId) -> Option<OccId> {
        let root = self.root(o);
        // `cuts` ascends and holds only the `A` roots, so the last entry
        // at or before `root` is the pair's `A`, if `root` is in a pair.
        let at = self.cuts.partition_point(|&a| a <= root).checked_sub(1)?;
        let a = self.cuts[at];
        let size = self.size(a);
        if root == a {
            Some(OccId::new(o.get() + size))
        } else if root.get() == a.get() + size {
            Some(OccId::new(o.get() - size))
        } else {
            None
        }
    }

    /// Returns whether `o` lies in a cut formula `A`, not in its dual.
    /// A [`Node::Cut`](crate::linear::Node::Cut) names its cut there.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    pub fn is_cut_formula(&self, o: OccId) -> bool {
        self.dual(o).is_some_and(|d| o < d)
    }

    /// Returns whether `goal` is the roots in any order, that is the
    /// sequent itself.
    pub(crate) fn is_roots(&self, goal: &[OccId]) -> bool {
        if goal.len() != self.roots.len() {
            return false;
        }
        if *goal == *self.roots {
            return true;
        }
        let mut sorted = goal.to_vec();
        sorted.sort_unstable();
        let mut roots = self.roots.to_vec();
        roots.sort_unstable();
        sorted == roots
    }

    /// Returns the arena term of an occurrence.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    pub fn term(&self, o: OccId) -> TermId {
        self.term[o.index()]
    }

    /// Returns the kind of an occurrence's term.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    pub fn kind(&self, o: OccId) -> Kind {
        self.kind[o.index()]
    }

    /// Returns the occurrence as a value that prints its formula.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    pub fn formula(&self, o: OccId) -> Formula<'_> {
        self.sequent.formula(self.term(o))
    }

    /// Returns the parent of an occurrence, or `None` for a root.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    pub fn parent(&self, o: OccId) -> Option<OccId> {
        match self.parent[o.index()] {
            NONE => None,
            p => Some(OccId::new(p)),
        }
    }

    /// Returns the root formula an occurrence lies below, or itself if it is
    /// a root.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    pub fn root(&self, o: OccId) -> OccId {
        self.root[o.index()]
    }

    /// Returns whether two occurrences lie below the same root formula.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    pub fn same_root(&self, x: OccId, y: OccId) -> bool {
        self.root(x) == self.root(y)
    }

    /// Returns the number of occurrences in the subtree of `o`, itself
    /// included.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    pub fn size(&self, o: OccId) -> u32 {
        self.size[o.index()]
    }

    /// Returns the number of ancestors of an occurrence: 0 for a root.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    pub fn depth(&self, o: OccId) -> u32 {
        self.depth[o.index()]
    }

    /// Returns whether the occurrence is a literal, `a` or `~a`.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    pub fn is_literal(&self, o: OccId) -> bool {
        self.kind(o).is_literal()
    }

    /// Returns the atom of a literal occurrence, or `None` for a connective.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    pub fn atom(&self, o: OccId) -> Option<Atom> {
        self.sequent.term(self.term(o)).atom()
    }

    /// Returns the sign of a literal occurrence, or `None` for a connective.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    pub fn sign(&self, o: OccId) -> Option<Sign> {
        self.kind(o).sign()
    }

    /// Returns whether `x` and `y` are an atom and its negation, the two
    /// literals an axiom pairs. Every test of axiom partners asks this
    /// function, so what pairs two literals changes here alone.
    pub(crate) fn dual_literals(&self, x: OccId, y: OccId) -> bool {
        self.is_literal(x) && self.atom(x) == self.atom(y) && self.sign(x) != self.sign(y)
    }

    /// Returns the first child: the only subformula of `!` and `?`, the left
    /// one of a binary connective, and `None` for a literal or a unit.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    pub fn left(&self, o: OccId) -> Option<OccId> {
        (self.kind(o).arity() >= 1).then(|| OccId::new(o.0 + 1))
    }

    /// Returns the right child of a binary connective, and `None` otherwise.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    pub fn right(&self, o: OccId) -> Option<OccId> {
        (self.kind(o).arity() == 2).then(|| {
            let left = o.0 + 1;
            OccId::new(left + self.size[left as usize])
        })
    }

    /// Returns the children of an occurrence in order, left before right.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    pub fn children(&self, o: OccId) -> impl Iterator<Item = OccId> {
        self.left(o).into_iter().chain(self.right(o))
    }

    /// Returns the subtree of `o` in preorder: `o` itself first, then every
    /// occurrence below it, which are the ids `o .. o + size(o)`.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    pub fn subtree(&self, o: OccId) -> impl DoubleEndedIterator<Item = OccId> + ExactSizeIterator {
        (o.0..o.0 + self.size(o)).map(OccId::new)
    }

    /// Returns whether `o` is `ancestor` itself or lies below it.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    pub fn is_below(&self, o: OccId, ancestor: OccId) -> bool {
        ancestor.0 <= o.0 && o.0 < ancestor.0 + self.size(ancestor)
    }

    /// Returns the lowest common ancestor of two occurrences, or `None` if
    /// they lie below different roots. Walks up from `x`, so it costs the
    /// depth of `x` at most.
    ///
    /// # Panics
    ///
    /// For an id of another forest, past this one's end.
    #[inline]
    pub fn lca(&self, x: OccId, y: OccId) -> Option<OccId> {
        if !self.same_root(x, y) {
            return None;
        }
        let mut a = x;
        while !self.is_below(y, a) {
            a = self.parent(a)?;
        }
        Some(a)
    }

    /// Returns the occurrences of one literal of an atom, `a` or `~a`, in
    /// ascending id order: the candidate axiom partners of a literal of
    /// the other sign.
    pub fn literals(&self, atom: Atom, sign: Sign) -> &[OccId] {
        let group = Self::list(atom, sign);
        let (start, end) = (self.literal_start[group], self.literal_start[group + 1]);
        &self.literals[start as usize..end as usize]
    }

    /// Returns the number of the list of the literals of `atom` with
    /// `sign`, in `0..lists()`: the atom's two lists side by side, `a`
    /// before `~a`.
    pub(crate) const fn list(atom: Atom, sign: Sign) -> usize {
        2 * atom.index() + sign as usize
    }

    /// Returns how many lists of literals the forest has: two per atom.
    pub(crate) fn lists(&self) -> usize {
        2 * self.sequent.atom_names().len()
    }

    /// Returns every literal occurrence, grouped by atom, `a` before `~a`
    /// within an atom, and in ascending id order within a group.
    pub fn all_literals(&self) -> &[OccId] {
        &self.literals
    }
}

impl Forest {
    /// Builds the forest of a sequent from the number of occurrences below
    /// each of its arena terms, the term's own included. The sizes must
    /// add up to no more than a forest can hold.
    fn build(sequent: Sequent, term_size: &[u64]) -> Self {
        let terms = sequent.terms();
        let n = sequent.occurrences_of(term_size) as usize;

        let mut roots = Vec::with_capacity(sequent.roots().len());
        let mut cuts = Vec::with_capacity(sequent.cuts().len());
        let mut term = Vec::with_capacity(n);
        let mut kind = Vec::with_capacity(n);
        let mut parent = Vec::with_capacity(n);
        let mut root = Vec::with_capacity(n);
        let mut size = Vec::with_capacity(n);
        let mut depth = Vec::with_capacity(n);

        // Preorder: the right child is pushed first so the left one is
        // visited, with its whole subtree, before it.
        let mut stack: Vec<(TermId, u32, u32)> = Vec::new();
        let conclusion = sequent.roots().len();
        let trees = sequent
            .roots()
            .iter()
            .chain(sequent.cuts().iter().flatten());
        for (i, &r) in trees.enumerate() {
            let root_id = OccId::new(term.len() as u32);
            if i < conclusion {
                roots.push(root_id);
            } else if (i - conclusion).is_multiple_of(2) {
                cuts.push(root_id);
            }
            stack.push((r, NONE, 0));
            while let Some((t, p, d)) = stack.pop() {
                let o = term.len() as u32;
                let node = terms[t.index()];
                term.push(t);
                kind.push(node.kind());
                parent.push(p);
                root.push(root_id);
                size.push(term_size[t.index()] as u32);
                depth.push(d);
                let subterms: Vec<TermId> = node.subterms().collect();
                for &k in subterms.iter().rev() {
                    stack.push((k, o, d + 1));
                }
            }
        }
        debug_assert_eq!(term.len(), n);

        // Literals: count per atom and sign, then lay the groups out by a
        // counting sort.
        let num_atoms = sequent.atom_names().len();
        let mut literal_start = vec![0u32; 2 * num_atoms + 1];
        for (o, k) in kind.iter().enumerate() {
            if let Some(s) = k.sign() {
                let a = terms[term[o].index()].atom().unwrap();
                literal_start[Self::list(a, s) + 1] += 1;
            }
        }
        for g in 1..literal_start.len() {
            literal_start[g] += literal_start[g - 1];
        }
        let mut next = literal_start.clone();
        let mut literals = vec![OccId::new(NONE); literal_start[2 * num_atoms] as usize];
        for (o, k) in kind.iter().enumerate() {
            if let Some(s) = k.sign() {
                let a = terms[term[o].index()].atom().unwrap();
                let group = Self::list(a, s);
                literals[next[group] as usize] = OccId::new(o as u32);
                next[group] += 1;
            }
        }

        Self {
            sequent,
            roots: roots.into_boxed_slice(),
            cuts: cuts.into_boxed_slice(),
            term: term.into_boxed_slice(),
            kind: kind.into_boxed_slice(),
            parent: parent.into_boxed_slice(),
            root: root.into_boxed_slice(),
            size: size.into_boxed_slice(),
            depth: depth.into_boxed_slice(),
            literals: literals.into_boxed_slice(),
            literal_start: literal_start.into_boxed_slice(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::linear::sequents::Term;

    /// Wraps a raw id.
    const fn o(id: u32) -> OccId {
        OccId::new(id)
    }

    /// Builds the forest of `input`, or panics with the parse error.
    #[cfg(feature = "parse")]
    fn forest(input: &str) -> Forest {
        let s: Sequent = input.parse().unwrap_or_else(|e| panic!("{input:?}: {e}"));
        Forest::new(&s).unwrap()
    }

    /// Checks the invariants that hold in every forest: preorder ranges,
    /// parents against children, depths, roots, sizes, and the literal
    /// tables against the occurrences.
    fn check_invariants(f: &Forest) {
        let n = f.len() as u32;
        assert_eq!(f.ids().count(), n as usize);
        assert_eq!(
            f.roots().iter().map(|&r| f.size(r)).sum::<u32>(),
            n,
            "the roots' subtrees partition the ids"
        );
        for (i, &r) in f.roots().iter().enumerate() {
            let expected = f.roots()[..i].iter().map(|&q| f.size(q)).sum::<u32>();
            assert_eq!(r, o(expected), "root {i} starts after the roots before it");
            assert_eq!(f.parent(r), None);
            assert_eq!(f.depth(r), 0);
            assert_eq!(f.root(r), r);
            assert_eq!(f.term(r), f.sequent().roots()[i]);
        }
        for x in f.ids() {
            let node = f.sequent().term(f.term(x));
            assert_eq!(f.kind(x), node.kind());
            let children: Vec<OccId> = f.children(x).collect();
            assert_eq!(children.len(), node.kind().arity() as usize);
            assert_eq!(children.first().copied(), f.left(x));
            assert_eq!(children.get(1).copied(), f.right(x));
            let subterms: Vec<TermId> = node.subterms().collect();
            for (&c, &t) in children.iter().zip(&subterms) {
                assert_eq!(f.parent(c), Some(x), "the child's parent is the node");
                assert_eq!(f.depth(c), f.depth(x) + 1);
                assert_eq!(f.root(c), f.root(x));
                assert_eq!(f.term(c), t, "children come in the term's order");
                assert!(f.is_below(c, x));
            }
            assert_eq!(
                f.size(x),
                1 + children.iter().map(|&c| f.size(c)).sum::<u32>()
            );
            if let Some(l) = f.left(x) {
                assert_eq!(l, o(x.get() + 1), "the left child follows its parent");
            }
            if let (Some(l), Some(r)) = (f.left(x), f.right(x)) {
                assert_eq!(
                    r,
                    o(l.get() + f.size(l)),
                    "the right child follows the left subtree"
                );
            }
            // Every id in the range descends from x through parents, and no
            // id outside does.
            for y in f.ids() {
                let mut a = Some(y);
                while let Some(b) = a
                    && b != x
                {
                    a = f.parent(b);
                }
                assert_eq!(a == Some(x), f.is_below(y, x), "{y:?} below {x:?}");
                assert_eq!(f.subtree(x).any(|z| z == y), f.is_below(y, x));
            }
            match f.parent(x) {
                Some(p) => assert_eq!(f.depth(x), f.depth(p) + 1),
                None => assert!(f.roots().contains(&x)),
            }
            // Atom and sign agree with the term.
            assert_eq!(f.atom(x), node.atom());
            assert_eq!(f.sign(x), node.kind().sign());
            assert_eq!(f.is_literal(x), node.kind().is_literal());
        }
        // The literal tables list exactly the literal occurrences, sorted.
        let mut all: Vec<OccId> = Vec::new();
        for a in 0..f.sequent().atom_names().len() {
            let atom = Atom::new(a as u32);
            for sign in [Sign::Atom, Sign::Dual] {
                let list = f.literals(atom, sign);
                assert!(list.windows(2).all(|w| w[0] < w[1]), "sorted");
                for &l in list {
                    assert_eq!(f.atom(l), Some(atom));
                    assert_eq!(f.sign(l), Some(sign));
                }
                all.extend_from_slice(list);
            }
        }
        assert_eq!(all, f.all_literals());
        let mut literal_ids: Vec<OccId> = f.ids().filter(|&x| f.is_literal(x)).collect();
        all.sort();
        literal_ids.sort();
        assert_eq!(all, literal_ids);
    }

    /// The forest of the empty sequent has nothing in it.
    #[test]
    fn empty() {
        let f = Forest::new(&Sequent::new()).unwrap();
        assert!(f.is_empty());
        assert_eq!(f.len(), 0);
        assert_eq!(f.roots(), []);
        assert_eq!(f.all_literals(), []);
        check_invariants(&f);
    }

    /// The numbering of `⊢ ~A, A ⊗ ~B, B` is preorder with the left subterm
    /// first, and the queries return what the layout says.
    #[cfg(feature = "parse")]
    #[test]
    fn layout() {
        let f = forest("A, A -o B |- B");
        check_invariants(&f);
        assert_eq!(f.len(), 5);
        assert_eq!(f.roots(), [o(0), o(1), o(4)]);
        let kinds: Vec<Kind> = f.ids().map(|x| f.kind(x)).collect();
        use Kind::*;
        assert_eq!(kinds, [DualAtom, Tensor, Atom, DualAtom, Atom]);
        assert_eq!(f.formula(o(1)).to_string(), "A ⊗ ~B");
        assert_eq!(f.left(o(1)), Some(o(2)));
        assert_eq!(f.right(o(1)), Some(o(3)));
        assert_eq!(f.subtree(o(1)).collect::<Vec<_>>(), [o(1), o(2), o(3)]);
        assert_eq!(f.size(o(1)), 3);
        assert_eq!(f.depth(o(3)), 1);
        assert_eq!(f.root(o(3)), o(1));
        assert!(f.same_root(o(2), o(3)));
        assert!(!f.same_root(o(0), o(2)));
    }

    /// Nested and repeated formulas keep every invariant, including shared
    /// subterms and repeated roots.
    #[cfg(feature = "parse")]
    #[test]
    fn invariants_on_a_table() {
        for input in [
            "|- A",
            "|- A, A",
            "|- A * A",
            "|- (A * B), (A * B)",
            "|- !(A & B) + ?(A * B), 1, bot, top, 0",
            "A -o B -o C, (A -o B) -o C |- (A * B) + (0 & top)",
            "!A, ?B, A * B, C par D |- ~A, B^, A & B, C + D",
            "|- ((A * B) * (A * B)) * ((A * B) * (A * B))",
        ] {
            check_invariants(&forest(input));
        }
    }

    /// The lowest common ancestor is the deepest node above both, and
    /// nothing across roots.
    #[cfg(feature = "parse")]
    #[test]
    fn lowest_common_ancestor() {
        // ⊢ (A ⊗ B) ⅋ (C ⊗ D), E
        let f = forest("|- (A * B) par (C * D), E");
        check_invariants(&f);
        assert_eq!(f.lca(o(2), o(3)), Some(o(1)));
        assert_eq!(f.lca(o(2), o(5)), Some(o(0)));
        assert_eq!(f.lca(o(3), o(6)), Some(o(0)));
        assert_eq!(f.lca(o(1), o(4)), Some(o(0)));
        assert_eq!(f.lca(o(0), o(6)), Some(o(0)));
        assert_eq!(f.lca(o(6), o(0)), Some(o(0)));
        assert_eq!(f.lca(o(5), o(5)), Some(o(5)));
        assert_eq!(f.lca(o(2), o(7)), None);
        assert_eq!(f.lca(o(7), o(7)), Some(o(7)));
    }

    /// Every literal occurrence is listed once, by atom and sign.
    #[cfg(feature = "parse")]
    #[test]
    fn literals() {
        // ⊢ ~A, ~A, A, B, ~C ⅋ C, ~C ⅋ C
        let f = forest("A, A |- A, B, C -o C, C -o C");
        check_invariants(&f);
        let s = f.sequent();
        let (a, b, c) = (
            s.atom("A").unwrap(),
            s.atom("B").unwrap(),
            s.atom("C").unwrap(),
        );
        assert_eq!(f.literals(a, Sign::Atom), [o(2)]);
        assert_eq!(f.literals(a, Sign::Dual), [o(0), o(1)]);
        assert_eq!(f.literals(b, Sign::Atom), [o(3)]);
        assert_eq!(f.literals(b, Sign::Dual), []);
        assert_eq!(f.literals(c, Sign::Atom), [o(6), o(9)]);
        assert_eq!(f.literals(c, Sign::Dual), [o(5), o(8)]);
    }

    /// Connectives have their fixed polarities.
    #[cfg(feature = "parse")]
    #[test]
    fn connective_polarities() {
        let f = forest("|- (A * B) par (A & B) + (!A par ?B), 1, bot, top, 0");
        check_invariants(&f);
        let by_kind = |k: Kind| {
            f.ids()
                .filter(|&x| f.kind(x) == k)
                .map(|x| f.kind(x).polarity().unwrap())
                .collect::<Vec<_>>()
        };
        use Kind::*;
        use Polarity::*;
        for (k, p) in [
            (Tensor, Positive),
            (Plus, Positive),
            (One, Positive),
            (Zero, Positive),
            (Bang, Positive),
            (Par, Negative),
            (With, Negative),
            (Bot, Negative),
            (Top, Negative),
            (Quest, Negative),
        ] {
            assert!(!by_kind(k).is_empty(), "{k:?} occurs");
            assert!(by_kind(k).iter().all(|&q| q == p), "{k:?} is {p:?}");
        }
    }

    /// A shared subterm is walked once per occurrence, and a deeply shared
    /// arena is refused rather than mis-numbered.
    #[test]
    fn sharing() {
        // Atom(0) shared by two roots and inside a tensor of itself.
        let s = Sequent {
            terms: vec![
                Term::Atom(Atom::new(0)),
                Term::Tensor(TermId::new(0), TermId::new(0)),
            ],
            roots: vec![TermId::new(1), TermId::new(0), TermId::new(1)],
            atoms: vec!["A".into()],
            antecedents: None,
            cuts: vec![],
            fo: Default::default(),
        };
        let f = Forest::new(&s).unwrap();
        check_invariants(&f);
        assert_eq!(f.len(), 7);
        assert_eq!(f.roots(), [o(0), o(3), o(4)]);
        assert_eq!(
            f.literals(Atom::new(0), Sign::Atom),
            [o(1), o(2), o(3), o(5), o(6)]
        );

        // A limit admits a sequent of exactly that many occurrences.
        assert_eq!(s.occurrences(), 7);
        let limit = |n| Limits::default().with_occurrences(n);
        assert_eq!(Forest::within(&s, &limit(Some(7))).unwrap().len(), 7);
        assert!(matches!(
            Forest::within(&s, &limit(Some(6))),
            Err(Error::Refused(Refusal::Occurrences {
                occurrences: 7,
                limit: 6
            }))
        ));

        // No limit admits more occurrences than a `u32` numbers.
        let s = doubling(40);
        assert_eq!(s.occurrences(), (1 << 41) - 1);
        assert!(matches!(
            Forest::within(&s, &limit(None)),
            Err(Error::Refused(Refusal::Index { what: Space::Occurrence, count, most }))
                if count == (1 << 41) - 1 && most == (1 << 32) - 2
        ));
        assert_eq!(doubling(100).occurrences(), u64::MAX, "the count saturates");
    }

    /// Returns `⊢ 1` under `levels` tensors, each of the term below with
    /// itself: `levels + 1` terms that unfold to `2^(levels + 1) − 1`
    /// occurrences.
    fn doubling(levels: u32) -> Sequent {
        let mut terms = vec![Term::One];
        for k in 0..levels {
            terms.push(Term::Tensor(TermId::new(k), TermId::new(k)));
        }
        Sequent {
            terms,
            roots: vec![TermId::new(levels)],
            atoms: vec![],
            antecedents: None,
            cuts: vec![],
            fo: Default::default(),
        }
    }

    /// A small arena that unfolds past the default limit is refused before
    /// anything of the unfolding's size is built, borrowed or owned: the
    /// forest of this one would take gigabytes and seconds.
    #[test]
    fn refuses_an_unfolding_past_the_default_limit() {
        let s = doubling(26);
        let refused = |result: Result<Forest, Error>| {
            matches!(
                result,
                Err(Error::Refused(crate::limits::Refusal::Occurrences { occurrences, limit }))
                    if occurrences == (1 << 27) - 1 && limit == Limits::DEFAULT_OCCURRENCES
            )
        };
        let start = std::time::Instant::now();
        assert!(refused(Forest::new(&s)));
        assert!(refused(Forest::from_owned(s, &Limits::default())));
        assert!(start.elapsed() < std::time::Duration::from_secs(1));
    }
}