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

//! Sequentialization: from a proof net with boxes to a proof term of the
//! dyadic calculus, by the splitting tensor lemma at every box depth.
//!
//! A sub-net is given by its conclusions, all at one depth. A stage first
//! opens what needs no choice:
//! - a `⅋` conclusion is replaced by its premises, and a `⅋` rule goes
//!   below the rest;
//! - a `?` vertex conclusion gets a `?` rule, which moves its subformula
//!   into the unrestricted zone. Its copies at its depth become
//!   conclusions, each brought into the linear zone by a copy rule above
//!   the `?` rule. The subformula stays in the unrestricted zone, so the
//!   copies inside boxes are in reach when their box is proved;
//! - inside a box, the doors are such conclusions from the start, with
//!   their `?` rules below the promotion.
//!
//! Then the stage proves what is left. With Mix allowed, a sub-net in
//! several parts is proved part by part. Two literals alone are an axiom,
//! and a `!` vertex alone is the promotion of its box's contents.
//! Otherwise some `⊗` conclusion or cut link is splitting: taking it away
//! leaves its two premises in two separate parts. A cut link counts as a
//! `⊗` without a conclusion, whose rule is the cut. As in the
//! multiplicative case, its premise edge is a bridge of the plain graph,
//! the graph with every edge. For this the depth's graph is a
//! multiplicative structure: a `?` vertex or a door is a `⅋` of any arity,
//! a `!` vertex with its box is a hypothesis whose conclusions are the `!`
//! formula and its wires, and a link with the weakenings that hang on it
//! is an axiom with more conclusions.

use super::graph::Scratch;
use super::{MellStructure, SCRATCH_BYTES, VERTEX_BYTES};
use crate::Error;
use crate::limits::{Limits, Phase, Progress};
use crate::linear::fragment::Mode;
use crate::linear::nets::{NONE, STOPPED, VertexId, afford};
use crate::linear::occurrences::{Member, OccId};
use crate::linear::proofs::{Node, NodeId, Proof};
use crate::linear::sequents::Kind;

/// A rule a stage applies below what proves the rest, on an occurrence.
#[derive(Clone, Copy, Debug)]
enum Open {
    /// A `⅋` rule.
    Par(OccId),
    /// A `?` rule.
    Quest(OccId),
    /// A copy.
    Copy(OccId),
}

/// A step of a sequentialization.
enum Step {
    /// Prove the sub-net with these conclusions, graph vertices of one
    /// depth.
    Prove(Vec<u32>),
    /// Join the last two sub-nets proved with Mix.
    Mix,
    /// Apply this `⊗` to the last two sub-nets proved.
    Tensor(OccId),
    /// Cut on this occurrence of a cut formula's tree the last two
    /// sub-nets proved, which hold it and its dual.
    Cut(OccId),
    /// Apply this promotion to the last sub-net proved.
    Bang(OccId),
    /// Apply these rules to the last sub-net proved, the last first.
    Opened(Vec<Open>),
}

impl MellStructure {
    /// Turns a proof net with boxes into a proof term of its sequent.
    ///
    /// The checker accepts the term in classical mode, with Mix where the
    /// criterion allows it, and that is the mode the proof records.
    /// Without Mix, where the sequent has an intuitionistic reading, the
    /// checker accepts it in intuitionistic mode too: every sequent of the
    /// term then holds one formula in output position, as every sequent of
    /// a classical proof of such a sequent does.
    ///
    /// The term's nodes are `⅋`, `⊗`, axiom, promotion, `?`, copy, a cut
    /// for each cut link, and Mix where the structure falls apart. A
    /// weakening is a `?` rule without copies.
    ///
    /// It takes time at most quadratic in the graph. It holds within
    /// `limits.memory_bytes`, estimated before anything is made, and asks
    /// `stop` as [`is_correct`](Self::is_correct) does and once per stage.
    ///
    /// # Errors
    ///
    /// The criterion's [`NetError`](crate::linear::NetError) if the structure is
    /// not a proof net; [`NetError::Refused`](crate::linear::NetError::Refused)
    /// when the bound or the stop ended it.
    #[expect(
        clippy::missing_panics_doc,
        reason = "the expect states that a sequentialization keeps premises before conclusions, which the stages establish"
    )]
    pub fn sequentialize(
        &self,
        limits: &Limits,
        mut stop: impl FnMut(Progress) -> bool,
    ) -> Result<Proof, Error> {
        let vertices = self.graph.vertex_count() as u64;
        let bytes = vertices.saturating_mul(VERTEX_BYTES + SCRATCH_BYTES + 8);
        afford(bytes, limits)?;
        self.is_correct(|progress| {
            stop(Progress {
                held_bytes: bytes,
                ..progress
            })
        })?;
        let mut run = Sequentialization {
            net: self,
            scratch: Scratch::new(&self.graph),
            nodes: Vec::with_capacity(self.len()),
            steps: Vec::new(),
            proved: Vec::new(),
        };
        let mut stages = 0;
        let mut stop = |stage: u64| {
            stages += stage;
            stop(Progress {
                held_bytes: bytes,
                ..Progress::new(Phase::Net, stage, stages)
            })
        };
        let mut roots: Vec<u32> = (0..self.forest.roots().len() as u32).collect();
        roots.extend(self.graph.cuts_in(NONE));
        let Some(root) = run.sequentialize(roots, &mut stop) else {
            return Err(STOPPED.into());
        };
        let mode = if self.criterion.mix {
            Mode::CLASSICAL.with_mix()
        } else {
            Mode::CLASSICAL
        };
        let proof = Proof::new(self.forest.clone(), run.nodes, root)
            .expect("premises precede conclusions and every occurrence is the forest's")
            .with_mode(mode);
        debug_assert_eq!(proof.check(mode), Ok(()));
        debug_assert!(
            self.criterion.mix
                || self.reading().is_err()
                || proof.check(Mode::INTUITIONISTIC).is_ok()
        );
        Ok(proof)
    }
}

/// A sequentialization in progress.
struct Sequentialization<'a> {
    /// The proof net.
    net: &'a MellStructure,
    /// Working memory for the searches. The conclusions handled are
    /// deleted in it, so a sub-net is what its conclusions reach.
    scratch: Scratch,
    /// The proof's arena so far.
    nodes: Vec<Node>,
    /// What is yet to do, the next step last.
    steps: Vec<Step>,
    /// The nodes concluding the sub-nets proved and not yet used.
    proved: Vec<NodeId>,
}

impl Sequentialization<'_> {
    /// Adds a node and returns its id.
    fn push(&mut self, node: Node) -> NodeId {
        self.nodes.push(node);
        NodeId::new(self.nodes.len() as u32 - 1)
    }

    /// Takes the node concluding the last sub-net proved.
    fn premise(&mut self) -> NodeId {
        self.proved
            .pop()
            .expect("a sub-net proved for every premise")
    }

    /// Returns the occurrence of a structure vertex as a member.
    fn member(&self, v: u32) -> Member {
        Member::from(self.net.occurrence[v as usize])
    }

    /// Proves the sub-net with the given conclusions and returns the node
    /// concluding it, asking `stop` before each stage. `None` when `stop`
    /// fired.
    fn sequentialize(
        &mut self,
        gamma: Vec<u32>,
        stop: &mut dyn FnMut(u64) -> bool,
    ) -> Option<NodeId> {
        self.steps.push(Step::Prove(gamma));
        while let Some(step) = self.steps.pop() {
            let node = match step {
                Step::Prove(gamma) => {
                    if stop(1) {
                        return None;
                    }
                    self.stage(gamma);
                    continue;
                }
                Step::Mix => {
                    let other = self.premise();
                    let node = self.premise();
                    self.push(Node::Mix(node, other))
                }
                Step::Tensor(t) => {
                    let right = self.premise();
                    let left = self.premise();
                    self.push(Node::Tensor(Member::from(t), left, right))
                }
                Step::Cut(a) => {
                    let right = self.premise();
                    let left = self.premise();
                    self.push(Node::Cut(Member::from(a), left, right))
                }
                Step::Bang(b) => {
                    let premise = self.premise();
                    self.push(Node::Bang(Member::from(b), premise))
                }
                Step::Opened(rules) => {
                    let mut node = self.premise();
                    for &rule in rules.iter().rev() {
                        node = self.push(match rule {
                            Open::Par(o) => Node::Par(Member::from(o), node),
                            Open::Quest(o) => Node::Quest(Member::from(o), node),
                            Open::Copy(o) => Node::Copy(Member::from(o), node),
                        });
                    }
                    node
                }
            };
            self.proved.push(node);
        }
        Some(self.premise())
    }

    /// Opens the copies of a `?` vertex or door at its depth: each becomes
    /// a conclusion, brought into the linear zone by a copy rule.
    fn copies(&self, source: u32, gamma: &mut Vec<u32>, rules: &mut Vec<Open>) {
        let graph = &self.net.graph;
        for w in graph.wires(source) {
            if w < graph.vertex_offset() && graph.parent_edge(w) == source {
                rules.push(Open::Copy(self.net.occurrence[w as usize]));
                gamma.push(w);
            }
        }
    }

    /// Runs one stage on the sub-net with the given conclusions. It opens
    /// the `⅋` and `?` conclusions and the doors. Then it proves the
    /// sub-net by an axiom, or pushes the steps that prove it: its parts
    /// with a Mix after each but the first; the contents of its box and the
    /// promotion; or the two sides of its splitting `⊗` or cut link, and
    /// the rule after them.
    fn stage(&mut self, mut gamma: Vec<u32>) {
        let net = self.net;
        let graph = &net.graph;
        let n = graph.vertex_offset();
        let first_cut = graph.first_cut();
        let mut rules = Vec::new();
        // A conclusion opened without a premise to take its place is
        // marked `NONE` and dropped at the end, so that each costs constant
        // time.
        let mut i = 0;
        while i < gamma.len() {
            let c = gamma[i];
            if c >= first_cut {
                i += 1;
                continue;
            }
            if c >= n {
                gamma[i] = NONE;
                i += 1;
                self.scratch.delete(c);
                self.copies(c, &mut gamma, &mut rules);
                continue;
            }
            match net.kind(c) {
                Kind::Par => {
                    let mut premises = net.premises(VertexId::new(c));
                    let (l, r) = (premises.next().unwrap(), premises.next().unwrap());
                    self.scratch.delete(c);
                    rules.push(Open::Par(net.occurrence[c as usize]));
                    gamma[i] = l.get();
                    gamma.push(r.get());
                }
                Kind::Quest => {
                    gamma[i] = NONE;
                    i += 1;
                    self.scratch.delete(c);
                    rules.push(Open::Quest(net.occurrence[c as usize]));
                    self.copies(c, &mut gamma, &mut rules);
                }
                Kind::Atom
                | Kind::DualAtom
                | Kind::Tensor
                | Kind::Bang
                | Kind::One
                | Kind::Bot
                | Kind::Top
                | Kind::Zero
                | Kind::With
                | Kind::Plus
                | Kind::Forall
                | Kind::Exists => i += 1,
            }
        }
        gamma.retain(|&c| c != NONE);
        if !rules.is_empty() {
            self.steps.push(Step::Opened(rules));
        }

        let parts = graph.search(&mut self.scratch, gamma.iter().copied());
        if parts > 1 {
            debug_assert!(net.criterion.mix, "a proof net without Mix is connected");
            // The parts in the order of their first conclusion. Sorting the
            // labels keeps a stage of many parts near linear.
            let mut first: Vec<(u32, usize)> = gamma
                .iter()
                .enumerate()
                .map(|(i, &c)| (self.scratch.component(c), i))
                .collect();
            first.sort_unstable();
            first.dedup_by_key(|&mut (label, _)| label);
            let labels: Vec<u32> = first.iter().map(|&(label, _)| label).collect();
            first.sort_unstable_by_key(|&(_, i)| i);
            let mut parts: Vec<Vec<u32>> = vec![Vec::new(); labels.len()];
            for &c in &gamma {
                let label = self.scratch.component(c);
                let j = labels.binary_search(&label).expect("every label is listed");
                parts[j].push(c);
            }
            for (i, &(label, _)) in first.iter().enumerate().rev() {
                if i > 0 {
                    self.steps.push(Step::Mix);
                }
                let j = labels.binary_search(&label).expect("every label is listed");
                self.steps.push(Step::Prove(std::mem::take(&mut parts[j])));
            }
        } else if gamma
            .iter()
            .all(|&c| c < n && net.forest.is_literal(net.occurrence[c as usize]))
        {
            debug_assert!(
                gamma.len() == 2 && net.partner[gamma[0] as usize] == gamma[1],
                "a connected sub-net of literals is one link"
            );
            let (x, y) = (self.member(gamma[0]), self.member(gamma[1]));
            let axiom = self.push(Node::Ax(x.min(y), x.max(y)));
            self.proved.push(axiom);
        } else if let [bang] = gamma[..]
            && bang < n
            && net.kind(bang) == Kind::Bang
        {
            self.scratch.delete(bang);
            let premise = net.premises(VertexId::new(bang)).next().unwrap().get();
            let mut contents = vec![premise];
            contents.extend(graph.doors_in(bang));
            contents.extend(graph.cuts_in(bang));
            self.steps.push(Step::Bang(net.occurrence[bang as usize]));
            self.steps.push(Step::Prove(contents));
        } else {
            // The splitting ⊗ conclusion with the smallest id: one whose
            // premise edge is a bridge. Else the splitting cut vertex with
            // the smallest id: one whose edge to its end in a cut formula's
            // tree is a bridge.
            let tensor = gamma
                .iter()
                .copied()
                .filter(|&c| c < n && net.kind(c) == Kind::Tensor)
                .filter(|&c| {
                    let l = net.premises(VertexId::new(c)).next().unwrap().get();
                    self.scratch.is_bridge(c, l)
                })
                .min();
            let cut = || {
                gamma
                    .iter()
                    .copied()
                    .filter(|&c| c >= first_cut)
                    .filter(|&c| self.scratch.is_bridge(c, graph.cut_ends(c).0))
                    .min()
            };
            let (split, l, r) = match tensor {
                Some(t) => {
                    let mut premises = net.premises(VertexId::new(t));
                    let (l, r) = (
                        premises.next().unwrap().get(),
                        premises.next().unwrap().get(),
                    );
                    (t, l, r)
                }
                None => {
                    let c = cut().expect(
                        "a connected proof net that is no link and no box has a splitting ⊗ or \
                         cut link",
                    );
                    let (a, d) = graph.cut_ends(c);
                    (c, a, d)
                }
            };
            self.scratch.delete(split);
            graph.search(&mut self.scratch, [l]);
            let (mut left, mut right) = (vec![l], vec![r]);
            for &c in &gamma {
                if c == split {
                    continue;
                }
                if self.scratch.reached(c) {
                    left.push(c);
                } else {
                    right.push(c);
                }
            }
            let occurrence = net.occurrence[l as usize];
            self.steps.push(if split < n {
                Step::Tensor(net.occurrence[split as usize])
            } else {
                Step::Cut(occurrence)
            });
            self.steps.push(Step::Prove(right));
            self.steps.push(Step::Prove(left));
        }
    }
}