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

//! The translations into linear logic. Each is a table of patterns. Per
//! connective and per translation function (the side for the classical
//! translation, `t₀` or `t₁` for the 0/1 one), a pattern gives how many
//! `!` stand on top of the image, the linear connective under them, and
//! each operand with its function and the `!` added above it. The image
//! of a sequent is built from the table bottom-up over the arena. The
//! read-back walks the forest of the image with the same table, so it
//! knows every occurrence as the image of an ordinary formula.

use super::{Formulas, Logic, Node, NodeId, Sequent, Side, Translation};
use crate::hash::HashMap;
use crate::linear::sequents::{Atom, Term, TermId};
use crate::{Error, linear::Mode};

/// The linear connective at the top of an image, under its `!`s.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Core {
    /// An atom; false in minimal logic is the atom [`FALSE`].
    Atom,
    /// A unit, as it stands right of `⊢`.
    Unit(Term),
    /// `⊗`
    Tensor,
    /// `⅋`
    Par,
    /// `&`
    With,
    /// `⊕`
    Plus,
    /// `⊸`, whose antecedent stands on the other side.
    Lollipop,
    /// No connective: the image is that of the operand, whose function is
    /// given (the classical negation).
    Pass,
}

/// An operand of a pattern: the subformula, its translation function and
/// the `!`s put above its image.
pub(super) type Operand = (NodeId, u8, u8);

/// The image of a formula under one translation function.
#[derive(Clone, Copy, Debug)]
pub(super) struct Pattern {
    /// The `!`s on top.
    pub(super) bangs: u8,
    /// The connective under them.
    pub(super) core: Core,
    /// Its operands, in order.
    pub(super) operands: [Option<Operand>; 2],
}

/// The name of the atom that false becomes in minimal logic. No atom of
/// an ordinary sequent can have it, since `false` is a keyword of the
/// ordinary syntax.
pub const FALSE: &str = "false";

/// The classical translation's function for a formula right of `⊢`.
const RIGHT: u8 = 0;
/// The classical translation's function for a formula left of `⊢`.
const LEFT: u8 = 1;
/// The 0/1 translation's negative function `t₀`.
const T0: u8 = 0;
/// The 0/1 translation's positive function `t₁`.
const T1: u8 = 1;

/// The extra nodes a translation refers to: the two implications of every
/// equivalence, and false, since the translations into ILL take `¬A` as
/// `A → false`.
#[derive(Clone, Debug)]
pub(super) struct Extra {
    /// Per node, the implications `A → B` and `B → A` of an equivalence.
    pub(super) iff: HashMap<NodeId, (NodeId, NodeId)>,
    /// The node of false.
    pub(super) falsity: NodeId,
}

impl Extra {
    /// Adds the extra nodes of every formula of the arena to it.
    pub(super) fn add(formulas: &mut Formulas) -> Result<Self, Error> {
        let mut iff = HashMap::default();
        for n in 0..formulas.len() {
            let id = NodeId(n as u32);
            if let Node::Iff(a, b) = formulas.node(id) {
                let pair = (
                    formulas.add(Node::Implies(a, b))?,
                    formulas.add(Node::Implies(b, a))?,
                );
                iff.insert(id, pair);
            }
        }
        let falsity = formulas.add(Node::False)?;
        Ok(Self { iff, falsity })
    }
}

/// Returns the pattern of the formula `id` under `function` of the
/// translation, in `logic`.
pub(super) fn pattern(
    formulas: &Formulas,
    extra: &Extra,
    translation: Translation,
    logic: Logic,
    id: NodeId,
    function: u8,
) -> Pattern {
    use Core::*;
    let node = formulas.node(id);
    let make = |bangs, core, a: Option<Operand>, b: Option<Operand>| Pattern {
        bangs,
        core,
        operands: [a, b],
    };
    let falsity = extra.falsity;
    // An equivalence's implications, read as a conjunction.
    let (forward, backward) = match node {
        Node::Iff(..) => extra.iff[&id],
        Node::Atom(_)
        | Node::True
        | Node::False
        | Node::Not(_)
        | Node::And(..)
        | Node::Or(..)
        | Node::Implies(..) => (id, id),
    };
    let minimal_false = logic == Logic::Minimal && node == Node::False;
    match translation {
        Translation::Affine => {
            let (f, flip) = (function, 1 - function);
            let right = function == RIGHT;
            match node {
                Node::Atom(_) => make(0, Atom, None, None),
                Node::True => make(
                    0,
                    Unit(if right { Term::Top } else { Term::Bot }),
                    None,
                    None,
                ),
                Node::False => make(
                    0,
                    Unit(if right { Term::Bot } else { Term::Top }),
                    None,
                    None,
                ),
                Node::Not(a) => make(0, Pass, Some((a, flip, 0)), None),
                Node::And(a, b) => make(
                    0,
                    if right { With } else { Par },
                    Some((a, f, 0)),
                    Some((b, f, 0)),
                ),
                Node::Or(a, b) => make(
                    0,
                    if right { Par } else { With },
                    Some((a, f, 0)),
                    Some((b, f, 0)),
                ),
                Node::Implies(a, b) => make(
                    0,
                    if right { Par } else { With },
                    Some((a, flip, 0)),
                    Some((b, f, 0)),
                ),
                Node::Iff(..) => make(
                    0,
                    if right { With } else { Par },
                    Some((forward, f, 0)),
                    Some((backward, f, 0)),
                ),
            }
        }
        // Minimal logic's false is an atom, with an atom's `!`s.
        _ if minimal_false => make(
            u8::from(translation == Translation::CallByValue),
            Atom,
            None,
            None,
        ),
        Translation::CallByName => match node {
            Node::Atom(_) => make(0, Atom, None, None),
            Node::True => make(0, Unit(Term::Top), None, None),
            Node::False => make(0, Unit(Term::Zero), None, None),
            Node::Not(a) => make(0, Lollipop, Some((a, 0, 1)), Some((falsity, 0, 0))),
            Node::And(a, b) => make(0, With, Some((a, 0, 0)), Some((b, 0, 0))),
            Node::Or(a, b) => make(0, Plus, Some((a, 0, 1)), Some((b, 0, 1))),
            Node::Implies(a, b) => make(0, Lollipop, Some((a, 0, 1)), Some((b, 0, 0))),
            Node::Iff(..) => make(0, With, Some((forward, 0, 0)), Some((backward, 0, 0))),
        },
        Translation::CallByValue => match node {
            Node::Atom(_) => make(1, Atom, None, None),
            Node::True => make(0, Unit(Term::One), None, None),
            Node::False => make(0, Unit(Term::Zero), None, None),
            Node::Not(a) => make(1, Lollipop, Some((a, 0, 0)), Some((falsity, 0, 0))),
            Node::And(a, b) => make(0, Tensor, Some((a, 0, 0)), Some((b, 0, 0))),
            Node::Or(a, b) => make(0, Plus, Some((a, 0, 0)), Some((b, 0, 0))),
            Node::Implies(a, b) => make(1, Lollipop, Some((a, 0, 0)), Some((b, 0, 0))),
            Node::Iff(..) => make(0, Tensor, Some((forward, 0, 0)), Some((backward, 0, 0))),
        },
        Translation::ZeroOne if function == T0 => match node {
            Node::Atom(_) => make(0, Atom, None, None),
            Node::True => make(0, Unit(Term::Top), None, None),
            Node::False => make(0, Unit(Term::Zero), None, None),
            Node::Not(a) => make(0, Lollipop, Some((a, T1, 1)), Some((falsity, T0, 1))),
            Node::And(a, b) => make(0, With, Some((a, T0, 1)), Some((b, T0, 1))),
            Node::Or(a, b) => make(0, Plus, Some((a, T0, 1)), Some((b, T0, 1))),
            Node::Implies(a, b) => make(0, Lollipop, Some((a, T1, 1)), Some((b, T0, 1))),
            Node::Iff(..) => make(0, With, Some((forward, T0, 1)), Some((backward, T0, 1))),
        },
        Translation::ZeroOne => match node {
            Node::Atom(_) => make(0, Atom, None, None),
            Node::True => make(0, Unit(Term::One), None, None),
            Node::False => make(0, Unit(Term::Zero), None, None),
            Node::Not(a) => make(1, Lollipop, Some((a, T0, 1)), Some((falsity, T1, 0))),
            Node::And(a, b) => make(1, With, Some((a, T1, 0)), Some((b, T1, 0))),
            Node::Or(a, b) => make(0, Plus, Some((a, T1, 1)), Some((b, T1, 1))),
            Node::Implies(a, b) => make(1, Lollipop, Some((a, T0, 1)), Some((b, T1, 0))),
            Node::Iff(..) => make(1, With, Some((forward, T1, 0)), Some((backward, T1, 0))),
        },
    }
}

/// What a root formula of the image is: the ordinary formula, its
/// translation function, the `!`s above its pattern's, and its side.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Root {
    /// The ordinary formula.
    pub(super) node: NodeId,
    /// Its translation function.
    pub(super) function: u8,
    /// The `!`s on top of its image, its pattern's included.
    pub(super) bangs: u8,
    /// The side of `⊢` it stands on.
    pub(super) side: Side,
}

/// The image of an ordinary sequent under a translation: the linear
/// sequent, stored one-sided as every [`Sequent`](crate::linear::Sequent)
/// is, the mode it is decided in, and what the read-back needs to map a
/// proof of it back to the ordinary formulas.
#[derive(Clone, Debug)]
pub struct Image {
    /// The linear sequent.
    pub(super) sequent: crate::linear::Sequent,
    /// Its mode: affine classical, or intuitionistic.
    pub(super) mode: Mode,
    /// The logic.
    pub(super) logic: Logic,
    /// The translation.
    pub(super) translation: Translation,
    /// The ordinary sequent decided: the one given, with false as the goal
    /// of an intuitionistic or minimal sequent that has none.
    pub(super) ordinary: Sequent,
    /// The extra nodes, which the arena of `ordinary` holds.
    pub(super) extra: Extra,
    /// Per root of the linear sequent, in its order, what it is.
    pub(super) roots: Vec<Root>,
}

impl Image {
    /// Returns the linear sequent.
    pub fn sequent(&self) -> &crate::linear::Sequent {
        &self.sequent
    }

    /// Returns the mode the image is decided in: classical and affine for
    /// the affine translation, intuitionistic for the others.
    pub fn mode(&self) -> Mode {
        self.mode
    }

    /// Returns the logic.
    pub fn logic(&self) -> Logic {
        self.logic
    }

    /// Returns the translation.
    pub fn translation(&self) -> Translation {
        self.translation
    }

    /// Returns the ordinary sequent the image is of: the one translated,
    /// with false right of `⊢` where an intuitionistic or minimal sequent
    /// has nothing there.
    pub fn ordinary(&self) -> &Sequent {
        &self.ordinary
    }
}

/// Returns the number of an ILL image's antecedents, the hypotheses'
/// images.
///
/// # Errors
///
/// [`Refusal::Index`](crate::Refusal::Index) for more than `u32::MAX`, the
/// most a sequent's `antecedents` holds: a hypothesis may be written many
/// times over one node of the arena, so the arena's own bound does not
/// keep the count below it.
fn antecedents(hypotheses: usize) -> Result<u32, Error> {
    u32::try_from(hypotheses).map_err(|_| {
        Error::Refused(crate::limits::Refusal::Index {
            what: crate::limits::Space::Member,
            count: u64::try_from(hypotheses).unwrap_or(u64::MAX),
            most: u64::from(u32::MAX),
        })
    })
}

/// Returns the image of an ordinary sequent under a translation, for
/// deciding it in `logic`. The sequent is valid exactly when the image is
/// provable in the image's [`mode`](Image::mode).
///
/// # Errors
///
/// [`Error::Translation`] when the translation does not decide the logic
/// ([`Translation::decides`]), [`Error::Succedents`] for an intuitionistic
/// or minimal sequent with more than one formula right of `⊢`, and
/// [`Refusal::Occurrences`](crate::Refusal::Occurrences) for an image that
/// unfolds to more occurrences than `limits.occurrences` or than an arena
/// holds, before a forest of it is laid out, or
/// [`Refusal::Index`](crate::Refusal::Index) for more than `u32::MAX`
/// hypotheses.
#[expect(
    clippy::missing_panics_doc,
    reason = "the expects state facts of the pattern table the translation builds from"
)]
pub fn translate(
    sequent: &Sequent,
    logic: Logic,
    translation: Translation,
    limits: &crate::Limits,
) -> Result<Image, Error> {
    if !translation.decides(logic) {
        return Err(Error::Translation { translation, logic });
    }
    let mut ordinary = sequent.clone();
    let classical = logic == Logic::Classical;
    if !classical && ordinary.right.len() > 1 {
        return Err(Error::Succedents {
            count: ordinary.right.len(),
        });
    }
    let extra = Extra::add(&mut ordinary.formulas)?;
    if !classical && ordinary.right.is_empty() {
        ordinary.right.push(extra.falsity);
    }
    let formulas = &ordinary.formulas;
    let functions: u8 = match translation {
        Translation::Affine | Translation::ZeroOne => 2,
        Translation::CallByName | Translation::CallByValue => 1,
    };

    // Every node's image under every function, right of `⊢` and dual, in
    // index order, so that each operand's image is made before its
    // formula's. The extra nodes may stand after the formulas that use
    // them, so they are made earlier: an equivalence's implications just
    // before it, since their operands precede both.
    let mut builder = Builder::default();
    let mut images: Vec<Option<(TermId, TermId)>> = vec![None; formulas.len() * functions as usize];
    let slot = |id: NodeId, function: u8| id.index() * functions as usize + function as usize;
    // False first, which a negation refers to wherever it stands.
    let mut order = Vec::with_capacity(formulas.len() + 1);
    order.push(extra.falsity);
    for n in 0..formulas.len() {
        let id = NodeId(n as u32);
        if let Some(&(forward, backward)) = extra.iff.get(&id) {
            order.extend([forward, backward]);
        }
        order.push(id);
    }
    for id in order {
        for function in 0..functions {
            if images[slot(id, function)].is_some() {
                continue;
            }
            let pattern = pattern(formulas, &extra, translation, logic, id, function);
            let operand =
                |(k, f, bangs): Operand, b: &mut Builder| -> Result<(TermId, TermId), Error> {
                    let (mut positive, mut negative) =
                        images[slot(k, f)].expect("an operand precedes its formula");
                    for _ in 0..bangs {
                        positive = b.add(Term::Bang(positive))?;
                        negative = b.add(Term::Quest(negative))?;
                    }
                    Ok((positive, negative))
                };
            let a = pattern.operands[0]
                .map(|o| operand(o, &mut builder))
                .transpose()?;
            let b = pattern.operands[1]
                .map(|o| operand(o, &mut builder))
                .transpose()?;
            let mut image = match pattern.core {
                Core::Atom => {
                    let name = match formulas.node(id) {
                        Node::Atom(a) => formulas.atom_name(a),
                        Node::True
                        | Node::False
                        | Node::Not(_)
                        | Node::And(..)
                        | Node::Or(..)
                        | Node::Implies(..)
                        | Node::Iff(..) => FALSE,
                    };
                    let atom = builder.atom(name);
                    let (var, dual) = (
                        builder.add(Term::Atom(atom))?,
                        builder.add(Term::DualAtom(atom))?,
                    );
                    // The classical translation reads an atom left of `⊢`
                    // as its negation.
                    if classical && function == LEFT {
                        (dual, var)
                    } else {
                        (var, dual)
                    }
                }
                Core::Unit(unit) => (builder.add(unit)?, builder.add(unit.dual())?),
                Core::Pass => a.expect("a negation has an operand"),
                core @ Core::Tensor
                | core @ Core::Par
                | core @ Core::With
                | core @ Core::Plus
                | core @ Core::Lollipop => {
                    let ((pa, na), (pb, nb)) = (a.expect("binary"), b.expect("binary"));
                    let (positive, negative) = match core {
                        Core::Tensor => (Term::Tensor(pa, pb), Term::Par(na, nb)),
                        Core::Par => (Term::Par(pa, pb), Term::Tensor(na, nb)),
                        Core::With => (Term::With(pa, pb), Term::Plus(na, nb)),
                        Core::Plus => (Term::Plus(pa, pb), Term::With(na, nb)),
                        Core::Atom | Core::Unit(_) | Core::Lollipop | Core::Pass => {
                            (Term::Par(na, pb), Term::Tensor(pa, nb))
                        }
                    };
                    (builder.add(positive)?, builder.add(negative)?)
                }
            };
            for _ in 0..pattern.bangs {
                image = (
                    builder.add(Term::Bang(image.0))?,
                    builder.add(Term::Quest(image.1))?,
                );
            }
            images[slot(id, function)] = Some(image);
        }
    }

    // The roots. Classically every formula stands right of the one-sided
    // sequent's `⊢`, a hypothesis under the function for the left side; in
    // ILL a hypothesis stands as its dual.
    let mut roots = Vec::with_capacity(ordinary.left.len() + ordinary.right.len());
    let mut terms = Vec::with_capacity(roots.capacity());
    for (side, list) in [(Side::Left, &ordinary.left), (Side::Right, &ordinary.right)] {
        for &node in list {
            let (function, extra_bang) = match (translation, side) {
                (Translation::Affine, Side::Left) => (LEFT, 0),
                (Translation::Affine, Side::Right) => (RIGHT, 0),
                (Translation::CallByName, Side::Left) => (0, 1),
                (Translation::ZeroOne, Side::Left) => (T0, 1),
                (Translation::ZeroOne, Side::Right) => (T1, 0),
                _ => (0, 0),
            };
            let pattern = pattern(formulas, &extra, translation, logic, node, function);
            let (mut positive, mut negative) =
                images[slot(node, function)].expect("every image is made");
            for _ in 0..extra_bang {
                positive = builder.add(Term::Bang(positive))?;
                negative = builder.add(Term::Quest(negative))?;
            }
            let dual = side == Side::Left && !classical;
            terms.push(if dual { negative } else { positive });
            roots.push(Root {
                node,
                function,
                bangs: pattern.bangs + extra_bang,
                side,
            });
        }
    }

    // Classically every image stands right of `⊢`; in ILL the hypotheses'
    // duals, the first roots, stand left of it.
    let antecedents = if classical {
        0
    } else {
        antecedents(ordinary.left.len())?
    };
    let mut linear = crate::linear::Sequent {
        terms: builder.terms,
        roots: terms,
        atoms: builder.atoms,
        antecedents: Some(antecedents),
        cuts: vec![],
        fo: crate::linear::sequents::fo::FirstOrder::new(),
    };
    linear.optimize();
    let mode = if classical {
        Mode::CLASSICAL.with_affine()
    } else {
        Mode::INTUITIONISTIC
    };
    let occurrences = linear.occurrences();
    if let Some(limit) = limits.occurrences
        && occurrences > limit
    {
        return Err(Error::Refused(crate::Refusal::Occurrences {
            occurrences,
            limit,
        }));
    }
    Ok(Image {
        sequent: linear,
        mode,
        logic,
        translation,
        ordinary,
        extra,
        roots,
    })
}

/// A linear arena under construction, every term made once.
#[derive(Default)]
struct Builder {
    /// The terms, each after its subterms.
    terms: Vec<Term>,
    /// The index of every term made.
    ids: HashMap<Term, TermId>,
    /// The atom names.
    atoms: Vec<String>,
    /// The index of every atom name.
    names: HashMap<String, Atom>,
}

impl Builder {
    /// Returns the id of `term`, adding it unless it is there, or fails
    /// when the arena is full.
    fn add(&mut self, term: Term) -> Result<TermId, Error> {
        if let Some(&id) = self.ids.get(&term) {
            return Ok(id);
        }
        let most = crate::linear::Forest::MOST;
        if self.terms.len() as u64 >= most {
            return Err(Error::Refused(crate::limits::Refusal::Occurrences {
                occurrences: most.saturating_add(1),
                limit: most,
            }));
        }
        let id = TermId::new(self.terms.len() as u32);
        self.terms.push(term);
        self.ids.insert(term, id);
        Ok(id)
    }

    /// Returns the atom called `name`.
    fn atom(&mut self, name: &str) -> Atom {
        if let Some(&atom) = self.names.get(name) {
            return atom;
        }
        let atom = Atom::new(self.atoms.len() as u32);
        self.atoms.push(name.to_owned());
        self.names.insert(name.to_owned(), atom);
        atom
    }
}

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

    /// A count of hypotheses past `u32::MAX` is refused, never cut to 32
    /// bits; a count that fits is the image's antecedents.
    #[test]
    fn the_antecedents_fit_32_bits() {
        assert_eq!(antecedents(3), Ok(3));
        // A `usize` past `u32::MAX` exists on 64 bits alone.
        #[cfg(target_pointer_width = "64")]
        {
            use crate::Error;
            use crate::limits::Refusal;
            assert!(matches!(
                antecedents(usize::try_from(u64::from(u32::MAX) + 1).unwrap()),
                Err(Error::Refused(Refusal::Index { most, .. })) if most == u64::from(u32::MAX)
            ));
        }
    }
}