deduxit 0.3.0

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

//! The resources a call may use, what a long call tells its stop, and why
//! a call was refused without an answer.
//!
//! Every long call of the crate takes a [`Limits`] and a stop, a closure
//! `FnMut(Progress) -> bool` that the call asks at a bounded interval of
//! work and that ends the call when it returns `true`. The crate reads no
//! clock: a front end with a deadline reads its own clock in the stop, as
//! often as the work done ([`Progress::work`]) says it should. A call
//! that a bound or the stop ends answers with a [`Refusal`], which is
//! never a verdict on its input.
//!
//! The long calls, the fields of [`Limits`] that bind each, and how often
//! each asks its stop:
//!
//! | call | bound by | asks the stop |
//! |---|---|---|
//! | `Sequent::parse_within`, `lltp::read`, `mist::read`, `ordinary::Sequent::parse_within`, `ordinary::read_tptp`, `wire::upgrade`, `wire::Within` | `occurrences` | never: linear in the input |
//! | `Forest::within`, `Interactive::within`, `ordinary::translate` | `occurrences` | never: linear in the bound |
//! | `search::prove_within`, `search::prove_goal` | `memory_bytes`, `recursion_depth`, `occurrences`, `work` (the search's and the check's) | at every node an engine searches, and in its long passes |
//! | `search::batch::run`, `search::batch::prove` | each search's limits, the batch's memory shared out | through each problem's work, and `Results::cancel` |
//! | `Proof::check_within` | `memory_bytes`, `work` | every 4 096 nodes or 65 536 units of work |
//! | `proofs::cut::step`, `proofs::cut::eliminate` | `cut::Options::steps` and `nodes`; `memory_bytes` and `work` for each check, `memory_bytes` for a step's specialized erasure and the proof it makes | between steps, as each check does, and every 4 096 places a specialized erasure makes |
//! | `Proof::derivation_size`, `Proof::derivation_within`, `Interactive::derivation_within` | `derivation_bytes`, `memory_bytes` | as the check, then at every inference built |
//! | `Interactive::close`, `close_with`, `close_all`, `proof` | the search's and the derivation's | as the search and the derivation |
//! | `ProofStructure::is_correct` | none: its memory is linear in the structure | at every round of the criterion |
//! | `ProofStructure::from_proof`, `ProofStructure::sequentialize` | `memory_bytes` | at every node, at every stage |
//! | `ordinary::Image::read_back`, `ordinary::Derivation::check` | `derivation_bytes`, `memory_bytes`; `work` inferences checked | at every inference |
//! | `ordinary::decide` | all of the above it runs | as each step |
//! | `ordinary::Interactive::within` | `occurrences` | never: linear in the bound |
//! | `ordinary::Interactive::apply` | `derivation_bytes` of the start, for the run of structural rules an axiom or a shared rule makes, by an estimate before it is made | never: within the bound |
//! | `ordinary::Interactive::close`, `hint` | as `ordinary::decide`; `derivation_bytes` for the graft | as `ordinary::decide` |
//! | `ordinary::Interactive::derivation_within`, `finished` | `derivation_bytes` by an estimate before anything is built; `work` for the check | before building, then as the check |
//! | `export::{latex, typst, svg, rocq}::write`, `Derivation::write_text`, `write_steps` | the derivation's, when it was made | at every inference written |
//! | `export::{latex, typst, svg}::sequent` | `derivation_bytes`, by an estimate before anything is laid out | never: linear in the estimate |
//! | `export::svg::net` | `derivation_bytes` | as the criterion |
//! | `export::{png, pdf}::from_svg` | `memory_bytes`, the pixel bound of the options | never: refused before the render starts |

use crate::errors::counted;
use std::fmt::{self, Display, Formatter};

#[cfg(feature = "serialize")]
use serde::{Deserialize, Serialize};

/// The resources a call may use, which the library enforces. `None` in an
/// optional field means no bound; the defaults are the named constants.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serialize",
    derive(Serialize, Deserialize),
    serde(default, deny_unknown_fields)
)]
pub struct Limits {
    /// The most bytes a call holds at once beyond its input: a search's
    /// growing structures, a check's pass, a derivation's making, a
    /// render's estimate. The sequent, its forest (bounded by
    /// [`occurrences`](Self::occurrences)), the proof returned, the
    /// threads' stacks and the allocator's own overhead are not counted.
    #[cfg_attr(feature = "serialize", serde(with = "crate::serialize::exact"))]
    pub memory_bytes: Option<u64>,
    /// The most subformula occurrences a sequent may unfold to, on every
    /// reader and wherever a forest is built. The text readers also refuse
    /// a text nested deeper than it (more `(` or `~` waiting at once than
    /// the bound), as if it had that many occurrences.
    #[cfg_attr(feature = "serialize", serde(with = "crate::serialize::exact"))]
    pub occurrences: Option<u64>,
    /// The most first-order terms a sequent's atoms may unfold to
    /// ([`Sequent::fo_size`](crate::linear::Sequent::fo_size)), and the most
    /// entries a proof's instance table may hold, on every reader: a short
    /// document of shared terms can name an atom of exponential length.
    #[cfg_attr(feature = "serialize", serde(with = "crate::serialize::exact"))]
    pub terms: Option<u64>,
    /// The most bytes a derivation, or the drawing of a net or a sequent,
    /// may be estimated at; past it nothing is made.
    #[cfg_attr(feature = "serialize", serde(with = "crate::serialize::exact"))]
    pub derivation_bytes: Option<u64>,
    /// The most units of work a call may do: the proof checker counts a
    /// node or an entry of a sequent its rules handle, the ordinary
    /// checker an inference, a search its engine's unit (each
    /// [`Engine`](crate::linear::search::Engine) variant says which; where the net
    /// engine takes a goal over at another engine's limit, both engines'
    /// units together). A search past
    /// it is unknown with `Reason::WorkLimit`, as is one whose proof's
    /// check passes it; a check alone refuses with
    /// `Error::Check(CheckError::Refused)`.
    #[cfg_attr(feature = "serialize", serde(with = "crate::serialize::exact"))]
    pub work: Option<u64>,
    /// The deepest recursion on any one stack; every thread the library
    /// starts is sized for it ([`stack_bytes`](Self::stack_bytes)). The
    /// focused engine takes a level per asynchronous phase, per stable
    /// sequent and per focus, a chain of `⅋`, `⊥` and `?` rules or of
    /// forced splits none, so a formula copied `k` times on a branch takes
    /// `k` focus levels; the additive path takes one per pair.
    pub recursion_depth: u32,
}

impl Limits {
    /// The default memory bound: one gibibyte.
    pub const DEFAULT_MEMORY_BYTES: u64 = 1 << 30;
    /// The default bound on occurrences: fifty million, above the largest
    /// problem of the LLTP library (27.8 million); a forest takes about
    /// 25 bytes an occurrence.
    pub const DEFAULT_OCCURRENCES: u64 = 50_000_000;
    /// The default bound on first-order terms: as many as occurrences, so
    /// that a sequent's terms take no more than its forest.
    pub const DEFAULT_TERMS: u64 = 50_000_000;
    /// The default bound on a derivation's estimated size: 64 mebibytes.
    pub const DEFAULT_DERIVATION_BYTES: u64 = 64 << 20;
    /// The default recursion depth: 2048 levels, which fit a main
    /// thread's stack of 8 MiB in an optimized build.
    pub const DEFAULT_RECURSION_DEPTH: u32 = 2048;

    /// No bound at all but the default recursion depth, which every stack
    /// needs.
    pub const UNBOUNDED: Self = Self {
        memory_bytes: None,
        occurrences: None,
        terms: None,
        derivation_bytes: None,
        work: None,
        recursion_depth: Self::DEFAULT_RECURSION_DEPTH,
    };

    /// The stack one level of the search's recursion may take: twice the
    /// most it was measured to take, on a Mix of pairs whose parts are
    /// recursed into (6.5 KiB unoptimized, 1.4 KiB optimized, on x86-64),
    /// the deepest beside a chain of tensors whose splits are searched
    /// (5.8 KiB, 1.2 KiB) and nested `&` (1.4 KiB, 0.4 KiB).
    const PER_LEVEL: usize = if cfg!(debug_assertions) { 13312 } else { 3072 };

    /// What a thread needs below and beside the recursion: the frames of
    /// its caller, the search's set-up and its proof's checks.
    const RESERVE: usize = 1 << 20;

    /// Returns the stack a thread needs to recurse to
    /// [`recursion_depth`](Self::recursion_depth), at least a main
    /// thread's 8 MiB.
    #[must_use]
    pub const fn stack_bytes(&self) -> usize {
        let needed = (self.recursion_depth as usize)
            .saturating_mul(Self::PER_LEVEL)
            .saturating_add(Self::RESERVE);
        if needed > 8 << 20 { needed } else { 8 << 20 }
    }

    /// Returns the deepest recursion a stack of `bytes` holds, the inverse
    /// of [`stack_bytes`](Self::stack_bytes) above its floor.
    #[must_use]
    pub const fn recursion_depth_for_stack(bytes: usize) -> u32 {
        let levels = bytes.saturating_sub(Self::RESERVE) / Self::PER_LEVEL;
        if levels > u32::MAX as usize {
            u32::MAX
        } else {
            levels as u32
        }
    }

    /// Returns the limits with another memory bound.
    #[must_use]
    pub const fn with_memory_bytes(mut self, memory_bytes: Option<u64>) -> Self {
        self.memory_bytes = memory_bytes;
        self
    }

    /// Returns the limits with another bound on occurrences.
    #[must_use]
    pub const fn with_occurrences(mut self, occurrences: Option<u64>) -> Self {
        self.occurrences = occurrences;
        self
    }

    /// Returns the limits with another bound on first-order terms.
    #[must_use]
    pub const fn with_terms(mut self, terms: Option<u64>) -> Self {
        self.terms = terms;
        self
    }

    /// Returns the limits with another bound on a derivation's size.
    #[must_use]
    pub const fn with_derivation_bytes(mut self, derivation_bytes: Option<u64>) -> Self {
        self.derivation_bytes = derivation_bytes;
        self
    }

    /// Returns the limits with another bound on a search's work.
    #[must_use]
    pub const fn with_work(mut self, work: Option<u64>) -> Self {
        self.work = work;
        self
    }

    /// Returns the limits with another recursion depth.
    #[must_use]
    pub const fn with_recursion_depth(mut self, recursion_depth: u32) -> Self {
        self.recursion_depth = recursion_depth;
        self
    }
}

impl Default for Limits {
    /// Returns the default bounds, each a named constant.
    fn default() -> Self {
        Self {
            memory_bytes: Some(Self::DEFAULT_MEMORY_BYTES),
            occurrences: Some(Self::DEFAULT_OCCURRENCES),
            terms: Some(Self::DEFAULT_TERMS),
            derivation_bytes: Some(Self::DEFAULT_DERIVATION_BYTES),
            work: None,
            recursion_depth: Self::DEFAULT_RECURSION_DEPTH,
        }
    }
}

/// What a long call tells its stop each time it asks it.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(Serialize))]
pub struct Progress {
    /// The units of work done since the previous poll, the unit of
    /// [`Limits::work`].
    pub work: u64,
    /// The units of work done since the call began.
    pub done: u64,
    /// The bytes the call holds by its own count now: the proof checker's
    /// pass and what derives from it fill it in, the net calls their
    /// estimate (the criterion alone its working memory); a search, whose
    /// two searches of the default bias each count their own half, leaves
    /// it zero.
    pub held_bytes: u64,
    /// What the call is doing.
    pub phase: Phase,
    /// The item of a call that runs several, by its place: a goal of a
    /// session's `close_all`, zero for every other call.
    pub item: u32,
}

impl Progress {
    /// Returns the progress of a call in `phase` that has done `done`
    /// units of work, `work` of them since the previous poll.
    pub(crate) const fn new(phase: Phase, work: u64, done: u64) -> Self {
        Self {
            work,
            done,
            held_bytes: 0,
            phase,
            item: 0,
        }
    }
}

/// What a long call is doing when it asks its stop or is refused.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serialize",
    derive(Serialize),
    serde(rename_all = "snake_case")
)]
pub enum Phase {
    /// Reading an input.
    #[default]
    Read,
    /// Searching for a proof.
    Search,
    /// Refuting a sequent after a search.
    Refute,
    /// Checking a proof.
    Check,
    /// Making a derivation.
    View,
    /// Writing a derivation in a format.
    Write,
    /// Rendering a drawing.
    Render,
    /// Building or judging a proof net.
    Net,
    /// Reading a proof back as one of ordinary logic or as a lambda-term.
    ReadBack,
    /// Eliminating the cuts of a proof.
    Eliminate,
}

impl Phase {
    /// Returns the phase as a lowercase noun phrase, as messages use it.
    pub const fn name(self) -> &'static str {
        match self {
            Self::Read => "reading",
            Self::Search => "search",
            Self::Refute => "refutation",
            Self::Check => "check",
            Self::View => "derivation",
            Self::Write => "writing",
            Self::Render => "render",
            Self::Net => "net",
            Self::ReadBack => "read-back",
            Self::Eliminate => "elimination",
        }
    }
}

/// What a count of [`Refusal::Index`] counts: the spaces whose indices
/// have a fixed width.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serialize",
    derive(Serialize),
    serde(rename_all = "snake_case")
)]
pub enum Space {
    /// The atoms of a sequent.
    Atom,
    /// The terms of a sequent's arena.
    Term,
    /// The nodes of a proof.
    Node,
    /// The occurrences of a forest.
    Occurrence,
    /// The members of a sequent of a proof, a derivation or a session.
    Member,
    /// The vertices of a proof structure.
    Vertex,
    /// The inferences of a derivation.
    Inference,
    /// The formulas of an ordinary arena.
    Formula,
    /// The symbols of a sequent's first-order tables.
    Symbol,
}

impl Space {
    /// Returns the noun that names one member of the space.
    pub(crate) const fn singular(self) -> &'static str {
        match self {
            Self::Atom => "atom",
            Self::Term => "term",
            Self::Node => "node",
            Self::Occurrence => "occurrence",
            Self::Member => "member",
            Self::Vertex => "vertex",
            Self::Inference => "inference",
            Self::Formula => "formula",
            Self::Symbol => "symbol",
        }
    }

    /// Returns the plural noun that counts members of the space.
    pub const fn plural(self) -> &'static str {
        match self {
            Self::Atom => "atoms",
            Self::Term => "terms",
            Self::Node => "nodes",
            Self::Occurrence => "occurrences",
            Self::Member => "members",
            Self::Vertex => "vertices",
            Self::Inference => "inferences",
            Self::Formula => "formulas",
            Self::Symbol => "symbols",
        }
    }
}

/// Which bound of cut elimination a [`Refusal::Elimination`] reached.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(
    feature = "serialize",
    derive(Serialize),
    serde(rename_all = "snake_case")
)]
pub enum Bound {
    /// The number of steps.
    Steps,
    /// The nodes of a proof a step makes.
    Nodes,
    /// The vertices of a proof net a step makes.
    Vertices,
}

/// Why a call was given up without an answer: a bound the caller set, or
/// a default, refused it, or the caller's stop ended it. A refusal says
/// nothing of the input; lifting the bound may answer.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(
    feature = "serialize",
    derive(Serialize),
    serde(tag = "kind", rename_all = "snake_case")
)]
pub enum Refusal {
    /// The caller's stop ended the call.
    #[non_exhaustive]
    Stopped {
        /// What the call was doing.
        phase: Phase,
    },
    /// The call would have held more memory than its bound.
    #[non_exhaustive]
    Memory {
        /// What the call was doing.
        phase: Phase,
        /// The bound, [`Limits::memory_bytes`].
        limit_bytes: u64,
        /// What the call would have needed, where it was estimated before
        /// anything was made.
        needed_bytes: Option<u64>,
    },
    /// A sequent unfolds to more occurrences than the bound: the count, or
    /// a number of them at which the count stopped.
    #[non_exhaustive]
    Occurrences {
        /// How many occurrences, or a number past the bound.
        occurrences: u64,
        /// The bound, [`Limits::occurrences`].
        limit: u64,
    },
    /// A sequent's atoms unfold to more first-order terms than the bound,
    /// or a proof's instance table holds more entries: the count, or a
    /// number of them at which the count stopped.
    #[non_exhaustive]
    Terms {
        /// How many terms or entries, or a number past the bound.
        terms: u64,
        /// The bound, [`Limits::terms`].
        limit: u64,
    },
    /// An output is estimated past its bound; nothing was made.
    #[non_exhaustive]
    Output {
        /// What was to be made: a derivation, a drawing.
        what: &'static str,
        /// The estimate.
        estimate_bytes: u64,
        /// The bound, [`Limits::derivation_bytes`].
        limit_bytes: u64,
        /// The least a smaller form of the output would take, where one
        /// was tried: a compact derivation's lower bound.
        least_bytes: Option<u64>,
    },
    /// A call did the most work its bound allows.
    #[non_exhaustive]
    Work {
        /// The bound, [`Limits::work`].
        limit: u64,
    },
    /// An image would have more pixels than its options allow.
    #[non_exhaustive]
    Pixels {
        /// The image's pixels.
        pixels: u64,
        /// The bound of the image's options.
        limit: u64,
    },
    /// Cut elimination reached its bound on steps or on a proof's nodes.
    #[non_exhaustive]
    Elimination {
        /// The bound reached.
        what: Bound,
        /// Its value, [`cut::Options::steps`](crate::linear::proofs::cut::Options::steps)
        /// or [`cut::Options::nodes`](crate::linear::proofs::cut::Options::nodes).
        limit: u64,
    },
    /// A count passes what a representation's indices can name, whatever
    /// a bound says.
    #[non_exhaustive]
    Index {
        /// What is counted.
        what: Space,
        /// The count, or a number past the most.
        count: u64,
        /// The most the representation holds.
        most: u64,
    },
}

impl Refusal {
    /// Returns the stable code a program branches on.
    pub const fn code(&self) -> &'static str {
        match self {
            Self::Stopped { .. } => "stopped",
            Self::Memory { .. } => "memory_limit",
            Self::Occurrences { .. } => "too_many_occurrences",
            Self::Terms { .. } => "too_many_terms",
            Self::Output { .. } => "output_too_large",
            Self::Work { .. } => "work_limit",
            Self::Pixels { .. } => "too_many_pixels",
            Self::Elimination { .. } => "elimination_limit",
            Self::Index { .. } => "index_limit",
        }
    }

    /// Returns the settings key whose bound refused the call; `None` for
    /// the stop and for a representation's width, which no setting lifts.
    pub const fn setting(&self) -> Option<&'static str> {
        match self {
            Self::Memory { .. } => Some("limits.memory_bytes"),
            Self::Occurrences { .. } => Some("limits.occurrences"),
            Self::Terms { .. } => Some("limits.terms"),
            Self::Output { .. } => Some("limits.derivation_bytes"),
            Self::Work { .. } => Some("limits.work"),
            Self::Pixels { .. } => Some("styles.png.pixels"),
            Self::Elimination {
                what: Bound::Steps, ..
            } => Some("cut.steps"),
            Self::Elimination {
                what: Bound::Nodes | Bound::Vertices,
                ..
            } => Some("cut.nodes"),
            Self::Stopped { .. } | Self::Index { .. } => None,
        }
    }

    /// Returns whether the caller's stop ended the call, rather than a
    /// bound.
    pub const fn is_stop(&self) -> bool {
        matches!(self, Self::Stopped { .. })
    }
}

impl Display for Refusal {
    /// Writes the reason in a sentence without a full stop.
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::Stopped { phase } => write!(f, "the {} was stopped", phase.name()),
            Self::Memory {
                phase,
                limit_bytes,
                needed_bytes: Some(needed),
            } => write!(
                f,
                "the {} would take {}, more than the memory limit of {}",
                phase.name(),
                counted(*needed, "byte", "bytes"),
                counted(*limit_bytes, "byte", "bytes")
            ),
            Self::Memory {
                phase,
                limit_bytes,
                needed_bytes: None,
            } => write!(
                f,
                "the {} takes more than the memory limit of {}",
                phase.name(),
                counted(*limit_bytes, "byte", "bytes")
            ),
            Self::Occurrences { occurrences, limit } => write!(
                f,
                "the sequent unfolds to at least {}, more than the limit of {limit}",
                counted(
                    *occurrences,
                    "subformula occurrence",
                    "subformula occurrences"
                )
            ),
            Self::Terms { terms, limit } => write!(
                f,
                "the first-order terms unfold to at least {}, more than the limit of {limit}",
                counted(*terms, "term", "terms")
            ),
            Self::Output {
                what,
                estimate_bytes,
                limit_bytes,
                least_bytes,
            } => {
                write!(
                    f,
                    "the {what} is estimated at {}, more than the limit of {limit_bytes}",
                    counted(*estimate_bytes, "byte", "bytes")
                )?;
                match least_bytes {
                    Some(least) => write!(
                        f,
                        ", and a compact one at {} at least",
                        counted(*least, "byte", "bytes")
                    ),
                    None => Ok(()),
                }
            }
            Self::Work { limit } => {
                write!(
                    f,
                    "the call did the most work allowed, {}",
                    counted(*limit, "unit", "units")
                )
            }
            Self::Pixels { pixels, limit } => write!(
                f,
                "the image would have {}, more than the limit of {limit}",
                counted(*pixels, "pixel", "pixels")
            ),
            Self::Elimination {
                what: Bound::Steps,
                limit,
            } => write!(f, "the elimination took the most steps allowed, {limit}"),
            Self::Elimination {
                what: Bound::Nodes,
                limit,
            } => write!(
                f,
                "the next step of the elimination makes a proof of more than {}",
                counted(*limit, "node", "nodes")
            ),
            Self::Elimination {
                what: Bound::Vertices,
                limit,
            } => write!(
                f,
                "the next step of the elimination makes a net of more than {}",
                counted(*limit, "vertex", "vertices")
            ),
            Self::Index { what, count, most } => write!(
                f,
                "{count} {} are more than this representation can index ({most})",
                what.plural()
            ),
        }
    }
}

impl std::error::Error for Refusal {}

/// Turns a progress stop into the plain condition a loop asks once per
/// unit of work in `phase`, telling the stop each unit and the units done.
pub(crate) fn counting(
    mut stop: impl FnMut(Progress) -> bool,
    phase: Phase,
) -> impl FnMut() -> bool {
    let mut done = 0u64;
    move || {
        done = done.saturating_add(1);
        stop(Progress::new(phase, 1, done))
    }
}