deduxit 0.5.0

A collection of logic suites: decides, checks, proves step by step and exports sequents of linear logic and of classical, intuitionistic and minimal propositional logic, with checked proofs, Kripke countermodels and Rocq certificates.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

use crate::Error;
use crate::limits::{Limits, Refusal, Space};
use crate::rules::{Associativity, Calculus, Derivation, Discipline, Fixity, Step, TermId};
use crate::rules::{Node, Term, Terms};
use crate::wire::{self, Readable};
use serde::de::{DeserializeSeed, MapAccess, SeqAccess, Visitor};
use serde::ser::{SerializeMap, SerializeSeq};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::BTreeMap;
use std::fmt::{Formatter, Result as FmtResult};

/// The deepest a pattern of a rule file is nested. No rule of a calculus
/// in use comes near it, and a reader that stops there recurses no deeper
/// whatever deserializer it is given.
pub(crate) const DEPTH: u32 = 64;

/// The serialized form of a calculus: a rule file.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct CalculusForm {
    /// The wire level, written only at the top of a document.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "wire::version"
    )]
    pub(crate) version: Option<u32>,
    /// The calculus's name, which a derivation names.
    pub(crate) name: String,
    /// What the calculus is, for a reader.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub(crate) description: String,
    /// The sorts beside `formula`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) sorts: Vec<String>,
    /// The connectives.
    pub(crate) connectives: Vec<ConnectiveForm>,
    /// The zones of a sequent, in the order written.
    pub(crate) sequent: Vec<ZoneForm>,
    /// The schematic variables, by sort.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub(crate) variables: BTreeMap<String, Vec<String>>,
    /// The context variables.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) contexts: Vec<String>,
    /// The rules.
    pub(crate) rules: Vec<RuleForm>,
}

/// The serialized form of a connective.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct ConnectiveForm {
    /// Its name, which terms and patterns use.
    pub(crate) name: String,
    /// How many terms it takes.
    pub(crate) arity: u32,
    /// The sorts of its arguments, then of the term it makes; absent
    /// where all are `formula`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) sorts: Option<Vec<String>>,
    /// What is printed for it, where that is not its name.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) symbol: Option<String>,
    /// Where it is printed among its arguments.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) fixity: Option<Fixity>,
    /// How tightly it binds when printed: a higher number binds tighter.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) precedence: Option<u32>,
    /// How a chain of it is read without brackets.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) associativity: Option<Associativity>,
}

/// The serialized form of a zone of a sequent.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct ZoneForm {
    /// Its name, which a rule's sequents use as a key.
    pub(crate) name: String,
    /// The sort of its members; `formula` where absent.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) sort: Option<String>,
    /// Whether its members are a set, a multiset or a sequence.
    pub(crate) discipline: Discipline,
    /// What is written before it, as `⊢`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) mark: Option<String>,
    /// The fewest members it holds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) least: Option<u32>,
    /// The most members it holds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) most: Option<u32>,
}

/// The serialized form of a rule.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct RuleForm {
    /// Its name, which a derivation's nodes use.
    pub(crate) name: String,
    /// Its premises, in order.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) premises: Vec<PremiseForm>,
    /// Its conclusion.
    #[serde(deserialize_with = "once")]
    pub(crate) conclusion: SequentForm,
    /// The variables matched by atoms new to the conclusion.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) fresh: Vec<String>,
    /// The variables matched by atoms.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub(crate) atomic: Vec<String>,
}

/// The serialized form of a schematic sequent: the entries of each zone,
/// by the zone's name. An absent zone is empty.
pub(crate) type SequentForm = BTreeMap<String, Vec<PatternForm>>;

/// The serialized form of a premise: a schematic sequent, and under
/// `discharges` the hypotheses it discharges.
#[derive(Clone, Debug, Default)]
pub(crate) struct PremiseForm {
    /// The sequent.
    pub(crate) sequent: SequentForm,
    /// The hypotheses the premise discharges, each a sequent of written
    /// members.
    pub(crate) discharges: Vec<SequentForm>,
}

/// The key of a premise that holds what it discharges. No zone has this
/// name.
pub(crate) const DISCHARGES: &str = "discharges";

impl Serialize for PremiseForm {
    /// Writes the zones, then `discharges` where there are any.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut map = serializer.serialize_map(None)?;
        for (zone, entries) in &self.sequent {
            map.serialize_entry(zone, entries)?;
        }
        if !self.discharges.is_empty() {
            map.serialize_entry(DISCHARGES, &self.discharges)?;
        }
        map.end()
    }
}

impl<'de> Deserialize<'de> for PremiseForm {
    /// Reads the zones and `discharges`, refusing a key written twice.
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        /// Reads a premise's map.
        struct Keys;
        impl<'de> Visitor<'de> for Keys {
            type Value = PremiseForm;

            fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {
                f.write_str("a premise: its zones, and what it discharges")
            }

            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<PremiseForm, A::Error> {
                let mut premise = PremiseForm::default();
                let mut discharges = false;
                while let Some(key) = map.next_key::<String>()? {
                    let twice = if key == DISCHARGES {
                        let hypotheses: Vec<Once> = map.next_value()?;
                        premise.discharges = hypotheses.into_iter().map(|h| h.0).collect();
                        std::mem::replace(&mut discharges, true)
                    } else {
                        let entries = map.next_value()?;
                        premise.sequent.insert(key.clone(), entries).is_some()
                    };
                    if twice {
                        return Err(serde::de::Error::custom(format!(
                            "the key {key:?} is written twice"
                        )));
                    }
                }
                Ok(premise)
            }
        }
        deserializer.deserialize_map(Keys)
    }
}

/// A schematic sequent read with every zone's key once. A plain map keeps
/// the last of two equal keys, and a rule whose conclusion wrote `"s"`
/// twice would read as the second alone.
struct Once(SequentForm);

impl<'de> Deserialize<'de> for Once {
    /// Reads the zones, refusing a key written twice.
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        /// Reads a sequent's map.
        struct Keys;
        impl<'de> Visitor<'de> for Keys {
            type Value = Once;

            fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {
                f.write_str("a sequent: the entries of each zone, by the zone's name")
            }

            fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Once, A::Error> {
                let mut sequent = SequentForm::new();
                while let Some(key) = map.next_key::<String>()? {
                    let entries = map.next_value()?;
                    if sequent.insert(key.clone(), entries).is_some() {
                        return Err(serde::de::Error::custom(format!(
                            "the key {key:?} is written twice"
                        )));
                    }
                }
                Ok(Once(sequent))
            }
        }
        deserializer.deserialize_map(Keys)
    }
}

/// Reads a schematic sequent with every zone's key once.
fn once<'de, D: Deserializer<'de>>(deserializer: D) -> Result<SequentForm, D::Error> {
    Once::deserialize(deserializer).map(|once| once.0)
}

/// The serialized form of a pattern: a name, or a connective's name
/// followed by the patterns it is applied to, as an array.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum PatternForm {
    /// A variable, a context or a connective without arguments.
    Name(String),
    /// A connective applied to patterns.
    Apply(String, Vec<PatternForm>),
}

impl Serialize for PatternForm {
    /// Writes a name as a string and an application as an array. A
    /// pattern is nested [`DEPTH`] deep at most, so this recursion is
    /// bounded.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Name(name) => serializer.serialize_str(name),
            Self::Apply(connective, arguments) => {
                let mut seq = serializer.serialize_seq(Some(arguments.len() + 1))?;
                seq.serialize_element(connective)?;
                for argument in arguments {
                    seq.serialize_element(argument)?;
                }
                seq.end()
            }
        }
    }
}

/// Reads a pattern that lies this deep in another.
struct Nested(u32);

impl<'de> DeserializeSeed<'de> for Nested {
    type Value = PatternForm;

    /// Reads a string or an array, refusing an array past [`DEPTH`].
    fn deserialize<D: Deserializer<'de>>(self, deserializer: D) -> Result<PatternForm, D::Error> {
        deserializer.deserialize_any(self)
    }
}

impl<'de> Visitor<'de> for Nested {
    type Value = PatternForm;

    fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {
        f.write_str("a name, or an array of a connective's name and its arguments")
    }

    fn visit_str<E: serde::de::Error>(self, name: &str) -> Result<PatternForm, E> {
        Ok(PatternForm::Name(name.to_owned()))
    }

    fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<PatternForm, A::Error> {
        if self.0 >= DEPTH {
            return Err(serde::de::Error::custom(format!(
                "a pattern is nested deeper than {DEPTH}"
            )));
        }
        let connective: String = seq
            .next_element()?
            .ok_or_else(|| serde::de::Error::custom("an empty array names no connective"))?;
        let mut arguments = Vec::new();
        while let Some(argument) = seq.next_element_seed(Nested(self.0 + 1))? {
            arguments.push(argument);
        }
        Ok(PatternForm::Apply(connective, arguments))
    }
}

impl<'de> Deserialize<'de> for PatternForm {
    /// Reads a pattern nested [`DEPTH`] deep at most.
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        Nested(0).deserialize(deserializer)
    }
}

impl Serialize for Calculus {
    /// Serializes the calculus as the rule file it was read from, at
    /// level 15.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut form = self.form().clone();
        form.version = Some(wire::RULES);
        form.serialize(serializer)
    }
}

impl<'a> Deserialize<'a> for Calculus {
    /// Deserializes a calculus within the default limits, as
    /// [`wire::upgrade`] does.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        Self::read(deserializer, &Limits::default())
    }
}

impl crate::sealed::Readable for Calculus {}

impl Readable for Calculus {
    const FORM: &'static str = "calculus";

    /// Reads a rule file and checks that it is a calculus.
    fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
        let mut form = CalculusForm::deserialize(deserializer)?;
        form.version = None;
        Self::from_form(form, limits).map_err(wire::fail)
    }
}

/// The serialized form of a term of a derivation: an atom of sort
/// `formula` as its name, an atom of another sort as `{"atom": name,
/// "sort": sort}`, a connective applied to earlier terms as `[name,
/// index, …]`.
#[derive(Clone, Debug)]
enum TermForm {
    /// An atom: its name and its sort.
    Atom(String, String),
    /// A connective and the indices of its arguments.
    Apply(String, Vec<u32>),
}

/// The serialized form of an atom of a sort other than `formula`.
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct AtomForm {
    /// The atom's name.
    atom: String,
    /// The name of its sort.
    #[serde(default = "formula")]
    sort: String,
}

/// Returns the name of the sort every calculus has.
fn formula() -> String {
    crate::rules::FORMULA.to_owned()
}

impl Serialize for TermForm {
    /// Writes the term in the shortest of its three forms.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Atom(name, sort) if sort == crate::rules::FORMULA => {
                serializer.serialize_str(name)
            }
            Self::Atom(name, sort) => AtomForm {
                atom: name.clone(),
                sort: sort.clone(),
            }
            .serialize(serializer),
            Self::Apply(connective, arguments) => {
                let mut seq = serializer.serialize_seq(Some(arguments.len() + 1))?;
                seq.serialize_element(connective)?;
                for argument in arguments {
                    seq.serialize_element(argument)?;
                }
                seq.end()
            }
        }
    }
}

impl<'de> Deserialize<'de> for TermForm {
    /// Reads a string, an object or an array.
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        /// Reads a term's three forms.
        struct Forms;
        impl<'de> Visitor<'de> for Forms {
            type Value = TermForm;

            fn expecting(&self, f: &mut Formatter<'_>) -> FmtResult {
                f.write_str("an atom's name, an atom with its sort, or a connective and indices")
            }

            fn visit_str<E: serde::de::Error>(self, name: &str) -> Result<TermForm, E> {
                Ok(TermForm::Atom(name.to_owned(), formula()))
            }

            fn visit_map<A: MapAccess<'de>>(self, map: A) -> Result<TermForm, A::Error> {
                let atom =
                    AtomForm::deserialize(serde::de::value::MapAccessDeserializer::new(map))?;
                Ok(TermForm::Atom(atom.atom, atom.sort))
            }

            fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<TermForm, A::Error> {
                let connective: String = seq.next_element()?.ok_or_else(|| {
                    serde::de::Error::custom("an empty array names no connective")
                })?;
                let mut arguments = Vec::new();
                while let Some(argument) = seq.next_element()? {
                    arguments.push(argument);
                }
                Ok(TermForm::Apply(connective, arguments))
            }
        }
        deserializer.deserialize_any(Forms)
    }
}

/// The serialized form of a node: its sequent as the term indices of
/// each zone, what justifies it, and where it stands.
#[derive(Clone, Debug, Serialize, Deserialize)]
struct NodeForm {
    /// The members of each zone, as indices of terms.
    sequent: Vec<Vec<u32>>,
    /// The rule's name; absent for a hypothesis and an open goal.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    rule: Option<String>,
    /// Whether the node is a hypothesis.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    hypothesis: bool,
    /// The positions of the members the rule finds by position.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    at: Vec<u32>,
    /// The premises, as indices of nodes.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    premises: Vec<u32>,
    /// The node's scope; the root scope where absent.
    #[serde(default, skip_serializing_if = "is_zero")]
    scope: u32,
}

/// Returns whether a scope is the root scope, which is not written.
#[expect(
    clippy::trivially_copy_pass_by_ref,
    reason = "serde's skip_serializing_if passes a reference"
)]
const fn is_zero(scope: &u32) -> bool {
    *scope == 0
}

/// The serialized form of a derivation.
#[derive(Clone, Debug, Serialize, Deserialize)]
struct DerivationForm {
    /// The wire level, written only at the top of a document.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "wire::version"
    )]
    version: Option<u32>,
    /// The name of the calculus the derivation is in.
    calculus: String,
    /// The terms, every argument before the term built from it.
    terms: Vec<TermForm>,
    /// The parent of each scope after the root scope.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    scopes: Vec<u32>,
    /// The nodes, premises before conclusions, the root last.
    nodes: Vec<NodeForm>,
}

impl From<&Derivation> for DerivationForm {
    /// Writes the derivation's form.
    fn from(derivation: &Derivation) -> Self {
        let index = |id: &TermId| id.index() as u32;
        Self {
            version: None,
            calculus: derivation.calculus().to_owned(),
            terms: terms_form(derivation.terms()),
            scopes: derivation.scope_parents().iter().skip(1).copied().collect(),
            nodes: derivation
                .nodes()
                .map(|node| NodeForm {
                    sequent: (0..derivation.zones())
                        .map(|zone| node.zone(zone).iter().map(index).collect())
                        .collect(),
                    rule: match node.step() {
                        Step::Rule(name) => Some(name.to_owned()),
                        Step::Hypothesis | Step::Open => None,
                    },
                    hypothesis: node.step() == Step::Hypothesis,
                    at: node.positions().to_vec(),
                    premises: node.premises().iter().map(|p| p.index() as u32).collect(),
                    scope: node.scope().index() as u32,
                })
                .collect(),
        }
    }
}

/// Returns the forms of every term of `terms`, in the arena's order.
fn terms_form(terms: &Terms) -> Vec<TermForm> {
    (0..terms.len())
        .map(|n| match terms.term(TermId::new(n as u32)) {
            Term::Atom { name, sort } => TermForm::Atom(name.to_owned(), sort.to_owned()),
            Term::Apply {
                connective,
                arguments,
            } => TermForm::Apply(
                connective.to_owned(),
                arguments.iter().map(|id| id.index() as u32).collect(),
            ),
        })
        .collect()
}

/// Reads terms into `terms` and returns the term of each form; equal
/// forms are one term. Refuses more forms than `limits.occurrences`.
fn read_terms(
    forms: &[TermForm],
    terms: &mut Terms,
    limits: &Limits,
) -> Result<Vec<TermId>, Error> {
    if let Some(limit) = limits.occurrences
        && forms.len() as u64 > limit
    {
        return Err(Error::Refused(Refusal::Occurrences {
            occurrences: forms.len() as u64,
            limit,
        }));
    }
    let mut ids: Vec<TermId> = Vec::with_capacity(forms.len());
    for form in forms {
        let id = match form {
            TermForm::Atom(name, sort) => terms.atom(name, sort)?,
            TermForm::Apply(connective, arguments) => {
                let arguments = arguments
                    .iter()
                    .map(|&index| term_at(&ids, index))
                    .collect::<Result<Vec<_>, _>>()?;
                terms.apply(connective, &arguments)?
            }
        };
        ids.push(id);
    }
    Ok(ids)
}

/// Returns the term a form's index names, or the error for one past
/// the forms read.
fn term_at(ids: &[TermId], index: u32) -> Result<TermId, Error> {
    ids.get(index as usize)
        .copied()
        .ok_or(Error::IndexOutOfBounds {
            space: Space::Term,
            index: index as usize,
            len: ids.len(),
        })
}

impl DerivationForm {
    /// Returns the derivation the form holds, its terms within
    /// `limits.occurrences`. Every index is checked; whether it is a
    /// derivation of its calculus is for [`Derivation::check`] to say.
    fn within(self, limits: &Limits) -> Result<Derivation, Error> {
        let zones = self.nodes.first().map_or(0, |node| node.sequent.len());
        let mut derivation = Derivation::new(&self.calculus, zones);
        // Equal terms of the document are one term of the arena.
        let ids = read_terms(&self.terms, derivation.terms_mut(), limits)?;
        let at = term_at;
        for parent in self.scopes {
            derivation.scope(parent)?;
        }
        for form in self.nodes {
            let sequent = form
                .sequent
                .iter()
                .map(|zone| zone.iter().map(|&index| at(&ids, index)).collect())
                .collect::<Result<Vec<Vec<TermId>>, _>>()?;
            let step = match (&form.rule, form.hypothesis) {
                (Some(rule), false) => Step::Rule(rule),
                (None, true) => Step::Hypothesis,
                (None, false) => Step::Open,
                (Some(_), true) => {
                    return Err(Error::Json {
                        form: Derivation::FORM,
                        message: "a node is both a rule's and a hypothesis".to_owned(),
                    });
                }
            };
            derivation.push(Node {
                sequent: &sequent,
                step,
                premises: &form.premises,
                positions: &form.at,
                scope: form.scope,
            })?;
        }
        if derivation.is_empty() {
            return Err(Error::Json {
                form: Derivation::FORM,
                message: "a derivation has at least one node".to_owned(),
            });
        }
        Ok(derivation)
    }
}

impl Serialize for Derivation {
    /// Serializes the derivation as a document at level 15.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut form = DerivationForm::from(self);
        form.version = Some(wire::RULES);
        form.serialize(serializer)
    }
}

impl<'a> Deserialize<'a> for Derivation {
    /// Deserializes a derivation within the default limits, as
    /// [`wire::upgrade`] does.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        Self::read(deserializer, &Limits::default())
    }
}

impl crate::sealed::Readable for Derivation {}

impl Readable for Derivation {
    const FORM: &'static str = "derivation";

    /// Reads a derivation and checks its indices.
    fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
        let form = DerivationForm::deserialize(deserializer)?;
        form.within(limits).map_err(wire::fail)
    }
}

/// The serialized form of a scope of a session.
#[cfg(all(feature = "interactive", feature = "parse"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
struct ScopeForm {
    /// The scope around it.
    #[serde(default, skip_serializing_if = "is_zero")]
    parent: u32,
    /// The node and the premise of it that lie in the scope.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    owner: Option<(u32, u32)>,
    /// The hypotheses it offers, each a sequent of term indices.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    hypotheses: Vec<Vec<Vec<u32>>>,
}

/// The serialized form of a node of a session.
#[cfg(all(feature = "interactive", feature = "parse"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
struct SessionNodeForm {
    /// The members of each zone, as indices of terms.
    sequent: Vec<Vec<u32>>,
    /// The rule's name; absent for a hypothesis and an open goal.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    rule: Option<String>,
    /// Whether the node is a hypothesis.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    hypothesis: bool,
    /// The positions the rule needs.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    at: Vec<u32>,
    /// The premises, as later nodes.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    premises: Vec<u32>,
    /// The node's scope; the root scope where absent.
    #[serde(default, skip_serializing_if = "is_zero")]
    scope: u32,
    /// The scope the node was opened in, where a hypothesis left it.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    opened: Option<u32>,
    /// Whether the node is a line a forward step derived (level 18).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    line: bool,
    /// The derived line that closes the goal (level 18).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    cites: Option<u32>,
}

/// The serialized form of a session.
#[cfg(all(feature = "interactive", feature = "parse"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
struct SessionForm {
    /// The wire level, written only at the top of a document.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "wire::version"
    )]
    version: Option<u32>,
    /// The rule file.
    calculus: CalculusForm,
    /// The terms.
    terms: Vec<TermForm>,
    /// The scopes, the root scope first.
    scopes: Vec<ScopeForm>,
    /// The nodes, the root first.
    nodes: Vec<SessionNodeForm>,
    /// The goals the steps closed, in order.
    #[serde(default)]
    history: Vec<u32>,
}

#[cfg(all(feature = "interactive", feature = "parse"))]
impl Serialize for crate::rules::Interactive {
    /// Serializes the session as a document at level 17, or at 18 where
    /// it holds a line a forward step derived.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use crate::rules::interactive::Done;
        let ids = |sequent: &[Vec<TermId>]| -> Vec<Vec<u32>> {
            sequent
                .iter()
                .map(|zone| zone.iter().map(|id| id.index() as u32).collect())
                .collect()
        };
        let mut calculus = self.calculus().form().clone();
        calculus.version = None;
        let forward = self.nodes.iter().any(|node| node.line);
        let form = SessionForm {
            version: Some(if forward {
                wire::FORWARD
            } else {
                wire::SESSION
            }),
            calculus,
            terms: terms_form(self.terms()),
            scopes: self
                .scopes
                .iter()
                .map(|scope| ScopeForm {
                    parent: scope.parent,
                    owner: scope.owner,
                    hypotheses: scope.hypotheses.iter().map(|h| ids(h)).collect(),
                })
                .collect(),
            nodes: self
                .nodes
                .iter()
                .map(|node| SessionNodeForm {
                    sequent: ids(&node.sequent),
                    rule: match &node.done {
                        Done::Rule(name, _) => Some(name.clone()),
                        Done::Open | Done::Hypothesis | Done::Line(_) => None,
                    },
                    hypothesis: node.done == Done::Hypothesis,
                    at: match &node.done {
                        Done::Rule(_, at) => at.clone(),
                        Done::Open | Done::Hypothesis | Done::Line(_) => Vec::new(),
                    },
                    premises: node.premises.clone(),
                    scope: node.scope,
                    opened: (node.opened != node.scope).then_some(node.opened),
                    line: node.line,
                    cites: match node.done {
                        Done::Line(line) => Some(line),
                        Done::Open | Done::Hypothesis | Done::Rule(..) => None,
                    },
                })
                .collect(),
            history: self.history.clone(),
        };
        form.serialize(serializer)
    }
}

#[cfg(all(feature = "interactive", feature = "parse"))]
impl<'a> Deserialize<'a> for crate::rules::Interactive {
    /// Deserializes a session within the default limits, as
    /// [`wire::upgrade`] does.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        Self::read(deserializer, &Limits::default())
    }
}

#[cfg(all(feature = "interactive", feature = "parse"))]
impl crate::sealed::Readable for crate::rules::Interactive {}

#[cfg(all(feature = "interactive", feature = "parse"))]
impl Readable for crate::rules::Interactive {
    const FORM: &'static str = "session in a calculus";

    /// Reads a session and checks every step it holds.
    fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
        let form = SessionForm::deserialize(deserializer)?;
        session(form, limits).map_err(wire::fail)
    }
}

/// Returns the session a form holds, its calculus read and every step
/// checked, within the limits.
#[cfg(all(feature = "interactive", feature = "parse"))]
fn session(form: SessionForm, limits: &Limits) -> Result<crate::rules::Interactive, Error> {
    use crate::rules::interactive::{Done, Goal, Scope};
    let calculus = Calculus::from_form(form.calculus, limits)?;
    let mut terms = Terms::default();
    let ids = read_terms(&form.terms, &mut terms, limits)?;
    let sequent = |zones: &[Vec<u32>]| -> Result<Vec<Vec<TermId>>, Error> {
        zones
            .iter()
            .map(|zone| zone.iter().map(|&i| term_at(&ids, i)).collect())
            .collect()
    };
    let scopes = form
        .scopes
        .iter()
        .map(|scope| {
            Ok(Scope {
                parent: scope.parent,
                owner: scope.owner,
                hypotheses: scope
                    .hypotheses
                    .iter()
                    .map(|h| sequent(h))
                    .collect::<Result<_, Error>>()?,
            })
        })
        .collect::<Result<Vec<_>, Error>>()?;
    let nodes = form
        .nodes
        .iter()
        .map(|node| {
            let done = match (&node.rule, node.hypothesis, node.cites) {
                (Some(rule), false, None) => Done::Rule(rule.clone(), node.at.clone()),
                (None, true, None) => Done::Hypothesis,
                (None, false, Some(line)) => Done::Line(line),
                (None, false, None) => Done::Open,
                _ => {
                    return Err(Error::InconsistentSession {
                        reason: "a node is more than one of a rule's, a hypothesis and a line's",
                    });
                }
            };
            Ok(Goal {
                sequent: sequent(&node.sequent)?,
                done,
                premises: node.premises.clone(),
                scope: node.scope,
                opened: node.opened.unwrap_or(node.scope),
                line: node.line,
            })
        })
        .collect::<Result<Vec<_>, Error>>()?;
    crate::rules::Interactive::from_parts(calculus, terms, scopes, nodes, form.history, limits)
}