Skip to main content

latexml_core/
gullet.rs

1use std::{
2  cell::{RefCell, RefMut},
3  collections::{VecDeque, hash_map::Entry},
4  sync::LazyLock,
5};
6
7use rustc_hash::{FxHashMap, FxHashSet as HashSet};
8
9// use std::mem;
10// use std::rc::Rc;
11use crate::alignment::Alignment;
12use crate::{
13  DigestedData,
14  common::{
15    arena::{self, SymStr},
16    dimension::Dimension,
17    error::*,
18    float::Float,
19    glue::{FillCode, Glue},
20    locator::Locator,
21    mudimension::MuDimension,
22    muglue::MuGlue,
23    number::Number,
24    numeric_ops::{MAX_DIMEN, MAX_INTEGER, NumericOps, UNITY, fixpoint, fixpoint_unit_checked},
25    object::Object,
26    store::Stored,
27  },
28  definition::{
29    Definition,
30    conditional::ConditionalType,
31    register::{Register, RegisterType, RegisterValue},
32  },
33  mouth::Mouth,
34  state::*,
35  token::{Catcode, TOKEN_ENDCSNAME, TOKEN_RELAX, Token},
36  tokens::Tokens,
37};
38
39/// The digit classes of tex.web §444-445 (Perl `readDigits`' `[0-9]`,
40/// `[0-7]`, `[0-9A-F]` ranges). Plain predicates, not regexes: every digit of
41/// every number scan passes through `read_digits`, and a regex match there
42/// was ~11% of a pgfmath-heavy run (pgf-interference-en, 2026-09-23 profile).
43fn is_decimal_digit(c: char) -> bool { c.is_ascii_digit() }
44fn is_octal_digit(c: char) -> bool { ('0'..='7').contains(&c) }
45fn is_hex_digit(c: char) -> bool { c.is_ascii_digit() || ('A'..='F').contains(&c) }
46
47/// Cached snapshot of `LXML_TRACE_GROUP_END` env var, sampled exactly
48/// once per process. Inlining `std::env::var(...)` on the hot
49/// `read_x_token` path was triggering SIGSEGVs in `__GI_getenv` under
50/// concurrent test-thread execution: glibc's `getenv` walks the
51/// process-global `environ` array unprotected, and the volume of
52/// concurrent calls (millions/sec across N threads) made the unsafe
53/// concurrent walks visible. The fix is to read the env var ONCE at
54/// static-init time; subsequent checks are a free atomic load.
55pub static TRACE_GROUP_END: LazyLock<bool> =
56  LazyLock::new(|| std::env::var("LXML_TRACE_GROUP_END").is_ok());
57
58/// Cached `LATEXML_CSNAME_TRACE` flag + the shared lookahead dump used by
59/// both csname-assembly error sites: reads up to 40 tokens, prints them,
60/// and puts them back (a counted-read/retracting-unread round trip — align
61/// ledger symmetric).
62pub static CSNAME_TRACE: LazyLock<bool> =
63  LazyLock::new(|| std::env::var("LATEXML_CSNAME_TRACE").is_ok());
64
65fn csname_trace_lookahead(tag: &str, cs: &str, bad: &Token) -> Result<()> {
66  let mut ahead = Vec::new();
67  for _ in 0..40 {
68    match read_token()? {
69      Some(t) => ahead.push(t),
70      None => break,
71    }
72  }
73  eprintln!(
74    "CSNAME-TRACE({tag}) partial={cs:?} bad={bad} ahead={}",
75    Tokens::new(ahead.clone())
76  );
77  unread_vec(ahead);
78  Ok(())
79}
80
81// `\noexpand`'d tokens are represented per-token by the `\special_relax` family
82// (`Token::is_noexpand_family` / `token::noexpand_family`): the shadowed token's
83// identity is encoded in the CS name, so it survives storage and dumps without a
84// global smuggle slot. The family resolves to `\relax` meaning via the
85// `state::lookup_meaning` fallback. Faithful to TeX's `no_expand_flag`, which
86// preserves the shadowed `cur_cs` while giving it relax meaning for one access.
87use std::cell::Cell;
88
89use crate::pin;
90
91/// True when `token` is a `\noexpand`'d form (`\special_relax` family) shadowing
92/// `target` — used by delimited-parameter / keyword matching so that, faithful to
93/// TeX, a `\noexpand`'d token still matches its underlying identity.
94fn special_relax_matches(token: &Token, target: &Token) -> bool {
95  token.noexpand_shadowed().as_ref() == Some(target)
96}
97fn deferred_commands() -> HashSet<SymStr> {
98  set!(
99    pin!("\\the"),
100    pin!("\\showthe"),
101    pin!("\\unexpanded"),
102    pin!("\\detokenize")
103  )
104}
105thread_static! {
106  static DEFERRED_COMMANDS: HashSet<SymStr> = deferred_commands();
107}
108
109// If it is a column ending token, Returns the token, a keyword and whether it is "hidden"
110fn column_ends() -> [(Token, &'static str, bool); 6] {
111  [
112    // besides T_ALIGN
113    (T_CS!("\\cr"), "cr", false),
114    (T_CS!("\\crcr"), "crcr", false),
115    (T_CS!("\\lx@hidden@cr"), "cr", true),
116    (T_CS!("\\lx@hidden@crcr"), "crcr", true),
117    (T_CS!("\\lx@hidden@align"), "insert", true),
118    (T_CS!("\\span"), "span", false),
119  ]
120}
121thread_static! {
122  static COLUMN_ENDS: [(Token, &'static str, bool); 6] = column_ends();
123}
124
125/// What a balanced read ([`read_balanced`]) does when it exhausts a mouth before
126/// the braces balance.
127///
128/// Perl has no such distinction: `Gullet.pm` L465-472 reads `$$self{mouth}
129/// ->readToken()` — the *current* mouth only — and `last`s at the boundary, so
130/// every Perl mouth is [`Opaque`](BalancedBoundary::Opaque). Rust crosses the
131/// boundary for token-level injections, which is a deliberate surpass-Perl
132/// divergence (xint, see [`read_balanced`]) and must stay narrow: crossing from a
133/// mouth that is *its own input* lets one runaway argument swallow everything
134/// after it.
135#[derive(PartialEq, Eq, Debug, Clone, Copy)]
136pub enum BalancedBoundary {
137  /// The mouth is a token-level continuation of the enclosing stream
138  /// (`\scantokens`, RawTeX): its `}` may legitimately live in the parent, so a
139  /// balanced read drains it and resumes there.
140  Transparent,
141  /// The mouth is a self-contained input. A balanced read stops at its end, as
142  /// Perl always does — an unbalanced argument loses the rest of *this* mouth
143  /// and nothing more. An Opaque mouth that is also a file level (catchfile's
144  /// opener) gets TeX's file-end recovery, like any file
145  /// ([`recover_at_file_end`]).
146  Opaque,
147}
148
149/// What the scanner is reading, for the recovery TeX makes when a file ends in
150/// the middle of it: tex.web §305 `scanner_status` (with `warning_index`, the
151/// command it names). A scan that owns a status sets it for its duration with
152/// [`set_scanner_status`] and restores the enclosing one after, as tex.web
153/// saves and restores it (§389 `macro_call`, §473 `scan_toks`); every nested
154/// read that sets none inherits it. [`recover_at_file_end`] consults it.
155///
156/// tex.web's `skipping` (conditional text) is not modelled: a skip that runs
157/// off an input level stops there, as Perl's does (`read_next_conditional`).
158#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
159pub enum ScannerStatus {
160  /// Not inside any of the scans below: a file's end is not a runaway.
161  #[default]
162  Normal,
163  /// `defining`: a definition body, `\def`/`\edef` (§473 `scan_toks(true, _)`).
164  Defining,
165  /// `matching`: a macro's arguments (§389-391 `macro_call`).
166  Matching,
167  /// `aligning`: an alignment preamble (§777 `init_align`).
168  Aligning,
169  /// `absorbing`: a balanced text, `\message`, `\write`, `\toks=`,
170  /// `\detokenize` … (§473 `scan_toks(false, _)`, eTeX `scan_general_text`).
171  Absorbing,
172}
173
174impl ScannerStatus {
175  /// The word tex.web §339 prints after "while scanning".
176  fn scanning_what(self) -> &'static str {
177    match self {
178      ScannerStatus::Normal => "input",
179      ScannerStatus::Defining => "definition",
180      ScannerStatus::Matching => "use",
181      ScannerStatus::Aligning => "preamble",
182      ScannerStatus::Absorbing => "text",
183    }
184  }
185}
186
187/// Why a macro call's arguments are abandoned ([`argument_runaway`]).
188#[derive(Clone, Debug, PartialEq)]
189pub enum Runaway {
190  /// An argument ran off the end of a file (tex.web §338-339; §392 with `long_state=outer_call`): the tokens it had
191  /// read, for [`abandon_runaway_call`].
192  FileEnd(Vec<Token>),
193  /// A non-`\long` macro met `\par` in its argument (§392, §399 with `long_state=call`): the `\par` as read.
194  Paragraph(Token),
195  /// A macro re-requested at the true end of all input an argument it missed there ([`note_missing_argument`]): the
196  /// put-back stays in the input; `first` the first such call of that macro and argument, the one reported.
197  TrueEnd { first: bool },
198}
199
200/// Restores the enclosing [`ScannerStatus`] (and `warning_index`) when it
201/// drops, on every exit path of the scan that set it, `?` included.
202/// The runaway argument ([`argument_runaway`]) is scoped the same way: a scan
203/// starts without one, and the enclosing scan's comes back when it ends.
204#[must_use = "the scanner status is restored when this guard drops"]
205pub struct ScannerStatusGuard {
206  status:            ScannerStatus,
207  warning_index:     Option<Token>,
208  runaway_argument:  Option<Runaway>,
209  par_ends_argument: bool,
210  ended:             bool,
211}
212
213impl ScannerStatusGuard {
214  /// End the scan now and hand back the macro argument that ran off a file
215  /// inside it, if one did ([`argument_runaway`]): the tokens it had read,
216  /// for [`abandon_runaway_call`]. A `macro_call` abandons itself then
217  /// (tex.web §392; `Expandable::read_call_arguments`).
218  pub fn end_taking_runaway_argument(mut self) -> Option<Runaway> {
219    let mut gullet = gullet_root().borrow_mut();
220    gullet.scanner_status = self.status;
221    gullet.warning_index = self.warning_index.take();
222    PAR_ENDS_ARGUMENT.with(|c| c.set(self.par_ends_argument));
223    self.ended = true;
224    std::mem::replace(&mut gullet.runaway_argument, self.runaway_argument.take())
225  }
226}
227
228impl Drop for ScannerStatusGuard {
229  fn drop(&mut self) {
230    if self.ended {
231      return;
232    }
233    // `try_`: a guard dropped while unwinding from a panic that holds the
234    // gullet must not panic again; `initialize_gullet` resets the status.
235    if let Ok(mut gullet) = gullet_root().try_borrow_mut() {
236      gullet.scanner_status = self.status;
237      gullet.warning_index = self.warning_index.take();
238      gullet.runaway_argument = self.runaway_argument.take();
239    }
240    PAR_ENDS_ARGUMENT.with(|c| c.set(self.par_ends_argument));
241  }
242}
243
244/// What [`recover_at_file_end`] did.
245#[derive(Clone, Copy, Debug, PartialEq, Eq)]
246pub enum FileEndRecovery {
247  /// Not a runaway: the scan is at [`ScannerStatus::Normal`], or the input
248  /// level that ended is not a file with an enclosing input. The caller keeps
249  /// its own end-of-input behaviour.
250  NotARunaway,
251  /// The file is closed and TeX's recovery tokens are the next input: a `}`
252  /// for a definition or a text, `\cr}` for a preamble. Read on.
253  Inserted,
254  /// A macro argument ran off: the call is abandoned, so the reader stops and
255  /// returns what it has, which the call discards.
256  Abandoned,
257}
258
259#[derive(PartialEq, Debug)]
260pub struct MouthRuntime {
261  pub autoclose:       bool,
262  pub mouth:           Mouth,
263  /// eTeX `\everyeof`: when this mouth (an `\input` file or a `\scantokens`
264  /// pseudo-file) is exhausted, the CURRENT `\everyeof` register tokens are inserted as
265  /// TOKENS (not retokenized text — l3tl's rescan quarks and xint's
266  /// captures depend on their token identity). Read at CLOSE time, per
267  /// eTeX's file-end evaluation.
268  pub insert_everyeof: bool,
269  /// eTeX's `eof_seen[index]` (tex.web §362 as changed by etex.ch): the
270  /// `\everyeof` payload is inserted ONCE, at this mouth's own level, the
271  /// first time it runs dry — the mouth stays current until the payload is
272  /// read, so a delimited scan inside the pseudo-file sees the payload as
273  /// the file's last tokens and never crosses into the parent stream.
274  /// `\endinput` sets it too (eTeX's `force_eof` ends the file without the
275  /// payload, §362).
276  pub eof_seen:        bool,
277  /// The file's end runs `\InputIfFileExists`' code after `\@@input` ([`mark_file_hooks_mouth`]).
278  pub file_hooks:      Option<FileHooksEnd>,
279  /// See [`BalancedBoundary`]. Only consulted when `autoclose` is set and the
280  /// mouth is not a file.
281  pub boundary:        BalancedBoundary,
282  /// Pushback LIFO stack: the "next to read" token is at `pushback.last()`.
283  /// Invariant: reading pops from the back; `unread_one` pushes to the back;
284  /// `unread_vec` iterates its input in reverse and pushes each — so the
285  /// first element of an unread Vec ends up on top (= next to read).
286  /// See `flush_mouth` for the rare FIFO-prepend semantics (\endinput).
287  ///
288  /// Previously a `VecDeque<Token>` — switched to a plain Vec because the
289  /// hot-path is pure LIFO and VecDeque's push_front/pop_front machinery
290  /// (head-pointer + wrap arithmetic) showed up at ~3.3% of total Ir in
291  /// callgrind on siunitx-heavy fixtures.
292  pub pushback:        Vec<Token>,
293  /// How short the pushback has been since each input mark taken on this mouth ([`input_mark`]): every shortening of
294  /// it tells the watch ([`PushbackWatch::note_len`]).
295  watch:               PushbackWatch,
296}
297
298/// A content file read with latex.ltx's file hooks (`content::input_content_with_file_hooks`): its request, and
299/// whether its load pushed ltfilehook's file-name stack, which its end pops (`content::input_file_ended`).
300#[derive(PartialEq, Debug, Clone)]
301pub struct FileHooksEnd {
302  pub request: String,
303  pub pop:     bool,
304}
305
306/// The input marks' watch on one mouth's pushback ([`input_mark`], [`input_unread_since`]): for each mark taken on the
307/// mouth, the shortest the pushback has been since — no token below a mark's length was read while that is no less
308/// than the length. Kept as runs: the marks from a run's serial up to the next run's share its shortest length, the
309/// serials increasing and the lengths never decreasing towards the top, so a mark costs at most one run and a
310/// shortening of the pushback one comparison, with the top run's length ([`floor`](Self::floor)); no token is copied.
311/// A run whose every mark is read — the pushback more than [`MARK_HELD`] shorter than its shortest mark — is dropped:
312/// its marks answer from the run below, no longer, or from none (read), and the reads below it are fast again.
313#[derive(PartialEq, Debug, Default)]
314struct PushbackWatch {
315  runs:  Vec<WatchRun>,
316  /// the top run's length, 0 when there is none: only a pushback shorter than it changes a run, so the fast read
317  /// (`read_internal_token_checked`) pops only above it and every other shortening tells [`note_len`](Self::note_len)
318  floor: usize,
319}
320
321/// A run of input marks on a [`PushbackWatch`].
322#[derive(PartialEq, Debug, Clone, Copy)]
323struct WatchRun {
324  /// the serial of its first mark
325  serial: u64,
326  /// the shortest the pushback has been since that mark
327  low:    usize,
328  /// the shortest of its marks' lengths: the run is live while the pushback has been at most [`MARK_HELD`] shorter
329  least:  usize,
330}
331
332impl WatchRun {
333  fn live(&self) -> bool { self.low + MARK_HELD >= self.least }
334}
335
336impl PushbackWatch {
337  /// The pushback is `len` tokens long now, shorter than it was.
338  #[inline(always)]
339  fn note_len(&mut self, len: usize) {
340    if len < self.floor {
341      self.lower(len);
342    }
343  }
344
345  /// [`note_len`](Self::note_len) below the floor: the runs longer than `len` become one at `len` (joined to the run
346  /// below when that is at `len` already), dropped when every mark of it is read.
347  #[cold]
348  #[inline(never)]
349  fn lower(&mut self, len: usize) {
350    let keep = self.runs.partition_point(|run| run.low <= len);
351    let mut lowered = self.runs.drain(keep..).reduce(|first, run| WatchRun {
352      least: first.least.min(run.least),
353      ..first
354    });
355    if let Some(run) = lowered.as_mut() {
356      run.low = len;
357    }
358    if let Some(run) = lowered.filter(WatchRun::live) {
359      match self.runs.last_mut() {
360        Some(below) if below.low == len => below.least = below.least.min(run.least),
361        _ => self.runs.push(run),
362      }
363    }
364    self.floor = self.runs.last().map_or(0, |run| run.low);
365  }
366
367  /// A mark `serial` taken with the pushback `len` tokens long: it joins the top run when that run is at `len` (the
368  /// top run is never longer than the pushback).
369  fn mark(&mut self, serial: u64, len: usize) {
370    match self.runs.last_mut() {
371      Some(top) if top.low == len => top.least = len,
372      _ => self.runs.push(WatchRun { serial, low: len, least: len }),
373    }
374    self.floor = len;
375  }
376
377  /// No longer than the shortest the pushback has been since the mark `serial` — that, while the mark's run is live —,
378  /// if a run of this mouth's holds a mark at or before it.
379  fn shortest_since(&self, serial: u64) -> Option<usize> {
380    let after = self.runs.partition_point(|run| run.serial <= serial);
381    after.checked_sub(1).map(|run| self.runs[run].low)
382  }
383}
384
385#[derive(Debug, Default)]
386pub struct Gullet {
387  pub runtime:              Option<MouthRuntime>,
388  pub mouthstack:           VecDeque<MouthRuntime>,
389  pub pending_comments:     VecDeque<Token>,
390  pub token_limit:          Option<usize>,
391  /// The front end's `--token-limit` set [`token_limit`](Self::token_limit): the source size no longer raises it
392  /// ([`fix_token_limit`]).
393  pub token_limit_fixed:    bool,
394  /// Bytes of every source file opened so far this conversion — the basis
395  /// of [`scale_token_limit_to_source`].
396  pub source_bytes_total:   usize,
397  pub pushback_limit:       Option<usize>,
398  pub progress:             usize,
399  /// The value of [`progress`](Self::progress) at which [`read_internal_token_checked`] next has more to do than
400  /// take a token off the pushback: the token limit, the deadline's period, the cycle guard's window. 0 asks for it
401  /// to be worked out on the next read ([`Gullet::next_full_read`]), and a write to any of those fields sets it so.
402  full_read_at:             usize,
403  /// The value of [`progress`](Self::progress) past which a read fails, a budgeted run's ([`read_budget`]).
404  read_budget_at:           Option<usize>,
405  /// A read failed for [`read_budget_at`](Self::read_budget_at).
406  read_budget_spent:        bool,
407  /// Token-progress floor above which [`cycle_guard`](Self::cycle_guard)
408  /// engages. Defaults to `CYCLE_GUARD_ACTIVATE` (20M). Graphics packages
409  /// whose healthy expansion legitimately runs to 100M+ tokens (pgf/tikz/xy)
410  /// raise it via [`raise_cycle_guard_activate`] so their streams stay out of
411  /// the per-token fingerprint regime; the 1G `token_limit` remains the hard
412  /// backstop. `#[derive(Default)]` would zero this (guard-always-on), so it is
413  /// set explicitly in the constructor and the per-conversion reset.
414  pub cycle_guard_activate: usize,
415  /// Windowed cycle detector over the expansion (read-token) stream — catches
416  /// small-period infinite expansion loops (`\def\x{a\x}` etc.) far earlier
417  /// and more cheaply than `token_limit`/`pushback_limit`. Gated on a high
418  /// `progress` so normal documents never touch it. See [`crate::cycle_guard`].
419  pub cycle_guard:          crate::cycle_guard::CycleGuard,
420  /// Reading-context serial, mixed into every cycle-guard fingerprint so that
421  /// windows never match ACROSS `reading_from_mouth` contexts: a cycle is only
422  /// a cycle within one expansion context. Each `reading_from_mouth` entry
423  /// allocates a fresh serial (from `ctx_next`) and restores the outer one on
424  /// exit (`ctx_stack`), so (a) consecutive IDENTICAL short expansions — the
425  /// math0402448 xymatrix per-cell `get_xmarg_id` stream — get distinct
426  /// serials and can never concatenate into a pseudo-periodic window (the
427  /// false positive an earlier blanket `reset()` suppressed), while (b) an
428  /// OUTER loop's tokens keep their serial across inner expansions, so a
429  /// runaway whose body calls `do_expand` each iteration (~164 call sites)
430  /// remains detectable — the blind spot the blanket reset had (PR #249
431  /// review P2-7).
432  pub ctx_serial:           u64,
433  ctx_next:                 u64,
434  ctx_stack:                Vec<u64>,
435  /// The last input mark's serial ([`input_mark`]), never reset: a mark is told from those of another mouth.
436  mark_serial:              u64,
437  /// tex.web `scanner_status` (see [`ScannerStatus`]).
438  scanner_status:           ScannerStatus,
439  /// tex.web `warning_index`: the command a runaway report names.
440  warning_index:            Option<Token>,
441  /// The tokens of a macro argument that ran off the end of a file, as read
442  /// (see [`argument_runaway`]).
443  runaway_argument:         Option<Runaway>,
444  /// Each required argument missed at the true end of all input, by its caller and spec: the input left at its
445  /// last miss, and whether a call was abandoned for it ([`note_missing_argument`]).
446  true_end_misses:          FxHashMap<(Option<Token>, String), (usize, bool)>,
447}
448
449thread_local! {
450  /// Debug-only (LATEXML_DEBUG_FATAL): ring of the most recent read tokens,
451  /// dumped when the gullet cycle guard trips so the repeating window is
452  /// identifiable from logs (this is how the math0402448 xymatrix
453  /// false-positive was diagnosed).
454  static DEBUG_RECENT_TOKENS: RefCell<VecDeque<String>> =
455    RefCell::new(VecDeque::with_capacity(512));
456  /// Depth of number/dimension/glue scans in progress (`read_number` & co.).
457  /// tex.web §440ff `scan_int`'s digit/unit/keyword lookahead is pure
458  /// expansion: an alignment tab or row end met there is an UNEXPANDABLE
459  /// token that ends the scan and is re-read by the main loop. Our alignment
460  /// actions live in `read_x_token` (`handle_template`), so without this gate
461  /// `\ifnum1<\nb\\…\fi` inside a p/m tabular cell (tabularcalc.sty:428, a
462  /// macro operand forcing the lookahead) broke the row mid-scan, and the
463  /// false-branch skip then desynchronized the cell ("\noalign cannot be used
464  /// here", then every group close of the table; tabularcalc ×3, floatrow-rus,
465  /// fepslatex ≈ 200 errors; Perl clean). Batch 56bi. The same scan ends
466  /// at a macro that peeks by `\futurelet` (`scan_stops_at_futurelet_peek`).
467  static NUMBER_SCAN_DEPTH: Cell<u32> = const { Cell::new(0) };
468  /// tex.web §389 `long_state=call`: the macro whose arguments are being read is not `\long` and its long-ness is
469  /// TeX's ([`crate::definition::expandable::Expandable::checks_par`]), so a `\par` token in them ends the call
470  /// (§392, §399; [`is_par_ending_argument`]). Set for the argument scan by [`set_scanner_status_checking_par`] and
471  /// restored with the enclosing scan's, so a nested scan has its own.
472  static PAR_ENDS_ARGUMENT: Cell<bool> = const { Cell::new(false) };
473}
474
475/// RAII marker for a number/dimension/glue scan (see `NUMBER_SCAN_DEPTH`).
476/// Every `?`-return and every unwind past a reader runs the drop, so the
477/// depth is back to what it was the moment the scan ends. The eTeX expression
478/// evaluator (`etex.rs`) takes one too, for its own inter-operand reads
479/// (etex.ch `scan_expr` treats a tab/row end the same).
480pub struct NumberScan;
481impl NumberScan {
482  pub fn begin() -> Self {
483    NUMBER_SCAN_DEPTH.with(|c| c.set(c.get() + 1));
484    NumberScan
485  }
486
487  /// TeX never digests inside `scan_int`, but a binding can: calc's
488  /// `\widthof` measures its box while `\makebox[…]`'s width is being
489  /// scanned. The digestion is no part of the scan, so its own reads are at
490  /// depth 0 (its alignment tabs act, its peeking macros peek) until the
491  /// returned guard drops and gives the scan its depth back. Taken by the
492  /// stomach's digestion entries (`stomach::digest`, `digest_next_body`).
493  pub fn suspend() -> NumberScanSuspended {
494    NumberScanSuspended(NUMBER_SCAN_DEPTH.with(|c| c.replace(0)))
495  }
496}
497impl Drop for NumberScan {
498  fn drop(&mut self) { NUMBER_SCAN_DEPTH.with(|c| c.set(c.get().saturating_sub(1))); }
499}
500/// The guard [`NumberScan::suspend`] returns: restores the suspended depth.
501pub struct NumberScanSuspended(u32);
502impl Drop for NumberScanSuspended {
503  fn drop(&mut self) { NUMBER_SCAN_DEPTH.with(|c| c.set(self.0)); }
504}
505fn in_number_scan() -> bool { NUMBER_SCAN_DEPTH.with(|c| c.get() > 0) }
506
507thread_static! {
508  /// Control sequences emptied for printing whose value a quantity's operand still reads (tex.web §441: the token after
509  /// the signs), with that value: the title-page deposit's fields (`\lx@deposit@maketitle`), set for its run.
510  static OPERAND_VALUES: RefCell<Vec<(Token, Tokens)>> = RefCell::new(Vec::new());
511}
512thread_local! {
513  /// Whether the scan is reading its operand's first token ([`OperandRead`]).
514  static READING_OPERAND: Cell<bool> = const { Cell::new(false) };
515}
516
517/// RAII marker for the read of a quantity's operand head (`READING_OPERAND`): `scan_optional_signs`'s, and the
518/// eTeX expression's factor (etex.ch `scan_expr`).
519pub struct OperandRead(bool);
520impl OperandRead {
521  pub fn begin() -> Self {
522    OperandRead(READING_OPERAND.replace(!OPERAND_VALUES.borrow().is_empty()))
523  }
524}
525impl Drop for OperandRead {
526  fn drop(&mut self) { READING_OPERAND.set(self.0); }
527}
528
529/// The guards of a read ahead of a quantity's operand that expands as the operand's does: an assignment's optional `=`
530/// (tex.web §405 `scan_optional_equals`), the `by` of `\advance`, `\multiply` and `\divide` (§1236 `scan_keyword`),
531/// whose first non-matching token is the operand's. Only while `OPERAND_VALUES` holds values (the deposit).
532pub fn operand_lookahead() -> Option<(OperandRead, NumberScan)> {
533  if OPERAND_VALUES.borrow().is_empty() {
534    return None;
535  }
536  Some((OperandRead::begin(), NumberScan::begin()))
537}
538
539/// Give the control sequences `OPERAND_VALUES` holds, returning the ones given before.
540pub fn set_operand_values(values: Vec<(Token, Tokens)>) -> Vec<(Token, Tokens)> {
541  OPERAND_VALUES.replace(values)
542}
543
544/// The value an operand reads from `token`, while its meaning `defn` is still the empty macro it was made for printing.
545#[cold]
546fn operand_value(token: &Token, defn: &dyn Definition) -> Option<Tokens> {
547  use crate::definition::ExpansionBody;
548  let emptied = defn
549    .get_parameters()
550    .is_none_or(|p| p.get_parameters().is_empty())
551    && match defn.get_expansion() {
552      None => true,
553      Some(ExpansionBody::Tokens(body)) => body.unlist_ref().is_empty(),
554      Some(ExpansionBody::Closure(_)) => false,
555    };
556  if !emptied || !in_number_scan() {
557    return None;
558  }
559  OPERAND_VALUES
560    .borrow()
561    .iter()
562    .find(|(t, _)| t == token)
563    .map(|(_, v)| v.clone())
564}
565
566/// Hoisted env probe for the LATEXML_DEBUG_FATAL diagnostics (shared seam in
567/// `common::error`; read once so the per-token hot path pays one bool test).
568static DEBUG_FATAL: LazyLock<bool> = LazyLock::new(debug_fatal_enabled);
569
570fn fresh_gullet() -> Gullet {
571  Gullet {
572    token_limit: default_token_limit(),
573    // Explicit: `#[derive(Default)]` would set this to 0 (guard active from the
574    // first token). Graphics packages raise it at load (see
575    // `raise_cycle_guard_activate`).
576    cycle_guard_activate: CYCLE_GUARD_ACTIVATE,
577    ..Gullet::default()
578  }
579}
580thread_root! {
581pub fn gullet_root() -> RefCell<Gullet> = RefCell::new(fresh_gullet());
582}
583
584/// Eagerly initialize this thread's gullet-phase per-thread roots
585/// (`DEFERRED_COMMANDS`, `COLUMN_ENDS`, `GULLET`). Their initializers intern
586/// `SymStr`s / build `Token`s via the arena, so force them AFTER
587/// [`arena::force_init`](crate::common::arena::force_init) /
588/// [`token::force_init`](crate::token::force_init). Forcing them at
589/// conversion entry keeps them from initializing re-entrantly from within
590/// another root's init mid-conversion — the macOS thread-local hazard
591/// behind issue #217. No behavioral change on Linux.
592pub(crate) fn force_init() {
593  let _ = &*DEFERRED_COMMANDS;
594  let _ = &*COLUMN_ENDS;
595  gullet_root();
596}
597
598/// After `arena::reset`, in [`force_init`]'s order: the symbol constants pinned again (`false` if one differs, as
599/// `token::repin_constants`), and a fresh gullet in place of the last conversion's.
600pub(crate) fn repin_constants() -> bool {
601  let same = deferred_commands() == *DEFERRED_COMMANDS
602    && column_ends()
603      .iter()
604      .zip(COLUMN_ENDS.iter())
605      .all(|(new, old)| new.0 == old.0);
606  *gullet_root().borrow_mut() = fresh_gullet();
607  same
608}
609
610/// An empty gullet and no `\csname` buffer, for a thread about to exit (`crate::shrink_thread_engine`).
611pub(crate) fn shrink() {
612  *gullet_root().borrow_mut() = Gullet::default();
613  CS_NAME_BUFFER.with(|buffer| drop(buffer.take()));
614}
615
616macro_rules! gullet {
617  () => {
618    gullet_root().borrow()
619  };
620}
621macro_rules! gullet_mut {
622  () => {
623    gullet_root().borrow_mut()
624  };
625}
626
627/// Enter a scan at `status`, naming `warning_index` (the command TeX's runaway
628/// message names: the macro whose arguments are read, the primitive whose text
629/// is absorbed). tex.web saves and restores the status around such a scan;
630/// the returned guard does the restoring.
631pub fn set_scanner_status(
632  status: ScannerStatus,
633  warning_index: Option<Token>,
634) -> ScannerStatusGuard {
635  set_scanner_status_checking_par(status, warning_index, false)
636}
637
638/// [`set_scanner_status`] for a macro call's arguments, with `checks_par` its macro's
639/// [`crate::definition::expandable::Expandable::checks_par`] (tex.web §389 `long_state`).
640pub fn set_scanner_status_checking_par(
641  status: ScannerStatus,
642  warning_index: Option<Token>,
643  checks_par: bool,
644) -> ScannerStatusGuard {
645  let mut gullet = gullet_mut!();
646  ScannerStatusGuard {
647    status:            std::mem::replace(&mut gullet.scanner_status, status),
648    warning_index:     std::mem::replace(&mut gullet.warning_index, warning_index),
649    runaway_argument:  gullet.runaway_argument.take(),
650    par_ends_argument: PAR_ENDS_ARGUMENT.with(|c| c.replace(checks_par)),
651    ended:             false,
652  }
653}
654
655/// The current [`ScannerStatus`].
656pub fn scanner_status() -> ScannerStatus { gullet!().scanner_status }
657
658/// Whether a macro argument has run off the end of a file and the call is to
659/// be abandoned (see [`FileEndRecovery::Abandoned`]); readers stop at once.
660pub fn argument_runaway() -> bool { gullet!().runaway_argument.is_some() }
661
662/// A reader stopping at a runaway argument puts in front of the runaway
663/// tokens the ones it had read itself, so that [`abandon_runaway_call`] sees
664/// the argument as it was read: a delimited reader's text before a brace group
665/// that ran off, then the group's own.
666pub fn note_runaway_tokens(mut read: Vec<Token>) {
667  if let Some(Runaway::FileEnd(ref mut runaway)) = gullet_mut!().runaway_argument {
668    read.append(runaway);
669    *runaway = read;
670  }
671}
672
673/// Whether `token`, read into a macro argument, ends the call: tex.web §392/§399 `cur_tok=par_token` — the control
674/// sequence named `par`, whatever it means (a `\noexpand`ed one too) — while a non-`\long` macro's arguments are read.
675pub fn is_par_ending_argument(token: &Token) -> bool {
676  PAR_ENDS_ARGUMENT.with(Cell::get) && token.noexpand_shadowed().unwrap_or(*token) == T_CS!("\\par")
677}
678
679/// Abandon the call at the `\par` just read into its argument ([`is_par_ending_argument`]): the readers stop, and
680/// [`abandon_runaway_call`] reports it and puts the `\par` back (tex.web §396).
681pub fn abandon_argument_at_par(par: Token) {
682  gullet_mut!().runaway_argument = Some(Runaway::Paragraph(par));
683}
684
685/// Whether `token`, read into a macro argument, is a `}` that ends the call (tex.web §392 `cur_tok<right_brace_limit`,
686/// §395): a right brace met while a macro's arguments are read, delimited or not.
687#[inline]
688pub fn is_extra_brace_in_argument(token: &Token) -> bool {
689  token.get_catcode() == Catcode::END && scanner_status() == ScannerStatus::Matching
690}
691
692/// A macro's argument scan met a `}` ([`is_extra_brace_in_argument`]): "Argument of \x has an extra }", the `}` put
693/// back, and the `\par` TeX inserts returned as the reader's next token, the rest of the call read as a non-`\long`
694/// macro's (tex.web §395 `long_state:=call`): a `\par` delimiter takes it, any other reader ends the call (§396).
695pub fn insert_par_at_extra_brace(brace: Token) -> Result<Token> {
696  let cs = gullet!().warning_index;
697  let cs = cs.map(|cs| cs.to_string()).unwrap_or_default();
698  unread_one(brace);
699  PAR_ENDS_ARGUMENT.with(|c| c.set(true));
700  Error!("unexpected", "}", s!("Argument of {cs} has an extra }}"));
701  Ok(T_CS!("\\par"))
702}
703
704/// Set the token limit and reset progress. Returns previous (limit, progress) for restoration.
705pub fn set_token_limit(limit: Option<usize>) -> (Option<usize>, usize) {
706  let mut g = gullet_mut!();
707  let prev = (g.token_limit, g.progress);
708  g.token_limit = limit;
709  g.progress = 0;
710  g.full_read_at = 0;
711  prev
712}
713
714/// The front end's explicit token limit (`--token-limit`): kept as given, as `LATEXML_TOKEN_LIMIT` is, where
715/// [`scale_token_limit_to_source`] would raise a limit below the source's scaled one.
716pub fn fix_token_limit(limit: Option<usize>) {
717  set_token_limit(limit);
718  gullet_mut!().token_limit_fixed = true;
719}
720
721/// Set the pushback limit (maximum pushback stack size before fatal error).
722pub fn set_pushback_limit(limit: Option<usize>) { gullet_mut!().pushback_limit = limit; }
723
724/// How many tokens the gullet has read so far: at the end of a run, the
725/// telemetry basis for `token_limit` / `CYCLE_GUARD_ACTIVATE`; during one, the
726/// input a stretch of digestion consumed, for the stomach's box-cycle guard
727/// (`stomach.rs` `cycle_guard_record`).
728pub fn token_progress() -> usize { gullet!().progress }
729
730/// Count `reads` tokens as read, where a run's reading is known without making it (the frontmatter's rehearsal of a
731/// text it rehearsed before): [`progress`](Gullet::progress) stands where the run would leave it, its limits read again.
732pub fn count_reads(reads: usize) {
733  let mut g = gullet_mut!();
734  g.progress = g.progress.saturating_add(reads);
735  g.full_read_at = 0;
736}
737
738/// A run of digestion's limit on the tokens it reads, until [`ReadBudget::end`]: the read past it fails, and so does
739/// each one after, with an [`ErrorCategory::ReadBudget`](crate::common::error::ErrorCategory) error that is logged
740/// nowhere and latches nothing, so whoever made the run ends it and the document goes on. The title-page check's runs
741/// (latexml_engine sect05.rs `speculative_run_read`): a run's cost is bounded whatever the document's text does. The count is
742/// the one [`progress`](Gullet::progress) keeps; the token limit, the deadline and the cycle guard read theirs as before.
743#[must_use]
744pub fn read_budget(reads: usize) -> ReadBudget {
745  let mut g = gullet_mut!();
746  let start = g.progress;
747  g.read_budget_at = Some(start.saturating_add(reads));
748  g.read_budget_spent = false;
749  g.full_read_at = 0;
750  ReadBudget { start, reads }
751}
752
753/// What [`read_budget`] began; the budget is off once this is ended or dropped.
754pub struct ReadBudget {
755  start: usize,
756  reads: usize,
757}
758
759impl ReadBudget {
760  /// The run is over: how many tokens it read, and whether it read all it may. A run the budget ended counts as read
761  /// what it read, as a run that finished does: the failed reads, and an inner [`reading_from_mouth`]'s reset of the
762  /// count on the way out, leave no mark on [`progress`](Gullet::progress). A run that ended otherwise keeps the count
763  /// as it found it. (A failed run's reset is that path's own.)
764  pub fn end(self) -> ReadBudgetEnd {
765    let mut g = gullet_mut!();
766    let at = g.read_budget_at.unwrap_or(usize::MAX);
767    let left = at.saturating_sub(g.progress);
768    let reads = self.reads.saturating_sub(left);
769    let over = g.read_budget_spent;
770    if over {
771      g.progress = self.start.saturating_add(reads);
772    }
773    drop(g);
774    ReadBudgetEnd { reads, over }
775  }
776}
777
778impl Drop for ReadBudget {
779  fn drop(&mut self) {
780    let mut g = gullet_mut!();
781    g.read_budget_at = None;
782    g.read_budget_spent = false;
783    g.full_read_at = 0;
784  }
785}
786
787/// What [`ReadBudget::end`] tells.
788#[derive(Debug, Clone, Copy, PartialEq, Eq)]
789pub struct ReadBudgetEnd {
790  /// the tokens the run read
791  pub reads: usize,
792  /// it read all it may, and a read failed
793  pub over:  bool,
794}
795
796/// Restore the token limit and progress from a previous set_token_limit call.
797pub fn restore_token_limit(saved: (Option<usize>, usize)) {
798  let mut g = gullet_mut!();
799  g.token_limit = saved.0;
800  g.progress = saved.1;
801  g.full_read_at = 0;
802}
803
804macro_rules! runtime {
805  () => {
806    gullet_root().borrow_mut().runtime
807  };
808}
809
810/// The runaway-token BACKSTOP's baseline: real runaways are cut far earlier
811/// by the cycle guards / pushback limit / byte budget, so erring high costs
812/// no detection latency. The heaviest measured legit arXiv paper is
813/// math0402448 (amsart + xy-pic, 80.2M end-of-run progress under the
814/// 2026-06-10 all-three-reader-loop accounting; the old "80M" figure
815/// predated that multi-counting) and the former 400M ceiling was 5× that —
816/// but the TeX Live doc corpus goes higher with NO loop: tikzlings-doc
817/// (scrartcl, ~250 raw-pgf animal pictures through tcolorbox listings,
818/// each box typeset twice) completes at a measured 444.5M
819/// (`Debug:gullet:progress`, 2026-09-01, 30 KB main source so the
820/// per-byte scaling never engaged), and finite O(n²) macro work goes
821/// further still: circularglyphs-sample (xstring `\StrSubstitute` ×34 over
822/// 600-char phrases, ~2.5G) and source2e (l3doc crossrefs over 46k
823/// codelines, ~2G) both COMPLETE under `LATEXML_TOKEN_LIMIT=0` within the
824/// 300 s budget where Perl times out, yet died at the former 1G with a
825/// false "infinite loop?". 4G; raised, never lowered (a genuine loop is
826/// still bounded — by this ceiling, by the `--timeout` wall clock, by the
827/// cycle guards, and by the RSS cap). `LATEXML_TOKEN_LIMIT` overrides
828/// (0 disables). Book-scale sources raise it proportionally per
829/// conversion — see [`scale_token_limit_to_source`].
830/// 20e9 = the 300 s sweep wall at the measured 65 M tok/s ceiling: at 4e9
831/// the backstop fired at 61 s on lie-hasse's legitimate E8 poset figure
832/// (completes at ~8e9 in 124 s with a 304 KB picture; pdflatex 83 s) and
833/// mislabelled it "infinite loop" with a 39-byte XML. True loops are still
834/// bounded by the wall clock, the cycle guards and the RSS cap.
835pub const DEFAULT_TOKEN_LIMIT: usize = 20_000_000_000;
836
837/// Initialize the runaway-token backstop from the environment, falling back to
838/// [`DEFAULT_TOKEN_LIMIT`].
839fn default_token_limit() -> Option<usize> {
840  match std::env::var("LATEXML_TOKEN_LIMIT")
841    .ok()
842    .and_then(|v| v.parse::<usize>().ok())
843  {
844    Some(0) => None,
845    Some(n) => Some(n),
846    None => Some(DEFAULT_TOKEN_LIMIT),
847  }
848}
849
850/// Scale the runaway-token backstop to the SOURCE size — cumulatively, over
851/// every file the conversion opens. The [`DEFAULT_TOKEN_LIMIT`] baseline is
852/// sized for arXiv-scale inputs; a book-scale source legitimately expands
853/// past it (witness: a 131 MB flat-index compilation died at the then-400M
854/// ceiling mid-digestion with no loop in sight, at a measured ~3+
855/// tokens/byte and paper-class documents measured up to ~160 tokens/byte;
856/// l3doc's crossref pass over source2e's `.dtx`s ~1000/byte). ×1000/byte
857/// keeps the ceiling finite — a true infinite loop still trips, and opens
858/// no new files while it spins — while never LOWERING the baseline for
859/// small documents. The bytes are summed over the main source AND
860/// everything it `\input`s/`\DocInclude`s (every `Mouth::open_file`):
861/// source2e.tex is a 15 KB driver over ~40 `.dtx` files (~2 MB), so the
862/// driver-only sizing never engaged. An explicit `LATEXML_TOKEN_LIMIT` or
863/// `--token-limit` ([`fix_token_limit`]) wins unchanged (including 0 = disabled).
864pub fn scale_token_limit_to_source(source_bytes: usize) {
865  if std::env::var_os("LATEXML_TOKEN_LIMIT").is_some() {
866    return;
867  }
868  let mut gullet = gullet_mut!();
869  if gullet.token_limit_fixed {
870    return;
871  }
872  gullet.source_bytes_total = gullet.source_bytes_total.saturating_add(source_bytes);
873  let scaled = gullet
874    .source_bytes_total
875    .saturating_mul(1000)
876    .max(DEFAULT_TOKEN_LIMIT);
877  if let Some(limit) = gullet.token_limit.as_mut() {
878    *limit = (*limit).max(scaled);
879  }
880  gullet.full_read_at = 0;
881}
882
883/// Tell the setter watches whether the current mouth reads the document's own text
884/// (`definition::origin::note_document_mouth`), after the mouth changed.
885fn note_current_mouth(gullet: &Gullet) {
886  crate::definition::origin::note_document_mouth(
887    gullet
888      .runtime
889      .as_ref()
890      .is_some_and(|rt| rt.mouth.is_document_text()),
891  );
892}
893
894/// Initialize (or reset, if reentrant) a Gullet to its default empty state.
895pub fn initialize_gullet() {
896  let mut gullet = gullet_mut!();
897  gullet.runtime = None;
898  crate::definition::origin::note_document_mouth(false);
899  gullet.mouthstack = VecDeque::new();
900  gullet.pending_comments = VecDeque::new();
901  // Fresh per-conversion backstop: a prior book-scale conversion in this
902  // reused thread-local engine must not leak its scaled token limit into
903  // the next document.
904  gullet.token_limit = default_token_limit();
905  gullet.token_limit_fixed = false;
906  gullet.source_bytes_total = 0;
907  // Fresh per-conversion progress + cycle-guard history (the engine is a
908  // thread-local singleton reused across conversions in the test harness).
909  gullet.progress = 0;
910  gullet.cycle_guard.reset();
911  crate::cycle_guard::reset_value_salt();
912  // Reset the Cluster F expansion-depth counter + re-read its env limit
913  // (independent thread-locals, no GULLET borrow — safe to call here).
914  reset_expand_depth();
915  // Restore the default activation floor: a prior tikz/xy conversion in this
916  // reused thread-local engine must not leak its raised floor into the next doc.
917  gullet.cycle_guard_activate = CYCLE_GUARD_ACTIVATE;
918  gullet.full_read_at = 0;
919  gullet.read_budget_at = None;
920  gullet.read_budget_spent = false;
921  gullet.ctx_serial = 0;
922  gullet.ctx_next = 0;
923  gullet.ctx_stack.clear();
924  gullet.scanner_status = ScannerStatus::Normal;
925  gullet.warning_index = None;
926  gullet.runaway_argument = None;
927  gullet.true_end_misses.clear();
928  PAR_ENDS_ARGUMENT.with(|c| c.set(false));
929}
930
931/// Get the current location of input getting read
932pub fn get_locator() -> Locator { get_locator_opt().unwrap_or_default() }
933
934/// After Perl's `getLocator` (Gullet.pm:150-162): the innermost mouth with a source, else the first mouth of the
935/// stack; `None` when there is neither (before the first mouth opens, or a sourceless one alone). Perl keeps the
936/// last mouth its walk examined, so a sourceless mouth alone reports its own `String; line …` and an all-sourceless
937/// stack ends on the outermost mouth; here the first case has no `at` line (the binding machinery's mouth, not the
938/// document's, is the only one open) and the second takes the innermost (`front()`), as before. Porting Perl's
939/// walk exactly is a logged follow-up (row R RHAILOCWALK); only the message text differs.
940pub fn get_locator_opt() -> Option<Locator> {
941  let gullet = gullet!();
942  let mut runtime_opt = gullet.runtime.as_ref();
943  let mut mouthstack_iter = gullet.mouthstack.iter();
944  while runtime_opt.is_some() && runtime_opt.as_ref().unwrap().mouth.get_source().is_empty() {
945    runtime_opt = mouthstack_iter.next();
946  }
947  // A Mouth's `get_locator` is `Option` (per the `Object` trait) but always `Some`.
948  runtime_opt
949    .or_else(|| gullet.mouthstack.front())
950    .and_then(|runtime| runtime.mouth.get_locator())
951}
952
953/// `get_locator`'s accurate-start sibling (§1, docs/performance/SOURCE_PROVENANCE.md): same
954/// mouthstack walk, but reads the mouth's `get_locator_from_start` (`from` = the
955/// last token's captured start) instead of the heuristic `from`. Used for the
956/// construct-START snapshot at constructor digest under `--source-map`.
957pub fn get_locator_from_start() -> Locator {
958  let gullet = gullet!();
959  let mut runtime_opt = gullet.runtime.as_ref();
960  let mut mouthstack_iter = gullet.mouthstack.iter();
961  while runtime_opt.is_some() && runtime_opt.as_ref().unwrap().mouth.get_source().is_empty() {
962    runtime_opt = mouthstack_iter.next();
963  }
964  if let Some(runtime) = runtime_opt {
965    runtime.mouth.get_locator_from_start()
966  } else if let Some(runtime) = gullet.mouthstack.front() {
967    runtime.mouth.get_locator_from_start()
968  } else {
969    Locator::default()
970  }
971}
972
973/// The location of the innermost mouth that reads a source (not a token string,
974/// `Anonymous String`): where in the document a construct digested from a token
975/// list stands — `\footnote{…}`'s or `\section{…}`'s line, rather than nowhere.
976pub fn get_source_location() -> Option<String> {
977  innermost_locator(false).map(|locator| s!("at {}", locator))
978}
979
980/// `\inputlineno`'s locator: the innermost TeX input level, past the token mouths an `Expand` opens (Perl's are
981/// sourceless, Gullet.pm:150-156). `\scantokens`' pseudo-file is a level that counts its own lines (eTeX's
982/// `pseudo_start` sets `line:=0`, pdftex.web:38551), so it stops the walk though it reads no named source.
983pub fn get_input_locator() -> Locator { innermost_locator(true).unwrap_or_else(get_locator) }
984
985/// The locator of the innermost mouth reading a source, or (`file_levels`) marked a file level by
986/// [`mark_everyeof_mouth`].
987fn innermost_locator(file_levels: bool) -> Option<Locator> {
988  let gullet = gullet!();
989  gullet
990    .runtime
991    .iter()
992    .chain(gullet.mouthstack.iter())
993    .find(|runtime| {
994      let source = runtime.mouth.get_source();
995      (file_levels && runtime.insert_everyeof)
996        || (!source.is_empty() && source != "Anonymous String")
997    })
998    .and_then(|runtime| runtime.mouth.get_locator())
999}
1000
1001/// Comment-oriented location string, based on `get_locator`
1002pub fn get_location() -> String {
1003  let loc = get_locator();
1004  s!("at {}", loc)
1005}
1006
1007/// A message's location (`Error`/`Warn`, `error::location_line`): the innermost mouth reading a named source, past the
1008/// token lists a binding digests (`digest()`'s "Anonymous String"), as Perl's `getLocator` walks past a sourceless
1009/// mouth (Gullet.pm:150-162; `\lx@empheq@box`); else [`get_locator_opt`]'s; `None` where it finds no mouth (a
1010/// `--preload`ed binding, the dump load), where Perl's message has no `at` line (Error.pm:623) instead of
1011/// `Locator::default`'s Rust file. A box's locator stays [`get_locator_opt`]'s, which `--source-map` reads.
1012pub fn get_location_opt() -> Option<String> {
1013  innermost_locator(false)
1014    .or_else(get_locator_opt)
1015    .map(|loc| s!("at {}", loc))
1016}
1017
1018pub fn mouth_is_open(mouth: &Mouth) -> bool {
1019  let gullet = gullet!();
1020  if let Some(ref runtime) = gullet.runtime
1021    && mouth == &runtime.mouth
1022  {
1023    return true;
1024  }
1025  gullet
1026    .mouthstack
1027    .iter()
1028    .any(|runtime| &runtime.mouth == mouth)
1029}
1030
1031/// Push the `tokens` back into the input stream to be re-read.
1032pub fn unread(tokens: Tokens) { unread_vec(tokens.unlist()); }
1033/// Unreads a single `Token` to the start of the token stream.
1034/// Perl: unread() always adjusts $ALIGN_STATE when unreading { or } tokens.
1035pub fn unread_one(token: Token) {
1036  match token.get_catcode() {
1037    Catcode::BEGIN => decrement_align_group_count(), // Retract scanned brace
1038    Catcode::END => increment_align_group_count(),
1039    _ => {},
1040  }
1041  if let Some(ref mut runtime) = gullet_mut!().runtime {
1042    runtime.pushback.push(token);
1043  };
1044}
1045/// Push EXPANSION OUTPUT (macro bodies, conditional-branch replays, `\the`
1046/// results) to the start of the token stream WITHOUT touching the alignment
1047/// brace ledger.
1048///
1049/// tex.web distinguishes two insertion flavors: `back_input` (§325) RETRACTS
1050/// `align_state` for a brace token because that token was already counted
1051/// when scanned (`get_next` §342-344 counts every scanned brace, token lists
1052/// included §357); `begin_token_list` — how an expansion enters the input —
1053/// adjusts NOTHING, because expansion output was never scanned and its braces
1054/// will be counted when they are. Retracting never-scanned braces here is not
1055/// merely a transient skew: expl3 brace-tricks (`\if… { \else: } \fi:` under
1056/// `\exp_after:wN`, the l3tl replace machinery) legitimately push UNBALANCED
1057/// fragments whose skipped half was counted by the conditional skipper — the
1058/// Perl-style retract-everything protocol (Gullet.pm L343-358, which Perl
1059/// LaTeXML still has) then drifts `ALIGN_STATE` permanently negative and every
1060/// later `&` in the alignment goes stray (l3doc `{function}` manuals; repro:
1061/// `\tl_greplace_all:Nnn` + a protected macro emitting `&` inside a tabular
1062/// cell). See `cluster_package_guards::alignment_ledger_expansion_pushback`.
1063pub fn unread_expansion(tokens: Tokens) {
1064  if let Some(ref mut runtime) = gullet_mut!().runtime {
1065    let tokens = tokens.unlist();
1066    runtime.pushback.reserve(tokens.len());
1067    for token in tokens.into_iter().rev() {
1068      runtime.pushback.push(token);
1069    }
1070  }
1071}
1072
1073/// Push `tokens` to be read where the innermost `\input` file ([`mark_everyeof_mouth`]) ends, in its enclosing level,
1074/// after the file's own end code (`content::input_file_ended`); false when no such file is open.
1075pub fn unread_after_current_file(tokens: Tokens) -> bool {
1076  let mut gullet = gullet_mut!();
1077  let gullet = &mut *gullet;
1078  let mut levels = gullet
1079    .runtime
1080    .iter_mut()
1081    .chain(gullet.mouthstack.iter_mut());
1082  if !levels.any(|runtime| runtime.insert_everyeof) {
1083    return false;
1084  }
1085  let Some(enclosing) = levels.next() else {
1086    return false;
1087  };
1088  enclosing.pushback.extend(tokens.unlist().into_iter().rev());
1089  true
1090}
1091
1092/// [`unread_substituted`] of arguments all read as tokens, each found where it is.
1093pub fn unread_substituted_args(
1094  body: &[Token],
1095  plan: &[crate::tokens::BodyPiece],
1096  args: &[crate::definition::argument::ArgWrap],
1097) {
1098  use crate::{definition::argument::ArgWrap, tokens::BodyPiece};
1099  if let Some(ref mut runtime) = gullet_mut!().runtime {
1100    let pushback = &mut runtime.pushback;
1101    for piece in plan.iter().rev() {
1102      match *piece {
1103        BodyPiece::Run(start, end) => {
1104          pushback.extend(body[start as usize..end as usize].iter().rev().copied());
1105        },
1106        BodyPiece::Parameter(n) => {
1107          if let Some(ArgWrap::Tokens(arg)) = n.checked_sub(1).and_then(|i| args.get(i)) {
1108            pushback.extend(arg.unlist_ref().iter().rev().copied());
1109          }
1110        },
1111      }
1112    }
1113  }
1114}
1115
1116/// [`unread_expansion`] of a macro body with its parameters substituted (`Tokens::substitute_parameters`),
1117/// without building the list first: tex.web `macro_call` (§390) puts the body on the input as stored and the
1118/// arguments where its `out_param`s are. The pieces go onto the pushback stack last first, each reversed;
1119/// `args[n - 1]` is parameter `#n`'s argument. The brace ledger is not touched, as for any expansion output.
1120pub fn unread_substituted(body: &[Token], plan: &[crate::tokens::BodyPiece], args: &[&[Token]]) {
1121  use crate::tokens::BodyPiece;
1122  if let Some(ref mut runtime) = gullet_mut!().runtime {
1123    let pushback = &mut runtime.pushback;
1124    for piece in plan.iter().rev() {
1125      match *piece {
1126        BodyPiece::Run(start, end) => {
1127          pushback.extend(body[start as usize..end as usize].iter().rev().copied());
1128        },
1129        BodyPiece::Parameter(n) => {
1130          if let Some(arg) = n.checked_sub(1).and_then(|i| args.get(i)) {
1131            pushback.extend(arg.iter().rev().copied());
1132          }
1133        },
1134      }
1135    }
1136  }
1137}
1138
1139/// `back_input`-style ledger retraction WITHOUT pushing anything: apply to
1140/// tokens that were READ through a counting reader and are about to be
1141/// RE-EMITTED as part of an expansion result (so they will be counted again
1142/// when rescanned). tex.web §368: `\expandafter` saves its first token and
1143/// `back_input`s it (§325 retracts a scanned brace) around the one-step
1144/// expansion, which enters as an unadjusted token list. A closure-style
1145/// expandable that returns previously-read tokens inside its expansion must
1146/// call this on that re-emitted portion, or every `{`/`}` passed through it
1147/// is double-counted (l3's `\exp_after:wN {` idiom drove the alignment
1148/// ledger positive and `&` went stray — see [`unread_expansion`]).
1149pub fn retract_scanned_brace(token: &Token) { retract_scanned_braces(std::slice::from_ref(token)); }
1150
1151pub fn retract_scanned_braces(tokens: &[Token]) {
1152  for token in tokens {
1153    match token.get_catcode() {
1154      Catcode::BEGIN => decrement_align_group_count(),
1155      Catcode::END => increment_align_group_count(),
1156      _ => {},
1157    }
1158  }
1159}
1160
1161/// Unreads a `Vec<Token>` to the start of the token stream
1162/// Perl: also adjusts ALIGN_STATE by retracting scanned braces (Gullet.pm lines 343-358).
1163/// Correct ONLY for tokens that were previously READ (and hence counted) —
1164/// for expansion output use [`unread_expansion`] (tex.web `begin_token_list`
1165/// flavor, which adjusts nothing).
1166pub fn unread_vec(tokens: Vec<Token>) { unread_iter(tokens.into_iter()) }
1167
1168/// [`unread_vec`] of the tokens `tokens` yields (a drain of a buffer kept for reuse).
1169fn unread_iter(tokens: impl DoubleEndedIterator<Item = Token> + ExactSizeIterator) {
1170  let mut level: i64 = 0;
1171  if let Some(ref mut runtime) = gullet_mut!().runtime {
1172    // Reserve once, push each token in reverse-iteration order so the
1173    // first element of `tokens` ends up at the stack top. Same
1174    // semantics as the old VecDeque push_front loop, but without
1175    // per-element head-pointer arithmetic.
1176    runtime.pushback.reserve(tokens.len());
1177    for token in tokens.rev() {
1178      match token.get_catcode() {
1179        Catcode::BEGIN => level -= 1, // Retract scanned braces
1180        Catcode::END => level += 1,
1181        _ => {},
1182      }
1183      runtime.pushback.push(token);
1184    }
1185  }
1186  if level != 0 {
1187    set_align_group_count(align_group_count() + level as i32);
1188  }
1189}
1190
1191//**********************************************************************
1192// Start reading tokens from a new Mouth.
1193// This pushes the mouth as the current source that $gullet->readToken (etc) will read from.
1194// Once this Mouth has been exhausted, readToken, etc, will return undef,
1195// until you call $gullet->closeMouth to clear the source.
1196// Exception: if $toplevel=1, readXToken will step to next source
1197// Note that a Tokens can act as a Mouth.
1198pub fn open_mouth(mouth: Mouth, autoclose: bool) {
1199  open_mouth_with(mouth, autoclose, BalancedBoundary::Transparent);
1200}
1201
1202/// [`open_mouth`], choosing how a balanced read treats the new mouth's end.
1203///
1204/// Pass [`BalancedBoundary::Opaque`] whenever the mouth carries a self-contained
1205/// input rather than a continuation of the current line — see the type's docs.
1206pub fn open_mouth_with(mouth: Mouth, autoclose: bool, boundary: BalancedBoundary) {
1207  let mut gullet = gullet_mut!();
1208  if let Some(runtime) = gullet.runtime.take() {
1209    gullet.mouthstack.push_front(runtime);
1210  };
1211  gullet.runtime = Some(MouthRuntime {
1212    mouth,
1213    autoclose,
1214    boundary,
1215    insert_everyeof: false,
1216    eof_seen: false,
1217    file_hooks: None,
1218    pushback: Vec::with_capacity(128),
1219    watch: PushbackWatch::default(),
1220  });
1221  note_current_mouth(&gullet);
1222}
1223
1224/// Mark the CURRENT mouth as an eTeX file level whose end inserts the
1225/// `\everyeof` token list (see [`MouthRuntime::insert_everyeof`]). Every
1226/// `\input` file mouth is marked (`content.rs::load_tex_content`), and so is
1227/// the `\scantokens` pseudo-file (`etex.rs`).
1228///
1229/// The mark also makes the mouth a TeX file level, of which at most [`MAX_IN_OPEN`] may be open at once: one more is
1230/// TeX's "TeX capacity exceeded, sorry [text input levels=15]" (tex.web §328), a Fatal. A macro that `\input`s the
1231/// file it is read from (`\def\x{\input loopf }\x`, loopf.tex holding `\x`) otherwise nested files without end.
1232pub fn mark_everyeof_mouth() -> Result<()> {
1233  let levels = {
1234    let mut gullet = gullet_mut!();
1235    if let Some(ref mut runtime) = gullet.runtime {
1236      runtime.insert_everyeof = true;
1237    }
1238    gullet
1239      .runtime
1240      .iter()
1241      .chain(gullet.mouthstack.iter())
1242      .filter(|r| r.insert_everyeof)
1243      .count()
1244  };
1245  if levels > MAX_IN_OPEN {
1246    Fatal!(
1247      Mouth,
1248      Recursion,
1249      s!("TeX capacity exceeded, sorry [text input levels={MAX_IN_OPEN}]")
1250    );
1251  }
1252  Ok(())
1253}
1254
1255/// Mark the CURRENT mouth, a content file just opened, as one whose end runs `\InputIfFileExists`' code after
1256/// `\@@input` (latex.ltx:19670-19673), decided when the file ends as TeX reads it then (`content::input_file_ended`).
1257pub fn mark_file_hooks_mouth(end: FileHooksEnd) {
1258  if let Some(ref mut runtime) = gullet_mut!().runtime {
1259    runtime.file_hooks = Some(end);
1260  }
1261}
1262
1263pub fn close_mouth(forced: bool) -> Result<()> {
1264  let mut shift_from_mouthstack = false;
1265  let mut error_has_more_input = false;
1266  if let Some(ref mut runtime) = runtime!()
1267    && !forced
1268    && (!runtime.pushback.is_empty() || runtime.mouth.has_more_input())
1269  {
1270    error_has_more_input = true
1271  }
1272  if error_has_more_input {
1273    let next = match read_token()? {
1274      Some(t) => t.stringify(),
1275      None => String::from("Empty"),
1276    };
1277    let message = s!("Closing mouth with input remaining '{}'", next);
1278    Error!("unexpected", next, message);
1279  }
1280  let mut wants_everyeof = false;
1281  let mut file_hooks = None;
1282  {
1283    let mut gullet = gullet_mut!();
1284    if let Some(ref mut runtime) = gullet.runtime {
1285      runtime.mouth.finish();
1286      file_hooks = runtime.file_hooks.take();
1287      // A FORCED close is error-recovery/cleanup (`reading_from_mouth`
1288      // teardown) — never a file end, so it must not inject the payload
1289      // into a recovery stream.
1290      wants_everyeof = runtime.insert_everyeof && !forced && !runtime.eof_seen;
1291      shift_from_mouthstack = true;
1292    }
1293    if shift_from_mouthstack {
1294      gullet.runtime = gullet.mouthstack.pop_front();
1295      note_current_mouth(&gullet);
1296    }
1297  }
1298  if let Some(end) = file_hooks {
1299    crate::binding::content::input_file_ended(&end, forced)?;
1300  }
1301  // Insurance for a marked mouth closed before it ever ran dry (a forced
1302  // teardown is excluded above, and `\endinput` sets `eof_seen`): insert the
1303  // payload where reading continues. Token-identity preserved — expansion
1304  // flavor push.
1305  if wants_everyeof
1306    && let Some(RegisterValue::Tokens(eof_toks)) = internal_register_value("\\everyeof")
1307    && !eof_toks.is_empty()
1308  {
1309    unread_expansion(eof_toks);
1310  }
1311  Ok(())
1312}
1313/// A file has just ended under the current read: tex.web §362 closes it and
1314/// calls §336 `check_outer_validity`, which, when the [`ScannerStatus`] is not
1315/// normal, reports the runaway (§338 "File ended while scanning definition /
1316/// use / preamble / text of \cs") and inserts the tokens that should lead to
1317/// recovery (§339).
1318///
1319/// Only an autoclose file level with an enclosing input ends like this: an
1320/// `\input` file, a file held in memory (filecontents, an `\openout` file),
1321/// catchfile's opener ([`crate::mouth::Mouth::is_file_level`]). A package or
1322/// class read through `reading_from_mouth` (not autoclose) and the main
1323/// document keep Perl's stop at their end; string mouths (`\scantokens`,
1324/// RawTeX) are no file levels (`read_balanced` crosses them).
1325///
1326/// - `defining`, `absorbing`: a `}` — the definition or text ends at the
1327///   file's end and the enclosing input goes on;
1328/// - `aligning`: `\cr` and `}` — the preamble, and with it the alignment, ends;
1329/// - `matching`: TeX inserts `\par` with `long_state:=outer_call`, and
1330///   `macro_call` abandons the call and drops its arguments on reading it
1331///   (§392 "Report a runaway argument and abort", which consumes the `\par`).
1332///   Modelled without the token: [`FileEndRecovery::Abandoned`] marks
1333///   [`argument_runaway`] and the reader stops; the report and the file's
1334///   close wait for the call ([`abandon_runaway_call`]), which alone knows
1335///   whether TeX would have stopped earlier, at a `\par`. Until then the ended
1336///   file stays current, so a reader loop that does not look at the mark meets
1337///   the same end again rather than reading on into the enclosing input.
1338///
1339/// The inserted tokens enter as `ins_list` inserts them, as input never
1340/// scanned (`unread_expansion`): the brace ledger counts the `}` when it is
1341/// read, which balances the definition's opening `{`.
1342pub fn recover_at_file_end() -> Result<FileEndRecovery> {
1343  let (status, warning_index, file_end, runaway) = {
1344    let gullet = gullet!();
1345    let file_end = !gullet.mouthstack.is_empty()
1346      && gullet
1347        .runtime
1348        .as_ref()
1349        .is_some_and(|r| r.autoclose && r.mouth.is_file_level());
1350    (
1351      gullet.scanner_status,
1352      gullet.warning_index,
1353      file_end,
1354      gullet.runaway_argument.is_some(),
1355    )
1356  };
1357  if status == ScannerStatus::Normal || !file_end {
1358    return Ok(FileEndRecovery::NotARunaway);
1359  }
1360  if status == ScannerStatus::Matching {
1361    // Met again by a reader that went on, the same end is the same runaway.
1362    if !runaway {
1363      gullet_mut!().runaway_argument = Some(Runaway::FileEnd(Vec::new()));
1364    }
1365    return Ok(FileEndRecovery::Abandoned);
1366  }
1367  let of = warning_index.map(|cs| s!(" of {cs}")).unwrap_or_default();
1368  let message = s!("File ended while scanning {}{of}", status.scanning_what());
1369  Error!("expected", "}", message);
1370  close_mouth(false)?;
1371  unread_expansion(if status == ScannerStatus::Aligning {
1372    // TeX inserts `frozen_cr` (§339), the primitive whatever `\cr` means now:
1373    // the engine's `\lx@frozen@cr`, a `\let` copy of the primitive taken when
1374    // `\cr` is defined (tex_tables.rs), so an author's `\def\cr` does not run
1375    // here (`is_column_end` takes the copy for `\cr`). Guard:
1376    // `perfect_kernel_batch65::file_end_in_a_preamble_inserts_the_frozen_cr`.
1377    let frozen_cr = T_CS!("\\lx@frozen@cr");
1378    let cr = if with_meaning(&frozen_cr, |defn| defn.is_some()) {
1379      frozen_cr
1380    } else {
1381      T_CS!("\\cr")
1382    };
1383    Tokens!(cr, T_END!())
1384  } else {
1385    Tokens!(T_END!())
1386  });
1387  Ok(FileEndRecovery::Inserted)
1388}
1389
1390/// [`recover_at_file_end`] for a reader of macro arguments only (a single
1391/// token, a delimited argument; tex.web §392): whether the call is abandoned.
1392/// At any other status such a reader keeps its own end-of-input behaviour.
1393pub fn argument_ran_off_a_file() -> Result<bool> {
1394  Ok(
1395    scanner_status() == ScannerStatus::Matching
1396      && recover_at_file_end()? == FileEndRecovery::Abandoned,
1397  )
1398}
1399
1400/// Abandon the call of `cs` whose argument ran off the end of a file, given
1401/// the `runaway` tokens it had read ([`ScannerStatusGuard::end_taking_runaway_argument`]).
1402///
1403/// TeX checks every token of a non-`\long` macro's argument for `\par`
1404/// (tex.web §392, §399) and at the first one abandons the call, "Paragraph
1405/// ended before \cs was complete", putting the `\par` back (§396
1406/// `back_error`): the call and its argument up to there are dropped, and the
1407/// rest is read again. The readers make that check while they read for a
1408/// macro whose long-ness is TeX's ([`Runaway::Paragraph`]); for LaTeXML's own
1409/// macros (Perl's `isLong` is stored, Expandable.pm:46, and never read) it is
1410/// made here, on the runaway only: the argument ran to the file's end, past
1411/// the `\par` where TeX stopped, and without the check the call would drop
1412/// everything after it too. The tokens from that `\par` on go back into the
1413/// file, which then ends later, under the enclosing scan.
1414///
1415/// Otherwise (a `\long` macro, or no `\par`) it is the file's end: "File ended
1416/// while scanning use of \cs" (§338-339), and the file is closed now, as
1417/// tex.web §362 closes it (`end_file_reading`) before recovering, so the next
1418/// read is from the enclosing input (`\expandafter\a\foo{…` gives `\a` the
1419/// next token after `\input`).
1420pub fn abandon_runaway_call(
1421  cs: Token,
1422  is_long: bool,
1423  checks_par: bool,
1424  runaway: Runaway,
1425) -> Result<()> {
1426  let runaway = match runaway {
1427    // The reader stopped at the `\par` (tex.web §392, §399): report it and put back only the `\par` (§396
1428    // `back_error`); the arguments read so far are dropped with the call.
1429    // The token goes back as TeX's `cur_tok`: a `\noexpand`ed `\par` without its mark (§358).
1430    Runaway::Paragraph(par) => {
1431      Error!(
1432        "unexpected",
1433        "\\par",
1434        s!("Paragraph ended before {cs} was complete")
1435      );
1436      let par = if par.noexpand_shadowed().is_some() {
1437        T_CS!("\\par")
1438      } else {
1439        par
1440      };
1441      unread_expansion(Tokens!(par));
1442      return Ok(());
1443    },
1444    // The put-back is still in the input, read on after the call (§392 drops the argument; Perl reads it on).
1445    Runaway::TrueEnd { first: true } => {
1446      Error!(
1447        "expected",
1448        "\\par",
1449        s!("File ended while scanning use of {cs}")
1450      );
1451      return Ok(());
1452    },
1453    Runaway::TrueEnd { first: false } => {
1454      Info!(
1455        "expected",
1456        "\\par",
1457        s!("File ended while scanning use of {cs} again")
1458      );
1459      return Ok(());
1460    },
1461    Runaway::FileEnd(tokens) => tokens,
1462  };
1463  let par = T_CS!("\\par");
1464  // A macro that checks while it reads met no `\par` it should stop at (only one a delimiter accepted): the
1465  // file's end. The others are checked here, on the runaway only.
1466  match runaway
1467    .iter()
1468    .position(|t| !is_long && !checks_par && *t == par)
1469  {
1470    Some(at) => {
1471      Error!(
1472        "unexpected",
1473        "\\par",
1474        s!("Paragraph ended before {cs} was complete")
1475      );
1476      // Never scanned, as far as the brace ledger knows: the readers
1477      // retracted the argument's braces when they stopped.
1478      unread_expansion(Tokens::new(runaway[at..].to_vec()));
1479    },
1480    None => {
1481      Error!(
1482        "expected",
1483        "\\par",
1484        s!("File ended while scanning use of {cs}")
1485      );
1486      // Only the file that ended: still current, nothing left in it.
1487      let ended_file = {
1488        let mut gullet = gullet_mut!();
1489        let has_parent = !gullet.mouthstack.is_empty();
1490        gullet.runtime.as_mut().is_some_and(|r| {
1491          has_parent
1492            && r.autoclose
1493            && r.mouth.is_file_level()
1494            && r.pushback.is_empty()
1495            && !r.mouth.has_more_input()
1496        })
1497      };
1498      if ended_file {
1499        close_mouth(false)?;
1500      }
1501    },
1502  }
1503  Ok(())
1504}
1505
1506/// This flushes a mouth so that it will be automatically closed, next time it's read
1507/// Corresponds to TeX's \endinput
1508pub fn flush_mouth() {
1509  if let Some(ref mut runtime) = runtime!() {
1510    // Collect remaining mouth tokens in mouth order (t1, t2, t3, …),
1511    // then splice them into the stack's BOTTOM in reverse order so
1512    // that after the stack's existing top is popped, the mouth tokens
1513    // come out in the original mouth order (t1 first, then t2, …).
1514    // Only the current line's: a comment ends it, and with source comments off (OD #2) the Mouth reads past a `%` to
1515    // the next line, whose tokens TeX never reads (tex.web §362). atbegshi.sty:557's
1516    // `\AtBegShi@AbortIfUndefined{AtBeginDocument}%`, whose `\endinput` comes from the macro's expansion, read on
1517    // into line 558 under the restored `@` catcode (`\AtBegShi` undefined, the file's definitions unbalanced: math0305287, a
1518    // plain TeX paper loading pstricks through pgfutil-plain.def; guard
1519    // `perfect_kernel_batch65f::endinput_from_a_macro_ends_the_file_at_the_line`).
1520    let line = runtime.mouth.line_number();
1521    let mut trailer: Vec<Token> = Vec::new();
1522    while !runtime.mouth.is_eol() {
1523      if let Some(token) = runtime.mouth.read_token() {
1524        if runtime.mouth.line_number() != line {
1525          break;
1526        }
1527        trailer.push(token);
1528      }
1529    }
1530    if !trailer.is_empty() {
1531      trailer.reverse();
1532      // (every token the pushback held moves up a slot: as if read, for the input marks)
1533      runtime.watch.note_len(0);
1534      runtime.pushback.splice(0..0, trailer);
1535    }
1536    // Stop reading (clear buffers, close file) but do NOT restore catcodes.
1537    // Catcodes are restored by close_mouth → finish() when the mouth is
1538    // properly popped from the stack.
1539    runtime.mouth.stop_reading();
1540    // eTeX inserts `\everyeof` only when a file really ends: `\endinput` sets
1541    // `force_eof`, and §362 then ends the file without the list (pdflatex
1542    // `[X]` for `X\endinput`; the payload came out as `[X[EOF]]`). Guard:
1543    // `noexpand_input_ends::endinput_does_not_insert_everyeof`.
1544    runtime.eof_seen = true;
1545  }
1546}
1547
1548//**********************************************************************
1549// Low-level readers: read token, read expanded token
1550//**********************************************************************
1551// # Get the next pending comment token (if any)
1552pub fn get_pending_comment() -> Option<Token> { gullet_mut!().pending_comments.pop_front() }
1553
1554/// Queue sizes `(mouthstack, pending_comments)` — pass-1 streaming telemetry.
1555pub fn queue_sizes() -> (usize, usize) {
1556  let gullet = gullet!();
1557  (gullet.mouthstack.len(), gullet.pending_comments.len())
1558}
1559
1560/// Note that every char (token) comes through here (maybe even twice, through args parsing),
1561/// So, be Fast & Clean!  This method only reads from the current input stream (Mouth).
1562fn handle_template(
1563  mut alignment: RefMut<Alignment>,
1564  token: Token,
1565  vtype: &str,
1566  hidden: bool,
1567) -> Result<()> {
1568  //  Append expansion to end!?!?!?!
1569  let _token_guard = local_current_token_guard(token);
1570  let post = alignment.get_column_after();
1571  set_align_group_count(1000000);
1572  // ### NOTE: Truly fishy smuggling w/ \lx@hidden@cr
1573  let arg_opt = if (vtype == "cr") && hidden {
1574    // \lx@hidden@cr gets an argument as payload!!!!!
1575    Some(read_arg(ExpansionLevel::Off)?)
1576  } else {
1577    None
1578  };
1579  // eprintln!("Halign: column after {post}");// . ToString($post) if $LaTeXML::DEBUG{halign};
1580  if (vtype == "cr" || vtype == "crcr")
1581    && alignment.is_in_row()
1582    && !alignment
1583      .current_row()
1584      .map(|v| v.is_pseudo())
1585      .unwrap_or(false)
1586  {
1587    unread_one(T_CS!("\\lx@alignment@row@after"));
1588  }
1589  if let Some(arg) = arg_opt {
1590    // slippery - to unread {arg} we first unread } then arg then {, as we push to the front.
1591    unread_one(T_END!());
1592    unread(arg);
1593    unread_one(T_BEGIN!());
1594  }
1595  unread_one(token);
1596  unread(post);
1597  Ok(())
1598}
1599
1600/// Where a combined read ([`read_internal_token_checked`]) routes COMMENT
1601/// tokens: the shared `pending_comments` queue (`read_token` / `read_x_token` /
1602/// `read_next_conditional`) or straight into a caller-owned buffer
1603/// (`read_balanced`, which keeps comments in its result).
1604enum CommentSink<'a> {
1605  Pending,
1606  Into(&'a mut Vec<Token>),
1607}
1608
1609/// Outcome of [`read_internal_token_checked`].
1610enum CheckedRead {
1611  /// The gullet has no runtime — early shutdown / recovery from a fatal
1612  /// error. Treated as end-of-input instead of panicking. Driver: 2404.06289
1613  /// (natbib \NAT@@wrout cascade landed here after the conversion was already
1614  /// in error-recovery mode).
1615  NoRuntime,
1616  /// The current mouth(s) yielded no token (exhausted); the caller decides
1617  /// whether an autoclose boundary may be crossed.
1618  Exhausted,
1619  /// The next token, already progress-counted and cycle-fingerprinted.
1620  Tok(Token),
1621}
1622
1623/// Duty cycle for the ACTIVE cycle guard (`progress` above the activation
1624/// floor): fingerprint + scan only [`CYCLE_GUARD_DUTY_ON`] of every
1625/// [`CYCLE_GUARD_DUTY_PERIOD`] tokens. A genuine infinite expansion loop is
1626/// *persistent*, so scanning periodic windows still detects it — worst case
1627/// one duty period plus a ring fill later (~36k tokens), four orders of
1628/// magnitude before the 1G `token_limit` backstop — while a legitimately
1629/// huge healthy stream (pgfplots data plots routinely read 200M+ tokens, past
1630/// even the raised graphics floor) stops paying a per-token fingerprint tax
1631/// for the whole remainder of the run (`cycle_guard_checkpoint` was 6.07% of
1632/// self-time on witness 2405.14114 before duty-cycling). The ring is reset at
1633/// each ON-window start so a window never straddles an OFF gap (no cross-gap
1634/// phase artifacts). The ON width covers the ring capacity
1635/// (`MAX_WINDOW × REPEAT = 3200`) plus detection cadence (`CHECK_EVERY`) for
1636/// every period, so any loop already running at an ON-window start is caught
1637/// within that same window; both widths doubled with `MAX_WINDOW` 10 → 32, so
1638/// the fingerprinted share stays 1/8. Bursts that end on their own inside an
1639/// OFF window are, by definition, not infinite loops — the guard's only target.
1640const CYCLE_GUARD_DUTY_PERIOD: usize = 32_768; // power of two (masked below)
1641const CYCLE_GUARD_DUTY_ON: usize = 4_096;
1642const _: () =
1643  assert!(CYCLE_GUARD_DUTY_ON > crate::cycle_guard::MAX_WINDOW * crate::cycle_guard::REPEAT + 256);
1644
1645/// Per-token combined step for all FOUR reader loops (`read_token`,
1646/// `read_x_token`, `read_balanced`, `read_next_conditional`): resource
1647/// checkpoint, low-level pushback/mouth read, and (duty-cycled) cycle-guard
1648/// fingerprint in ONE `GULLET` borrow. The loops are siblings, NOT a
1649/// delegation chain, so each runs this same step — otherwise full-expansion
1650/// paths (`\edef`, csname construction, conditional skipping) bypass every
1651/// gullet guard and a runaway grinds to the watchdog (gap found on
1652/// math0402448). Previously three separate borrows per token
1653/// (`read_resource_checkpoint` → `read_internal_token` →
1654/// `cycle_guard_checkpoint`, together ~10% of self-time on the pgfplots
1655/// witness 2405.14114); the single borrow is the point of the merge.
1656///
1657/// Resource accounting:
1658/// - `progress` counts UNCONDITIONALLY: the cycle guard's activation gate
1659///   feeds off it, so nesting the increment inside the token-limit branch
1660///   made `LATEXML_TOKEN_LIMIT=0` (and `set_token_limit(None)` during format
1661///   init) silently disable the cycle guard as well — exactly when an
1662///   operator disables the limit to let a big document through is when the
1663///   loop guard matters most. (PR #249 review P2-5.) Only the limit
1664///   COMPARISON stays conditional.
1665/// - Limit breaches Fatal via the `#[cold]` outlined helpers below, with the
1666///   borrow dropped first (`Fatal!` runs error machinery). A breach consumes
1667///   no token: the read is skipped, exactly as when the old checkpoint fired
1668///   before the read.
1669///
1670/// Cycle guard: fingerprints the token AS READ (before alignment /
1671/// `\dont_expand` special-casing), so the guard sees the same stream
1672/// regardless of which loop reads it. The reading-context serial is mixed
1673/// into the fingerprint (see `Gullet::ctx_serial`) so windows never match
1674/// across `reading_from_mouth` contexts; a token read from the Mouth (input,
1675/// not expansion output) also carries its source position. Activation is gated on
1676/// `progress > cycle_guard_activate` AND the duty window above.
1677#[inline]
1678fn read_internal_token_checked(sink: CommentSink) -> Result<CheckedRead> {
1679  {
1680    let mut borrow = gullet_mut!();
1681    let g: &mut Gullet = &mut borrow;
1682    // The usual read: nothing is due at this count (`full_read_at`), and the token on top of the pushback is an
1683    // ordinary one. It does exactly what the full read does in that case, without testing each thing that isn't due.
1684    // (The input marks' floor, `PushbackWatch`, is its emptiness test: 0 with no live mark; a read at or below it is
1685    // the full read's, which tells the watch.)
1686    if g.progress + 1 < g.full_read_at
1687      && (matches!(sink, CommentSink::Pending) || g.pending_comments.is_empty())
1688      && let Some(rt) = g.runtime.as_mut()
1689      && g
1690        .pushback_limit
1691        .is_none_or(|limit| rt.pushback.len() <= limit)
1692      && rt.pushback.len() > rt.watch.floor
1693      && let Some(&token) = rt.pushback.last()
1694      && !matches!(token.get_catcode(), Catcode::COMMENT | Catcode::MARKER)
1695    {
1696      rt.pushback.pop();
1697      g.progress += 1;
1698      return Ok(CheckedRead::Tok(token));
1699    }
1700  }
1701  read_internal_token_full(sink)
1702}
1703
1704/// [`read_internal_token_checked`] in full, whatever is due: see that function's documentation above.
1705#[inline(never)]
1706fn read_internal_token_full(mut sink: CommentSink) -> Result<CheckedRead> {
1707  enum Breach {
1708    TokenLimit(usize),
1709    PushbackLimit(usize),
1710    Cycle(usize, Token),
1711    Deadline,
1712    ReadBudget,
1713  }
1714  let mut breach: Option<Breach> = None;
1715  let mut outcome = CheckedRead::Exhausted;
1716  {
1717    let mut borrow = gullet_mut!();
1718    let g: &mut Gullet = &mut borrow;
1719    if g.runtime.is_none() {
1720      return Ok(CheckedRead::NoRuntime);
1721    }
1722    g.progress += 1;
1723    if g.progress >= g.full_read_at {
1724      g.full_read_at = g.next_full_read();
1725    }
1726    // (`next_due_read` stands in for these tests on the fast path, and `token_limit_tests::is_due` spells them: change
1727    // all three together.)
1728    let rt = g.runtime.as_mut().unwrap();
1729    if let Some(limit) = g.token_limit
1730      && g.progress > limit
1731    {
1732      breach = Some(Breach::TokenLimit(limit));
1733    } else if let Some(limit) = g.pushback_limit
1734      && rt.pushback.len() > limit
1735    {
1736      breach = Some(Breach::PushbackLimit(limit));
1737    } else if g.progress & DEADLINE_CHECK_MASK == 0 && crate::stomach::conversion_deadline_passed()
1738    {
1739      // The cooperative conversion deadline (`stomach::set_timeout`), checked here too: an expansion that never
1740      // returns to a digestion loop never met it, and only a process watchdog, where one is armed, ended the run
1741      // (OD #538).
1742      breach = Some(Breach::Deadline);
1743    } else if g.read_budget_at.is_some_and(|at| g.progress > at) {
1744      g.read_budget_spent = true;
1745      breach = Some(Breach::ReadBudget);
1746    } else {
1747      // Duty-cycled guard activation, computed BEFORE the read: the phase —
1748      // and the ON-window-start ring reset — depends only on `progress`,
1749      // which is already final for this iteration. An Exhausted read landing
1750      // exactly on phase 1 must still reset the ring, or the next window
1751      // would splice onto the previous ON-window's history (adversarial-
1752      // review finding, 2026-07-29).
1753      let duty_on = g.progress > g.cycle_guard_activate && {
1754        let phase = (g.progress - g.cycle_guard_activate) & (CYCLE_GUARD_DUTY_PERIOD - 1);
1755        if phase == 1 {
1756          // ON-window start: drop any pre-gap history.
1757          g.cycle_guard.reset();
1758        }
1759        (1..=CYCLE_GUARD_DUTY_ON).contains(&phase)
1760      };
1761      if let CommentSink::Into(ref mut out) = sink {
1762        // read_balanced keeps comments in its result: flush comments stashed
1763        // by earlier reads before reading fresh ones (same order as the old
1764        // inline loop's `pending_comments` drain at its top).
1765        if !g.pending_comments.is_empty() {
1766          out.extend(g.pending_comments.drain(..));
1767        }
1768      }
1769      // The raw read: pushback first, then the current Mouth. COMMENT tokens
1770      // go to the sink, MARKER tokens are handled inline (handle_marker only
1771      // touches the align-count thread-locals, never GULLET — it already ran
1772      // under this borrow in the old `read_internal_token`). `route` is the
1773      // shared per-token filter: `Some(t)` = a real token, `None` = consumed
1774      // (comment/marker).
1775      let pending = &mut g.pending_comments;
1776      let mut route = |t: Token| -> Option<Token> {
1777        match t.get_catcode() {
1778          Catcode::COMMENT => {
1779            match sink {
1780              CommentSink::Pending => pending.push_back(t),
1781              CommentSink::Into(ref mut out) => out.push(t),
1782            }
1783            None
1784          },
1785          Catcode::MARKER => {
1786            handle_marker(t);
1787            None
1788          },
1789          _ => Some(t),
1790        }
1791      };
1792      let mut next_token: Option<Token> = None;
1793      while let Some(t) = rt.pushback.pop() {
1794        if let Some(t) = route(t) {
1795          next_token = Some(t);
1796          break;
1797        }
1798      }
1799      rt.watch.note_len(rt.pushback.len());
1800      // Whether the token is expansion output (the pushback, `\everyeof`'s tokens included) rather than the current
1801      // Mouth's own input, for the cycle guard below.
1802      let mut expanded = next_token.is_some();
1803      if next_token.is_none() {
1804        while let Some(t) = rt.mouth.read_token() {
1805          if let Some(t) = route(t) {
1806            next_token = Some(t);
1807            break;
1808          }
1809        }
1810      }
1811      // eTeX file end (tex.web §362 + etex.ch `every_eof`): the first time a
1812      // marked mouth runs dry, its `\everyeof` tokens are read AS THE FILE'S
1813      // LAST TOKENS — pushed at this level, before the mouth closes. Token
1814      // identity preserved (l3tl's rescan quarks, xint's captures). spreadtab
1815      // 's `\ST_scan_func_arg` (spreadtab.sty:1493-1504) ends its `\scantokens`
1816      // scan on `\everyeof{\ST_nil}`; a parent-level insertion after the close
1817      // (the earlier designs) reached a nested scan in the enclosing stream.
1818      if next_token.is_none() && rt.insert_everyeof && !rt.eof_seen {
1819        rt.eof_seen = true;
1820        if let Some(RegisterValue::Tokens(eof_toks)) = internal_register_value("\\everyeof")
1821          && !eof_toks.is_empty()
1822        {
1823          rt.pushback.extend(eof_toks.unlist().into_iter().rev());
1824          while let Some(t) = rt.pushback.pop() {
1825            if let Some(t) = route(t) {
1826              next_token = Some(t);
1827              expanded = true;
1828              break;
1829            }
1830          }
1831          rt.watch.note_len(rt.pushback.len());
1832        }
1833      }
1834      if let Some(token) = next_token {
1835        // Record BEFORE the activation gate: the ring is also what the
1836        // token-limit fatal dumps, and that fatal fires precisely for
1837        // runaways the cycle guard never recognised — which includes ones
1838        // that trip a lowered `LATEXML_TOKEN_LIMIT` before the guard ever
1839        // activates. Gating the ring on activation left it empty in exactly
1840        // that case. Debug-only, so free in production.
1841        if *DEBUG_FATAL {
1842          DEBUG_RECENT_TOKENS.with(|ring| {
1843            let mut ring = ring.borrow_mut();
1844            if ring.len() >= 512 {
1845              ring.pop_front();
1846            }
1847            ring.push_back(format!("{token:?}"));
1848          });
1849        }
1850        if duty_on {
1851          // Mix the reading-context serial into the fingerprint (see the
1852          // `Gullet::ctx_serial` field doc): tokens read in different
1853          // `reading_from_mouth` contexts can then never form a matching
1854          // window, scoping cycle detection to ONE expansion context
1855          // without destroying the outer context's history. The multiplier
1856          // spreads the serial across the hash bits (splitmix64's odd
1857          // constant).
1858          //
1859          // A token read from the Mouth is input, which advances: its fingerprint also carries where it starts in
1860          // the file (line, column), so a file's repeated text is no period. Fingerprinted by meaning alone, it was a
1861          // loop once the activation floor was passed: 1009.1698's gnuplot label file, 626 lines of
1862          // `\color{black}%` read as one argument with the pushback empty, a window of 8 tokens "repeated 100+ times"
1863          // (repro expansion-primitives/cycle_guard_repeated_file_input.tex). A loop that re-reads the same text
1864          // through a new Mouth reads it at the same places every period, and is still one (a nesting one, as
1865          // `\def\x{\scantokens{\x}}`, stops first at TeX's input-level limit, `mark_everyeof_mouth`).
1866          //
1867          // The register values read since the last token ([`crate::cycle_guard::note_value`]) go in too: a counter
1868          // loop re-reads the same tokens with a new `\n` each period (`\loop … \ifnum\n<N \repeat`, ~25 tokens), and
1869          // is finite.
1870          let mut fp = token.cycle_fingerprint()
1871            ^ g.ctx_serial.wrapping_mul(0x9E37_79B9_7F4A_7C15)
1872            ^ crate::cycle_guard::take_value_salt().wrapping_mul(0x94D0_49BB_1331_11EB);
1873          if !expanded {
1874            let (line, column) = rt.mouth.last_token_start();
1875            fp ^= (((line as u64) << 32) ^ column as u64).wrapping_mul(0xBF58_476D_1CE4_E5B9);
1876          }
1877          if let Some(period) = g.cycle_guard.push(fp, rt.pushback.len()) {
1878            breach = Some(Breach::Cycle(period, token));
1879          }
1880        }
1881        if breach.is_none() {
1882          outcome = CheckedRead::Tok(token);
1883        }
1884      }
1885    }
1886  }
1887  // Borrow dropped; cold outlined fatal paths only from here on.
1888  match breach {
1889    None => Ok(outcome),
1890    Some(Breach::TokenLimit(limit)) => token_limit_fatal(limit),
1891    Some(Breach::PushbackLimit(limit)) => pushback_limit_fatal(limit),
1892    Some(Breach::Cycle(period, token)) => cycle_trip_fatal(period, &token),
1893    Some(Breach::Deadline) => fatal!(Timeout, Convert, "Conversion timed out!"),
1894    Some(Breach::ReadBudget) => read_budget_error(),
1895  }
1896}
1897
1898/// The read [`read_budget`] refuses: an error for the run to end on, no Fatal (nothing logged, nothing latched).
1899#[cold]
1900#[inline(never)]
1901fn read_budget_error() -> Result<CheckedRead> {
1902  Err(Error::from(ErrorData {
1903    target:   ErrorTarget::Timeout,
1904    category: ErrorCategory::ReadBudget,
1905    message:  "A budgeted run read all it may".to_string(),
1906  }))
1907}
1908
1909impl Gullet {
1910  /// The next value of `progress` at which a read has anything to do but pop a token: [`next_due_read`], or 0 under
1911  /// `LATEXML_DEBUG_FATAL`, whose ring records every token.
1912  fn next_full_read(&self) -> usize {
1913    if *DEBUG_FATAL {
1914      return 0;
1915    }
1916    let due = next_due_read(self.progress, self.token_limit, self.cycle_guard_activate);
1917    // (and the read past a budget, and each one after it: [`read_budget`])
1918    self.read_budget_at.map_or(due, |at| {
1919      due.min(at.saturating_add(1).max(self.progress.saturating_add(1)))
1920    })
1921  }
1922}
1923
1924/// The first count past `read` at which [`read_internal_token_full`]'s tests have something to do, by the count alone:
1925/// past the token `limit`, a multiple of the deadline's period, or in one of the cycle guard's windows, phases
1926/// 1..=`CYCLE_GUARD_DUTY_ON` of a period past its `floor`.
1927fn next_due_read(read: usize, limit: Option<usize>, floor: usize) -> usize {
1928  let deadline = (read | DEADLINE_CHECK_MASK) + 1;
1929  let limit = limit.map_or(usize::MAX, |limit| limit.saturating_add(1));
1930  let guard = match read.checked_sub(floor) {
1931    None => floor + 1,
1932    Some(past) => {
1933      let phase = past & (CYCLE_GUARD_DUTY_PERIOD - 1);
1934      if phase < CYCLE_GUARD_DUTY_ON {
1935        read + 1
1936      } else {
1937        read + (CYCLE_GUARD_DUTY_PERIOD - phase) + 1
1938      }
1939    },
1940  };
1941  deadline.min(limit).min(guard)
1942}
1943
1944const DEADLINE_CHECK_MASK: usize = (1 << 16) - 1;
1945
1946/// TeX's limit on simultaneously open input files (`\input` files and `\scantokens` pseudo-files): `max_in_open`,
1947/// texmf.cnf:868 (TL 2025; tex.web §328 `begin_file_reading` checks `in_open = max_in_open` before opening another).
1948pub const MAX_IN_OPEN: usize = 15;
1949
1950/// Token-limit breach ([`read_internal_token_checked`]). The cycle guard
1951/// already dumps its window when it trips, but a runaway that reaches THIS
1952/// limit is by definition one the cycle guard did NOT recognise — an aperiodic
1953/// grind (a counter that keeps advancing, a list that keeps growing). Those
1954/// are exactly the ones with no other clue in the log, so dump the same
1955/// recent-token ring here. Without it a TokenLimit fatal says only "infinite
1956/// loop?" and every investigation starts from zero (witness 2606.21610, a
1957/// 42 s silent grind).
1958#[cold]
1959#[inline(never)]
1960fn token_limit_fatal(limit: usize) -> Result<CheckedRead> {
1961  let msg = s!("Token limit of {} exceeded, infinite loop?", limit);
1962  if *DEBUG_FATAL {
1963    eprintln!("[debug-fatal] token limit tripped: {msg}");
1964    DEBUG_RECENT_TOKENS.with(|ring| {
1965      let ring = ring.borrow();
1966      let recent: Vec<&str> = ring.iter().map(String::as_str).collect();
1967      eprintln!(
1968        "[debug-fatal] last {} read tokens: {}",
1969        ring.len(),
1970        recent.join(" ")
1971      );
1972    });
1973  }
1974  Fatal!(Timeout, TokenLimit, msg);
1975}
1976
1977/// Pushback-limit breach ([`read_internal_token_checked`]). Diagnostic: the
1978/// looping token window is right here in the pushback — dump its head so the
1979/// cycle is identifiable from logs.
1980#[cold]
1981#[inline(never)]
1982fn pushback_limit_fatal(limit: usize) -> Result<CheckedRead> {
1983  if *DEBUG_FATAL && let Some(rt) = gullet!().runtime.as_ref() {
1984    let head: Vec<String> = rt
1985      .pushback
1986      .iter()
1987      .take(48)
1988      .map(|t| format!("{t:?}"))
1989      .collect();
1990    eprintln!("[debug-fatal] pushback head: {}", head.join(" "));
1991  }
1992  let msg = s!("Pushback limit of {} exceeded, infinite loop?", limit);
1993  Fatal!(Timeout, PushbackLimit, msg);
1994}
1995
1996/// Cycle-guard trip ([`read_internal_token_checked`]): a small-period infinite
1997/// expansion loop, cut with a clean Fatal in O(window) extra tokens instead of
1998/// grinding to the token limit (and the gigabytes of RSS that implies).
1999#[cold]
2000#[inline(never)]
2001fn cycle_trip_fatal(period: usize, nextt: &Token) -> Result<CheckedRead> {
2002  let msg = s!(
2003    "Infinite expansion loop: a window of {} token(s) repeated {}+ times",
2004    period,
2005    crate::cycle_guard::REPEAT
2006  );
2007  if *DEBUG_FATAL {
2008    eprintln!("[debug-fatal] gullet cycle guard tripping on token {nextt:?}: {msg}");
2009    {
2010      let g = gullet_root().borrow();
2011      eprintln!(
2012        "[debug-fatal] pushback backlog samples (oldest first): {:?}; pushback now {}",
2013        g.cycle_guard.backlog_trace(),
2014        g.runtime.as_ref().map_or(0, |rt| rt.pushback.len())
2015      );
2016    }
2017    DEBUG_RECENT_TOKENS.with(|ring| {
2018      let ring = ring.borrow();
2019      let recent: Vec<&str> = ring.iter().map(String::as_str).collect();
2020      eprintln!("[debug-fatal] last 512 read tokens: {}", recent.join(" "));
2021    });
2022  }
2023  Fatal!(Timeout, Recursion, msg);
2024}
2025
2026/// Read a token as tex.web §367 `\noexpand` does: `get_token` under
2027/// `scanner_status := normal`, so an input level that ends here closes
2028/// without a runaway (§362 `end_file_reading`, §336 passes) and the read goes
2029/// on in the enclosing level. Crosses exactly what `read_x_token` drains:
2030/// autoclose mouths with a parent (`\input` files, `\scantokens`
2031/// pseudo-files, line remainders), never a `reading_from_mouth` context. A
2032/// definition, text, preamble or macro argument that runs off a file's end is
2033/// still a §338 runaway: [`read_token`] stops there, and the scan recovers by
2034/// its [`ScannerStatus`] ([`recover_at_file_end`]).
2035/// This is what `\everyeof{\noexpand}` relies on
2036/// (catchfile.sty:251-261, morewrites.sty:465, l3build regression-test.tex:101).
2037/// Guards: `noexpand_input_ends::*`.
2038pub fn read_token_across_input_ends() -> Result<Option<Token>> {
2039  loop {
2040    if let Some(token) = read_token()? {
2041      return Ok(Some(token));
2042    }
2043    let crossable = {
2044      let gullet = gullet!();
2045      gullet.runtime.as_ref().is_some_and(|r| r.autoclose) && !gullet.mouthstack.is_empty()
2046    };
2047    if !crossable {
2048      return Ok(None);
2049    }
2050    close_mouth(false)?;
2051  }
2052}
2053
2054/// Read a token as a primitive reads one: tex.web §365 `get_token` under the
2055/// current [`ScannerStatus`] (`\let`, `\futurelet`, `\afterassignment`,
2056/// `\aftergroup`, `\expandafter`, a `Token` parameter). An input level
2057/// that ends here closes (§362 `end_file_reading`) and §336
2058/// `check_outer_validity` looks at the status:
2059/// - `normal`: no runaway; the read goes on in the enclosing input, as
2060///   [`read_token_across_input_ends`] reads, so a primitive that is the last
2061///   token of an `\input` file takes its token from the input that follows;
2062/// - `defining`, `absorbing`, `aligning`: the scan in progress ran off the file,
2063///   and the primitive's read meets it: the runaway is reported there and
2064///   TeX's recovery tokens are read ([`recover_at_file_end`]), so an
2065///   `\edef\x{\expandafter` at a file's end reads the inserted `}` and
2066///   `\x` is empty, as in pdflatex;
2067/// - `matching`: TeX reads a macro's arguments without expanding, so it gives
2068///   no primitive's read this status, but Rust does: an expandable primitive
2069///   with typed parameters (`\csname CSName`, `\number Number`, `\readline …
2070///   Token`) reads them at `matching`, set by `Expandable::read_call_arguments`.
2071///   The read stops at the file's end (a residual: `\csname a\expandafter` as
2072///   a file's last tokens does not cross), and so does a macro's `Token`
2073///   argument (the macro gets `\relax`, the `Token` parameter's end value).
2074///
2075/// `\ifx` and `\ifdefined` read at `normal` whatever the status (§507), with
2076/// [`read_token_across_input_ends`]. The status is consulted only once the
2077/// current input has run out.
2078///
2079/// Guards: `token_kernel_gaps::*`.
2080pub fn read_primitive_token() -> Result<Option<Token>> {
2081  if let Some(token) = read_token()? {
2082    return Ok(Some(token));
2083  }
2084  match scanner_status() {
2085    ScannerStatus::Normal => read_token_across_input_ends(),
2086    ScannerStatus::Matching => Ok(None),
2087    _ => loop {
2088      if let Some(token) = read_token()? {
2089        return Ok(Some(token));
2090      }
2091      if recover_at_file_end()? != FileEndRecovery::Inserted {
2092        return Ok(None);
2093      }
2094    },
2095  }
2096}
2097
2098/// The control sequence a definition names: tex.web §1215 `get_r_token`,
2099/// `repeat get_token until cur_tok<>space_token` (`\def`, `\let`, `\futurelet`,
2100/// `\chardef`, `\countdef` …). Each read is [`read_primitive_token`], so a
2101/// bare `\let` or `\def` as a file's last token takes its name from the input
2102/// after the file, skipping the spaces there.
2103///
2104/// A name that is neither a control sequence nor an active character
2105/// (`cur_cs=0`) is "Missing control sequence inserted": the token is read
2106/// again (`back_input`) and the frozen `\inaccessible` (§222
2107/// `frozen_protection`) is named instead, so `\gdef{}X{Y}` defines it and
2108/// typesets `X{Y}`. yquant-doc.tex:3832's `\gdef{…` (an `\edef`-expanded
2109/// `\pgfsyssoftpath@flushbuffers`) had installed a macro on the Begin catcode,
2110/// and every later `{` read a delimited argument: 1001 errors and a Fatal.
2111/// Perl reads the name as a `Token` (TeX_Macro.pool.ltxml:174-177) and shares
2112/// that. A frozen control sequence as the name (`cur_cs>frozen_control_sequence`,
2113/// dropped with the same error) is not modelled: Rust has none.
2114///
2115/// A `\noexpand`ed name is the control sequence it marks: §358 `get_next`
2116/// sets `cur_cs` to the shadowed token, so `\expandafter\def\noexpand\foo`
2117/// defines `\foo`. Rust's marker is a `\special_relax` family token, which
2118/// had defined the family's shared `\relax` meaning instead.
2119///
2120/// Guards: `rtoken_patchcmd::def_of_a_non_cs_defines_inaccessible`,
2121/// `rtoken_patchcmd::let_family_of_a_non_cs_reads_the_token_again`,
2122/// `rtoken_patchcmd::noexpand_marked_name_is_its_control_sequence`.
2123pub fn read_redefinable_token() -> Result<Option<Token>> {
2124  loop {
2125    match read_primitive_token()? {
2126      Some(token) if token.get_catcode() == Catcode::SPACE => {},
2127      Some(token) if token.is_noexpand_family() => {
2128        return Ok(Some(token.noexpand_shadowed().unwrap_or(token)));
2129      },
2130      Some(token) if !token.get_catcode().is_active_or_cs() => {
2131        Error!(
2132          "expected",
2133          "<cs>",
2134          "Missing control sequence inserted",
2135          s!("{} cannot be a definition's name", token.stringify()),
2136          "Please don't say `\\def cs{...}', say `\\def\\cs{...}'.\n\tI've inserted an \
2137           inaccessible control sequence so that your definition will be completed without \
2138           mixing me up too badly."
2139        );
2140        unread_one(token);
2141        // `\inaccessible ` is how TeX prints it (§262 `print_cs`); the
2142        // trailing space keeps it apart from a document's `\inaccessible`
2143        // (not from `\csname inaccessible\space\endcsname`, nor from a
2144        // `\DeclareRobustCommand\inaccessible`'s inner macro).
2145        return Ok(Some(T_CS!("\\inaccessible ")));
2146      },
2147      other => return Ok(other),
2148    }
2149  }
2150}
2151
2152/// Read a token that the calling macro/primitive REQUIRES, holding the
2153/// "argument expected but input ended" diagnostic in one place.
2154///
2155/// `read_token()` returning `None` (input exhausted) is a normal, expected
2156/// control-flow signal in most contexts (end of file/group/optional-arg scan) —
2157/// so the primitive deliberately keeps the `Option`. But for a caller that
2158/// genuinely requires a token here, `None` is TeX's *"File ended while scanning
2159/// use of \cs"* error state (real `pdftex` raises an `! Emergency stop`). This
2160/// helper emits that parity `Error!` once, centrally, instead of every call site
2161/// `.unwrap()`-panicking on the `None`. It STILL returns the `Option` (it does
2162/// NOT fabricate a token), so the type system keeps each caller honest about how
2163/// it degrades — close its group, substitute a default, etc.
2164pub fn read_token_required(what: &str) -> Result<Option<Token>> {
2165  let tok = read_token()?;
2166  if tok.is_none() {
2167    Error!(
2168      "expected",
2169      what,
2170      format!("input ended while scanning use of {what}")
2171    );
2172  }
2173  Ok(tok)
2174}
2175
2176/// Gullet.pm `readToken` (L300-324); its loop is in `read_token_after`.
2177pub fn read_token() -> Result<Option<Token>> {
2178  let first = read_internal_token_checked(CommentSink::Pending)?;
2179  // The usual token: no alignment is being read, so it ends no column, and it is no `\dont_expand`.
2180  if let CheckedRead::Tok(token) = first
2181    && !has_reading_alignment()
2182    && !(token.code == Catcode::CS && token.text == pin!("\\dont_expand"))
2183  {
2184    match token.get_catcode() {
2185      Catcode::BEGIN => increment_align_group_count(),
2186      Catcode::END => decrement_align_group_count(),
2187      _ => {},
2188    }
2189    return Ok(Some(token));
2190  }
2191  read_token_after(first)
2192}
2193
2194/// [`read_token`] given what its first read found, in full: the alignment and `\dont_expand` cases.
2195#[inline(never)]
2196fn read_token_after(first: CheckedRead) -> Result<Option<Token>> {
2197  let mut next_token: Option<Token>;
2198  let mut read = Some(first);
2199  loop {
2200    // Combined checkpoint + raw read + cycle fingerprint, one borrow.
2201    let this_read = match read.take() {
2202      Some(this_read) => this_read,
2203      None => read_internal_token_checked(CommentSink::Pending)?,
2204    };
2205    next_token = match this_read {
2206      CheckedRead::NoRuntime => return Ok(None),
2207      // A marked eTeX pseudo-file (`\scantokens`) end is NOT crossed here:
2208      // its `\everyeof` payload was already read at the file's own level
2209      // (`read_internal_token_checked`, `eof_seen`), so this is the true end
2210      // — a delimited scan whose marker misses must not escape into the
2211      // enclosing LIVE stream (inside an alignment cell it swallowed the
2212      // column-after program as data and poisoned l3tl rescan results: l3doc
2213      // `\tl_replace_all` 5-token loop, witnesses spath3/litetable-zh/
2214      // zref-check; settled dead-end, tried 3× 2026-09-01). Plain execution
2215      // crosses via read_x_token's autoclose drain.
2216      CheckedRead::Exhausted => None,
2217      CheckedRead::Tok(t) => Some(t),
2218    };
2219    // ProgressStep() if ($$self{progress}++ % $TOKEN_PROGRESS_QUANTUM) == 0;
2220
2221    // Strict-Perl translation of Gullet.pm `readToken`:
2222    //   alignment column-end check → \dont_expand check → break
2223    //   ALIGN_STATE tracking happens AFTER the loop, on the FINAL
2224    //   token to be returned (Perl L320-324).
2225    if let Some(ref nextt) = next_token {
2226      if (align_group_count() == 0)
2227        && has_reading_alignment()
2228        && let Some((_atoken, atype, ahidden)) = is_column_end(nextt)
2229      {
2230        let reading_alignment = get_reading_alignment().unwrap();
2231        if let DigestedData::Alignment(data) = reading_alignment.data() {
2232          // The token as read goes back after the v-part, not its canonical `\cr`/`&` (Perl Gullet.pm:310 passes
2233          // `$token`): TeX drops the token and keeps its meaning (tex.web §789), so a `\let\crnorm=\cr` is no name a
2234          // v-part's keyword scan can expand — with `\cr` itself redefined (`\def\cr{&\crnorm}`, Cowan's tables.tex)
2235          // a `\vrule` before it read the macro's `&` (hep-ph9612244, hep-ph9711334). Guard
2236          // `perfect_kernel_batch68z::a_let_cr_ends_the_row_as_itself`.
2237          handle_template(data.borrow_mut(), *nextt, atype, ahidden)?;
2238        } else {
2239          return Err("reading_alignment should always contain DigestedData::Alignment".into());
2240        }
2241        continue; // Perl: handleTemplate then continue while(1) loop
2242      }
2243      if nextt.code == Catcode::CS && nextt.text == pin!("\\dont_expand") {
2244        // `\noexpand <tok>`: collapse to the per-token `\special_relax` family,
2245        // encoding <tok>'s identity in the name (faithful to TeX's
2246        // `no_expand_flag`, which keeps `cur_cs`). End-of-input ⇒ bare
2247        // `\special_relax` (nothing to shadow).
2248        next_token = Some(match read_token()? {
2249          Some(tok) => crate::token::noexpand_family(&tok),
2250          None => T_CS!("\\special_relax"),
2251        });
2252      }
2253      break;
2254    } else {
2255      break;
2256    }
2257  }
2258  // Perl Gullet.pm L320-324: ALIGN_STATE tracking happens AFTER the loop,
2259  // applied only to the FINAL returned token. Previously this was inside
2260  // the loop BEFORE the alignment check, which prevented column-end
2261  // template handling on `{` tokens (count became 1 before the check).
2262  if let Some(ref nextt) = next_token {
2263    match nextt.get_catcode() {
2264      Catcode::BEGIN => increment_align_group_count(),
2265      Catcode::END => decrement_align_group_count(),
2266      _ => {},
2267    }
2268  }
2269  Ok(next_token)
2270}
2271
2272/// Engage the expansion-stream cycle guard only after this many tokens — above
2273/// the ordinary range (measured known-good papers 0.6–7.5M under the 2026-06-10
2274/// all-three-loop accounting; 20M keeps them fingerprint-free with ~2.7×
2275/// headroom), so only a runaway (heading for the 1G `token_limit` / RSS cap)
2276/// records fingerprints, cut off in O(window) tokens (false positives guarded by
2277/// the period-`REPEAT` requirement, not this bound). DEFAULT floor; graphics-heavy
2278/// packages legitimately reach ~100–155M (math0402448 xy-pic, 1805.03265 tikz-cd)
2279/// and raise it to [`CYCLE_GUARD_ACTIVATE_GRAPHICS`] at load via
2280/// [`raise_cycle_guard_activate`], the 1G `token_limit` staying the backstop.
2281const CYCLE_GUARD_ACTIVATE: usize = 20_000_000;
2282
2283/// Cycle-guard activation floor for graphics-heavy bindings (pgf/tikz/xy).
2284/// These packages legitimately expand 100M+ tokens; this floor sits above the
2285/// heaviest measured healthy graphics doc (1805.03265 tikz-cd ~155M) so they
2286/// stay out of the per-token fingerprint regime, while remaining far below the
2287/// 1G `token_limit` backstop. Raised — never lowered — per [`raise_cycle_guard_activate`].
2288pub const CYCLE_GUARD_ACTIVATE_GRAPHICS: usize = 150_000_000;
2289
2290/// Raise the cycle-guard activation floor for the current (thread-local) gullet,
2291/// only ever upward. Called from graphics package bindings (pgf/tikz/xy) whose
2292/// healthy expansion runs to 100M+ tokens — see [`CYCLE_GUARD_ACTIVATE_GRAPHICS`].
2293/// Idempotent and order-independent: loading several graphics packages just
2294/// re-asserts the same floor. The per-conversion reset (`initialize_gullet`)
2295/// restores the default so the raise does not leak across documents.
2296pub fn raise_cycle_guard_activate(floor: usize) {
2297  let mut g = gullet_mut!();
2298  if floor > g.cycle_guard_activate {
2299    g.cycle_guard_activate = floor;
2300    g.full_read_at = 0;
2301    // The duty-window phase is derived from `progress - cycle_guard_activate`
2302    // (see `read_internal_token_checked`); raising the floor while the guard
2303    // is already active shifts that phase, which could splice a previous
2304    // ON-window's ring history against a later window with no reset at the
2305    // seam. The history only ever describes the pre-raise regime — drop it.
2306    g.cycle_guard.reset();
2307  }
2308}
2309
2310// Cluster F: bound gullet expansion-recursion depth (= `read_x_token`
2311// re-entrancy) so a runaway — an xint number-arg chain, a self-referential
2312// `\csname`/`\number`/`\romannumeral` — raises a fast `Fatal:Timeout:Recursion`
2313// rather than grinding to the watchdog / RSS fuse. Legit docs nest ≲20; the cap
2314// is 12_000. Env override `LATEXML_EXPAND_DEPTH_LIMIT` (0 disables).
2315thread_local! {
2316  static EXPAND_DEPTH: Cell<usize> = const { Cell::new(0) };
2317}
2318thread_local! {
2319  static EXPAND_DEPTH_LIMIT: Cell<usize> = const { Cell::new(12_000) };
2320}
2321
2322/// Reset the counter + re-read the env limit each conversion (the thread-local
2323/// engine is reused; a caught unwind could otherwise leave the counter high).
2324fn reset_expand_depth() {
2325  EXPAND_DEPTH.set(0);
2326  EXPAND_DEPTH_LIMIT.set(
2327    std::env::var("LATEXML_EXPAND_DEPTH_LIMIT")
2328      .ok()
2329      .and_then(|v| v.trim().parse().ok())
2330      .unwrap_or(12_000),
2331  );
2332}
2333
2334/// RAII depth counter for `read_x_token`: `enter` increments (Fatals past the
2335/// limit), drop decrements — so every return path stays balanced.
2336struct ExpandDepthGuard;
2337impl ExpandDepthGuard {
2338  #[inline]
2339  fn enter() -> Result<ExpandDepthGuard> {
2340    let d = EXPAND_DEPTH.get() + 1;
2341    EXPAND_DEPTH.set(d);
2342    let limit = EXPAND_DEPTH_LIMIT.get();
2343    if limit != 0 && d > limit {
2344      return Self::too_deep(d, limit);
2345    }
2346    Ok(ExpandDepthGuard)
2347  }
2348
2349  /// The Fatal of [`Self::enter`], out of line: its message formatting kept `enter` itself from being
2350  /// inlined into every `read_x_token` (a 152-byte frame per read).
2351  #[cold]
2352  #[inline(never)]
2353  fn too_deep(d: usize, limit: usize) -> Result<ExpandDepthGuard> {
2354    EXPAND_DEPTH.set(d - 1); // Drop won't run — decrement here.
2355    Fatal!(
2356      Timeout,
2357      Recursion,
2358      format!("Excessive expansion recursion (depth {d} > {limit}); infinite macro loop?")
2359    );
2360  }
2361}
2362impl Drop for ExpandDepthGuard {
2363  #[inline]
2364  fn drop(&mut self) { EXPAND_DEPTH.set(EXPAND_DEPTH.get().saturating_sub(1)); }
2365}
2366
2367/// Real LaTeX defines every optional-argument `\newcommand` through
2368/// `\@protected@testopt`: under a non-typesetting `\protect` regime
2369/// (`\protected@edef`/`\protected@write`) the command emits
2370/// `\protect\cs` UNEXPANDED. Our binding-level `\newcommand` builds a
2371/// bare `Optional` parameter with no such indirection, so a recursive
2372/// optional-arg macro (titlecaps' `\textnc` → `\titlecap[s]{…}` chain)
2373/// expanded forever under `\protected@edef` — 2 GB pushback OOM
2374/// (perfect-kernel sweep 16; real LaTeX and Perl-with-real-latex.ltx are
2375/// clean). Treat a leading-Optional definition as protected exactly when
2376/// `\protect` is not `\@typeset@protect` — literally
2377/// `\@protected@testopt`'s test. Cheap: the parameter check is a slice
2378/// peek; the state lookups run only for leading-Optional definitions
2379/// under partial expansion. A first parameter flagged
2380/// [`Parameter::testopt`](crate::parameter::Parameter::testopt) is a protected command
2381/// too: xargs's `\newcommandx` with any optional argument
2382/// (`\@protected@testopt@xargs`, xargs.sty:20-25, 205-212), whose first
2383/// argument may be a plain one.
2384fn optional_arg_protected(defn: &std::rc::Rc<dyn Definition>) -> bool {
2385  match defn.get_parameters() {
2386    Some(params) => match params.get_parameters().first() {
2387      Some(p) => {
2388        (p.name == crate::pin!("Optional") || p.testopt)
2389          && !super::definition::expandable::protect_is_typeset()
2390      },
2391      None => false,
2392    },
2393    None => false,
2394  }
2395}
2396
2397/// TeX's number scan stops at the unexpandable head of a peeking macro.
2398/// latex.ltx's `\@ifnextchar` (1756-1760), and with it `\@ifstar`,
2399/// `\@testopt` and every `\newcommand` optional argument, opens with `\let`
2400/// and peeks by `\futurelet`; the digits of a number scan end at the first
2401/// unexpandable token (tex.web §445), so the peek happens only where the
2402/// macro is executed. Our peeking macros are closures that peek as they
2403/// expand: in a scan they stay unexpanded, the scan ends at them, and the
2404/// next reader outside the scan (the main loop, an alignment's cell-head
2405/// peek) expands them. Expanding them in the scan read the chosen branch
2406/// into the number (`\count@=1\@ifstar{7}{5}*` assigned 17), or its
2407/// conditionals into a false branch's skip: egpeirce.sty:184-189 `\ifodd
2408/// \the\value{cutdepth}%` + `\psset` → `\XKV@ifstar` exposed
2409/// `\let\ifXKV@st\iffalse` and the skip ran off the end of the document
2410/// (egpeirce-doc, 51 errors; Perl shares the bug). Guards:
2411/// `cluster_package_guards::ifnextchar_scans`.
2412#[inline]
2413pub fn scan_stops_at_futurelet_peek(defn: &std::rc::Rc<dyn Definition>) -> bool {
2414  in_number_scan() && defn.peeks_by_futurelet()
2415}
2416
2417/// Whether `defn` expands when met by a reader that `fully_expand`s or not:
2418/// the gate `read_x_token` applies (protected macros, and binding-defined
2419/// optional-argument macros outside typesetting, wait unless fully
2420/// expanding; see [`optional_arg_protected`]; a number scan ends at a
2421/// peeking macro, [`scan_stops_at_futurelet_peek`]).
2422#[inline]
2423fn expands_now(defn: &std::rc::Rc<dyn Definition>, fully_expand: bool) -> bool {
2424  defn.is_expandable()
2425    && (fully_expand || (!defn.is_protected() && !optional_arg_protected(defn)))
2426    && !scan_stops_at_futurelet_peek(defn)
2427}
2428
2429/// A place in the input ([`input_mark`]): how many mouths enclose it, the current mouth's read position, its
2430/// pushback's length then, the mark's serial on the mouth's watch (`PushbackWatch`), and the pushback's last
2431/// `MARK_HELD` tokens, the next to read last. `Copy`: a mark holds nothing on the heap, so the marks a ledger keeps (an
2432/// author block's each) cost what their number does, whatever the pushback holds (revRC1: a copy of the pushback per
2433/// mark made 3,000 macro-held authors take 3.7 GB).
2434#[derive(Debug, Clone, Copy, PartialEq)]
2435pub struct InputMark {
2436  depth:  usize,
2437  mouth:  (usize, usize, usize, usize),
2438  len:    usize,
2439  serial: u64,
2440  held:   [Option<Token>; MARK_HELD],
2441}
2442
2443/// How many of the pushback's tokens an [`InputMark`] keeps: read below its length and put back, as many as these
2444/// leave the input unread (a peek, a `\futurelet`).
2445const MARK_HELD: usize = 4;
2446
2447/// Whether `a` and `b` are the very same token: their text, catcode and provenance, field by field (`PartialEq` on
2448/// `Token` compares a meaning, not a token: any two spaces are equal, the provenance is not compared).
2449fn same_token(a: &Token, b: &Token) -> bool {
2450  #[cfg(feature = "token-locators")]
2451  if a.loc != b.loc {
2452    return false;
2453  }
2454  a.text == b.text && a.code == b.code && a.prov == b.prov
2455}
2456
2457/// Is the next token read straight from the document's own text — nothing pushed back, the mouth a content file's
2458/// ([`Mouth::is_document_text`])? A macro called now reads its arguments from what the document wrote
2459/// (`state::note_document_call`).
2460pub fn reading_document_text() -> bool {
2461  gullet!()
2462    .runtime
2463    .as_ref()
2464    .is_some_and(|rt| rt.pushback.is_empty() && rt.mouth.is_document_text())
2465}
2466
2467/// Mark the input as it stands: everything still to be read now ([`input_unread_since`]). What is pushed back after
2468/// the mark (a macro's expansion, unread on top of the pushback) is read before anything the mark holds.
2469pub fn input_mark() -> InputMark {
2470  let mut gullet = gullet_mut!();
2471  let depth = gullet.mouthstack.len();
2472  gullet.mark_serial += 1;
2473  let serial = gullet.mark_serial;
2474  let mut mark = InputMark {
2475    depth,
2476    mouth: (0, 0, 0, 0),
2477    len: 0,
2478    serial,
2479    held: [None; MARK_HELD],
2480  };
2481  if let Some(rt) = gullet.runtime.as_mut() {
2482    mark.len = rt.pushback.len();
2483    mark.mouth = rt.mouth.read_position();
2484    rt.watch.mark(serial, mark.len);
2485    let top = &rt.pushback[mark.len.saturating_sub(MARK_HELD)..];
2486    for (slot, token) in mark.held.iter_mut().zip(top) {
2487      *slot = Some(*token);
2488    }
2489  }
2490  mark
2491}
2492
2493/// Whether none of the input `mark` held has been read since it was taken ([`input_mark`]): its mouth is still open,
2494/// has read no further, and its pushback still holds every token it held then (only what was pushed after the mark
2495/// was read, or what a mouth opened since holds). Read-only, for an observer telling apart what a call's expansion
2496/// did from what the input after the call did (the frontmatter observer's ledger, the title-page check's document
2497/// calls). The mouth's watch tells how short its pushback has been since the mark (`PushbackWatch`): no shorter
2498/// than the mark's length, nothing it held was read; shorter by at most `MARK_HELD` tokens, those read were put
2499/// back if the slots hold the very tokens they held (`same_token`: a peek leaves the input unread); shorter still,
2500/// it was read. Tokens read below the mark and others pushed in their place read as read, though the token now at
2501/// the mark's last slot equals the one it held — IEEEtran's `\IEEEauthorblockN{…}⏎\IEEEauthorblockA{…}`, whose
2502/// line-end space was read with `\IEEEauthorblockA` and its argument and whose expansion, longer, put another space
2503/// there: its affiliation calls read as the author block's own and were lost by the frontmatter emitter (2401.11731,
2504/// 1801.03314). No token is copied but the held ones: a mark costs at most one run of the watch, a test a binary
2505/// search of its runs.
2506pub fn input_unread_since(mark: &InputMark) -> bool {
2507  let gullet = gullet!();
2508  let depth = gullet.mouthstack.len();
2509  if depth < mark.depth {
2510    return false;
2511  }
2512  let runtime = if depth == mark.depth {
2513    gullet.runtime.as_ref()
2514  } else {
2515    gullet.mouthstack.get(depth - mark.depth - 1)
2516  };
2517  let Some(rt) = runtime else {
2518    return mark.len == 0 && mark.mouth == (0, 0, 0, 0);
2519  };
2520  if rt.mouth.read_position() != mark.mouth || rt.pushback.len() < mark.len {
2521    return false;
2522  }
2523  let Some(shortest) = rt.watch.shortest_since(mark.serial) else {
2524    return false;
2525  };
2526  let held_from = mark.len.saturating_sub(MARK_HELD);
2527  shortest >= mark.len
2528    || (shortest >= held_from
2529      && rt.pushback[shortest..mark.len]
2530        .iter()
2531        .zip(&mark.held[shortest - held_from..])
2532        .all(|(now, then)| then.is_some_and(|then| same_token(now, &then))))
2533}
2534
2535/// What the invocation of a token with field provenance `prov` ([`Token::prov`]) consumed of its field's stored
2536/// value, now that it read what it reads: its own position up to the next token of that value still to be read, if
2537/// the pushback holds one (a primitive's or a macro's arguments: `\hspace{1em}`, `\\[2pt]`, `$x$`), else its own
2538/// position alone. The pushback only: a field's stored tokens are read from it (an expansion, a digested argument),
2539/// never from a mouth, so nothing is read or tokenized. OXIDIZED_DESIGN #715.
2540pub fn field_cover_of(prov: u16) -> crate::token::FieldCover {
2541  use crate::token::{field_prov_field, field_prov_pos};
2542  let (field, pos) = (field_prov_field(prov), field_prov_pos(prov));
2543  let next = {
2544    let gullet = gullet!();
2545    gullet
2546      .runtime
2547      .as_ref()
2548      .and_then(|rt| rt.pushback.last().map(|t| t.prov))
2549      .unwrap_or(0)
2550  };
2551  let end = if next != 0 && field_prov_field(next) == field && field_prov_pos(next) > pos {
2552    field_prov_pos(next)
2553  } else {
2554    pos + 1
2555  };
2556  crate::token::FieldCover { field, start: pos, end }
2557}
2558
2559/// The expansion of a field token, its tokens about to go on the input: what it read is pending for the next box
2560/// ([`field_cover_of`]), and a rehearsal's notes hear of it (`token::FieldNotesHook`). Out of line: no token of a paper's
2561/// body is a field's.
2562#[cold]
2563#[inline(never)]
2564fn note_field_expansion(token: &Token, expansion: &Tokens) {
2565  let cover = field_cover_of(token.prov);
2566  crate::token::field_cover_set_pending(cover);
2567  if let Some(notes) = crate::token::field_notes_hook() {
2568    notes(
2569      token,
2570      cover,
2571      crate::token::FieldInvocation::Expanded(expansion),
2572    );
2573  }
2574}
2575
2576/// A look at the input's pushback as it stands, the next token to read last; nothing is read, so nothing is tokenized
2577/// or counted. For a native reader of what a macro's own expansion put there ([`crate::definition::expandable::NativeCall`]).
2578pub fn with_pushback<R>(look: impl FnOnce(&[Token]) -> R) -> Option<R> {
2579  gullet!().runtime.as_ref().map(|rt| look(&rt.pushback))
2580}
2581
2582/// Consume the pushback down to its first `len` tokens, as a native reader's answer does ([`with_pushback`]); braces
2583/// among them must balance, since the brace ledger counts none of them, read or not.
2584pub fn consume_pushback_to(len: usize) {
2585  if let Some(ref mut runtime) = gullet_mut!().runtime {
2586    runtime.pushback.truncate(len);
2587    runtime.watch.note_len(runtime.pushback.len());
2588  }
2589}
2590
2591/// How many more levels of expansion recursion the guard of `read_x_token` allows, `usize::MAX` if it is off.
2592pub fn expand_depth_left() -> usize {
2593  match EXPAND_DEPTH_LIMIT.get() {
2594    0 => usize::MAX,
2595    limit => limit.saturating_sub(EXPAND_DEPTH.get()),
2596  }
2597}
2598
2599/// Whether the input's pushback is empty: no token of a field's stored value is left to read ([`field_cover_of`]).
2600pub fn pushback_is_empty() -> bool {
2601  gullet!()
2602    .runtime
2603    .as_ref()
2604    .is_none_or(|rt| rt.pushback.is_empty())
2605}
2606
2607/// How many tokens the input's pushback holds ([`with_pushback`]): a macro's expansion is being read while it holds more
2608/// than it did before the expansion (a rehearsal's notes, `token::FieldNotesHook`).
2609pub fn pushback_len() -> usize { gullet!().runtime.as_ref().map_or(0, |rt| rt.pushback.len()) }
2610
2611/// Expand `token` (defined as `defn`) ONE level and push the expansion back
2612/// onto the input, as `read_x_token` does for each expandable token it meets.
2613#[inline]
2614fn invoke_expansion(token: Token, defn: &std::rc::Rc<dyn Definition>) -> Result<()> {
2615  // (Perl's `local $LaTeXML::CURRENT_TOKEN`, Gullet.pm:240: gone however the expansion ends, an `Err` too)
2616  let _token_guard = local_current_token_guard(token);
2617  // Grow the native stack ahead of deep expansion recursion (xint
2618  // `\XINT_…` number-arg chains nest tens of thousands deep) so
2619  // finite-deep recursion completes instead of overflowing the conversion
2620  // thread's 256 MB stack → SIGABRT (Perl degrades via `$MAXSTACK`). This
2621  // only grows the stack; the depth CAP is `ExpandDepthGuard` at the top
2622  // of `read_x_token` / `expand_once_partial`. Same idiom as the recursive walks in `document.rs`
2623  // / the math parser; params in `crate::stack_guard`.
2624  // The expansion goes straight onto the input (`Definition::invoke_onto_input`, tex.web §390) unless it is
2625  // inspected on the way: token-locators fill its origins, `TRACE_GROUP_END` counts its groups.
2626  // A token of a frontmatter field's stored value passes its provenance to its expansion (`Token::prov`).
2627  if cfg!(not(feature = "token-locators")) && !*TRACE_GROUP_END && token.prov == 0 {
2628    crate::stack_guard::maybe_grow(|| defn.invoke_onto_input(false))?;
2629    return Ok(());
2630  }
2631  let mut invoked = crate::stack_guard::maybe_grow(|| match defn.native_expansion()? {
2632    Some(expansion) => Ok(expansion),
2633    None => defn.invoke(false),
2634  })?;
2635  if token.prov != 0 {
2636    // the macro's position and its arguments are covered by the boxes its expansion digests to (or by the next ones,
2637    // when it expands to nothing): a field's print is whole with them (OXIDIZED_DESIGN #715)
2638    note_field_expansion(&token, &invoked);
2639    crate::token::inherit_field_prov(token.prov, &mut invoked);
2640  }
2641  // token-locators: fill-only origin inheritance. A macro that
2642  // expands into synthesized tokens with no origin — e.g.
2643  // `\today → ExplodeText!(Today!())` yielding "May 25, 2026" —
2644  // would leave its output unlocatable. Attribute such tokens to
2645  // the invocation site so the rendered text is source-mapped.
2646  // The inherited handle is flagged `inherited` (one push per
2647  // expansion, shared by every result token), so `child_span`'s
2648  // genuine-origin-first scan never lets a macro's structural body
2649  // literals widen its arguments' content-exact span. We also never
2650  // overwrite a token that already carries an origin. See
2651  // SOURCE_PROVENANCE.md §3.1.3.
2652  #[cfg(feature = "token-locators")]
2653  {
2654    let inv_loc = token.loc;
2655    if inv_loc != 0 {
2656      let mut inherited = 0u32;
2657      for t in invoked.unlist_mut() {
2658        if t.loc == 0 {
2659          if inherited == 0 {
2660            inherited = crate::token::push_inherited_origin(inv_loc);
2661          }
2662          t.loc = inherited;
2663        }
2664      }
2665    }
2666  }
2667  if *TRACE_GROUP_END {
2668    // Print per-event {macro, delta} so post-processing can sum
2669    // by-macro to find which expandable CS contributes net +/- 1
2670    // imbalance across the run. Format: TRACE_GE delta CS
2671    let (mut begs, mut ends) = (0, 0);
2672    for t in invoked.unlist_ref() {
2673      if *t == T_CS!("\\group_begin:") || *t == T_CS!("\\begingroup") {
2674        begs += 1;
2675      } else if *t == T_CS!("\\group_end:") || *t == T_CS!("\\endgroup") {
2676        ends += 1;
2677      }
2678    }
2679    if begs > 0 || ends > 0 {
2680      eprintln!(
2681        "TRACE_GE delta={} begs={} ends={} cs={}",
2682        begs - ends,
2683        begs,
2684        ends,
2685        token
2686      );
2687    }
2688  }
2689  unread_expansion(invoked);
2690  Ok(())
2691}
2692
2693/// Expand `token`, just read, ONE level if `read_x_token(Some(false), ..)`
2694/// would expand it, pushing the expansion back onto the input, and report
2695/// whether it did. A reader that must look at every token an expansion yields
2696/// before expanding it further (the case changer's l3text checks) steps with
2697/// this; a token it leaves alone is still the caller's to handle (unread it
2698/// for `read_x_token` to return, stub or resolve).
2699pub fn expand_once_partial(token: Token) -> Result<bool> {
2700  let _depth_guard = ExpandDepthGuard::enter()?;
2701  let defn = with_meaning(&token, |defn_opt| match defn_opt {
2702    Some(Stored::Token(_)) | Some(Stored::None) | None => None,
2703    Some(other) => other.to_definition(),
2704  });
2705  match defn {
2706    Some(defn) if expands_now(&defn, false) => {
2707      invoke_expansion(token, &defn)?;
2708      Ok(true)
2709    },
2710    _ => Ok(false),
2711  }
2712}
2713
2714/// The alignment's cell-head peek, tex.web §785 `align_peek` and §791 (e-TeX `get_x_or_protected`): expand until
2715/// the first token that is not expandable — or protected, as `read_x_token(Some(true), false, Some(false))` stops —
2716/// and stop as well at a macro whose optional argument is a `\newcommand` one ([`Parameter::testopt`]): LaTeX's
2717/// `\newcommand\dg[3][]` is `\@protected@testopt\dg\\dg{}`, whose expansion reaches the unexpandable `\let` of
2718/// `\kernel@ifnextchar` before it reads an argument (latex.ltx:1249-1261), so TeX starts the cell there and the
2719/// arguments are read inside it. Our macro reads its arguments as it expands; expanded in the peek it read the
2720/// cell's `&` before the cell existed (diagbox.sty:212 `\newcommand\diagbox[3][]`, 2406.11917). The token is
2721/// returned unexpanded: the cell's own reader expands it. The binding closures that peek by `\futurelet`
2722/// ([`Definition::peeks_by_futurelet`], the kernel's `\@ifnextchar` family) still expand here: several stand for a
2723/// TeX macro whose head is not the peek (booktabs' `\cmidrule` is `\noalign{…\@ifnextchar[…}`, booktabs.sty:166).
2724///
2725/// [`Parameter::testopt`]: crate::parameter::Parameter::testopt
2726pub fn read_x_token_cell_head() -> Result<Option<Token>> {
2727  read_x_token_cell_head_stopping_at(|_| false)
2728}
2729
2730/// [`read_x_token_cell_head`], also stopping, unexpanded, at a token `stop` accepts (empheq's `left`, which looks for
2731/// a `\multicolumn` before it expands).
2732pub fn read_x_token_cell_head_stopping_at(stop: impl Fn(&Token) -> bool) -> Result<Option<Token>> {
2733  loop {
2734    let Some(token) = read_token()? else {
2735      return read_x_token(Some(true), false, Some(false));
2736    };
2737    if stop(&token) {
2738      return Ok(Some(token));
2739    }
2740    if token.get_catcode().is_active_or_cs()
2741      && with_meaning(&token, |defn| {
2742        defn.and_then(Stored::to_definition).is_some_and(|defn| {
2743          defn.is_expandable()
2744            && defn.get_parameters().is_some_and(|params| {
2745              params
2746                .get_parameters()
2747                .first()
2748                .is_some_and(|param| param.testopt)
2749            })
2750        })
2751      })
2752    {
2753      return Ok(Some(token));
2754    }
2755    if !expand_once_partial(token)? {
2756      unread_one(token);
2757      return read_x_token(Some(true), false, Some(false));
2758    }
2759  }
2760}
2761
2762/// Read the next non-expandable token, expanding until one appears. Hot path —
2763/// `read_token` is folded in. `toplevel` (default true): on mouth exhaustion,
2764/// step to the containing mouth. `fully_expand` (default = toplevel): expand
2765/// even protected defns ("for execution"). Unlike `read_balanced`, does NOT
2766/// defer `\the` & friends; `\noexpand`'d tokens act like `\relax`. For `\if`/
2767/// `\ifx` arguments pass `for_conditional=true` (handles `\noexpand` and CS
2768/// `\let` to tokens specially).
2769pub fn read_x_token(
2770  toplevel_opt: Option<bool>,
2771  for_conditional: bool,
2772  fully_expand_opt: Option<bool>,
2773) -> Result<Option<Token>> {
2774  // toplevel should be true by default
2775  let toplevel = toplevel_opt.unwrap_or(true);
2776  let fully_expand = fully_expand_opt.unwrap_or(toplevel);
2777  let _depth_guard = ExpandDepthGuard::enter()?; // Cluster F expansion-depth cap
2778  loop {
2779    // Combined checkpoint + raw read: this loop reads via the low-level
2780    // `read_internal_token_checked` (NOT `read_token`), so it runs the same
2781    // guards itself — otherwise every full-expansion read path (`\edef`,
2782    // `read_balanced`, csname construction) bypasses the token/pushback
2783    // limits and the expansion cycle guard entirely, and a `\def\x{a\x}`
2784    // runaway grinds to the multi-GB watchdog instead of a clean Fatal.
2785    let next_token = match read_internal_token_checked(CommentSink::Pending)? {
2786      // No runtime ≡ nothing more to read. (The pre-merge code fell through
2787      // to the exhausted branch below, whose autoclose peek — runtime gone ⇒
2788      // not autoclose — concluded Ok(None); return that directly.)
2789      CheckedRead::NoRuntime => return Ok(None),
2790      CheckedRead::Exhausted => None,
2791      CheckedRead::Tok(t) => Some(t),
2792    };
2793    //ProgressStep() if ($$self{progress}++ % $TOKEN_PROGRESS_QUANTUM) == 0;
2794    let Some(token) = next_token else {
2795      if read_x_token_crosses_input_end()? {
2796        continue;
2797      }
2798      return Ok(None);
2799    };
2800    if token.get_catcode() == Catcode::CS && token.text == pin!("\\dont_expand") {
2801      return read_x_token_dont_expand(for_conditional);
2802    }
2803    // Wow!!!!! See TeX the Program \S 309
2804    // SHOULD count nesting of { }!!! when SCANNED (not digested)
2805    if has_reading_alignment() {
2806      match read_x_token_column_end(token)? {
2807        ColumnEndRead::Worked => continue,
2808        ColumnEndRead::EndsNumberScan => return Ok(Some(token)),
2809        ColumnEndRead::NotOne => {},
2810      }
2811    }
2812    if token.get_catcode().is_active_or_cs() {
2813      // Read the meaning via closure so we can branch on the borrowed
2814      // Stored without cloning (Stored::clone was ~1% of total on
2815      // siunitx-heavy profiles; this site fires on every CS/ACTIVE
2816      // expansion — the hottest lookup_meaning caller).
2817      enum Outcome {
2818        LetTo(Token),
2819        Undefined,
2820        NonExpandable,
2821        Invoke(std::rc::Rc<dyn Definition>),
2822      }
2823      let outcome = with_meaning(&token, |defn_opt| match defn_opt {
2824        Some(Stored::Token(t)) => Outcome::LetTo(*t),
2825        Some(Stored::None) | None => Outcome::Undefined,
2826        Some(other) => match other.to_definition() {
2827          Some(defn) => {
2828            if expands_now(&defn, fully_expand) {
2829              Outcome::Invoke(defn)
2830            } else {
2831              Outcome::NonExpandable
2832            }
2833          },
2834          None => Outcome::Undefined,
2835        },
2836      });
2837      match outcome {
2838        Outcome::LetTo(let_token) => {
2839          return Ok(Some(if for_conditional { let_token } else { token }));
2840        },
2841        Outcome::Undefined => match read_x_token_undefined(token)? {
2842          Some(result) => return Ok(Some(result)),
2843          None => continue,
2844        },
2845        Outcome::NonExpandable => {
2846          return Ok(Some(token));
2847        },
2848        Outcome::Invoke(defn) => {
2849          if READING_OPERAND.get()
2850            && let Some(value) = operand_value(&token, &*defn)
2851          {
2852            unread(value);
2853            continue;
2854          }
2855          invoke_expansion(token, &defn)?;
2856          continue;
2857        },
2858      }
2859    } else {
2860      // Perl Gullet.pm L421-422: track { and } at scan level for ALIGN_STATE
2861      match token.get_catcode() {
2862        Catcode::BEGIN => increment_align_group_count(),
2863        Catcode::END => decrement_align_group_count(),
2864        _ => {},
2865      }
2866      return Ok(Some(token));
2867    }
2868  }
2869}
2870
2871/// [`read_x_token`] at the end of its input: whether a transparent injection closed and reading goes on.
2872#[cold]
2873#[inline(never)]
2874fn read_x_token_crosses_input_end() -> Result<bool> {
2875  {
2876    let gullet = gullet!();
2877    let current_is_autoclose = gullet
2878      .runtime
2879      .as_ref()
2880      .map(|r| r.autoclose)
2881      .unwrap_or(false);
2882    // Drain a *transparent autoclose injection* (\scantokens, raw_tex) and
2883    // resume the enclosing mouth even for a BOUNDED reader (toplevel==false,
2884    // e.g. the InputDefinitions file loop) — these are part of the current
2885    // logical stream. Faithful to tex.web `get_next` §362-365 (exhausting any
2886    // input level resumes the enclosing one; \scantokens is a pseudo-file
2887    // level). DIVERGES from Perl `Gullet.pm` readXToken, which gates on
2888    // `autoclose = toplevel` and so returns at the first exhausted mouth —
2889    // truncating a `.sty` whenever `\scantokens` runs mid-load (witness
2890    // 1906.03240: real babel.sty `\selectlanguage` dropped every later def →
2891    // undefined-CS cascade; Perl's hand-written babel.ltxml dodges it).
2892    // A non-autoclose boundary is left to its owner (return None).
2893    if !current_is_autoclose || gullet.mouthstack.is_empty() {
2894      return Ok(false);
2895    }
2896  }
2897  close_mouth(false)?; // Drain the autoclose injection; resume the parent.
2898  Ok(true)
2899}
2900
2901/// [`read_x_token`] of `\dont_expand`.
2902#[cold]
2903#[inline(never)]
2904fn read_x_token_dont_expand(for_conditional: bool) -> Result<Option<Token>> {
2905  let unexpanded = match read_token()? {
2906    Some(t) => t,
2907    None => return Ok(Some(T_CS!("\\special_relax"))), // \dont_expand at end-of-input
2908  };
2909  if for_conditional && unexpanded.code == Catcode::ACTIVE {
2910    Ok(Some(unexpanded))
2911  } else {
2912    // `\noexpand <tok>`: per-token `\special_relax` family encoding <tok>'s
2913    // identity in the name — faithful to TeX's `no_expand_flag`, which keeps
2914    // `cur_cs` while giving relax meaning for this one access. (Perl
2915    // readXToken returns a bare `\special_relax`, dropping the identity;
2916    // recovering it is a deliberate, SURPASS-PERL fidelity fix so a
2917    // `\noexpand`'d delimiter — e.g. xint's `\XINTfstop`, witness
2918    // 1804.01117 — reaches the surrounding parser as itself. The marker
2919    // lasts for this one read: a scanner that puts the token back puts
2920    // back its plain self (`unread_scanned`, KNOWN_PERL_ERRORS #255).)
2921    Ok(Some(crate::token::noexpand_family(&unexpanded)))
2922  }
2923}
2924
2925/// What [`read_x_token`] does with a token while an alignment is being read.
2926enum ColumnEndRead {
2927  Worked,
2928  EndsNumberScan,
2929  NotOne,
2930}
2931
2932/// [`read_x_token`] while an alignment is being read: "Wow!!!!! See TeX the Program \S 309"
2933/// SHOULD count nesting of { }!!! when SCANNED (not digested)
2934#[inline(never)]
2935fn read_x_token_column_end(token: Token) -> Result<ColumnEndRead> {
2936  if align_group_count() != 0 {
2937    return Ok(ColumnEndRead::NotOne);
2938  }
2939  let Some((_atoken, atype, ahidden)) = is_column_end(&token) else {
2940    return Ok(ColumnEndRead::NotOne);
2941  };
2942  if in_number_scan() {
2943    // tex.web §440: a tab/row end is unexpandable inside a number
2944    // scan — it ends the scan and is re-read (and then acted on) by
2945    // the main loop. Batch 56bi.
2946    return Ok(ColumnEndRead::EndsNumberScan);
2947  }
2948  let reading_alignment = get_reading_alignment().unwrap();
2949  if let DigestedData::Alignment(data) = reading_alignment.data() {
2950    handle_template(data.borrow_mut(), token, atype, ahidden)?;
2951  } else {
2952    panic!("malformed alignmed was stored?");
2953  }
2954  // And *then* continue the main loop checks
2955  Ok(ColumnEndRead::Worked)
2956}
2957
2958/// [`read_x_token`] of a token with no meaning: what it returns, or `None` to read again.
2959#[cold]
2960#[inline(never)]
2961fn read_x_token_undefined(token: Token) -> Result<Option<Token>> {
2962  if token.get_catcode() == Catcode::CS {
2963    // The LaTeX format may not be loaded yet (a document may use a
2964    // kernel CS before `\documentclass` — real LaTeX has no "before
2965    // the kernel"). If this is a kernel CS, pull the format in and
2966    // re-resolve rather than stubbing it as `<ltx:ERROR/>`. Fires at
2967    // most once per session; see `binding::kernel_autoload`.
2968    if crate::binding::kernel_autoload::try_autoload(&token) {
2969      unread_one(token); // Retry, now that the kernel is in state.
2970      return Ok(None);
2971    }
2972    // a command a refused class environment defines for its body (`kernel_autoload`)
2973    if crate::binding::kernel_autoload::try_refused_environment_definition(&token) {
2974      unread_one(token);
2975      return Ok(None);
2976    }
2977    // a stand-in named for the undefined name (`\chapter` in a class without chapters, OXIDIZED_DESIGN #734)
2978    if let Some(stand_in) = crate::binding::kernel_autoload::undefined_fallback(&token) {
2979      unread_one(stand_in);
2980      return Ok(None);
2981    }
2982    // a family the ar5iv preload provides on first use (`kernel_autoload::provide_on_first_use`, OXIDIZED_DESIGN #588)
2983    if crate::binding::kernel_autoload::provide_on_first_use(&token)? {
2984      unread_one(token);
2985      return Ok(None);
2986    }
2987    Ok(Some(generate_error_stub(&token)?))
2988  } else {
2989    Ok(Some(token))
2990  }
2991}
2992
2993/// Read the next raw line (string);
2994/// primarily to read from the Mouth, but keep any unread input!
2995/// Whether the gullet's unread (pushed-back) tokens include a non-space token.
2996///
2997/// Raw-line readers need this to interpret their FIRST [`read_raw_line`]
2998/// call. A `read_non_space` argument probe that found no `[` has crossed the
2999/// newline after `\begin{env}` and unread the BODY's first non-space
3000/// character — the "first raw line" is then real content, not the leftover of
3001/// the `\begin` line. A benign probe (`if_next` via `read_token`) unreads at
3002/// most the end-of-line SPACE token, so space-only pushback still means "the
3003/// first raw line is `\begin`-line leftover, discard it". See
3004/// `listings_sty::listings_read_raw_lines` (OXIDIZED_DESIGN #162).
3005pub fn pushback_holds_nonspace() -> bool {
3006  let gullet = gullet!();
3007  match gullet.runtime {
3008    Some(ref runtime) => runtime
3009      .pushback
3010      .iter()
3011      .any(|t| t.get_catcode() != Catcode::SPACE),
3012    None => false,
3013  }
3014}
3015
3016/// The pending pushback as text, next-to-read first, left in place: what a raw
3017/// line reader would take before the mouth's line (see [`read_raw_line`]).
3018pub fn pushback_text() -> String {
3019  let gullet = gullet!();
3020  match gullet.runtime {
3021    Some(ref runtime) => Tokens::new(runtime.pushback.iter().rev().cloned().collect()).to_string(),
3022    None => String::new(),
3023  }
3024}
3025
3026/// The current mouth line as raw text from column 0, DROPPING the pushback:
3027/// for a reader that knows the pushback holds tokens probed off this very
3028/// line (`pushback_holds_nonspace`), so the line comes back whole — with its
3029/// indentation and any catcode-9 characters the probe's tokenization lost.
3030pub fn read_raw_current_line_from_start() -> Option<String> {
3031  let mut gullet = gullet_mut!();
3032  match gullet.runtime {
3033    Some(ref mut runtime) => {
3034      runtime.pushback.clear();
3035      runtime.watch.note_len(0);
3036      runtime.mouth.read_raw_line_from_start()
3037    },
3038    None => None,
3039  }
3040}
3041
3042/// [`read_raw_line`] from the current mouth with its input bytes decoded
3043/// through the declared input encoding (`Mouth::read_raw_line_decoded`); the
3044/// `.bib` reader's and `{verbatim}`'s line source. Pending pushback is taken
3045/// as `read_raw_line` takes it, and decoded with the rest of the line: a
3046/// pushed-back active byte prints as its Latin-1 character (a `{verbatim}`
3047/// wrapper whose optional-argument check peeked the body's first character
3048/// left a cp1251 first line as mojibake).
3049pub fn read_raw_line_decoded() -> Option<String> {
3050  let has_pushback = gullet!()
3051    .runtime
3052    .as_ref()
3053    .is_some_and(|runtime| !runtime.pushback.is_empty());
3054  if has_pushback {
3055    let line = read_raw_line()?;
3056    let gullet = gullet!();
3057    return Some(match gullet.runtime.as_ref() {
3058      Some(runtime) => runtime.mouth.decode_eight_bit(line),
3059      None => line,
3060    });
3061  }
3062  let mut gullet = gullet_mut!();
3063  gullet
3064    .runtime
3065    .as_mut()
3066    .and_then(|runtime| runtime.mouth.read_raw_line_decoded(false))
3067}
3068
3069pub fn read_raw_line() -> Option<String> {
3070  // If we've got unread tokens, they presumably should come before the Mouth's raw data
3071  // but we'll convert them back to string.
3072  let mut gullet = gullet_mut!();
3073  if let Some(ref mut runtime) = gullet.runtime {
3074    // Vec-as-stack stores bottom-to-top, but the caller expects
3075    // "next to read" first — reverse the drained order to match the
3076    // old VecDeque drain(..) which was front-to-back (= next-to-read).
3077    let tokens: Vec<Token> = runtime.pushback.drain(..).rev().collect();
3078    runtime.watch.note_len(0);
3079
3080    // TODO
3081    // let markers : Vec<&Token> = tokens.iter().filter(|t:Token| t.get_catcode() ==
3082    // Catcode::MARKER).collect(); if !markers.is_empty() {    // Whoops, profiling markers!
3083
3084    // @tokens = grep { $_->getCatcode != Catcode::MARKER } @tokens;    // Remove
3085    // map { LaTeXML::Core::Definition::stopProfiling($_, 'expand') } @markers;
3086    // }
3087
3088    // If we still have peeked tokens, we ONLY want to combine it with the remainder
3089    // of the current line from the Mouth (NOT reading a new line)
3090    if !tokens.is_empty() {
3091      Some(Tokens::new(tokens).to_string() + &runtime.mouth.read_raw_line(true).unwrap_or_default())
3092    } else {
3093      // Otherwise, read the next line from the Mouth.
3094      runtime.mouth.read_raw_line(false)
3095    }
3096  } else {
3097    None
3098  }
3099}
3100
3101/// Give back the rest of the line a raw reader just read, as the current line of the input it came from, so the next
3102/// token or raw line is read from it and then from the lines after — one TeX input line (`\end{lstlisting} x
3103/// \begin{lstlisting}`: the second listing's raw reader reads its body from the following lines, 2408.11865). False
3104/// when tokens wait in front of it, which the line would then follow.
3105pub fn restore_raw_line_rest(rest: &str) -> bool {
3106  let mut gullet = gullet_mut!();
3107  match gullet.runtime.as_mut() {
3108    Some(runtime) if runtime.pushback.is_empty() => {
3109      runtime.mouth.restore_line_rest(rest);
3110      true
3111    },
3112    _ => false,
3113  }
3114}
3115
3116//**********************************************************************
3117// Mid-level readers: checking and matching tokens, strings etc.
3118//**********************************************************************
3119// The following higher-level parsing methods are built upon readToken & `.
3120
3121/// Read a single non-space token
3122pub fn read_non_space() -> Result<Option<Token>> {
3123  loop {
3124    match read_token()? {
3125      None => return Ok(None),
3126      Some(t) => {
3127        if t.get_catcode() != Catcode::SPACE {
3128          return Ok(Some(t));
3129        }
3130      },
3131    }
3132  }
3133}
3134
3135/// Read a single expanded, non-space, token
3136pub fn read_x_non_space() -> Result<Option<Token>> {
3137  loop {
3138    match read_x_token(Some(false), false, None)? {
3139      None => return Ok(None),
3140      Some(t) => {
3141        if t.get_catcode() != Catcode::SPACE {
3142          return Ok(Some(t));
3143        }
3144      },
3145    }
3146  }
3147}
3148
3149/// A directive describing to what degree a gullet reader should perform TeX's expansion
3150#[derive(Copy, Debug, Clone, PartialEq, Default)]
3151pub enum ExpansionLevel {
3152  // No expansion, reads currently present tokens
3153  #[default]
3154  Off,
3155  /// Expands while reading, but deferring `\the` and `\protected`
3156  Partial,
3157  /// Expands completely while reading
3158  Full,
3159}
3160
3161/// Approximates TeX's scan_toks (but doesn't parse \def parameter lists)
3162/// and only optionally requires the openning "{".
3163///
3164/// It may return comments in the token lists.
3165/// `pack_parameters` packs the `#` parameters of a macro body (Perl's
3166/// `$macrodef`, `Tokens::pack_parameters`). What happens when a file ends
3167/// inside the read is the [`ScannerStatus`]'s business, not this flag's: see
3168/// [`read_definition_body`] and [`read_balanced_text`] for the scans that set
3169/// one, and [`recover_at_file_end`].
3170/// If `require_open` is true, the opening T_BEGIN has not yet been read, and is required.
3171///
3172/// If `toplevel` is true, it will automatically close empty mouths as it reads,
3173/// and will also fully expand macros (unless overridden by `expansion_level` being explicitly Off).
3174pub fn read_balanced(
3175  expansion_level: ExpansionLevel,
3176  pack_parameters: bool,
3177  require_open: bool,
3178) -> Result<Tokens> {
3179  Ok(read_balanced_with_close(expansion_level, pack_parameters, require_open)?.0)
3180}
3181
3182/// A definition body: tex.web §473 `scan_toks(true, xpand)`, read at
3183/// `defining` status with its `#` parameters packed (`\def`, `\edef`, via the
3184/// `DefPlain`/`DefExpanded` parameter types). A file that ends inside it ends
3185/// the definition there (§339). TeX names the macro being defined; the body
3186/// reader does not know it, so the report says "definition" alone.
3187pub fn read_definition_body(expansion_level: ExpansionLevel) -> Result<Tokens> {
3188  let _status = set_scanner_status(ScannerStatus::Defining, None);
3189  read_balanced(expansion_level, true, true)
3190}
3191
3192/// A balanced text: tex.web §473 `scan_toks(false, xpand)` (eTeX
3193/// `scan_general_text`), read at `absorbing` status for the command being
3194/// executed (`\write`, `\uppercase`, `\detokenize`, `\toks=`, the pdfTeX
3195/// texts …). A file that ends inside it ends the text there (§339).
3196pub fn read_balanced_text(expansion_level: ExpansionLevel, require_open: bool) -> Result<Tokens> {
3197  let _status = set_scanner_status(ScannerStatus::Absorbing, get_current_token());
3198  read_balanced(expansion_level, false, require_open)
3199}
3200
3201/// [`read_balanced`] that also hands back the CLOSE token that ended the
3202/// group (`None` when the read ran out or found no opening brace). A
3203/// delimited reader stores a matched group verbatim (tex.web §392-398
3204/// `macro_call`'s `store_new_token(cur_tok)` — the argument keeps the braces
3205/// it was scanned with; the single-group outer-brace strip is §399-400, by
3206/// catcode). Diverges from Perl's canonical `T_END` (Gullet.pm:661/674),
3207/// OXIDIZED_DESIGN_DIVERGENCES #224. chemfig scans `(…)`
3208/// submols with `(`/`)` given catcodes 1/2 (chemfig.tex:1315-1324) and a
3209/// canonical `}` in their place re-tokenized as a real end-brace in the next
3210/// `\scantokens`, unbalancing it (chemexec/chemnum, sweep 74).
3211pub fn read_balanced_with_close(
3212  expansion_level: ExpansionLevel,
3213  pack_parameters: bool,
3214  require_open: bool,
3215) -> Result<(Tokens, Option<Token>)> {
3216  use ExpansionLevel::*;
3217  let mut close: Option<Token> = None;
3218  // NOTE: no align-ledger localization and no entry compensator here.
3219  // tex.web's `scan_toks` (§473-482) does NOT touch `align_state`: every
3220  // scanned brace counts on the live ledger, and the opening `{` of the
3221  // balanced text (counted by the caller for `require_open=false`, or by
3222  // the read below) is itself what keeps the ledger ≥1 inside, so `&`
3223  // cannot fire the alignment interrupt mid-argument. Perl instead
3224  // localizes ALIGN_STATE to 1000000 with an entry `--` compensator
3225  // (Gullet.pm readBalanced); that ERASES the interior net effect, so
3226  // expl3 brace-tricks (`\if_true: { \else: } \fi:` pairs whose halves
3227  // travel through different reads) drift the ledger permanently and a
3228  // later cell-top `&` goes stray (Perl shares that failure; l3doc
3229  // `{function}` repro). See [`unread_expansion`] for the pushback half
3230  // of the same protocol.
3231  // let startloc = if lookup_verbosity() > 0 { Some(get_locator()) } else { None };
3232  // Do we need to expand to get the { ???
3233  if require_open {
3234    let token_opt = if expansion_level != Off {
3235      // TeX's scan_left_brace uses plain get_x_token: \protected macros
3236      // EXPAND while hunting the required `{` — protection inhibits
3237      // expansion only during body absorption (live-probed pdflatex
3238      // 2026-08-31: `\protected\def\pp{{abc}}\expanded\pp` typesets abc).
3239      // With the default (toplevel) expansion this errored on every
3240      // `\xinttheexpr` (`\expanded\csname XINTexprprint…` is \protected) —
3241      // the ~16-doc `expected:{` xint cluster. #161-family fidelity fix.
3242      // Guard: cluster_package_guards::expanded_protected_brace_hunt.
3243      read_x_token(Some(false), false, Some(true))?
3244    } else {
3245      read_token()?
3246    };
3247    let is_open = match token_opt {
3248      None => false,
3249      Some(token) => {
3250        token.get_catcode() == Catcode::BEGIN
3251          || with_meaning(
3252            &token,
3253            |m| matches!(m, Some(Stored::Token(t)) if *t == T_BEGIN!()),
3254          )
3255      },
3256    };
3257    if !is_open {
3258      // Push the token back so subsequent reads (especially alignment `&`,
3259      // newline `\\`, or `\end{tabular}`) recover gracefully when an
3260      // upstream macro had a required `{}` arg with no `{...}` available
3261      // (e.g. mn2e/multirow with a missing 3rd arg — 0903.4199 cascade).
3262      // Without this, the consumed `&` was lost from alignment context,
3263      // turning a 1-error "missing arg" into a 10001-cap `&`-cascade.
3264      if let Some(t) = token_opt {
3265        unread_one(t);
3266      }
3267      Error!("expected", "{", s!("Expected opening '{{'"));
3268      return Ok((Tokens!(), None));
3269    }
3270  }
3271  // Pre-size the token accumulator: most balanced reads are short
3272  // macro arguments (~4–16 tokens). This skips the Vec's early
3273  // doublings that the callgrind profile attributes to
3274  // `raw_vec::finish_grow` (1% of total instructions in read_balanced
3275  // alone).
3276  let mut tokens: Vec<Token> = Vec::with_capacity(16);
3277  let mut level = 1;
3278  loop {
3279    // Combined checkpoint + raw read: this loop reads RAW (pushback / mouth,
3280    // not via read_token/read_x_token) — without its own checkpoint,
3281    // `\edef`-body expansion loops (`\def\x{a\x}\edef\y{\x}`) bypass the
3282    // token/pushback limits AND the expansion cycle guard, and grind to the
3283    // multi-GB process watchdog instead of a clean early Fatal. Comments
3284    // (pending ones included) are kept in the result via the `Into` sink.
3285    let next_token = match read_internal_token_checked(CommentSink::Into(&mut tokens))? {
3286      // No runtime mid-balanced-read (fatal recovery): degrade as an
3287      // exhausted opaque boundary below. (The old inline read would have
3288      // panicked on a vanished runtime; end-of-input is the graceful
3289      // equivalent — unreachable in a healthy conversion.)
3290      CheckedRead::NoRuntime | CheckedRead::Exhausted => None,
3291      CheckedRead::Tok(t) => Some(t),
3292    };
3293    // ProgressStep() if ($$self{progress}++ % $TOKEN_PROGRESS_QUANTUM) == 0;
3294    match next_token {
3295      // Mouth exhausted mid-balanced-read: mirror read_x_token / tex.web get_next
3296      // §362-365 — a transparent autoclose injection (\scantokens, raw_tex) is
3297      // part of the current logical stream, so drain it and resume the enclosing
3298      // mouth rather than reporting an unbalanced read. xint's
3299      // `\edef\X{\scantokens{...}}` opens an autoclose mouth mid-edef whose
3300      // matching `}` lives in the PARENT file; not crossing breaks the read at the
3301      // boundary and leaks `\xintexprSafeCatcodes`' `\begingroup`, corrupting
3302      // everything after. SURPASS-PERL: Perl readBalanced (Gullet.pm:466) `last`s
3303      // here and also fails this xint input.
3304      //
3305      // Gate on the mouth KIND, not just the autoclose bit: `\input` file
3306      // mouths are ALSO opened autoclose, and a truncated/unbalanced included
3307      // file must ERROR like TeX ("File ended while scanning use of …") and
3308      // Perl — not silently absorb the parent document into the argument
3309      // (PR_READINESS should-fix 9). Only string/literal injections
3310      // (\scantokens, RawTeX) are transparent to a balanced read.
3311      //
3312      // The `boundary` check narrows it further, because "literal mouth" is not
3313      // by itself evidence of a continuation: `\ProcessBibTeXEntry` also hands
3314      // an entry to `Mouth::new` (bibtex.rs, Perl BibTeX.pool L165-166), and
3315      // there one runaway field — a bare `%` in a title is enough — used to
3316      // swallow every following entry AND `\end{bibtex@bibliography}`, emptying
3317      // the whole bibliography while reporting a single error. Perl keeps all
3318      // the other entries. Such a mouth declares itself
3319      // [`BalancedBoundary::Opaque`].
3320      //
3321      // What counts as a file is the input LEVEL, not how it is read: a file
3322      // held in memory (filecontents, an `\openout` file) is read from a
3323      // string but ends like any file ([`crate::mouth::Mouth::is_file_level`]).
3324      // At a file's end TeX closes the file and recovers by the scanner status
3325      // (tex.web §362 `check_outer_validity`, §338-339; [`recover_at_file_end`]):
3326      // a definition or a text gets a `}` and the enclosing input goes on, so
3327      // the rest of the document is kept; a macro argument abandons its call.
3328      // At normal status the read keeps the stop and the error below.
3329      // Guards: `vfs_file_end::*`, `scanner_status::*`.
3330      None => {
3331        let (autoclosed, file_level, transparent) = {
3332          let gullet = gullet!();
3333          let has_parent = !gullet.mouthstack.is_empty();
3334          gullet.runtime.as_ref().map_or((false, false, false), |r| {
3335            (
3336              r.autoclose && has_parent,
3337              r.mouth.is_file_level(),
3338              r.boundary == BalancedBoundary::Transparent,
3339            )
3340          })
3341        };
3342        if autoclosed && transparent && !file_level {
3343          close_mouth(false)?;
3344          continue;
3345        }
3346        match recover_at_file_end()? {
3347          FileEndRecovery::Inserted => continue,
3348          FileEndRecovery::Abandoned => {
3349            // The call drops this argument; retract its unmatched braces from
3350            // the alignment ledger as §392 does (`align_state-unbalance`).
3351            set_align_group_count(align_group_count() - level);
3352            note_runaway_tokens(tokens);
3353            return Ok((Tokens!(), None));
3354          },
3355          FileEndRecovery::NotARunaway => break,
3356        }
3357      },
3358      // A `\par` in a non-`\long` macro's braced argument ends the call (tex.web §399): drop the group, retracting
3359      // its unmatched braces as §396 does (`align_state-unbalance`).
3360      Some(token) if is_par_ending_argument(&token) => {
3361        set_align_group_count(align_group_count() - level);
3362        abandon_argument_at_par(token);
3363        return Ok((Tokens!(), None));
3364      },
3365      Some(token) => match token.get_catcode() {
3366        Catcode::CS if token.text == pin!("\\dont_expand") => {
3367          if let Some(next_t) = read_token()? {
3368            if is_par_ending_argument(&next_t) {
3369              set_align_group_count(align_group_count() - level);
3370              abandon_argument_at_par(next_t);
3371              return Ok((Tokens!(), None));
3372            }
3373            tokens.push(next_t); // Pass on NEXT token, unchanged.
3374          }
3375        },
3376        // The v-part's `}` of a template that braces its cells (latex.ltx:15760-15763 `{eqnarray}`'s
3377        // `$\displaystyle{##}$`, amsmath's templates), carried as latexml_engine tex_box.rs `\lx@template@egroup`:
3378        // an argument read when a column end fires at alignment count 0 meets it (the cell's `}` closed the
3379        // template's `{`, so the argument's `{` holds the count at 0, tex.web §342), and as the explicit `}` it is in
3380        // TeX it closes the argument (§392). `a^{b}_c} - \frac{x}{y_{d}&=& 0.` in an eqnarray: `\frac`'s second
3381        // argument is `y_{d}`, as in pdflatex (0 errors); before, the argument ran past the template to the end of the
3382        // document (0902.2869, from line 409). The count is left as the primitive leaves it: the template's braces
3383        // are invisible to it (§324 resets it after the u-part). Guard
3384        // `perfect_kernel_batch69c::eqnarray_cell_braces_balance_across_the_template`.
3385        Catcode::CS if token.text == pin!("\\lx@template@egroup") => {
3386          level -= 1;
3387          if level <= 0 {
3388            close = Some(T_END!());
3389            break;
3390          }
3391          tokens.push(T_END!());
3392        },
3393        Catcode::END => {
3394          // Perl Gullet.pm L476: track ALIGN_STATE for } inside readBalanced
3395          decrement_align_group_count();
3396          level -= 1;
3397          if level <= 0 {
3398            close = Some(token);
3399            break;
3400          }
3401          tokens.push(token);
3402        },
3403        Catcode::BEGIN => {
3404          // Perl Gullet.pm L482: track ALIGN_STATE for { inside readBalanced
3405          increment_align_group_count();
3406          level += 1;
3407          tokens.push(token);
3408        },
3409        cc => {
3410          // Wow!!!!! See TeX the Program \S 309
3411          // Not sure if this code still applies within scan_toks???
3412          // SHOULD count nesting of { }!!! when SCANNED (not digested)
3413          if has_reading_alignment()
3414            && align_group_count() == 0
3415            && let Some((_atoken, atype, ahidden)) = is_column_end(&token)
3416          {
3417            match get_reading_alignment().unwrap().data() {
3418              DigestedData::Alignment(data) => {
3419                handle_template(data.borrow_mut(), token, atype, ahidden)?;
3420              },
3421              _ => {
3422                panic!("malformed alignmed was stored?");
3423              },
3424            }
3425            continue;
3426          }
3427          // Note: use general-purpose lookup, since we may reexamine $defn below
3428          if expansion_level != Off && cc.is_active_or_cs() {
3429            // Borrow the stored meaning via with_meaning so the Stored
3430            // enum is not cloned per token. We extract (a) whether a
3431            // meaning exists at all (for the undefined-CS diagnostic
3432            // below) and (b) the Rc<dyn Definition> if it's a proper
3433            // definition — both are cheap (bool + Rc-clone).
3434            let (has_meaning, defn_opt) =
3435              with_meaning(&token, |m| (m.is_some(), m.and_then(|s| s.to_definition())));
3436            if let Some(defn) = defn_opt {
3437              if defn.is_expandable()
3438                && (!defn.is_protected() || expansion_level == Full)
3439                && (expansion_level == Full || !optional_arg_protected(&defn))
3440              {
3441                let _token_guard = local_current_token_guard(token);
3442                // A closure that expands its argument (`Expand!`, `\lx@ifundefined`) recurses into this read, past
3443                // `read_x_token`'s depth count: count it too, so `\def\x{\@ifundefined{\x}{}{}}` ends in the
3444                // recursion Fatal (TeX: "capacity exceeded [input stack size]"), not a stack overflow (CCJNL397).
3445                let mut expansion = {
3446                  let _depth_guard = ExpandDepthGuard::enter()?;
3447                  crate::stack_guard::maybe_grow(|| defn.invoke(false))?
3448                };
3449                crate::token::inherit_field_prov(token.prov, &mut expansion);
3450                if expansion.is_empty() {
3451                  continue;
3452                }
3453                // If a special \the type command, push the expansion directly into the result
3454                // Well, almost directly: handle any MARKER tokens now, and possibly un-pack T_PARAM
3455                //
3456                // Perl `Gullet.pm:505` checks `$$defn{cs}[0]` — the Lt-aliases (e.g.
3457                // `Lt('\\exp_not:n','\\unexpanded')`) share the SAME Definition, so its cs
3458                // field IS `\unexpanded`. The dump now writes such a copy as `PA` (the same
3459                // definition too); the alias check remains for a by-value copy that carries
3460                // alias=`\unexpanded` (`dump_reader`), so the DEFERRED_COMMANDS gate still fires
3461                // for it inside `\edef` bodies. Without that gate, expl3's `\seq_gpush:Nn`
3462                // (`\exp_not:n` wrapping `\__seq_item:n {…}`) loses its item — re-expanded into
3463                // the expandable-error trap, leaving the seq stack empty and triggering
3464                // `extra-pop-label`/`\q_no_value`-recursion cascades during `\@pushfilename`.
3465                let cs_matches = DEFERRED_COMMANDS.contains(&defn.get_cs().text);
3466                let alias_matches = defn
3467                  .get_alias()
3468                  .map(|a| DEFERRED_COMMANDS.contains(&arena::pin(a)))
3469                  .unwrap_or(false);
3470                if expansion_level != Full && (cs_matches || alias_matches) {
3471                  for t in expansion.unlist() {
3472                    match t.get_catcode() {
3473                      Catcode::MARKER => handle_marker(t),
3474                      Catcode::PARAM if pack_parameters => {
3475                        // "unpack" to cover the packParameters at end!
3476                        tokens.push(t);
3477                        tokens.push(t);
3478                      },
3479                      _ => tokens.push(t),
3480                    }
3481                  }
3482                } else {
3483                  // otherwise, prepend to pushback to be expanded further.
3484                  unread_expansion(expansion);
3485                }
3486                continue;
3487              }
3488            } else if cc == Catcode::CS && !has_meaning {
3489              // a family provided on first use is defined now and read again (`kernel_autoload`)
3490              if crate::binding::kernel_autoload::provide_on_first_use(&token)? {
3491                unread_one(token);
3492                continue;
3493              }
3494              // cs SHOULD have defn by now; report early!
3495              generate_error_stub(&token)?;
3496            }
3497          }
3498          // Return the token — EXCEPT a `\special_relax` (noexpand'd) family token
3499          // collected into an expanded token list reverts to its plain shadowed
3500          // identity: TeX's no_expand_flag is transient (tex.web §1149-1153), so
3501          // `\edef`/`\xdef` store the PLAIN token, not a relax marker (etex ground
3502          // truth: `\def\s{\noexpand\s}\edef\r{\romannumeral0\s}` → `\meaning\r` =
3503          // "macro:->\s", xint's f-stop idiom). Otherwise the family token persists
3504          // into the `\edef` body and a later number scan hits "Missing number".
3505          // Gated on CS/active so the hot per-token push pays only a catcode check.
3506          if cc.is_active_or_cs() {
3507            tokens.push(token.noexpand_shadowed().unwrap_or(token));
3508          } else {
3509            tokens.push(token);
3510          }
3511        },
3512      },
3513    }
3514  }
3515  if level > 0 {
3516    // Reached for a genuinely unbalanced read: a balancing end in a LITERAL
3517    // (string-injection) mouth IS recognized via the autoclose crossing above;
3518    // a FILE boundary deliberately is not (TeX/Perl parity — "file ended
3519    // while scanning"), so a truncated \input lands here with the loud Error.
3520    // TODO: add the startloc details
3521    // my $loc_message = $startloc ? ("Started at " . ToString($startloc)) : ("Ended at " .
3522    // ToString($self->getLocator));
3523    Error!(
3524      "expected",
3525      "}",
3526      "Gullet->readBalanced ran out of input in an unbalanced state"
3527    );
3528  }
3529  if tokens.is_empty() {
3530    Ok((Tokens!(), close))
3531  } else {
3532    Ok((
3533      if pack_parameters {
3534        Tokens::new(tokens).pack_parameters()?
3535      } else {
3536        Tokens::new(tokens)
3537      },
3538      close,
3539    ))
3540  }
3541}
3542
3543/// Match the input against a set of keywords; Similar to readMatch, but the keywords are strings,
3544/// and Case and catcodes are ignored; additionally, leading spaces are skipped.
3545/// AND, macros are expanded.
3546///
3547/// Perf: zero-allocation char-wise comparison against each keyword.
3548/// The previous version allocated two Strings per char-match (via `to_uppercase()`
3549/// and `char::to_string()`), which was expensive in hot parameter parsing loops.
3550pub fn read_keyword<'k>(keywords: &[&'k str]) -> Result<Option<&'k str>> {
3551  skip_spaces()?;
3552  // One token per matched char, unread on no-match; one buffer for every keyword tried (`read_unit`'s ten).
3553  let mut matched = Vec::new();
3554  for keyword in keywords.iter() {
3555    let mut ok = true;
3556    for expected in keyword.chars() {
3557      let Some(tok) = read_x_token(Some(false), false, None)? else {
3558        ok = false;
3559        break;
3560      };
3561      // Compare char-by-char against the token's text, case-insensitively.
3562      let eq = tok.with_str(|s| {
3563        let mut it = s.chars();
3564        match it.next() {
3565          Some(c) if it.next().is_none() => {
3566            // single-char token: case-insensitive compare
3567            c.to_uppercase().eq(expected.to_uppercase())
3568          },
3569          _ => false,
3570        }
3571      });
3572      matched.push(tok);
3573      if !eq {
3574        ok = false;
3575        break;
3576      }
3577    }
3578    if ok {
3579      return Ok(Some(keyword));
3580    } else {
3581      // scan_keyword backs up the plain tokens it read (tex.web §407): a
3582      // `\noexpand`'d one goes back as its plain self (see `unread_scanned`).
3583      unread_iter(
3584        matched
3585          .drain(..)
3586          .map(|token| token.noexpand_shadowed().unwrap_or(token)),
3587      );
3588    }
3589  }
3590  Ok(None)
3591}
3592
3593/// Return a (balanced) sequence tokens until a match against one of the Tokens in @delims.
3594///
3595/// Note that Braces on input hides the contents from matching,
3596/// so this assumes there wont be braces in $delim!
3597/// But, see readUntilBrace for that case.
3598/// Reads until the delimiter tokens match. Returns `None` when input RAN OUT
3599/// before the delimiter appeared (everything consumed is unread first) —
3600/// mirroring Perl `Gullet::readUntil`'s undef (Gullet.pm L683-685), so an
3601/// `Until:` parameter can raise the Perl-faithful per-iteration "Missing
3602/// argument" Error instead of silently yielding empty. The silent empty made
3603/// zero-progress delimited-scan loops (fancyvrb `\FancyVerbGetLine#1^^M`
3604/// rescanning a replayed tail after an error stub swallowed its sentinel —
3605/// willowtreebook) spin to the 50k-box Stomach:Recursion fatal; with the
3606/// distinguishable EOF the TooManyErrors latch ends them like Perl's
3607/// MAX_ERRORS does, naming the looping macro. A MATCHED delimiter with empty
3608/// content stays `Some(empty)` — legitimate `\def\foo#1;{…}\foo;` args.
3609/// Is the gullet at the TRUE end of all input — no mouth left beneath the
3610/// current one and no `reading_from_mouth` context open? A delimited read
3611/// that misses its delimiter here has really run off the end of the
3612/// document (tex.web §338 "File ended while scanning use of"), as opposed
3613/// to the artificial end of an isolated reading context, where the
3614/// enclosing stream would still hold the delimiter.
3615pub fn at_end_of_all_input() -> bool {
3616  let g = gullet!();
3617  g.mouthstack.is_empty() && g.ctx_stack.is_empty()
3618}
3619
3620/// A required argument of `spec` whose reader ran out: at the true end of all input Perl's "Missing argument" Error
3621/// (Parameter.pm:93-97), the call then running on the reader's empty value; an isolated mouth's end stays quiet.
3622///
3623/// A later macro call missing the same argument (same macro, same spec) with no less input left is a scanner
3624/// re-requesting it from the put-back, which Perl reruns to its error cap (ifthen's `\@tempc`, `\@iforloop`, fancyvrb
3625/// `\FV@Scan`): TeX's runaway, "File ended while scanning use of", the call abandoned (tex.web §338-339, §392;
3626/// [`abandon_runaway_call`]) and the put-back read on. Every later call of it is abandoned too, reported once: a loop
3627/// broken there re-enters from the put-back. One that consumed input is a new call, run as Perl runs it (a caption
3628/// typeset after its measuring, PiCTeX's `\put`s). Witnesses 2511.11682, 2510.17429 (500 Errors to the cap).
3629pub fn note_missing_argument(object: &str, spec: &str) -> Result<()> {
3630  if !at_end_of_all_input() {
3631    return Ok(());
3632  }
3633  let caller = get_current_token();
3634  let runaway = {
3635    let gullet = &mut *gullet_mut!();
3636    // At the true end the input left is the pushback: the reader that ran out put back what it scanned.
3637    let left = gullet.runtime.as_ref().map_or(0, |r| r.pushback.len());
3638    let matching = gullet.scanner_status == ScannerStatus::Matching;
3639    match gullet.true_end_misses.entry((caller, spec.to_string())) {
3640      Entry::Vacant(miss) => {
3641        miss.insert((left, false));
3642        None
3643      },
3644      Entry::Occupied(mut miss) => {
3645        let (last, abandoned) = *miss.get();
3646        if matching && (abandoned || left >= last) {
3647          miss.insert((left, true));
3648          Some(Runaway::TrueEnd { first: !abandoned })
3649        } else {
3650          miss.insert((left, abandoned));
3651          None
3652        }
3653      },
3654    }
3655  };
3656  if let Some(runaway) = runaway {
3657    let mut gullet = gullet_mut!();
3658    if gullet.runaway_argument.is_none() {
3659      gullet.runaway_argument = Some(runaway);
3660    }
3661    return Ok(());
3662  }
3663  let caller = caller.map(|t| t.to_string()).unwrap_or_default();
3664  Error!(
3665    "expected",
3666    object,
3667    s!("Missing argument {spec} at end of input"),
3668    s!("while reading the arguments of {caller}")
3669  );
3670  Ok(())
3671}
3672
3673/// A token argument, or `\relax` when the input ran out (after [`note_missing_argument`]): the no-op stand-in a
3674/// primitive's coercion accepts.
3675pub fn token_or_relax(token: Option<Token>, spec: &str) -> Result<Token> {
3676  match token {
3677    Some(token) => Ok(token),
3678    None => {
3679      note_missing_argument(spec, spec)?;
3680      Ok(T_CS!("\\relax"))
3681    },
3682  }
3683}
3684
3685/// Whether a `\par` read after the tokens in `ring` continues a partial match of the delimiter `want`: some prefix
3686/// of `want` ends in `\par` and the ring's last tokens are the rest of that prefix (tex.web §397's partial match).
3687fn continues_partial_match(ring: &VecDeque<Token>, want: &[Token]) -> bool {
3688  let par = T_CS!("\\par");
3689  (1..=want.len()).any(|k| {
3690    want[k - 1] == par
3691      && k - 1 <= ring.len()
3692      && ring
3693        .iter()
3694        .skip(ring.len() + 1 - k)
3695        .eq(want[..k - 1].iter())
3696  })
3697}
3698
3699pub fn read_until(delim: &Tokens) -> Result<Option<Tokens>> {
3700  // Pre-size like `read_balanced`: the accumulator is grown one token at a time
3701  // in the loops below, so an unsized `Vec::new()` pays the 0→1→2→4→8 doubling
3702  // reallocations on every call. 16 covers the common short delimited read in a
3703  // single allocation (a top `grow_one` site in the allocation profile).
3704  let mut tokens: Vec<Token> = Vec::with_capacity(16);
3705  let mut nbraces = 0;
3706  let want = delim.unlist_ref();
3707  let ntomatch = want.len();
3708  let mut has_matched;
3709
3710  if ntomatch == 1 {
3711    let want = &want[0];
3712    // The `\par` §395 inserts at a `}`, read next.
3713    let mut inserted: Option<Token> = None;
3714    loop {
3715      let token = match inserted
3716        .take()
3717        .map_or_else(read_token, |par| Ok(Some(par)))?
3718      {
3719        Some(t) => t,
3720        None => {
3721          // A delimited macro argument that runs off a file's end abandons
3722          // its call (`recover_at_file_end`), which drops the argument.
3723          if argument_ran_off_a_file()? {
3724            note_runaway_tokens(tokens);
3725            return Ok(Some(Tokens!()));
3726          }
3727          // Ran out! Unread and report the distinguishable EOF. A marked
3728          // `\scantokens` mouth has already delivered its `\everyeof`
3729          // payload as its last tokens (`eof_seen`), so this is the true end.
3730          unread(Tokens::new(tokens));
3731          return Ok(None);
3732        },
3733      };
3734      // Perl: check direct match OR \special_relax smuggling (Gullet.pm line 662)
3735      if token == *want || special_relax_matches(&token, want) {
3736        break;
3737      }
3738      // After the delimiter test, as tex.web §392 orders them: a `\par` delimiter is matched, any other `\par`
3739      // ends a non-`\long` macro's call.
3740      if is_par_ending_argument(&token) {
3741        abandon_argument_at_par(token);
3742        return Ok(Some(Tokens!()));
3743      }
3744      if is_extra_brace_in_argument(&token) {
3745        inserted = Some(insert_par_at_extra_brace(token)?);
3746        continue;
3747      }
3748      match token.get_catcode() {
3749        Catcode::MARKER => {
3750          // would have been handled by readToken, but we're bypassing
3751          handle_marker(token);
3752        },
3753        Catcode::BEGIN => {
3754          // And if it's a BEGIN, copy till balanced END
3755          nbraces += 1;
3756          tokens.push(token);
3757          let (balanced_arg, close) = read_balanced_with_close(ExpansionLevel::Off, false, false)?;
3758          if argument_runaway() {
3759            note_runaway_tokens(tokens);
3760            return Ok(Some(Tokens!()));
3761          }
3762          if !balanced_arg.is_empty() {
3763            tokens.extend(balanced_arg.unlist());
3764          }
3765          // The group's OWN close (tex.web §392), not a canonical `}`.
3766          tokens.push(close.unwrap_or_else(|| T_END!()));
3767        },
3768        _ => {
3769          tokens.push(token);
3770        },
3771      }
3772    }
3773  } else {
3774    let mut ring = VecDeque::new();
3775    let mut inserted: Option<Token> = None;
3776    let mut met_brace = false;
3777    loop {
3778      // prefill the required number of tokens
3779      while ring.len() < ntomatch {
3780        let token = match inserted
3781          .take()
3782          .map_or_else(read_token, |par| Ok(Some(par)))?
3783        {
3784          Some(t) => t,
3785          None => {
3786            if argument_ran_off_a_file()? {
3787              tokens.extend(ring);
3788              note_runaway_tokens(tokens);
3789              return Ok(Some(Tokens!()));
3790            }
3791            // Ran out! Unread and report the distinguishable EOF.
3792            // The partial ring is DROPPED, not unread — replaying a
3793            // half-matched delimiter prefix into the stream re-tokenizes
3794            // it under current catcodes (l3doc `_`-laden names became
3795            // double-subscript cascades: spath3 1→1001, 2026-09-01).
3796            unread(Tokens::new(tokens));
3797            return Ok(None);
3798          },
3799        };
3800        // A `\par` that continues a partial match of the delimiter is accepted quietly (tex.web §397); any other
3801        // ends a non-`\long` macro's call (§392).
3802        if is_par_ending_argument(&token) && !continues_partial_match(&ring, want) {
3803          abandon_argument_at_par(token);
3804          return Ok(Some(Tokens!()));
3805        }
3806        if is_extra_brace_in_argument(&token) {
3807          let par = insert_par_at_extra_brace(token)?;
3808          // A delimiter starting with `\par` takes the inserted one and meets the `}` again: TeX loops to its error cap;
3809          // the second `}` ends the call.
3810          if met_brace {
3811            abandon_argument_at_par(par);
3812            return Ok(Some(Tokens!()));
3813          }
3814          met_brace = true;
3815          // The `}` ends any partial match (§397): the ring's tokens are the argument's.
3816          tokens.extend(ring.drain(..));
3817          inserted = Some(par);
3818          continue;
3819        }
3820        // Perl: $$token[1] == CC_BEGIN — direct catcode check. A `{` that completes the delimiter (one ending in `{`,
3821        // from a parameter text's closing `#{`) is its last token: tex.web §392 compares the token with the delimiter
3822        // before it takes a `{` as a group.
3823        if token.get_catcode() == Catcode::BEGIN
3824          && !(ring.len() + 1 == ntomatch
3825            && token == want[ntomatch - 1]
3826            && ring
3827              .iter()
3828              .zip(want.iter())
3829              .all(|(have, wanted)| have == wanted))
3830        {
3831          // read balanced, and refill ring.
3832          nbraces += 1;
3833          // the ring empties into the tokens: the scan retries with a fresh one
3834          for r_token in std::mem::take(&mut ring) {
3835            tokens.push(r_token);
3836          }
3837          tokens.push(token);
3838          let (balanced_arg, close) = read_balanced_with_close(ExpansionLevel::Off, false, false)?;
3839          if argument_runaway() {
3840            note_runaway_tokens(tokens);
3841            return Ok(Some(Tokens!()));
3842          }
3843          if !balanced_arg.is_empty() {
3844            tokens.append(&mut balanced_arg.unlist());
3845          }
3846          tokens.push(close.unwrap_or_else(|| T_END!())); // the group's own close
3847        } else {
3848          ring.push_back(token);
3849        }
3850      }
3851      has_matched = &ring == want; // Test match
3852      if has_matched {
3853        break;
3854      } // Matched all!
3855      if let Some(ring_token) = ring.pop_front() {
3856        tokens.push(ring_token);
3857      }
3858    }
3859  }
3860  // Notice that IFF the arg looks like {balanced}, the outer braces are stripped
3861  // so that delimited arguments behave more similarly to simple, undelimited arguments.
3862  // Perl: ($nbraces == 1) && ($tokens[0][1] == CC_BEGIN) && ($tokens[-1][1] == CC_END)
3863  if nbraces == 1
3864    && tokens.first().unwrap().get_catcode() == Catcode::BEGIN
3865    && tokens.last().unwrap().get_catcode() == Catcode::END
3866  {
3867    tokens.remove(0);
3868    tokens.pop();
3869  }
3870  Ok(Some(Tokens::new(tokens)))
3871}
3872
3873/// Convenience method wrapping around `read_until` — EOF degrades to empty
3874/// (callers that need to distinguish use `read_until` directly).
3875/// Expanding delimited scan: read tokens with full expansion up to (and
3876/// consuming) `until`, copying brace groups unexpanded once opened. The
3877/// `XUntil:` parameter type's reader (Perl `Parameters.pm` `XUntil`, after
3878/// PR #2767 "should only expand, not digest": a bare token push is all that
3879/// remains). A `\noexpand`'d token collected here reverts to its plain
3880/// shadowed identity, as in `read_balanced`: TeX's no_expand_flag is
3881/// transient (tex.web §1149-1153), so a `\protect\cs ` pair produced under
3882/// `\@unexpandable@protect` is stored as the plain pair, not relax markers.
3883pub fn read_x_until(until: &Token) -> Result<Tokens> {
3884  Ok(read_x_until_any(std::slice::from_ref(until))?.0)
3885}
3886
3887/// [`read_x_until`] up to the first of `untils`, returned with the text (`None` when the input ran out).
3888pub fn read_x_until_any(untils: &[Token]) -> Result<(Tokens, Option<Token>)> {
3889  let mut tokens: Vec<Token> = Vec::new();
3890  while let Some(token) = read_x_token(Some(false), false, None)? {
3891    if untils.contains(&token) {
3892      return Ok((Tokens::new(tokens), Some(token)));
3893    } else if token.get_catcode() == Catcode::BEGIN {
3894      tokens.push(token);
3895      tokens.extend(read_balanced(ExpansionLevel::Off, false, false)?.unlist());
3896      if argument_runaway() {
3897        // The group ran off a file's end: the call is abandoned (§392).
3898        note_runaway_tokens(tokens);
3899        return Ok((Tokens!(), None));
3900      }
3901      tokens.push(T_END!());
3902    } else if token.get_catcode().is_active_or_cs() {
3903      tokens.push(token.noexpand_shadowed().unwrap_or(token));
3904    } else {
3905      tokens.push(token);
3906    }
3907  }
3908  Ok((Tokens::new(tokens), None))
3909}
3910
3911pub fn read_until_token(t: Token) -> Result<Tokens> {
3912  Ok(read_until(&Tokens!(t))?.unwrap_or_default())
3913}
3914/// reads until it encounters a Catcode::BEGIN token
3915/// Note: Perl uses `$$token[1] == CC_BEGIN` (catcode check, not defined_as)
3916pub fn read_until_brace() -> Result<Option<Tokens>> {
3917  let mut tokens = Vec::new();
3918  loop {
3919    match read_token()? {
3920      Some(token) if token.get_catcode() == Catcode::BEGIN => {
3921        unread_one(token); // Unread with proper agc adjustment
3922        break;
3923      },
3924      Some(token) if is_par_ending_argument(&token) => {
3925        abandon_argument_at_par(token);
3926        return Ok(None);
3927      },
3928      // The `\par` inserted at a `}` is no `{`: it ends the call (§395).
3929      Some(token) if is_extra_brace_in_argument(&token) => {
3930        abandon_argument_at_par(insert_par_at_extra_brace(token)?);
3931        return Ok(None);
3932      },
3933      Some(token) => tokens.push(token),
3934      None => {
3935        // A `#{`-delimited macro argument that runs off a file's end: the
3936        // call is abandoned (tex.web §392).
3937        if argument_ran_off_a_file()? {
3938          note_runaway_tokens(std::mem::take(&mut tokens));
3939        }
3940        break;
3941      },
3942    }
3943  }
3944  if tokens.is_empty() {
3945    Ok(None)
3946  } else {
3947    let tks = Tokens::new(tokens);
3948    Ok(Some(tks))
3949  }
3950}
3951
3952pub fn read_cs_name() -> Result<Token> { read_cs_name_inner(false) }
3953
3954/// Quiet version of read_cs_name — used by \ifcsname.
3955/// In TeX, \ifcsname silently skips non-expandable CS tokens and returns the constructed name
3956/// without emitting errors (unlike \csname which DOES emit errors).
3957pub fn read_cs_name_quiet() -> Result<Token> { read_cs_name_inner(true) }
3958
3959thread_local! {
3960  /// e-TeX `\ifincsname` (etex.ch "Implement \ifincsname"): depth of the
3961  /// `\csname…\endcsname` scans in progress. utf8.def:55-90's octet handlers
3962  /// test it to keep a non-ASCII character LITERAL in a name instead of
3963  /// expanding to its LICR (clefval's `\csname V@a§b\endcsname`). Nest-safe
3964  /// via `CsnameScope`'s `Drop`, so an early error return still unwinds it.
3965  static CSNAME_DEPTH: Cell<u32> = const { Cell::new(0) };
3966}
3967struct CsnameScope;
3968impl Drop for CsnameScope {
3969  fn drop(&mut self) { CSNAME_DEPTH.set(CSNAME_DEPTH.get().saturating_sub(1)); }
3970}
3971/// True while a `\csname…\endcsname` name is being scanned.
3972pub fn in_csname() -> bool { CSNAME_DEPTH.get() > 0 }
3973
3974/// Fully expand `tokens` as the name inside a `\csname…\endcsname`
3975/// (`\ifincsname` true), the way LaTeX reads a file name: `\set@curr@file`
3976/// (latex.ltx) expands `\input`'s argument within `\csname`, so an active
3977/// character guarded by `\ifincsname` keeps its literal form there
3978/// (underscore-ltx.sty's `_`, utf8.def's octets).
3979pub fn expand_as_csname_text<T: Into<Tokens>>(tokens: T) -> Result<Tokens> {
3980  CSNAME_DEPTH.set(CSNAME_DEPTH.get() + 1);
3981  let _csname_scope = CsnameScope;
3982  do_expand(tokens)
3983}
3984
3985/// A file name as latex.ltx reads one (`\set@curr@file`, `\@kernel@make@file@csname`, latex.ltx:9654, :19745-19747):
3986/// `\@firstofone#1` strips the braces of a leading group (`\include{{./x}}` reads `./x.tex`; 2406.05605), then the
3987/// name is expanded within `\csname` ([`expand_as_csname_text`]).
3988pub fn expand_as_file_name<T: Into<Tokens>>(tokens: T) -> Result<Tokens> {
3989  let mut tokens = tokens.into().unlist();
3990  if tokens.first().is_some_and(|t| t.group_step() == 1) {
3991    let mut depth = 0;
3992    if let Some(close) = tokens.iter().position(|t| {
3993      depth += t.group_step();
3994      depth == 0
3995    }) {
3996      tokens.remove(close);
3997      tokens.remove(0);
3998    }
3999  }
4000  expand_as_csname_text(tokens)
4001}
4002
4003fn read_cs_name_inner(quiet: bool) -> Result<Token> {
4004  CSNAME_DEPTH.set(CSNAME_DEPTH.get() + 1);
4005  let _csname_scope = CsnameScope;
4006  // TeX does NOT store the csname with the leading `\`, BUT stores active chars with a flag
4007  // However, so long as the Mouth's CS and \string properly respect \escapechar, all's well!
4008
4009  // Safety bound: a real CS name fits in well under 256 chars. We've seen
4010  // pathological cases (lipsum.sty with malformed \cs_set_nopar:Npe expansion,
4011  // or expl3 raw-load before \endcsname is bound) where `\csname` reads
4012  // thousands of tokens accumulating into `cs`, eventually OOMing the
4013  // `read_x_token` pushback Vec. Cap at 4096 bytes — beyond that there's no
4014  // legitimate CS name, just a runaway. Emit one clear error and break.
4015  const MAX_CS_NAME_BYTES: usize = 4096;
4016  // A nested `\csname` (read while expanding this one's name) takes an empty buffer.
4017  let mut cs = CS_NAME_BUFFER.with(|buffer| buffer.take());
4018  cs.clear();
4019  cs.push('\\');
4020  // keep newlines from having \n inside!
4021  while let Some(token) = read_x_token(Some(true), false, None)? {
4022    if token.defined_as(&TOKEN_ENDCSNAME) {
4023      break;
4024    }
4025    // tex.web §370: an undefined control sequence inside `\csname…\endcsname`
4026    // is reported by `expand` and DISCARDED — the name scan continues. The
4027    // `read_x_token` above just stubbed it (`generate_error_stub`, error
4028    // emitted), so without this check it read as a defined non-expandable
4029    // token and took the §373 `back_error` path, ending the name early and
4030    // leaving the real `\endcsname` stray ("Extra \endcsname" ×1693 lines /
4031    // 65 manuals: babel's `\csname l@\beamer@torinoth@language\endcsname`
4032    // in beamer2thesis, gckanbun's pgf arrow declarations …). Perl consumes
4033    // the `\endcsname` but also emits a second error; pdflatex emits one.
4034    if token.get_catcode() == Catcode::CS && is_error_stub(&token) {
4035      continue;
4036    }
4037    if cs.len() > MAX_CS_NAME_BYTES {
4038      Error!(
4039        "runaway",
4040        "csname",
4041        format!(
4042          "CS-name read exceeded {MAX_CS_NAME_BYTES} bytes; aborting at partial cs: {:?}",
4043          // Truncate by CHARS, not bytes — a byte slice at 200 can split a
4044          // multi-byte UTF-8 char (e.g. 'ä') and panic. Witness 2601.03403.
4045          cs.chars().take(200).collect::<String>()
4046        )
4047      );
4048      break;
4049    }
4050    match token.get_catcode() {
4051      Catcode::CS => {
4052        // Soft-substitute the underlying char for a character-equivalent CS
4053        // token in the \csname stream — a documented divergence from Knuth TeX
4054        // (tex.web L7745-7758 hard-errors "Missing \endcsname inserted" for any
4055        // CS that isn't \endcsname). Our expansion pipeline surfaces PA-aliased
4056        // `Stored::Token` CSes (expl3 `\exp_stop_f:` = frozen space, `\lx@NBSP`
4057        // from CLUSTER-NBSP) into the csname stream where real TeX wouldn't reach
4058        // this state; erroring like Knuth would break real expl3/mhchem/glossaries
4059        // loads, so we substitute the char the author meant. Witnesses: `\lx@NBSP`
4060        // (CLUSTER-NBSP, 18 papers; `~`→U+00A0 in `\csname r@LABEL\endcsname`),
4061        // `\exp_stop_f:` (mhchem raw-load). The `\lx@NBSP` carve-out below stays
4062        // for clarity; the general `Stored::Token` case handles the rest uniformly.
4063        let is_applyaccent = token.text == crate::pin!("\\lx@applyaccent");
4064        // Well-known `\text…` primitives that map to a single char in real
4065        // pdflatex's csname-stream interpretation. The `DefPrimitive!(name,
4066        // "char")` body is a closure that wraps a Tbox — not statically
4067        // inspectable from here — so we maintain an explicit table for the
4068        // canonical set. Witnesses (stage-1..3 of 100k warning corpus):
4069        //   \\textquoteright surfacing in `\twemoji flag: Côte d` cluster
4070        //   (≥4 papers across 2603.08303, 2604.13899, 2604.17338, 2604.20621).
4071        let soft_char: Option<char> = token.with_str(|cs_str| match cs_str {
4072          "\\lx@NBSP" | "\\lx@nobreakspace" | "\\nobreakspace" => Some('\u{00A0}'),
4073          "\\textquoteright" => Some('\u{2019}'),
4074          "\\textquoteleft" => Some('\u{2018}'),
4075          "\\textquotedblright" => Some('\u{201D}'),
4076          "\\textquotedblleft" => Some('\u{201C}'),
4077          "\\textquotedbl" => Some('"'),
4078          "\\textemdash" => Some('\u{2014}'),
4079          "\\textendash" => Some('\u{2013}'),
4080          "\\textbackslash" => Some('\u{005C}'),
4081          "\\textbar" => Some('|'),
4082          "\\textbraceleft" => Some('{'),
4083          "\\textbraceright" => Some('}'),
4084          "\\textless" => Some('<'),
4085          "\\textgreater" => Some('>'),
4086          "\\textdollar" => Some('$'),
4087          "\\textasciigrave" => Some('`'),
4088          "\\textasciicircum" => Some('^'),
4089          "\\textasciitilde" => Some('~'),
4090          "\\textunderscore" => Some('_'),
4091          "\\textasteriskcentered" => Some('*'),
4092          // NFSS encoding-specific glyph CS names (`\<encoding>\<glyph>`)
4093          // built by \DeclareTextSymbol for the i/j dotless letters. These
4094          // surface when a paper composes `\'\i` style accented chars
4095          // that travel through `\lx@applyaccent` and a downstream
4096          // encoding-specific dispatcher. Substitute the dotless glyph
4097          // (U+0131 / U+0237) so the constructed csname carries the
4098          // character the author meant.
4099          // Witnesses: arXiv:2603.22193, 2603.23433, 2604.20621 (twemoji
4100          // São Tomé & Príncipe / St. Barthélemy / Côte d'Ivoire cluster).
4101          "\\T1\\i" | "\\OT1\\i" | "\\LY1\\i" => Some('\u{0131}'),
4102          "\\T1\\j" | "\\OT1\\j" | "\\LY1\\j" => Some('\u{0237}'),
4103          _ => None,
4104        });
4105        if let Some(c) = soft_char {
4106          cs.push(c);
4107        } else if is_applyaccent {
4108          // Accent macros (`\'`, `\"`, `\^`, …) expand to
4109          // `\lx@applyaccent <accent> <combining> <standalone> {<letter>}`
4110          // (tex_character.rs::accent_def). pdflatex's `\csname` skips the
4111          // accented char (the accent runs in the gullet); ours is a stomach
4112          // `DefPrimitive`, so a literal `\lx@applyaccent` surfaces in the csname
4113          // stream and aborts the read (witnesses: twemoji.sty, arXiv:2603.22193 /
4114          // 2603.23433). Faithful fix: peek the 4 args, append the standalone char
4115          // (arg 3, T_OTHER!) to the name, discard the rest — mirrors the
4116          // implicit-character substitution above.
4117          let _accent = read_x_token(Some(true), false, None)?;
4118          let _combiner = read_x_token(Some(true), false, None)?;
4119          let standalone = read_x_token(Some(true), false, None)?;
4120          // The 4th arg is a brace group `{<letter>}` — consume the
4121          // T_BEGIN, then read tokens until matching T_END.
4122          if let Some(t) = read_x_token(Some(true), false, None)?
4123            && t.get_catcode() == Catcode::BEGIN
4124          {
4125            let mut depth: i32 = 1;
4126            while depth > 0 {
4127              match read_x_token(Some(true), false, None)? {
4128                Some(t2) => match t2.get_catcode() {
4129                  Catcode::BEGIN => depth += 1,
4130                  Catcode::END => depth -= 1,
4131                  _ => {},
4132                },
4133                None => break,
4134              }
4135            }
4136          }
4137          if let Some(c) = standalone {
4138            c.with_str(|s| cs.push_str(s));
4139          }
4140        } else {
4141          match lookup_meaning(&token) {
4142            Some(Stored::Token(letted)) => {
4143              // CS is \let-equivalent to a single token. If that token is
4144              // a character (LETTER/OTHER/SPACE), append its string repr
4145              // to the constructed csname — mirrors real TeX's behaviour
4146              // of substituting the let-target into the csname stream.
4147              // Non-character lets (Catcode::CS, MATH, etc.) fall through
4148              // to the error branches below.
4149              let target_cc = letted.get_catcode();
4150              if matches!(target_cc, Catcode::LETTER | Catcode::OTHER | Catcode::SPACE) {
4151                if target_cc == Catcode::SPACE {
4152                  cs.push(' ');
4153                } else {
4154                  letted.with_str(|s| cs.push_str(s));
4155                }
4156              } else if !quiet {
4157                if *CSNAME_TRACE {
4158                  csname_trace_lookahead("let", &cs, &token)?;
4159                }
4160                let message = s!(
4161                  "The control sequence {:?} should not appear between \\csname and \\endcsname (partial cs so far: {:?})",
4162                  token,
4163                  cs
4164                );
4165                Error!("unexpected", token, message);
4166                // tex.web §373 `back_error`: "Missing \endcsname inserted" —
4167                // the csname ENDS here and the offending token is re-read
4168                // AFTER the constructed CS. Swallowing it instead lost every
4169                // token up to the real `\endcsname` (tikzpingus-doc:
4170                // `\csname foo\relax bar\endcsname` must typeset "bar").
4171                unread_one(token);
4172                break;
4173              }
4174            },
4175            _ => {
4176              if !quiet {
4177                if lookup_definition(&token)?.is_some() {
4178                  if *CSNAME_TRACE {
4179                    csname_trace_lookahead("def", &cs, &token)?;
4180                  }
4181                  let message = s!(
4182                    "The control sequence {:?} should not appear between \\csname and \\endcsname (partial cs so far: {:?})",
4183                    token,
4184                    cs
4185                  );
4186                  Error!("unexpected", token, message);
4187                } else {
4188                  let message = s!("The token {:?} is not defined", token);
4189                  Error!("undefined", token, message);
4190                }
4191                // §373 back_error recovery, as above.
4192                unread_one(token);
4193                break;
4194              }
4195            },
4196          }
4197        }
4198        // In quiet mode (ifcsname), just skip the CS token
4199      },
4200      Catcode::SPACE => cs.push(' '), // Keep newlines from having \n!
4201      _ => {
4202        token.with_str(|s| cs.push_str(s));
4203      },
4204    };
4205  }
4206  // K10: under the pdfTeX byte mouth a name has two spellings — the bytes
4207  // (`\csname\string\color@#1\endcsname` from a detokenized key, tikz's
4208  // colour probe) and the characters the octet readers emit (the binding's
4209  // `\definecolor` name) — which pdfTeX never distinguishes. One spelling
4210  // per name: the decoded one (`mouth::decode_byte_mouth_runs`).
4211  let token = match crate::mouth::decode_byte_mouth_runs(&cs) {
4212    std::borrow::Cow::Borrowed(name) => T_CS!(name),
4213    std::borrow::Cow::Owned(decoded) => T_CS!(decoded),
4214  };
4215  CS_NAME_BUFFER.with(|buffer| buffer.set(cs));
4216  Ok(token)
4217}
4218
4219thread_local! {
4220  /// The buffer [`read_cs_name_inner`] spells a name in, kept across `\csname`s. `ManuallyDrop`: no TLS
4221  /// destructor to register or check on this hot path; the buffer goes with the thread, as the roots do.
4222  static CS_NAME_BUFFER: std::mem::ManuallyDrop<Cell<String>> =
4223    const { std::mem::ManuallyDrop::new(Cell::new(String::new())) };
4224}
4225
4226/// reads and discards tokens, until it encounters a conditional, if any.
4227/// Perl: skipConditionalBody inner loop (Conditional.pm L127-133) reads tokens directly
4228/// from pushback/mouth (NOT through readToken) and manually tracks
4229/// `$LaTeXML::ALIGN_STATE` for `{` and `}`. This loop does not call `read_token` either:
4230/// its expansion and comment handling belong to digestion, and calling it from
4231/// here once let pmatrix's `&` get treated as the OUTER alignment's
4232/// column-end during `\ifx.#1.\else…\fi` skip when `#1` contains
4233/// `\begin{pmatrix}…&…\end{pmatrix}`. (REG-2 / math-ph0501074: the 9-line
4234/// `\nonumber+\lefteqn+\pmatrix` repro.) It does take a column end at a zero count
4235/// for the cell's end, as tex.web's `pass_text` does through `get_next` (§342) and
4236/// Perl does not (KNOWN_PERL_ERRORS #1183).
4237pub fn read_next_conditional() -> Result<Option<(Token, ConditionalType)>> {
4238  loop {
4239    // The FOURTH reader loop over the combined checked read (the `\else`/`\fi`
4240    // skipper — it must not delegate to read_token, whose alignment trigger
4241    // misfires during conditional-skip; see the fn doc). It still needs the
4242    // resource/cycle checkpoints: a skip over a pathologically large stream
4243    // must count progress and remain loop-detectable like every other read
4244    // path (PR #249 review P2-9).
4245    match read_internal_token_checked(CommentSink::Pending)? {
4246      CheckedRead::NoRuntime => return Ok(None),
4247      CheckedRead::Tok(token) => {
4248        let cc = token.get_catcode();
4249        // Perl L128-130: manual ALIGN_STATE tracking for `{` / `}` (avoids
4250        // the trigger check that read_token applies).
4251        match cc {
4252          Catcode::BEGIN => increment_align_group_count(),
4253          Catcode::END => decrement_align_group_count(),
4254          _ => {},
4255        }
4256        // tex.web §342: `pass_text` reads through `get_next`, so a tab or `\cr` met at align_state 0 while a false
4257        // branch is skipped ends the cell all the same: the column's v-part goes in ahead of it (§789,
4258        // `handle_template` raises the count to 1000000) and the skip reads on through it, where its `\fi` can end
4259        // the skip — the hide-column template `>{\iffalse}c<{\fi}` (witness 1504.08100). A column end inside a brace
4260        // group of the skipped text is at a nonzero count and is skipped, as the pmatrix `&` above is. The hidden
4261        // ends (`\lx@hidden@cr`, `\lx@hidden@align`) stand for LaTeX's `\\` and amsmath's tabs, whose `\cr` or `&`
4262        // TeX reaches only by expansion, behind `\relax\iffalse{\fi` (latex.ltx `\@arraycr`), so a skip passes
4263        // them (`\ifnum1<\nb\\\hline\fi`, tabularcalc.sty:428). Guard
4264        // `perfect_kernel_batch80a::a_false_conditional_in_a_template_ends_at_its_v_part`.
4265        if align_group_count() == 0
4266          && has_reading_alignment()
4267          && let Some((_, atype, false)) = is_column_end(&token)
4268          && let Some(reading_alignment) = get_reading_alignment()
4269          && let DigestedData::Alignment(data) = reading_alignment.data()
4270        {
4271          handle_template(data.borrow_mut(), token, atype, false)?;
4272          continue;
4273        }
4274        if cc.is_active_or_cs()
4275          && let Some(cond_type) = lookup_conditional(&token)
4276        {
4277          return Ok(Some((token, cond_type)));
4278        }
4279      },
4280      CheckedRead::Exhausted => {
4281        // The current mouth is exhausted: the skip ENDS here, like Perl's
4282        // `skipConditionalBody` (Core/Definition/Conditional.pm:127), which
4283        // reads `$$gullet{mouth}->readToken()` — the current mouth only —
4284        // and reports "conditional fell off end". Only `read_x_token`'s
4285        // normal reading crosses an input boundary (Perl `readXToken`,
4286        // Gullet.pm:393); `read_token` (above) does not either. Crossing here
4287        // let an `\ifX` left open by an `\input`ed preamble file devour the
4288        // PARENT file's `\begin{document}` through EOF — a 39-byte output
4289        // with no root (thesis-sample; RUST-ONLY, Perl keeps the body). Guard
4290        // `conditional_skip_stops_at_the_input_file_boundary`.
4291        return Ok(None);
4292      },
4293    }
4294  }
4295}
4296
4297//**********************************************************************
4298// Higher-level readers: Read various types of things from the input:
4299//  tokens, non-expandable tokens, args, Numbers, ...
4300//**********************************************************************
4301
4302/// Read and return a "normal" TeX argument
4303///
4304/// The next Token or Tokens (if surrounded by braces).
4305/// `expansion_level` controls expansion as if the argument were read
4306///  and then expanded in isolation:
4307///
4308/// In the case of a single unbraced expandable token,
4309///  it will **not** read any macro arguments from the following input!
4310pub fn read_arg(expansion_level: ExpansionLevel) -> Result<Tokens> {
4311  Ok(read_arg_or_none(expansion_level)?.unwrap_or_default())
4312}
4313
4314/// [`read_arg`] for a required parameter of type `spec`: input that ran out is [`note_missing_argument`]'s, and the
4315/// call runs on the empty argument (Perl's put-back, Parameter.pm:93-97; OD #304).
4316pub fn read_required_arg(expansion_level: ExpansionLevel, spec: &str) -> Result<Tokens> {
4317  match read_arg_or_none(expansion_level)? {
4318    Some(arg) => Ok(arg),
4319    None => {
4320      note_missing_argument(spec, spec)?;
4321      Ok(Tokens::default())
4322    },
4323  }
4324}
4325
4326/// [`read_arg`], or `None` when the input ran out before the argument (Perl `readArg`'s undef, Gullet.pm:735).
4327pub fn read_arg_or_none(expansion_level: ExpansionLevel) -> Result<Option<Tokens>> {
4328  match read_non_space()? {
4329    None => {
4330      // `\foo` as a file's last token, `\foo` taking an argument: a runaway
4331      // argument (tex.web §392), which abandons the call.
4332      Ok(argument_ran_off_a_file()?.then(Tokens::default))
4333    },
4334    // An undelimited argument that is `\par` ends a non-`\long` macro's call (tex.web §392).
4335    Some(token) if is_par_ending_argument(&token) => {
4336      abandon_argument_at_par(token);
4337      Ok(Some(Tokens!()))
4338    },
4339    // A `}` is no undelimited macro argument (tex.web §395; Perl's readArg takes it, Gullet.pm:732), and the `\par`
4340    // inserted for it ends the call. Witness 1012.2852.
4341    Some(token) if is_extra_brace_in_argument(&token) => {
4342      abandon_argument_at_par(insert_par_at_extra_brace(token)?);
4343      Ok(Some(Tokens!()))
4344    },
4345    Some(token) => {
4346      // Perl: $$token[1] == CC_BEGIN — checks actual catcode, NOT defined_as.
4347      // \bgroup (catcode CS) does NOT match here; only literal { does.
4348      if token.get_catcode() == Catcode::BEGIN {
4349        read_balanced(expansion_level, false, false).map(Some)
4350      } else if matches!(expansion_level, ExpansionLevel::Off) {
4351        // A `\noexpand`'d token captured as an (undelimited) macro argument
4352        // reverts to its plain shadowed identity — faithful to TeX, where the
4353        // `no_expand_flag` is transient and never stored in the captured arg
4354        // (`#1` is `cur_cs`, the plain token). This lets `\ifx\X#1` match (xint's
4355        // `\def\XINTfstop{\noexpand\XINTfstop}` f-stop, witness 1804.01117).
4356        // `\let`/`\ifx` of the LIVE token read via `read_token` (the `Token`
4357        // param), NOT here, so their relax-meaning capture is unaffected.
4358        Ok(Some(Tokens!(token.noexpand_shadowed().unwrap_or(token))))
4359      } else {
4360        // Perl Gullet.pm `readArg`:
4361        //   return $self->readingFromMouth(Tokens(T_BEGIN, $token, T_END), sub {
4362        //       readBalanced($self, $expanded, 0, 1); });
4363        // Use an isolated mouth so leftover tokens (e.g. an extra `}` when
4364        // `$token` itself happens to be T_END) cannot leak back into the
4365        // caller's stream. `unread_vec` here would pollute the parent mouth.
4366        let synth = Tokens::new(vec![T_BEGIN!(), token, T_END!()]);
4367        reading_from_mouth(Mouth::default(), move || -> Result<Tokens> {
4368          unread(synth);
4369          read_balanced(expansion_level, false, true)
4370        })
4371        .map(Some)
4372      }
4373    },
4374  }
4375}
4376/// Read and return a LaTeX optional argument
4377///
4378/// returns `default` if there is no '[', otherwise the contents of the array.
4379/// Note that this returns an empty array if `[]` is present,
4380/// i.e. `[contents]` in TeX will lead to `Tokens(contents)`, otherwise returns `None`
4381pub fn read_optional(default: Option<Tokens>) -> Result<Option<Tokens>> {
4382  read_optional_delimited(T_OTHER!("["), T_OTHER!("]"), default)
4383}
4384
4385/// The rest of an xparse `o`/`O{}`/`r[]`/`D<>` argument whose `open` was just read: up to the matching `close`, nested
4386/// pairs and braced groups kept whole, as ltcmd's delimited grab nests them (LaTeX's `\@ifnextchar[` stops at the first).
4387pub fn read_delimited_balanced(open: &Token, close: &Token) -> Result<Tokens> {
4388  Ok(read_delimited_balanced_in(open, close, false)?.0)
4389}
4390
4391/// [`read_delimited_balanced`]; `as_argument`: read as TeX reads a macro's delimited argument at the caller's
4392/// [`ScannerStatus::Matching`] (tex.web §392-399): a `\par` or a `}` ([`insert_par_at_extra_brace`]) ends the call,
4393/// as a file's end does ([`argument_runaway`]). Whether the `close` was met.
4394fn read_delimited_balanced_in(
4395  open: &Token,
4396  close: &Token,
4397  as_argument: bool,
4398) -> Result<(Tokens, bool)> {
4399  let mut depth = 0i32;
4400  let mut toks: Vec<Token> = Vec::new();
4401  let mut inserted: Option<Token> = None;
4402  loop {
4403    let Some(tok) = inserted
4404      .take()
4405      .map_or_else(read_token, |par| Ok(Some(par)))?
4406    else {
4407      if as_argument {
4408        argument_ran_off_a_file()?;
4409      }
4410      return Ok((Tokens::new(toks), false));
4411    };
4412    if tok == *close {
4413      if depth == 0 {
4414        return Ok((Tokens::new(toks), true));
4415      }
4416      depth -= 1;
4417    } else if as_argument && is_par_ending_argument(&tok) {
4418      abandon_argument_at_par(tok);
4419      return Ok((Tokens::new(toks), false));
4420    } else if as_argument && is_extra_brace_in_argument(&tok) {
4421      inserted = Some(insert_par_at_extra_brace(tok)?);
4422      continue;
4423    } else if tok == *open {
4424      depth += 1;
4425    } else if tok.get_catcode() == Catcode::BEGIN {
4426      toks.push(tok);
4427      toks.extend(read_balanced(ExpansionLevel::Off, false, false)?.unlist());
4428      if as_argument && argument_runaway() {
4429        return Ok((Tokens::new(toks), false));
4430      }
4431      toks.push(T_END!());
4432      continue;
4433    }
4434    toks.push(tok);
4435  }
4436}
4437
4438/// ltcmd's `\__cmd_peek_nonspace_remove:NTF` (latex.ltx:4475-4482): whether the next token past spaces means
4439/// `target`, peeked unexpanded; if so it goes with the spaces, else one explicit space per space taken goes back.
4440pub fn peek_nonspace_remove(target: &Token) -> Result<bool> {
4441  let _tabs = SuppressedTabMarks::for_argument_scan();
4442  let space = T_SPACE!();
4443  let mut spaces = 0;
4444  while let Some(token) = read_token()? {
4445    if token.defined_as(&space) {
4446      spaces += 1;
4447      continue;
4448    }
4449    if token.defined_as(target) {
4450      return Ok(true);
4451    }
4452    unread_one(token);
4453    break;
4454  }
4455  for _ in 0..spaces {
4456    unread_one(space);
4457  }
4458  Ok(false)
4459}
4460
4461/// ltcmd's `s` argument (`\__cmd_grab_t:w`, latex.ltx:3816): a `*` past spaces.
4462pub fn read_ltcmd_star() -> Result<bool> { peek_nonspace_remove(&T_OTHER!("*")) }
4463
4464/// ltcmd's `o` argument (`\__cmd_grab_D_aux:NNnNN`, latex.ltx:3594-3651) of the command `cs`: `[…]` past spaces, to
4465/// the matching explicit `]` ([`read_delimited_balanced`]), one brace pair around the whole of it stripped; `Some(None)`
4466/// when absent. Read as the non-`\long` delimited macro ltcmd grabs it with (`\cs_set_protected_nopar:Npn`): a `\par`,
4467/// a `}` or a file's end in it ends the call, `None`, with TeX's Error naming `cs` (tex.web §395-396, §338).
4468pub fn read_ltcmd_optional(cs: Token) -> Result<Option<Option<Tokens>>> {
4469  let open = T_OTHER!("[");
4470  if !peek_nonspace_remove(&open)? {
4471    return Ok(Some(None));
4472  }
4473  let _tabs = SuppressedTabMarks::for_argument_scan();
4474  let matching = set_scanner_status_checking_par(ScannerStatus::Matching, Some(cs), true);
4475  let (arg, closed) = read_delimited_balanced_in(&open, &T_OTHER!("]"), true)?;
4476  match matching.end_taking_runaway_argument() {
4477    Some(runaway) => {
4478      abandon_runaway_call(cs, false, true, runaway)?;
4479      return Ok(None);
4480    },
4481    // (the end of all input, where no file encloses the read)
4482    None if !closed => {
4483      abandon_runaway_call(cs, false, true, Runaway::TrueEnd { first: true })?;
4484      return Ok(None);
4485    },
4486    None => {},
4487  }
4488  let v = arg.unlist_ref();
4489  // (one group: its first brace closes at the last token)
4490  let mut depth = 0;
4491  let one_group = v.len() >= 2
4492    && v.iter().enumerate().all(|(i, t)| {
4493      depth += t.group_step();
4494      depth > 0 || i + 1 == v.len()
4495    });
4496  Ok(Some(Some(if one_group {
4497    Tokens::new(v[1..v.len() - 1].to_vec())
4498  } else {
4499    arg
4500  })))
4501}
4502
4503/// The angle-bracket twin of [`read_optional`].
4504///
4505/// Perl `beamer.cls.ltxml` L50-57 `readBeamerAngled` (backing its
4506/// `BeamerAngled` / `OptionalBeamerAngled` parameter types) does exactly this.
4507/// The angle-bracket optional is not beamer-specific — apacite spells its
4508/// citation pre-note that way (`\cite<see>[p.5]{key}`, apacite.sty L313
4509/// `\def\@cite<#1>`), so it lives here beside `read_optional`.
4510pub fn read_optional_angled(default: Option<Tokens>) -> Result<Option<Tokens>> {
4511  read_optional_delimited(T_OTHER!("<"), T_OTHER!(">"), default)
4512}
4513
4514/// Shared core of [`read_optional`] / [`read_optional_angled`]: if the next
4515/// non-space token is the `open` delimiter, read up to (and consuming) `close`;
4516/// otherwise unread the token and yield `default`.
4517///
4518/// The peek/unread contract is the whole point, and is why an optional
4519/// delimited argument must NOT be spelled `OptionalMatch:x OptionalUntil:y`:
4520/// `Until` never checks for the OPENING delimiter, so when the argument is
4521/// absent it scans to the next `y` ANYWHERE downstream (`\citeA{Smith} and
4522/// $a > b$` swallows the cite and the math, yielding the key `b`).
4523fn read_optional_delimited(
4524  open: Token,
4525  close: Token,
4526  default: Option<Tokens>,
4527) -> Result<Option<Tokens>> {
4528  match read_non_space()? {
4529    None => Ok(None),
4530    // `Token`'s `PartialEq` compares catcode + text (and deliberately NOT the
4531    // token-locators origin handle), so this is the catcode-and-symbol match
4532    // the delimiters need.
4533    Some(t) => {
4534      if t == open {
4535        // Optional-content EOF degrades to empty (prior behavior): the
4536        // Missing-argument discipline belongs to REQUIRED Until params.
4537        Ok(Some(read_until(&Tokens!(close))?.unwrap_or_default()))
4538      } else {
4539        unread_one(t);
4540        Ok(default)
4541      }
4542    },
4543  }
4544}
4545
4546/// `<filler> = <optional spaces> | <filler>\relax<optional spaces>`
4547///
4548/// TeX Book p.276 "`<left brace>` can be implicit", and experimentation, indicate Expansion!!!
4549pub fn skip_filler() -> Result<()> {
4550  while let Some(tok) = read_x_non_space()? {
4551    if !tok.defined_as(&TOKEN_RELAX) {
4552      unread_one(tok);
4553      break;
4554    }
4555  }
4556  Ok(())
4557}
4558
4559pub fn if_next(token: Token) -> Result<bool> {
4560  let mut is_next = false;
4561  if let Some(tok) = read_token()? {
4562    is_next = tok == token;
4563    unread_one(tok);
4564  }
4565  Ok(is_next)
4566}
4567
4568/// Perl: peekToken — peek at the next token without triggering alignment
4569/// Sets ALIGN_STATE to 1000000 to suppress alignment template handling (Perl line 331-337)
4570pub fn peek_token() -> Result<Option<Token>> {
4571  local_align_group_count(1000000);
4572  let result = read_token()?;
4573  if let Some(ref tok) = result {
4574    unread_one(*tok);
4575  }
4576  expire_align_group_count();
4577  Ok(result)
4578}
4579
4580/// Perl: showUnexpected — returns a debug message about the next available token
4581pub fn show_unexpected() -> String {
4582  match peek_token() {
4583    Ok(Some(token)) => {
4584      let meaning = lookup_meaning(&token)
4585        .map(|m| format!("{:?}", m))
4586        .unwrap_or_else(|| "undef".to_string());
4587      s!("Next token is {} ( == {})", token.stringify(), meaning)
4588    },
4589    _ => "Input is empty".to_string(),
4590  }
4591}
4592
4593//**********************************************************************
4594//  Numbers, Dimensions, Glue
4595// See TeXBook, Ch.24, pp.269-271.
4596//**********************************************************************
4597
4598pub fn read_value(value_type: RegisterType) -> Result<RegisterValue> {
4599  match value_type {
4600    RegisterType::Number => Ok(read_number()?.into()),
4601    RegisterType::Dimension => Ok(read_dimension()?.into()),
4602    RegisterType::MuDimension => Ok(read_mu_dimension()?.into()),
4603    RegisterType::Glue => Ok(read_glue()?.into()),
4604    RegisterType::MuGlue => Ok(read_mu_glue()?.into()),
4605    RegisterType::Tokens => Ok(read_tokens_value()?.into()),
4606    RegisterType::Token => {
4607      // The token registers are the family ones (`\textfont`, `\scriptfont`, `\scriptscriptfont`), whose value TeX
4608      // reads with tex.web §577 `scan_font_ident`: expanded (`get_x_token`), so a `\csname`, a macro (`\protected`
4609      // too) or an `\expandafter` reaches the family branch (Perl Gullet.pm:770-775 reads unexpanded but for
4610      // `\csname`, KNOWN_PERL_ERRORS #1271).
4611      let token = read_non_blank_non_call()?.unwrap_or(*TOKEN_RELAX);
4612      // `def_family`: `\textfont9=\textfont1` is family 1's font (Perl took `\textfont` and left the "1" to print,
4613      // 2511.21986)
4614      if let Some(defn) = lookup_register_definition(&token)
4615        && matches!(defn.register_type(), Some(RegisterType::Token))
4616      {
4617        let args = defn.read_arguments()?;
4618        return Ok(defn.value_of(args).unwrap_or_else(|| token.into()));
4619      }
4620      Ok(token.into())
4621    },
4622    RegisterType::CharDef => Ok(read_number()?.into()),
4623    RegisterType::Any => Ok(read_arg(ExpansionLevel::Off)?.into()),
4624  }
4625}
4626
4627/// A package-installed resolver for control sequences that yield an *internal
4628/// dimension* by reading their own argument — e.g. calc.sty's `\widthof{box}`.
4629/// Given the already-read CS token, it either consumes that CS's argument(s)
4630/// from the gullet and returns the measured value (`Ok(Some(_))`), or leaves
4631/// the stream untouched and declines (`Ok(None)`), in which case the caller
4632/// un-reads the token. Keeps core calc-agnostic: the base dimension reader
4633/// consults this seam before giving up with "Missing number", so
4634/// `\makebox[\widthof{X}]` / `\rule{\widthof{X}}{…}` resolve like real LaTeX
4635/// without `\widthof` having to be a register (which would change its bare
4636/// digestion). See `calc_sty.rs` / OXIDIZED_DESIGN #115.
4637pub type InternalDimensionFn = std::rc::Rc<dyn Fn(&Token) -> Result<Option<RegisterValue>>>;
4638
4639thread_local! {
4640  static INTERNAL_DIMENSION_FN: RefCell<Option<InternalDimensionFn>> = const { RefCell::new(None) };
4641}
4642
4643/// Install the internal-dimension resolver (calc.sty at load time).
4644pub fn set_internal_dimension_fn(f: InternalDimensionFn) {
4645  INTERNAL_DIMENSION_FN.with(|c| *c.borrow_mut() = Some(f));
4646}
4647
4648/// Consult the installed resolver for `tok`. `Ok(None)` when none is installed,
4649/// the document has not loaded calc ([`calc_expressions_active`]), or it
4650/// declines; `tok` is left for the caller to un-read in that case.
4651fn resolve_internal_dimension(tok: &Token) -> Result<Option<RegisterValue>> {
4652  if !calc_expressions_active() {
4653    return Ok(None);
4654  }
4655  let f = INTERNAL_DIMENSION_FN.with(|c| c.borrow().clone());
4656  match f {
4657    Some(f) => f(tok),
4658    None => Ok(None),
4659  }
4660}
4661
4662/// A package-installed evaluator for a braced LENGTH argument — calc.sty's
4663/// expression scanner. latex.ltx hands every user length to `\setlength`
4664/// (`\@hspace`, `\@imakebox`, `\@rule`, `\@iiiparbox`, `\@iiiminipage`, array's
4665/// `\@startpbox`: latex.ltx:9425, 16099-16102, 16360-16366, 16249, 16305), and
4666/// calc redefines `\setlength` to evaluate its whole argument as an expression
4667/// (calc.sty:86, `\calc@assign@skip` → `\calc@open(#4!`, :51-53). A binding's
4668/// `{Dimension}`/`{Glue}` argument is that `\setlength` operand, so with calc
4669/// loaded [`crate::parameter::Parameters::reparse_argument`] evaluates it here:
4670/// `\makebox[\widthof{ab}+\widthof{cd}]` gets the sum, not the first term. The
4671/// evaluator reads from the argument's own mouth, leaving unread whatever calc
4672/// could not parse (after reporting it, as calc.sty:281-284 does).
4673pub type BracedLengthFn = std::rc::Rc<dyn Fn(RegisterType) -> Result<RegisterValue>>;
4674
4675thread_local! {
4676  static BRACED_LENGTH_FN: RefCell<Option<BracedLengthFn>> = const { RefCell::new(None) };
4677}
4678
4679/// The State flag calc's binding sets when it loads. The resolvers above are
4680/// thread-local closures that outlive a document; this per-document flag keeps
4681/// them from reaching a later document on the same thread that never loaded calc.
4682const CALC_EXPRESSIONS: &str = "calc_expressions";
4683
4684/// Install the braced-length evaluator and switch the calc seams on for the
4685/// current document (calc.sty at load time).
4686pub fn set_braced_length_fn(f: BracedLengthFn) {
4687  BRACED_LENGTH_FN.with(|c| *c.borrow_mut() = Some(f));
4688  assign_value(CALC_EXPRESSIONS, true, Some(Scope::Global));
4689}
4690
4691/// Whether the current document loaded calc, whose seams
4692/// ([`set_internal_dimension_fn`], [`set_braced_length_fn`]) are then in force.
4693pub fn calc_expressions_active() -> bool { lookup_bool(CALC_EXPRESSIONS) }
4694
4695/// The braced-length evaluator, when the current document loaded calc.
4696pub fn braced_length_evaluator() -> Option<BracedLengthFn> {
4697  if calc_expressions_active() {
4698    BRACED_LENGTH_FN.with(|c| c.borrow().clone())
4699  } else {
4700    None
4701  }
4702}
4703
4704/// Take everything still unread in the CURRENT mouth — its pushback, then the
4705/// rest of its source — as raw tokens, leaving it exhausted. The enclosing
4706/// input is untouched. This is how a braced argument hands back what followed
4707/// the quantity scanned from it ([`crate::parameter::Parameters::reparse_argument`]):
4708/// TeX leaves that tail in the input (`\setlength#1#2{#1 #2\relax}`,
4709/// latex.ltx:10253). The tokens count as READ for the alignment brace ledger
4710/// (as [`read_token`] counts them), so a caller that puts them back uses
4711/// [`unread_vec`], which retracts them again.
4712pub fn take_rest_of_mouth() -> Vec<Token> {
4713  let rest = {
4714    let mut g = gullet_mut!();
4715    let Some(runtime) = g.runtime.as_mut() else {
4716      return Vec::new();
4717    };
4718    // The pushback is a stack whose LAST element is read next.
4719    let mut rest: Vec<Token> = runtime.pushback.drain(..).rev().collect();
4720    runtime.watch.note_len(0);
4721    rest.extend(runtime.mouth.read_tokens().unlist());
4722    rest
4723  };
4724  let level: i32 = rest
4725    .iter()
4726    .map(|token| match token.get_catcode() {
4727      Catcode::BEGIN => 1,
4728      Catcode::END => -1,
4729      _ => 0,
4730    })
4731    .sum();
4732  if level != 0 {
4733    set_align_group_count(align_group_count() + level);
4734  }
4735  rest
4736}
4737
4738pub fn read_register_value(value_type: RegisterType) -> Result<Option<RegisterValue>> {
4739  read_register_value_coerce(value_type, false)
4740}
4741
4742/// Read a register value, optionally coercing from a compatible larger type.
4743/// Perl: readRegisterValue($self, $type, $sign, $coerce)
4744/// Coercion rules (from Perl %RegisterCoercionTypes):
4745///   Number    <- Dimension, Glue     (extract raw i64)
4746///   Dimension <- Glue                (extract skip as Dimension)
4747///   MuDimension <- MuGlue            (extract skip as MuDimension)
4748pub fn read_register_value_coerce(
4749  value_type: RegisterType,
4750  coerce: bool,
4751) -> Result<Option<RegisterValue>> {
4752  match read_x_token(None, false, None)? {
4753    None => Ok(None),
4754    Some(token) => match register_value_from(token, value_type, coerce)? {
4755      Scanned::Value(value) => Ok(value),
4756      Scanned::Declined(token) => {
4757        unread_one(token); // Unread
4758        Ok(None)
4759      },
4760    },
4761  }
4762}
4763
4764/// What a token in hand introduces where a quantity is scanned.
4765enum Scanned<T> {
4766  /// A quantity of the kind (its tokens read): its value, if it has one.
4767  Value(Option<T>),
4768  /// No quantity of the kind: the token, not consumed.
4769  Declined(Token),
4770}
4771
4772/// The register value of `value_type` that `token` (already read with expansion, TeX's
4773/// `cur_tok`) introduces, or the token back when it introduces none: `scan_int` and
4774/// `scan_dimen` test the token in hand for each kind of quantity in turn (tex.web §413, §440,
4775/// §448) instead of putting it back between the tests.
4776fn register_value_from(
4777  token: Token,
4778  value_type: RegisterType,
4779  coerce: bool,
4780) -> Result<Scanned<RegisterValue>> {
4781  match lookup_register_definition(&token) {
4782    Some(defn) => {
4783      if let Some(mut register_type) = defn.register_type() {
4784        if register_type == RegisterType::CharDef {
4785          // CharDefs treated as numbers here
4786          register_type = RegisterType::Number;
4787        }
4788        if register_type == value_type {
4789          let args = defn.read_arguments()?;
4790          let value = defn.value_of(args);
4791          crate::cycle_guard::note_value(value.as_ref());
4792          Ok(Scanned::Value(value))
4793        } else if coerce {
4794          // Try type coercion per Perl's %RegisterCoercionTypes
4795          Ok(match coerce_register(value_type, register_type, &defn)? {
4796            Some(coerced) => {
4797              crate::cycle_guard::note_value(Some(&coerced));
4798              Scanned::Value(Some(coerced))
4799            },
4800            None => Scanned::Declined(token),
4801          })
4802        } else {
4803          Ok(Scanned::Declined(token))
4804        }
4805      } else {
4806        Ok(Scanned::Declined(token))
4807      }
4808    },
4809    _ => {
4810      // calc.sty seam: `\widthof{box}` &friends yield an internal dimension
4811      // by reading their own argument. Only in dimension-like contexts
4812      // (calc errors "not expected here" for a Number). On decline the
4813      // resolver leaves the stream untouched, so the token is handed back.
4814      // OXIDIZED_DESIGN #115.
4815      if value_type != RegisterType::Number
4816        && let Some(rv) = resolve_internal_dimension(&token)?
4817      {
4818        return Ok(Scanned::Value(Some(rv)));
4819      }
4820      Ok(Scanned::Declined(token))
4821    },
4822  }
4823}
4824
4825/// Attempt to coerce a register value from `source_type` to `target_type`.
4826fn coerce_register(
4827  target_type: RegisterType,
4828  source_type: RegisterType,
4829  defn: &Register,
4830) -> Result<Option<RegisterValue>> {
4831  use crate::common::numeric_ops::NumericOps;
4832  // Perl fix 50f0061d: include self-coercions (Number→Number, etc.)
4833  // so \number \fam works when \fam is already a Number register
4834  let can_coerce = matches!(
4835    (target_type, source_type),
4836    (RegisterType::Number, RegisterType::Number)
4837      | (RegisterType::Number, RegisterType::Dimension)
4838      | (RegisterType::Number, RegisterType::Glue)
4839      | (RegisterType::Dimension, RegisterType::Dimension)
4840      | (RegisterType::Dimension, RegisterType::Glue)
4841      | (RegisterType::MuDimension, RegisterType::MuDimension)
4842      | (RegisterType::MuDimension, RegisterType::MuGlue)
4843      | (RegisterType::Glue, RegisterType::Glue)
4844      | (RegisterType::MuGlue, RegisterType::MuGlue)
4845  );
4846  if !can_coerce {
4847    return Ok(None);
4848  }
4849  let args = defn.read_arguments()?;
4850  if let Some(val) = defn.value_of(args) {
4851    let raw = match val {
4852      RegisterValue::Dimension(d) => d.value_of(),
4853      RegisterValue::Glue(g) => g.value_of(),
4854      RegisterValue::MuGlue(mg) => mg.value_of(),
4855      RegisterValue::Number(n) => n.value_of(),
4856      RegisterValue::MuDimension(md) => md.value_of(),
4857      _ => return Ok(None),
4858    };
4859    let coerced = match target_type {
4860      RegisterType::Number => RegisterValue::Number(Number::new(raw)),
4861      RegisterType::Dimension => RegisterValue::Dimension(Dimension::new(raw)),
4862      RegisterType::MuDimension => RegisterValue::MuDimension(MuDimension::new(raw)),
4863      _ => return Ok(None),
4864    };
4865    Ok(Some(coerced))
4866  } else {
4867    Ok(None)
4868  }
4869}
4870
4871/// Match the input against one of the Token or Tokens in @choices; return the matching one or
4872/// undef.
4873pub fn read_match(choices: &[&Tokens]) -> Result<Option<Tokens>> {
4874  for choice in choices {
4875    let mut to_match: Vec<&Token> = choice.unlist_ref().iter().rev().collect();
4876    // `matched` accumulates tokens read so far, bounded by `choice.len()`.
4877    // Pre-size to avoid reallocations on multi-token match attempts.
4878    let mut matched = Vec::with_capacity(choice.unlist_ref().len());
4879    while !to_match.is_empty() {
4880      match read_token()? {
4881        None => break,
4882        Some(token) => {
4883          // Perl: also check smuggled \special_relax token (Gullet.pm line 612)
4884          let was_last_match = if let Some(&&want) = to_match.last() {
4885            token == want || special_relax_matches(&token, &want)
4886          } else {
4887            false
4888          };
4889          matched.push(token);
4890          if was_last_match {
4891            to_match.pop();
4892          } else {
4893            break;
4894          }
4895          // A space in the delimiter matches exactly one space token (tex.web §392:
4896          // the delimiter tokens are matched one for one). Perl then skips every
4897          // following space (Gullet.pm:614-617, KNOWN_PERL_ERRORS #222), which eats the
4898          // space xint's `\XINT_zapsp_b`-style macros leave for the next call: a `\def`
4899          // prefix delimiter `\B<space>` met by `\B<space><space>X` must leave
4900          // `<space>X` (pdflatex `| X|`, Perl `|X|`).
4901        },
4902      }
4903    }
4904    if to_match.is_empty() {
4905      return Ok(Some((*choice).clone())); // All matched!!!
4906    } else {
4907      // Put 'em back and try next — use unread_vec for proper agc adjustment
4908      unread_vec(matched);
4909    }
4910  }
4911  Ok(None)
4912}
4913
4914//======================================================================
4915// Integer, Number
4916//======================================================================
4917// ```
4918// <number> = <optional signs><unsigned number>
4919// <unsigned number> = <normal integer> | <coerced integer>
4920// <coerced integer> = <internal dimen> | <internal glue>
4921// ```
4922pub fn read_number() -> Result<Number> {
4923  let _scan = NumberScan::begin();
4924  // tex.web §440 scan_int: the signs, then the token after them (cur_tok) is tested in hand for
4925  // each kind of number, never put back between the tests. A register read without a value
4926  // consumed its tokens, so the next kind is tried on a fresh token (as Perl's chain of reads).
4927  let (is_negative, mut hand) = scan_optional_signs()?;
4928  let s = if is_negative { -1 } else { 1 };
4929  for attempt in 0..2 {
4930    if let Some(token) = in_hand_or_read(hand.take())? {
4931      match normal_integer_from(token)? {
4932        Scanned::Value(Some(n)) => return Ok(if is_negative { n.negate() } else { n }),
4933        Scanned::Value(None) => {},
4934        Scanned::Declined(token) => hand = Some(token),
4935      }
4936    }
4937    if let Some(token) = in_hand_or_read(hand.take())? {
4938      match register_value_from(token, RegisterType::Dimension, false)? {
4939        Scanned::Value(Some(n)) => return Ok(Number::new(s * Dimension::from(n).value_of())),
4940        Scanned::Value(None) => {},
4941        Scanned::Declined(token) => hand = Some(token),
4942      }
4943    }
4944    if let Some(token) = in_hand_or_read(hand.take())? {
4945      match register_value_from(token, RegisterType::Glue, false)? {
4946        Scanned::Value(Some(n)) => return Ok(Number::new(s * Glue::from(n).value_of())),
4947        Scanned::Value(None) => {},
4948        Scanned::Declined(token) => hand = Some(token),
4949      }
4950    }
4951    match hand.take() {
4952      Some(token) if attempt == 0 && became_expandable(&token)? => unread_one(token),
4953      other => {
4954        hand = other;
4955        break;
4956      },
4957    }
4958  }
4959  {
4960    let next = match hand {
4961      Some(token) => Some(token),
4962      None => read_token()?,
4963    };
4964    // Perl Gullet.pm:904-905: the primary message is just "Missing number,
4965    // treated as zero"; the processing context and the unexpected-token
4966    // (showUnexpected) are SEPARATE Error details rendered on their own
4967    // lines. Render the tokens with ToString/Stringify, not Rust-Debug
4968    // (which leaks `Some("\\relax")` into user-facing diagnostics).
4969    let current = get_current_token()
4970      .map(|t| t.to_string())
4971      .unwrap_or_default();
4972    let unexpected = match next {
4973      Some(t) => s!("Next token is {}", t.stringify()),
4974      None => s!("Input is empty"),
4975    };
4976    Warn!(
4977      "expected",
4978      "<number>",
4979      "Missing number, treated as zero",
4980      s!("while processing {current}"),
4981      unexpected
4982    );
4983    if let Some(next) = next {
4984      unread_one(next);
4985    }
4986    Ok(Number::new(0))
4987  }
4988}
4989
4990/// ```bnf
4991/// <normal integer> = <internal integer> | <integer constant>
4992///   | '<octal constant><one optional space> | "<hexadecimal constant><one optional space>
4993///   | `<character token><one optional space>
4994/// ```
4995pub fn read_normal_integer() -> Result<Option<Number>> {
4996  match read_x_token(None, false, None)? {
4997    None => Ok(None),
4998    Some(token) => match normal_integer_from(token)? {
4999      Scanned::Value(value) => Ok(value),
5000      Scanned::Declined(token) => {
5001        unread_one(token); // Unread
5002        Ok(None)
5003      },
5004    },
5005  }
5006}
5007
5008/// tex.web §445: an integer constant (decimal, octal or hexadecimal) of 2^31 or
5009/// more is "Number too big", and its value is `infinity` = 2^31 − 1. An Error,
5010/// as TeX's: the recovered value is not the author's (OXIDIZED_DESIGN #519).
5011fn number_too_big(n: i64) -> Result<i64> {
5012  if n > MAX_INTEGER {
5013    Error!(
5014      "expected",
5015      "<number>",
5016      "Number too big.",
5017      s!("{n} clamped to {MAX_INTEGER} (tex.web §445)")
5018    );
5019    Ok(MAX_INTEGER)
5020  } else {
5021    Ok(n)
5022  }
5023}
5024
5025/// tex.web §460 `attach_sign`: a scanned dimension whose magnitude reaches
5026/// 2^30 sp (`arith_error`, or `abs(cur_val) >= @'10000000000`) is "Dimension
5027/// too large", and its value is `max_dimen` (16383.99998pt), negated only for
5028/// the scan's own `<optional signs>` (`negative`) — a negative internal unit
5029/// (`2000000000\dimen0` with `\dimen0` < 0) gives +max_dimen, as pdfTeX
5030/// prints it. `scaled` is the fixed-point product, `Err(_)` when it left the
5031/// i64 range. An Error, as for [`number_too_big`], a Warning in a box measured by our approximation
5032/// ([`approximated_measure`]).
5033fn dimension_too_large(scaled: std::result::Result<i64, i64>, negative: bool) -> Result<i64> {
5034  match scaled {
5035    Ok(v) if v.abs() <= MAX_DIMEN => Ok(v),
5036    _ => {
5037      let detail = "clamped to max_dimen (tex.web §460)";
5038      match approximated_measure() {
5039        Some((ours, true)) => Warn!("expected", "<dimen>", "Dimension too large.", detail, ours),
5040        Some((ours, false)) => Info!("expected", "<dimen>", "Dimension too large.", detail, ours),
5041        None => Error!("expected", "<dimen>", "Dimension too large.", detail),
5042      }
5043      Ok(if negative { -MAX_DIMEN } else { MAX_DIMEN })
5044    },
5045  }
5046}
5047
5048/// <normal integer> from the token in hand (TeX's `cur_tok`, read with expansion), or the token
5049/// back when it starts none.
5050fn normal_integer_from(token: Token) -> Result<Scanned<Number>> {
5051  let cc = token.get_catcode();
5052  // tex.web §440-448 `scan_int` inspects the token's command/char codes
5053  // and never stringifies it; the decimal arm is the only one that needs
5054  // the text, so the common internal-quantity case (`\pgf@x`, a count
5055  // register) pays no String — this ran once per number read.
5056  let is_decimal_start = cc == Catcode::OTHER
5057    && token.with_str(|s| !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()));
5058  if is_decimal_start {
5059    // Read decimal literal, accumulating the digits as tex.web §444-445
5060    // does (no string). The accumulation saturates at i64::MAX; the
5061    // constant is then held to TeX's `infinity` (`number_too_big`).
5062    let mut n = token.with_str(|s| s.parse::<i64>().unwrap_or(i64::MAX));
5063    let end = loop {
5064      let Some(next) = read_x_token(None, false, None)? else {
5065        break None;
5066      };
5067      let digit = next.with_str(|s| {
5068        let mut chars = s.chars();
5069        match (chars.next(), chars.next()) {
5070          (Some(c), None) => c.to_digit(10),
5071          _ => None,
5072        }
5073      });
5074      match digit {
5075        Some(d) => {
5076          n = n
5077            .checked_mul(10)
5078            .and_then(|v| v.checked_add(i64::from(d)))
5079            .unwrap_or(i64::MAX)
5080        },
5081        None => break Some(next),
5082      }
5083    };
5084    // <one optional space> (`read_digits`' skip).
5085    if let Some(end) = end
5086      && !is_space_or_implicit_space(&end)
5087    {
5088      unread_scanned(end);
5089    }
5090    Ok(Scanned::Value(Some(Number::new(number_too_big(n)?))))
5091  } else if token == T_OTHER!("'") {
5092    // Read Octal literal. Perl: `Number(oct(readDigits(...)))`, and
5093    // Perl's `oct("")` is 0 — so a `'` with no octal digit following
5094    // yields 0 (TeX's "Missing number, treated as zero"), NOT a fatal
5095    // error. Mirror that, and clamp overflow to i64::MAX like the
5096    // decimal arm rather than propagating a ParseIntError.
5097    let digits = read_digits(is_octal_digit, true)?;
5098    let decimal = if digits.is_empty() {
5099      0
5100    } else {
5101      i64::from_str_radix(&digits, 8).unwrap_or(i64::MAX)
5102    };
5103    Ok(Scanned::Value(Some(Number::new(number_too_big(decimal)?))))
5104  } else if token == T_OTHER!("\"") {
5105    //  Read Hex literal. Perl: `Number(hex(readDigits(...)))`, and
5106    // Perl's `hex("")` is 0 — so a `"` with no hex digit following
5107    // yields 0, NOT a fatal error. (Witness 2008.10843: mdwmath.sty
5108    // raw-load reads a bare `"` with no hex digit → previously a
5109    // `Fatal:Document:Generic(ParseIntError)` aborting the run.)
5110    let digits = read_digits(is_hex_digit, true)?;
5111    let decimal = if digits.is_empty() {
5112      0
5113    } else {
5114      i64::from_str_radix(&digits, 16).unwrap_or(i64::MAX)
5115    };
5116    Ok(Scanned::Value(Some(Number::new(number_too_big(decimal)?))))
5117  } else if token == T_OTHER!("`") {
5118    //  Read Charcode: `<character token><one optional space>
5119    // The leading `\` is stripped only from a control-sequence token
5120    // (`\a` → 'a', `\\` → '\'). Perl (Gullet.pm L926 `s/^\\//`) strips
5121    // it from a catcode-12 backslash *character* too, so `` `\ `` after
5122    // `\detokenize`/`\string` reads as 0 instead of TeX's 92 — see
5123    // KNOWN_PERL_ERRORS "backquote charcode of a detokenized backslash"
5124    // (witness bibleref-parse.sty L481-486 `\brp@ifcs`).
5125    let (mut s, is_cs) = match read_token()? {
5126      None => (String::new(), false),
5127      Some(next) => {
5128        // tex.web §442: a brace read as a character constant is NOT a
5129        // group for ALIGN_STATE — `get_token` counted it, so undo that.
5130        // This is what makes the `\iffalse{\fi\ifnum0=`}\fi` idiom
5131        // (expl3 `\group_align_safe_begin:`, amsmath) leave align_state
5132        // +1 with no group open, so an alignment-catcode token inside
5133        // a delimited-macro definition in a tabular cell (l3tl
5134        // `\tl_replace_all` with a rescanned `_`(4), l3doc `\marg` in
5135        // `syntax`) is not mistaken for the cell end. Perl Gullet.pm:926
5136        // omits the undo (SHARED).
5137        match next.get_catcode() {
5138          Catcode::BEGIN => decrement_align_group_count(),
5139          Catcode::END => increment_align_group_count(),
5140          _ => {},
5141        }
5142        // A space token's character code is 32 whatever its text
5143        // (tex.web §289; an end-of-line space carries "\n" — batch 56gc,
5144        // the same normalization as `Token::get_charcode`).
5145        if next.get_catcode() == Catcode::SPACE {
5146          (" ".to_string(), false)
5147        } else {
5148          (next.to_string(), next.get_catcode() == Catcode::CS)
5149        }
5150      },
5151    };
5152    if is_cs && s.starts_with('\\') {
5153      s.remove(0);
5154    }
5155    let s_char = s.chars().next().unwrap_or('\0');
5156    // Perl: skip1Space($self, 1); — expanded space-skip after charcode
5157    skip_one_space(true)?;
5158    Ok(Scanned::Value(Some(Number::new(s_char as i64)))) //  Only a character token!!! NOT expanded!!!!
5159  } else {
5160    Ok(
5161      match register_value_from(token, RegisterType::Number, false)? {
5162        Scanned::Value(value) => Scanned::Value(value.map(Number::from)),
5163        Scanned::Declined(token) => Scanned::Declined(token),
5164      },
5165    )
5166  }
5167}
5168
5169///======================================================================
5170/// Float, a floating point number.
5171/// Similar to factor, but does NOT accept comma!
5172/// This is NOT part of TeX, but is convenient.
5173pub fn read_float() -> Result<Float> {
5174  let _scan = NumberScan::begin();
5175  let is_negative = read_optional_signs()?;
5176  let s = if is_negative { -1.0 } else { 1.0 };
5177  let mut string = read_digits(is_decimal_digit, true)?;
5178  let mut token = read_x_token(None, false, None)?;
5179  if token.is_some() && token.as_ref().unwrap().get_sym() == pin!(".") {
5180    string = s!("{string}.{}", read_digits(is_decimal_digit, true)?);
5181    token = read_x_token(None, false, None)?;
5182  }
5183  let n_opt: Option<f64> = if !string.is_empty() {
5184    if let Some(t) = token
5185      && t.get_catcode() != Catcode::SPACE
5186    {
5187      unread_one(t);
5188    }
5189    // Same rationale as read_normal_integer above: malformed float
5190    // literals (e.g. very long digit runs, "1e" without exponent)
5191    // should degrade to 0.0 rather than panic.
5192    Some(string.parse::<f64>().unwrap_or(0.0))
5193  } else {
5194    if let Some(t) = token {
5195      unread_one(t); // Unread
5196    }
5197    read_normal_integer()?.map(|v| v.value_of() as f64)
5198  };
5199
5200  if let Some(n) = n_opt {
5201    Ok(Float::new_f64(s * n))
5202  } else {
5203    Ok(Float::new_f64(0.0))
5204  }
5205}
5206
5207fn read_internal_integer() -> Result<Option<Number>> {
5208  match read_register_value(RegisterType::Number)? {
5209    None => Ok(None),
5210    Some(val) => Ok(Some(val.into())),
5211  }
5212}
5213fn read_internal_dimension() -> Result<Option<Dimension>> {
5214  match read_register_value(RegisterType::Dimension)? {
5215    None => Ok(None),
5216    Some(val) => Ok(Some(val.into())),
5217  }
5218}
5219fn read_internal_glue() -> Result<Option<Glue>> {
5220  match read_register_value(RegisterType::Glue)? {
5221    None => Ok(None),
5222    Some(val) => Ok(Some(val.into())),
5223  }
5224}
5225
5226//======================================================================
5227// Dimensions
5228//======================================================================
5229// ```
5230// <dimen> = <optional signs><unsigned dimen>
5231// <unsigned dimen> = <normal dimen> | <coerced dimen>
5232// <coerced dimen> = <internal glue>
5233// ```
5234pub fn read_dimension() -> Result<Dimension> {
5235  let _scan = NumberScan::begin();
5236  // tex.web §448 scan_dimen: the token after the signs is tested in hand for an internal
5237  // dimension, then glue (as `read_number`), and put back once for the factor.
5238  let (is_negative, mut hand) = scan_optional_signs()?;
5239  for attempt in 0..2 {
5240    if let Some(token) = in_hand_or_read(hand.take())? {
5241      match register_value_from(token, RegisterType::Dimension, false)? {
5242        Scanned::Value(Some(d)) => {
5243          let d = Dimension::from(d);
5244          return Ok(if is_negative { d.negate() } else { d });
5245        },
5246        Scanned::Value(None) => {},
5247        Scanned::Declined(token) => hand = Some(token),
5248      }
5249    }
5250    if let Some(token) = in_hand_or_read(hand.take())? {
5251      match register_value_from(token, RegisterType::Glue, false)? {
5252        Scanned::Value(Some(d)) => {
5253          let d = Glue::from(d);
5254          return Ok(Dimension::new(if is_negative {
5255            d.negate().value_of()
5256          } else {
5257            d.value_of()
5258          }));
5259        },
5260        Scanned::Value(None) => {},
5261        Scanned::Declined(token) => hand = Some(token),
5262      }
5263    }
5264    match hand.take() {
5265      Some(token) if attempt == 0 && became_expandable(&token)? => unread_one(token),
5266      other => {
5267        hand = other;
5268        break;
5269      },
5270    }
5271  }
5272  if let Some(token) = hand {
5273    unread_one(token);
5274  }
5275  if let Some(d) = read_factor()? {
5276    let (num, den) = match read_unit()? {
5277      Some(ratio) => ratio,
5278      None => {
5279        Warn!(
5280          "expected",
5281          "<unit>",
5282          "Illegal unit of measure (pt inserted)."
5283        );
5284        (1, 1)
5285      },
5286    };
5287    let d_signed = if is_negative { -d } else { d };
5288    // tex.web §460 attach_sign: "Dimension too large" at 2^30 sp, the value
5289    // clamped to max_dimen (the i128 product once wrapped to garbage past the
5290    // i64 range: `200000000000\dimen0`, chinesechess.sty:2016-2020).
5291    Ok(Dimension::new(dimension_too_large(
5292      fixpoint_unit_checked(d_signed, num, den),
5293      is_negative,
5294    )?))
5295  } else {
5296    // Perl Gullet.pm:972: the type is named in the primary message
5297    // ("(Dimension)") and "while processing X" is a separate detail
5298    // (ToString of the current token, not Rust-Debug).
5299    let cur = get_current_token()
5300      .map(|t| t.to_string())
5301      .unwrap_or_default();
5302    Warn!(
5303      "expected",
5304      "<number>",
5305      "Missing number (Dimension), treated as zero.",
5306      s!("while processing {cur}")
5307    );
5308    Ok(Dimension::new(0))
5309  }
5310}
5311
5312// ```
5313// <unit of measure> = <optional spaces><internal unit>
5314//     | <optional true><physical unit><one optional space>
5315// <internal unit> = em <one optional space> | ex <one optional space>
5316//     | <internal integer> | <internal dimen> | <internal glue>
5317// <physical unit> = pt | pc | in | bp | cm | mm | dd | cc | sp
5318// ```
5319
5320/// Read a unit, returning the exact TeX `(num, den)` conversion fraction (see
5321/// [`convert_unit_ratio`] / `numeric_ops::fixpoint_unit`). Internal/coerced units
5322/// (`\wd0`, `\dimen`, glue) yield `(value_sp, 65536)` — the `floor(fix·v/65536)`
5323/// path of tex.web §8983, exact in integer arithmetic.
5324pub fn read_unit() -> Result<Option<(i64, i64)>> {
5325  let unit_opt = if let Some(u) = read_keyword(&["ex", "em", "zw", "zh"])? {
5326    skip_one_space(true)?;
5327    Some(convert_unit_ratio(u))
5328  } else if let Some(u) = read_internal_integer()? {
5329    Some((u.value_of(), UNITY)) // These are coerced to number=>sp
5330  } else if let Some(u) = read_internal_dimension()? {
5331    Some((u.value_of(), UNITY))
5332  } else if let Some(u) = read_internal_glue()? {
5333    Some((u.value_of(), UNITY))
5334  } else {
5335    read_keyword(&["true"])?; // But ignore, we're not bothering with mag...
5336    if let Some(u) = read_keyword(&["pt", "pc", "in", "bp", "cm", "mm", "dd", "cc", "sp", "px"])? {
5337      skip_one_space(true)?;
5338      Some(convert_unit_ratio(u))
5339    } else {
5340      None
5341    }
5342  };
5343  Ok(unit_opt)
5344}
5345
5346//======================================================================
5347// Glue
5348//======================================================================
5349// <glue> = <optional signs><internal glue> | <dimen><stretch><shrink>
5350// <stretch> = plus <dimen> | plus <fil dimen> | <optional spaces>
5351// <shrink>  = minus <dimen> | minus <fil dimen> | <optional spaces>
5352pub fn read_glue() -> Result<Glue> {
5353  let _scan = NumberScan::begin();
5354  let is_negative = read_optional_signs()?;
5355  if let Some(n) = read_internal_glue()? {
5356    if is_negative { Ok(n.negate()) } else { Ok(n) }
5357  } else {
5358    let mut d = read_dimension()?;
5359    if is_negative {
5360      d = d.negate();
5361    }
5362    let (r1, f1) = match read_keyword(&["plus"])? {
5363      Some(_) => read_rubber(false)?,
5364      None => (None, None),
5365    };
5366    let (r2, f2) = match read_keyword(&["minus"])? {
5367      Some(_) => read_rubber(false)?,
5368      None => (None, None),
5369    };
5370
5371    Ok(Glue::new_spec(
5372      &d.value_of().to_string(),
5373      r1.map(|v| v as f64),
5374      f1,
5375      r2.map(|v| v as f64),
5376      f2,
5377    ))
5378  }
5379}
5380
5381pub fn read_rubber(mu: bool) -> Result<(Option<i64>, Option<FillCode>)> {
5382  let is_negative = read_optional_signs()?;
5383  let s = if is_negative { -1 } else { 1 };
5384  match read_factor()? {
5385    None => {
5386      let f = if mu {
5387        read_mu_dimension()?.value_of()
5388      } else {
5389        read_dimension()?.value_of()
5390      };
5391      Ok((Some(f * s), None))
5392    },
5393    Some(f) => match read_keyword(&["filll", "fill", "fil"])? {
5394      Some(fil) => Ok((Some(fixpoint(s as f64 * f, None)), FillCode::from(fil))),
5395      None => {
5396        let ratio = if mu {
5397          match read_mu_unit()? {
5398            None => {
5399              Warn!(
5400                "expected",
5401                "<unit>",
5402                "Illegal unit of measure (mu inserted)."
5403              );
5404              None
5405            },
5406            some => some,
5407          }
5408        } else {
5409          match read_unit()? {
5410            None => {
5411              Warn!(
5412                "expected",
5413                "<unit>",
5414                "Illegal unit of measure (pt inserted)."
5415              );
5416              None
5417            },
5418            some => some,
5419          }
5420        };
5421        let val = s as f64 * f;
5422        // The <dimen> of a glue component is `scan_dimen`'s (§460).
5423        let sp = match ratio {
5424          Some((num, den)) => dimension_too_large(fixpoint_unit_checked(val, num, den), s < 0)?,
5425          None => fixpoint(val, None),
5426        };
5427        Ok((Some(sp), None))
5428      },
5429    },
5430  }
5431}
5432
5433//======================================================================
5434// Mu Glue
5435//======================================================================
5436// <muglue> = <optional signs><internal muglue> | <mudimen><mustretch><mushrink>
5437// <mustretch> = plus <mudimen> | plus <fil dimen> | <optional spaces>
5438// <mushrink> = minus <mudimen> | minus <fil dimen> | <optional spaces>
5439pub fn read_mu_glue() -> Result<MuGlue> {
5440  let _scan = NumberScan::begin();
5441  let is_negative = read_optional_signs()?;
5442  if let Some(n) = read_internal_mu_glue()? {
5443    Ok(if is_negative { n.negate() } else { n })
5444  } else {
5445    let mut d = read_mu_dimension()?;
5446    if is_negative {
5447      d = d.negate()
5448    }
5449    let (r1, f1) = if read_keyword(&["plus"])?.is_some() {
5450      read_rubber(true)?
5451    } else {
5452      (None, None)
5453    };
5454    let (r2, f2) = if read_keyword(&["minus"])?.is_some() {
5455      read_rubber(true)?
5456    } else {
5457      (None, None)
5458    };
5459    Ok(MuGlue::new_full(d.value_of(), r1, f1, r2, f2))
5460  }
5461}
5462
5463//======================================================================
5464// Mu Dimensions
5465//======================================================================
5466// <mudimen> = <optional signs><unsigned mudimem>
5467// <unsigned mudimen> = <normal mudimen> | <coerced mudimen>
5468// <normal mudimen> = <factor><mu unit>
5469// <mu unit> = <optional spaces><internal muglue> | mu <one optional space>
5470// <coerced mudimen> = <internal muglue>
5471pub fn read_mu_dimension() -> Result<MuDimension> {
5472  let _scan = NumberScan::begin();
5473  let is_negative = read_optional_signs()?;
5474  if let Some(mut m) = read_factor()? {
5475    let munit = read_mu_unit()?;
5476    if munit.is_none() {
5477      Warn!(
5478        "expected",
5479        "<unit>",
5480        "Illegal unit of measure (mu inserted)."
5481      );
5482    }
5483    if is_negative {
5484      m *= -1.0;
5485    }
5486    // `scan_dimen` with `mu` (§456) ends in the same `attach_sign` (§460).
5487    let sp = match munit {
5488      Some((num, den)) => dimension_too_large(fixpoint_unit_checked(m, num, den), is_negative)?,
5489      None => fixpoint(m, None),
5490    };
5491    Ok(MuDimension::new(sp))
5492  } else if let Some(mglue) = read_internal_mu_glue()? {
5493    let m = if is_negative { mglue.negate() } else { mglue };
5494    Ok(MuDimension::new(m.value_of()))
5495  } else {
5496    Warn!("expected", "<mudimen>", "Expecting mudimen; assuming 0");
5497    Ok(MuDimension::new(0))
5498  }
5499}
5500
5501pub fn read_mu_unit() -> Result<Option<(i64, i64)>> {
5502  if read_keyword(&["mu"])?.is_some() {
5503    skip_one_space(true)?;
5504    Ok(Some((UNITY, UNITY))) // effectively, scaled mu
5505  } else if let Some(m) = read_internal_mu_glue()? {
5506    Ok(Some((m.value_of(), UNITY)))
5507  } else {
5508    Ok(None)
5509  }
5510}
5511
5512fn read_internal_mu_glue() -> Result<Option<MuGlue>> {
5513  match read_register_value(RegisterType::MuGlue)? {
5514    None => Ok(None),
5515    Some(val) => Ok(Some(val.into())),
5516  }
5517}
5518
5519/// The right-hand side of a token-list assignment, `\toks<n>=…`, `\everypar=…`
5520/// (tex.web §1226-1227), after its optional `=`: the next non-blank
5521/// non-`\relax` token, expanding (§404, `get_x_token`, which at a file's end
5522/// goes on in the enclosing input). A left brace, explicit or implicit
5523/// (`\toks0=\bgroup abc}`), opens the balanced text, read at `absorbing`
5524/// status (`scan_toks(false, false)`, [`read_balanced_text`]); a token-list
5525/// register or parameter gives its value. Any other token is the value
5526/// itself, as in Perl (Gullet.pm:824-842 `readTokensValue`), after TeX's
5527/// error, "Missing { inserted" (§403 `scan_left_brace`; TeX then absorbs up to
5528/// the next `}`).
5529/// Perl reads the token unexpanded and recurses on an expandable one, so a
5530/// `\relax`, an implicit brace or a file end before the text lost it:
5531/// Paul Taylor's diagrams.sty:15 `\toks0=\bgroup}` stored `\bgroup`, and its
5532/// `}` closed a group (arXiv 2605.02221, 2605.25087).
5533/// Guards: `token_kernel_gaps::*`.
5534pub fn read_tokens_value() -> Result<Tokens> {
5535  let Some(token) = read_non_blank_non_relax()? else {
5536    return Ok(Tokens!());
5537  };
5538  if is_left_brace(&token) {
5539    return read_balanced_text(ExpansionLevel::Off, false);
5540  }
5541  match lookup_register_definition(&token) {
5542    Some(defn)
5543      if matches!(
5544        defn.register_type(),
5545        Some(RegisterType::Tokens) | Some(RegisterType::Token)
5546      ) =>
5547    {
5548      let args = defn.read_arguments()?;
5549      Ok(defn.value_of(args).map(Into::into).unwrap_or_default())
5550    },
5551    _ => {
5552      Error!("expected", "{", "Missing { inserted");
5553      Ok(Tokens!(token))
5554    },
5555  }
5556}
5557
5558/// tex.web §404 "Get the next non-blank non-relax non-call token": expanded (a `\protected` macro too, as
5559/// `get_x_token` expands it), past spaces and implicit spaces, `\relax` and `\noexpand`ed tokens (`relax`, §358);
5560/// an undefined control sequence is reported by `expand` and discarded (§370), as the csname reader does — the scan
5561/// goes on, so `\hbox\undefined{…}` is still the box of `{…}`.
5562pub fn read_non_blank_non_relax() -> Result<Option<Token>> {
5563  loop {
5564    match read_x_token(Some(false), false, Some(true))? {
5565      Some(t)
5566        if is_space_or_implicit_space(&t)
5567          || t.defined_as(&TOKEN_RELAX)
5568          || t.is_noexpand_family()
5569          || (t.get_catcode() == Catcode::CS && is_error_stub(&t)) => {},
5570      other => return Ok(other),
5571    }
5572  }
5573}
5574
5575/// tex.web §406 "Get the next non-blank non-call token": `get_x_token`, so a `\protected` macro expands too, past
5576/// spaces and implicit spaces (`cur_cmd=spacer`); an undefined control sequence is reported by `expand` and
5577/// discarded (§370), as in [`read_non_blank_non_relax`]. §577 `scan_font_ident` reads a font identifier with it.
5578pub fn read_non_blank_non_call() -> Result<Option<Token>> {
5579  loop {
5580    match read_x_token(Some(false), false, Some(true))? {
5581      Some(t) if is_space_or_implicit_space(&t) || (t.is_active_or_cs() && is_error_stub(&t)) => {},
5582      other => return Ok(other),
5583    }
5584  }
5585}
5586
5587/// tex.web §403 `scan_left_brace`: the next non-blank non-relax token ([`read_non_blank_non_relax`]) is a `{`
5588/// ([`is_left_brace`]); any other is put back with "Missing { inserted", and the group is taken as begun.
5589pub fn scan_left_brace() -> Result<()> {
5590  match read_non_blank_non_relax()? {
5591    Some(t) if is_left_brace(&t) => {},
5592    other => {
5593      Error!("expected", "{", "Missing { inserted");
5594      if let Some(t) = other {
5595        unread_one(t);
5596      }
5597    },
5598  }
5599  Ok(())
5600}
5601
5602/// tex.web's `cur_cmd=left_brace`: a character of catcode 1, or a control
5603/// sequence or active character `\let` to one (`\bgroup`).
5604pub fn is_left_brace(token: &Token) -> bool {
5605  token.get_catcode() == Catcode::BEGIN
5606    || (token.get_catcode().is_active_or_cs()
5607      && with_meaning(
5608        token,
5609        |m| matches!(m, Some(Stored::Token(t)) if t.get_catcode() == Catcode::BEGIN),
5610      ))
5611}
5612
5613/// tex.web's `cur_cmd=right_brace` (§1068 `handle_right_brace`): a character of catcode 2, or a control
5614/// sequence or active character `\let` to one (`\egroup`). The closer that matches [`is_left_brace`]'s opener:
5615/// under `\catcode`\<=1 \catcode`\>=2`, `\hbox<…>` is a box (2606.11726's plain-TeX macros), where Perl's
5616/// `defined_as(T_END)` knew only `}`.
5617pub fn is_right_brace(token: &Token) -> bool {
5618  token.get_catcode() == Catcode::END
5619    || (token.get_catcode().is_active_or_cs()
5620      && with_meaning(
5621        token,
5622        |m| matches!(m, Some(Stored::Token(t)) if t.get_catcode() == Catcode::END),
5623      ))
5624}
5625
5626/// Discard any run of spaces at the head of the input — Perl
5627/// `Package.pm:SkipSpaces`.
5628///
5629/// Reads past the spaces via [`read_non_space`] and pushes the first
5630/// non-space token back, so the caller's next read starts on real content.
5631/// End of input is not an error: there is simply nothing to unread.
5632pub fn skip_spaces() -> Result<()> {
5633  if let Some(t) = read_non_space()? {
5634    unread_one(t);
5635  }
5636  Ok(())
5637}
5638
5639/// Check if a token is a space token (catcode SPACE) or an "implicit space"
5640/// (a CS or ACTIVE token `\let` to a space token).
5641/// See TeXbook p269: `<one optional space>` absorbs both explicit and implicit spaces.
5642/// (tex.web's `cur_cmd=spacer`.)
5643pub fn is_space_or_implicit_space(token: &Token) -> bool {
5644  if token.get_catcode() == Catcode::SPACE {
5645    return true;
5646  }
5647  // Check for implicit space: CS/ACTIVE let to a space token
5648  if token.get_catcode() == Catcode::CS || token.get_catcode() == Catcode::ACTIVE {
5649    return with_meaning(
5650      token,
5651      |m| matches!(m, Some(Stored::Token(t)) if t.get_catcode() == Catcode::SPACE),
5652    );
5653  }
5654  false
5655}
5656
5657/// Put back a token an EXPANDING scan read but does not use (TeX's
5658/// `back_input` of `cur_tok`). A `\noexpand`'d token goes back as its plain
5659/// self: `\noexpand` suppresses expansion only for the read that met it
5660/// (tex.web:7509-7514); get_x_token leaves the plain control sequence in
5661/// `cur_tok` (:7837-7838), and the optional-space check just calls `back_input`
5662/// (:8755-8757). The marker survived instead, and a later `\csname` met
5663/// `\special_relax\foo`: trimspaces' `\trim@spaces` on an argument starting with
5664/// a macro (`\romannumeral-`\q\noexpand\foo`), yquant-doc's 501-error runaway.
5665/// Perl alike (KNOWN_PERL_ERRORS #255). Guard:
5666/// `perfect_kernel_batch56::noexpand_marker_does_not_survive_a_scan`.
5667fn unread_scanned(token: Token) { unread_one(token.noexpand_shadowed().unwrap_or(token)); }
5668
5669/// Skip one optional space.
5670/// If `expanded` is true, acts like `<one optional space>` and expands tokens (readXToken).
5671/// Perl: skip1Space($self, $expanded)
5672pub fn skip_one_space(expanded: bool) -> Result<()> {
5673  let token = if expanded {
5674    read_x_token(None, false, None)?
5675  } else {
5676    read_token()?
5677  };
5678  if let Some(t) = token
5679    && !is_space_or_implicit_space(&t)
5680  {
5681    if expanded {
5682      unread_scanned(t);
5683    } else {
5684      unread_one(t);
5685    }
5686  }
5687  Ok(())
5688}
5689
5690//======================================================================
5691// some helpers...
5692
5693// <optional signs> = <optional spaces> | <optional signs><plus or minus><optional spaces>
5694// returns false if None, or positive, true if negative
5695pub fn read_optional_signs() -> Result<bool> {
5696  let (sign, next) = scan_optional_signs()?;
5697  if let Some(t) = next {
5698    unread_one(t); // Unread and end
5699  }
5700  Ok(sign)
5701}
5702
5703/// <optional signs>, returning whether they are negative and the token after them (TeX's
5704/// `cur_tok`, read with expansion and not put back).
5705fn scan_optional_signs() -> Result<(bool, Option<Token>)> {
5706  let _operand = OperandRead::begin();
5707  let mut sign = false;
5708  while let Some(t) = read_x_token(None, false, None)? {
5709    let sym = t.get_sym();
5710    if sym == pin!("-") {
5711      sign = !sign;
5712    } else if (sym != pin!("+")) && !is_space_or_implicit_space(&t) {
5713      return Ok((sign, Some(t)));
5714    }
5715  }
5716  Ok((sign, None))
5717}
5718
5719/// Whether a token in hand that every kind of quantity declined is now expandable: an
5720/// undefined control sequence's own read installs its error stub (`\iffoo` `\let` to
5721/// `\iffalse`, State.pm:537-545), which Perl's chain of reads expands on its next read. The
5722/// scan puts it back once, so it is read (and expanded) again.
5723fn became_expandable(token: &Token) -> Result<bool> {
5724  Ok(
5725    matches!(token.get_catcode(), Catcode::CS | Catcode::ACTIVE)
5726      && lookup_definition(token)?.is_some_and(|defn| defn.is_expandable()),
5727  )
5728}
5729
5730/// The token in hand, or the next one read with expansion.
5731fn in_hand_or_read(hand: Option<Token>) -> Result<Option<Token>> {
5732  match hand {
5733    Some(token) => Ok(Some(token)),
5734    None => read_x_token(None, false, None),
5735  }
5736}
5737
5738/// Scan digits with expansion, returning them with the token that ended them
5739/// (TeX's `cur_tok`), which is NOT put back.
5740fn scan_digits(is_digit: fn(char) -> bool) -> Result<(String, Option<Token>)> {
5741  let mut result = String::new();
5742  while let Some(token) = read_x_token(None, false, None)? {
5743    let digit_opt = token.with_str(|s| {
5744      let mut chars = s.chars();
5745      match (chars.next(), chars.next()) {
5746        (Some(c), None) if is_digit(c) => Some(c),
5747        _ => None,
5748      }
5749    });
5750    match digit_opt {
5751      Some(digit) => result.push(digit),
5752      None => return Ok((result, Some(token))),
5753    }
5754  }
5755  Ok((result, None))
5756}
5757
5758fn read_digits(is_digit: fn(char) -> bool, skip: bool) -> Result<String> {
5759  let (digits, end) = scan_digits(is_digit)?;
5760  if let Some(token) = end
5761    && !(skip && is_space_or_implicit_space(&token))
5762  {
5763    unread_scanned(token);
5764  }
5765  Ok(digits)
5766}
5767
5768// ```
5769// <factor> = <normal integer> | <decimal constant>
5770// <decimal constant> = . | , | <digit><decimal constant> | <decimal constant><digit>
5771// ```
5772/// Return a number (Rust f64 number)
5773pub fn read_factor() -> Result<Option<f64>> {
5774  // scan_dimen tests the token that ended the digits (`cur_tok`) for the
5775  // decimal point without reading it again (tex.web §448, §452), then puts it
5776  // back once, a `\noexpand`'d token as its plain self (`unread_scanned`).
5777  // An undefined control sequence ending the digits installed its error stub on that read;
5778  // Perl's `readFactor` reads the end token again (Gullet.pm:876-880), which expands it.
5779  let reread_stub = |token_opt: Option<Token>| -> Result<Option<Token>> {
5780    match token_opt {
5781      Some(token) if became_expandable(&token)? => {
5782        unread_one(token);
5783        read_x_token(None, false, None)
5784      },
5785      other => Ok(other),
5786    }
5787  };
5788  let (mut factor, token_opt) = scan_digits(is_decimal_digit)?;
5789  let mut token_opt = reread_stub(token_opt)?;
5790  if let Some(ref token) = token_opt {
5791    let sym = token.get_sym();
5792    if sym == pin!(".") || sym == pin!(",") {
5793      let (fraction, end) = scan_digits(is_decimal_digit)?;
5794      factor = s!("{factor}.{fraction}");
5795      token_opt = reread_stub(end)?;
5796    }
5797  }
5798
5799  // Note: zero is an edge case with the unwrap_or fallback, handle it
5800  if !factor.is_empty() {
5801    // The integer part is `scan_int`'s (§448), held to `infinity` (§445).
5802    let (whole, fraction) = factor.split_once('.').unwrap_or((factor.as_str(), ""));
5803    let value = whole
5804      .parse::<i64>()
5805      .unwrap_or(if whole.is_empty() { 0 } else { i64::MAX });
5806    if number_too_big(value)? != value {
5807      factor = s!("{MAX_INTEGER}.{fraction}");
5808    }
5809    let factor_f64: f64 = factor.parse::<f64>().unwrap_or(0.0);
5810    if let Some(token) = token_opt
5811      && token.get_catcode() != Catcode::SPACE
5812    {
5813      unread_scanned(token);
5814    }
5815    Ok(Some(factor_f64))
5816  } else {
5817    // No digits: back_input, and scan_int reads the token again (§448).
5818    if let Some(token) = token_opt {
5819      unread_scanned(token);
5820    }
5821    match read_normal_integer()? {
5822      None => Ok(None),
5823      Some(n) => Ok(Some(n.value_of() as f64)),
5824    }
5825  }
5826}
5827
5828/// Fully expand `tokens` and return the result, without digesting them.
5829///
5830/// Port of Perl `Package.pm:Expand` L950-955. The tokens are read from a fresh
5831/// mouth wrapped in `{`…`}` and consumed with `readBalanced` — the braces are
5832/// what bound the expansion to exactly this material, so an unbalanced or
5833/// runaway body cannot walk off into whatever follows in the real input.
5834///
5835/// See [`do_expand_partially`] for the expand-until-unexpandable variant.
5836pub fn do_expand<T: Into<Tokens>>(tokens: T) -> Result<Tokens> {
5837  let tokens: Tokens = tokens.into();
5838  reading_from_mouth(Mouth::default(), move || -> Result<Tokens> {
5839    {
5840      unread_one(T_END!());
5841      unread(tokens);
5842      unread_one(T_BEGIN!());
5843    }
5844    read_balanced(ExpansionLevel::Full, false, true)
5845  })
5846}
5847
5848/// As [`do_expand`], but stopping at the first unexpandable token of each
5849/// branch ([`ExpansionLevel::Partial`]) instead of expanding to the bitter end.
5850///
5851/// What a binding wants when it needs to *look* at what a macro produces —
5852/// resolving a `\newcommand` alias, say — without forcing the primitives
5853/// underneath it, whose expansion has side effects the caller is not ready for.
5854pub fn do_expand_partially<T: Into<Tokens>>(tokens: T) -> Result<Tokens> {
5855  let tokens: Tokens = tokens.into();
5856  reading_from_mouth(Mouth::default(), move || -> Result<Tokens> {
5857    {
5858      unread_one(T_END!());
5859      unread(tokens);
5860      unread_one(T_BEGIN!());
5861    }
5862    read_balanced(ExpansionLevel::Partial, false, true)
5863  })
5864}
5865
5866/// Is `token` an alignment column end — a tab or a row end — and which one: the `COLUMN_ENDS` entry (the token
5867/// to act on, its keyword, whether it is hidden), or `(token, "align", false)` for a tab.
5868///
5869/// tex.web §342/§789 insert the v-template when `get_next` yields `cur_cmd` ∈ {`tab_mark`, `car_ret`}: a column
5870/// end is recognized by its COMMAND CODE, which `\let` copies and `\def` replaces. So `\let\myspan\span` ends a
5871/// cell, while after `\def\span{\mathrm{span}}` a `\span` is a macro call — expanded, never a column end. A
5872/// LaTeXML primitive's command code is its defining cs: `\let` copies the `Primitive`/`Constructor` with that cs
5873/// (and the format dump restores such copies as aliases of the cs), while `\def`/`\newcommand` make an
5874/// `Expandable`. So a binding that re-`DefPrimitive`s/`DefConstructor`s `\cr`, `\crcr` or `\span` under that name
5875/// makes a column end too; the frozen copies `\lx@span`/`\lx@frozen@cr` (tex_tables.rs) are column ends for the
5876/// same reason. Perl `Gullet.pm` L266-277 compares the token's meaning with the CURRENT meaning of each
5877/// end instead, so a redefined `\span` (or `\cr`) still matched itself and ended the cell (math0004102:
5878/// `\def\span{{\mathrm{span}}}` in an `eqnarray` cell split the cell at the `\span` and ran `^` out of math).
5879/// Guard: `perfect_kernel_batch65::redefined_span_is_a_macro_not_a_column_end`.
5880pub fn is_column_end(token: &Token) -> Option<(Token, &'static str, bool)> {
5881  match token.get_catcode() {
5882    Catcode::ALIGN => Some((*token, "align", false)),
5883    Catcode::CS | Catcode::ACTIVE => with_meaning(token, |defn| {
5884      let primitive_cs = match defn? {
5885        // Perl Gullet.pm L273: if meaning is a Token with CC_ALIGN, treat as alignment tab
5886        Stored::Token(t) if t.get_catcode() == Catcode::ALIGN => {
5887          return Some((*token, "align", false));
5888        },
5889        Stored::Primitive(p) => p.cs,
5890        Stored::Constructor(c) => c.cs,
5891        _ => return None,
5892      };
5893      COLUMN_ENDS
5894        .iter()
5895        .find(|end| end.0 == primitive_cs)
5896        .copied()
5897    }),
5898    _ => None,
5899  }
5900}
5901/// Handle a marker token, by updating the current alignment group count
5902fn handle_marker(marker_token: Token) {
5903  marker_token.with_str(|arg| match arg {
5904    "before-column" => {
5905      // Were in before-column template
5906      set_align_group_count(0);
5907    }, // switch to column proper!
5908    "after-column" => { // Were in before-column template
5909      // let alignment = lookup_alignment();
5910      // Debug("Halign $alignment: alignment  after column") if $LaTeXML::DEBUG{halign};
5911    },
5912    _ => {},
5913  });
5914}
5915
5916/// The mouths open: the one in reading ([`Gullet::runtime`]) and those under it. [`open_mouth`] pushes nothing on the stack
5917/// when none is in reading, so the stack alone doesn't count them. A [`pushback_len`] compares only at one depth: a
5918/// constructor digests its argument in a mouth of its own (a rehearsal's notes, `token::FieldNotesHook`).
5919pub fn mouth_depth() -> usize {
5920  let g = gullet!();
5921  g.mouthstack.len() + usize::from(g.runtime.is_some())
5922}
5923
5924thread_local! {
5925  /// The conversion's "Mouth is unexpectedly already closed" errors ([`reading_from_mouth`]'s budget).
5926  static MOUTH_CLOSED_ERRORS: Cell<usize> = const { Cell::new(0) };
5927}
5928
5929/// Forgets the mouth-closed errors counted: a predecessor that spent the budget (0906.1883) silenced the next paper's
5930/// first ten and made its first a Fatal.
5931pub fn reset_mouth_closed_errors() { MOUTH_CLOSED_ERRORS.with(|c| c.set(0)); }
5932
5933/// Do something, while reading tokens from a specific Mouth.
5934///
5935/// This reads ONLY from that mouth (or any mouth openned by code in that source),
5936/// and the mouth should end up empty afterwards, and only be closed here.
5937pub fn reading_from_mouth<R, FnR>(mouth: Mouth, reader: FnR) -> Result<R>
5938where FnR: FnOnce() -> Result<R> {
5939  let context_mouth_source = arena::pin(mouth.get_source());
5940  let outer_mouths = mouth_depth();
5941  // A cycle is only a cycle WITHIN one expansion context. Rather than
5942  // resetting the guard history here (an earlier fix that also BLINDED the
5943  // guard to outer loops whose body calls `do_expand` each iteration), give
5944  // this reading context a fresh SERIAL that `read_internal_token_checked`
5945  // mixes into every fingerprint: windows can never match across contexts, so
5946  // consecutive identical short expansions — the math0402448 xymatrix
5947  // per-cell `get_xmarg_id` stream that false-positived as a "loop" — stay
5948  // inert, while the OUTER context's serial (restored on exit) keeps outer
5949  // periodicity intact and detectable. PR #249 review P2-7.
5950  {
5951    let mut g = gullet_mut!();
5952    let outer = g.ctx_serial;
5953    g.ctx_stack.push(outer);
5954    g.ctx_next += 1;
5955    g.ctx_serial = g.ctx_next;
5956  }
5957  open_mouth(mouth, false); // only allow mouth to be explicitly closed here.
5958  let reader_result = reader();
5959  // Reading in this context is over (whether Ok or Err): restore the outer
5960  // context's serial before any cleanup/return path below.
5961  {
5962    let mut g = gullet_mut!();
5963    let restored = g.ctx_stack.pop().unwrap_or(0);
5964    g.ctx_serial = restored;
5965  }
5966  // If the reader returned an error (e.g., Fatal from token limit),
5967  // we STILL need to clean up the mouth to preserve the caller's state.
5968  let results: R = match reader_result {
5969    Ok(v) => v,
5970    Err(e) => {
5971      // Force-close our mouth and any mouth above it, by depth: another of the same name above ours (an "Anonymous
5972      // String", a `\scantokens`'s in a discarded run) is not ours, and stopping at it left ours open and took the
5973      // document's text next (`perfect_kernel_batchr1::a_run_over_budget_leaves_no_trace`).
5974      while mouth_depth() > outer_mouths {
5975        close_mouth(true).ok();
5976      }
5977      // Reset progress counter so subsequent processing isn't immediately killed
5978      let mut g = gullet_mut!();
5979      // (what a budgeted run has left stays what it has left: [`read_budget`])
5980      let progress = g.progress;
5981      g.read_budget_at = g.read_budget_at.map(|at| at.saturating_sub(progress));
5982      g.progress = 0;
5983      g.full_read_at = 0;
5984      drop(g);
5985      return Err(e);
5986    },
5987  };
5988  // `mouth` must still be open, with (at worst) empty autoclosable mouths in front of it.
5989  // Rate-limit the "mouth closed" error — when the gullet gets into a state
5990  // where the cleanup loop keeps finding stale mouths above the target, the
5991  // same error can fire on EVERY caller of reading_from_mouth. Arxiv 0906.1883
5992  // (birkmult + local .cls) can trigger 10K+ such firings, one per stack frame.
5993  // Fatal out after 50 repeat firings so the process surfaces a clear "we lost
5994  // the mouth stack" signal instead of filling the log with identical messages.
5995  fn record_mouth_closed_error() { MOUTH_CLOSED_ERRORS.with(|c| c.set(c.get().saturating_add(1))); }
5996  fn should_emit_mouth_closed() -> bool { MOUTH_CLOSED_ERRORS.with(|c| c.get() < 10) }
5997  fn mouth_closed_budget_exhausted() -> bool { MOUTH_CLOSED_ERRORS.with(|c| c.get() >= 50) }
5998  loop {
5999    let mouth_source = gullet!()
6000      .runtime
6001      .as_ref()
6002      .map(|r| arena::pin(r.mouth.get_source()));
6003    if mouth_source == Some(context_mouth_source) {
6004      close_mouth(true)?;
6005      break;
6006    } else if gullet!().mouthstack.is_empty() {
6007      if should_emit_mouth_closed() {
6008        // `arena::to_string` clones the resolved &str into an owned String
6009        // BEFORE we hand it to Error! — a following `arena::pin` triggered
6010        // deep inside generate_message!/get_location() can grow the
6011        // interner's buffer and invalidate a borrowed &str (observed as
6012        // garbled, buffer-adjacent symbol content in 0906.1883 errors).
6013        let src = arena::to_string(context_mouth_source);
6014        Error!(
6015          "unexpected",
6016          "<closed>",
6017          "Mouth is unexpectedly already closed",
6018          s!("Reading from {src}, but it has already been closed.")
6019        );
6020      }
6021      record_mouth_closed_error();
6022      if mouth_closed_budget_exhausted() {
6023        Fatal!(
6024          Stomach,
6025          Recursion,
6026          "Too many unexpectedly-closed mouth errors (>50); gullet mouth-stack state is inconsistent"
6027        );
6028      }
6029      break;
6030    } else {
6031      let is_autoclosable = gullet!()
6032        .runtime
6033        .as_ref()
6034        .map(|r| r.autoclose)
6035        .unwrap_or(false);
6036      if is_autoclosable {
6037        // Auto-closable mouth (e.g. from \scantokens, raw_tex) — safe to close
6038        close_mouth(true)?;
6039      } else {
6040        // Non-autoclosable mouth that isn't our target — this means our target
6041        // mouth was already consumed. Don't close this mouth (it belongs to an
6042        // outer reading_from_mouth call). Just error and stop.
6043        if should_emit_mouth_closed() {
6044          let src = arena::to_string(context_mouth_source);
6045          Error!(
6046            "unexpected",
6047            "<closed>",
6048            "Mouth is unexpectedly already closed",
6049            s!(
6050              "Reading from {src}, but it has already been closed (found different non-closable mouth on top)."
6051            )
6052          );
6053        }
6054        record_mouth_closed_error();
6055        if mouth_closed_budget_exhausted() {
6056          Fatal!(
6057            Stomach,
6058            Recursion,
6059            "Too many unexpectedly-closed mouth errors (>50); gullet mouth-stack state is inconsistent"
6060          );
6061        }
6062        break;
6063      }
6064    }
6065  }
6066  Ok(results)
6067}
6068
6069/// The reading context tokens are read in now, as `(serial, depth)`: the serial [`reading_from_mouth`] gives each
6070/// isolated context (a constructor's argument digested on its own; 0 for the document's own input, `\input` files
6071/// included), and how many such contexts are open. A `\left` records it (stomach.rs `record_left_group_input`), so that
6072/// only the end of the input it was read in closes its group (OXIDIZED_DESIGN #530).
6073pub fn reading_context() -> (u64, usize) {
6074  let g = gullet!();
6075  (g.ctx_serial, g.ctx_stack.len())
6076}
6077
6078/// Whether the token just read ends an isolated reading context ([`reading_from_mouth`]: a token list digested on its
6079/// own, such as a constructor's argument `{$x}`, which may come wrapped in a further brace pair): only `}`s left in
6080/// its pushback and its mouth exhausted. A `}` read here is the argument's own closing brace, which TeX strips with the
6081/// argument — one end of a construct digested as a unit (stomach.rs `formula_ends_with_its_unit`, OXIDIZED_DESIGN
6082/// #553). `false` whenever a mouth of its own is still open in the context.
6083pub fn isolated_input_ends_here() -> bool {
6084  let mut g = gullet_mut!();
6085  if g.ctx_stack.is_empty() {
6086    return false;
6087  }
6088  match g.runtime.as_mut() {
6089    Some(runtime) => {
6090      !runtime.autoclose
6091        && runtime
6092          .pushback
6093          .iter()
6094          .all(|t| t.get_catcode() == Catcode::END)
6095        && !runtime.mouth.has_more_input()
6096    },
6097    None => false,
6098  }
6099}
6100
6101/// The tokens the current input holds next, without reading them: the pushback, next-read first, then the current
6102/// mouth's next `max_lines` source lines (at most `max_chars` characters of them, [`Mouth::peek_text`]) tokenized by
6103/// a scratch mouth under the current catcodes as the iterator is drawn on, `max_tokens` in all. Nothing is read,
6104/// expanded or moved, so a catcode change the look-ahead runs past still applies to the text when it is really read.
6105/// Only the current mouth: the input levels outside it are not reached. The cost is bounded by the limits, not by the
6106/// length of the line or of the pending expansion. A look-ahead for a decision about what follows (stomach.rs
6107/// `formula_continues_past_par`, OXIDIZED_DESIGN #553).
6108pub fn peek_upcoming_tokens(
6109  max_lines: usize,
6110  max_chars: usize,
6111  max_tokens: usize,
6112) -> impl Iterator<Item = Token> {
6113  let (pending, text) = {
6114    let gullet = gullet!();
6115    match gullet.runtime.as_ref() {
6116      Some(runtime) => (
6117        runtime
6118          .pushback
6119          .iter()
6120          .rev()
6121          .take(max_tokens)
6122          .copied()
6123          .collect::<Vec<Token>>(),
6124        runtime.mouth.peek_text(max_lines, max_chars),
6125      ),
6126      None => (Vec::new(), String::new()),
6127    }
6128  };
6129  let mut scratch = if pending.len() < max_tokens && !text.is_empty() {
6130    Mouth::new(&text, None).ok()
6131  } else {
6132    None
6133  };
6134  pending
6135    .into_iter()
6136    .chain(std::iter::from_fn(move || scratch.as_mut()?.read_token()))
6137    .take(max_tokens)
6138}
6139
6140/// Check if there is more input to be read from the current mouth
6141pub fn has_more_input() -> bool {
6142  match runtime!() {
6143    Some(ref mut runtime) => runtime.mouth.has_more_input(),
6144    None => false,
6145  }
6146}
6147
6148thread_local! {
6149  /// How many speculative digestions are running ([`speculative_digestion`]).
6150  static SPECULATIVE_DIGESTIONS: Cell<usize> = const { Cell::new(0) };
6151}
6152
6153/// A speculative digestion runs while this lives ([`speculative_digestion`]).
6154pub struct SpeculativeDigestion;
6155
6156impl Drop for SpeculativeDigestion {
6157  fn drop(&mut self) { SPECULATIVE_DIGESTIONS.with(|runs| runs.set(runs.get() - 1)); }
6158}
6159
6160/// A run of digestion whose output and assignments are all discarded starts (latexml_engine sect05.rs `speculative_run_read`,
6161/// the observer's rehearsal, `queue_digest::speculative_label_ink`), until the guard drops: the document does not end
6162/// in it. A `\end{document}`, `\enddocument`, `\@@end` or `\bye` it reads does nothing ([`flush`], the kernel's document
6163/// end), whatever text brought it there: a stored argument, `\closing{\end{document}}`, ended the real document with the
6164/// run otherwise, and took the whole body with it.
6165#[must_use]
6166pub fn speculative_digestion() -> SpeculativeDigestion {
6167  SPECULATIVE_DIGESTIONS.with(|runs| runs.set(runs.get() + 1));
6168  SpeculativeDigestion
6169}
6170
6171/// Is a speculative digestion running ([`speculative_digestion`])?
6172pub fn in_speculative_digestion() -> bool { SPECULATIVE_DIGESTIONS.with(|runs| runs.get() != 0) }
6173
6174/// Obscure, but the only way I can think of to End!! (see \bye or \end{document})
6175/// Flush all sources (close all pending mouth's)
6176///
6177/// In a speculative digestion ([`speculative_digestion`]) it does nothing: what a discarded run reads is not the end of
6178/// the document's input.
6179pub fn flush() {
6180  if in_speculative_digestion() {
6181    return;
6182  }
6183  let mut g = gullet_mut!();
6184  if let Some(ref mut runtime) = g.runtime {
6185    runtime.mouth.finish();
6186  }
6187  while !g.mouthstack.is_empty() {
6188    if let Some(mut entry) = g.mouthstack.pop_front() {
6189      entry.mouth.finish();
6190    }
6191  }
6192  g.runtime = Some(MouthRuntime {
6193    mouth:           Mouth::default(),
6194    pushback:        Vec::with_capacity(128),
6195    autoclose:       true,
6196    boundary:        BalancedBoundary::Transparent,
6197    insert_everyeof: false,
6198    eof_seen:        false,
6199    file_hooks:      None,
6200    watch:           PushbackWatch::default(),
6201  });
6202  g.mouthstack = VecDeque::new();
6203  note_current_mouth(&g);
6204}
6205
6206/// Execute a function with a mutable reference to the current mouth
6207pub fn with_mouth_mut<FnR, R>(caller: FnR) -> R
6208where FnR: FnOnce(Option<&mut Mouth>) -> R {
6209  let mut gullet = gullet_mut!();
6210  let mouth_opt = match gullet.runtime {
6211    None => None,
6212    Some(ref mut runtime) => Some(&mut runtime.mouth),
6213  };
6214  caller(mouth_opt)
6215}
6216
6217#[cfg(test)]
6218mod token_limit_tests {
6219  use super::*;
6220
6221  /// A budget refuses the read past it and each one after, leaves the count as the reads made it, and leaves no due count
6222  /// on the fast path once it is off; a failed inner reading context keeps what is left of it.
6223  #[test]
6224  fn a_read_budget_ends_at_its_read_and_counts_what_was_read() {
6225    let tokens = || Tokens::new(vec![T_LETTER!("a"); 10]);
6226    reading_from_mouth(Mouth::default(), || {
6227      unread(tokens());
6228      let start = token_progress();
6229      let budget = read_budget(3);
6230      for _ in 0..3 {
6231        assert!(read_token()?.is_some());
6232      }
6233      for _ in 0..2 {
6234        let failed = read_token().unwrap_err();
6235        assert!(matches!(failed.category, ErrorCategory::ReadBudget));
6236      }
6237      assert_eq!(budget.end(), ReadBudgetEnd { reads: 3, over: true });
6238      assert_eq!(token_progress(), start + 3);
6239      assert!(read_token()?.is_some());
6240      assert_eq!(token_progress(), start + 4);
6241
6242      // An inner context's failure resets the count, and takes nothing off what the budget has left.
6243      let start = token_progress();
6244      let budget = read_budget(4);
6245      assert!(read_token()?.is_some());
6246      let inner: Result<()> = reading_from_mouth(Mouth::default(), || {
6247        unread(tokens());
6248        assert!(read_token()?.is_some());
6249        fatal_free_failure()
6250      });
6251      assert!(inner.is_err());
6252      assert_eq!(token_progress(), 0);
6253      assert!(read_token()?.is_some());
6254      assert!(read_token()?.is_some());
6255      assert!(read_token().is_err());
6256      assert_eq!(budget.end(), ReadBudgetEnd { reads: 4, over: true });
6257      assert_eq!(token_progress(), start + 4);
6258
6259      // A run the budget did not end leaves the count alone, whatever is left.
6260      let start = token_progress();
6261      let budget = read_budget(100);
6262      assert!(read_token()?.is_some());
6263      assert_eq!(budget.end(), ReadBudgetEnd { reads: 1, over: false });
6264      assert_eq!(token_progress(), start + 1);
6265      Ok(())
6266    })
6267    .unwrap();
6268  }
6269
6270  /// An input mark reads "unread" until a token it held is read, though the tokens pushed in their place put an equal
6271  /// token at its last slot (a space, IEEEtran's `\IEEEauthorblockN{…}⏎\IEEEauthorblockA{…}`: 2401.11731, 1801.03314);
6272  /// a peek, a token read and put back, and tokens pushed on top leave it unread.
6273  #[test]
6274  fn an_input_mark_tells_a_refilled_slot_from_a_peek() {
6275    reading_from_mouth(Mouth::default(), || {
6276      unread(Tokens::new(vec![T_SPACE!(), T_CS!("\\next")]));
6277      let mark = input_mark();
6278      assert!(input_unread_since(&mark));
6279      // (a peek, and an expansion pushed on top)
6280      let peeked = read_token()?.unwrap();
6281      unread_one(peeked);
6282      assert!(input_unread_since(&mark));
6283      unread(Tokens::new(vec![T_LETTER!("a"), T_SPACE!()]));
6284      assert!(input_unread_since(&mark));
6285      assert_eq!(read_token()?, Some(T_LETTER!("a")));
6286      assert_eq!(read_token()?, Some(T_SPACE!()));
6287      assert!(input_unread_since(&mark));
6288      // (both tokens read, a longer list pushed whose token at the mark's last slot is a space again)
6289      assert_eq!(read_token()?, Some(T_SPACE!()));
6290      assert_eq!(read_token()?, Some(T_CS!("\\next")));
6291      unread(Tokens::new(vec![
6292        T_LETTER!("a"),
6293        T_SPACE!(),
6294        T_LETTER!("b"),
6295      ]));
6296      assert!(!input_unread_since(&mark));
6297      Ok(())
6298    })
6299    .unwrap();
6300  }
6301
6302  /// Marks nest, each answering for its own length: a mark on top of another reads as read once what was pushed
6303  /// between them is read, the one below it still unread; a `\futurelet`'s two tokens read and put back leave the input
6304  /// unread, more than [`MARK_HELD`] read and put back read as read (the stricter answer), and a native reader's
6305  /// consumption (`consume_pushback_to`) as any read. A mark of a mouth since closed reads as read. A list read down
6306  /// while a mark is taken at each step (an author list a macro holds, `\authorlist` of 3,000 `\author`/`\affiliation`
6307  /// pairs: revRC1's memory probe) keeps one run on the watch, no copy of the pushback (`InputMark` holds no heap).
6308  #[test]
6309  fn input_marks_nest_and_keep_no_copy_of_the_pushback() {
6310    reading_from_mouth(Mouth::default(), || {
6311      let letters = |n: usize| Tokens::new((0..n).map(|_| T_LETTER!("x")).collect());
6312      unread(letters(8));
6313      let outer = input_mark();
6314      unread(letters(2));
6315      let inner = input_mark();
6316      unread(letters(1));
6317      assert_eq!(read_token()?, Some(T_LETTER!("x")));
6318      assert!(input_unread_since(&inner) && input_unread_since(&outer));
6319      read_token()?;
6320      assert!(!input_unread_since(&inner));
6321      assert!(input_unread_since(&outer));
6322      // (a `\futurelet` below the outer mark: two tokens read, put back)
6323      read_token()?;
6324      let (a, b) = (read_token()?.unwrap(), read_token()?.unwrap());
6325      unread(Tokens::new(vec![a, b]));
6326      assert!(input_unread_since(&outer));
6327      // (five read and put back)
6328      let five: Vec<Token> = (0..5).map(|_| read_token().unwrap().unwrap()).collect();
6329      unread(Tokens::new(five));
6330      assert!(!input_unread_since(&outer));
6331      let mark = input_mark();
6332      consume_pushback_to(pushback_len() - 1);
6333      assert!(!input_unread_since(&mark));
6334      // (a mark of a mouth since closed)
6335      let closed = reading_from_mouth(Mouth::default(), || {
6336        unread(letters(1));
6337        Ok(input_mark())
6338      })?;
6339      assert!(!input_unread_since(&closed));
6340      // (a list read down, a mark at each step)
6341      while read_token()?.is_some() {}
6342      unread(letters(12_000));
6343      let mut marks = Vec::new();
6344      for _ in 0..3_000 {
6345        marks.push(input_mark());
6346        for _ in 0..4 {
6347          read_token()?;
6348        }
6349      }
6350      assert!(marks.iter().all(|mark| !input_unread_since(mark)));
6351      assert!(
6352        gullet!()
6353          .runtime
6354          .as_ref()
6355          .is_some_and(|rt| rt.watch.runs.len() <= 1)
6356      );
6357      fn copy<T: Copy>() {}
6358      copy::<InputMark>();
6359      Ok(())
6360    })
6361    .unwrap();
6362  }
6363
6364  /// An error that is no Fatal, for an inner context to fail with.
6365  fn fatal_free_failure() -> Result<()> { read_budget_error().map(|_| ()) }
6366
6367  /// The "Mouth is unexpectedly already closed" budget is the conversion's: after a predecessor on the thread spent it
6368  /// (0906.1883: 10K+), the next conversion's first such error is logged, not a Fatal (`reset_conversion_state`, revST3b).
6369  #[test]
6370  fn the_mouth_closed_budget_is_each_conversions() {
6371    let closing_its_own_mouth = || reading_from_mouth(Mouth::default(), || close_mouth(true));
6372    let counts = || {
6373      let c = snapshot_report_counts();
6374      (c.error, get_status_code())
6375    };
6376    initialize_report();
6377    let failed: Vec<usize> = (0..50)
6378      .filter(|_| closing_its_own_mouth().is_err())
6379      .collect();
6380    assert_eq!(failed, [49], "the 50th is the Fatal");
6381    assert_eq!(counts(), (10, 3));
6382    initialize_report();
6383    assert!(closing_its_own_mouth().is_ok());
6384    assert_eq!(counts(), (1, 2));
6385  }
6386
6387  /// A failed reading context closes its own mouth and those above it, by depth: another of the same name above it (two
6388  /// `Mouth::default()`, a `\scantokens`'s in a discarded run) is not its own, and the mouth under it stays open. A run
6389  /// that stopped inside one left its own mouth open, and the next close took the document's.
6390  #[test]
6391  fn a_failed_context_closes_its_own_mouths_by_depth() {
6392    reading_from_mouth(Mouth::default(), || {
6393      unread(Tokens::new(vec![T_LETTER!("o")]));
6394      let failed: Result<()> = reading_from_mouth(Mouth::default(), || {
6395        open_mouth(Mouth::default(), false);
6396        open_mouth(Mouth::default(), false);
6397        fatal_free_failure()
6398      });
6399      assert!(failed.is_err());
6400      assert_eq!(read_token()?, Some(T_LETTER!("o")));
6401      Ok(())
6402    })
6403    .unwrap();
6404  }
6405
6406  /// The count of open mouths holds the one in reading: with none open on entry, [`open_mouth`] pushes nothing on the stack
6407  /// and a count of the stack alone left the reader's own mouth open (and everything opened above it down to it). A failed
6408  /// context leaves as many open as it found: none, or one, or one and a stack.
6409  #[test]
6410  fn a_failed_context_leaves_as_many_mouths_as_it_found() {
6411    let close_all = || {
6412      while mouth_depth() > 0 {
6413        close_mouth(true).unwrap();
6414      }
6415    };
6416    close_all();
6417    for found in 0..3 {
6418      for opened_above in 0..3 {
6419        for _ in 0..found {
6420          open_mouth(Mouth::default(), false);
6421        }
6422        assert_eq!(mouth_depth(), found);
6423        let failed: Result<()> = reading_from_mouth(Mouth::default(), || {
6424          for _ in 0..opened_above {
6425            open_mouth(Mouth::default(), false);
6426          }
6427          fatal_free_failure()
6428        });
6429        assert!(failed.is_err());
6430        assert_eq!(
6431          mouth_depth(),
6432          found,
6433          "found {found}, opened {opened_above} above"
6434        );
6435        assert_eq!(gullet!().runtime.is_none(), found == 0);
6436        close_all();
6437      }
6438    }
6439  }
6440
6441  /// What [`read_internal_token_full`] tests per count, spelled as it spells them.
6442  fn is_due(count: usize, limit: Option<usize>, floor: usize) -> bool {
6443    limit.is_some_and(|limit| count > limit)
6444      || count & DEADLINE_CHECK_MASK == 0
6445      || (count > floor
6446        && (1..=CYCLE_GUARD_DUTY_ON).contains(&((count - floor) & (CYCLE_GUARD_DUTY_PERIOD - 1))))
6447  }
6448
6449  /// Runs `reads` counts from `start` as the read does, and fails if a due count takes the fast path. `change` is what
6450  /// a writer of the limit or floor does at one count: sets them and resets `full_read_at`.
6451  fn no_due_count_takes_the_fast_path(
6452    start: usize,
6453    reads: usize,
6454    (mut limit, mut floor): (Option<usize>, usize),
6455    change: Option<(usize, Option<usize>, usize)>,
6456  ) {
6457    let mut full_read_at = 0;
6458    for count in start + 1..=start + reads {
6459      if let Some((at, new_limit, new_floor)) = change
6460        && count == at
6461      {
6462        (limit, floor, full_read_at) = (new_limit, new_floor, 0);
6463      }
6464      if count < full_read_at {
6465        assert!(
6466          !is_due(count, limit, floor),
6467          "count {count} is due and took the fast path (start {start}, limit {limit:?}, floor {floor})"
6468        );
6469      } else {
6470        full_read_at = next_due_read(count, limit, floor);
6471      }
6472    }
6473  }
6474
6475  /// Around the limit, each multiple of the deadline's period and each window's edges.
6476  #[test]
6477  fn a_token_read_skips_only_what_is_not_due() {
6478    let limits = [
6479      None,
6480      Some(0),
6481      Some(5),
6482      Some(65_535),
6483      Some(65_536),
6484      Some(65_537),
6485      Some(70_000),
6486    ];
6487    let floors = [0, 1, 16_383, 16_384, 65_536, 100_000];
6488    for start in [0, 16_380, 65_530, 65_535, 131_070] {
6489      for limit in limits {
6490        for floor in floors {
6491          no_due_count_takes_the_fast_path(start, 140_000, (limit, floor), None);
6492        }
6493      }
6494    }
6495  }
6496
6497  /// A limit or floor changed mid-run: `set_token_limit`, `scale_token_limit_to_source`, `raise_cycle_guard_activate`.
6498  #[test]
6499  fn a_token_read_follows_a_limit_or_floor_changed_mid_run() {
6500    for at in [1, 2_047, 2_048, 16_385, 65_536, 65_537] {
6501      for (from, to) in [
6502        ((Some(1_000_000), 100_000), (Some(70_000), 100_000)),
6503        ((Some(70_000), 0), (None, 90_000)),
6504        ((None, 200_000), (Some(at + 3), 200_000)),
6505        ((None, 200_000), (None, at)),
6506      ] {
6507        no_due_count_takes_the_fast_path(0, 140_000, from, Some((at, to.0, to.1)));
6508      }
6509    }
6510  }
6511
6512  /// The runaway backstop grows with the bytes of EVERY opened source, not
6513  /// just the driver (source2e.tex: 15 KB over ~2 MB of `.dtx`).
6514  /// tex.web §444 `scan_int`: a decimal run, `'` octal, `"` hex, and a
6515  /// first token that is no numeric constant falls through to the internal-
6516  /// quantity path (§444's "Missing number, treated as zero" when nothing
6517  /// there is a number either). The decimal test is a non-allocating digit
6518  /// peek on the token's text (lever E), so the empty-text OTHER token —
6519  /// which the old vacuous `all(is_ascii_digit)` mis-read as a decimal and
6520  /// parsed to `i64::MAX` — now takes the missing-number route.
6521  #[test]
6522  fn read_normal_integer_arms_follow_scan_int() {
6523    reset_thread_state();
6524    initialize_gullet();
6525    let read = |tokens: Vec<Token>| -> Option<i64> {
6526      reading_from_mouth(Mouth::default(), || {
6527        unread_vec(tokens);
6528        let n = read_normal_integer()?.map(|n| n.value_of());
6529        // Drain whatever the reader left (an unread non-digit).
6530        while read_token()?.is_some() {}
6531        Ok(n)
6532      })
6533      .expect("no fatal")
6534    };
6535    let other = |s: &str| Token::new(s, Catcode::OTHER);
6536    assert_eq!(read(vec![other("1"), other("2"), T_SPACE!()]), Some(12));
6537    assert_eq!(read(vec![other("12"), other("3"), T_SPACE!()]), Some(123));
6538    assert_eq!(
6539      read(vec![other("'"), other("1"), other("7"), T_SPACE!()]),
6540      Some(15)
6541    );
6542    assert_eq!(
6543      read(vec![other("\""), other("F"), other("F"), T_SPACE!()]),
6544      Some(255)
6545    );
6546    assert_eq!(read(vec![other("`"), T_CS!("\\a"), T_SPACE!()]), Some(97));
6547    let dot = read(vec![other("."), T_SPACE!()]);
6548    let empty = read(vec![other(""), T_SPACE!()]);
6549    assert_eq!(
6550      dot, empty,
6551      "an empty-text OTHER token is no more a number than `.`"
6552    );
6553    assert_ne!(empty, Some(i64::MAX), "never the old fabricated i64::MAX");
6554  }
6555
6556  #[test]
6557  fn token_limit_scales_with_cumulative_source_bytes() {
6558    if std::env::var_os("LATEXML_TOKEN_LIMIT").is_some() {
6559      return;
6560    }
6561    initialize_gullet();
6562    scale_token_limit_to_source(15_000);
6563    assert_eq!(
6564      gullet_root().borrow().token_limit,
6565      Some(DEFAULT_TOKEN_LIMIT)
6566    );
6567    for _ in 0..40 {
6568      scale_token_limit_to_source(500_000);
6569    }
6570    assert_eq!(gullet_root().borrow().token_limit, Some(20_015_000 * 1000));
6571    // A fresh conversion starts over.
6572    initialize_gullet();
6573    assert_eq!(
6574      gullet_root().borrow().token_limit,
6575      Some(DEFAULT_TOKEN_LIMIT)
6576    );
6577  }
6578}