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

//! Writes sequents and proofs as LaTeX, Typst, SVG, PNG, PDF and Rocq.
//!
//! Each format is a module with one options value: start from its
//! `default()` and set the fields you want to change. To export a proof,
//! take its derivation with
//! [`Proof::derivation`](crate::linear::Proof::derivation) and hand it to
//! the format:
//!
//! | to get | call | cargo feature |
//! |---|---|---|
//! | a LaTeX proof tree, for the `ebproof` package | [`latex::to_string`] | `latex` |
//! | a Typst proof tree, for the `curryst` package | [`typst::to_string`] | `typst` |
//! | an SVG drawing | [`svg::to_string`] | `svg` |
//! | a drawing of a proof net | [`svg::net`] | `svg` |
//! | a PNG image | [`png::from_svg`] of the SVG text | `png` |
//! | a PDF | [`pdf::from_svg`] of the SVG text | `pdf` |
//! | a Rocq proof script that certifies the proof | [`rocq::to_string`] | `rocq` |
//!
//! Of these features, all but `png` and `pdf` are on by default. LaTeX, Typst and
//! SVG also write a sequent alone (`sequent`).
//!
//! # Examples
//!
//! A proof as LaTeX:
//!
#![cfg_attr(all(feature = "parse", feature = "latex"), doc = "```")]
#![cfg_attr(not(all(feature = "parse", feature = "latex")), doc = "```ignore")]
//! use deduxit::export::latex;
//! use deduxit::linear::{Mode, Options, Sequent, Verdict, prove};
//!
//! let sequent: Sequent = "A, A -o B |- B".parse()?;
//! let outcome = prove(&sequent, Mode::INTUITIONISTIC, &Options::default())?;
//! let Verdict::Proved(proof) = &outcome.verdict else {
//!     panic!("provable");
//! };
//! let tex = latex::to_string(&proof.derivation()?, &latex::Options::default())?;
//! assert!(tex.starts_with(r"\begin{prooftree}"));
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! # Writing as you go
//!
//! Each `to_string` has a `write` beside it, with the signature of the
//! text tree's [`Derivation::write_text`](crate::linear::Derivation::write_text).
//! It writes into any [`std::fmt::Write`] one inference at a time, and asks
//! a stop closure between two inferences; the closure returns `true` to
//! stop. Use it to write into your own buffer, or to stop a large export.
//! A closure that never stops is `|_| false`.
//!
//! # What every format shares
//!
//! - The output depends on the input and the options alone, byte for
//!   byte. Every options value has serde behind the cargo feature
//!   `serialize`, and [`Styles`] holds the options of every format in one
//!   value.
//! - The formats take anything [`Drawable`]: a derivation of linear logic,
//!   the two-sided view of a classical one, or a derivation of LK or LJ.
//! - LaTeX, Typst and Rocq write a fragment to paste into your document, or
//!   a document that compiles on its own ([`Form`]). SVG always writes a
//!   whole document.
//! - Formulas are bracketed as `Display` brackets them: every binary
//!   subformula of a formula in brackets. Derivations are drawn as
//!   `Display` draws them: one-sided, or two-sided with the hypotheses in
//!   the order of their ids when the derivation has a reading.
//! - Rules are labelled as [`Labels`](crate::linear::proofs::Labels) says,
//!   and an open goal is drawn as
//!   [`OpenGoal`](crate::linear::proofs::OpenGoal) says. In a compact
//!   derivation ([`Compact`](crate::linear::proofs::Compact)), an inference
//!   that stands for a run of a structural rule has its label starred.
//! - The writers keep their own stack, so a derivation of any height fits,
//!   and the text grows with the derivation, not with its width.

// A new variant of an enum of the calculus must be decided at every arm,
// never fall into an existing one.
#![deny(clippy::wildcard_enum_match_arm)]

#[cfg(feature = "latex")]
pub mod latex;
/// The symbol tables and the printers the targets share.
#[cfg(any(
    feature = "latex",
    feature = "typst",
    feature = "svg",
    feature = "rocq"
))]
pub(crate) mod notation;
#[cfg(feature = "pdf")]
pub mod pdf;
#[cfg(feature = "png")]
pub mod png;
#[cfg(feature = "rocq")]
pub mod rocq;
/// The options of every format in one value.
mod styles;
#[cfg(feature = "svg")]
pub mod svg;
#[cfg(feature = "typst")]
pub mod typst;

pub use styles::Styles;

/// Returns the forest of a sequent that prints two-sided in `mode`, built
/// within the limits, or `None` for one that prints one-sided.
///
/// It first estimates the text at `per_occurrence` bytes, plus the longest
/// atom name, per occurrence, and refuses an estimate past
/// `limits.derivation_bytes` (`Refusal::Output`) before anything is laid
/// out.
#[cfg(any(feature = "latex", feature = "typst", feature = "svg"))]
pub(crate) fn printed(
    sequent: &crate::linear::Sequent,
    mode: crate::linear::Mode,
    per_occurrence: u64,
    limits: &crate::Limits,
) -> Result<Option<crate::linear::Forest>, crate::Error> {
    let name = sequent
        .atom_names()
        .iter()
        .map(String::len)
        .max()
        .unwrap_or(0);
    let estimate = sequent
        .occurrences()
        .saturating_mul(per_occurrence.saturating_add(name as u64));
    if let Some(limit) = limits.derivation_bytes
        && estimate > limit
    {
        return Err(crate::Error::Refused(crate::limits::Refusal::Output {
            what: "sequent",
            estimate_bytes: estimate,
            limit_bytes: limit,
            least_bytes: None,
        }));
    }
    if !mode.is_intuitionistic() {
        return Ok(None);
    }
    crate::linear::Forest::within(sequent, limits).map(Some)
}

/// Returns a sequent in math mode, between `$`s, in `notation`: one-sided,
/// or in intuitionistic mode two-sided by its reading. It refuses as
/// [`printed`] does.
#[cfg(any(feature = "latex", feature = "typst"))]
pub(crate) fn math(
    sequent: &crate::linear::Sequent,
    mode: crate::linear::Mode,
    per_occurrence: u64,
    limits: &crate::Limits,
    notation: &crate::linear::sequents::notation::Notation,
) -> Result<String, crate::Error> {
    let mut out = String::from("$");
    match printed(sequent, mode, per_occurrence, limits)? {
        None => notation.one_sided(&mut out, sequent),
        Some(forest) => {
            let reading = crate::linear::occurrences::Reading::of_mode(&forest, mode)
                .map_err(crate::Error::NotIntuitionistic)?;
            let roots = forest.root_members();
            notation.sequent(
                &mut out,
                &forest,
                Some(&reading),
                None,
                &roots,
                false,
                false,
            )
        }
    }
    .map_err(|_| crate::Error::WriteFailed)?;
    out.push('$');
    Ok(out)
}

/// Returns the typing judgement of a derivation's lambda-term in a
/// target's spelling, or `None` where `term` asks for none. The term is
/// read back and written within the default limits, asking `stop`.
#[cfg(any(feature = "latex", feature = "typst", feature = "svg"))]
pub(crate) fn judgement(
    drawable: Drawable<'_>,
    term: Option<&crate::lambda::Options>,
    spelling: &crate::lambda::print::Spelling,
    mut stop: impl FnMut(crate::Progress) -> bool,
) -> Result<Option<String>, crate::Error> {
    let Some(options) = term else {
        return Ok(None);
    };
    let limits = crate::Limits::default();
    let term = match drawable {
        Drawable::Linear(derivation) => derivation.term(&limits, &mut stop)?,
        Drawable::Ordinary(derivation) => derivation.term(&limits, &mut stop)?,
        Drawable::Classical(_) => {
            return Err(crate::Error::NoTerm {
                reason: crate::lambda::NoTerm::Classical,
            });
        }
        #[cfg(feature = "serialize")]
        Drawable::Rules(_) | Drawable::Fitch(_) => {
            return Err(crate::Error::NoTerm {
                reason: crate::lambda::NoTerm::Calculus,
            });
        }
    };
    let mut out = String::new();
    term.write_in(spelling, options.types, true, &mut out, &limits, stop)?;
    Ok(Some(out))
}

/// A derivation that every format writes.
///
/// You rarely name it: each format's `write` and `to_string` take
/// `&derivation` and convert it with `From`. It is one of:
/// - a derivation of linear logic, one- or two-sided;
/// - the two-sided view of a classical derivation;
/// - a derivation of LK or LJ, read back from a proof of an ordinary
///   sequent's image;
/// - a derivation in a calculus given as data, as a tree
///   ([`rules::Drawing`](crate::rules::Drawing)) or as a Fitch proof
///   ([`rules::Fitch`](crate::rules::Fitch)).
#[non_exhaustive]
#[derive(Clone, Copy, Debug)]
pub enum Drawable<'a> {
    /// A derivation of linear logic.
    Linear(&'a crate::linear::Derivation<'a>),
    /// A derivation of LK or LJ.
    Ordinary(&'a crate::ordinary::Derivation),
    /// The two-sided view of a classical derivation, as its sequent was
    /// written.
    Classical(&'a crate::linear::TwoSided<'a>),
    /// A derivation in a calculus given as data.
    ///
    /// Needs the cargo feature `serialize`.
    #[cfg(feature = "serialize")]
    Rules(&'a crate::rules::Drawing<'a>),
    /// A derivation in a calculus given as data, as a Fitch proof.
    ///
    /// Needs the cargo feature `serialize`.
    #[cfg(feature = "serialize")]
    Fitch(&'a crate::rules::Fitch<'a>),
}

#[cfg(feature = "serialize")]
impl<'a, 'p: 'a> From<&'a crate::rules::Fitch<'p>> for Drawable<'a> {
    /// Writes a derivation in a calculus given as data as a Fitch proof.
    fn from(proof: &'a crate::rules::Fitch<'p>) -> Self {
        Self::Fitch(proof)
    }
}

#[cfg(feature = "serialize")]
impl<'a, 'p: 'a> From<&'a crate::rules::Drawing<'p>> for Drawable<'a> {
    /// Draws a derivation in a calculus given as data.
    fn from(drawing: &'a crate::rules::Drawing<'p>) -> Self {
        Self::Rules(drawing)
    }
}

impl<'a, 'p: 'a> From<&'a crate::linear::Derivation<'p>> for Drawable<'a> {
    /// Draws a derivation of linear logic.
    fn from(derivation: &'a crate::linear::Derivation<'p>) -> Self {
        Self::Linear(derivation)
    }
}

impl<'a, 'p: 'a> From<&'a crate::linear::TwoSided<'p>> for Drawable<'a> {
    /// Draws the two-sided view of a classical derivation.
    fn from(view: &'a crate::linear::TwoSided<'p>) -> Self {
        Self::Classical(view)
    }
}

impl<'a> From<&'a crate::ordinary::Derivation> for Drawable<'a> {
    /// Draws a derivation of LK or LJ.
    fn from(derivation: &'a crate::ordinary::Derivation) -> Self {
        Self::Ordinary(derivation)
    }
}

/// Whether an export is a fragment to paste into your document, or a
/// document of its own.
///
/// Needs one of the cargo features `latex`, `typst` or `rocq`.
#[non_exhaustive]
#[cfg(any(feature = "latex", feature = "typst", feature = "rocq"))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(rename_all = "lowercase"))]
pub enum Form {
    /// The sequent or the proof tree alone, for a document that loads the
    /// packages it needs.
    #[default]
    Fragment,
    /// A complete document that compiles on its own, cropped to its
    /// content; for Rocq, a whole file with its imports.
    Standalone,
}

/// Returns the `<title>` and the `<desc>` of an SVG document of [`svg`],
/// where it has them: its accessible name and the text that reads it.
#[cfg(any(feature = "png", feature = "pdf"))]
fn texts(svg: &str) -> (Option<String>, Option<String>) {
    let Ok(document) = resvg::usvg::roxmltree::Document::parse(svg) else {
        return (None, None);
    };
    let text = |name: &str| {
        let element = document
            .root_element()
            .children()
            .find(|node| node.has_tag_name(name))?;
        Some(element.text().unwrap_or_default().to_owned())
    };
    (text("title"), text("desc"))
}

/// Parses an SVG document with the fonts given and no others, so that the
/// font a text is set in depends on the arguments alone.
#[cfg(any(feature = "png", feature = "pdf"))]
fn parse(svg: &str, fonts: &[&[u8]]) -> Result<resvg::usvg::Tree, crate::Error> {
    let mut options = resvg::usvg::Options::default();
    let database = options.fontdb_mut();
    for font in fonts {
        database.load_font_data(font.to_vec());
    }
    resvg::usvg::Tree::from_str(svg, &options).map_err(|e| crate::Error::NotSvg {
        message: e.to_string(),
    })
}

/// What a render costs, in bytes, per unit of a [`Measure`].
///
/// Each cost is the larger of the memory and the time measured per unit,
/// time counted at [`BYTES_PER_MICROSECOND`], plus a quarter. So a bound
/// on the estimate bounds both memory and time.
///
/// Measured with usvg 0.47 and krilla 0.8, in a release build on one slow
/// core of an x86-64 desktop (peak resident memory and wall time), on:
/// - derivations of `a0 ⊗ … ⊗ aN ⊢ a0 ⊗ … ⊗ aN`, N from 50 to 200, with
///   atom names of 2 to 4 and of 20 characters: 0.9 to 13 MB of SVG, up
///   to 1.2 GB and 5 s as a PDF;
/// - a sequent of 40 000 literals on one line, 160 million units wide;
/// - nets of `a0 ⅋ … ⅋ aN, aN⊥ ⅋ … ⅋ a0⊥` and of crossing links under
///   Mix: 500 to 6 000 links, up to 5.7 MB of SVG and 15 s.
#[cfg(any(feature = "png", feature = "pdf"))]
#[derive(Clone, Copy, Debug)]
struct Costs {
    /// What every render takes, whatever it draws: the fonts and the
    /// renderer's own tables.
    base: u64,
    /// Per byte of the SVG text, which is read and parsed whole.
    byte: u64,
    /// Per element. Measured: 3 750 bytes in usvg's tree, 3 490 in the
    /// PDF.
    element: u64,
    /// Per glyph. usvg sets each glyph as a path. Measured: 795 bytes and
    /// 4.7 µs in usvg; in the PDF, 1 035 bytes and 6.2 µs with text
    /// embedded, 1 600 bytes and 12 µs with text as outlines.
    glyph: u64,
    /// Per pixel of the image. Measured: 6.0 to 6.5 bytes, and 33 to 76 ns
    /// to draw and encode it.
    pixel: u64,
    /// How often the arcs are stroked: once in the parse, to bound them,
    /// and once more where an image is drawn.
    arc_passes: u64,
}

/// The rate at which the renderers fill memory, 128 MiB a second
/// (measured: usvg and krilla filled 167 MB a second on glyphs). A cost
/// that takes time but little memory, such as an arc or a pixel, is
/// charged the bytes they would fill in that time.
#[cfg(any(feature = "png", feature = "pdf"))]
const BYTES_PER_MICROSECOND: u64 = 134;

/// The costs of a PNG: usvg's parse, then the image.
#[cfg(feature = "png")]
const PNG: Costs = Costs {
    base: 32 << 20,
    byte: 2,
    element: 4700,
    glyph: 1000,
    pixel: 14,
    arc_passes: 2,
};

/// The costs of a PDF with its text embedded as text: usvg's parse, then
/// krilla.
#[cfg(feature = "pdf")]
const PDF: Costs = Costs {
    base: 32 << 20,
    byte: 2,
    element: 4400,
    glyph: 1300,
    pixel: 0,
    arc_passes: 1,
};

/// The costs of a PDF with its text as outlines.
#[cfg(feature = "pdf")]
const PDF_OUTLINES: Costs = Costs { glyph: 2000, ..PDF };

/// The least time usvg takes to stroke an arc while bounding it in the
/// parse, in microseconds.
#[cfg(any(feature = "png", feature = "pdf"))]
const ARC_LEAST: u64 = 200;

/// The microseconds an arc takes beyond [`ARC_LEAST`] for each million
/// units its start point lies from the origin ([`arc_micros`]).
#[cfg(any(feature = "png", feature = "pdf"))]
const ARC_PER_MILLION: u64 = 2000;

/// The microseconds a wide arc takes beyond the others, wherever it
/// starts. Measured: 1.4 ms for a half-width of 10 million at the origin.
#[cfg(any(feature = "png", feature = "pdf"))]
const ARC_WIDE: u64 = 1500;

/// The half-width from which an arc is wide.
#[cfg(any(feature = "png", feature = "pdf"))]
const WIDE: f64 = 5e5;

/// The most microseconds an arc may take: the most measured, 35 ms, plus
/// a seventh.
#[cfg(any(feature = "png", feature = "pdf"))]
const ARC_MOST: u64 = 40_000;

/// Returns the microseconds usvg may take to stroke an arc that starts
/// `start` units from the origin and whose larger radius is `radius`.
///
/// usvg computes in single precision, so it strokes an arc that starts
/// millions of units out in many pieces. Measured on arcs of half-width
/// 100 000: 11 ms each starting at 8 million units, 24 ms at 30 million,
/// 29 to 35 ms at 50 to 200 million, almost nothing at a billion; a wide
/// arc near the origin took 1.4 ms. The estimate is a line from
/// `ARC_LEAST` rising `ARC_PER_MILLION` per million units, plus
/// `ARC_WIDE` for a wide arc, capped at `ARC_MOST`. It lies above every
/// point measured on a grid of starts from 0 to 10 billion units and
/// half-widths from 1 000 to 30 million, 50 arcs each.
#[cfg(any(feature = "png", feature = "pdf"))]
fn arc_micros(start: f64, radius: f64) -> u64 {
    if !start.is_finite() || !radius.is_finite() {
        return ARC_MOST;
    }
    let out = (start.abs() / 1e6 * ARC_PER_MILLION as f64) as u64;
    let wide = if radius.abs() >= WIDE { ARC_WIDE } else { 0 };
    ARC_LEAST
        .saturating_add(out)
        .saturating_add(wide)
        .min(ARC_MOST)
}

/// The elements a drawing of [`svg`] has, and the only ones a render
/// reads. The measure knows what these cost. An element that refers to
/// another (`<use>`) or brings a cost of its own (a filter, a pattern, an
/// image) could make a short text cost far more than the measure sees.
#[cfg(any(feature = "png", feature = "pdf"))]
const ELEMENTS: [&str; 8] = [
    "svg", "title", "desc", "g", "text", "path", "rect", "circle",
];

/// What decides the cost of rendering a drawing, read off its SVG text
/// without parsing it. It has to be read before the parse: usvg sets
/// every glyph as a path and strokes every arc inside one call, so
/// nothing can be compared with a bound once it runs.
#[cfg(any(feature = "png", feature = "pdf"))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct Measure {
    /// The bytes of the text.
    bytes: u64,
    /// The elements.
    elements: u64,
    /// The glyphs of the drawing: the characters of its text content
    /// outside `<title>` and `<desc>`, white space left out.
    glyphs: u64,
    /// The microseconds stroking the arcs of every path may take
    /// ([`arc_micros`]).
    arcs: u64,
}

#[cfg(any(feature = "png", feature = "pdf"))]
impl Measure {
    /// Returns the measure of an SVG document. Every count saturates, so
    /// that no text, however large, wraps to a small estimate.
    ///
    /// # Errors
    ///
    /// [`Error::NotSvg`](crate::Error::NotSvg) for a document with an
    /// element that no drawing of [`svg`] has ([`ELEMENTS`]), a reference
    /// (`href`) or a document type. The measure cannot see what those
    /// cost: six levels of `<use>` in 1 287 bytes were measured to take
    /// 227 MB and 4.3 s under a bound of 64 MiB.
    fn of(svg: &str) -> Result<Self, crate::Error> {
        let refused = |what: String| {
            Err(crate::Error::NotSvg {
                message: format!("{what}, which no drawing of deduxit has"),
            })
        };
        let count = |text: &str| text.chars().filter(|c| !c.is_whitespace()).count() as u64;
        let mut measure = Self {
            bytes: svg.len() as u64,
            ..Self::default()
        };
        let mut rest = svg;
        while let Some(start) = rest.find('<') {
            measure.glyphs = measure.glyphs.saturating_add(count(&rest[..start]));
            rest = &rest[start..];
            // Where the markup ends: a comment at `-->`; a `<title>` or
            // `<desc>` at its end tag, since its text is no glyph, unless
            // its start tag closes it (`<title/>`); any other tag at its
            // first `>` outside a quoted value.
            let start_tag = &rest[..tag_end(rest)];
            let empty = start_tag.ends_with("/>");
            let text = ["title", "desc"]
                .into_iter()
                .find(|name| rest[1..].starts_with(name) && !empty);
            let plain = !rest.starts_with("<!--") && text.is_none();
            let close = if rest.starts_with("<!--") {
                rest.find("-->").map_or(rest.len(), |i| i + "-->".len())
            } else if let Some(name) = text {
                start_tag.len() + through_end_tag(&rest[start_tag.len()..], name)
            } else {
                start_tag.len()
            };
            let tag = &rest[..close];
            if tag.starts_with("<!") && !tag.starts_with("<!--") {
                return refused("a document type".to_owned());
            }
            if tag.as_bytes().get(1).is_some_and(u8::is_ascii_alphabetic) {
                let name = tag[1..]
                    .split(|c: char| c.is_whitespace() || c == '>' || c == '/')
                    .next()
                    .unwrap_or_default();
                if !ELEMENTS.contains(&name) {
                    return refused(format!("the element <{name}>"));
                }
                if plain && tag.contains("href") {
                    return refused("a reference".to_owned());
                }
                measure.elements = measure.elements.saturating_add(1);
                if plain {
                    measure.arcs = measure.arcs.saturating_add(arcs(tag));
                }
            }
            rest = &rest[close..];
        }
        measure.glyphs = measure.glyphs.saturating_add(count(rest));
        Ok(measure)
    }

    /// Returns the bytes a render of the drawing is estimated to take at
    /// `costs`, with an image of `pixels`. It saturates, so that a huge
    /// drawing is refused, never estimated small.
    fn estimate(&self, costs: &Costs, pixels: u64) -> u64 {
        [
            (self.bytes, costs.byte),
            (self.elements, costs.element),
            (self.glyphs, costs.glyph),
            (pixels, costs.pixel),
            (
                self.arcs,
                BYTES_PER_MICROSECOND.saturating_mul(costs.arc_passes),
            ),
        ]
        .into_iter()
        .fold(costs.base, |sum, (n, cost)| {
            sum.saturating_add(n.saturating_mul(cost))
        })
    }
}

/// Returns the length of the markup that starts `text`, up to and with its
/// first `>` outside a quoted attribute value. Counting a `>` inside a
/// value would end the tag early: `<desc class=">"/>` would hide what
/// follows it from the measure.
#[cfg(any(feature = "png", feature = "pdf"))]
fn tag_end(text: &str) -> usize {
    let mut quote = None;
    for (i, c) in text.char_indices() {
        match (quote, c) {
            (None, '>') => return i + 1,
            (None, '"' | '\'') => quote = Some(c),
            (Some(open), c) if c == open => quote = None,
            _ => {}
        }
    }
    text.len()
}

/// Returns the length of `text` up to and with the end tag `</name>`, or
/// the whole length where it has none. The end tag may hold white space
/// before its `>`; missing that, `</desc >` would hide what follows it
/// from the measure.
#[cfg(any(feature = "png", feature = "pdf"))]
fn through_end_tag(text: &str, name: &str) -> usize {
    let open = format!("</{name}");
    let mut from = 0;
    while let Some(i) = text[from..].find(&open) {
        let after = from + i + open.len();
        let rest = text[after..].trim_start();
        if rest.starts_with('>') {
            return text.len() - rest.len() + 1;
        }
        from = after;
    }
    text.len()
}

/// Returns the microseconds that stroking the arcs of a start tag's path
/// data (its `d` attribute) may take: [`arc_micros`] of each arc's start
/// point and radii, summed with saturation. The start point is followed
/// through absolute moves and lines. An arc after any other command, or
/// in data that does not read, counts [`ARC_MOST`].
#[cfg(any(feature = "png", feature = "pdf"))]
fn arcs(tag: &str) -> u64 {
    let Some((start, quote)) = [" d=\"", " d='"]
        .into_iter()
        .find_map(|key| tag.find(key).map(|i| (i + key.len(), &key[3..])))
    else {
        return 0;
    };
    let data = &tag[start..];
    let data = &data[..data.find(quote).unwrap_or(data.len())];
    let mut point = Some((0.0f64, 0.0f64));
    let mut micros = 0u64;
    let mut rest = data;
    while let Some(letter) = rest.chars().next() {
        let end = rest[letter.len_utf8()..]
            .find(|c: char| c.is_ascii_alphabetic())
            .map_or(rest.len(), |i| i + letter.len_utf8());
        let numbers: Option<Vec<f64>> = rest[letter.len_utf8()..end]
            .split([' ', ','])
            .filter(|n| !n.is_empty())
            .map(|n| n.parse().ok())
            .collect();
        let numbers = numbers.unwrap_or_default();
        point = match (letter, numbers.as_slice(), point) {
            ('M' | 'L', [.., x, y], _) => Some((*x, *y)),
            ('H', [.., x], Some((_, y))) => Some((*x, y)),
            ('V', [.., y], Some((x, _))) => Some((x, *y)),
            ('A', arcs, mut at) if !arcs.is_empty() && arcs.len() % 7 == 0 => {
                for arc in arcs.chunks(7) {
                    micros = micros.saturating_add(match at {
                        Some((x, y)) => {
                            arc_micros(x.abs().max(y.abs()), arc[0].abs().max(arc[1].abs()))
                        }
                        None => ARC_MOST,
                    });
                    at = Some((arc[5], arc[6]));
                }
                at
            }
            ('A' | 'a', ..) => {
                micros = micros.saturating_add(ARC_MOST);
                None
            }
            _ => None,
        };
        rest = &rest[end..];
    }
    micros
}

/// Returns the width and height in pixels that an SVG document's root
/// declares, read off its start tag without parsing the document. It reads
/// plain numbers and numbers in `px`, as every drawing of [`svg`] has
/// them, and answers `None` for anything else.
#[cfg(feature = "png")]
fn declared_size(svg: &str) -> Option<(f64, f64)> {
    let root = &svg[svg.find("<svg")?..];
    let root = &root[..root.find('>')?];
    let attribute = |name: &str| -> Option<f64> {
        let value = &root[root.find(&format!(" {name}=\""))? + name.len() + 3..];
        let value = &value[..value.find('"')?];
        let number: f64 = value.strip_suffix("px").unwrap_or(value).parse().ok()?;
        (number.is_finite() && number > 0.0).then_some(number)
    };
    Some((attribute("width")?, attribute("height")?))
}