deduxit 0.3.0

Logic suites, linear logic first: decides, checks, proves step by step and exports sequents of classical and intuitionistic linear logic, and ordinary propositional logic through its embeddings.
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
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! Proofs: terms over occurrence ids, the checker that validates a term
//! against its sequent independently of any engine, and the derivation view
//! for humans and exporters.
//!
//! A [`Proof`] is an arena of [`Node`]s, one per rule instance, over the
//! [`Forest`] of the sequent it proves. A node names the rule, the
//! occurrence the rule acts on and the nodes that prove its premises. The
//! rules are those of the dyadic sequent calculus every engine searches in:
//! the standard rules, with the `?` formulas handled through an unrestricted
//! zone `Θ` (a `?` step moves a formula into it, a copy uses it without
//! consuming it), plus weakening for affine mode and Mix. A node does not
//! record the sequent it proves: the checker derives that from the premises,
//! and the derivation view shows it.

pub mod check;
pub mod cut;
pub mod derivation;
/// First-order proofs written by hand, and their tests.
#[cfg(all(test, feature = "parse"))]
mod first_order;
/// Text rendering of derivations.
pub(crate) mod fmt;
#[cfg(feature = "interactive")]
pub mod interactive;
/// Multisets of occurrence ids.
mod multiset;
/// The checker's first implementation, which the tests compare it with.
#[cfg(all(test, feature = "parse"))]
mod oracle;
/// The rules of the standard calculus, one-sided and named two-sided.
mod rule;
pub mod size;
pub mod style;

use crate::linear::occurrences::{Instances, instances};
pub use check::{CheckError, Dyadic, Fault, Invalid, Refused};
pub use derivation::{
    ClassicalRule, ClassicalSides, Compact, Derivation, InfId, Inference, Sides, Structural,
    TwoSided, ViewOptions,
};
pub use fmt::TextOptions;
#[cfg(feature = "interactive")]
pub use interactive::{CutFormula, GoalId, Interactive, Step, StepError};
pub use rule::{Division, Named, Rule};
pub use size::Size;
pub use style::{Labels, OpenGoal};

use crate::Error;
use crate::limits::{Limits, Progress};
use crate::linear::fragment::Mode;
use crate::linear::occurrences::{Forest, Member, OccId, Reading};
use crate::linear::sequents::{Eigen, FoTermId, Sequent};
use std::fmt::{Display, Formatter, Result as FmtResult};

/// A number of bytes, written in the largest binary unit that divides it:
/// `1 GiB`, `512 MiB`, `1500 B`.
pub(crate) struct Bytes(pub(crate) u64);

impl std::fmt::Display for Bytes {
    /// Writes the number with its unit.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let units = [(30, "GiB"), (20, "MiB"), (10, "KiB")];
        match units
            .into_iter()
            .find(|&(shift, _)| self.0 != 0 && self.0.is_multiple_of(1 << shift))
        {
            Some((shift, unit)) => write!(f, "{} {unit}", self.0 >> shift),
            None => write!(f, "{} B", self.0),
        }
    }
}

/// The index of a node in a proof's arena.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct NodeId(u32);

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

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

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

/// Which subformula of a binary connective a rule picks.
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Branch {
    /// The left subformula.
    Left,
    /// The right subformula.
    Right,
}

/// One rule instance of a proof: the rule, the member it acts on, and the
/// nodes that prove its premises, which precede it in the arena. The rules
/// are the dyadic calculus's, so `⊢ Θ ; Γ` below is a sequent with the
/// unrestricted zone `Θ` and the linear zone `Γ`; `Θ` is empty until a
/// [`Quest`](Self::Quest) fills it.
///
/// The type is closed: a new rule is a new release of the calculus, with
/// its tag, its checker's arm, its rule of the derivation view and its
/// constructor wherever the type is mirrored ([`NAMES`](Self::NAMES)).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Node {
    /// The axiom `⊢ Θ ; a, ~a` on two literal occurrences of one atom with
    /// opposite signs, in either order.
    Ax(Member, Member),
    /// `⊢ Θ ; Γ, Δ, A ⊗ B` from `⊢ Θ ; Γ, A` and `⊢ Θ ; Δ, B`, on the
    /// occurrence of `A ⊗ B`; the premises prove its left and right
    /// subformula, in that order.
    Tensor(Member, NodeId, NodeId),
    /// `⊢ Θ ; Γ, A ⅋ B` from `⊢ Θ ; Γ, A, B`.
    Par(Member, NodeId),
    /// `⊢ Θ ; 1`.
    One(Member),
    /// `⊢ Θ ; Γ, ⊥` from `⊢ Θ ; Γ`.
    Bot(Member, NodeId),
    /// `⊢ Θ ; Γ, A & B` from `⊢ Θ ; Γ, A` and `⊢ Θ ; Γ, B`, the premises in
    /// that order.
    With(Member, NodeId, NodeId),
    /// `⊢ Θ ; Γ, A ⊕ B` from `⊢ Θ ; Γ, A` or from `⊢ Θ ; Γ, B`, as the side
    /// says.
    Plus(Member, Branch, NodeId),
    /// `⊢ Θ ; Γ, ⊤` for any `Γ`.
    Top(Member),
    /// Promotion: `⊢ Θ ; !A` from `⊢ Θ ; A`, with an empty linear zone.
    Bang(Member, NodeId),
    /// `⊢ Θ ; Γ, ?A` from `⊢ Θ, A ; Γ`: the subformula moves into the
    /// unrestricted zone.
    Quest(Member, NodeId),
    /// A copy: `⊢ Θ, A ; Γ` from `⊢ Θ, A ; Γ, A`, on the occurrence of `A`,
    /// which stays in `Θ`. The only rule that can repeat an occurrence in a
    /// branch, which is why the linear zone is a multiset.
    Copy(Member, NodeId),
    /// Weakening: `⊢ Θ ; Γ, A` from `⊢ Θ ; Γ`, in affine mode, or in any
    /// mode when `A` is a `?` formula (the standard `?w`; the dyadic form of
    /// it is a [`Quest`](Self::Quest) whose formula goes unused).
    Weaken(Member, NodeId),
    /// Mix, when the mode allows it: `⊢ Θ ; Γ, Δ` from `⊢ Θ ; Γ` and
    /// `⊢ Θ ; Δ`.
    Mix(NodeId, NodeId),
    /// The cut `⊢ Θ ; Γ, Δ` from `⊢ Θ ; Γ, A` and `⊢ Θ ; Δ, A⊥`, on an
    /// occurrence of a cut formula `A` of the sequent
    /// ([`Sequent::cuts`](crate::linear::Sequent::cuts)), whose dual in `A⊥`
    /// ([`Forest::dual`](crate::linear::Forest::dual)) the second premise
    /// consumes. Refused in an ordered mode. Intuitionistically `Γ ⊢ A`
    /// and `Δ, A ⊢ C` give `Γ, Δ ⊢ C`, whichever premise has the cut
    /// formula in output position.
    Cut(Member, NodeId, NodeId),
    /// `⊢ Θ ; Γ, ∀x.A` from `⊢ Θ ; Γ, A[a/x]`, on the occurrence of
    /// `∀x.A`, with the eigenvariable `a`, which the proof's instance
    /// table ([`Instances`]) names: `a` must occur
    /// nowhere in the conclusion, which the checker sees to by a
    /// condition on the whole proof (every eigenvariable introduced by
    /// one such node, and found in witnesses above it alone). The premise
    /// consumes the body's instance under the frame of `∀x.A` with `a`
    /// added.
    Forall(Member, Eigen, NodeId),
    /// `⊢ Θ ; Γ, ∃x.A` from `⊢ Θ ; Γ, A[t/x]`, on the occurrence of
    /// `∃x.A`, with the witness `t`, a closed term of the sequent's arena
    /// or of the proof's extension of it. The premise consumes the body's
    /// instance under the frame of `∃x.A` with `t` added.
    Exists(Member, FoTermId, NodeId),
}

/// A node is a tag, an occurrence and two node indices at most.
const _: () = assert!(size_of::<Node>() == 16);

/// How many nodes [`Proof::build`] passes over between two polls of its
/// stop: some tenths of a millisecond.
const BUILD_POLL: usize = 1 << 16;

impl Node {
    /// The variants' names, in their order: what a mirror of the type in
    /// another language matches, one constructor each.
    pub const NAMES: &'static [&'static str] = &[
        "Ax", "Tensor", "Par", "One", "Bot", "With", "Plus", "Top", "Bang", "Quest", "Copy",
        "Weaken", "Mix", "Cut", "Forall", "Exists",
    ];

    /// The rules' tags in a proof's JSON form and their names
    /// ([`name`](Self::name)): one per variant, and two for `Plus`, whose
    /// branch is in its tag.
    pub const TAGS: &'static [&'static str] = &[
        "ax", "⊗", "⅋", "1", "⊥", "&", "⊕₁", "⊕₂", "⊤", "!", "?", "copy", "wk", "mix", "cut", "∀",
        "∃",
    ];

    /// Returns the member the rule acts on: `None` for Mix and the cut,
    /// and the first literal of an axiom.
    pub const fn principal(self) -> Option<Member> {
        use Node::*;
        match self {
            Ax(o, _)
            | Tensor(o, ..)
            | Par(o, _)
            | One(o)
            | Bot(o, _)
            | With(o, ..)
            | Plus(o, ..)
            | Top(o)
            | Bang(o, _)
            | Quest(o, _)
            | Copy(o, _)
            | Weaken(o, _)
            | Forall(o, ..)
            | Exists(o, ..) => Some(o),
            Mix(..) | Cut(..) => None,
        }
    }

    /// Returns the members the node names: one, or two for an axiom, or
    /// none for Mix; the cut names its cut formula's occurrence.
    pub fn members(self) -> impl Iterator<Item = Member> {
        use Node::*;
        let second = match self {
            Ax(_, b) | Cut(b, ..) => Some(b),
            Tensor(..) | Par(..) | One(_) | Bot(..) | With(..) | Plus(..) | Top(_) | Bang(..)
            | Quest(..) | Copy(..) | Weaken(..) | Mix(..) | Forall(..) | Exists(..) => None,
        };
        self.principal().into_iter().chain(second)
    }

    /// Returns the node with every member it names renamed, or the first
    /// error the renaming gives.
    pub(crate) fn renamed<E>(
        self,
        rename: impl Fn(Member) -> Result<Member, E>,
    ) -> Result<Self, E> {
        use Node::*;
        Ok(match self {
            Ax(a, b) => Ax(rename(a)?, rename(b)?),
            Tensor(o, l, r) => Tensor(rename(o)?, l, r),
            Par(o, p) => Par(rename(o)?, p),
            One(o) => One(rename(o)?),
            Bot(o, p) => Bot(rename(o)?, p),
            With(o, l, r) => With(rename(o)?, l, r),
            Plus(o, b, p) => Plus(rename(o)?, b, p),
            Top(o) => Top(rename(o)?),
            Bang(o, p) => Bang(rename(o)?, p),
            Quest(o, p) => Quest(rename(o)?, p),
            Copy(o, p) => Copy(rename(o)?, p),
            Weaken(o, p) => Weaken(rename(o)?, p),
            Mix(l, r) => Mix(l, r),
            Cut(a, l, r) => Cut(rename(a)?, l, r),
            Forall(o, a, p) => Forall(rename(o)?, a, p),
            Exists(o, w, p) => Exists(rename(o)?, w, p),
        })
    }

    /// Returns the nodes that prove the premises, in the rule's order: none
    /// for an axiom, `1` or `⊤`, two for `⊗`, `&`, Mix and the cut, one
    /// otherwise.
    pub fn premises(self) -> impl Iterator<Item = NodeId> {
        use Node::*;
        let (first, second) = match self {
            Ax(..) | One(_) | Top(_) => (None, None),
            Tensor(_, l, r) | With(_, l, r) | Mix(l, r) | Cut(_, l, r) => (Some(l), Some(r)),
            Par(_, p)
            | Bot(_, p)
            | Plus(_, _, p)
            | Bang(_, p)
            | Quest(_, p)
            | Copy(_, p)
            | Weaken(_, p)
            | Forall(_, _, p)
            | Exists(_, _, p) => (Some(p), None),
        };
        first.into_iter().chain(second)
    }

    /// Returns the rule's name: `ax`, `⊗`, `⅋`, `1`, `⊥`, `&`, `⊕₁`, `⊕₂`,
    /// `⊤`, `!`, `?`, `copy`, `wk`, `mix`, `cut`, `∀` or `∃`.
    pub const fn name(self) -> &'static str {
        use Node::*;
        match self {
            Ax(..) => "ax",
            Tensor(..) => "⊗",
            Par(..) => "⅋",
            One(_) => "1",
            Bot(..) => "⊥",
            With(..) => "&",
            Plus(_, Branch::Left, _) => "⊕₁",
            Plus(_, Branch::Right, _) => "⊕₂",
            Top(_) => "⊤",
            Bang(..) => "!",
            Quest(..) => "?",
            Copy(..) => "copy",
            Weaken(..) => "wk",
            Mix(..) => "mix",
            Cut(..) => "cut",
            Forall(..) => "∀",
            Exists(..) => "∃",
        }
    }
}

impl Display for Node {
    /// Writes the rule's name, then `on` the occurrences and `from` the
    /// premise nodes, as in `⊗ on 1 from 0, 2`.
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.write_str(self.name())?;
        let mut occurrences = self.members().map(Member::get);
        if let Some(o) = occurrences.next() {
            write!(f, " on {o}")?;
            for o in occurrences {
                write!(f, ", {o}")?;
            }
        }
        let mut premises = self.premises().map(|p| p.get());
        if let Some(p) = premises.next() {
            write!(f, " from {p}")?;
            for p in premises {
                write!(f, ", {p}")?;
            }
        }
        Ok(())
    }
}

/// A proof of a sequent: an arena of rule instances over the sequent's
/// occurrence forest, which the proof owns. Every node refers only to nodes
/// before it, the last node is the root, and every node is reachable from
/// the root; a subproof that two nodes share is stored once.
///
/// A proof is built bottom-up, premises before conclusions, and is what a
/// search engine returns. Whether it proves its sequent is a separate
/// question, answered by [`check`](Self::check).
///
/// # Examples
///
#[cfg_attr(feature = "parse", doc = "```")]
#[cfg_attr(not(feature = "parse"), doc = "```ignore")]
/// use deduxit::linear::{Forest, Member, Mode, Node, NodeId, Proof, Sequent};
///
/// // ⊢ ~A, A ⊗ ~B, B, with the members 0: ~A, 1: A ⊗ ~B, 2: A,
/// // 3: ~B, 4: B.
/// let sequent: Sequent = "A, A -o B |- B".parse()?;
/// let forest = Forest::new(&sequent)?;
/// let (o, n) = (Member::new, NodeId::new);
/// let nodes = vec![
///     Node::Ax(o(0), o(2)),
///     Node::Ax(o(3), o(4)),
///     Node::Tensor(o(1), n(0), n(1)),
/// ];
/// let proof = Proof::new(forest, nodes, n(2))?;
/// proof.check(Mode::CLASSICAL)?;
/// assert_eq!(
///     proof.derivation()?.to_string(),
///     "─────── ax   ─────── ax\n\
///      ⊢ ~A, A      ⊢ ~B, B\n\
///      ──────────────────── ⊗\n\
///     \x20 ⊢ ~A, A ⊗ ~B, B"
/// );
/// # Ok::<(), deduxit::Error>(())
/// ```
///
/// # JSON
///
/// With the feature `serialize` a proof is `{"version": 1, "sequent": …,
/// "nodes": […], "mode": …, "goal": […]}` ([`wire`](crate::wire)): its
/// sequent in [`Sequent`]'s form (nested, without `version`), the mode it
/// is meant for and the goal it concludes where recorded, and its nodes,
/// premises before conclusions and the root last, each an object of one
/// key, the rule:
/// `{"ax": [x, y]}` on two literals, `{"1": o}` and `{"⊤": o}` on one
/// occurrence, `{"⊗": [o, l, r]}` and `{"&": [o, l, r]}` with the indices
/// of two premises, `{"mix": [l, r]}`, and `{"⅋": [o, p]}` with one, as
/// `⊥`, `⊕₁`, `⊕₂`, `!`, `?`, `copy` and `wk` have it. An occurrence is
/// an id of the sequent's [`Forest`], a premise a node's index: a proof of
/// `A, B ⊢ A ⊗ B` is `[{"ax": [0, 3]}, {"ax": [1, 4]}, {"⊗": [2, 0, 1]}]`.
/// Reading rebuilds the forest within the limits and checks the indices
/// and their order; whether the proof is one is [`Proof::check`]'s
/// question, in the mode the caller names. The command's `check` reads
/// this form, and the output of `prove --format json` holds it. A proof
/// of a first-order sequent adds `{"∀": [m, a, p]}` and `{"∃": [m, w,
/// p]}` and its `instances` ([`wire`](crate::wire)).
#[derive(Clone, Debug)]
pub struct Proof {
    /// The forest of the sequent the proof is of.
    forest: Forest,
    /// The rule instances, premises before conclusions, the root last.
    nodes: Box<[Node]>,
    /// The members the root concludes, where they are not the sequent's
    /// root formulas.
    goal: Option<Box<[Member]>>,
    /// The mode the proof is meant for: a claim, which only a check tests.
    mode: Option<Mode>,
    /// What the members past the forest's length stand for, canonical:
    /// `None` for a proof whose sequent has no binder.
    instances: Option<Box<Instances>>,
}

impl Proof {
    /// Builds a proof from the nodes of an arena and its root, keeping the
    /// nodes the root reaches in their order. Fails if a node the root
    /// reaches names an occurrence outside the forest or a premise that does
    /// not precede it, if the root lies outside the arena, or if it reaches
    /// more nodes than a [`NodeId`] counts (2³² − 1).
    ///
    /// # Errors
    ///
    /// [`Error::IndexOutOfBounds`] for a root outside the arena or a node
    /// naming an occurrence outside the forest, [`Error::NotTopological`] for
    /// a premise that does not precede its node, and
    /// [`Refusal::Index`](crate::Refusal::Index) for more nodes than a proof
    /// holds.
    pub fn new(forest: Forest, nodes: Vec<Node>, root: NodeId) -> Result<Self, Error> {
        if forest.has_binders() {
            let instances = Instances::new(&forest);
            return Self::with_instances(forest, instances, nodes, root);
        }
        Self::build(forest, nodes, root, &mut || false)
    }

    /// Builds a proof as [`new`](Self::new) does, whose members past the
    /// forest's length are those `instances` numbers: occurrences under
    /// binders with the terms the binders were opened with. The table is
    /// checked against the forest and kept canonical, so that equal
    /// instances are one member: the nodes' members and witnesses are
    /// renumbered into it, which changes no instance they name, and every
    /// member a check derives from one a node names (a subformula's
    /// instance, a binder's body under its eigenvariable or witness, a
    /// cut's dual) is added to it.
    ///
    /// # Errors
    ///
    /// As [`new`](Self::new) does, where a member is in range when the
    /// table numbers it and a witness when it is a term of the sequent or
    /// of the table; [`Error::Json`] (form `instance table`) for a table
    /// made for another sequent or not well formed, or a witness with a
    /// loose bound variable.
    pub fn with_instances(
        forest: Forest,
        instances: Instances,
        nodes: Vec<Node>,
        root: NodeId,
    ) -> Result<Self, Error> {
        let members = (forest.len() as u64).saturating_add(instances.len() as u64);
        let mut proof = Self::reach(forest, nodes, root, members, &mut || false)?;
        let mut nodes = std::mem::take(&mut proof.nodes).into_vec();
        let table = instances::canonical(&proof.forest, &instances, &mut nodes)?;
        proof.nodes = nodes.into_boxed_slice();
        proof.instances = (proof.forest.has_binders() || table != Instances::new(&proof.forest))
            .then(|| Box::new(table));
        Ok(proof)
    }

    /// Returns the proof's instance table: `None` for a proof whose
    /// sequent has no binder.
    pub fn instances(&self) -> Option<&Instances> {
        self.instances.as_deref()
    }

    /// Builds a proof as [`new`](Self::new) does, in the nodes' own
    /// vector, asking `stopped` every [`BUILD_POLL`] nodes of its two
    /// passes: an engine's proof can have hundreds of millions of nodes.
    ///
    /// # Errors
    ///
    /// As `new`, and [`Refusal::Stopped`](crate::Refusal::Stopped) in the
    /// search's phase once `stopped` answers true.
    pub(crate) fn build(
        forest: Forest,
        nodes: Vec<Node>,
        root: NodeId,
        stopped: &mut dyn FnMut() -> bool,
    ) -> Result<Self, Error> {
        let members = forest.len() as u64;
        Self::reach(forest, nodes, root, members, stopped)
    }

    /// Builds a proof as [`build`](Self::build) does, whose members are
    /// in range below `members`.
    fn reach(
        forest: Forest,
        mut nodes: Vec<Node>,
        root: NodeId,
        members: u64,
        stopped: &mut dyn FnMut() -> bool,
    ) -> Result<Self, Error> {
        /// The index of a node the root does not reach.
        const UNREACHED: u32 = u32::MAX;
        let stop = || {
            Error::Refused(crate::limits::Refusal::Stopped {
                phase: crate::limits::Phase::Search,
            })
        };
        if root.index() >= nodes.len() {
            return Err(Error::IndexOutOfBounds {
                space: crate::limits::Space::Node,
                index: root.index(),
                len: nodes.len(),
            });
        }
        // A premise precedes its conclusion, so one pass from the root down
        // visits every reachable node after the node that reaches it; a
        // node reached has index 0 until the second pass gives it its new
        // one. The root's index is below the length of a vector, so one
        // more is a `usize`.
        let mut index = vec![UNREACHED; root.index() + 1];
        index[root.index()] = 0;
        for i in (0..=root.index()).rev() {
            if i % BUILD_POLL == 0 && stopped() {
                return Err(stop());
            }
            if index[i] == UNREACHED {
                continue;
            }
            for o in nodes[i].members() {
                if u64::from(o.get()) >= members {
                    return Err(Error::IndexOutOfBounds {
                        space: crate::limits::Space::Occurrence,
                        index: o.index(),
                        len: usize::try_from(members).unwrap_or(usize::MAX),
                    });
                }
            }
            for p in nodes[i].premises() {
                if p.index() >= i {
                    return Err(Error::NotTopological {
                        space: crate::limits::Space::Node,
                        index: p.index(),
                        parent: i,
                    });
                }
                index[p.index()] = 0;
            }
        }
        // The number of nodes is a `u32` too, which the checker's counts
        // of a node's readers rely on; the root's index alone allows one
        // node more.
        let reached = index.iter().filter(|&&i| i != UNREACHED).count();
        if u32::try_from(reached).is_err() {
            return Err(Error::Refused(crate::limits::Refusal::Index {
                what: crate::limits::Space::Node,
                count: reached as u64,
                most: u64::from(u32::MAX),
            }));
        }
        // The nodes kept move down in their order: a node is written at or
        // below where it was read, after the premises it names.
        let mut kept = 0;
        for i in 0..=root.index() {
            if i % BUILD_POLL == 0 && stopped() {
                return Err(stop());
            }
            if index[i] == UNREACHED {
                continue;
            }
            // Fewer than `reached` nodes are kept so far.
            index[i] = kept as u32;
            nodes[kept] = nodes[i].map_premises(|p| NodeId::new(index[p.index()]));
            kept += 1;
        }
        nodes.truncate(kept);
        Ok(Self {
            forest,
            nodes: nodes.into_boxed_slice(),
            goal: None,
            mode: None,
            instances: None,
        })
    }

    /// Builds a proof of `goal`, members of the forest that stand for the
    /// sequent of those subformulas, as [`new`](Self::new) builds a proof
    /// of the sequent; its root concludes the goal. The roots in any order
    /// are the sequent itself, and the proof records no goal then. Fails as
    /// `new` does, or for a member outside the forest.
    ///
    /// # Errors
    ///
    /// As [`new`](Self::new) does, and [`Error::IndexOutOfBounds`] for a
    /// member of the goal outside the forest.
    pub fn new_of_goal(
        forest: Forest,
        goal: &[Member],
        nodes: Vec<Node>,
        root: NodeId,
    ) -> Result<Self, Error> {
        if let Some(m) = goal.iter().find(|m| m.occurrence(&forest).is_none()) {
            return Err(Error::IndexOutOfBounds {
                space: crate::limits::Space::Member,
                index: m.index(),
                len: forest.len(),
            });
        }
        // The roots in any order are the sequent itself, as `prove_goal`
        // takes them.
        let occurrences: Vec<OccId> = goal.iter().map(|m| m.occ()).collect();
        let roots = forest.is_roots(&occurrences);
        let mut proof = Self::new(forest, nodes, root)?;
        proof.goal = (!roots).then(|| goal.into());
        Ok(proof)
    }

    /// Returns the proof with the mode it is meant for recorded.
    #[must_use]
    pub fn with_mode(self, mode: Mode) -> Self {
        Self {
            mode: Some(mode),
            ..self
        }
    }

    /// Returns the members the root concludes, or `None` for a proof of
    /// the sequent, whose root concludes its root formulas.
    pub fn goal(&self) -> Option<&[Member]> {
        self.goal.as_deref()
    }

    /// Returns the mode the proof is meant for, as the search that found
    /// it records: a claim, which [`check`](Self::check) tests in the mode
    /// it is given.
    pub fn mode(&self) -> Option<Mode> {
        self.mode
    }

    /// Returns the occurrence a member of the proof stands for.
    pub fn occurrence(&self, member: Member) -> OccId {
        match self.instances.as_deref().and_then(|t| t.instance(member)) {
            Some((o, _)) => o,
            None => member.occ(),
        }
    }

    /// Returns the formula a member of the proof stands for: of a proof
    /// that records an intuitionistic mode as the sequent's reading writes
    /// it, two-sided (a pass over the forest each call), else as the
    /// one-sided sequent writes it; an instance with the terms of its
    /// frame for its loose bound variables, each cut after a few thousand
    /// characters (a term of shared subterms can unfold past any memory).
    ///
    /// # Panics
    ///
    /// For a member the proof does not number.
    pub fn formula(&self, member: Member) -> impl Display + '_ {
        let reading = self
            .mode
            .filter(|mode| mode.is_intuitionistic())
            .and_then(|mode| Reading::of_mode(&self.forest, mode.with_empty_antecedents()).ok());
        if let Some(table) = self.instances.as_deref()
            && member.index() >= self.forest.len()
        {
            let framing = instances::Framing::new(&self.forest.sequent().fo, table);
            let mut text = String::new();
            crate::linear::sequents::notation::TEXT
                .instance(
                    &mut text,
                    &self.forest,
                    reading.as_ref(),
                    &framing,
                    member,
                    Some(crate::errors::describe::TERM),
                )
                .expect("writing into a string cannot fail");
            return text;
        }
        match reading {
            Some(reading) => reading.formula(member.occ()).to_string(),
            None => self.forest.formula(member.occ()).to_string(),
        }
    }

    /// Returns the proof with `goal` recorded as what its root concludes.
    pub(crate) fn concluding(self, goal: &[OccId]) -> Self {
        Self {
            goal: Some(goal.iter().copied().map(Member::from).collect()),
            ..self
        }
    }

    /// Returns the proof carried over to `goal`, members of `forest` whose
    /// formulas are the proof's conclusions up to their order: each
    /// conclusion is matched to a member of the goal that is the same
    /// formula (the same connectives, units and literals, the atoms by
    /// their names), and every occurrence below it renamed to the one in
    /// the same place below that member. The proof then concludes the goal
    /// and is what it was, rule for rule; whether it holds in a mode is the
    /// checker's to say, as for any proof. Of equal formulas any may take
    /// another's place, since they are alike.
    ///
    /// # Errors
    ///
    /// [`Error::SequentMismatch`], with the formulas only the proof
    /// concludes and those only the goal holds, when the two differ beyond
    /// their order; [`Error::IndexOutOfBounds`] for a member of the goal
    /// outside `forest`, or a member a node names outside every conclusion.
    pub fn onto(&self, forest: Forest, goal: &[Member]) -> Result<Self, Error> {
        if let Some(m) = goal.iter().find(|m| m.occurrence(&forest).is_none()) {
            return Err(Error::IndexOutOfBounds {
                space: crate::limits::Space::Member,
                index: m.index(),
                len: forest.len(),
            });
        }
        let from = &self.forest;
        let name = |f: &Forest, o: OccId| f.atom(o).map(|a| f.sequent().atom_name(a).to_owned());
        let alike = |o: OccId, t: OccId| {
            from.size(o) == forest.size(t)
                && from.subtree(o).zip(forest.subtree(t)).all(|(a, b)| {
                    from.kind(a) == forest.kind(b) && name(from, a) == name(&forest, b)
                })
        };
        // Each conclusion takes the first free member of the goal alike to
        // it, and each occurrence below it the one in its place there. The
        // members wait in buckets by the formula as written, so that a
        // conclusion compares with the members written as it is and not with
        // every member, which on a goal of n formulas is n² comparisons;
        // `alike` still decides.
        let mut free: crate::hash::HashMap<String, std::collections::VecDeque<usize>> =
            crate::hash::HashMap::default();
        for (i, m) in goal.iter().enumerate() {
            free.entry(forest.formula(m.occ()).to_string())
                .or_default()
                .push_back(i);
        }
        let mut taken = vec![false; goal.len()];
        let mut place: Vec<Option<OccId>> = vec![None; from.len()];
        let mut only_proof = Vec::new();
        for c in self.conclusion() {
            let written = from.formula(c).to_string();
            let found = free.get_mut(&written).and_then(|bucket| {
                let at = bucket.iter().position(|&i| alike(c, goal[i].occ()))?;
                bucket.remove(at)
            });
            match found {
                Some(i) => {
                    taken[i] = true;
                    for (o, t) in from.subtree(c).zip(forest.subtree(goal[i].occ())) {
                        place[o.index()] = Some(t);
                    }
                }
                None => only_proof.push(c),
            }
        }
        let only_goal: Vec<OccId> = goal
            .iter()
            .zip(&taken)
            .filter(|&(_, &t)| !t)
            .map(|(m, _)| m.occ())
            .collect();
        if !only_proof.is_empty() || !only_goal.is_empty() {
            // Written as the proof's mode reads each forest: two-sided in
            // an intuitionistic one, where the forest has a reading.
            let written = |f: &Forest, os: Vec<OccId>| -> Vec<String> {
                let reading = self
                    .mode
                    .filter(|mode| mode.is_intuitionistic())
                    .and_then(|mode| Reading::of_mode(f, mode.with_empty_antecedents()).ok());
                os.into_iter()
                    .map(|o| match &reading {
                        Some(reading) => reading.formula(o).to_string(),
                        None => f.formula(o).to_string(),
                    })
                    .collect()
            };
            return Err(Error::SequentMismatch {
                proof: written(from, only_proof),
                goal: written(&forest, only_goal),
            });
        }
        let rename = |m: Member| {
            place
                .get(m.index())
                .copied()
                .flatten()
                .map(Member::from)
                .ok_or(Error::IndexOutOfBounds {
                    space: crate::limits::Space::Member,
                    index: m.index(),
                    len: from.len(),
                })
        };
        let nodes = self
            .nodes
            .iter()
            .map(|node| node.renamed(rename))
            .collect::<Result<Vec<_>, _>>()?;
        let mut carried = Self::new_of_goal(forest, goal, nodes, self.root())?;
        carried.mode = self.mode;
        Ok(carried)
    }

    /// Returns the occurrences the root concludes: the goal's, or the
    /// sequent's roots.
    pub(crate) fn conclusion(&self) -> Vec<OccId> {
        match &self.goal {
            Some(goal) => goal.iter().map(|m| m.occ()).collect(),
            None => self.forest.roots().to_vec(),
        }
    }

    /// Returns the forest of the sequent the proof is of.
    pub fn forest(&self) -> &Forest {
        &self.forest
    }

    /// Returns the sequent the proof is of.
    pub fn sequent(&self) -> &Sequent {
        self.forest.sequent()
    }

    /// Returns whether the proof has no cut.
    pub fn is_cut_free(&self) -> bool {
        !self.nodes.iter().any(|node| matches!(node, Node::Cut(..)))
    }

    /// Returns the arena: every node, premises before conclusions, the root
    /// last.
    pub fn nodes(&self) -> &[Node] {
        &self.nodes
    }

    /// Returns the node at `id`, which must belong to this proof.
    ///
    /// # Panics
    ///
    /// For an id of another one, past its end.
    pub fn node(&self, id: NodeId) -> Node {
        self.nodes[id.index()]
    }

    /// Returns every node id in arena order.
    pub fn ids(&self) -> impl DoubleEndedIterator<Item = NodeId> + ExactSizeIterator {
        // A proof has at least one node and fewer than 2³².
        (0..self.nodes.len() as u32).map(NodeId::new)
    }

    /// Returns the root: the node that concludes the sequent, the last one.
    pub fn root(&self) -> NodeId {
        // A proof has at least one node and fewer than 2³².
        NodeId::new(self.nodes.len() as u32 - 1)
    }

    /// Checks that the proof proves its sequent under the rules the mode
    /// allows, within the default [`Limits`]: every node
    /// applies its rule to what its premises derive, the mode allows the
    /// rule, and the root derives exactly the sequent's formulas with
    /// nothing left in the unrestricted zone; in intuitionistic mode also
    /// that the sequent has an intuitionistic reading and every sequent of
    /// the proof one formula on the right of `⊢`. The error names the first
    /// node that fails, in arena order, with what it needed.
    ///
    /// # Errors
    ///
    /// [`CheckError::Invalid`] naming the first node that fails, and
    /// [`CheckError::Refused`] when the default memory bound refused the
    /// pass.
    pub fn check(&self, mode: Mode) -> Result<(), CheckError> {
        check::check(self, mode)
    }

    /// Checks the proof as [`check`](Self::check) does, holding
    /// `limits.memory_bytes` at most, doing `limits.work` units of work at
    /// most, and asking `stop` every 4 096 nodes or 65 536 units, whichever
    /// comes first. A unit is a node, or an entry of a premise's sequent
    /// that its rule handles: a node that many others read, with a large
    /// sequent, costs each of them that sequent, which a short file can
    /// make quadratic in its length. A check that a bound or
    /// the stop ends answers [`CheckError::Refused`]: the proof is then
    /// neither valid nor invalid. What is counted is what the pass holds
    /// beyond the proof and its forest: a count and a pointer for every node
    /// (twelve bytes on a 64-bit target, eight on a 32-bit one), and
    /// every sequent it keeps for a later node at the size of its tables
    /// of members, a sequent that several nodes read once for each.
    ///
    /// # Errors
    ///
    /// As [`check`](Self::check) does, [`CheckError::Refused`] also past
    /// `limits.work` and when `stop` fired.
    pub fn check_within(
        &self,
        mode: Mode,
        limits: &Limits,
        mut stop: impl FnMut(Progress) -> bool,
    ) -> Result<(), CheckError> {
        check::check_within(self, mode, limits, &mut stop)
    }

    /// Unfolds the proof into the derivation of the standard sequent
    /// calculus it stands for, within the default [`Limits`], or reports
    /// why it is not a proof or why the derivation was not built; see
    /// [`Derivation`], and [`derivation_within`](Self::derivation_within)
    /// for other options. A proof meant for intuitionistic mode unfolds
    /// two-sided.
    ///
    /// # Examples
    ///
    #[cfg_attr(feature = "parse", doc = "```")]
    #[cfg_attr(not(feature = "parse"), doc = "```ignore")]
    /// use deduxit::linear::{Mode, Options, Sequent, Verdict, prove};
    ///
    /// let sequent: Sequent = "A, A -o B |- B".parse()?;
    /// let outcome = prove(&sequent, Mode::INTUITIONISTIC, &Options::default())?;
    /// let Verdict::Proved(proof) = &outcome.verdict else {
    ///     panic!("provable");
    /// };
    /// assert_eq!(
    ///     proof.derivation()?.to_string(),
    ///     "───── ax   ───── ax\n\
    ///      A ⊢ A      B ⊢ B\n\
    ///      ──────────────── ⊸L\n\
    ///     \x20 A, A ⊸ B ⊢ B"
    /// );
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    ///
    /// [`Error::Check`] for a term that is no proof in the mode the view
    /// reads it in, [`Error::NotIntuitionistic`] for a two-sided view of a
    /// sequent without a reading, and [`Error::Refused`] for a derivation past
    /// the default bounds.
    pub fn derivation(&self) -> Result<Derivation<'_>, Error> {
        self.derivation_within(&ViewOptions::default(), &Limits::default(), |_| false)
    }

    /// Unfolds the proof as [`derivation`](Self::derivation) does, shown
    /// as `view` says, within `limits.derivation_bytes` and
    /// `limits.memory_bytes`, and until `stop` returns true, which is
    /// asked as [`check_within`](Self::check_within) asks it in the
    /// checker's passes and once per node unfolded.
    ///
    /// # Errors
    ///
    /// As [`derivation`](Self::derivation) does within `limits`, and
    /// [`Refusal::Stopped`](crate::Refusal::Stopped) when `stop` fired.
    pub fn derivation_within(
        &self,
        view: &ViewOptions,
        limits: &Limits,
        stop: impl FnMut(Progress) -> bool,
    ) -> Result<Derivation<'_>, Error> {
        if view.two_sided(self) {
            Derivation::two_sided(self, view, limits, stop)
        } else {
            Derivation::new(self, view, limits, stop)
        }
    }

    /// Returns the two-sided derivation within the default limits: the
    /// tests' short form.
    #[cfg(all(test, feature = "parse"))]
    pub(crate) fn two_sided(&self) -> Result<Derivation<'_>, Error> {
        let view = ViewOptions::default().with_sides(Sides::Two);
        self.derivation_within(&view, &Limits::default(), |_| false)
    }
}

impl Node {
    /// Returns the node with every premise index replaced by what `f` maps
    /// it to.
    pub(crate) fn map_premises(self, mut f: impl FnMut(NodeId) -> NodeId) -> Self {
        use Node::*;
        match self {
            Tensor(o, l, r) => Tensor(o, f(l), f(r)),
            Par(o, p) => Par(o, f(p)),
            Bot(o, p) => Bot(o, f(p)),
            With(o, l, r) => With(o, f(l), f(r)),
            Plus(o, s, p) => Plus(o, s, f(p)),
            Bang(o, p) => Bang(o, f(p)),
            Quest(o, p) => Quest(o, f(p)),
            Copy(o, p) => Copy(o, f(p)),
            Weaken(o, p) => Weaken(o, f(p)),
            Mix(l, r) => Mix(f(l), f(r)),
            Cut(o, l, r) => Cut(o, f(l), f(r)),
            Forall(o, a, p) => Forall(o, a, f(p)),
            Exists(o, w, p) => Exists(o, w, f(p)),
            leaf @ (Ax(..) | One(_) | Top(_)) => leaf,
        }
    }
}

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

    /// The name lists follow the variants: `NAMES` one each in order, and
    /// `TAGS` every rule's name, in order, `Plus` twice.
    #[test]
    fn name_lists_follow_the_variants() {
        let (m, n) = (Member::new(0), NodeId::new(0));
        let nodes = [
            Node::Ax(m, m),
            Node::Tensor(m, n, n),
            Node::Par(m, n),
            Node::One(m),
            Node::Bot(m, n),
            Node::With(m, n, n),
            Node::Plus(m, Branch::Left, n),
            Node::Top(m),
            Node::Bang(m, n),
            Node::Quest(m, n),
            Node::Copy(m, n),
            Node::Weaken(m, n),
            Node::Mix(n, n),
            Node::Cut(m, n, n),
            Node::Forall(m, Eigen::new(0), n),
            Node::Exists(m, FoTermId::new(0), n),
        ];
        let names: Vec<String> = nodes
            .iter()
            .map(|node| format!("{node:?}").split('(').next().unwrap().to_owned())
            .collect();
        assert_eq!(names, Node::NAMES);
        let mut tags: Vec<&str> = nodes.iter().map(|node| node.name()).collect();
        tags.insert(7, Node::Plus(m, Branch::Right, n).name());
        assert_eq!(tags, Node::TAGS);
    }

    /// A goal is a sequent of the mode it is checked in: under the reading
    /// one output, as every sequent of its derivation has; and the roots
    /// in another order are the sequent itself.
    #[cfg(feature = "parse")]
    #[test]
    fn a_goal_is_a_sequent_of_its_mode() {
        // `0 ⊢ a`: the input `0`, one-sided `⊤`, is occurrence 0.
        let sequent: Sequent = "0 |- a".parse().unwrap();
        let top = Member::new(0);
        let forest = Forest::new(&sequent).unwrap();
        let proof = Proof::new_of_goal(forest, &[top], vec![Node::Top(top)], NodeId::new(0));
        let proof = proof.unwrap();
        assert_eq!(proof.check(Mode::CLASSICAL), Ok(()));
        let Err(CheckError::Invalid(invalid)) = proof.check(Mode::INTUITIONISTIC) else {
            panic!("a goal without an output is no intuitionistic sequent");
        };
        assert_eq!(invalid.fault, Fault::Succedents { count: 0 });
        let sequent: Sequent = "A |- A".parse().unwrap();
        let (a, b) = (Member::new(0), Member::new(1));
        let forest = Forest::new(&sequent).unwrap();
        let swapped = Proof::new_of_goal(forest, &[b, a], vec![Node::Ax(a, b)], NodeId::new(0));
        assert_eq!(swapped.unwrap().goal(), None);
    }
}