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
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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! Reads coverability problems in the `.spec` format of the Mist tool
//! (`github.com/pierreganty/mist`).
//!
//! The coverability suites of software verification, such as `qcover`,
//! are written in this format. A problem is a Petri net: counters, rules
//! that test and change them, an initial marking, and the markings to
//! cover. It asks whether a marking reachable from the initial one covers
//! the target: has on each counter at least the tokens the target asks
//! for.
//!
//! [`read`] turns a problem into a Horn program to prove in an affine
//! mode, where weakening lets a marking that covers the target stand for
//! it:
//! - each counter is an atom, and each of its tokens an occurrence of it;
//! - each rule is a clause under `!`, from the tokens it takes to the
//!   tokens it gives;
//! - the initial marking's tokens stand left of `⊢`, the target right of
//!   it.
//!
//! The problem
//!
//! ```text
//! vars    x y
//! rules   x >= 1 -> x' = x - 1, y' = y + 2;
//! init    x = 1, y >= 0
//! target  y >= 2
//! ```
//!
//! is `!(x ⊸ y ⊗ y), !y, x ⊢ y ⊗ y`. An initial count written `x >= k` is
//! `k` tokens and `!x`, any number more. A target of several lines is
//! covered when one of them is: each line becomes a clause `!(line ⊸
//! goal)` to a fresh atom, the goal.
//!
//! # Examples
//!
//! Read that problem and prove it in intuitionistic affine mode, as the
//! benchmark harness does:
//!
//! ```
//! use deduxit::Limits;
//! use deduxit::linear::Mode;
//! use deduxit::linear::mist::{Safety, read};
//! use deduxit::linear::search::{Options, prove};
//!
//! let text = "#expected result: unsafe\n\
//!             vars x y\n\
//!             rules x >= 1 -> x' = x - 1, y' = y + 2;\n\
//!             init x = 1, y >= 0\n\
//!             target y >= 2\n";
//! let problem = read(text, &Limits::default())?;
//! assert_eq!(problem.expected, Some(Safety::Unsafe));
//! // `Display` writes the one-sided form: `!(x ⊸ y ⊗ y)` is `?(x ⊗ (~y ⅋ ~y))`,
//! // and a token `x` left of `⊢` is `~x`.
//! assert_eq!(problem.sequent.to_string(), "⊢ ?(x ⊗ (~y ⅋ ~y)), ?~y, ~x, y ⊗ y");
//!
//! // Unsafe: a reachable marking covers the target, so the sequent is provable.
//! let mode = Mode::INTUITIONISTIC.with_affine();
//! let outcome = prove(&problem.sequent, mode, &Options::default())?;
//! assert!(outcome.verdict.proof().is_some());
//! # Ok::<(), deduxit::Error>(())
//! ```
//!
//! Needs the cargo feature `parse` (on by default).

use crate::hash::HashMap;
use crate::limits::{Limits, Refusal, Space};
use crate::linear::occurrences::Forest;
use crate::linear::sequents::{Atom, Term, TermId};
use crate::{Error, linear::Sequent};

/// A problem read from a `.spec` file by [`read`].
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct Problem {
    /// The problem as a Horn program for an affine mode: the rules under
    /// `!` and the initial marking left of `⊢`, the target right of it.
    pub sequent: Sequent,
    /// The answer the file's first line states (`#expected result: safe`
    /// or `unsafe`), or `None` if it states none.
    pub expected: Option<Safety>,
}

/// The answer to a coverability problem.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Safety {
    /// No marking reachable from the initial one covers the target: the
    /// sequent is unprovable in affine mode.
    Safe,
    /// Some reachable marking covers the target: the sequent is provable
    /// in affine mode.
    Unsafe,
}

/// Reads the text of a `.spec` file into a Horn program.
///
/// The file has four sections, in this order:
/// - `vars`: the counters' names;
/// - `rules`: each `guards -> updates;`, a guard `x >= k`, an update
///   `x' = x + k` or `x' = x - k`;
/// - `init`: `x = k` or `x >= k`; a counter not named starts at zero;
/// - `target`: lines of `x >= k`. The target is covered when every
///   condition of one of its lines holds.
///
/// A comma at the end of a line or at the start of the next joins the two
/// lines. An `invariants` section may follow the target; the reader skips
/// it, though its characters must be ones the format uses. From `#` to
/// the end of a line is a comment.
///
/// A rule takes from each counter the larger of its guard and its
/// decrement, since a counter does not go below zero. It gives back what
/// it took less the decrement plus the increment.
///
/// Every token is an occurrence of its counter's atom, so a few bytes
/// (`x = 4000000000`) can ask for billions of occurrences. The reader adds
/// up the tokens first and refuses a problem past `limits.occurrences`
/// before it builds anything of that size, as [`Forest::within`] would
/// refuse the sequent.
///
/// # Errors
///
/// - [`Error::Spec`] for text that is not such a problem: a character the
///   format does not use, a section missing or out of order, no target, a
///   counter not declared, a counter updated twice by one rule or from
///   another counter, a counter given twice in `init`, a count that is no
///   number below 2³², or a rule that gives 2³² tokens or more;
/// - [`Error::AtomName`] for a counter named by a keyword of the text
///   syntax: `par`, `top`, `bot`, `forall` or `exists`;
/// - [`Error::Refused`] with [`Refusal::Occurrences`] for more tokens
///   than `limits.occurrences`, or with [`Refusal::Index`] for more than
///   a forest can number.
#[expect(
    clippy::missing_panics_doc,
    reason = "the expects state facts of the problem the reader has checked"
)]
pub fn read(text: &str, limits: &Limits) -> Result<Problem, Error> {
    let expected = text.lines().next().and_then(|line| {
        let line = line.trim().strip_prefix('#')?.trim();
        match line.strip_prefix("expected result:")?.trim() {
            "safe" => Some(Safety::Safe),
            "unsafe" => Some(Safety::Unsafe),
            _ => None,
        }
    });
    let tokens = tokens(text)?;
    let mut reader = Reader { tokens, at: 0 };
    reader.keyword("vars")?;
    let mut names = Vec::new();
    while !reader.at_keyword("rules") {
        let name = reader.name()?;
        crate::linear::sequents::name::check(name)?;
        names.push(name);
    }
    let index: HashMap<&str, usize> = names.iter().enumerate().map(|(i, &n)| (n, i)).collect();
    let counter = |name: &str| {
        index
            .get(name)
            .copied()
            .ok_or_else(|| error(format!("the counter `{name}` is not declared")))
    };
    reader.keyword("rules")?;
    let mut clauses = Vec::new();
    while !reader.at_keyword("init") {
        clauses.push(reader.rule(&names, &counter)?);
    }
    reader.keyword("init")?;
    let mut tokens = vec![0u32; names.len()];
    let mut parameters = Vec::new();
    let mut initial = vec![false; names.len()];
    while !reader.at_keyword("target") {
        let name = reader.name()?;
        let x = counter(name)?;
        // Read either way, `x >= 1, x = 3` would be neither constraint.
        if std::mem::replace(&mut initial[x], true) {
            return Err(error(format!(
                "the counter `{name}` is given twice in `init`"
            )));
        }
        let at_least = match reader.next()? {
            Token::Word("=") => false,
            Token::Word(">=") => true,
            token => return Err(error(format!("expected `=` or `>=` at {token}"))),
        };
        tokens[x] = reader.number()?;
        if at_least {
            parameters.push(x);
        }
        reader.comma_or_line();
    }
    reader.keyword("target")?;
    let mut targets = Vec::new();
    let mut target = Vec::new();
    while !reader.at_keyword("invariants") && reader.at < reader.tokens.len() {
        let name = reader.name()?;
        let x = counter(name)?;
        reader.word(">=")?;
        target.push((x, reader.number()?));
        if !reader.comma_or_line() {
            targets.push(merged(std::mem::take(&mut target)));
        }
    }
    if !target.is_empty() {
        targets.push(merged(target));
    }
    if targets.is_empty() {
        return Err(error("no target".to_owned()));
    }

    // Every token is an occurrence of its atom: count them before building.
    let total = |counts: &[(usize, u32)]| counts.iter().map(|&(_, k)| u64::from(k)).sum::<u64>();
    let tokens_written = tokens
        .iter()
        .map(|&k| u64::from(k))
        .chain(clauses.iter().map(|(i, o)| total(i) + total(o)))
        .chain(targets.iter().map(|t| total(t)))
        .fold(0u64, u64::saturating_add);
    if let Some(limit) = limits.occurrences
        && tokens_written > limit
    {
        return Err(Error::Refused(Refusal::Occurrences {
            occurrences: tokens_written,
            limit,
        }));
    }
    if tokens_written > Forest::MOST {
        return Err(Error::Refused(Refusal::Index {
            what: Space::Occurrence,
            count: tokens_written,
            most: Forest::MOST,
        }));
    }
    // One-sided, as the parser would read `rules, params, tokens |- goal`:
    // a rule `!(in ⊸ out)` is `?(in ⊗ ~out)`, a token `x` is `~x`. Every
    // token of a counter is one shared literal of the arena.
    let mut arena = Arena::new(&names);
    let mut roots = Vec::new();
    for (inputs, outputs) in &clauses {
        let (taken, given) = (arena.tensor(inputs), arena.par_of_duals(outputs));
        let clause = arena.push(Term::Tensor(taken, given));
        roots.push(arena.push(Term::Quest(clause)));
    }
    let goal = if let [target] = &targets[..] {
        arena.tensor(target)
    } else {
        let name = (0..)
            .map(|i| {
                if i == 0 {
                    "goal".to_owned()
                } else {
                    format!("goal_{i}")
                }
            })
            .find(|name| !index.contains_key(name.as_str()))
            .expect("some name is fresh");
        let goal = arena.fresh(name);
        for target in &targets {
            let covered = arena.tensor(target);
            let reached = arena.push(Term::DualAtom(goal));
            let clause = arena.push(Term::Tensor(covered, reached));
            roots.push(arena.push(Term::Quest(clause)));
        }
        arena.push(Term::Atom(goal))
    };
    for &x in &parameters {
        let dual = arena.dual(x);
        roots.push(arena.push(Term::Quest(dual)));
    }
    for (x, &k) in tokens.iter().enumerate() {
        if k > 0 {
            let dual = arena.dual(x);
            roots.extend(std::iter::repeat_n(dual, k as usize));
        }
    }
    roots.push(goal);
    // Everything but the goal stands left of `⊢`. `optimize` merges equal
    // terms, as the parser does with what it reads.
    let antecedents = Some(antecedents(roots.len())?);
    let mut sequent = Sequent::from_parts(arena.terms, roots, arena.atoms, antecedents);
    sequent.optimize();
    Ok(Problem { sequent, expected })
}

/// Returns how many of a sequent's roots stand left of `⊢`: all but the
/// goal.
///
/// # Errors
///
/// [`Refusal::Index`] for more than `u32::MAX`, which the tokens alone
/// stay below but the tokens with one root per rule, target line and
/// parameter may pass.
fn antecedents(roots: usize) -> Result<u32, Error> {
    let count = roots.saturating_sub(1);
    u32::try_from(count).map_err(|_| {
        Error::Refused(Refusal::Index {
            what: Space::Member,
            count: u64::try_from(count).unwrap_or(u64::MAX),
            most: u64::from(u32::MAX),
        })
    })
}

/// The arena of a problem's sequent while it is built: its terms, its
/// atoms' names, and each counter's atom and two literals, made on first
/// use and shared by every occurrence after.
struct Arena<'a> {
    /// The counters' names.
    names: &'a [&'a str],
    /// The terms.
    terms: Vec<Term>,
    /// The atoms' names, in the order they were made.
    atoms: Vec<String>,
    /// Each counter's atom, its literal and its negation, once made.
    made: Vec<(Option<Atom>, Option<TermId>, Option<TermId>)>,
}

impl<'a> Arena<'a> {
    /// Returns an empty arena over the counters.
    fn new(names: &'a [&'a str]) -> Self {
        Self {
            names,
            terms: Vec::new(),
            atoms: Vec::new(),
            made: vec![(None, None, None); names.len()],
        }
    }

    /// Pushes a term and returns its id.
    fn push(&mut self, term: Term) -> TermId {
        self.terms.push(term);
        TermId::new(self.terms.len() as u32 - 1)
    }

    /// Adds an atom of that name and returns it.
    fn fresh(&mut self, name: String) -> Atom {
        self.atoms.push(name);
        Atom::new(self.atoms.len() as u32 - 1)
    }

    /// Returns counter `x`'s atom, made on first use.
    fn atom(&mut self, x: usize) -> Atom {
        if let Some(atom) = self.made[x].0 {
            return atom;
        }
        let atom = self.fresh(self.names[x].to_owned());
        self.made[x].0 = Some(atom);
        atom
    }

    /// Returns counter `x`'s literal, made on first use.
    fn var(&mut self, x: usize) -> TermId {
        if let Some(var) = self.made[x].1 {
            return var;
        }
        let atom = self.atom(x);
        let var = self.push(Term::Atom(atom));
        self.made[x].1 = Some(var);
        var
    }

    /// Returns counter `x`'s negated literal, made on first use.
    fn dual(&mut self, x: usize) -> TermId {
        if let Some(dual) = self.made[x].2 {
            return dual;
        }
        let atom = self.atom(x);
        let dual = self.push(Term::DualAtom(atom));
        self.made[x].2 = Some(dual);
        dual
    }

    /// Returns the tensor of the tokens `counts` names, grouped to the
    /// left, or `1` for none.
    fn tensor(&mut self, counts: &[(usize, u32)]) -> TermId {
        let mut tensor = None;
        for &(x, k) in counts {
            let var = self.var(x);
            for _ in 0..k {
                tensor = Some(match tensor {
                    None => var,
                    Some(left) => self.push(Term::Tensor(left, var)),
                });
            }
        }
        tensor.unwrap_or_else(|| self.push(Term::One))
    }

    /// Returns the `⅋` of the negated tokens `counts` names, the negation
    /// of their [`tensor`](Self::tensor), or `⊥` for none.
    fn par_of_duals(&mut self, counts: &[(usize, u32)]) -> TermId {
        let mut par = None;
        for &(x, k) in counts {
            let dual = self.dual(x);
            for _ in 0..k {
                par = Some(match par {
                    None => dual,
                    Some(left) => self.push(Term::Par(left, dual)),
                });
            }
        }
        par.unwrap_or_else(|| self.push(Term::Bot))
    }
}

/// Returns the error of a text that is no `.spec` problem.
fn error(message: String) -> Error {
    Error::Spec { message }
}

/// Some counters' counts, each a counter's index and its count, sorted by
/// counter. Sparse, since a rule names a few of the tens of thousands of
/// counters a file may declare.
type Counts = Vec<(usize, u32)>;

/// Returns the counts sorted by counter and without zeros; a counter
/// named twice keeps its larger count.
fn merged(mut counts: Counts) -> Counts {
    counts.sort_unstable();
    let mut merged: Counts = Vec::with_capacity(counts.len());
    for (x, k) in counts {
        match merged.last_mut() {
            Some((y, m)) if *y == x => *m = (*m).max(k),
            _ => merged.push((x, k)),
        }
    }
    merged.retain(|&(_, k)| k > 0);
    merged
}

/// A token of a `.spec` file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Token<'a> {
    /// A name, a number or an operator.
    Word(&'a str),
    /// The end of a line.
    Line,
}

impl std::fmt::Display for Token<'_> {
    /// Writes the token for an error message.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Token::Word(word) => write!(f, "`{word}`"),
            Token::Line => f.write_str("the end of a line"),
        }
    }
}

/// Returns a file's tokens without its comments: words of ASCII letters,
/// digits and `_` (names and numbers), the operators `>=`, `->`, `=`,
/// `'`, `+`, `-`, `,` and `;`, and the ends of lines. Any other character
/// outside white space is an error.
fn tokens(text: &str) -> Result<Vec<Token<'_>>, Error> {
    let mut tokens = Vec::new();
    for line in text.lines() {
        let line = line.split_once('#').map_or(line, |(code, _)| code);
        let mut at = 0;
        while at < line.len() {
            let rest = &line[at..];
            let c = rest.chars().next().expect("not at the end");
            let length = if c.is_whitespace() {
                at += c.len_utf8();
                continue;
            } else if c.is_ascii_alphanumeric() || c == '_' {
                rest.find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
                    .unwrap_or(rest.len())
            } else if rest.starts_with(">=") || rest.starts_with("->") {
                2
            } else if "=+-,;'".contains(c) {
                1
            } else {
                return Err(error(format!("unexpected `{c}`")));
            };
            tokens.push(Token::Word(&rest[..length]));
            at += length;
        }
        tokens.push(Token::Line);
    }
    Ok(tokens)
}

/// Reads a file's tokens in order.
struct Reader<'a> {
    /// The tokens.
    tokens: Vec<Token<'a>>,
    /// The next token's index.
    at: usize,
}

impl<'a> Reader<'a> {
    /// Skips ends of lines.
    fn skip_lines(&mut self) {
        while self.tokens.get(self.at) == Some(&Token::Line) {
            self.at += 1;
        }
    }

    /// Reads the next word after any ends of lines, or fails where the
    /// file ends.
    fn next(&mut self) -> Result<Token<'a>, Error> {
        self.skip_lines();
        let token = *self
            .tokens
            .get(self.at)
            .ok_or_else(|| error("the file ends early".to_owned()))?;
        self.at += 1;
        Ok(token)
    }

    /// Skips any ends of lines and returns whether the next word is
    /// `keyword`.
    fn at_keyword(&mut self, keyword: &str) -> bool {
        self.skip_lines();
        self.tokens.get(self.at) == Some(&Token::Word(keyword))
    }

    /// Reads the word `word`, or fails naming what stands there instead.
    fn word(&mut self, word: &str) -> Result<(), Error> {
        match self.next()? {
            Token::Word(w) if w == word => Ok(()),
            token => Err(error(format!("expected `{word}` at {token}"))),
        }
    }

    /// Reads the keyword `keyword` that starts a section, or fails naming
    /// that section.
    fn keyword(&mut self, keyword: &str) -> Result<(), Error> {
        self.word(keyword)
            .map_err(|_| error(format!("expected the section `{keyword}`")))
    }

    /// Reads a name: a word that starts with an ASCII letter or `_`.
    fn name(&mut self) -> Result<&'a str, Error> {
        match self.next()? {
            Token::Word(w) if w.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_') => Ok(w),
            token => Err(error(format!("expected a name at {token}"))),
        }
    }

    /// Reads a number below 2³².
    fn number(&mut self) -> Result<u32, Error> {
        match self.next()? {
            Token::Word(w) => w
                .parse()
                .map_err(|_| error(format!("expected a number below 2³² at `{w}`"))),
            token => Err(error(format!("expected a number at {token}"))),
        }
    }

    /// Reads a comma if one comes next, on this line or first on a later
    /// one. Returns whether one did or the current line goes on, so that a
    /// comma at the end of a line or at the start of the next joins the
    /// two, as qcover's files write long initial markings.
    fn comma_or_line(&mut self) -> bool {
        let mut at = self.at;
        while self.tokens.get(at) == Some(&Token::Line) {
            at += 1;
        }
        match self.tokens.get(at) {
            Some(Token::Word(",")) => {
                self.at = at + 1;
                true
            }
            Some(Token::Word(_)) => at == self.at,
            _ => false,
        }
    }

    /// Reads a rule, `guards -> updates;`, as the tokens it takes from
    /// each counter and those it gives.
    fn rule(
        &mut self,
        names: &[&str],
        counter: &dyn Fn(&str) -> Result<usize, Error>,
    ) -> Result<(Counts, Counts), Error> {
        let mut guards = Vec::new();
        let mut changes: Vec<(usize, i64)> = Vec::new();
        if !matches!(self.tokens.get(self.at), Some(Token::Word("->"))) {
            loop {
                let x = counter(self.name()?)?;
                self.word(">=")?;
                guards.push((x, self.number()?));
                match self.next()? {
                    Token::Word(",") => {}
                    Token::Word("->") => break,
                    token => return Err(error(format!("expected `,` or `->` at {token}"))),
                }
            }
        } else {
            self.at += 1;
        }
        loop {
            if let Ok(Token::Word(";")) = self.peek() {
                self.at += 1;
                break;
            }
            let name = self.name()?;
            let x = counter(name)?;
            self.word("'")?;
            self.word("=")?;
            if self.name()? != name {
                return Err(error(format!("`{name}'` is updated from another counter")));
            }
            let sign = match self.next()? {
                Token::Word("+") => 1,
                Token::Word("-") => -1,
                token => return Err(error(format!("expected `+` or `-` at {token}"))),
            };
            let k = i64::from(self.number()?);
            changes.push((x, sign * k));
            match self.next()? {
                Token::Word(",") => {}
                Token::Word(";") => break,
                token => return Err(error(format!("expected `,` or `;` at {token}"))),
            }
        }
        let guards = merged(guards);
        changes.sort_unstable();
        if let Some(pair) = changes.windows(2).find(|pair| pair[0].0 == pair[1].0) {
            return Err(error(format!(
                "a rule updates `{}` twice",
                names[pair[0].0]
            )));
        }
        // Both are sorted by counter: one merge.
        let (mut inputs, mut outputs) = (Vec::new(), Vec::new());
        let (mut g, mut c) = (0, 0);
        while g < guards.len() || c < changes.len() {
            let x = match (guards.get(g), changes.get(c)) {
                (Some(&(a, _)), Some(&(b, _))) => a.min(b),
                (Some(&(a, _)), None) => a,
                (None, Some(&(b, _))) => b,
                (None, None) => unreachable!("the loop's condition"),
            };
            let guard = match guards.get(g) {
                Some(&(y, k)) if y == x => {
                    g += 1;
                    k
                }
                _ => 0,
            };
            let change = match changes.get(c) {
                Some(&(y, d)) if y == x => {
                    c += 1;
                    d
                }
                _ => 0,
            };
            let taken = i64::from(guard).max(-change);
            let given = u32::try_from(taken + change)
                .map_err(|_| error(format!("a rule gives `{}` 2³² tokens or more", names[x])))?;
            let taken = u32::try_from(taken).expect("a guard or a decrement");
            if taken > 0 {
                inputs.push((x, taken));
            }
            if given > 0 {
                outputs.push((x, given));
            }
        }
        Ok((inputs, outputs))
    }

    /// Returns the next word after any ends of lines, without reading it.
    fn peek(&mut self) -> Result<Token<'a>, Error> {
        let token = self.next()?;
        self.at -= 1;
        Ok(token)
    }
}

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

    /// More antecedents than a sequent counts are refused, never wrapped.
    #[test]
    #[cfg(target_pointer_width = "64")]
    fn refuses_more_antecedents_than_a_sequent_counts() {
        let most = usize::try_from(u32::MAX).unwrap();
        assert_eq!(antecedents(most + 1), Ok(u32::MAX));
        assert_eq!(
            antecedents(most + 2),
            Err(Error::Refused(Refusal::Index {
                what: Space::Member,
                count: u64::from(u32::MAX) + 1,
                most: u64::from(u32::MAX),
            }))
        );
    }

    /// Rules over several lines, guards above a decrement, a decrement
    /// without a guard, a rule without guards, comments, parameters, lines
    /// joined by a comma at the end of one or the start of the next, a
    /// target of two lines and a counter left out of `init`, and malformed
    /// files refused.
    #[test]
    fn reads_problems() {
        let text = "# a comment\n\
                    vars\n  a b c\n\
                    rules\n  a >= 2 ->\n    a' = a - 1,\n    b' = b + 1;\n\
                    \x20 b >= 1 -> c' = c - 1;   # takes a c it does not test\n\
                    \x20 -> a' = a + 1;\n\
                    init\n  a = 1\n  , b >= 2\n\
                    target\n  c >= 1,\n  b >= 1\n  a >= 3\n\
                    invariants\n  a = 1, b = 1\n";
        let problem = read(text, &Limits::default()).unwrap();
        assert_eq!(problem.expected, None);
        let expected: Sequent = "!(a * a -o a * b), !(b * c -o b), !(1 -o a), \
                                 !(b * c -o goal), !(a * a * a -o goal), !b, a, b, b |- goal"
            .parse()
            .unwrap();
        // The same formulas, in any order.
        let formulas = |sequent: &Sequent| {
            let mut formulas: Vec<String> = sequent.to_string()[4..]
                .split(", ")
                .map(str::to_owned)
                .collect();
            formulas.sort();
            formulas
        };
        assert_eq!(formulas(&problem.sequent), formulas(&expected));

        for bad in [
            "rules init target a >= 1",
            "vars a rules init a = 1",
            "vars a rules a >= 1 -> b' = b + 1; init target a >= 1",
            "vars a b rules a >= 1 -> a' = b + 1; init target a >= 1",
            "vars a rules a >= 1 -> a' = a + 1, a' = a - 1; init target a >= 1",
            "vars a b rules a >= 4 -> a' = a - 4, b' = b + 1; init a >= 1, a = 3 target b >= 1",
            "vars a rules init a = 4294967296 target a >= 1",
        ] {
            assert!(
                matches!(read(bad, &Limits::default()), Err(Error::Spec { .. })),
                "{bad:?}"
            );
        }
        for bad in [
            "vars top rules init target top >= 1",
            "vars forall rules init target forall >= 1",
        ] {
            assert!(
                matches!(read(bad, &Limits::default()), Err(Error::AtomName { .. })),
                "{bad:?}"
            );
        }
        // The expected result is the first line's; two guards on a counter
        // are the larger, and a guard of zero asks for no token.
        for (header, expected) in [
            ("# expected result: safe", Some(Safety::Safe)),
            ("#expected result: unsafe", Some(Safety::Unsafe)),
            ("# expected result: maybe", None),
        ] {
            let text = format!("{header}\nvars a rules init a = 1 target a >= 1");
            let problem = read(&text, &Limits::default()).unwrap();
            assert_eq!(problem.expected, expected, "{header}");
        }
        let text = "vars a b rules a >= 1, a >= 3, b >= 0 -> b' = b + 1; init a = 3 target b >= 1";
        let problem = read(text, &Limits::default()).unwrap();
        let expected: Sequent = "!(a * a * a -o a * a * a * b), a, a, a |- b"
            .parse()
            .unwrap();
        assert_eq!(formulas(&problem.sequent), formulas(&expected));
        // The messages say what is wrong.
        for (text, message) in [
            (
                "vars a rules a >= 1 -> a' - a + 1; init a = 1 target a >= 1",
                "expected `=` at `-`",
            ),
            (
                "vars 1x rules init target a >= 1",
                "expected a name at `1x`",
            ),
            (
                "vars a b rules a >= 1 -> a' = b + 1; init target a >= 1",
                "`a'` is updated from another counter",
            ),
        ] {
            match read(text, &Limits::default()) {
                Err(Error::Spec { message: m }) => assert_eq!(m, message, "{text}"),
                other => panic!("{text}: {other:?}"),
            }
        }
        // Five bytes of a count ask for more tokens than the limit, which
        // is refused before any is written.
        let big = "vars a rules init a = 99999 target a >= 1";
        let limits = |n| Limits::default().with_occurrences(Some(n));
        assert!(super::read(big, &limits(100_000)).is_ok());
        assert!(matches!(
            super::read(big, &limits(99_999)),
            Err(Error::Refused(Refusal::Occurrences { .. }))
        ));
        // A rule's tokens are those it takes and those it gives: 4 of the
        // initial marking, 2 taken and 3 given, 3 of the target.
        let rule = "vars a b rules a >= 2 -> a' = a - 2, b' = b + 3; init a = 4 target b >= 3";
        assert!(super::read(rule, &limits(12)).is_ok());
        assert!(matches!(
            super::read(rule, &limits(11)),
            Err(Error::Refused(Refusal::Occurrences {
                occurrences: 12,
                ..
            }))
        ));
    }
}