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

//! Coverability by the backward algorithm. A marking (a count of tokens
//! per place) covers the target when it has at least the target's count
//! on every place. The question is whether some firing sequence from the
//! initial marking reaches a marking that covers the target.
//!
//! The markings from which some firing sequence covers the target form an
//! upward-closed set: with a marking it holds every larger one. The
//! search keeps the set as its minimal elements, the basis. It starts
//! from the target. Every element `m` and transition `t` give the least
//! marking from which `t` leads to a marking at least `m`:
//! `max(m − out(t), 0) + in(t)`. That marking joins the basis unless an
//! element is already at most it.
//!
//! A marking at most the initial one proves the target coverable, and the
//! transitions from it up its line of parents are the firing sequence. A
//! basis that no transition adds to is the whole set, and then the
//! initial marking outside it refutes.
//!
//! The search ends. No element added is at least an element added before
//! it: that one stays in the index and would have kept it out. And by
//! Dickson's lemma, every infinite sequence of count vectors has an
//! element at least an earlier one. Dickson's lemma does not bound how
//! long the search takes; the memory bound and the caller's stop do.

use super::equation::Equation;
use super::reach::room;
use super::{Parents, Program};
use crate::hash::HashMap;
use crate::linear::search::memory::{Account, Charged};
use crate::linear::search::{Reason, Statistics};
use std::cell::RefCell;
use std::cmp::Reverse;
use std::collections::BinaryHeap;

/// Searches backward from the program's target for a marking at most the
/// initial one.
///
/// Returns the transitions of a firing sequence from the initial marking
/// to one that covers the target, `None` when no reachable marking covers
/// it or the state equation refutes, or the reason the search stopped.
/// Where the search saturated, it also returns every element it kept,
/// as [`Elements`]: the basis that shows the target uncoverable. And it
/// returns the counters:
/// - `nodes`: the markings computed;
/// - `memo_hits`: those kept out by an element at most them;
/// - `memo_entries`: the elements kept.
///
/// It polls `stop` at every element taken from the queue and every
/// marking computed, keeps at most `most` elements, and gives `equation`
/// its share of the work.
pub(super) fn search(
    program: &Program,
    account: &Account,
    most: usize,
    equation: &mut Equation<'_>,
    stop: &mut dyn FnMut(u64) -> bool,
) -> (
    Result<Option<Vec<u32>>, Reason>,
    Statistics,
    Option<Elements>,
) {
    let mut search = Cover::new(program, account);
    let result = search.run(most, equation, stop);
    let statistics = Statistics {
        nodes: search.computed,
        memo_hits: search.covered,
        memo_entries: search.parents.len() as u64,
        ..Statistics::default()
    };
    let basis = search.saturated.then(|| Elements {
        entries: std::mem::take(&mut search.entries),
        ends: std::mem::take(&mut search.ends),
    });
    (result, statistics, basis)
}

/// The elements a search kept: each its places in increasing order with
/// their counts, all above zero, one after the other.
pub(super) struct Elements {
    /// The places and counts of every element.
    pub(super) entries: Vec<(u32, u32)>,
    /// Where each element's entries end.
    pub(super) ends: Vec<usize>,
}

/// The state of a search: the elements kept, their index (a trie of
/// their places), the queue, the transitions indexed by their output
/// places, and the counters.
struct Cover<'a> {
    /// The program searched.
    program: &'a Program,
    /// The elements, one after the other. Each is its places in increasing
    /// order with their counts, all above zero.
    entries: Vec<(u32, u32)>,
    /// Where each element's entries end.
    ends: Vec<usize>,
    /// The tokens of each element.
    sums: Vec<u64>,
    /// For each element, the element it was computed from and the
    /// transition.
    parents: Parents,
    /// The index of the elements by their places, a trie: the child of a
    /// node by a place.
    ///
    /// The root is node zero, and a path follows places in increasing
    /// order. An element is listed at the node its places lead to. So the
    /// elements at most a marking are listed at nodes that some of the
    /// marking's places lead to.
    edges: HashMap<(u32, u32), u32>,
    /// The first element listed at each node, plus one; zero for none.
    listed: Vec<u32>,
    /// The first child of each node, plus one; zero for none.
    first_child: Vec<u32>,
    /// The next child of each node's parent after it, plus one.
    sibling: Vec<u32>,
    /// The place that leads to each node from its parent.
    place_of_node: Vec<u32>,
    /// How many children each node has.
    children: Vec<u32>,
    /// The element listed after each at its node, plus one.
    after: Vec<u32>,
    /// The nodes a query has still to visit, each with where its children
    /// start in the marking's places.
    stack: RefCell<Vec<(u32, u32)>>,
    /// The elements to take, fewest tokens first.
    queue: BinaryHeap<Reverse<(u64, u32)>>,
    /// The transitions with an output to each place: those of place `p`
    /// are `by_output[starts[p]..starts[p + 1]]`.
    starts: Vec<u32>,
    /// The transitions by their output places.
    by_output: Vec<u32>,
    /// The element each transition was last tried on, plus one.
    tried: Vec<u32>,
    /// A marking tested against the elements, as a count per place.
    probe: Vec<u32>,
    /// The index of each place among the probe's marked places, plus one;
    /// zero for a place it does not mark.
    position: Vec<u32>,
    /// A buffer for a computed marking.
    next: Vec<(u32, u32)>,
    /// The memory charged for the buffers that grow.
    charged: Charged<'a>,
    /// The markings computed.
    computed: u64,
    /// The markings computed that an element at most them kept out.
    covered: u64,
    /// The work done: transitions tried, elements compared, and the
    /// index's nodes and lookups.
    work: u64,
    /// Whether the search took every element and found nothing more to
    /// keep, so that the elements are closed backward.
    saturated: bool,
}

impl<'a> Cover<'a> {
    /// Returns a search of the program with nothing kept yet.
    fn new(program: &'a Program, account: &'a Account) -> Self {
        let width = program.places;
        let mut starts = vec![0u32; width + 1];
        for transition in &program.transitions {
            for &(p, _) in program.outputs(transition) {
                starts[p as usize + 1] += 1;
            }
        }
        for p in 0..width {
            starts[p + 1] += starts[p];
        }
        let mut next = starts.clone();
        let mut by_output = vec![0; starts[width] as usize];
        for (t, transition) in program.transitions.iter().enumerate() {
            for &(p, _) in program.outputs(transition) {
                by_output[next[p as usize] as usize] = t as u32;
                next[p as usize] += 1;
            }
        }
        Self {
            program,
            entries: Vec::new(),
            ends: Vec::new(),
            sums: Vec::new(),
            parents: Parents::default(),
            edges: HashMap::default(),
            listed: vec![0],
            first_child: vec![0],
            sibling: vec![0],
            place_of_node: vec![0],
            children: vec![0],
            after: Vec::new(),
            stack: RefCell::new(Vec::new()),
            queue: BinaryHeap::new(),
            starts,
            by_output,
            tried: vec![0; program.transitions.len()],
            probe: vec![0; width],
            position: vec![0; width],
            next: Vec::new(),
            charged: Charged::new(account),
            computed: 0,
            covered: 0,
            work: 0,
            saturated: false,
        }
    }

    /// Runs the search, as [`search`] describes.
    fn run(
        &mut self,
        most: usize,
        equation: &mut Equation<'_>,
        stop: &mut dyn FnMut(u64) -> bool,
    ) -> Result<Option<Vec<u32>>, Reason> {
        let program = self.program;
        self.next.clear();
        for (p, &count) in program.target.iter().enumerate() {
            if count > 0 {
                self.next.push((p as u32, count));
            }
        }
        if self.below_initial() {
            return Ok(Some(Vec::new()));
        }
        self.keep(Parents::ROOT, 0, most)?;
        while let Some(Reverse((_, e))) = self.queue.pop() {
            if stop(1) {
                return Err(Reason::Stopped);
            }
            let budget = equation.budget(self.work);
            if equation.wants(budget) && equation.run(program, budget, stop)? {
                return Ok(None);
            }
            let (start, end) = self.span(e);
            // An element kept after this one and at most it covers
            // everything this one would compute, so this one is skipped.
            load(
                &mut self.probe,
                &mut self.position,
                &self.entries[start..end],
                false,
            );
            let (superseded, compared) = self.dominated(&self.entries[start..end], e);
            load(
                &mut self.probe,
                &mut self.position,
                &self.entries[start..end],
                true,
            );
            self.work += compared;
            if superseded {
                continue;
            }
            for i in start..end {
                let p = self.entries[i].0 as usize;
                for k in self.starts[p]..self.starts[p + 1] {
                    let t = self.by_output[k as usize];
                    if self.tried[t as usize] == e + 1 {
                        continue;
                    }
                    self.tried[t as usize] = e + 1;
                    if stop(1) {
                        return Err(Reason::Stopped);
                    }
                    self.computed += 1;
                    self.before(e, t)?;
                    if self.below_initial() {
                        let mut firings = vec![t];
                        firings.extend(self.path(e));
                        return Ok(Some(firings));
                    }
                    load(&mut self.probe, &mut self.position, &self.next, false);
                    let (dominated, compared) = self.dominated(&self.next, u32::MAX);
                    load(&mut self.probe, &mut self.position, &self.next, true);
                    self.work += 1 + compared;
                    if dominated {
                        self.covered += 1;
                    } else {
                        // Out of room, the search takes back the simplex's
                        // memory and tries once more.
                        match self.keep(e, t, most) {
                            Err(Reason::MemoryLimit { .. }) if equation.release() => {
                                self.keep(e, t, most)?;
                            }
                            kept => kept?,
                        }
                    }
                }
            }
        }
        self.saturated = true;
        Ok(None)
    }

    /// Returns where an element's entries start and end.
    fn span(&self, e: u32) -> (usize, usize) {
        let e = e as usize;
        (if e == 0 { 0 } else { self.ends[e - 1] }, self.ends[e])
    }

    /// Computes into `next` the least marking from which transition `t`
    /// leads to one at least element `e`: the element less the outputs,
    /// but not below zero, plus the inputs.
    ///
    /// Fails with [`Reason::IndexLimit`] when a count passes `u32::MAX`.
    fn before(&mut self, e: u32, t: u32) -> Result<(), Reason> {
        let program = self.program;
        let transition = &program.transitions[t as usize];
        let outputs = program.outputs(transition);
        let inputs = program.inputs(transition);
        let (start, end) = self.span(e);
        let element = &self.entries[start..end];
        self.next.clear();
        // The element, the outputs and the inputs are each sorted by
        // place, so one merge does.
        let (mut i, mut j, mut o) = (0, 0, 0);
        while i < element.len() || j < inputs.len() {
            let p = match (element.get(i), inputs.get(j)) {
                (Some(&(a, _)), Some(&(b, _))) => a.min(b),
                (Some(&(a, _)), None) => a,
                (None, Some(&(b, _))) => b,
                (None, None) => unreachable!("the loop's condition"),
            };
            let mut count = 0;
            if let Some(&(a, c)) = element.get(i)
                && a == p
            {
                i += 1;
                while o < outputs.len() && outputs[o].0 < p {
                    o += 1;
                }
                let given = match outputs.get(o) {
                    Some(&(q, w)) if q == p => w,
                    _ => 0,
                };
                count = c.saturating_sub(given);
            }
            if let Some(&(b, w)) = inputs.get(j)
                && b == p
            {
                j += 1;
                count = count.checked_add(w).ok_or(Reason::IndexLimit)?;
            }
            if count > 0 {
                self.next.push((p, count));
            }
        }
        Ok(())
    }

    /// Whether the marking in `next` is at most the initial marking.
    fn below_initial(&self) -> bool {
        self.next
            .iter()
            .all(|&(p, c)| c <= self.program.initial[p as usize])
    }

    /// Returns whether an element other than `except` is at most
    /// `marking`, which the probe holds, and how many nodes and elements it
    /// looked at.
    ///
    /// It visits the index's nodes that the marking's places lead to. The
    /// elements listed there have all their places marked by the marking,
    /// and it compares those of no more tokens.
    fn dominated(&self, marking: &[(u32, u32)], except: u32) -> (bool, u64) {
        let tokens: u64 = marking.iter().map(|&(_, c)| u64::from(c)).sum();
        let mut looked = 0;
        let mut stack = self.stack.borrow_mut();
        stack.clear();
        stack.push((0, 0));
        while let Some((node, from)) = stack.pop() {
            looked += 1;
            let mut listed = self.listed[node as usize];
            while listed != 0 {
                let b = listed - 1;
                if b != except && self.sums[b as usize] <= tokens {
                    looked += 1;
                    let (start, end) = self.span(b);
                    if self.entries[start..end]
                        .iter()
                        .all(|&(q, c)| self.probe[q as usize] >= c)
                    {
                        return (true, looked);
                    }
                }
                listed = self.after[b as usize];
            }
            // The node's children that the rest of the marking's places
            // lead to. They are found from the smaller side, the children
            // or the places, each step costing about a comparison.
            let rest = marking.len() - from as usize;
            let children = self.children[node as usize] as usize;
            if children <= rest {
                looked += children as u64;
                let mut next = self.first_child[node as usize];
                while next != 0 {
                    let child = next - 1;
                    let at = self.position[self.place_of_node[child as usize] as usize];
                    if at > from {
                        stack.push((child, at));
                    }
                    next = self.sibling[child as usize];
                }
            } else {
                looked += rest as u64;
                for (i, &(p, _)) in marking.iter().enumerate().skip(from as usize) {
                    if let Some(&child) = self.edges.get(&(node, p)) {
                        stack.push((child, i as u32 + 1));
                    }
                }
            }
        }
        (false, looked)
    }

    /// Keeps the marking in `next` as an element, computed from `parent`
    /// by `transition`. Fails with the reason when it cannot be kept.
    fn keep(&mut self, parent: u32, transition: u32, most: usize) -> Result<(), Reason> {
        let index = self.parents.len();
        if index >= most {
            return Err(Reason::IndexLimit);
        }
        let more = self.next.len();
        // An element adds at most a node per place, and the nodes are
        // `u32`.
        if self.listed.len() + more >= u32::MAX as usize {
            return Err(Reason::IndexLimit);
        }
        if !room(&mut self.entries, more, &mut self.charged)
            || !room(&mut self.ends, 1, &mut self.charged)
            || !room(&mut self.sums, 1, &mut self.charged)
            || !self.parents.room(&mut self.charged)
            || !room(&mut self.listed, more, &mut self.charged)
            || !room(&mut self.first_child, more, &mut self.charged)
            || !room(&mut self.sibling, more, &mut self.charged)
            || !room(&mut self.place_of_node, more, &mut self.charged)
            || !room(&mut self.children, more, &mut self.charged)
            || !room(&mut self.after, 1, &mut self.charged)
            || !self.room_in_edges(more)
            || !self.room_in_queue()
        {
            return Err(Reason::MemoryLimit {
                limit_bytes: self.charged.account().limit(),
            });
        }
        self.entries.extend_from_slice(&self.next);
        self.ends.push(self.entries.len());
        let tokens = self.next.iter().map(|&(_, c)| u64::from(c)).sum();
        self.sums.push(tokens);
        self.parents.push(parent, transition);
        let index = index as u32;
        let mut node = 0;
        for &(p, _) in &self.next {
            node = match self.edges.get(&(node, p)) {
                Some(&child) => child,
                None => {
                    let child = self.listed.len() as u32;
                    self.edges.insert((node, p), child);
                    self.listed.push(0);
                    self.first_child.push(0);
                    self.sibling.push(self.first_child[node as usize]);
                    self.first_child[node as usize] = child + 1;
                    self.place_of_node.push(p);
                    self.children.push(0);
                    self.children[node as usize] += 1;
                    child
                }
            };
        }
        self.after.push(self.listed[node as usize]);
        self.listed[node as usize] = index + 1;
        self.queue.push(Reverse((tokens, index)));
        Ok(())
    }

    /// Makes room in the index's edges for `more`, and charges what the
    /// table grew by (its slots and a control byte each). Returns false
    /// when the bound has no room.
    fn room_in_edges(&mut self, more: usize) -> bool {
        let slot = size_of::<((u32, u32), u32)>() + 1;
        if self.edges.capacity() - self.edges.len() >= more {
            return true;
        }
        let before = self.edges.capacity() * slot;
        let wanted = self
            .edges
            .len()
            .checked_add(more)
            .map(|needed| needed.max(2 * self.edges.capacity()));
        let fits = wanted
            .and_then(|wanted| wanted.checked_mul(2 * slot))
            .is_some_and(|bytes| self.charged.account().fits(bytes.saturating_sub(before)));
        let (true, Some(wanted)) = (fits, wanted) else {
            return false;
        };
        self.edges.reserve(wanted - self.edges.len());
        self.charged.resize(before, self.edges.capacity() * slot);
        true
    }

    /// Makes room in the queue for one more element, doubling it, and
    /// charges what it grew by. Returns false when the bound has no room.
    fn room_in_queue(&mut self) -> bool {
        let size = size_of::<Reverse<(u64, u32)>>();
        if self.queue.len() < self.queue.capacity() {
            return true;
        }
        let more = self.queue.capacity().max(16);
        let fits = more
            .checked_mul(size)
            .is_some_and(|bytes| self.charged.account().fits(bytes));
        if !fits {
            return false;
        }
        let before = self.queue.capacity() * size;
        self.queue.reserve_exact(more);
        self.charged.resize(before, self.queue.capacity() * size);
        true
    }

    /// Returns the transitions fired from a marking at least element `e`
    /// to one that covers the target: `e`'s transition, then its
    /// parent's, up to the target.
    fn path(&self, e: u32) -> Vec<u32> {
        self.parents.up(e)
    }
}

/// Writes a marking into two dense vectors, or clears them: its count on
/// each place into `counts`, and each place's index among its marked
/// places, plus one, into `position`.
fn load(counts: &mut [u32], position: &mut [u32], marking: &[(u32, u32)], clear: bool) {
    for (i, &(p, c)) in marking.iter().enumerate() {
        (counts[p as usize], position[p as usize]) = if clear { (0, 0) } else { (c, i as u32 + 1) };
    }
}