deduxit 0.3.0

Logic suites, linear logic first: decides, checks, proves step by step and exports sequents of classical and intuitionistic linear logic, and ordinary propositional logic through its embeddings.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! The certificate of an ordinary sequent: a lemma over `Prop` whose
//! proof is a term made from a checked derivation of LK or LJ, one
//! construction per rule. An LJ sequent `Γ ⊢ C` is a term of type `C`
//! (`False` when nothing is right of `⊢`) with a variable per hypothesis;
//! an LK sequent `Γ ⊢ Δ` a term of type `False` with a variable per
//! hypothesis and one of type `~ D` per formula `D` of `Δ`, which the
//! rules that move a formula to the right close with the excluded middle
//! (`NNPP` of the standard library). The terms are written by a walk with
//! a stack of its own, so a derivation of any height is written.

use super::derivation::Side;
use super::{Derivation, Formulas, Image, Logic, Node, NodeId, Rule, Symbols};
use crate::Error;
use crate::export::Form;
use crate::export::rocq::{CLASSICAL_PRELUDE, Options, Unsupported, identifiers};
use crate::hash::HashMap;
use crate::linear::proofs::InfId;
use crate::linear::search::{Classical, Disproof, Refutation};
use std::fmt::Write;

/// The names the terms use, which an atom never gets.
const USED: &[&str] = &[
    "conj",
    "or_introl",
    "or_intror",
    "proj1",
    "proj2",
    "I",
    "True",
    "False",
    "False_ind",
    "NNPP",
    "iff",
    "and",
    "or",
    "not",
];

/// How Rocq spells the connectives.
const ROCQ: Symbols = Symbols {
    not: "~ ",
    and: "/\\",
    or: "\\/",
    implies: "->",
    iff: "<->",
    truth: "True",
    falsity: "False",
};

/// What the walk has yet to do.
enum Task {
    /// Write the term of an inference.
    Enter(InfId),
    /// Write text.
    Text(String),
    /// Give formulas names for the premise that follows.
    Bind(Vec<((NodeId, Side), String)>),
    /// Take back the names of the last `Bind` of this many.
    Unbind(Vec<(NodeId, Side)>),
}

/// The writer of one certificate.
struct Certificate<'a> {
    /// The derivation.
    derivation: &'a Derivation,
    /// The Rocq identifier of every atom.
    atoms: Vec<String>,
    /// The variables in scope, per formula and side, the innermost last.
    names: HashMap<(NodeId, Side), Vec<String>>,
    /// How many variables were made.
    fresh: u64,
}

impl Certificate<'_> {
    /// Returns a formula in Rocq's syntax, in brackets if binary or a
    /// negation, so that it stands as an argument.
    fn formula(&self, id: NodeId) -> String {
        let mut out = String::new();
        let formulas: &Formulas = self.derivation.formulas();
        // A negation is an application, which an argument needs in
        // brackets as much as a binary formula.
        let negation = matches!(formulas.node(id), super::Node::Not(_));
        if negation {
            out.push('(');
        }
        formulas
            .write(&mut out, id, true, &ROCQ, |o, a| {
                o.write_str(&self.atoms[a as usize])
            })
            .unwrap();
        if negation {
            out.push(')');
        }
        out
    }

    /// Returns a new variable's name, with a `'` no atom has.
    fn name(&mut self, letter: char) -> String {
        self.fresh += 1;
        format!("{letter}'{}", self.fresh)
    }

    /// Returns the variable of a formula on a side.
    fn of(&self, node: NodeId, side: Side) -> String {
        self.names
            .get(&(node, side))
            .and_then(|v| v.last())
            .cloned()
            .expect("a checked derivation names only formulas in scope")
    }

    /// Returns the type of an LJ sequent's term: its goal, or `False`.
    fn goal(&self, id: InfId) -> String {
        match self.derivation.inference(id).right.first() {
            Some(&c) => self.formula(c),
            None => "False".to_owned(),
        }
    }

    /// Returns the tasks that write the term of an inference: text and
    /// premises, each premise between the names it binds and their end.
    fn tasks(&mut self, id: InfId) -> Vec<Task> {
        use Rule::*;
        use Side::{Left, Right};
        let d = self.derivation;
        let inference = d.inference(id);
        let classical = d.logic() == Logic::Classical;
        let f = d.formulas();
        let principal = inference
            .principal
            .map(|(side, at)| inference.side(side)[at]);
        let p = principal.unwrap_or(NodeId(0));
        let operands = f.node(p).operands();
        let (a, b) = (operands.0.unwrap_or(p), operands.1.unwrap_or(p));
        let premises = &inference.premises;
        let text = |s: String| Task::Text(s);
        // A premise with the formulas given bound to new names.
        let premise = |n: usize, binds: Vec<((NodeId, Side), String)>| {
            let keys = binds.iter().map(|(k, _)| *k).collect();
            [
                Task::Bind(binds),
                Task::Enter(premises[n]),
                Task::Unbind(keys),
            ]
        };
        let fa = self.formula(a);
        let fb = self.formula(b);
        let mut tasks = Vec::new();
        // The term of a premise whose goal moves to the right, classically:
        // `NNPP A (fun k : ~ A => premise)`.
        let excluded = |this: &mut Self, n: usize, node: NodeId, tasks: &mut Vec<Task>| {
            let k = this.name('k');
            let shown = this.formula(node);
            tasks.push(text(format!("(NNPP {shown} (fun {k} : ~ {shown} => ")));
            tasks.extend(premise(n, vec![((node, Right), k)]));
            tasks.push(text("))".to_owned()));
        };
        match inference.rule {
            // `write` refuses a derivation with an open goal.
            Open => unreachable!("an open goal has no term"),
            Axiom => {
                let (x, y) = (inference.left[0], inference.right[0]);
                let h = self.of(x, Left);
                tasks.push(text(if classical {
                    format!("({} {h})", self.of(y, Right))
                } else {
                    h
                }));
            }
            WeakenLeft | ContractLeft | ContractRight | TrueLeft | FalseRight => {
                tasks.extend(premise(0, vec![]));
            }
            WeakenRight if classical => tasks.extend(premise(0, vec![])),
            WeakenRight => {
                tasks.push(text(format!("(False_ind {} ", self.goal(id))));
                tasks.extend(premise(0, vec![]));
                tasks.push(text(")".to_owned()));
            }
            TrueRight if classical => tasks.push(text(format!("({} I)", self.of(p, Right)))),
            TrueRight => tasks.push(text("I".to_owned())),
            FalseLeft if classical => tasks.push(text(self.of(p, Left))),
            FalseLeft => tasks.push(text(format!(
                "(False_ind {} {})",
                self.goal(id),
                self.of(p, Left)
            ))),
            AndLeft | AndLeft1 | AndLeft2 | IffLeft | IffLeft1 | IffLeft2 => {
                let h = self.of(p, Left);
                let iff = matches!(inference.rule, IffLeft | IffLeft1 | IffLeft2);
                let (x, y) = if iff { implications(f, a, b) } else { (a, b) };
                let pair = if iff {
                    format!("({h} : {} /\\ {})", self.formula(x), self.formula(y))
                } else {
                    h
                };
                let mut binds = Vec::new();
                let mut lets = String::from("(");
                for (keep, node, projection) in [
                    (!matches!(inference.rule, AndLeft2 | IffLeft2), x, "proj1"),
                    (!matches!(inference.rule, AndLeft1 | IffLeft1), y, "proj2"),
                ] {
                    if keep {
                        let n = self.name('h');
                        write!(
                            lets,
                            "let {n} : {} := {projection} {pair} in ",
                            self.formula(node)
                        )
                        .unwrap();
                        binds.push(((node, Left), n));
                    }
                }
                tasks.push(text(lets));
                tasks.extend(premise(0, binds));
                tasks.push(text(")".to_owned()));
            }
            AndRight | IffRight => {
                let iff = inference.rule == IffRight;
                let (x, y) = if iff { implications(f, a, b) } else { (a, b) };
                let cast = format!(" : {} /\\ {}", self.formula(x), self.formula(y));
                if classical {
                    tasks.push(text(format!("({} (conj ", self.of(p, Right))));
                    excluded(self, 0, x, &mut tasks);
                    tasks.push(text(" ".to_owned()));
                    excluded(self, 1, y, &mut tasks);
                    tasks.push(text(format!("{cast}))")));
                } else {
                    tasks.push(text("(conj ".to_owned()));
                    tasks.extend(premise(0, vec![]));
                    tasks.push(text(" ".to_owned()));
                    tasks.extend(premise(1, vec![]));
                    tasks.push(text(format!("{cast})")));
                }
            }
            OrLeft => {
                let h = self.of(p, Left);
                let (h1, h2) = (self.name('h'), self.name('h'));
                let goal = if classical {
                    "False".to_owned()
                } else {
                    self.goal(id)
                };
                tasks.push(text(format!(
                    "(match {h} return {goal} with or_introl {h1} => "
                )));
                tasks.extend(premise(0, vec![((a, Left), h1)]));
                tasks.push(text(format!(" | or_intror {h2} => ")));
                tasks.extend(premise(1, vec![((b, Left), h2)]));
                tasks.push(text(" end)".to_owned()));
            }
            OrRight => {
                let k = self.of(p, Right);
                let (k1, k2) = (self.name('k'), self.name('k'));
                tasks.push(text(format!(
                    "(let {k1} : ~ {fa} := fun x' => {k} (or_introl x') in \
                     let {k2} : ~ {fb} := fun x' => {k} (or_intror x') in "
                )));
                tasks.extend(premise(0, vec![((a, Right), k1), ((b, Right), k2)]));
                tasks.push(text(")".to_owned()));
            }
            OrRight1 | OrRight2 => {
                let (constructor, x) = if inference.rule == OrRight1 {
                    ("or_introl", a)
                } else {
                    ("or_intror", b)
                };
                if classical {
                    tasks.push(text(format!("({} ({constructor} ", self.of(p, Right))));
                    excluded(self, 0, x, &mut tasks);
                    tasks.push(text("))".to_owned()));
                } else {
                    tasks.push(text(format!("({constructor} ")));
                    tasks.extend(premise(0, vec![]));
                    tasks.push(text(")".to_owned()));
                }
            }
            ImpliesRight | NotRight => {
                let h = self.name('h');
                if classical {
                    tasks.push(text(format!("({} (fun {h} : {fa} => ", self.of(p, Right))));
                } else {
                    tasks.push(text(format!("(fun {h} : {fa} => ")));
                }
                if classical && inference.rule == ImpliesRight {
                    let k = self.name('k');
                    tasks.push(text(format!("NNPP {fb} (fun {k} : ~ {fb} => ")));
                    tasks.extend(premise(0, vec![((a, Left), h), ((b, Right), k)]));
                    tasks.push(text(")".to_owned()));
                } else {
                    tasks.extend(premise(0, vec![((a, Left), h)]));
                }
                tasks.push(text(if classical { "))" } else { ")" }.to_owned()));
            }
            NotLeft if premises.len() == 1 => {
                let k = self.name('k');
                tasks.push(text(format!(
                    "(let {k} : ~ {fa} := {} in ",
                    self.of(p, Left)
                )));
                tasks.extend(premise(0, vec![((a, Right), k)]));
                tasks.push(text(")".to_owned()));
            }
            ImpliesLeft | NotLeft => {
                let h = self.of(p, Left);
                let (consequent, shown) = if inference.rule == NotLeft {
                    let falsity = f.ids.get(&super::Node::False).copied();
                    (falsity.expect("a checked ¬L has ⊥"), "False".to_owned())
                } else {
                    (b, fb.clone())
                };
                let h2 = self.name('h');
                tasks.push(text(format!("(let {h2} : {shown} := {h} ")));
                if classical {
                    excluded(self, 0, a, &mut tasks);
                } else {
                    tasks.push(text("(".to_owned()));
                    tasks.extend(premise(0, vec![]));
                    tasks.push(text(")".to_owned()));
                }
                tasks.push(text(" in ".to_owned()));
                tasks.extend(premise(1, vec![((consequent, Left), h2)]));
                tasks.push(text(")".to_owned()));
            }
        }
        tasks
    }
}

/// Returns the implications `A → B` and `B → A` an equivalence of `a` and
/// `b` stands for, which a checked derivation's arena holds.
fn implications(formulas: &Formulas, a: NodeId, b: NodeId) -> (NodeId, NodeId) {
    let id = |node| {
        formulas
            .ids
            .get(&node)
            .copied()
            .expect("a checked derivation holds the implications of its equivalences")
    };
    (
        id(super::Node::Implies(a, b)),
        id(super::Node::Implies(b, a)),
    )
}

/// Writes the certificate of a derivation, which is checked first
/// ([`Derivation::check`], an open goal refused before it): the lemma `options.lemma` stating the sequent
/// over `Prop`, with a variable for every atom, and its proof term;
/// standalone, it starts with `options.prelude`, by default the import of
/// the standard library's excluded middle for a classical certificate and
/// nothing for one of LJ. Asks `stop` after each inference.
pub(crate) fn write(
    derivation: &Derivation,
    options: &Options,
    out: &mut impl Write,
    mut stop: impl FnMut() -> bool,
) -> Result<(), Error> {
    // A derivation of a proof in progress or one read from a document
    // may be no derivation of its logic; the terms are made only of one
    // that is.
    if derivation
        .inferences()
        .iter()
        .any(|i| i.rule() == Rule::Open)
    {
        return Err(Unsupported::Open.into());
    }
    let unbounded = crate::Limits {
        work: None,
        ..crate::Limits::default()
    };
    derivation.check(&unbounded, |_| stop())?;
    let classical = derivation.logic() == Logic::Classical;
    let formulas = derivation.formulas();
    let mut atoms = identifiers(formulas.atom_names(), options.lemma.as_str());
    for atom in &mut atoms {
        while USED.contains(&atom.as_str()) {
            atom.push('\'');
        }
    }
    let mut certificate = Certificate {
        derivation,
        atoms,
        names: HashMap::default(),
        fresh: 0,
    };
    if options.form == Form::Standalone {
        let prelude = match &options.prelude {
            Some(prelude) => Some(prelude.as_str()),
            None if classical => Some(CLASSICAL_PRELUDE),
            None => None,
        };
        if let Some(prelude) = prelude {
            write!(out, "{}\n\n", prelude.trim_end())?;
        }
    }
    let root = derivation.inference(derivation.root());
    let mut statement = String::new();
    let mut binders = String::new();
    if !certificate.atoms.is_empty() {
        let all = certificate.atoms.join(" ");
        write!(statement, "forall {all} : Prop, ").unwrap();
        write!(binders, "({all} : Prop) ").unwrap();
    }
    for &h in &root.left {
        let name = certificate.name('h');
        let shown = certificate.formula(h);
        write!(statement, "{shown} -> ").unwrap();
        write!(binders, "({name} : {shown}) ").unwrap();
        certificate
            .names
            .entry((h, Side::Left))
            .or_default()
            .push(name);
    }
    let mut body = String::new();
    let mut closing = String::new();
    let right: Vec<String> = root.right.iter().map(|&d| certificate.formula(d)).collect();
    match right.len() {
        0 => statement.push_str("False"),
        _ if !classical => statement.push_str(&right[0]),
        n => {
            let disjunction = right.join(" \\/ ");
            statement.push_str(&disjunction);
            if n == 1 {
                let k = certificate.name('k');
                write!(body, "NNPP {} (fun {k} : ~ {} => ", right[0], right[0]).unwrap();
                certificate
                    .names
                    .entry((root.right[0], Side::Right))
                    .or_default()
                    .push(k);
            } else {
                let k = certificate.name('k');
                write!(
                    body,
                    "NNPP ({disjunction}) (fun {k} : ~ ({disjunction}) => "
                )
                .unwrap();
                for (i, &d) in root.right.iter().enumerate() {
                    let ki = certificate.name('k');
                    let mut injection = "x'".to_owned();
                    if i + 1 < n {
                        injection = format!("(or_introl {injection})");
                    }
                    for _ in 0..i {
                        injection = format!("(or_intror {injection})");
                    }
                    write!(
                        body,
                        "let {ki} : ~ {} := fun x' => {k} {injection} in ",
                        right[i]
                    )
                    .unwrap();
                    certificate
                        .names
                        .entry((d, Side::Right))
                        .or_default()
                        .push(ki);
                }
            }
            closing.push(')');
        }
    }
    // A statement without atoms or hypotheses binds nothing, and `fun =>`
    // is no term.
    let lambda = if binders.is_empty() {
        String::new()
    } else {
        format!("fun {binders}=> ")
    };
    write!(
        out,
        "Lemma {} : {statement}.\nProof.\n  exact ({lambda}{body}",
        options.lemma
    )?;
    let mut stack = vec![Task::Enter(derivation.root())];
    while let Some(task) = stack.pop() {
        match task {
            Task::Enter(id) => {
                let tasks = certificate.tasks(id);
                stack.extend(tasks.into_iter().rev());
                if stop() {
                    return Err(Error::Refused(crate::limits::Refusal::Stopped {
                        phase: crate::limits::Phase::Write,
                    }));
                }
            }
            Task::Text(text) => out.write_str(&text)?,
            Task::Bind(binds) => {
                for (key, name) in binds {
                    certificate.names.entry(key).or_default().push(name);
                }
            }
            Task::Unbind(keys) => {
                for key in keys {
                    if let Some(names) = certificate.names.get_mut(&key) {
                        names.pop();
                    }
                }
            }
        }
    }
    write!(out, "{closing}).\nQed.\n")?;
    Ok(())
}

/// Writes the certificate that an ordinary sequent is not valid, from the
/// classical refutation of its image: the lemma `options.lemma` stating
/// `~ (forall a b : Prop, Γ -> Δ)`, `Γ` and `Δ` as the positive
/// certificate states them, proved by instantiating every atom with
/// `True` or `False` as the image's assignment gives it (an atom the
/// image lacks with `False`) and `tauto`, which decides the closed
/// formula left. The assignment is first checked to make every
/// hypothesis true and every formula right of `⊢` false; standalone, the
/// file starts with `options.prelude` where one is given, since the
/// certificate needs no library.
pub(crate) fn not_valid(
    image: &Image,
    disproof: &Disproof,
    options: &Options,
    out: &mut impl Write,
) -> Result<(), Error> {
    let Refutation::Classical(Classical { assignment }) = disproof.refutation() else {
        return Err(Unsupported::NotValid.into());
    };
    disproof.check()?;
    let sequent = image.ordinary();
    let formulas = sequent.formulas();
    let linear = image.sequent();
    let value = |name: &str| linear.atom(name).is_some_and(|a| assignment[a.index()]);
    // Every subformula precedes the formulas built from it.
    let mut truth: Vec<bool> = Vec::with_capacity(formulas.len());
    for id in 0..formulas.len() {
        let of = |k: NodeId| truth[k.index()];
        let node = formulas.node(NodeId(id as u32));
        let t = match node {
            Node::Atom(a) => value(&formulas.atom_names()[a as usize]),
            Node::True => true,
            Node::False => false,
            Node::Not(a) => !of(a),
            Node::And(a, b) => of(a) && of(b),
            Node::Or(a, b) => of(a) || of(b),
            Node::Implies(a, b) => !of(a) || of(b),
            Node::Iff(a, b) => of(a) == of(b),
        };
        truth.push(t);
    }
    let holds = |id: NodeId| truth[id.index()];
    if !sequent.left().iter().all(|&h| holds(h)) || sequent.right().iter().any(|&d| holds(d)) {
        return Err(Unsupported::NotValid.into());
    }
    let mut atoms = identifiers(formulas.atom_names(), options.lemma.as_str());
    for atom in &mut atoms {
        while USED.contains(&atom.as_str()) {
            atom.push('\'');
        }
    }
    if options.form == Form::Standalone
        && let Some(prelude) = &options.prelude
    {
        write!(out, "{}\n\n", prelude.trim_end())?;
    }
    let shown = |id: NodeId| {
        let mut text = String::new();
        let negation = matches!(formulas.node(id), Node::Not(_));
        if negation {
            text.push('(');
        }
        formulas
            .write(&mut text, id, true, &ROCQ, |o, a| {
                o.write_str(&atoms[a as usize])
            })
            .expect("a string takes the text");
        if negation {
            text.push(')');
        }
        text
    };
    let mut statement = String::new();
    if !atoms.is_empty() {
        write!(statement, "forall {} : Prop, ", atoms.join(" ")).expect("a string");
    }
    for &h in sequent.left() {
        write!(statement, "{} -> ", shown(h)).expect("a string");
    }
    let right: Vec<String> = sequent.right().iter().map(|&d| shown(d)).collect();
    if right.is_empty() {
        statement.push_str("False");
    } else {
        statement.push_str(&right.join(" \\/ "));
    }
    let instances: Vec<&str> = (0..atoms.len())
        .map(|a| {
            if value(&formulas.atom_names()[a]) {
                "True"
            } else {
                "False"
            }
        })
        .collect();
    let specialize = if instances.is_empty() {
        String::new()
    } else {
        format!(" specialize (H {}).", instances.join(" "))
    };
    write!(
        out,
        "Lemma {} : ~ ({statement}).\nProof.\n  intro H.{specialize} tauto.\nQed.",
        options.lemma
    )?;
    Ok(())
}