deduxit 0.4.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
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! The text parser of sequents.
//!
//! It is a precedence parser with a stack of its own. It writes each term
//! into the arena as soon as the term is complete, so neither deep nesting
//! nor a long formula uses the caller's stack.
//!
//! [`Sequent`] documents the syntax it reads.
//!
//! The arena holds the formulas one-sided, in negation normal form: the
//! formulas left of the turnstile are negated, `A ⊸ B` is `A^⊥ ⅋ B`, and
//! every negation is pushed down to the atoms. The parser writes each term
//! as the text has it and notes where a negation applies. At the end, one
//! pass from the last term to the first dualises every term under an odd
//! number of negations.

use crate::Error;
use crate::errors::ParseError;
use crate::hash::HashMap;
use crate::limits::{Limits, Refusal, Space};
use crate::linear::fragment::Order;
use crate::linear::occurrences::Forest;
use crate::linear::occurrences::reading::Side;
use crate::linear::occurrences::written::Written;
use crate::linear::sequents::fo::{self, FoTerm, FoTermId, Interner, SymbolFault};
use crate::linear::sequents::name::{KEYWORDS, RESERVED, normalized, starts_identifier};
use crate::linear::sequents::{Atom, Sequent, Term, TermId};
use std::borrow::Cow;

/// The hint for a symbol used with another number of arguments than at
/// its first use.
const ARITY: &str = "a symbol takes the same number of arguments everywhere: \
                     this use differs from the first";
/// The hint for a name used both as a predicate and as a function symbol.
const ROLE: &str = "a name is a predicate or a function symbol, not both";
/// The hint for a keyword where a variable, constant or function symbol
/// should stand.
const KEYWORD: &str = "a keyword names no variable, constant or function symbol";
/// The hint for `->`, the arrow of ordinary logic, in a linear sequent.
const ARROW: &str = "-> is ordinary logic's arrow: write -o";

/// A binary connective as it is written.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Binary {
    /// `*` or `⊗`
    Tensor,
    /// `|`, `par` or `⅋`
    Par,
    /// `&`
    With,
    /// `+` or `⊕`
    Plus,
    /// `-o` or `⊸`
    Lollipop,
    /// `\`, the left division, read only by an ordered parse: `A \ B` is
    /// `A⊥ ⅋ B`, like `A ⊸ B`.
    Under,
    /// `/`, the right division, read only by an ordered parse: `B / A` is
    /// `B ⅋ A⊥`.
    Over,
}

impl Binary {
    /// Returns how tightly the connective binds: of two connectives on
    /// either side of an operand, the one with the larger number takes it.
    const fn strength(self) -> u8 {
        match self {
            Binary::Tensor => 5,
            Binary::Par => 4,
            Binary::With => 3,
            Binary::Plus => 2,
            Binary::Lollipop | Binary::Under | Binary::Over => 1,
        }
    }

    /// Returns whether an operand between this connective (on its left)
    /// and `next` (on its right) belongs to this one. It does when this one
    /// binds tighter, or when both are the same connective and it
    /// associates to the left, as every connective but `⊸` and `\` does.
    fn takes_before(self, next: Binary) -> bool {
        self.strength() > next.strength()
            || (self == next && !matches!(self, Binary::Lollipop | Binary::Under))
    }
}

/// Something read that waits for the operand on its right to be complete.
#[derive(Clone, Copy, Debug)]
enum Pending {
    /// `(`, which waits for its `)`.
    Open,
    /// `~`
    Dual,
    /// `!`
    Bang,
    /// `?`
    Quest,
    /// `∀x.` (`true`) or `∃x.` (`false`). Its variable's name is the last
    /// one in the parser's `scope`.
    Binder(bool),
    /// A binary connective with its left operand.
    Binary(Binary, TermId),
}

/// What the parser reads next.
enum State {
    /// Something a formula starts with.
    Operand,
    /// What follows an operand, the term given.
    Operator(TermId),
    /// Nothing: the sequent is complete.
    End,
}

/// The state of reading one sequent: the text and the place in it, the
/// arena so far, and what waits for its right operand.
struct Parser<'a> {
    /// The text of the sequent.
    input: &'a str,
    /// The byte offset of the next character to read.
    at: usize,
    /// Whether the formulas being read stand left of the turnstile.
    left: bool,
    /// Whether nothing on this side of the turnstile has been read yet, so
    /// that the side may still be empty.
    empty: bool,
    /// The terms read so far, each as it stands in the text.
    terms: Vec<Term>,
    /// Per term, whether the text negates it an odd number of times. A
    /// negation is a `~` or `^` on the term, the term being the antecedent
    /// of a `⊸` or `\` or the right operand of a `/`, or the term being a
    /// formula left of the turnstile. The negations of the terms above it
    /// are not counted until `dualise`, after which the flag says whether
    /// the term was dualised.
    negated: Vec<bool>,
    /// The formulas of the sequent, in the order of the text.
    roots: Vec<TermId>,
    /// How many formulas stand left of the turnstile, once it is passed.
    antecedents: u32,
    /// The names of the atoms, in the order they first occur.
    atoms: Vec<String>,
    /// The atom of every name read so far, keyed by the name in NFC
    /// (Unicode's composed form).
    names: HashMap<Cow<'a, str>, Atom>,
    /// The prefix operators, parentheses and binary connectives whose
    /// right operand is being read, the innermost last.
    pending: Vec<Pending>,
    /// How many parentheses are open.
    open: usize,
    /// How many `!`, `?` and binders wait in `pending`. Each will become a
    /// term, so it counts against the bound as soon as it is read, and a
    /// long run of them is refused before it is reduced.
    owed: u64,
    /// How many `(` and `~` wait in `pending`. They make no term, but more
    /// of them than the bound are refused all the same, so that a run of
    /// them cannot pile up.
    marks: u64,
    /// The most terms the arena may hold: the caller's bound, capped at
    /// what a forest can index.
    most: u64,
    /// The bound on occurrences the caller set, if any.
    limit: Option<u64>,
    /// The order of the calculus the sequent is read for, which decides
    /// what a negation does to a product and to the antecedents.
    order: Order,
    /// Whether to record how every term was written.
    recording: bool,
    /// While recording, the terms written as `⊸` or `\`, in ascending
    /// order.
    implications: Vec<TermId>,
    /// The names of the binders whose body is being read, the innermost
    /// last: what an identifier in term position is resolved against.
    scope: Vec<&'a str>,
    /// The symbols, terms and argument lists read so far, interned; empty
    /// until the text is first-order.
    interner: Interner,
    /// Whether the text is first-order so far: whether an atom with
    /// arguments or a binder has been read.
    first_order: bool,
    /// Per atom, its predicate symbol and arguments, once the text is
    /// first-order; empty before, so that a propositional text pays
    /// nothing.
    predicates: Vec<(fo::Symbol, fo::Args)>,
    /// The binders read, each with its variable's name, in the order of
    /// their terms.
    binders: Vec<(TermId, String)>,
}

/// Reads `text` as a sequent for a calculus of `order`. The text is
/// refused past `limit` terms, or past `terms` first-order terms in its
/// atoms ([`Sequent::fo_size`]). Where `written` is given, it is filled
/// with how every occurrence of the sequent's forest was written.
///
/// Every reader calls this function, the only place a parser is made and
/// run. So the parser's loop, and all the loop calls, has one caller and
/// is inlined. A copy of the loop in each reader costs the commutative
/// reader 1.5 % to 7 % more instructions, because a callee the copies
/// share loses its inlining.
fn read(
    text: &str,
    limit: Option<u64>,
    terms: Option<u64>,
    order: Order,
    written: Option<&mut Vec<Written>>,
) -> Result<Sequent, Error> {
    let mut parser = Parser::new(text, limit, order);
    parser.recording = written.is_some();
    let sequent = parser.sequent(written)?;
    if sequent.fo.atoms.is_empty() {
        return Ok(sequent);
    }
    first_order_within(sequent, terms)
}

/// Returns a first-order `sequent`, or its refusal when its atoms unfold
/// to more than `terms` terms. Text spells out every term it holds, so
/// here the bound limits no more than the text's length does; the parser
/// applies it because every reader does.
#[cold]
#[inline(never)]
fn first_order_within(sequent: Sequent, terms: Option<u64>) -> Result<Sequent, Error> {
    match terms {
        Some(limit) if sequent.fo_size() > limit => Err(Error::Refused(Refusal::Terms {
            terms: sequent.fo_size(),
            limit,
        })),
        _ => Ok(sequent),
    }
}

/// Reads `text` as a sequent of the commutative calculus within `limits`,
/// as [`Sequent::parse_within`] does, and returns it with how every
/// occurrence of its forest was written, by occurrence id.
pub(crate) fn written(text: &str, limits: &Limits) -> Result<(Sequent, Vec<Written>), Error> {
    let mut writing = Vec::new();
    let sequent = read(
        text,
        limits.occurrences,
        limits.terms,
        Order::Commutative,
        Some(&mut writing),
    )?;
    Ok((sequent, writing))
}

impl<'a> Parser<'a> {
    /// Returns a parser at the start of `input`, for a sequent of at most
    /// `limit` terms and never more than a forest can index.
    fn new(input: &'a str, limit: Option<u64>, order: Order) -> Self {
        let most = limit.unwrap_or(Forest::MOST).min(Forest::MOST);
        Self {
            input,
            at: 0,
            left: true,
            empty: true,
            terms: Vec::new(),
            negated: Vec::new(),
            roots: Vec::new(),
            antecedents: 0,
            atoms: Vec::new(),
            names: HashMap::default(),
            pending: Vec::new(),
            open: 0,
            owed: 0,
            marks: 0,
            most,
            limit,
            order,
            recording: false,
            implications: Vec::new(),
            scope: Vec::new(),
            interner: Interner::new(),
            first_order: false,
            predicates: Vec::new(),
            binders: Vec::new(),
        }
    }

    /// Returns the next character, or `None` at the end of the input.
    fn peek(&self) -> Option<char> {
        self.input[self.at..].chars().next()
    }

    /// Returns the error for the character at byte `at`, or for the end of
    /// the input there, where `expected` could have stood.
    fn unexpected(&self, at: usize, expected: &'static [&'static str]) -> Error {
        Error::from(ParseError::new(self.input, at, expected))
    }

    /// Returns what can stand here where a formula starts: a formula, and
    /// on an empty left side the turnstile too.
    const fn operands(&self) -> &'static [&'static str] {
        if self.empty && self.left {
            &["a formula", "`|-`"]
        } else {
            &["a formula"]
        }
    }

    /// Returns what can follow an operand here: a connective, and then
    /// inside a parenthesis its `)`; outside every parenthesis a comma, and
    /// the turnstile on the left side or the end on the right side.
    const fn operators(&self) -> &'static [&'static str] {
        if self.open > 0 {
            &["a connective", "`)`"]
        } else if self.left {
            &["a connective", "`,`", "`|-`"]
        } else {
            &["a connective", "`,`", "the end"]
        }
    }

    /// Appends a term to the arena and returns its index, or the refusal
    /// when the arena, with the terms still owed, is full.
    fn push(&mut self, term: Term) -> Result<TermId, Error> {
        let index = self.terms.len() as u64;
        if index.saturating_add(self.owed) >= self.most {
            return Err(self.past_bound());
        }
        self.terms.push(term);
        self.negated.push(false);
        Ok(TermId::new(index as u32))
    }

    /// Notes one more negation of a term.
    fn negate(&mut self, term: TermId) {
        self.negated[term.index()] ^= true;
    }

    /// Reads the rest of the identifier that starts at byte `start` and
    /// whose first character has been read, and returns it whole.
    fn identifier(&mut self, start: usize) -> &'a str {
        let rest = &self.input[self.at..];
        let end = rest
            .find(|c| !unicode_ident::is_xid_continue(c))
            .unwrap_or(rest.len());
        self.at += end;
        &self.input[start..self.at]
    }

    /// Returns the atom of `name`, compared in NFC, and makes a new atom
    /// for a new name, in one map lookup.
    fn atom(&mut self, name: &'a str) -> Atom {
        use std::collections::hash_map::Entry;
        let next = Atom::new(self.atoms.len() as u32);
        match self.names.entry(normalized(name)) {
            Entry::Occupied(known) => *known.get(),
            Entry::Vacant(new) => {
                self.atoms.push(new.key().clone().into_owned());
                new.insert(next);
                next
            }
        }
    }

    /// In a first-order text, gives `atom`, read as `name`, its predicate
    /// if the atom is new: the nullary symbol of its name.
    #[cold]
    #[inline(never)]
    fn nullary(&mut self, atom: Atom, name: &'a str) -> Result<(), Error> {
        if atom.index() < self.predicates.len() {
            return Ok(());
        }
        let start = self.at - name.len();
        let key = self.atoms[atom.index()].clone();
        let symbol = self.symbol(&key, 0, true, start..self.at)?;
        let empty = self.interner.list(&[]);
        self.predicates.push((symbol, empty));
        Ok(())
    }

    /// Marks the text as first-order, if it is not yet: every atom read so
    /// far gets its predicate, the nullary symbol of its name.
    #[cold]
    #[inline(never)]
    fn enter_first_order(&mut self, span: std::ops::Range<usize>) -> Result<(), Error> {
        if std::mem::replace(&mut self.first_order, true) || self.atoms.is_empty() {
            return Ok(());
        }
        let empty = self.interner.list(&[]);
        for a in 0..self.atoms.len() {
            let name = std::mem::take(&mut self.atoms[a]);
            let symbol = self.symbol(&name, 0, true, span.clone());
            self.atoms[a] = name;
            self.predicates.push((symbol?, empty));
        }
        Ok(())
    }

    /// Returns the interned symbol `name` of `arity`, a predicate or a
    /// function symbol as `predicate` says. Fails with an error at `span`
    /// when the name is known with another arity or in the other role.
    #[cold]
    #[inline(never)]
    fn symbol(
        &mut self,
        name: &str,
        arity: u32,
        predicate: bool,
        span: std::ops::Range<usize>,
    ) -> Result<fo::Symbol, Error> {
        self.interner
            .symbol(name, arity, predicate)
            .map_err(|fault| {
                let hint = match fault {
                    SymbolFault::Arity { .. } => ARITY,
                    SymbolFault::Role | SymbolFault::Repeated => ROLE,
                };
                ParseError::spanning(self.input, span, &[])
                    .with_hint(hint)
                    .into()
            })
    }

    /// Reads the variables and the dot after a binder's keyword (`x y.`
    /// of `forall x y.`), and opens one binder per variable, the first
    /// outermost.
    #[cold]
    #[inline(never)]
    fn binder(&mut self, universal: bool) -> Result<State, Error> {
        let keyword = self.at;
        // The text turns first-order here: every atom read so far gets its
        // predicate before any variable is in scope.
        self.enter_first_order(keyword..self.at)?;
        let mut names = 0;
        loop {
            self.skip_blank();
            let start = self.at;
            let Some(c) = self.peek() else {
                return Err(self.unexpected(start, &["a variable name"]));
            };
            if c == '.' && names > 0 {
                self.at += 1;
                break;
            }
            if !starts_identifier(c) {
                let expected: &'static [&'static str] = if names > 0 {
                    &["a variable name", "`.`"]
                } else {
                    &["a variable name"]
                };
                return Err(self.unexpected(start, expected));
            }
            self.at += c.len_utf8();
            let name = self.identifier(start);
            if KEYWORDS.contains(&name) || RESERVED.contains(&name) {
                let error = ParseError::spanning(self.input, start..self.at, &["a variable name"]);
                return Err(error.with_hint(KEYWORD).into());
            }
            self.scope.push(name);
            names += 1;
        }
        for _ in 0..names {
            self.prefix(Pending::Binder(universal))?;
        }
        Ok(State::Operand)
    }

    /// Skips the whitespace at the current place.
    fn skip_blank(&mut self) {
        let blank = &self.input[self.at..];
        self.at += blank.len() - blank.trim_start().len();
    }

    /// Reads the argument list of the predicate `name`, whose `(` has been
    /// read, up to its `)`, and returns the predicate's atom.
    ///
    /// An identifier before a `(` is a function symbol. Any other
    /// identifier is the variable of the innermost open binder of that
    /// name, or else a constant. Nested applications go on an explicit
    /// stack, so no term uses the caller's stack.
    #[cold]
    #[inline(never)]
    fn predicate(&mut self, name: &'a str, start: usize) -> Result<Atom, Error> {
        self.enter_first_order(start..self.at)?;
        // The applications being read: each one's symbol, where it starts
        // and its arguments so far. The predicate's own list is the first.
        let mut open: Vec<(Cow<'a, str>, usize, Vec<FoTermId>)> =
            vec![(normalized(name), start, Vec::new())];
        loop {
            // One term.
            self.skip_blank();
            let at = self.at;
            match self.peek() {
                Some(c) if starts_identifier(c) => {
                    self.at += c.len_utf8();
                }
                _ => return Err(self.unexpected(at, &["a term"])),
            }
            let word = self.identifier(at);
            if KEYWORDS.contains(&word) || RESERVED.contains(&word) {
                let error = ParseError::spanning(self.input, at..self.at, &["a term"]);
                return Err(error.with_hint(KEYWORD).into());
            }
            let word = normalized(word);
            self.skip_blank();
            if self.peek() == Some('(') {
                self.at += 1;
                open.push((word, at, Vec::new()));
                continue;
            }
            let mut term = match self.scope.iter().rev().position(|&v| *v == *word) {
                Some(index) => FoTerm::Bound(index as u32),
                None => {
                    let symbol = self.symbol(&word, 0, false, at..self.at)?;
                    FoTerm::App(symbol, self.interner.list(&[]))
                }
            };
            // The term closes every application whose last argument it is.
            loop {
                let id = self.interner.term(term);
                let list = &mut open.last_mut().expect("the predicate's list is open").2;
                list.push(id);
                self.skip_blank();
                let at = self.at;
                match self.peek() {
                    Some(',') => {
                        self.at += 1;
                        break;
                    }
                    Some(')') => self.at += 1,
                    _ => return Err(self.unexpected(at, &["`,`", "`)`"])),
                }
                let (symbol, from, items) = open.pop().expect("an application was open");
                let arity = u32::try_from(items.len()).map_err(|_| self.past_bound())?;
                let args = self.interner.list(&items);
                if open.is_empty() {
                    let symbol = self.symbol(&symbol, arity, true, from..self.at)?;
                    let key = self.interner.tables.atom_key(symbol, args);
                    let atom = match self.names.get(key.as_str()) {
                        Some(&atom) => atom,
                        None => {
                            let atom = Atom::new(self.atoms.len() as u32);
                            self.atoms.push(key.clone());
                            self.names.insert(Cow::Owned(key), atom);
                            self.predicates.push((symbol, args));
                            atom
                        }
                    };
                    return Ok(atom);
                }
                let symbol = self.symbol(&symbol, arity, false, from..self.at)?;
                term = FoTerm::App(symbol, args);
            }
        }
    }

    /// Applies to `operand` the pending operators that take it before the
    /// connective `next` does, the innermost first, and returns the term
    /// they make. For `None` it applies every one of them up to the
    /// innermost open parenthesis.
    fn reduce(&mut self, mut operand: TermId, next: Option<Binary>) -> Result<TermId, Error> {
        while let Some(&top) = self.pending.last() {
            let term = match top {
                Pending::Open => break,
                Pending::Dual => {
                    self.negate(operand);
                    self.pending.pop();
                    self.marks -= 1;
                    continue;
                }
                // Each becomes the term `owed` counted it as.
                Pending::Bang => {
                    self.owed -= 1;
                    Term::Bang(operand)
                }
                Pending::Quest => {
                    self.owed -= 1;
                    Term::Quest(operand)
                }
                Pending::Binder(universal) => {
                    // A binder binds loosest: a connective to its right is
                    // inside its scope.
                    if next.is_some() {
                        break;
                    }
                    self.close_binder(universal, operand)
                }
                Pending::Binary(connective, left) => {
                    if next.is_some_and(|next| !connective.takes_before(next)) {
                        break;
                    }
                    match connective {
                        Binary::Tensor => Term::Tensor(left, operand),
                        Binary::Par => Term::Par(left, operand),
                        Binary::With => Term::With(left, operand),
                        Binary::Plus => Term::Plus(left, operand),
                        Binary::Lollipop | Binary::Under => {
                            self.negate(left);
                            if self.recording {
                                // The index the term is pushed at below.
                                self.implications.push(TermId::new(self.terms.len() as u32));
                            }
                            Term::Par(left, operand)
                        }
                        Binary::Over => {
                            self.negate(operand);
                            Term::Par(left, operand)
                        }
                    }
                }
            };
            self.pending.pop();
            operand = self.push(term)?;
        }
        Ok(operand)
    }

    /// Closes the innermost binder over `operand` and returns its term,
    /// recording the variable's name for the term about to be pushed.
    #[cold]
    #[inline(never)]
    fn close_binder(&mut self, universal: bool, operand: TermId) -> Term {
        self.owed -= 1;
        let name = self.scope.pop().expect("a binder has its variable");
        self.binders
            .push((TermId::new(self.terms.len() as u32), name.to_owned()));
        if universal {
            Term::Forall(operand)
        } else {
            Term::Exists(operand)
        }
    }

    /// Completes a formula of the sequent with its last operand, outside
    /// every parenthesis, and negates it on the left side.
    fn root(&mut self, operand: TermId) -> Result<(), Error> {
        let root = self.reduce(operand, None)?;
        if self.left {
            self.negate(root);
        }
        self.roots.push(root);
        Ok(())
    }

    /// Passes the turnstile: what follows is the right side, of which
    /// nothing has been read.
    fn turnstile(&mut self) -> State {
        // Every formula is a term, of which there are fewer than `u32::MAX`.
        self.antecedents = self.roots.len() as u32;
        self.left = false;
        self.empty = true;
        State::Operand
    }

    /// Returns the refusal of a text with more terms than the bound:
    /// [`Refusal::Occurrences`] for the caller's bound, [`Refusal::Index`]
    /// where the bound is what a forest can index. Every term of a text is
    /// an occurrence of its own, so the text is refused at the first term
    /// past the bound.
    fn past_bound(&self) -> Error {
        Error::Refused(match self.limit {
            Some(limit) if limit < Forest::MOST => Refusal::Occurrences {
                occurrences: limit.saturating_add(1),
                limit,
            },
            _ => Refusal::Index {
                what: Space::Occurrence,
                count: Forest::MOST.saturating_add(1),
                most: Forest::MOST,
            },
        })
    }

    /// Notes an operator that stands before its operand, or an open
    /// parenthesis. Two `~` in a row cancel, so a run of them waits as one
    /// at most. A `!`, `?` or binder counts as the term it will become, and
    /// a `(` or `~` as a mark; more of either than the bound is refused.
    fn prefix(&mut self, operator: Pending) -> Result<State, Error> {
        self.empty = false;
        match operator {
            Pending::Dual if matches!(self.pending.last(), Some(Pending::Dual)) => {
                self.pending.pop();
                self.marks -= 1;
                return Ok(State::Operand);
            }
            Pending::Bang | Pending::Quest | Pending::Binder(_) => {
                self.owed += 1;
                if (self.terms.len() as u64).saturating_add(self.owed) > self.most {
                    return Err(self.past_bound());
                }
            }
            Pending::Open | Pending::Dual => {
                self.marks += 1;
                if self.marks > self.most {
                    return Err(self.past_bound());
                }
            }
            Pending::Binary(..) => {}
        }
        self.pending.push(operator);
        Ok(State::Operand)
    }

    /// Reads what a formula starts with: a prefix operator, an open
    /// parenthesis, a constant, an atom or a binder. On an empty left side
    /// the turnstile may stand there, and on an empty right side the end
    /// of the input.
    fn operand(&mut self) -> Result<State, Error> {
        let start = self.at;
        let Some(c) = self.peek() else {
            return if self.empty && !self.left {
                Ok(State::End)
            } else {
                Err(self.unexpected(start, self.operands()))
            };
        };
        self.at += c.len_utf8();
        let term = match c {
            '~' => return self.prefix(Pending::Dual),
            '!' => return self.prefix(Pending::Bang),
            '?' => return self.prefix(Pending::Quest),
            '(' => {
                self.open += 1;
                return self.prefix(Pending::Open);
            }
            '0' => Term::Zero,
            '1' => Term::One,
            '⊥' => Term::Bot,
            '⊤' => Term::Top,
            '∀' => return self.binder(true),
            '∃' => return self.binder(false),
            '⊢' if self.empty && self.left => return Ok(self.turnstile()),
            '|' if self.empty && self.left => {
                // Only `|-` can start a sequent with `|`, so what is wrong
                // is the character after it.
                if self.peek() != Some('-') {
                    return Err(self.unexpected(self.at, &["the `-` of `|-`"]));
                }
                self.at += 1;
                return Ok(self.turnstile());
            }
            _ if starts_identifier(c) => match self.identifier(start) {
                "bot" => Term::Bot,
                "top" => Term::Top,
                // `par` is a connective, and only a formula can stand here.
                "par" => {
                    let error = ParseError::spanning(self.input, start..self.at, self.operands());
                    return Err(error.into());
                }
                "forall" => return self.binder(true),
                "exists" => return self.binder(false),
                name if self.input.as_bytes().get(self.at) == Some(&b'(') => {
                    self.at += 1;
                    Term::Atom(self.predicate(name, start)?)
                }
                name => {
                    let atom = self.atom(name);
                    if self.first_order {
                        self.nullary(atom, name)?;
                    }
                    Term::Atom(atom)
                }
            },
            _ => return Err(self.unexpected(start, self.operands())),
        };
        self.empty = false;
        Ok(State::Operator(self.push(term)?))
    }

    /// Reads what follows the operand just read: a postfix `^`, a binary
    /// connective, a closing parenthesis, or outside every parenthesis a
    /// comma, the turnstile on the left side and the end of the input on
    /// the right side.
    fn operator(&mut self, operand: TermId) -> Result<State, Error> {
        let start = self.at;
        let outermost = self.open == 0;
        let Some(c) = self.peek() else {
            if self.left || !outermost {
                return Err(self.unexpected(start, self.operators()));
            }
            self.root(operand)?;
            return Ok(State::End);
        };
        self.at += c.len_utf8();
        let connective = match c {
            '^' => {
                self.negate(operand);
                return Ok(State::Operator(operand));
            }
            '*' | '⊗' => Binary::Tensor,
            '⅋' => Binary::Par,
            '&' => Binary::With,
            '+' | '⊕' => Binary::Plus,
            '⊸' => Binary::Lollipop,
            '-' => {
                // Only `-o` starts with `-`, so what is wrong is the
                // character after it.
                if self.peek() == Some('>') {
                    return Err(ParseError::new(self.input, self.at, &["the `o` of `-o`"])
                        .with_hint(ARROW)
                        .into());
                }
                if self.peek() != Some('o') {
                    return Err(self.unexpected(self.at, &["the `o` of `-o`"]));
                }
                self.at += 1;
                Binary::Lollipop
            }
            // The divisions of the Lambek calculus, only in an ordered parse.
            '\\' if self.order != Order::Commutative => Binary::Under,
            '/' if self.order != Order::Commutative => Binary::Over,
            '|' if self.left && outermost && self.peek() == Some('-') => {
                self.at += 1;
                self.root(operand)?;
                return Ok(self.turnstile());
            }
            // Where no turnstile can stand, `|-` is a par `|` before a `-`.
            // The `-` starts no formula, so the error is reported there.
            '|' => Binary::Par,
            '⊢' if self.left && outermost => {
                self.root(operand)?;
                return Ok(self.turnstile());
            }
            ',' if outermost => {
                self.root(operand)?;
                return Ok(State::Operand);
            }
            ')' if !outermost => {
                let inner = self.reduce(operand, None)?;
                // What stopped the reduction is the open parenthesis.
                self.pending.pop();
                self.open -= 1;
                self.marks -= 1;
                return Ok(State::Operator(inner));
            }
            _ if starts_identifier(c) && self.identifier(start) == "par" => Binary::Par,
            _ => return Err(self.unexpected(start, self.operators())),
        };
        let left = self.reduce(operand, Some(connective))?;
        self.pending.push(Pending::Binary(connective, left));
        Ok(State::Operand)
    }

    /// Reads the whole input as a sequent. Where `written` is given, it
    /// records there how every occurrence was written.
    fn sequent(mut self, written: Option<&mut Vec<Written>>) -> Result<Sequent, Error> {
        let mut state = State::Operand;
        loop {
            let blank = &self.input[self.at..];
            self.at += blank.len() - blank.trim_start().len();
            state = match state {
                State::Operand => self.operand()?,
                State::Operator(operand) => self.operator(operand)?,
                State::End => return self.finish(written),
            };
        }
    }

    /// Dualises every term that stands under an odd number of negations,
    /// reversing the operands of a product when `ORDERED`.
    fn dualise<const ORDERED: bool>(&mut self) {
        // A term comes after its subterms, so one pass from the last term
        // passes every negation down to a term before it reaches it.
        for n in (0..self.terms.len()).rev() {
            if self.negated[n] {
                let mut term = self.terms[n].dual();
                if ORDERED {
                    term = match term {
                        Term::Tensor(l, r) => Term::Tensor(r, l),
                        Term::Par(l, r) => Term::Par(r, l),
                        other => other,
                    };
                }
                self.terms[n] = term;
                for k in term.subterms() {
                    self.negated[k.index()] ^= true;
                }
            }
        }
    }

    /// Returns how every occurrence of the sequent's forest was written,
    /// by occurrence id. It runs after `dualise`: a term the negations
    /// dualised stands on the input side, and `negated` then says which
    /// terms those are. Before `optimize` every term has one parent, so
    /// the terms in preorder from the roots, in order, are the forest's
    /// occurrences in its numbering.
    fn written(&self) -> Vec<Written> {
        let mut implication = vec![false; self.terms.len()];
        for &term in &self.implications {
            implication[term.index()] = true;
        }
        let mut writing = Vec::with_capacity(self.terms.len());
        let mut stack = Vec::new();
        for &root in &self.roots {
            stack.push(root);
            while let Some(term) = stack.pop() {
                let side = if self.negated[term.index()] {
                    Side::Input
                } else {
                    Side::Output
                };
                writing.push(Written::new(side, implication[term.index()]));
                let (left, right) = self.terms[term.index()].operands();
                stack.extend(right);
                stack.extend(left);
            }
        }
        writing
    }

    /// Applies the negations noted and returns the sequent, optimized.
    /// Where `written` is given, it records there how every occurrence was
    /// written.
    ///
    /// In the cyclic order the dual of a product reverses it, `(A ⊗ B)⊥ =
    /// B⊥ ⅋ A⊥`, and the antecedents `A₁, …, Aₙ ⊢` become `Aₙ⊥, …, A₁⊥`,
    /// the dual of their product.
    fn finish(mut self, written: Option<&mut Vec<Written>>) -> Result<Sequent, Error> {
        if self.order == Order::Commutative {
            self.dualise::<false>();
        } else {
            self.dualise::<true>();
            self.roots[..self.antecedents as usize].reverse();
        }
        if let Some(written) = written {
            *written = self.written();
        }
        let mut fo = self.interner.tables;
        fo.atoms = self.predicates;
        fo.binders = self.binders;
        let mut sequent = Sequent {
            terms: self.terms,
            roots: self.roots,
            atoms: self.atoms,
            antecedents: Some(self.antecedents),
            cuts: vec![],
            fo,
        };
        debug_assert!(sequent.check().is_ok(), "{:?}", sequent.check());
        sequent.optimize();
        Ok(sequent)
    }
}

impl Sequent {
    /// Parses a sequent such as `A, B |- A * B` into its one-sided form,
    /// within `limits`.
    ///
    /// The text is refused at the first term past `limits.occurrences`,
    /// before anything of that size is built. Formulas may nest to any
    /// depth.
    ///
    /// Needs the cargo feature `parse` (on by default).
    ///
    /// # Errors
    ///
    /// - [`Error::Parse`] for text that is no sequent;
    /// - [`Refusal::Occurrences`] past `limits.occurrences`;
    /// - [`Refusal::Index`] for more terms than a forest can index,
    ///   whatever the bound;
    /// - [`Refusal::Terms`] when the atoms' arguments unfold to more than
    ///   `limits.terms` terms.
    ///
    /// # Examples
    ///
    /// ```
    /// use deduxit::{Limits, linear::Sequent};
    ///
    /// let sequent = Sequent::parse_within("A, A -o B |- B", &Limits::default())?;
    /// assert_eq!(sequent.to_string(), "⊢ ~A, A ⊗ ~B, B");
    ///
    /// // The text has five terms, more than this bound allows.
    /// let small = Limits::default().with_occurrences(Some(3));
    /// assert!(Sequent::parse_within("A, A -o B |- B", &small).is_err());
    /// # Ok::<(), deduxit::Error>(())
    /// ```
    pub fn parse_within(text: &str, limits: &Limits) -> Result<Self, Error> {
        read(
            text,
            limits.occurrences,
            limits.terms,
            Order::Commutative,
            None,
        )
    }

    /// Parses a sequent as [`parse_within`](Self::parse_within) does, for
    /// a calculus that keeps the order `order`.
    ///
    /// In [`Order::Cyclic`]:
    /// - the dual of a product reverses it: `~(A * B)` reads as
    ///   `~B par ~A`;
    /// - the formulas left of the turnstile come in reverse order, each
    ///   negated: `A, B |- C` is `|- ~B, ~A, C`, the cyclic sequent with
    ///   the same proofs as the two-sided one;
    /// - the two divisions of the Lambek calculus are read: `A \ B` as
    ///   `A -o B` (associating to the right) and `B / A` as `B par ~A`
    ///   (to the left), both binding as loosely as `-o`.
    ///
    /// The formulas then stand in the order the cyclic calculus reads,
    /// which is the occurrence forest's. In [`Order::Commutative`] this is
    /// [`parse_within`](Self::parse_within).
    ///
    /// Needs the cargo feature `parse` (on by default).
    ///
    /// # Errors
    ///
    /// Those of [`parse_within`](Self::parse_within).
    ///
    /// # Examples
    ///
    /// ```
    /// use deduxit::{Limits, linear::{Order, Sequent}};
    ///
    /// let cyclic = Sequent::parse_ordered("a * b |- a * b", Order::Cyclic, &Limits::default())?;
    /// assert_eq!(cyclic.to_string(), "⊢ ~b ⅋ ~a, a ⊗ b");
    /// let commutative: Sequent = "a * b |- a * b".parse()?;
    /// assert_eq!(commutative.to_string(), "⊢ ~a ⅋ ~b, a ⊗ b");
    /// # Ok::<(), deduxit::Error>(())
    /// ```
    pub fn parse_ordered(text: &str, order: Order, limits: &Limits) -> Result<Self, Error> {
        read(text, limits.occurrences, limits.terms, order, None)
    }
}

/// The hint for a negation in intuitionistic text: what to write instead.
const NEGATION: &str = "intuitionistic linear logic has no negation: write a negated formula \
                        on the other side of |- (A |- B, not |- ~A, B), and ~A par B as A -o B";
/// The hint for a par in intuitionistic text.
const PAR: &str = "intuitionistic linear logic has no par: write ~A par B as A -o B";
/// The hint for a `?` in intuitionistic text.
const QUEST: &str = "intuitionistic linear logic has no ?: write ?~A right of |- as !A left of it";
/// The hint for a bottom in intuitionistic text.
const BOT: &str = "intuitionistic linear logic has no bot: write bot right of |- as 1 left of it";

/// Returns the error, with its hint, for the first symbol of `text` that
/// classical linear logic has and intuitionistic linear logic lacks (`~`,
/// `^`, `⅋`, `par`, `|` as a connective, `?`, `⊥`, `bot`), if one starts
/// before byte `before`; else `None`.
///
/// None of these symbols is intuitionistic syntax wherever it stands, so a
/// scan finds them without the parser's state. The scan must cut the text
/// into tokens where the parser does:
/// - `|-` (the turnstile) and `-o` (the implication) are one token each;
/// - an identifier is read whole from where one starts.
///
/// So `bottom` is an atom, `A -obot` is `-o` and then the constant `bot`,
/// and `A |-obot` is the turnstile and then the atom `obot`. The scan runs
/// over the whole text, not a prefix cut at `before`, so that a token
/// across `before`, such as `|-`, is read as the parser reads it.
pub(crate) fn classical(text: &str, before: usize) -> Option<ParseError> {
    let mut chars = text.char_indices().peekable();
    while let Some((at, c)) = chars.next() {
        if at >= before {
            return None;
        }
        let mut end = at + c.len_utf8();
        let mut next_is = |d: char| {
            let is = chars.peek().is_some_and(|&(_, next)| next == d);
            if is {
                chars.next();
            }
            is
        };
        let hint = match c {
            '~' | '^' => NEGATION,
            '⅋' => PAR,
            // The turnstile and the implication, each one token.
            '|' if next_is('-') => continue,
            '-' if next_is('o') => continue,
            '|' => PAR,
            '?' => QUEST,
            '⊥' => BOT,
            _ if starts_identifier(c) => {
                while let Some(&(next, d)) = chars.peek() {
                    if !unicode_ident::is_xid_continue(d) {
                        break;
                    }
                    end = next + d.len_utf8();
                    chars.next();
                }
                match &text[at..end] {
                    "par" => PAR,
                    "bot" => BOT,
                    _ => continue,
                }
            }
            _ => continue,
        };
        return Some(ParseError::spanning(text, at..end, &[]).with_hint(hint));
    }
    None
}

impl std::str::FromStr for Sequent {
    type Err = Error;

    /// Parses a sequent as [`Sequent::parse_within`] does, within the
    /// default [`Limits`].
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse_within(s, &Limits::default())
    }
}

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

    /// A sequent of more terms than the arena may hold is refused, and one
    /// that fills it is read.
    #[test]
    fn refuses_more_terms_than_the_arena_holds() {
        let input = "A |- !A * B";
        assert_eq!(
            Parser::new(input, Some(5), Order::Commutative)
                .sequent(None)
                .unwrap()
                .terms()
                .len(),
            5
        );
        assert!(matches!(
            Parser::new(input, Some(4), Order::Commutative).sequent(None),
            Err(Error::Refused(Refusal::Occurrences {
                occurrences: 5,
                limit: 4
            }))
        ));
    }
}