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
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

use super::sequents::{FoExpression, Sequent};
use crate::limits::Limits;
use crate::linear::fragment::Mode;
use crate::linear::occurrences::{Forest, Member};
use crate::linear::proofs::{Branch, Named, Node, NodeId, Proof as Prf};
use crate::wire::{self, Readable};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// The serialized form of a proof node: the rule's tag with the member ids
/// it names and its premises' node indices. The tags are part of the
/// interchange format, so renaming one breaks it.
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
#[serde(rename = "N")]
pub(super) enum Step {
    /// The axiom on two literals.
    #[serde(rename = "ax")]
    Ax(u32, u32),
    /// `⊗` on an occurrence, from the left and the right premise.
    #[serde(rename = "⊗")]
    Tensor(u32, u32, u32),
    /// `⅋` on an occurrence, from a premise.
    #[serde(rename = "⅋")]
    Par(u32, u32),
    /// `1` on an occurrence.
    #[serde(rename = "1")]
    One(u32),
    /// `⊥` on an occurrence, from a premise.
    #[serde(rename = "⊥")]
    Bot(u32, u32),
    /// `&` on an occurrence, from the left and the right premise.
    #[serde(rename = "&")]
    With(u32, u32, u32),
    /// `⊕₁` on an occurrence, from a premise.
    #[serde(rename = "⊕₁")]
    PlusLeft(u32, u32),
    /// `⊕₂` on an occurrence, from a premise.
    #[serde(rename = "⊕₂")]
    PlusRight(u32, u32),
    /// `⊤` on an occurrence.
    #[serde(rename = "⊤")]
    Top(u32),
    /// Promotion on an occurrence, from a premise.
    #[serde(rename = "!")]
    Bang(u32, u32),
    /// The `?` step on an occurrence, from a premise.
    #[serde(rename = "?")]
    Quest(u32, u32),
    /// A copy of an occurrence, from a premise.
    #[serde(rename = "copy")]
    Copy(u32, u32),
    /// Weakening of an occurrence, from a premise.
    #[serde(rename = "wk")]
    Weaken(u32, u32),
    /// Mix, from two premises.
    #[serde(rename = "mix")]
    Mix(u32, u32),
    /// The cut on an occurrence of a cut formula, from two premises.
    #[serde(rename = "cut")]
    Cut(u32, u32, u32),
    /// `∀` on a member, with its eigenvariable, from a premise.
    #[serde(rename = "∀")]
    Forall(u32, u32, u32),
    /// `∃` on a member, with its witness, a term, from a premise.
    #[serde(rename = "∃")]
    Exists(u32, u32, u32),
}

/// The serialized form of a proof's instance table. Its keys:
/// - `members`: for each member past the forest, its occurrence and
///   frame;
/// - `frames`: for each frame, its parent (`null` for an outermost
///   binder's frame) and its term;
/// - `terms`: the proof's terms, numbered on from the sequent's `fo`
///   terms, an eigenvariable written `{"E": k}`.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub(super) struct Instances {
    /// The members, each `[occurrence, frame]`.
    members: Vec<(u32, u32)>,
    /// The frames, each `[parent, term]`.
    frames: Vec<(Option<u32>, u32)>,
    /// The proof's terms.
    terms: Vec<FoExpression>,
}

impl Instances {
    /// Returns the form of a proof's table over `forest`.
    fn of(table: &crate::linear::Instances, forest: &Forest) -> Self {
        use crate::linear::sequents::FoTerm;
        let terms = crate::linear::occurrences::instances::Terms {
            fo: &forest.sequent().fo,
            table,
        };
        let fo = |t: &FoTerm| match *t {
            FoTerm::Bound(i) => FoExpression::Bound(i),
            FoTerm::Eigen(a) => FoExpression::Eigen(a.get()),
            FoTerm::Meta(_) => unreachable!("a proof's table holds no metavariable"),
            FoTerm::App(f, args) => {
                FoExpression::App(f.get(), terms.list(args).iter().map(|t| t.get()).collect())
            }
        };
        Self {
            members: table
                .members
                .iter()
                .map(|&(o, f)| (o.get(), f.get()))
                .collect(),
            frames: table
                .frames
                .iter()
                .map(|&(p, t)| (p.map(crate::linear::FrameId::get), t.get()))
                .collect(),
            terms: table.terms().iter().map(fo).collect(),
        }
    }

    /// Returns the table over `forest` that the form holds, its entries
    /// within `limits.terms`. Whether it is well formed is for the proof's
    /// constructor to check.
    fn within(
        self,
        forest: &Forest,
        limits: &Limits,
    ) -> Result<crate::linear::Instances, crate::Error> {
        use crate::linear::occurrences::{FrameId, OccId};
        use crate::linear::sequents::{Eigen, FoTerm, FoTermId, Symbol};
        let entries = (self.members.len() as u64)
            .saturating_add(self.frames.len() as u64)
            .saturating_add(self.terms.len() as u64);
        if let Some(limit) = limits.terms
            && entries > limit
        {
            return Err(crate::Error::Refused(crate::limits::Refusal::Terms {
                terms: entries,
                limit,
            }));
        }
        let mut table = crate::linear::Instances::new(forest);
        for term in self.terms {
            match term {
                FoExpression::Bound(i) => {
                    table.push_term(FoTerm::Bound(i));
                }
                FoExpression::Eigen(k) => {
                    table.eigen(Eigen::new(k));
                }
                FoExpression::App(f, items) => {
                    let items: Vec<FoTermId> = items.into_iter().map(FoTermId::new).collect();
                    table.apply(Symbol::new(f), &items);
                }
            }
        }
        for (parent, term) in self.frames {
            table.frame(parent.map(FrameId::new), FoTermId::new(term));
        }
        for (o, f) in self.members {
            table.member(OccId::new(o), FrameId::new(f));
        }
        Ok(table)
    }
}

/// The serialized form of a proof: its level at the top of a document,
/// its sequent and its nodes, and where the proof has them, the mode it
/// is meant for, the goal it concludes and its instance table. Premises come
/// before their conclusions, and the root is last.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub(super) struct Proof {
    /// 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 sequent proved.
    sequent: Sequent,
    /// The nodes.
    nodes: Vec<Step>,
    /// The mode the proof is meant for, where recorded.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    mode: Option<Mode>,
    /// The goal the root concludes, absent for the sequent's roots.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    goal: Option<Vec<u32>>,
    /// The instance table of a proof whose sequent has binders.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    instances: Option<Instances>,
}

impl From<Node> for Step {
    /// Converts a node into its serialized form.
    fn from(n: Node) -> Self {
        use Node::*;
        use Step as S;
        let (o, n_) = (|o: Member| o.get(), |p: NodeId| p.get());
        match n {
            Ax(a, b) => S::Ax(o(a), o(b)),
            Tensor(x, l, r) => S::Tensor(o(x), n_(l), n_(r)),
            Par(x, p) => S::Par(o(x), n_(p)),
            One(x) => S::One(o(x)),
            Bot(x, p) => S::Bot(o(x), n_(p)),
            With(x, l, r) => S::With(o(x), n_(l), n_(r)),
            Plus(x, Branch::Left, p) => S::PlusLeft(o(x), n_(p)),
            Plus(x, Branch::Right, p) => S::PlusRight(o(x), n_(p)),
            Top(x) => S::Top(o(x)),
            Bang(x, p) => S::Bang(o(x), n_(p)),
            Quest(x, p) => S::Quest(o(x), n_(p)),
            Copy(x, p) => S::Copy(o(x), n_(p)),
            Weaken(x, p) => S::Weaken(o(x), n_(p)),
            Mix(l, r) => S::Mix(n_(l), n_(r)),
            Cut(a, l, r) => S::Cut(o(a), n_(l), n_(r)),
            Forall(x, a, p) => S::Forall(o(x), a.get(), n_(p)),
            Exists(x, w, p) => S::Exists(o(x), w.get(), n_(p)),
        }
    }
}

impl From<Step> for Node {
    /// Converts a serialized step back into a node.
    fn from(s: Step) -> Self {
        use Node as N;
        use Step::*;
        let (o, n) = (Member::new, NodeId::new);
        match s {
            Ax(a, b) => N::Ax(o(a), o(b)),
            Tensor(x, l, r) => N::Tensor(o(x), n(l), n(r)),
            Par(x, p) => N::Par(o(x), n(p)),
            One(x) => N::One(o(x)),
            Bot(x, p) => N::Bot(o(x), n(p)),
            With(x, l, r) => N::With(o(x), n(l), n(r)),
            PlusLeft(x, p) => N::Plus(o(x), Branch::Left, n(p)),
            PlusRight(x, p) => N::Plus(o(x), Branch::Right, n(p)),
            Top(x) => N::Top(o(x)),
            Bang(x, p) => N::Bang(o(x), n(p)),
            Quest(x, p) => N::Quest(o(x), n(p)),
            Copy(x, p) => N::Copy(o(x), n(p)),
            Weaken(x, p) => N::Weaken(o(x), n(p)),
            Mix(l, r) => N::Mix(n(l), n(r)),
            Cut(a, l, r) => N::Cut(o(a), n(l), n(r)),
            Forall(x, a, p) => N::Forall(o(x), crate::linear::Eigen::new(a), n(p)),
            Exists(x, w, p) => N::Exists(o(x), crate::linear::sequents::FoTermId::new(w), n(p)),
        }
    }
}

impl Proof {
    /// Returns the proof's keys as an outcome holds them: the sequent, the
    /// nodes, the goal and the instance table. The outcome writes its own
    /// `version` and `mode`.
    pub(super) fn keys(p: &Prf) -> Proof {
        Proof {
            version: None,
            sequent: Sequent::from(p.sequent()),
            nodes: p.nodes().iter().copied().map(Step::from).collect(),
            mode: None,
            goal: p.goal().map(|goal| goal.iter().map(|m| m.get()).collect()),
            instances: p.instances().map(|table| Instances::of(table, p.forest())),
        }
    }

    /// Returns the proof that an outcome's keys hold, with the outcome's
    /// mode.
    pub(super) const fn of_keys(
        sequent: Sequent,
        nodes: Vec<Step>,
        mode: Mode,
        goal: Option<Vec<u32>>,
        instances: Option<Instances>,
    ) -> Proof {
        Proof {
            version: None,
            sequent,
            nodes,
            mode: Some(mode),
            goal,
            instances,
        }
    }

    /// Returns the proof as a document: its level, its keys and its mode.
    fn document(p: &Prf) -> Proof {
        Proof {
            version: Some(wire::level_in(p.mode()).max(wire::level_of_sequent(p.sequent()))),
            mode: p.mode(),
            ..Proof::keys(p)
        }
    }

    /// Returns the proof the form holds, its forest built within `limits`.
    /// It checks the bounds and the order of the nodes, not the proof, and
    /// refuses an instance table beside a goal off the roots.
    pub(super) fn within(self, limits: &Limits) -> Result<Prf, crate::Error> {
        let sequent = crate::linear::Sequent::try_from(self.sequent)?;
        let forest = Forest::from_owned(sequent, limits)?;
        let nodes: Vec<Node> = self.nodes.into_iter().map(Node::from).collect();
        // The root is the last node, whose index must be a node id.
        let Ok(root) = u32::try_from(nodes.len().saturating_sub(1)) else {
            return Err(crate::Error::Refused(crate::limits::Refusal::Index {
                what: crate::limits::Space::Node,
                count: nodes.len() as u64,
                most: u64::from(u32::MAX),
            }));
        };
        let root = NodeId::new(root);
        let proof = match (self.goal, self.instances) {
            (None, Some(instances)) => {
                let table = instances.within(&forest, limits)?;
                Prf::with_instances(forest, table, nodes, root)?
            }
            (Some(_), Some(_)) => {
                return Err(crate::Error::Json {
                    form: "proof",
                    message: "a proof of a goal off the roots has no instance table".to_owned(),
                });
            }
            (None, None) => Prf::new(forest, nodes, root)?,
            (Some(goal), None) => {
                let goal: Vec<Member> = goal.into_iter().map(Member::new).collect();
                Prf::new_of_goal(forest, &goal, nodes, root)?
            }
        };
        Ok(match self.mode {
            Some(mode) => proof.with_mode(mode),
            None => proof,
        })
    }
}

impl serde::Serialize for Prf {
    /// Serializes the proof as a document.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        Proof::document(self).serialize(serializer)
    }
}

impl<'a> serde::Deserialize<'a> for Prf {
    /// Deserializes a proof 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 Prf {}

impl Readable for Prf {
    const FORM: &'static str = "proof";

    /// Reads a proof. Builds its forest within the limits and checks the
    /// bounds and the order of its nodes, not the proof.
    fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
        Proof::deserialize(deserializer)?
            .within(limits)
            .map_err(wire::fail)
    }
}

/// A step of a cut elimination on a proof, as its record writes it.
#[derive(Serialize)]
struct StepForm {
    /// The cut reduced, a node of the proof the step was taken on.
    cut: u32,
    /// The occurrence of the cut formula.
    formula: u32,
    /// The case.
    case: crate::linear::proofs::cut::Case,
    /// The node the step acted at besides the cut.
    #[serde(skip_serializing_if = "Option::is_none")]
    above: Option<u32>,
}

/// A cut elimination on a proof, as its record writes it.
#[derive(Serialize)]
struct EliminationForm<'a> {
    /// The wire level.
    version: u32,
    /// The proof reached, nested.
    proof: Proof,
    /// The steps.
    steps: Vec<StepForm>,
    /// `cut_free`, or `refused` with the reason.
    end: &'static str,
    /// Why the elimination was refused, in an error's form.
    #[serde(skip_serializing_if = "Option::is_none")]
    reason: Option<&'a crate::Error>,
}

impl serde::Serialize for crate::linear::proofs::cut::Elimination {
    /// Serializes the elimination as a document: the proof reached, the
    /// steps and how it ended.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        use crate::linear::proofs::cut::End;
        let reason = match &self.end {
            End::CutFree => None,
            End::Refused(refusal) => Some(crate::Error::Refused(refusal.clone())),
        };
        let document = Proof::document(&self.proof);
        EliminationForm {
            version: document.version.unwrap_or(wire::BASE),
            proof: Proof {
                version: None,
                ..document
            },
            steps: self
                .steps
                .iter()
                .map(|step| StepForm {
                    cut: step.cut.get(),
                    formula: step.formula.get(),
                    case: step.case,
                    above: step.above.map(NodeId::get),
                })
                .collect(),
            end: if reason.is_some() {
                "refused"
            } else {
                "cut_free"
            },
            reason: reason.as_ref(),
        }
        .serialize(serializer)
    }
}

impl serde::Serialize for Named {
    /// Serializes the rule as its name.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.name())
    }
}

impl<'a> serde::Deserialize<'a> for Named {
    /// Deserializes a rule from its name, as `Named::from_str` reads it.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        let name = <std::borrow::Cow<'a, str>>::deserialize(deserializer)?;
        name.parse().map_err(serde::de::Error::custom)
    }
}