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

//! Desequentialization: from a proof term of unit-free MELL to its
//! structure with boxes.
//!
//! The term is unfolded into a tree: a node that several others share is
//! read once per use. The tree is read from the leaves. Every rule makes
//! the vertex of the formula it introduces from the vertices its premises
//! left open, so the vertices of a formula are instances of its
//! occurrence:
//! - an axiom makes two literals and links them;
//! - a promotion closes the box around everything its premise made;
//! - a cut joins with a cut link the instances of its formula and of its
//!   dual that its two premises left open;
//! - a copy moves an instance from the linear zone to the unrestricted
//!   one;
//! - a `?` rule takes every copy of its subformula that its premise made
//!   and no `?` rule above took, as the checker reads the unrestricted
//!   zone. A `?` rule without copies is a weakening, and hangs on the
//!   first link its premise made.
//!
//! A term names occurrences, not instances. So where a sequent holds two
//! instances of one occurrence, the rule acting on it takes the last one
//! made. Any choice gives a sequent proof, and its net is a proof net.

use super::{BUILD_BYTES, MOST, MellStructure, Parts, Placed, VERTEX_BYTES};
use crate::Error;
use crate::limits::{Limits, Phase, Progress, Refusal, Space};
use crate::linear::fragment::Mode;
use crate::linear::nets::{Criterion, NONE, NetError, STOPPED, VertexId, afford};
use crate::linear::occurrences::OccId;
use crate::linear::proofs::{Node, NodeId, Proof};

/// The bytes the unfolding holds per vertex beside the structure: 8 for
/// its occurrence and box, 28 for its list of premises and its entry in
/// its parent's, 8 for an entry in a list of open or waiting instances, 12
/// for the renumbering's three arrays, and 16 for its vertex of the parts.
const UNFOLD_BYTES: u64 = 8 + 28 + 8 + 12 + 16;

impl MellStructure {
    /// Returns the proof net of a proof of unit-free MELL: its structure
    /// with boxes, over a copy of the proof's forest.
    ///
    /// The proof may be classical, with Mix where the criterion allows it,
    /// or intuitionistic, since every intuitionistic proof is a classical
    /// proof of the one-sided sequent. It is checked in classical mode,
    /// then unfolded into its structure. Both stay within `limits`: the
    /// check within its bounds, and the unfolded vertices, counted before
    /// anything is made, within `limits.memory_bytes`. `stop` is asked by
    /// the check, once per node of the unfolding, and as
    /// [`is_correct`](Self::is_correct) asks it; the call ends when it
    /// returns true.
    ///
    /// The vertices are numbered from the roots, then each root's formula
    /// tree depth first, a `?` vertex's copies in the order they were made.
    /// Every proof gives a proof net. Two proofs that differ in the order
    /// of their rules give the same net, up to the axiom links the
    /// weakenings hang on and, where a sequent holds two instances of one
    /// occurrence, up to the instance a rule takes (the last one made).
    ///
    /// # Errors
    ///
    /// [`Error::GoalProof`] for a proof of a goal other than the sequent;
    /// [`NetError::NotMell`] outside unit-free MELL;
    /// the checker's [`CheckError`](crate::linear::proofs::CheckError) for a term
    /// that is no proof; [`Refusal::Index`] for more vertices than a
    /// structure holds; [`NetError::Refused`] when the bound or the stop
    /// ended it.
    ///
    /// # Examples
    ///
    /// The net of a proof the search found: `!b` is weakened, so its `?~b`
    /// has no copy and hangs on the axiom link.
    ///
    #[cfg_attr(feature = "parse", doc = "```")]
    #[cfg_attr(not(feature = "parse"), doc = "```ignore")]
    /// use deduxit::Limits;
    /// use deduxit::linear::{Criterion, MellStructure, Mode, Options, Sequent, Verdict, prove};
    ///
    /// let sequent: Sequent = "!a, !b |- !a".parse()?;
    /// let outcome = prove(&sequent, Mode::CLASSICAL, &Options::default())?;
    /// let Verdict::Proved(proof) = &outcome.verdict else {
    ///     panic!("the sequent is provable");
    /// };
    /// let net = MellStructure::from_proof(proof, Criterion::MLL, &Limits::default(), |_| false)?;
    /// assert_eq!(
    ///     net.to_string(),
    ///     "⊢ ?~a, ?~b, !a\n\
    ///      ?~a[0]: ~a[3] in !a[2]\n\
    ///      ?~b[1]: no copy, hangs on a[4]\n\
    ///      ~a[3] — a[4]\n\
    ///      proof net (the correctness criterion holds)"
    /// );
    /// # Ok::<(), deduxit::Error>(())
    /// ```
    pub fn from_proof(
        proof: &Proof,
        criterion: Criterion,
        limits: &Limits,
        mut stop: impl FnMut(Progress) -> bool,
    ) -> Result<Self, Error> {
        if proof.goal().is_some() {
            return Err(Error::GoalProof);
        }
        let mode = if criterion.mix {
            Mode::CLASSICAL.with_mix()
        } else {
            Mode::CLASSICAL
        };
        Self::exist(proof.sequent().fragment(), mode)?;
        proof.check_within(mode, limits, &mut stop)?;
        let vertices = unfolded(proof);
        if vertices > MOST {
            return Err(Error::Refused(Refusal::Index {
                what: Space::Vertex,
                count: vertices,
                most: MOST,
            }));
        }
        let bytes = vertices.saturating_mul(VERTEX_BYTES + BUILD_BYTES + UNFOLD_BYTES);
        afford(bytes, limits)?;
        let mut unfolding = Unfolding::new(proof, vertices as usize);
        unfolding.run(&mut |done| {
            stop(Progress {
                held_bytes: bytes,
                ..Progress::new(Phase::Net, 1, done)
            })
        })?;
        let parts = unfolding.parts();
        let structure = Self::from_parts(proof.forest().clone(), criterion, &parts, limits)?;
        structure.is_correct(|progress| {
            stop(Progress {
                held_bytes: bytes,
                ..progress
            })
        })?;
        Ok(structure)
    }
}

/// Returns how many vertices the unfolded term makes: each node's uses,
/// counted from the root down and saturating, times the vertices its rule
/// makes.
fn unfolded(proof: &Proof) -> u64 {
    let nodes = proof.nodes();
    let mut uses = vec![0u64; nodes.len()];
    let root = proof.root().index();
    uses[root] = 1;
    let mut total = 0u64;
    for i in (0..=root).rev() {
        let made = match nodes[i] {
            Node::Ax(..) => 2,
            Node::Copy(..) | Node::Mix(..) | Node::Cut(..) => 0,
            Node::Tensor(..)
            | Node::Par(..)
            | Node::Bang(..)
            | Node::Quest(..)
            | Node::Weaken(..)
            | Node::One(_)
            | Node::Bot(..)
            | Node::With(..)
            | Node::Plus(..)
            | Node::Top(_) => 1,
            // A sequent with a binder has no net.
            Node::Forall(..) | Node::Exists(..) => unreachable!("a MELL proof has no binder"),
        };
        total = total.saturating_add(uses[i].saturating_mul(made));
        for p in nodes[i].premises() {
            uses[p.index()] = uses[p.index()].saturating_add(uses[i]);
        }
    }
    total
}

/// A node of the unfolded term being read. Its premises are read first:
/// the first into the vertices from `start` on, the second into those from
/// `middle` on.
struct Frame {
    /// The node.
    node: NodeId,
    /// The premises read so far.
    read: u8,
    /// The vertex count when the node was entered.
    start: u32,
    /// The vertex count once its first premise was read. For a `?` rule,
    /// the number of copies of its subformula waiting when it was entered.
    middle: u32,
    /// The link count when the node was entered.
    links: u32,
}

/// An unfolding in progress.
struct Unfolding<'a> {
    /// The proof.
    proof: &'a Proof,
    /// Per vertex, its occurrence.
    occurrence: Vec<OccId>,
    /// Per vertex, its box, as an index into `doors`, or `NONE`.
    boxed: Vec<u32>,
    /// Per vertex, its premises as they were made.
    premises: Vec<Vec<u32>>,
    /// Per box, its `!` vertex once its promotion is read.
    doors: Vec<u32>,
    /// The boxes the node being read lies in, the innermost last.
    open_boxes: Vec<u32>,
    /// Per occurrence, its instances in a linear zone, in the order made.
    open: Vec<Vec<u32>>,
    /// Per occurrence under a `?`, its copies no `?` rule took yet.
    waiting: Vec<Vec<u32>>,
    /// The links, in the order made.
    links: Vec<(u32, u32)>,
    /// The cut links made, each from its end in a cut formula's tree.
    cuts: Vec<(u32, u32)>,
    /// The weakenings and the literal each hangs on.
    weakenings: Vec<(u32, u32)>,
}

impl<'a> Unfolding<'a> {
    /// Returns an unfolding of a proof that makes `vertices` vertices.
    fn new(proof: &'a Proof, vertices: usize) -> Self {
        let n = proof.forest().len();
        Self {
            proof,
            occurrence: Vec::with_capacity(vertices),
            boxed: Vec::with_capacity(vertices),
            premises: Vec::with_capacity(vertices),
            doors: Vec::new(),
            open_boxes: Vec::new(),
            open: vec![Vec::new(); n],
            waiting: vec![Vec::new(); n],
            links: Vec::new(),
            cuts: Vec::new(),
            weakenings: Vec::new(),
        }
    }

    /// Makes a vertex in the current box and returns it.
    fn make(&mut self, o: OccId, premises: Vec<u32>) -> u32 {
        let v = self.occurrence.len() as u32;
        self.occurrence.push(o);
        self.boxed
            .push(self.open_boxes.last().copied().unwrap_or(NONE));
        self.premises.push(premises);
        self.open[o.index()].push(v);
        v
    }

    /// Takes the last instance of `o` among the vertices `from..to` out of
    /// the linear zone, and returns it. A checked proof's premise holds
    /// one.
    fn take(&mut self, o: OccId, from: u32, to: u32) -> u32 {
        let list = &mut self.open[o.index()];
        let i = list.partition_point(|&v| v < to);
        assert!(
            i > 0 && list[i - 1] >= from,
            "a checked premise holds its rule's subformula"
        );
        list.remove(i - 1)
    }

    /// Reads the whole term, asking `stop` before each node with the
    /// number of nodes read so far.
    fn run(&mut self, stop: &mut dyn FnMut(u64) -> bool) -> Result<(), NetError> {
        let nodes = self.proof.nodes();
        let mut frames = vec![self.enter(self.proof.root())];
        let mut read = 0u64;
        while let Some(frame) = frames.last_mut() {
            let node = nodes[frame.node.index()];
            let premise = node.premises().nth(frame.read as usize);
            if let Some(p) = premise {
                if frame.read == 1 {
                    frame.middle = self.occurrence.len() as u32;
                }
                frame.read += 1;
                read += 1;
                if stop(read) {
                    return Err(STOPPED);
                }
                let entered = self.enter(p);
                frames.push(entered);
                continue;
            }
            let frame = frames.pop().expect("the frame just looked at");
            self.exit(node, &frame);
        }
        Ok(())
    }

    /// Enters a node: a promotion opens its box, a `?` rule notes the
    /// copies waiting.
    fn enter(&mut self, id: NodeId) -> Frame {
        let node = self.proof.node(id);
        let mut middle = self.occurrence.len() as u32;
        match node {
            Node::Bang(..) => {
                self.open_boxes.push(self.doors.len() as u32);
                self.doors.push(NONE);
            }
            Node::Quest(q, _) => {
                let a = self.child(q.occ());
                middle = self.waiting[a.index()].len() as u32;
            }
            Node::Ax(..)
            | Node::Tensor(..)
            | Node::Par(..)
            | Node::One(_)
            | Node::Bot(..)
            | Node::With(..)
            | Node::Plus(..)
            | Node::Top(_)
            | Node::Copy(..)
            | Node::Weaken(..)
            | Node::Mix(..)
            | Node::Cut(..)
            | Node::Forall(..)
            | Node::Exists(..) => {}
        }
        Frame {
            node: id,
            read: 0,
            start: self.occurrence.len() as u32,
            middle,
            links: self.links.len() as u32,
        }
    }

    /// Returns the subformula of a unary connective's occurrence.
    fn child(&self, o: OccId) -> OccId {
        self.proof
            .forest()
            .left(o)
            .expect("a unary connective has a subformula")
    }

    /// Reads a node whose premises are read: makes the vertex of the
    /// formula it introduces, or for a cut its cut link.
    fn exit(&mut self, node: Node, frame: &Frame) {
        let f = self.proof.forest();
        let end = self.occurrence.len() as u32;
        match node {
            Node::Ax(x, y) => {
                let vx = self.make(x.occ(), Vec::new());
                let vy = self.make(y.occ(), Vec::new());
                self.links.push((vx, vy));
            }
            Node::Tensor(o, _, _) => {
                let o = o.occ();
                let l = self.take(f.left(o).unwrap(), frame.start, frame.middle);
                let r = self.take(f.right(o).unwrap(), frame.middle, end);
                self.make(o, vec![l, r]);
            }
            Node::Par(o, _) => {
                let o = o.occ();
                let l = self.take(f.left(o).unwrap(), frame.start, end);
                let r = self.take(f.right(o).unwrap(), frame.start, end);
                self.make(o, vec![l, r]);
            }
            Node::Bang(o, _) => {
                let o = o.occ();
                let a = self.take(self.child(o), frame.start, end);
                let b = self.open_boxes.pop().expect("the box its entry opened");
                let door = self.make(o, vec![a]);
                self.doors[b as usize] = door;
            }
            Node::Quest(o, _) => {
                let o = o.occ();
                let a = self.child(o);
                let copies = self.waiting[a.index()].split_off(frame.middle as usize);
                let q = self.make(o, copies);
                if self.premises[q as usize].is_empty() {
                    self.weakenings
                        .push((q, self.links[frame.links as usize].0));
                }
            }
            Node::Weaken(o, _) => {
                let q = self.make(o.occ(), Vec::new());
                self.weakenings
                    .push((q, self.links[frame.links as usize].0));
            }
            Node::Copy(a, _) => {
                let a = a.occ();
                let copy = self.take(a, frame.start, end);
                self.waiting[a.index()].push(copy);
            }
            Node::Mix(..) => {}
            Node::One(_)
            | Node::Bot(..)
            | Node::With(..)
            | Node::Plus(..)
            | Node::Top(_)
            | Node::Forall(..)
            | Node::Exists(..) => {
                unreachable!("a checked proof of unit-free MELL has no such rule")
            }
            Node::Cut(a, _, _) => {
                let a = a.occ();
                let d = f.dual(a).expect("a checked cut is on a cut formula's tree");
                let x = self.take(a, frame.start, frame.middle);
                let y = self.take(d, frame.middle, end);
                self.cuts.push((x, y));
            }
        }
    }

    /// Returns the parts of the structure read, the vertices renumbered
    /// from the roots, then each root's tree depth first.
    fn parts(self) -> Parts {
        let f = self.proof.forest();
        let roots: Vec<u32> = f
            .roots()
            .iter()
            .map(|r| {
                let list = &self.open[r.index()];
                debug_assert_eq!(list.len(), 1, "a proof concludes each root once");
                list[0]
            })
            .collect();
        let n = self.occurrence.len();
        let mut new = vec![NONE; n];
        let mut order = Vec::with_capacity(n);
        for &r in &roots {
            new[r as usize] = order.len() as u32;
            order.push(r);
        }
        // The cut links' ends and the trees above them come after the
        // roots' trees.
        let mut stack = Vec::new();
        let ends: Vec<u32> = self.cuts.iter().flat_map(|&(x, y)| [x, y]).collect();
        for &r in roots.iter().chain(&ends) {
            stack.push(r);
            while let Some(v) = stack.pop() {
                if new[v as usize] == NONE {
                    new[v as usize] = order.len() as u32;
                    order.push(v);
                }
                stack.extend(self.premises[v as usize].iter().rev());
            }
        }
        let mut parent = vec![NONE; n];
        for (v, premises) in self.premises.iter().enumerate() {
            for &w in premises {
                parent[w as usize] = v as u32;
            }
        }
        let renamed = |v: u32| VertexId::new(new[v as usize]);
        let vertices = order[roots.len()..]
            .iter()
            .map(|&v| {
                let b = self.boxed[v as usize];
                let inside = (b != NONE).then(|| renamed(self.doors[b as usize]));
                match parent[v as usize] {
                    NONE => Placed::cut(self.occurrence[v as usize], inside),
                    p => Placed::new(self.occurrence[v as usize], renamed(p), inside),
                }
            })
            .collect();
        Parts {
            vertices,
            cuts: self
                .cuts
                .iter()
                .map(|&(x, y)| (renamed(x), renamed(y)))
                .collect(),
            links: self
                .links
                .iter()
                .map(|&(x, y)| (renamed(x), renamed(y)))
                .collect(),
            weakenings: self
                .weakenings
                .iter()
                .map(|&(q, l)| (renamed(q), renamed(l)))
                .collect(),
        }
    }
}