Skip to main content

latexml_core/
stomach.rs

1use std::{
2  borrow::Cow,
3  cell::{Cell, RefCell},
4  collections::VecDeque,
5  rc::Rc,
6  sync::LazyLock,
7  time::{Duration, Instant},
8};
9
10use crate::{digested::DigestedData, pin};
11
12/// Cached snapshot of `LXML_TRACE_BOUND_MODE` env var. Like the
13/// `TRACE_GROUP_END` cache in gullet.rs, this avoids per-digest
14/// `getenv` calls — glibc's `getenv` is unsafe under high-volume
15/// concurrent reads from many test threads, manifesting as SIGSEGV
16/// in `__GI_getenv` when running `cargo test --release --tests`.
17/// Sample once at static-init; subsequent reads are an atomic load.
18static TRACE_BOUND_MODE: LazyLock<bool> =
19  LazyLock::new(|| std::env::var("LXML_TRACE_BOUND_MODE").is_ok());
20/// `LXML_TRACE_FRAMES=1`: one line per stack-frame push/pop with the depth, the
21/// owning token and (on pop) the bound mode — the save-stack view of a
22/// group/box/mode imbalance.
23pub(crate) static TRACE_FRAMES: LazyLock<bool> =
24  LazyLock::new(|| std::env::var("LXML_TRACE_FRAMES").is_ok());
25/// `LXML_TRACE_TERMINAL=1`: for every bounded body (`digest_next_body` with a
26/// terminal), the terminal, each token the loop reads with the boxing depth,
27/// and the exit — shows which loop actually digests a token (a brace group is
28/// a NESTED body here, so an until-body's terminal inside `{…}` never reaches
29/// the outer loop).
30static TRACE_TERMINAL: LazyLock<bool> =
31  LazyLock::new(|| std::env::var("LXML_TRACE_TERMINAL").is_ok());
32
33// Conversion timeout: thread-local deadline, with the setup time kept off the clock when it was set
34// (`watchdog::off_the_clock`). When set, digest loops check it.
35thread_local! {
36  static CONVERSION_DEADLINE: Cell<Option<ConversionDeadline>> = const { Cell::new(None) };
37}
38
39#[derive(Clone, Copy)]
40struct ConversionDeadline {
41  at:         Instant,
42  off_at_set: Duration,
43  /// Until the watchdog's coarse clock reads past this, the deadline has not passed (`watchdog::coarse_now_ns`).
44  coarse_ns:  u64,
45}
46
47/// Set a conversion timeout (seconds from now). 0 = no timeout.
48pub fn set_timeout(seconds: u64) {
49  let deadline = (seconds > 0).then(|| {
50    let at = Instant::now() + Duration::from_secs(seconds);
51    let off_at_set = crate::watchdog::time_off_the_clock();
52    let coarse_ns = crate::watchdog::nanos_since_epoch(at);
53    ConversionDeadline { at, off_at_set, coarse_ns }
54  });
55  crate::watchdog::note_cooperative_deadline(deadline.map(|d| (d.at, d.off_at_set)));
56  CONVERSION_DEADLINE.with(|d| d.set(deadline));
57}
58
59// A logged Fatal raised where no `Result` reaches the caller: [`check_timeout`] raises it at the next step (OD #1028).
60thread_local! {
61  static STASHED_FATAL: Cell<Option<Error>> = const { Cell::new(None) };
62  // (whether one is stashed: a destructor-free read for the checkpoint's hot path)
63  static FATAL_STASHED: Cell<bool> = const { Cell::new(false) };
64}
65
66/// Keep `fatal` for the next digestion or build step to raise, as Perl's `die` stops there: a register getter's
67/// (`Definition::value_of` returns an `Option`), a `fontTest`'s in `Document::set_node`. The first one is kept.
68pub fn stash_fatal(fatal: Error) {
69  STASHED_FATAL.with(|stashed| {
70    let first = stashed.take();
71    stashed.set(first.or(Some(fatal)));
72  });
73  FATAL_STASHED.with(|armed| armed.set(true));
74}
75
76/// Take the stashed Fatal out to raise it, marked as printed (its line is: a Fatal logged since must not make a sink
77/// print it again).
78pub fn take_stashed_fatal() -> Option<Error> {
79  let fatal = set_aside_stashed_fatal()?;
80  fatal.mark_logged_fatal();
81  Some(fatal)
82}
83
84/// Set the stashed Fatal aside for a speculative scope to run without it (`logger::DiagnosticsHold`).
85pub(crate) fn set_aside_stashed_fatal() -> Option<Error> {
86  if !FATAL_STASHED.with(|armed| armed.replace(false)) {
87    return None;
88  }
89  STASHED_FATAL.with(Cell::take)
90}
91
92/// Put an enclosing scope's stashed Fatal back: it stays the first; the scope's own is kept when `keep_scope` and
93/// there was none.
94pub(crate) fn restore_stashed_fatal(outer: Option<Error>, keep_scope: bool) {
95  let scope = set_aside_stashed_fatal().filter(|_| keep_scope);
96  if let Some(fatal) = outer.or(scope) {
97    stash_fatal(fatal);
98  }
99}
100
101/// Whether the conversion's deadline ([`set_timeout`]) has passed — for a reader that may never return to a digestion
102/// loop (the gullet's token reads).
103pub fn conversion_deadline_passed() -> bool { deadline_passed_on(crate::watchdog::coarse_now_ns()) }
104
105/// The deadline test, on the watchdog's coarse clock when one runs (`coarse_now`), confirmed on the exact clock once
106/// that reads past it; `None`: the exact clock only.
107fn deadline_passed_on(coarse_now: Option<u64>) -> bool {
108  CONVERSION_DEADLINE.with(|d| {
109    let Some(mut deadline) = d.get() else {
110      return false;
111    };
112    let passed = || crate::watchdog::deadline_passed(deadline.at, deadline.off_at_set);
113    match coarse_now {
114      None => passed(),
115      Some(now) if now <= deadline.coarse_ns => false,
116      Some(_) if passed() => true,
117      Some(_) => {
118        // Setup run off the clock moved it: wait for the coarse clock to pass the moved deadline.
119        deadline.coarse_ns =
120          crate::watchdog::deadline_ns_lower_bound(deadline.at, deadline.off_at_set);
121        d.set(Some(deadline));
122        false
123      },
124    }
125  })
126}
127
128// Explicit override for the cooperative soft-RSS budget (bytes). When set it
129// takes precedence over the `LATEXML_RSS_CAP_BYTES` env; when `None` the env /
130// built-in default applies. The binary sets it from the single `--max-memory`
131// knob (via [`soft_cap_from_ceiling`]) so that ONE flag governs the whole
132// memory limit — this cooperative fuse rides a fixed fraction below the hard
133// Watchdog ceiling rather than being an independent number, and `--max-memory=0`
134// disables both (this fuse via a `0` cap → `None`, the Watchdog via
135// `max_rss_kb == 0`).
136thread_local! {
137  static RSS_CAP_OVERRIDE: Cell<Option<u64>> = const { Cell::new(None) };
138  /// The `--max-memory` (MiB) the override was derived from ([`apply_memory_ceiling`]), for the fuse's Fatal to name;
139  /// `None` when the fuse came from elsewhere (`cortex_worker`'s `--max-rss-mb`, the env, the default).
140  static MEMORY_CEILING_MIB: Cell<Option<u64>> = const { Cell::new(None) };
141}
142
143/// Override the cooperative soft-RSS memory budget, in bytes. `Some(0)`
144/// disables the budget; `Some(n)` caps at `n` bytes; `None` restores the
145/// `LATEXML_RSS_CAP_BYTES` env / built-in default. Mirrors the `--max-memory`
146/// CLI convention where `0` means "no limit". See `resolve_rss_cap` (private)
147/// for the precedence order.
148pub fn set_memory_cap(bytes: Option<u64>) {
149  RSS_CAP_OVERRIDE.with(|c| c.set(bytes));
150  MEMORY_CEILING_MIB.set(None);
151}
152
153thread_local! {
154  /// The streaming-restart watermark (bytes of RSS): set by the CLI for an
155  /// EAGER run that may be rerun under `--streaming`. Crossing it stops
156  /// digestion with `ErrorCategory::StreamingRestart` — an Info, not a Fatal —
157  /// just below the fuse, so the abandoned attempt leaves no Fatal line and no
158  /// salvaged partial document behind (`streaming_restart::restart_watermark`
159  /// sets where). `None` (the default, and every path that does not rerun) = no
160  /// watermark.
161  static STREAMING_RESTART_WATERMARK: Cell<Option<u64>> = const { Cell::new(None) };
162}
163
164/// Arm (or clear) the streaming-restart watermark for this thread.
165pub fn set_streaming_restart_watermark(bytes: Option<u64>) {
166  STREAMING_RESTART_WATERMARK.set(bytes);
167}
168
169/// Why eager digestion stopped for memory on this thread.
170#[derive(Clone, Copy, Debug, PartialEq, Eq)]
171pub enum RestartSignal {
172  /// The streaming-restart watermark (an Info, no output lost yet).
173  Watermark,
174  /// The cooperative memory fuse (a Fatal; the attempt's output is partial).
175  Fuse,
176}
177
178thread_local! {
179  /// Thread-local, so a worker with several conversion threads never restarts
180  /// one paper on another's stop (the watchdog's process-wide memory latch is
181  /// for the end-of-run report only).
182  static STREAMING_RESTART_SIGNAL: Cell<Option<RestartSignal>> = const { Cell::new(None) };
183}
184
185/// Record a memory stop for the restart decision (`take_streaming_restart_signal`).
186pub fn note_streaming_restart_signal(signal: RestartSignal) {
187  STREAMING_RESTART_SIGNAL.set(Some(signal));
188}
189
190/// The pending memory stop, cleared by the read.
191pub fn take_streaming_restart_signal() -> Option<RestartSignal> { STREAMING_RESTART_SIGNAL.take() }
192
193/// Derive the cooperative soft-RSS budget (bytes) from the hard `--max-memory`
194/// ceiling (MiB). The soft fuse sits at 75% of the ceiling, leaving ~25%
195/// headroom for the post-processing phase (libxml DOM + XSLT) that runs above
196/// digestion and which this cooperative guard cannot see. `0` in → `0` out
197/// (disabled), so `--max-memory=0` disables the whole memory limit. This keeps
198/// `--max-memory` the single knob: the hard Watchdog rides the ceiling, this
199/// fuse rides a fixed fraction below it — no independent second number.
200///
201/// The 75% factor reproduces the historical ~4.5 GB-under-6 GiB relationship at
202/// the 6144 MiB default (→ 4608 MiB) while scaling with any user-chosen ceiling
203/// (so a tight `--max-memory` also gets the graceful cooperative failure first,
204/// and a generous one raises both guards together).
205pub fn soft_cap_from_ceiling(max_memory_mib: u64) -> u64 {
206  (max_memory_mib.saturating_mul(3) / 4).saturating_mul(1024 * 1024)
207}
208
209/// Minimum boxes that must accumulate before the **soft-RSS** yield branch may
210/// fire (the box-budget branch is unaffected and still yields on its own).
211///
212/// The soft-RSS test is a LEVEL test with no hysteresis: `rss > watermark`. A
213/// document whose irreducible resident floor sits above the watermark therefore
214/// latches it on permanently and yields at every legal seam, accumulating
215/// almost nothing between yields. Measured on the 131 MB witness at
216/// `--max-memory 48000` (watermark 12 GB, pass-1 RSS 13.3-14.9 GB — above it
217/// for the entire run): **24,051,712 yields** producing **459,579 segments
218/// averaging 5.5 KB**, against a box budget of ~2.0 M boxes that would on its
219/// own have yielded ~12 times. The same binary on a witness that never crosses
220/// its watermark yields **8** times.
221///
222/// A floor restores the trigger's intent — "respond to memory pressure sooner
223/// than the box budget would" — without the degenerate per-seam case. 1024
224/// boxes is ~2.5 MB of box memory at the measured 2416 B/box, i.e. negligible
225/// against any watermark large enough to matter, so the pressure response stays
226/// effectively immediate while the yield count drops by ~3 orders of magnitude.
227///
228/// **The floor is waived under real pressure** — see `soft_yield_is_urgent`.
229/// The soft-RSS branch exists because "the box budget alone assumes a per-box
230/// footprint; on content whose real cost per box is higher (math-dense trees),
231/// RSS crosses the ceiling long before the box count does". A floor that
232/// applied unconditionally would blunt that valve for exactly the pathological
233/// input it was added for: 1024 boxes of ordinary content is ~2.5 MB, but 1024
234/// boxes of something pathological is unbounded, and the fuse could fire inside
235/// one un-yielded window. So above a higher RSS mark the floor is ignored.
236///
237/// Env-overridable for calibration only (`LATEXML_SOFT_YIELD_MIN_BOXES`),
238/// deliberately not a CLI flag — same reasoning as `LATEXML_SPILL_AT_MIB`.
239/// Override the soft-RSS floor directly, bypassing the env lookup. For tests
240/// that need to drive the degenerate (floor = 1) and fixed (floor = N) regimes
241/// in one process — see `115_soft_yield_floor`.
242pub fn set_soft_yield_min_boxes(boxes: usize) { SOFT_YIELD_MIN_BOXES.set(Some(boxes)); }
243
244/// Is memory pressure URGENT enough to waive the soft-yield floor?
245///
246/// Halfway from the spill watermark to the cooperative fuse. Below this the
247/// floor applies and yields stay coarse; above it every legal seam yields, as
248/// before this floor existed — so a document whose per-box footprint is wildly
249/// larger than the 2416 B the box budget assumes still gets the immediate
250/// response the soft-RSS branch was introduced to provide, instead of Fatal-ing
251/// inside a 1024-box window.
252fn soft_yield_is_urgent(rss_kb: u64) -> bool {
253  soft_yield_urgency(
254    rss_kb,
255    spill_mark_kb().map(|kb| kb * 1024),
256    resolve_rss_cap(),
257  )
258}
259
260/// The pure predicate behind [`soft_yield_is_urgent`], split out so the
261/// arithmetic is unit-testable (an integration test would need a real RSS cap
262/// near the test process's actual footprint — flaky by construction on the
263/// 16 GB CI runner). `watermark`/`fuse` in bytes, `rss_kb` in KiB.
264fn soft_yield_urgency(rss_kb: u64, watermark: Option<u64>, fuse: Option<u64>) -> bool {
265  match (watermark, fuse) {
266    (Some(watermark), Some(fuse)) if fuse > watermark => {
267      rss_kb.saturating_mul(1024) >= watermark + (fuse - watermark) / 2
268    },
269    // No fuse to divide (`--max-memory=0`): the floor always applies, matching
270    // the watermark fallback's own "no ceiling to race" reasoning.
271    _ => false,
272  }
273}
274
275thread_local! {
276  /// Set while a `\left`/`\middle`/`\right` delimiter is digested ([`digest_as_delimiter`]).
277  static DIGESTING_DELIMITER: Cell<bool> = const { Cell::new(false) };
278}
279
280/// Digests `f`'s token as a delimiter: tex.web §1160 `scan_delimiter` takes a letter or other character by its
281/// `\delcode`, never its `\mathcode`, so a math-active character (`\mathcode`(="8000`, the active `(` a `\left(`) is
282/// that character, not its active meaning — which, `\left(` itself, recursed without end (2609.40266).
283pub fn digest_as_delimiter<T>(f: impl FnOnce() -> T) -> T {
284  // Restored on unwind too: a sweep catches a paper's panic and converts the next on this thread.
285  struct Restore(bool);
286  impl Drop for Restore {
287    fn drop(&mut self) { DIGESTING_DELIMITER.set(self.0); }
288  }
289  let _restore = Restore(DIGESTING_DELIMITER.replace(true));
290  f()
291}
292
293/// Whether a delimiter is being digested ([`digest_as_delimiter`]).
294pub fn digesting_delimiter() -> bool { DIGESTING_DELIMITER.get() }
295
296thread_local! {
297  /// RSS (KB) at the last fragment yield (or at digestion start): the soft-RSS
298  /// seam's GROWTH floor measures accumulation directly as resident memory
299  /// gained since then — the box-count floor never fires for a few huge
300  /// top-level bodies (pgf-spectra LSE: ~194 pictures, 6.4 GB, never 1024
301  /// boxes), with no fuse (`--max-memory=0`) nothing is ever "urgent", and a
302  /// box-tree byte ESTIMATE is a per-box-capped lower bound that undercounts
303  /// such pictures ~100× (measured: 6.36 GB, no transition).
304  static LAST_YIELD_RSS_KB: Cell<u64> = const { Cell::new(0) };
305}
306
307/// The growth floor of the soft-RSS yield, in KB: once over the watermark, a
308/// seam yields when at least this much resident memory was gained since the
309/// last yield — enough to be worth a spill, and far above the degenerate
310/// regime's 5.5 KB segments.
311const SOFT_YIELD_MIN_GROWTH_KB: u64 = 64 * 1024;
312
313/// Record the RSS baseline the growth floor measures from (digestion start
314/// and every yield).
315fn note_yield_rss_baseline(rss_kb: u64) { LAST_YIELD_RSS_KB.set(rss_kb); }
316
317/// Re-baseline the growth floor on the CURRENT resident set — called where the
318/// adaptive eager phase arms the soft trigger, i.e. after the engine load, so
319/// the first growth window measures the document alone.
320pub fn rebaseline_soft_yield_growth() {
321  if let Some(rss_kb) = crate::watchdog::process_rss_kb() {
322    LAST_SAMPLED_RSS_KB.set(rss_kb);
323    note_yield_rss_baseline(rss_kb);
324  }
325}
326
327/// Cached: this sits on the per-seam yield predicate, which the 131 MB witness
328/// evaluates tens of millions of times — an `std::env::var` there would be its
329/// own hotspot.
330pub fn soft_yield_min_boxes() -> usize {
331  const DEFAULT: usize = 1024;
332  if let Some(cached) = SOFT_YIELD_MIN_BOXES.get() {
333    return cached;
334  }
335  let resolved = std::env::var("LATEXML_SOFT_YIELD_MIN_BOXES")
336    .ok()
337    .and_then(|v| v.parse::<usize>().ok())
338    .unwrap_or(DEFAULT);
339  SOFT_YIELD_MIN_BOXES.set(Some(resolved));
340  resolved
341}
342
343thread_local! {
344  /// In-process override of the spill watermark (bytes), consulted before the
345  /// operator-facing `LATEXML_SPILL_AT_MIB` env. The environment is READ-ONLY
346  /// for this code base — a test or an embedder that needs a different
347  /// watermark sets this knob instead of mutating the process env.
348  static SPILL_WATERMARK_OVERRIDE: Cell<Option<u64>> = const { Cell::new(None) };
349}
350
351/// See `SPILL_WATERMARK_OVERRIDE`; `None` restores the env/default policy.
352pub fn set_spill_watermark_override(bytes: Option<u64>) {
353  SPILL_WATERMARK_OVERRIDE.with(|c| c.set(bytes));
354}
355
356thread_local! {
357  /// Set by `--streaming=false`: the conversion has no spill watermark, so an eager run never turns into
358  /// streaming pass 1 (`digest_adaptive` arms its yield only at a watermark).
359  static SPILL_DISABLED: Cell<bool> = const { Cell::new(false) };
360}
361
362/// See `SPILL_DISABLED`; wins over the override, the env and the default.
363pub fn set_spill_disabled(disabled: bool) { SPILL_DISABLED.with(|c| c.set(disabled)); }
364
365/// The RAM watermark, in bytes above the conversion's starting RSS ([`spill_mark_kb`]), at which streaming pass 1
366/// begins spilling closed subtrees to disk — the second derived quantity of the single
367/// `--max-memory` knob, and deliberately NOT a flag of its own (a watermark a
368/// user could raise above the fuse would Fatal before it ever spilled).
369///
370/// **A third of the cooperative fuse.** Not a half: the yields fire only at
371/// legal seams (a large alignment digests straight through any threshold), the
372/// RSS sample lags by up to 1024 guard ticks, and per-run bookkeeping creeps
373/// monotonically — measured on the 131 MB witness, a half-of-fuse watermark
374/// steadied pass 1 around 33 GB and the creep then walked it into the 37.7 GB
375/// fuse and died, where a third completed at 28.1 GB peak.
376///
377/// **With `--max-memory=0` there is no fuse to divide, and the watermark must
378/// still exist**: disabling the death ceiling says "do not kill me", not "let
379/// the machine run out". Fall back to an eighth of physical RAM, which lands
380/// the same 12 GiB on a 96 GB host that the validated 48 GiB ceiling derives.
381pub fn spill_watermark_bytes() -> Option<u64> {
382  if SPILL_DISABLED.with(Cell::get) {
383    return None;
384  }
385  if let Some(bytes) = SPILL_WATERMARK_OVERRIDE.with(|c| c.get()) {
386    return Some(bytes);
387  }
388  // Calibration override (`LATEXML_SPILL_AT_MIB`), deliberately env-only and
389  // NOT a CLI flag: a user-settable watermark could be raised above the fuse,
390  // producing a run that Fatals before it ever spills. It exists so the
391  // fuse-fraction below can be re-derived by measurement rather than argued.
392  if let Some(mib) = std::env::var("LATEXML_SPILL_AT_MIB")
393    .ok()
394    .and_then(|v| v.parse::<u64>().ok())
395  {
396    return Some(mib.saturating_mul(1024 * 1024));
397  }
398  match resolve_rss_cap() {
399    Some(fuse) => Some(fuse / 3),
400    None => crate::watchdog::total_memory_bytes().map(|ram| ram / 8),
401  }
402}
403
404thread_local! {
405  /// The process's resident set (KB) when this conversion's digestion was set up ([`mark_conversion_rss_baseline`]).
406  static CONVERSION_RSS_BASELINE_KB: Cell<u64> = const { Cell::new(0) };
407}
408
409/// Record the resident set the spill watermark is measured from: the conversion's own start, so a persistent worker
410/// switches a paper to streaming where that paper alone would (ST3b: 2507.13358 after 63 others).
411pub fn mark_conversion_rss_baseline() {
412  CONVERSION_RSS_BASELINE_KB.set(crate::watchdog::process_rss_kb().unwrap_or(0));
413}
414
415/// The resident set (KB) at which this conversion spills: [`spill_watermark_bytes`] above its starting RSS, never
416/// closer to the fuse (process RSS, it guards the machine) than two watermarks — the headroom the fuse fraction was
417/// calibrated for (a half-of-fuse mark crept into the fuse, [`spill_watermark_bytes`]). With the default third-of-fuse
418/// watermark that cap is the watermark itself, so under a fuse the mark is absolute, as before the conversion's
419/// baseline (revSTRM: a worker near its recycle threshold must not spill later than the calibration allows); the
420/// baseline moves the mark only without a fuse or under a smaller calibration watermark. Order independence rests on a
421/// switched conversion writing the eager XML, not on the mark. A zero watermark (a test's or a calibration's
422/// `LATEXML_SPILL_AT_MIB=0`) puts every seam over it.
423pub fn spill_mark_kb() -> Option<u64> {
424  let watermark_kb = spill_watermark_bytes()? / 1024;
425  Some(spill_mark(
426    CONVERSION_RSS_BASELINE_KB.get(),
427    watermark_kb,
428    resolve_rss_cap(),
429  ))
430}
431
432/// The arithmetic of [`spill_mark_kb`] (KB; `fuse` in bytes).
433fn spill_mark(baseline_kb: u64, watermark_kb: u64, fuse: Option<u64>) -> u64 {
434  if watermark_kb == 0 {
435    return 0;
436  }
437  let mark = baseline_kb.saturating_add(watermark_kb);
438  match fuse {
439    Some(fuse) => mark.min(
440      (fuse / 1024)
441        .saturating_sub(2 * watermark_kb)
442        .max(watermark_kb),
443    ),
444    None => mark,
445  }
446}
447
448/// Apply the single `--max-memory` ceiling (MiB) to this thread's cooperative
449/// soft fuse, so the one knob means the same thing on every conversion path.
450///
451/// **`--max-memory` wins over `LATEXML_RSS_CAP_BYTES`, unconditionally.** The
452/// flag is the single knob; an env var must not silently override what the user
453/// typed. This deliberately overwrites the env, which is why the env keeps its
454/// meaning exactly where no flag exists to contradict it: embedders that never
455/// parse CLI arguments and so never reach this function, such as the library
456/// test harness (`util::test`, which pins 9 GB). `cortex_worker` sets the fuse
457/// from its own `--max-rss-mb` through [`set_memory_cap`], on every conversion
458/// thread.
459///
460/// Callers must be EVERY conversion path: the plain one, the `--server` forked
461/// body child, and the in-process fallback. When only the first called it,
462/// `--server --max-memory=0` still ran against a live 4.5 GB fuse while the help
463/// text promised the limit was off.
464pub fn apply_memory_ceiling(max_memory_mib: u64) {
465  set_memory_cap(Some(soft_cap_from_ceiling(max_memory_mib)));
466  MEMORY_CEILING_MIB.set(Some(max_memory_mib));
467}
468
469/// Resolve the effective soft-RSS budget: `None` = disabled (no ceiling),
470/// `Some(n)` = abort above `n` bytes. Precedence: the explicit
471/// [`set_memory_cap`] override, else `LATEXML_RSS_CAP_BYTES`, else the 4.5 GB
472/// default. A cap of `0` from EITHER source resolves to `None`, so
473/// `--max-memory=0` / `LATEXML_RSS_CAP_BYTES=0` mean "no limit" — not "abort
474/// immediately" (a literal `0` compared as `rss_bytes > 0` is always true).
475///
476/// Note the env is consulted only when nothing set the override — i.e. only for
477/// embedders that never call [`apply_memory_ceiling`] or [`set_memory_cap`].
478/// Every path in the `latexml_oxide` binary calls the first, so there
479/// `--max-memory` always wins; every `cortex_worker` conversion the second, from
480/// `--max-rss-mb`.
481pub fn resolve_rss_cap() -> Option<u64> {
482  let cap = RSS_CAP_OVERRIDE.with(|c| c.get()).unwrap_or_else(|| {
483    std::env::var("LATEXML_RSS_CAP_BYTES")
484      .ok()
485      .and_then(|v| v.parse::<u64>().ok())
486      .unwrap_or(4_500_000_000)
487  });
488  (cap > 0).then_some(cap)
489}
490
491/// Check if conversion has timed out. Returns Err if deadline exceeded.
492///
493/// The deadline is read on the watchdog's coarse clock (one atomic load) while a watchdog runs, else on the exact
494/// clock; a caller that polls rarely uses [`check_timeout_now`].
495///
496/// Also samples RSS via /proc/self/status every ~1024 calls and raises
497/// `Fatal:oom:memory_budget` if the process is approaching the worker
498/// memory cap. R35.A witnesses (plain-TeX `$$\displaylines{ … \picture
499/// … }$$`, 7 sandbox papers from 1999–2006) trigger a runaway where
500/// `set_alloc_error_hook` fires AFTER the process has already allocated
501/// ~5+ GB; that hook can't easily walk back the call site under
502/// `panic="unwind"`. Sampling RSS here at well below the OS ulimit
503/// gives us a clean diagnostic and a unwound stack via `fatal!`.
504pub fn check_timeout() -> Result<()> { check_timeout_on(false) }
505
506/// [`check_timeout`] reading the deadline on the exact clock even while a watchdog runs, for a caller that polls rarely
507/// (once a page, the render workers' parent at 10 Hz) and so should not wait for the watchdog's next 100 ms publish.
508pub fn check_timeout_now() -> Result<()> { check_timeout_on(true) }
509
510fn check_timeout_on(exact: bool) -> Result<()> {
511  if let Some(fatal) = take_stashed_fatal() {
512    return Err(fatal);
513  }
514  // Box-list cycle guard fired in `push_box_list` (which cannot unwind) —
515  // surface it here, the regular Result-returning digestion checkpoint.
516  // (The `stomach_mut!` macro is defined textually below; use STOMACH
517  // directly, with a try-borrow so a transient borrow just defers to the
518  // next tick.)
519  let pending = stomach_root()
520    .try_borrow_mut()
521    .ok()
522    .and_then(|mut s| s.pending_cycle_fatal.take());
523  if let Some((category, msg)) = pending {
524    use crate::common::error::{Error as LatexmlError, ErrorTarget};
525    return Err(LatexmlError::from(ErrorData {
526      target: ErrorTarget::Stomach,
527      category,
528      message: msg,
529    }));
530  }
531  std::thread_local! {
532    static MEM_TICK: Cell<usize> = const { Cell::new(0) };
533  }
534  let tick = MEM_TICK.with(|t| {
535    let v = t.get().wrapping_add(1);
536    t.set(v);
537    v
538  });
539  let passed = match crate::watchdog::coarse_now_ns() {
540    Some(coarse_now) if !exact => deadline_passed_on(Some(coarse_now)),
541    // No watchdog keeps the coarse clock (the LSP server's in-process path, tests, embedders): the exact clock on
542    // every call, as before — a gate here could defer the deadline by that many slow steps.
543    _ => deadline_passed_on(None),
544  };
545  if passed {
546    fatal!(Timeout, Convert, "Conversion timed out!");
547  }
548  // Soft memory budget: every ~1024 calls, peek at our own RSS.
549  // 1024-call cadence keeps overhead negligible on the hot path
550  // (each call reads /proc/self/statm — a single syscall).
551  if tick & 0x3FF == 0 {
552    // Single RSS-reading seam: `watchdog::process_rss_kb` (this was a second
553    // hand-rolled /proc parser; PR #249 review P3-12). When the watchdog
554    // grows macOS/Windows backends, this cap follows for free.
555    {
556      {
557        if let Some(rss_kb) = crate::watchdog::process_rss_kb() {
558          LAST_SAMPLED_RSS_KB.set(rss_kb);
559          let rss_bytes = rss_kb * 1024;
560          // R35.A safety cap: 4.5 GB RSS. Real documents in the wp5 /
561          // canvas3 corpus stay below 1 GB peak RSS, so this is well
562          // into pathological territory while leaving headroom for
563          // post-processing (XSLT, MathML chain).
564          // Override via LATEXML_RSS_CAP_BYTES env or `set_memory_cap`; a
565          // value of 0 (or `--max-memory=0`) disables it — see
566          // `resolve_rss_cap`.
567          //
568          // This is a *per-process* fuse, deliberately kept LOW. It must
569          // bound ONE conversion: in production the binary is
570          // single-conversion (one paper per process), and a massively
571          // parallel fleet runs many such processes at once — so the
572          // aggregate host RSS is `N_processes × this_cap`. Raising the
573          // default would let a busy fleet OOM the machine. The
574          // `cortex_worker` fleet OVERRIDES it with its own per-child
575          // ceiling (`--max-rss-mb`, from `--child-mem-limit-mb`).
576          //
577          // The ONE multi-conversion-in-one-process case is the test
578          // harness: libtest spawns a thread per test, so at `cargo
579          // test`'s default parallelism on a many-core box (e.g. -j128)
580          // the process-wide RSS is the *sum* over all in-flight
581          // conversions and trips this single-conversion cap on
582          // otherwise-fine documents. That is handled NOT by raising this
583          // default but by the harness setting LATEXML_RSS_CAP_BYTES at
584          // test setup (latexml_oxide `util::test::init_test_rss_cap`).
585          // Any other single-process-many-conversion driver should do the
586          // same.
587          if let Some(watermark) = STREAMING_RESTART_WATERMARK.get()
588            && rss_bytes > watermark
589          {
590            // One stop per arming: the rerun is streaming and never armed.
591            STREAMING_RESTART_WATERMARK.set(None);
592            note_streaming_restart_signal(RestartSignal::Watermark);
593            use crate::common::error::{Error as LatexmlError, ErrorCategory, ErrorTarget};
594            return Err(LatexmlError::from(ErrorData {
595              target:   ErrorTarget::Timeout,
596              category: ErrorCategory::StreamingRestart,
597              message:  format!(
598                "eager digestion reached the streaming-restart watermark: RSS {} MB > {} MB; \
599                 rerunning under --streaming",
600                rss_bytes / 1_000_000,
601                watermark / 1_000_000
602              ),
603            }));
604          }
605          if let Some(cap) = resolve_rss_cap()
606            && rss_bytes > cap
607          {
608            // R35.A debug: when LATEXML_DEBUG_MEMBUDGET=1 is set, dump
609            // a stack backtrace before exiting so we can identify the
610            // expansion loop responsible. Backtrace allocation is
611            // fine here — we haven't hit the OS ulimit yet (we're
612            // 1.5 GB below it by default).
613            if std::env::var_os("LATEXML_DEBUG_MEMBUDGET").is_some() {
614              eprintln!(
615                "[membudget] RSS {} MB > cap {} MB — dumping backtrace",
616                rss_bytes / 1_000_000,
617                cap / 1_000_000
618              );
619              // Permanent LATEXML_DEBUG_MEMBUDGET diagnostic: which
620              // accumulating list is growing? (MEMORY.md's OOM-diagnosis
621              // recipe depends on this dump — do not remove as "temp".)
622              if let Ok(st) = stomach_root().try_borrow() {
623                eprintln!(
624                  "[membudget] box_list={} (~{} MB est) token_stack={} boxing={} localized_box_list_total={}",
625                  st.box_list.len(),
626                  estimate_box_list_bytes(&st.box_list) / 1_000_000,
627                  st.token_stack.len(),
628                  st.boxing.len(),
629                  st.localized_box_list
630                    .iter()
631                    .map(|level| level.list.len())
632                    .sum::<usize>(),
633                );
634              }
635              if let Ok(g) = gullet::gullet_root().try_borrow() {
636                let pb = g.runtime.as_ref().map(|r| r.pushback.len()).unwrap_or(0);
637                eprintln!("[membudget] gullet pushback={pb} progress={}", g.progress);
638              }
639              let bt = std::backtrace::Backtrace::force_capture();
640              eprintln!("{bt}");
641            }
642            // The actionable half of the message is a KNOWN NEED, not an
643            // anomaly: a document's peak scales with macro expansion and math
644            // density (the 131 MB witness needs ~23 GB resident just to
645            // stream through core), so the honest advice is "raise the
646            // ceiling", plus the derived flag value so the user knows which
647            // number they are raising — the cap here is the 75% fuse, not
648            // the `--max-memory` figure they typed. The latch lets the
649            // binary's end-of-run report add the kernel-tracked peak
650            // (`watchdog::peak_memory_report`, emitted only when this fired).
651            // A fuse `--max-memory` did not set (`cortex_worker`'s is its `--max-rss-mb`) names no CLI flag.
652            crate::watchdog::note_memory_fatal();
653            note_streaming_restart_signal(RestartSignal::Fuse);
654            let knob = match MEMORY_CEILING_MIB.get() {
655              Some(mib) => format!(
656                "the cooperative fuse at 75% of --max-memory={mib}). This document needs a larger \
657                 ceiling: rerun with a higher --max-memory on a machine with enough free RAM."
658              ),
659              None => "the cooperative memory fuse). This document needs a larger ceiling.".into(),
660            };
661            fatal!(
662              Timeout,
663              MemoryBudget,
664              format!(
665                "Memory budget exceeded: RSS {} MB > cap {} MB ({knob}",
666                rss_bytes / 1_000_000,
667                cap / 1_000_000,
668              )
669            );
670          }
671        }
672      }
673    }
674  }
675  Ok(())
676}
677
678use crate::{
679  BoxOps, Digested, TexMode,
680  binding::def::dialect::{END_HOOKS_RAN, environment_end_hooks},
681  comment::Comment,
682  common::{arena, arena::SymHashMap as HashMap, error::*, font, font::Font},
683  definition::{
684    Definition, ExpansionBody,
685    constructor::{Constructor, TexGroup},
686    expandable::Expandable,
687    register::RegisterValue,
688  },
689  gullet,
690  list::List,
691  mouth::{Mouth, MouthOptions},
692  state::*,
693  tbox::*,
694  token::{Catcode, Token},
695  tokens::Tokens,
696};
697
698static MAXSTACK: usize = 200;
699
700/// Where the paragraph being built on the box list began: the list's length when horizontal mode was entered from
701/// vertical, and whether its indent box is implicit. tex.web §1091 `new_graf` starts the paragraph on a list of its
702/// own, so `\lastbox` (§1080) never reaches the vertical material before it; LaTeXML builds the paragraph on the
703/// enclosing list, and `index` stands in for that list's bottom. TeX puts an indent box first unless `\noindent`
704/// began the paragraph; LaTeXML lists it only for `\indent` (its whatsit), so a paragraph begun by a letter or
705/// `\leavevmode` has an `implicit_indent`. Without one, a paragraph with nothing listed is null (§1096): `\noindent\par`,
706/// or `\indent\setbox0\lastbox\par` — `\lastbox` takes the implicit one too (`take_implicit_indent`). In a text group
707/// opened in the paragraph (`in_group`) the paragraph began below the group's own list, at its bottom.
708#[derive(Clone, Copy, Debug)]
709pub(crate) struct ParagraphStart {
710  index:           usize,
711  implicit_indent: bool,
712  /// The list is a text group's, opened in the paragraph ([`digest_group_body_in_paragraph`]).
713  in_group:        bool,
714}
715
716/// How a box list a Fatal leaves pending closes when the salvage keeps it (`salvage_pending_box_lists`, OD #251): the
717/// list's boxes in, what goes to the enclosing list out. Set by the construct that opened the list
718/// ([`close_pending_list_as`]); a list with none joins the enclosing one as it is (a body, a group).
719pub type PendingListCloser = Box<dyn FnOnce(Vec<Digested>) -> Vec<Digested>>;
720
721/// A box list suspended by [`new_local_box_list`]: the enclosing list, where its paragraph began, and how the list
722/// opened above it closes on a Fatal.
723#[derive(Default)]
724struct SuspendedList {
725  list:            Vec<Digested>,
726  paragraph_start: Option<ParagraphStart>,
727  closer:          Option<PendingListCloser>,
728  /// The list opened above lies in a formula: its closer's construct is in math or digests math.
729  in_formula:      bool,
730  /// The list opened above was opened in a vertical mode, which can hold paragraphs.
731  vertical:        bool,
732}
733
734/// The Stomach is responsible for digesting tokens into boxes, lists, etc.
735#[derive(Default)]
736pub struct Stomach {
737  /// currently invoked tokens
738  pub token_stack:     Vec<Token>,
739  /// tracks the tokens of boxing groups(?)
740  pub boxing:          Vec<Token>,
741  /// localized box lists for stacked digestion calls, each with its `paragraph_start`
742  localized_box_list:  Vec<SuspendedList>,
743  /// collects the intermediate boxes resulting from a `digest` call.
744  pub box_list:        Vec<Digested>,
745  /// Where the paragraph being built on `box_list` began ([`ParagraphStart`]).
746  paragraph_start:     Option<ParagraphStart>,
747  /// Windowed cycle detector over the accumulated digest list — the stomach
748  /// analog of the gullet's expansion-stream guard. Catches box-accumulation
749  /// runaways (a recursive macro/path that digests the same boxes forever, e.g.
750  /// pgf's `to [loop]` arc on a pathological picture, 2201.09268) that bypass
751  /// the gullet read loop entirely. Engaged only once `box_list` has grown far
752  /// past any flushed-document size. See [`crate::cycle_guard`].
753  cycle_guard:         crate::cycle_guard::CycleGuard,
754  /// The gullet's token progress at the last box the cycle guard recorded.
755  cycle_progress:      usize,
756  /// The tokens read for each recorded box ([`crate::cycle_guard::SpanHistory`]):
757  /// a box period is a loop only when its input repeats too.
758  cycle_spans:         crate::cycle_guard::SpanHistory,
759  /// The same spans without the register values read: a loop whose counters move repeats these (OD #538).
760  cycle_spans_raw:     crate::cycle_guard::SpanHistory,
761  /// Boxes the cycle guard has recorded this conversion, the clock `cycle_stuck` is measured on.
762  cycle_records:       usize,
763  /// How long a box period whose spans repeat with their register values has held (`STOMACH_CYCLE_HOLD_STUCK`).
764  cycle_stuck:         crate::cycle_guard::Persistence,
765  /// How long, in tokens read, a box period whose spans repeat register values aside has held
766  /// (`STOMACH_CYCLE_HOLD_MOVING`).
767  cycle_moving:        crate::cycle_guard::Persistence,
768  /// Set by the guarded box appenders when a stomach guard fires; consumed
769  /// and turned into a `Fatal` by `check_timeout` (the next
770  /// `Result`-returning checkpoint — `push_box_list` itself returns `()` and
771  /// cannot unwind). Carries the structured category so size/byte/depth
772  /// breaches report as `Stomach:MemoryBudget` while only genuine detected
773  /// cycles report as `Stomach:Recursion` — canvas/telemetry clustering on
774  /// `target:category` can tell them apart (PR #249 review P2-8).
775  pending_cycle_fatal: Option<(ErrorCategory, String)>,
776}
777
778thread_root! {
779pub fn stomach_root() -> RefCell<Stomach> = RefCell::new(Stomach::default());
780}
781
782// ---- Fragment yield (streaming mode) -------------------------------------
783//
784// Deliberately OUTSIDE the `Stomach` struct: these are driver-level
785// configuration, like the RSS cap — `initialize_stomach` resets the digestion
786// state between documents but must not forget that the driver asked for
787// fragmented digestion.
788
789thread_local! {
790  /// When `Some(n)`, `digest_next_body` may YIELD — return the boxes accumulated
791  /// so far, gullet and State untouched — once the current level holds `n` boxes
792  /// AND the position is a legal fragment seam. `None` (default) = eager.
793  static FRAGMENT_YIELD_BUDGET: Cell<Option<usize>> = const { Cell::new(None) };
794}
795thread_local! {
796  /// Set on yield; read-and-cleared by the streaming driver to distinguish
797  /// "more to come" from EOF.
798  static FRAGMENT_YIELDED: Cell<bool> = const { Cell::new(false) };
799}
800thread_local! {
801  /// A binding's request to yield at the NEXT legal seam regardless of the box
802  /// budget (`request_fragment_yield`): the end of a picture. A tikzpicture's
803  /// tens of thousands of path, coordinate and scope boxes sit at a deep group
804  /// level with no seam until it closes, then reach the body as ONE box — the
805  /// budget's count never sees them, and the RSS branch waits for its floor
806  /// (pgf-PeriodicTable: ~47,000 boxes and ~106 MB per table on the release
807  /// binary; the manual's 53 redraws peak at 24.8 GB eager, and an eight-table
808  /// document streamed under a 1 GB cap tripped the fuse mid-table with a
809  /// 39-byte output). The completed picture is the natural absorb-and-free
810  /// unit. Cleared on yield and whenever a driver sets the budget; inert
811  /// without a budget.
812  static FRAGMENT_YIELD_REQUESTED: Cell<bool> = const { Cell::new(false) };
813}
814thread_local! {
815  /// Serial of the last stack frame pushed (`lx@frame@id`): the identity a
816  /// box reader keys its terminal on (tex.web §1068 dispatches `}` on
817  /// `cur_group`, the group itself, never on the save-stack depth).
818  static FRAME_SERIAL: Cell<u64> = const { Cell::new(0) };
819}
820thread_local! {
821  /// Total yields this conversion (telemetry + test probe).
822  static FRAGMENT_YIELD_COUNT: Cell<usize> = const { Cell::new(0) };
823}
824thread_local! {
825  /// Soft RSS threshold (KiB) above which the yield predicate fires regardless
826  /// of the box count. The box budget alone assumes a per-box footprint; on
827  /// content whose real cost per box is higher (math-dense trees, debug
828  /// builds), RSS crosses the ceiling long before the box count does —
829  /// measured on the 19.8 MB witness at cap 24 GB, where the fuse fired
830  /// during early fragments while the 2.6M-box budget sat untouched.
831  static FRAGMENT_YIELD_RSS_SOFT_KB: Cell<Option<u64>> = const { Cell::new(None) };
832}
833thread_local! {
834  /// Resolved-once floor for the soft-RSS branch — see [`soft_yield_min_boxes`].
835  static SOFT_YIELD_MIN_BOXES: Cell<Option<usize>> = const { Cell::new(None) };
836}
837thread_local! {
838  /// The most recent RSS sample from `check_timeout`'s 1024-call cadence, so
839  /// the yield predicate reads a cell instead of `/proc`.
840  static LAST_SAMPLED_RSS_KB: Cell<u64> = const { Cell::new(0) };
841}
842
843/// Set (or clear) the soft-RSS yield threshold, in KiB.
844pub fn set_fragment_yield_rss_soft_kb(kb: Option<u64>) { FRAGMENT_YIELD_RSS_SOFT_KB.set(kb); }
845/// The armed soft-RSS yield watermark (KB), if any — see `set_fragment_yield_rss_soft_kb`.
846pub fn fragment_yield_rss_soft_kb() -> Option<u64> { FRAGMENT_YIELD_RSS_SOFT_KB.get() }
847
848/// The most recent sampled RSS in KiB — seeded with the real RSS at
849/// `initialize_stomach` / `rebaseline_soft_yield_growth`, then refreshed by the
850/// periodic sampler in `check_timeout`.
851pub fn last_sampled_rss_kb() -> u64 { LAST_SAMPLED_RSS_KB.get() }
852
853/// Ask digestion to yield at legal fragment seams once `budget` boxes have
854/// accumulated at the current level (`None` restores eager digestion). Set by
855/// the streaming pass-1 driver; the budget is a box COUNT — the driver derives
856/// it from the byte ceiling via the measured per-box footprint, the same basis
857/// as the box-list guards.
858pub fn set_fragment_yield_budget(budget: Option<usize>) {
859  let enabling = budget.is_some();
860  FRAGMENT_YIELD_BUDGET.set(budget);
861  FRAGMENT_YIELDED.set(false);
862  // An eager conversion raises requests it never honors (the clearing site
863  // is inside the budgeted branch); a later streaming conversion on the same
864  // thread must not inherit one.
865  FRAGMENT_YIELD_REQUESTED.set(false);
866  // The count is a per-conversion probe: reset when a driver ENABLES
867  // yielding, and preserved when it disables at end-of-digestion (the driver
868  // clears the budget before the tail phases, and telemetry/tests read the
869  // count after the conversion returns).
870  if enabling {
871    FRAGMENT_YIELD_COUNT.set(0);
872  }
873}
874/// The armed fragment-yield box budget, if any — see `set_fragment_yield_budget`.
875pub fn fragment_yield_budget() -> Option<usize> { FRAGMENT_YIELD_BUDGET.get() }
876
877/// Did the last `digest_next_body` return because of the yield budget (rather
878/// than EOF / terminal / depth-drop)? Read-and-clear.
879pub fn take_fragment_yielded() -> bool { FRAGMENT_YIELDED.replace(false) }
880
881/// Ask digestion to yield at the next legal fragment seam whatever the box
882/// count — a binding's signal that a large self-contained unit (a picture)
883/// just closed. Inert under eager digestion.
884pub fn request_fragment_yield() { FRAGMENT_YIELD_REQUESTED.set(true); }
885
886/// How many times digestion has yielded since the budget was last set.
887pub fn fragment_yield_count() -> usize { FRAGMENT_YIELD_COUNT.get() }
888
889macro_rules! stomach {
890  () => {
891    stomach_root().borrow()
892  };
893}
894macro_rules! stomach_mut {
895  () => {
896    stomach_root().borrow_mut()
897  };
898}
899
900/// Initialize various stomach parameters, preload, etc.
901pub fn initialize_stomach() {
902  // The soft-RSS growth floor measures from digestion start: sample the real
903  // RSS now (nothing has sampled it yet), else the first seam over the
904  // watermark would read the whole resident set as "growth" and yield once
905  // regardless of the box-count floor (115_soft_yield_floor).
906  let baseline = crate::watchdog::process_rss_kb().unwrap_or_else(|| LAST_SAMPLED_RSS_KB.get());
907  LAST_SAMPLED_RSS_KB.set(baseline);
908  note_yield_rss_baseline(baseline);
909  EVERYPAR_FIRING.with(|f| f.set(false));
910  let mut stomach = stomach_mut!();
911  stomach.boxing = Vec::new();
912  stomach.token_stack = Vec::new();
913  stomach.box_list = Vec::new();
914  stomach.localized_box_list = Vec::new();
915  stomach.paragraph_start = None;
916  stomach.cycle_guard.reset();
917  stomach.cycle_progress = 0;
918  stomach.cycle_spans.reset();
919  stomach.cycle_spans_raw.reset();
920  stomach.cycle_records = 0;
921  stomach.cycle_stuck.reset();
922  stomach.cycle_moving.reset();
923  stomach.pending_cycle_fatal = None;
924  set_aside_stashed_fatal();
925
926  assign_value("BOUND_MODE", "vertical", Some(Scope::Global));
927  assign_value("MODE", "vertical", Some(Scope::Global));
928  assign_value("IN_MATH", false, Some(Scope::Global));
929  assign_value("PRESERVE_NEWLINES", 1, Some(Scope::Global));
930  assign_value(
931    "afterGroup",
932    Stored::VecDequeStored(VecDeque::new()),
933    Some(Scope::Global),
934  );
935  assign_value("afterAssignment", Stored::None, Some(Scope::Global)); // undef ???
936  assign_value_sym(
937    crate::pin!("groupInitiator"),
938    "Initialization",
939    Some(Scope::Global),
940  );
941  // Setup default fonts.
942  assign_value("font", Font::text_default(), Some(Scope::Global));
943  assign_value("mathfont", Font::math_default(), Some(Scope::Global));
944}
945
946/// steal the previously digested boxes from the current level.
947pub fn regurgitate() -> Vec<Digested> {
948  let mut stomach = stomach_mut!();
949  stomach.paragraph_start = None;
950  std::mem::take(&mut stomach.box_list)
951}
952
953//**********************************************************************
954// Maintaining state
955//**********************************************************************
956// state changes that the Stomach needs to moderate and know about (?)
957
958//======================================================================
959// Dealing with TeX's bindings & grouping.
960// Note that lookups happen more often than bgroup/egroup (which open/close frames).
961
962/// Adds a new stack frame for a TeX group.
963pub fn push_stack_frame(nobox: bool) {
964  let current_token = get_current_token().unwrap_or_else(|| T_CS!("\\relax"));
965  if *TRACE_FRAMES {
966    eprintln!(
967      "[frames] push nobox={nobox} id={} depth {} -> {} at {current_token}",
968      FRAME_SERIAL.get() + 1,
969      get_frame_depth(),
970      get_frame_depth() + 1
971    );
972  }
973  push_frame();
974  let serial = FRAME_SERIAL.get() + 1;
975  FRAME_SERIAL.set(serial);
976  if *TRACE_FRAMES && (get_prefix("global") || get_prefix("long")) {
977    eprintln!("[frames] push id={serial} with a prefix pending at {current_token}");
978  }
979  assign_frame_value_sym(
980    crate::pin!("lx@frame@id"),
981    Stored::Number(crate::common::number::Number(serial as i64)),
982  );
983  assign_frame_value("beforeAfterGroup", Stored::VecDequeStored(VecDeque::new())); // ALWAYS bind this!
984  assign_frame_value("afterGroup", Stored::VecDequeStored(VecDeque::new())); // ALWAYS bind this!
985  assign_frame_value("afterAssignment", Stored::None); // ALWAYS bind this!
986  assign_frame_value_sym(crate::pin!("groupNonBoxing"), nobox); // ALWAYS bind this!
987  assign_frame_value_sym(crate::pin!("groupInitiator"), current_token);
988  assign_frame_value_sym(crate::pin!("groupInitiatorLocator"), gullet::get_locator());
989  if !nobox {
990    // For begingroup/endgroup
991    stomach_mut!().boxing.push(current_token)
992  }
993}
994/// Execute tokens stored on beforeAfterGroup (if any); done before popping a stack frame.
995/// Perl: sub executeBeforeAfterGroup (Stomach.pm lines 286-295)
996pub fn execute_before_after_group() -> Result<()> {
997  match remove_value("beforeAfterGroup") {
998    Some(Stored::VecDequeStored(beforeafter)) => digest_before_after_group(beforeafter),
999    _ => Ok(()),
1000  }
1001}
1002
1003/// Digests a frame's `beforeAfterGroup` tokens into the current box list ([`execute_before_after_group`]).
1004fn digest_before_after_group(beforeafter: VecDeque<Stored>) -> Result<()> {
1005  if !beforeafter.is_empty() {
1006    let mut result = Vec::with_capacity(beforeafter.len());
1007    for beforeafter_frame in beforeafter.into_iter() {
1008      match beforeafter_frame {
1009        Stored::Tokens(frametoks) => result.push(frametoks.be_digested()?),
1010        Stored::Token(frametok) => result.push(frametok.be_digested()?),
1011        _ => {
1012          // Unexpected value type in beforeAfterGroup — skip silently
1013          // rather than panic (could occur with non-standard TeX constructs)
1014        },
1015      }
1016    }
1017    // Perl Stomach.pm:182-183 — every digested item must be Box-like
1018    // (TBox / List / Whatsit / Alignment); anything else is a binding
1019    // bug. Emit Error per offender; the Box-like items still flow
1020    // through to box_list so partial output is preserved.
1021    // Perl additionally calls `@result = (makeMisdefinedError(@result))`
1022    // collapsing everything to a single error sentinel — we keep
1023    // the partial-output behaviour (Rust-side divergence; surfacing
1024    // *the* offending item via Error! is what the harness needs to
1025    // report, while the rest of the box stream is still useful).
1026    //
1027    // Implementation note: walk the result list with an index loop
1028    // rather than `retain(|d| {…})`. The Error! macro can `return
1029    // Err(…)` on the max-errors / runaway-loop guards, and a closure
1030    // returning `bool` can't propagate that out — only an explicit
1031    // for-loop in the surrounding `Result<()>` body can.
1032    let mut filtered = Vec::with_capacity(result.len());
1033    for d in result {
1034      let is_box = matches!(
1035        d.data(),
1036        DigestedData::TBox(_)
1037          | DigestedData::List(_)
1038          | DigestedData::Whatsit(_)
1039          | DigestedData::Alignment(_)
1040      );
1041      if is_box {
1042        filtered.push(d);
1043      } else {
1044        let kind_label = match d.data() {
1045          DigestedData::Postponed(_) => "Postponed",
1046          DigestedData::KeyVals(_) => "KeyVals",
1047          DigestedData::RegisterValue(_) => "RegisterValue",
1048          DigestedData::Comment(_) => "Comment",
1049          _ => "non-Box",
1050        };
1051        Error!(
1052          "misdefined",
1053          "<beforeAfterGroup>",
1054          format!(
1055            "Expected a Box|List|Whatsit, but got '{}' — dropping",
1056            kind_label
1057          )
1058        );
1059      }
1060    }
1061    // Route the group's digested boxes through the GUARDED appender (not a
1062    // raw `box_list.extend`) so the stomach's cycle / count / byte-budget
1063    // runaway guards see them. This is the path a grouped drawing loop
1064    // (`\@whiledim{…\hbox{…}…}`) flushes through, so bypassing it let a
1065    // heavy-box runaway accumulate unguarded until only the Linux RSS cap
1066    // caught it. Witness math0102053.
1067    extend_box_list(filtered);
1068  }
1069  Ok(())
1070}
1071
1072/// Removes the last/current stack frame, ending a TeX group
1073pub fn pop_stack_frame(nobox: bool) -> Result<()> { pop_stack_frame_with(nobox, true) }
1074
1075fn pop_stack_frame_with(nobox: bool, run_after_group: bool) -> Result<()> {
1076  if *TRACE_FRAMES {
1077    let current_token = get_current_token().unwrap_or_else(|| T_CS!("\\relax"));
1078    eprintln!(
1079      "[frames] pop  nobox={nobox} id={} depth {} -> {} at {current_token} (bound_mode={})",
1080      current_frame_id(),
1081      get_frame_depth(),
1082      get_frame_depth().saturating_sub(1),
1083      lookup_string_from_sym(crate::pin!("BOUND_MODE"))
1084    );
1085  }
1086  let mut after = remove_value("afterGroup");
1087  let depth_before = get_frame_depth();
1088  execute_before_after_group()?;
1089  if *TRACE_FRAMES && get_frame_depth() != depth_before {
1090    eprintln!(
1091      "[frames] beforeAfterGroup changed the depth {depth_before} -> {} (top id {} now)",
1092      get_frame_depth(),
1093      current_frame_id()
1094    );
1095  }
1096  // Guard: `perfect_kernel_batch64zf::setspace_switch_in_a_plain_group_rearms_on_the_enclosing_group`.
1097  // Perl Stomach.pm:308-314 takes the frame's afterGroup list by REFERENCE before
1098  // the beforeAfterGroup hooks run, and pushValue (State.pm:218-223) appends to that
1099  // same array, so an `\aftergroup` a hook performs is honoured after the pop. Here
1100  // the list was taken by value, and a hook's push re-created the frame's slot,
1101  // which the pop then discarded: append what the hooks queued on this frame.
1102  if get_frame_depth() == depth_before
1103    && let Some(Stored::VecDequeStored(queued)) = remove_value("afterGroup")
1104    && !queued.is_empty()
1105  {
1106    match after {
1107      Some(Stored::VecDequeStored(ref mut entries)) => entries.extend(queued),
1108      _ => after = Some(Stored::VecDequeStored(queued)),
1109    }
1110  }
1111  // The closers this frame still owes move to the frame now innermost ([`OWED_BRACES`]).
1112  let owed = [OWED_BRACES, OWED_ENDGROUPS].map(owed_closers);
1113  pop_frame()?;
1114  for (key, debt) in [OWED_BRACES, OWED_ENDGROUPS].into_iter().zip(owed) {
1115    if debt > 0 {
1116      assign_frame_value(key, Stored::Int(owed_closers(key) + debt));
1117    }
1118  }
1119  if !nobox {
1120    {
1121      stomach_mut!().boxing.pop(); // For begingroup/endgroup
1122    }
1123  }
1124  if !run_after_group {
1125    after = None;
1126  }
1127  if let Some(Stored::VecDequeStored(after_entries)) = after {
1128    for entry in after_entries.into_iter().rev() {
1129      match entry {
1130        Stored::Tokens(t) => gullet::unread(t),
1131        Stored::Token(t) => gullet::unread_one(t),
1132        other => panic!(r"\aftergroup should be used with tokens, got instead: {other:?}"),
1133      };
1134    }
1135  }
1136  Ok(())
1137}
1138
1139/// explain the current frame
1140/// `LXML_TRACE_FRAMES` helper: which group bindings each of the top `n`
1141/// frames carries — a frame without `groupInitiator` is a bare `push_frame`
1142/// (construct-time scope, `\protected@edef`, semiverbatim), invisible to the
1143/// `[frames]` push/pop trace.
1144pub fn dump_frame_bindings(n: usize) -> String {
1145  s!(
1146    "  depth {}\n  ids   {:?}\n  init  {:?}\n  nobox {:?}\n  mode  {:?}\n",
1147    get_frame_depth(),
1148    value_history("lx@frame@id", n),
1149    value_history("groupInitiator", n),
1150    value_history("groupNonBoxing", n),
1151    value_history("BOUND_MODE", n)
1152  )
1153}
1154
1155pub fn current_frame_message() -> String {
1156  let target = if is_value_bound("MODE", Some(0)) {
1157    // SET mode in CURRENT frame ?
1158    Cow::Owned(s!(
1159      "mode-switch to {}",
1160      lookup_string_from_sym(crate::pin!("MODE"))
1161    ))
1162  } else if lookup_bool_sym(crate::pin!("groupNonBoxing")) {
1163    // Current frame is a non-boxing group?
1164    Cow::Borrowed("non-boxing group")
1165  } else {
1166    Cow::Borrowed("boxing group")
1167  };
1168
1169  let initiator = if let Some(t) = lookup_token_sym(crate::pin!("groupInitiator")) {
1170    t.stringify()
1171  } else {
1172    String::new()
1173  };
1174  // Render the initiator's source locator as a readable "file; line N"
1175  // (the raw Stored Debug is redacted to `Stored::Locator[[...]]`, which is
1176  // useless for diagnosing where an unbalanced group opened).
1177  let locator = match lookup_value("groupInitiatorLocator") {
1178    Some(Stored::Locator(loc)) => s!("at {}", loc),
1179    Some(other) => other.to_string(),
1180    None => String::new(),
1181  };
1182  s!(
1183    "current frame is {} due to {} {}",
1184    target,
1185    initiator,
1186    locator
1187  )
1188}
1189
1190//======================================================================
1191// Grouping pushes a new stack frame for binding definitions, etc.
1192//======================================================================
1193
1194/// Begin a new level of binding by pushing a new stack frame,
1195/// and a new level of boxing the digested output.
1196/// The serial of the stack frame on top (`lx@frame@id`, written by
1197/// [`push_stack_frame`]); 0 below the first frame.
1198pub fn current_frame_id() -> u64 {
1199  match lookup_value("lx@frame@id") {
1200    Some(Stored::Number(n)) => n.0 as u64,
1201    _ => 0,
1202  }
1203}
1204
1205/// A group closer `closer` (`}`/`\egroup`, or `\endgroup` when `semi_simple`)
1206/// meeting the frame of an environment: end the environment first, as its own
1207/// closer would. Returns true when it acted.
1208///
1209/// LaTeX's `\begin` is `\begingroup` + `\X` (latex.ltx:15346-15355) and its
1210/// `\end` is `\endX` + `\endgroup` (latex.ltx:15386-15393); the environment's
1211/// local state goes with whichever closer ends that group. LaTeXML keeps a
1212/// mode frame for the environment's body (Perl Package.pm:1919-1925 `bgroup`
1213/// then `beginMode`, :1972 `beginMode` for the bare `\X`), which a plain
1214/// closer cannot pop (Perl Stomach.pm:343-375 errors and keeps the frame), so
1215/// the body swallowed the rest of the document. The recovery is tex.web
1216/// §1064-1065 `off_save`'s shape — back-input the closer, insert what the
1217/// innermost group expects:
1218/// * a bare `\X` frame (`{\thm …}`, `{\quote …}`, `\begingroup\rem …\endgroup`):
1219///   insert `\endX` and re-read the closer, which then ends the enclosing group
1220///   (or meets that group's own mismatch, reported there);
1221/// * a `\begin{X}` frame met by `\endgroup` (the ALICE author block): that
1222///   `\endgroup` closes `\begin`'s group (tex.web §1063 `end_group` against a
1223///   `semi_simple_group`: `unsave`), so the environment's own `\end{X}` takes
1224///   its place and pops the frame — the group is closed once.
1225///
1226/// What TeX itself reports decides the diagnostic, by the kind of group the
1227/// environment's begin code leaves open (`lx@env@tex@group`, a [`TexGroup`]
1228/// name; tex.web §269 group codes):
1229/// * none (`\trivlist`, `\list`): TeX has no mismatch at all (a bare `\X` opens
1230///   no group; `\begin`'s group is any `\endgroup`'s) — an Info;
1231/// * a `semi_simple_group` (`\begingroup` or a nested `\begin`: setspace,
1232///   lscape, multicols, beamer's blocks): `}` is §1068-1069 `extra_right_brace`
1233///   — an Error; `\endgroup` just unsaves it (§1063), which is clean for a bare
1234///   `\X` (`\begingroup\multicols{2} …\endgroup` — an Info: `\endX` takes the
1235///   `\endgroup`'s place and the enclosing group stays open, as in TeX) but
1236///   leaves `\begin`'s own group open for a `\begin{X}`, reported at the next
1237///   `\end` — an Error;
1238/// * a box or colour group (a float's `\@xfloat`, a minipage's `\vbox\bgroup`):
1239///   §1064 `off_save` "Missing } inserted" for `\endgroup`, the box ended early
1240///   for `}` (§1068 `handle_right_brace`) — an Error.
1241///
1242/// The kind is a frame value that follows TeX's group state: raw end code that
1243/// closes the box group without the binding's own closer (floatrow's
1244/// `\float@end` calling latex.ltx's `\@endfloatbox` against the bound `\@float`)
1245/// sets it to none (sect09.rs `\lx@endfloatbox@close`), so a closer that meets
1246/// the frame afterwards is clean in TeX and logs the Info. A `}` against a
1247/// `\begin{X}` frame (§1068-1069 `extra_right_brace`, "Extra }, or forgotten
1248/// \endgroup", the brace deleted) and any closer against an environment in math
1249/// mode (its `$` or `$$` opened a `math_shift_group`, §1064/§1069) are not
1250/// recovered here: both stay with the caller's Error. One attempt per frame:
1251/// the marker is taken, so a redefined `\endX` that does not close the frame
1252/// falls back to the Error. The frame is flagged (`environment_ended_by_group`) so that end
1253/// code TeX would not run — `\end`'s hooks, a theorem's end mark — is skipped.
1254/// Witnesses: 1210.5866 1111.2539 2405.03639 1703.03321 2202.11643 0812.1147
1255/// 1009.2722 1312.6689 1905.06220 2207.12734 2308.09714 2503.00772 1403.7312
1256/// 2104.03038 (`{\thm …}`), 2412.14057 (`{\quote …}`), 1702.01612 1909.03158
1257/// (`\begin{flushleft} … \endgroup`). A REVTeX 3 `\figure{N}` caption line
1258/// opens no group without the `floats` option (aps.sty:614-630, revtex3_support
1259/// overrides the flag): cond-mat9607130 is pdflatex-clean and gets the Info.
1260fn close_environment_frame(closer: Token, semi_simple: bool) -> Result<bool> {
1261  // Only the closer itself is re-read: a binding that calls `egroup()` /
1262  // `endgroup()` from its own code (a cell, a box argument) keeps the Error.
1263  let is_closer = if semi_simple {
1264    x_equals(&closer, &T_CS!("\\endgroup"))
1265  } else {
1266    gullet::is_right_brace(&closer)
1267  };
1268  if !is_closer {
1269    return Ok(false);
1270  }
1271  if matches!(lookup_mode(), m if m == crate::pin!("math") || m == crate::pin!("display_math")) {
1272    return Ok(false);
1273  }
1274  let (end, bare) = if is_value_bound("lx@env@bare@end", Some(0)) {
1275    (remove_value("lx@env@bare@end"), true)
1276  } else if semi_simple && is_value_bound("lx@env@begin@end", Some(0)) {
1277    (remove_value("lx@env@begin@end"), false)
1278  } else {
1279    return Ok(false);
1280  };
1281  let Some(Stored::Token(end)) = end else {
1282    return Ok(false);
1283  };
1284  // A bare frame's end is the binding's `\endX` under its private alias (dialect.rs `def_environment`), and any bare
1285  // start may be one too (a `\let` copy, a theorem's private constructor); the messages name them as `\X`/`\endX`.
1286  let environment = bare
1287    .then(|| lookup_token("lx@env@bare@shown"))
1288    .flatten()
1289    .or_else(|| lookup_token_sym(crate::pin!("groupInitiator")))
1290    .map(|t| t.to_string())
1291    .unwrap_or_default();
1292  let shown_end = bare.then(bare_end_shown).flatten().unwrap_or(end);
1293  assign_frame_value_sym(crate::pin!("lx@env@ended@by@group"), true);
1294  let kind = if is_value_bound("lx@env@tex@group", Some(0)) {
1295    TexGroup::from_name(&lookup_string("lx@env@tex@group")).unwrap_or(TexGroup::None)
1296  } else {
1297    TexGroup::None
1298  };
1299  let tex_error = match kind {
1300    TexGroup::None => None,
1301    TexGroup::SemiSimple if !semi_simple => Some(
1302      "TeX: Extra }, or forgotten \\endgroup (the } meets the \\begingroup the begin code opened)",
1303    ),
1304    TexGroup::SemiSimple if !bare => Some(
1305      "TeX: the \\endgroup closes the \\begingroup the begin code opened; \\begin's own group stays open \
1306       and TeX reports the mismatch at the next \\end",
1307    ),
1308    TexGroup::SemiSimple => None,
1309    TexGroup::Box if semi_simple => Some(
1310      "TeX: the \\endgroup meets the box group the begin code opened, and TeX reports a group mismatch \
1311       (Missing } inserted, or a later error once the group is gone)",
1312    ),
1313    TexGroup::Box => Some(
1314      "TeX: the } ends the box group the begin code opened, not the enclosing one, and TeX reports a mismatch later",
1315    ),
1316  };
1317  if let Some(tex) = tex_error {
1318    Error!(
1319      "unexpected",
1320      closer,
1321      s!("Environment {environment} opened a TeX group of its own: ending it with {shown_end}"),
1322      tex
1323    );
1324  } else {
1325    Info!(
1326      "unexpected",
1327      closer,
1328      s!("ends the group around environment {environment}: inserting {shown_end}")
1329    );
1330  }
1331  // A bare `\X` frame normally re-reads the closer for the enclosing group;
1332  // but an `\endgroup` against the `\begingroup` a bare `\X` opened only unsaves
1333  // that group (§1063), so `\endX` takes its place and the enclosing group
1334  // stays open, as in TeX (`{\multicols{2} …\endgroup}`).
1335  let reread = bare && !(semi_simple && kind == TexGroup::SemiSimple);
1336  if reread {
1337    gullet::unread(Tokens::new(vec![end, closer]));
1338  } else {
1339    gullet::unread_one(end);
1340  }
1341  Ok(true)
1342}
1343
1344/// Whether the environment whose frame is on top is being ended by a plain
1345/// group closer (`close_environment_frame`) rather than by its own `\end`:
1346/// end code TeX never runs then (`\end`'s hooks, latex.ltx:15386-15393; a
1347/// theorem's end mark and postwork) is skipped by the bindings that emit it.
1348pub fn environment_ended_by_group() -> bool { is_value_bound("lx@env@ended@by@group", Some(0)) }
1349
1350/// The innermost frame recording an open environment (`\@currenvir`): the one `\begin` opened for the environment the
1351/// next `\end` checks against, whatever plain groups stand above it.
1352fn open_environment_frame() -> Option<usize> {
1353  (0..get_frame_depth()).find(|&frame| is_value_bound("current_environment", Some(frame)))
1354}
1355
1356/// Whether the open environment's end hooks ran already, before the end of a command-form environment left open in it
1357/// (`end_command_form_before_enclosing_end`): read on that environment's own frame, so a `\begingroup` left above
1358/// it (raa.cls) does not hide the flag, and an environment begun and ended inside a hook does not see it.
1359pub fn environment_end_hooks_ran() -> bool {
1360  open_environment_frame().is_some_and(|open| is_value_bound(END_HOOKS_RAN, Some(open)))
1361}
1362
1363/// `\end{Y}` read with a bare `\X` (command form) left open in Y (`\begin{claim}\enumerate\item a\end{claim}`, ar5iv
1364/// #158, math9706207): Y's end hooks, X's end, then `\end{Y}`, as TeX's `\end{Y}` ends X with Y's group
1365/// (latex.ltx:15386-15393). OXIDIZED_DESIGN_DIVERGENCES #1252; guard `guard_rows::boxes_groups`.
1366fn end_command_form_before_enclosing_end(end: &Token) -> Result<bool> {
1367  if !is_value_bound("lx@env@bare@end", Some(0))
1368    || is_value_bound("lx@env@tex@group", Some(0))
1369      && lookup_string("lx@env@tex@group") != TexGroup::None.as_str()
1370    || matches!(lookup_mode(), m if m == crate::pin!("math") || m == crate::pin!("display_math"))
1371  {
1372    return Ok(false);
1373  }
1374  // Y is the environment open (`\@checkend`): the innermost frame recording one is the frame `\begin{Y}` opened for
1375  // this `\end{Y}`, below X's. An X opened by Y's own begin code (`\AtBeginEnvironment{Y}{\itemize}`) holds Y's record
1376  // in its frame and is left alone (row QA47REB).
1377  let Some(open) = open_environment_frame() else {
1378    return Ok(false);
1379  };
1380  if open == 0
1381    || !is_value_bound("lx@env@begin@end", Some(open))
1382    || !matches!(value_in_frame("lx@env@begin@end", open), Some(Stored::Token(t)) if t == *end)
1383  {
1384    return Ok(false);
1385  }
1386  let current = lookup_string("current_environment");
1387  // `\end{Y}`'s hooks run before its `\endgroup`, so they are read here as input, in X's last item, then `\end{Y}`
1388  // again; once (Y's end constructor skips them), as a hook may end X itself (`{…\enditemize}`) or open another.
1389  if !is_value_bound(END_HOOKS_RAN, Some(open)) {
1390    bind_value_in_frame(END_HOOKS_RAN, open, Stored::Bool(true));
1391    let mut input: Vec<Token> = environment_end_hooks(&current, None)
1392      .into_iter()
1393      .flat_map(Tokens::unlist)
1394      .collect();
1395    input.push(*end);
1396    gullet::unread(Tokens::new(input));
1397    return Ok(true);
1398  }
1399  let Some(Stored::Token(bare_end)) = remove_value("lx@env@bare@end") else {
1400    return Ok(false);
1401  };
1402  let shown_end = bare_end_shown().unwrap_or(bare_end);
1403  assign_frame_value_sym(crate::pin!("lx@env@ended@by@group"), true);
1404  Info!(
1405    "unexpected",
1406    *end,
1407    s!(
1408      "ends environment {current} with a command-form environment open in it: inserting {shown_end}"
1409    )
1410  );
1411  gullet::unread(Tokens::new(vec![bare_end, *end]));
1412  Ok(true)
1413}
1414
1415/// A bare frame's `\endX` as the document knows it (`\end{X}`; `\endlx@list` for a raw `\list`), not the binding's
1416/// private alias: only the frame on top's own record, never an enclosing bare frame's.
1417fn bare_end_shown() -> Option<Token> {
1418  is_value_bound("lx@env@bare@end@shown", Some(0))
1419    .then(|| lookup_token("lx@env@bare@end@shown"))
1420    .flatten()
1421}
1422
1423/// `\end{X}` met while plain `\begingroup` groups opened inside X stand above X's own frame — raa.cls:322-349
1424/// `\institutename`: `\begin{flushleft}\begingroup … \end{flushleft}\endgroup`. That is TeX's scoping, not an error:
1425/// groups are untyped between `\begingroup` and `\endgroup` (tex.web §1063-1069), so `\end{X}`'s `\endgroup`
1426/// (latex.ltx:15384-15393 `\end` = `\endX` + `\@checkend` + `\endgroup`; `\@checkend` reads `\@currenvir`, still X)
1427/// closes the innermost one, and the class's own `\endgroup` closes the group `\begin{X}` opened. Here, as there:
1428/// * the innermost plain group is popped, its local values undone (`\end`'s `\endgroup`);
1429/// * X ends: its open paragraph, its mode and its boxing level end here, so its element ends where `\end{X}` stands
1430///   and its own `beforeAfterGroup` work (an alignment, `\@add@centering`) acts on its body;
1431/// * X's frame stays open as a plain `\begingroup` group, keeping X's other local values (its `\@currenvir`, `\\`, a
1432///   value set before the class's `\begingroup`) until the `\endgroup` that closes it.
1433///
1434/// Perl ends the mode against the plain group instead and errors (Stomach.pm:544-550 "Attempt to end mode"); with
1435/// the error a raw class's title-page deposit was dropped — title, authors, abstract and keywords (KNOWN_PERL_ERRORS
1436/// #1207, OXIDIZED_DESIGN_DIVERGENCES #965). Only that shape acts: every frame above X a plain `\begingroup` group
1437/// (no mode, no box, no environment marker, and no environment recorded but X's own — not a raw `\newenvironment`'s
1438/// `\begin{Y}`; an X this branch ended earlier, its group still open, records X), the environment open X itself
1439/// (`\@checkend`), X's frame the `\begin{X}` of this very `\end{X}`, and X neither a math environment nor one whose
1440/// begin code opened a box group — where TeX itself errs (`\@badend`, or the box's own group). Otherwise false, and
1441/// the caller's `end_mode` raises today's Error. Witnesses 1404.3644, 1304.5354, 1508.02561, 1509.00139, 2004.06992,
1442/// 2110.11117, 2306.16795, 1604.05586, 2003.13998, 2102.01352, 2511.10805 (raa, raa_twocolumn). Guards
1443/// `perfect_kernel_batch98d::*`.
1444pub fn end_environment_over_plain_groups(name: &str, end: Token) -> Result<bool> {
1445  // The `\@checkend` the caller's `unexpected_end_closure` just ran: the environment open is X, and no group above
1446  // X's frame records another (a raw `\newenvironment`'s `\begin{Y}`) — else LaTeX's `\@badend`. A group recording X
1447  // is an X this branch ended earlier (`\begin{X}\begin{X}\begingroup … \end{X}…\end{X}`), as TeX's `\@currenvir`.
1448  if lookup_string("current_environment") != name {
1449    return Ok(false);
1450  }
1451  let depth = get_frame_depth();
1452  let records_only_x = |frame: usize| {
1453    !is_value_bound("current_environment", Some(frame))
1454      || matches!(value_in_frame("current_environment", frame),
1455        Some(Stored::String(open)) if arena::with(open, |open| open == name))
1456  };
1457  let plain_group = |frame: usize| {
1458    matches!(
1459      value_in_frame("groupNonBoxing", frame),
1460      Some(Stored::Bool(true))
1461    ) && is_value_bound("groupNonBoxing", Some(frame))
1462      && records_only_x(frame)
1463      && [
1464        "BOUND_MODE",
1465        "lx@env@begin@end",
1466        "lx@env@bare@end",
1467        "lx@env@ended@by@group",
1468      ]
1469      .iter()
1470      .all(|key| !is_value_bound(key, Some(frame)))
1471  };
1472  let mut frame = 0;
1473  while frame < depth && plain_group(frame) {
1474    frame += 1;
1475  }
1476  if frame == 0 || frame >= depth {
1477    return Ok(false);
1478  }
1479  let own_frame = is_value_bound("lx@env@begin@end", Some(frame))
1480    && matches!(value_in_frame("lx@env@begin@end", frame), Some(Stored::Token(t)) if t == end);
1481  let frame_string = |key: &str| match value_in_frame(key, frame) {
1482    Some(Stored::String(value)) if is_value_bound(key, Some(frame)) => {
1483      arena::with(value, str::to_string)
1484    },
1485    _ => String::new(),
1486  };
1487  let bound_mode = frame_string("BOUND_MODE");
1488  let box_group = frame_string("lx@env@tex@group") == TexGroup::Box.as_str();
1489  if !own_frame || bound_mode.is_empty() || bound_mode.ends_with("math") || box_group {
1490    return Ok(false);
1491  }
1492  Info!(
1493    "unexpected",
1494    end,
1495    s!(
1496      "{end} closes the \\begingroup opened inside the environment ({frame} open above it); the environment's own \
1497       group stays open for the next \\endgroup"
1498    )
1499  );
1500  if bound_mode.ends_with("vertical") {
1501    leave_horizontal_internal();
1502  }
1503  // `\end`'s `\endgroup`: the innermost group only.
1504  pop_stack_frame(true)?;
1505  let own = frame - 1;
1506  // X's element-closing work, run in its body as `end_mode`'s pop runs it.
1507  if let Some(Stored::VecDequeStored(work)) = replace_value_in_frame(
1508    "beforeAfterGroup",
1509    own,
1510    Stored::VecDequeStored(VecDeque::new()),
1511  ) {
1512    digest_before_after_group(work)?;
1513  }
1514  // X's mode and environment markers go; the rest of its frame is now a plain group's.
1515  for key in [
1516    "BOUND_MODE",
1517    "MODE",
1518    "IN_MATH",
1519    "lx@env@begin@end",
1520    "lx@env@tex@group",
1521    "lx@until@terminal",
1522    "lx@until@depth",
1523    // (a second `\end{X}` over this group runs X's end hooks again, as `\@currenvir` still names X)
1524    END_HOOKS_RAN,
1525  ] {
1526    unbind_value_in_frame(key, own);
1527  }
1528  replace_value_in_frame("groupNonBoxing", own, Stored::Bool(true));
1529  stomach_mut!().boxing.pop();
1530  Ok(true)
1531}
1532
1533/// The stack frame (0 = innermost) `\begin{X}` opened — the one marked with its `end` — when a begin hook left plain
1534/// groups or a text-mode environment open above it (2001.02707's `\AtBeginEnvironment{thm}{\begin{samepage}}`; a hook's
1535/// `\begin{center}` opens no TeX group beyond `\begin`'s, nested in X's). `None` when X's frame is on top, when X's
1536/// mode is a math mode or its begin code opened a TeX group (a box's), as TeX opens those inside the hook's groups, and
1537/// when a frame above it holds a math mode, a box or a bare `\X` (not handled: row QA47REB).
1538pub fn environment_frame_under_hook_groups(end: &Token, mode: &str) -> Option<usize> {
1539  if bindable_mode(mode).is_some_and(|bound| bound.ends_with("math")) {
1540    return None;
1541  }
1542  let depth = get_frame_depth();
1543  for frame in 0..depth {
1544    let tex_group = is_value_bound("lx@env@tex@group", Some(frame));
1545    if is_value_bound("lx@env@begin@end", Some(frame)) {
1546      let own =
1547        matches!(value_in_frame("lx@env@begin@end", frame), Some(Stored::Token(t)) if &t == end);
1548      if own {
1549        return (frame > 0 && !tex_group).then_some(frame);
1550      }
1551      // A hook's own text-mode environment (`center`): stepped past, as TeX nests it in X's group.
1552      let math = is_value_bound("IN_MATH", Some(frame))
1553        && matches!(value_in_frame("IN_MATH", frame), Some(Stored::Bool(true)));
1554      if tex_group || math {
1555        return None;
1556      }
1557      continue;
1558    }
1559    if ["BOUND_MODE", "MODE", "IN_MATH", "lx@env@bare@end"]
1560      .iter()
1561      .any(|key| is_value_bound(key, Some(frame)))
1562    {
1563      return None;
1564    }
1565  }
1566  None
1567}
1568
1569/// [`begin_mode_opt`] for X under a begin hook's open groups ([`environment_frame_under_hook_groups`]): the mode is
1570/// bound in the frame marked with `end`, X's own, so it ends with the environment and the hook's groups close as plain
1571/// groups (in TeX a list environment's begin code opens no group); a hook environment's mode on top stays in force.
1572/// The text font `set_mode_from` binds when a text mode is begun from math stays on top, beside a hook's own font.
1573pub fn begin_mode_under_hook_groups(mode: &str, end: &Token) -> Result<()> {
1574  const KEYS: [&str; 3] = ["BOUND_MODE", "MODE", "IN_MATH"];
1575  let shadowed = KEYS.map(|key| {
1576    is_value_bound(key, Some(0))
1577      .then(|| value_in_frame(key, 0))
1578      .flatten()
1579  });
1580  begin_mode_opt(mode, true)?;
1581  // Found by its marker after `begin_mode_opt`, whose `leave_horizontal` may change the depth.
1582  let Some(frame) = (1..get_frame_depth()).find(|&frame| {
1583    is_value_bound("lx@env@begin@end", Some(frame))
1584      && matches!(value_in_frame("lx@env@begin@end", frame), Some(Stored::Token(t)) if &t == end)
1585  }) else {
1586    return Ok(());
1587  };
1588  for (key, old) in KEYS.into_iter().zip(shadowed) {
1589    if is_value_bound(key, Some(0))
1590      && let Some(value) = value_in_frame(key, 0)
1591    {
1592      match old {
1593        Some(old) => bind_value_in_frame(key, 0, old),
1594        None => {
1595          unbind_value_in_frame(key, 0);
1596        },
1597      }
1598      bind_value_in_frame(key, frame, value);
1599    }
1600  }
1601  Ok(())
1602}
1603
1604pub fn bgroup() {
1605  push_stack_frame(false);
1606  // Perl's bgroup does NOT touch $ALIGN_STATE — it's tracked only at the scan level
1607  // (in read_token/read_x_token). The scan-level tracking in gullet.rs is sufficient.
1608}
1609/// End a level of binding by popping the last stack frame,
1610/// undoing whatever bindings appeared there, and also
1611/// decrementing the level of boxing.
1612pub fn egroup() -> Result<()> {
1613  if get_current_token().is_some_and(|t| gullet::is_right_brace(&t)) && close_template_brace() {
1614    return Ok(());
1615  }
1616  if is_value_bound("BOUND_MODE", Some(0)) {
1617    // Diagnostic for cluster investigation (project_explsyntax_midload.md).
1618    if *TRACE_BOUND_MODE {
1619      let mode = lookup_string_from_sym(crate::pin!("MODE"));
1620      let bound = lookup_string_from_sym(crate::pin!("BOUND_MODE"));
1621      let cur_tok = get_current_token()
1622        .map(|t| t.to_string())
1623        .unwrap_or_default();
1624      eprintln!(
1625        "[trace] egroup ERROR: cur_tok={cur_tok} BOUND_MODE={bound} MODE={mode}\n{}",
1626        std::backtrace::Backtrace::force_capture()
1627      );
1628    }
1629    // Last stack frame was a mode switch!?!?!
1630    // A bare `\X` environment inside the closed group ends first.
1631    if let Some(closer) = get_current_token()
1632      && close_environment_frame(closer, false)?
1633    {
1634      return Ok(());
1635    }
1636    // Don't pop if there's an error; maybe we'll recover?
1637    // Perl Stomach.pm:347-349 passes currentFrameMessage as a SEPARATE
1638    // Error detail (its own line), not merged into the primary message.
1639    // After a resource Fatal the recovery pass only drains pending closers:
1640    // that noise is not reported — `error::emit_record` drops every Error
1641    // once `resource_fatal_latched()`.
1642    Error!(
1643      "unexpected",
1644      get_current_token().unwrap_or_else(|| T_CS!("\\?")),
1645      s!(
1646        "Attempt to close a group that switched to mode {}",
1647        lookup_string_from_sym(crate::pin!("MODE"))
1648      ),
1649      current_frame_message()
1650    );
1651  } else if lookup_bool_sym(crate::pin!("groupNonBoxing")) {
1652    // or group was opened with \begingroup
1653    Error!(
1654      "unexpected",
1655      get_current_token().unwrap_or_else(|| T_CS!("\\?")),
1656      "Attempt to close boxing group",
1657      current_frame_message()
1658    );
1659  } else {
1660    // A `}` that closes a `\left` group (its group code, latexml_engine tex_math.rs `\lx@math@left@group`): tex.web
1661    // §1069 `extra_right_brace` reports "Extra }, or forgotten \right." and deletes the brace; here the group closes,
1662    // as Perl closes it, so the formula stays well nested — a Warning (user ruling 2026-10-11 on TeX-only errors).
1663    // Deleting it as TeX does leaves the enclosing `{` group open, which our `$` defers to rather than closing
1664    // (65d round 7, h1/e1: open, SYNC row MS). OXIDIZED_DESIGN #530. Guard
1665    // `perfect_kernel_batch65d::brace_closing_a_left_group_warns`.
1666    if in_left_group() && get_current_token().is_some_and(|t| gullet::is_right_brace(&t)) {
1667      Warn!(
1668        "unexpected",
1669        "}",
1670        "Extra }, or forgotten \\right.",
1671        "A } closed the group of a \\left; the group ends without its \\right."
1672      );
1673    }
1674    // Don't pop if there's an error; maybe we'll recover?
1675    pop_stack_frame(false)?;
1676  }
1677  // Perl's egroup does NOT touch $ALIGN_STATE — tracked at scan level only.
1678  Ok(())
1679}
1680/// Begin a new level of binding by pushing a new stack frame.
1681pub fn begingroup() {
1682  if *TRACE_BOUND_MODE {
1683    let depth = get_frame_depth();
1684    let loc = gullet::get_locator();
1685    let tok = get_current_token().unwrap_or_else(|| T_CS!("\\?"));
1686    eprintln!("[trace] begingroup pre-depth={depth} tok={tok} at {}", loc);
1687  }
1688  push_stack_frame(true);
1689}
1690/// End a level of binding by popping the last stack frame,
1691/// undoing whatever bindings appeared there.
1692pub fn endgroup() -> Result<()> {
1693  if *TRACE_BOUND_MODE {
1694    let depth = get_frame_depth();
1695    let bound = is_value_bound("BOUND_MODE", Some(0));
1696    let loc = gullet::get_locator();
1697    let tok = get_current_token().unwrap_or_else(|| T_CS!("\\?"));
1698    if depth == 0 {
1699      eprintln!(
1700        "[trace] endgroup at locked frame: tok={} at {}\n{}",
1701        tok,
1702        loc,
1703        std::backtrace::Backtrace::force_capture()
1704      );
1705    } else {
1706      eprintln!(
1707        "[trace] endgroup pre-depth={depth} bound_top={bound} tok={} at {}",
1708        tok, loc
1709      );
1710    }
1711  }
1712  if get_current_token().is_some_and(|t| t.defined_as(&T_CS!("\\endgroup"))) {
1713    // The author's `\endgroup` whose place an inserted one took ([`OWED_ENDGROUPS`]), met where it cannot close a
1714    // group: deleted, as tex.web deletes an extra closer ("Extra \endgroup."), a Warning (65d review r3, b3).
1715    if owed_closers(OWED_ENDGROUPS) > 0 && !lookup_bool_sym(crate::pin!("groupNonBoxing")) {
1716      assign_frame_value(
1717        OWED_ENDGROUPS,
1718        Stored::Int(owed_closers(OWED_ENDGROUPS) - 1),
1719      );
1720      Warn!(
1721        "unexpected",
1722        "\\endgroup",
1723        "Extra \\endgroup.",
1724        "The \\endgroup of a group closed earlier by an inserted \\endgroup is deleted."
1725      );
1726      return Ok(());
1727    }
1728    // tex.web §1065 `off_save`: an `\endgroup` inside an open `\left` group gets `\right.` first.
1729    if in_left_group() {
1730      insert_missing_right(T_CS!("\\endgroup"));
1731      return Ok(());
1732    }
1733  }
1734  // No exemption for raw `.sty`/`.tex` loading (INTERPRETING_DEFINITIONS): a
1735  // band-aid once popped the frame silently there, for 19 latent errors of the
1736  // expl3-code.tex raw load (`#` reaching the stomach, `\q_stop` recursion,
1737  // `\group_end:`); both `--init`s now log zero errors without it, with the
1738  // same dumps. A raw file's `\endgroup` against an `\hbox` frame is Perl's
1739  // Error at that line (Stomach.pm:363-372), and the frame stays (mybad.sty
1740  // probe: one Error, where the silent pop cost three later ones).
1741  if is_value_bound("BOUND_MODE", Some(0)) {
1742    // Diagnostic: dump BOUND_MODE binding context for cluster investigation.
1743    if *TRACE_BOUND_MODE {
1744      let mode = lookup_string_from_sym(crate::pin!("MODE"));
1745      let bound = lookup_string_from_sym(crate::pin!("BOUND_MODE"));
1746      eprintln!(
1747        "[trace] endgroup ERROR: BOUND_MODE={bound} MODE={mode}\n{}",
1748        std::backtrace::Backtrace::force_capture()
1749      );
1750    }
1751    // Last stack frame was a mode switch!?!?!
1752    // An environment's frame: a bare `\X` ends inside the group, a
1753    // `\begin{X}` ends with it.
1754    if let Some(closer) = get_current_token()
1755      && close_environment_frame(closer, true)?
1756    {
1757      return Ok(());
1758    }
1759    let mode = lookup_string_from_sym(crate::pin!("MODE"));
1760    if mode == "math" || mode == "display_math" {
1761      // tex.web §1063/§1064 `off_save`: `\endgroup` against a math_shift_group
1762      // inserts the missing `$` ("Missing $ inserted"), closes the math and
1763      // re-reads the `\endgroup`. Perl (Stomach.pm:367-369) only reports the
1764      // mismatch and leaves the math frame on the stack, so every later closer
1765      // re-errors and `<ltx:Math>` leaks to the document root — tikz calc's
1766      // bailout `\tikz@cc@end$` (tikzlibrarycalc.code.tex:118-129) eats the
1767      // injected `$` and `\tikz@finish` (tikz.code.tex:2500-2508) re-inserts
1768      // the orphaned one as real math (calc_fraction_partway_bailout_mode_frame:
1769      // pdflatex 3 / Perl 24 / Rust 23; kblocks-doc, ozguide, nathguide,
1770      // chemobabel carry the cascade). `}`/`\egroup` keep TeX's §1069 shape
1771      // (the brace is dropped, math stays open). OXIDIZED_DESIGN_DIVERGENCES
1772      // #195. Guard: `perfect_kernel_batch56::endgroup_against_open_math_inserts_the_missing_dollar`.
1773      let closer = get_current_token().unwrap_or_else(|| T_CS!("\\endgroup"));
1774      Error!(
1775        "expected",
1776        "$",
1777        "Missing $ inserted",
1778        s!("I've inserted an end-math symbol before {closer}.")
1779      );
1780      let mut toks = vec![T_MATH!()];
1781      if mode == "display_math" {
1782        toks.push(T_MATH!());
1783      }
1784      toks.push(closer);
1785      gullet::unread(Tokens::new(toks));
1786      return Ok(());
1787    }
1788    // Don't pop if there's an error; maybe we'll recover?
1789    // Settled dead end (K9): inserting the box's `}` here (tex.web §1064
1790    // `off_save`) reaches whichever nested consumer is reading, not the box
1791    // reader that owns the frame, and only doubled the count (modernposter,
1792    // dsptricks); the `\globaldefs` bookkeeping exemption was the real msc
1793    // root (state.rs `assign_local_unconditional`).
1794    // Perl Stomach.pm:367-369: currentFrameMessage is a SEPARATE detail.
1795    Error!(
1796      "unexpected",
1797      get_current_token()
1798        .map(|t| t.to_string())
1799        .unwrap_or_else(|| String::from("\\?")),
1800      s!("Attempt to close a group that switched to mode {mode}"),
1801      current_frame_message()
1802    );
1803  } else if !lookup_bool_sym(crate::pin!("groupNonBoxing")) {
1804    // A bare environment whose body is read in a boxing frame of its own — a brace-less `\abstract`'s
1805    // capture (`\lx@add@frontmatter@until`, marked by sect05.rs `\lx@abstract@bare@frame`) — ends as any
1806    // bare `\X` does (witness 2305.17823).
1807    if let Some(closer) = get_current_token()
1808      && close_environment_frame(closer, true)?
1809    {
1810      return Ok(());
1811    }
1812    // or group was opened with \bgroup
1813    Error!(
1814      "unexpected",
1815      get_current_token()
1816        .map(|t| t.to_string())
1817        .unwrap_or_else(|| String::from("\\?")),
1818      "Attempt to close non-boxing group",
1819      current_frame_message()
1820    );
1821  } else {
1822    pop_stack_frame(true)?;
1823  }
1824  Ok(())
1825}
1826
1827//======================================================================
1828// Mode (minimal so far; math vs text)
1829// Could (should?) be taken up by Stomach by building horizontal, vertical or math lists ?
1830
1831/// Sets the mode without doing any grouping (NOR does it stack the modes!!)
1832///
1833/// Useful for environments, where the group has already been established.
1834/// (presumably, in the long run, modes & groups should be much less coupled)
1835pub fn set_mode(mode: &str) -> Result<()> {
1836  let prevbound = lookup_string_from_sym(crate::pin!("BOUND_MODE"));
1837  set_mode_from(mode, &prevbound)
1838}
1839
1840/// [`set_mode`] with the bound mode that was in force before the caller bound
1841/// the new one: [`begin_mode_opt`] binds `BOUND_MODE` first and reads the
1842/// previous value before it does (Perl `beginMode` reads `$prevbound` before
1843/// its `assignValue`, Stomach.pm:503-507).
1844fn set_mode_from(mode: &str, prevbound: &str) -> Result<()> {
1845  // Perl reads `$wasmath` from MODE (Stomach.pm:504); there MODE differs from
1846  // BOUND_MODE only by the vertical/horizontal toggle, never in math. Rust
1847  // forces MODE to `internal_vertical` inside a math-level `\noalign`
1848  // (tex_tables.rs), so the bound mode is the faithful test: an `\hbox` in
1849  // `$$\eqalignno{…\noalign{\hbox{where}}…}$$` gets the pre-math font back.
1850  let wasmath = prevbound.ends_with("math");
1851  let ismath = mode.ends_with("math");
1852  // Perl: beginMode maps to internal mode names, but set_mode stores as-is
1853  // We also set BOUND_MODE so end_mode can find it
1854  let bound_mode = bindable_mode(mode).unwrap_or(mode);
1855  // Diagnostic
1856  if *TRACE_BOUND_MODE {
1857    eprintln!(
1858      "[trace] set_mode mode={mode} bound_mode={bound_mode}\n{}",
1859      std::backtrace::Backtrace::force_capture()
1860    );
1861  }
1862  assign_frame_value("BOUND_MODE", arena::pin(bound_mode));
1863  assign_frame_value("MODE", arena::pin(bound_mode));
1864  assign_value("IN_MATH", ismath, Some(Scope::Local));
1865  // Perl Stomach.pm:514-535: nothing when the bound mode is unchanged; the
1866  // math font on entering math; and the pre-math text font back ONLY when
1867  // leaving math (`elsif ($wasmath)`). Restoring it on every other change
1868  // undid a text font switch at the next `\hbox` inside a `\vbox` inside
1869  // math: fancyvrb's `BVerbatim[baseline=c]` (`$\vcenter\bgroup`,
1870  // fancyvrb.sty:1103-1105) lost its `\ttfamily` (cascade-french).
1871  if bound_mode == prevbound {
1872  } else if ismath {
1873    let curfont = lookup_font().unwrap();
1874    // When entering math mode, we set the font to the default math font,
1875    // and save the text font for any embedded text.
1876    assign_value("savedfont", curfont.clone(), Some(Scope::Local));
1877    // see get_script_level()
1878    assign_value("script_base_level", stomach!().boxing.len(), None);
1879    let isdisplay = mode.starts_with("display");
1880    assign_value("IN_MATH_DISPLAY", isdisplay, Some(Scope::Local));
1881    let new_font = Rc::new(lookup_mathfont().unwrap().merge(Font {
1882      color: curfont.color,
1883      bg: curfont.bg,
1884      size: curfont.size,
1885      mathstyle: if isdisplay {
1886        Some("display".into())
1887      } else {
1888        Some("text".into())
1889      },
1890      ..Font::default()
1891    }));
1892    assign_value(
1893      "initial_math_font",
1894      Stored::Font(new_font.clone()),
1895      Some(Scope::Local),
1896    );
1897    assign_font(new_font, Some(Scope::Local));
1898    // Perl Stomach.pm:505 — `$STATE->assignValue(fontfamily => -1, 'local');`
1899    // Resets `\fam` (whose getter reads `fontfamily`) on math entry so that
1900    // text-mode `\rm` (which sets `fontfamily=0`) doesn't leak into math.
1901    assign_value("fontfamily", -1_i64, Some(Scope::Local));
1902  } else if wasmath {
1903    // When entering text mode, we should set the font to the text font in use before the math
1904    // but inherit color and size
1905    if let Some(font) = hbox_font_in_math() {
1906      assign_font(font, Some(Scope::Local));
1907    }
1908  }
1909  Ok(())
1910}
1911
1912/// The font an `\hbox` opened in math gets: the text font in use before the math (`savedfont`), with the current
1913/// colour, background and size (Perl Stomach.pm:531-536, `beginMode`'s `$wasmath` branch); `None` without one.
1914pub fn hbox_font_in_math() -> Option<Rc<Font>> {
1915  let curfont = lookup_font()?;
1916  let Some(Stored::Font(saved_font)) = lookup_value("savedfont") else {
1917    return None;
1918  };
1919  Some(Rc::new(saved_font.merge(Font {
1920    color: curfont.color,
1921    bg: curfont.bg,
1922    size: curfont.size,
1923    ..Font::default()
1924  })))
1925}
1926
1927/// Map user-facing mode names to internal bound mode names.
1928/// Perl: our %bindable_mode = (text => 'restricted_horizontal', ...)
1929fn bindable_mode(umode: &str) -> Option<&'static str> {
1930  match umode {
1931    "text" | "restricted_horizontal" => Some("restricted_horizontal"),
1932    "vertical" | "internal_vertical" => Some("internal_vertical"),
1933    // Perl #2798: inline_internal_vertical binds to internal_vertical but does
1934    // NOT leaveHorizontal (inline blocks: \vbox/\vtop/\parbox/minipage/picture/
1935    // footnotes) — see begin_mode_opt.
1936    "inline_internal_vertical" => Some("internal_vertical"),
1937    "math" | "inline_math" => Some("math"),
1938    "display_math" => Some("display_math"),
1939    _ => None,
1940  }
1941}
1942
1943/// Run `f`, the digestion of a list of its own whose `\vadjust` material never reaches the paragraph around it: a
1944/// restricted horizontal box's contents (`\hbox`, `\mbox`, `\sbox`, calc's `\widthof`, pgfmath's `width()`), where it
1945/// stays in the box and prints nothing (tex.web §655 migrates it only when the packer is handed an adjust list: a
1946/// paragraph's lines §889, an alignment's cells §796), and a `\vadjust`'s own material, whose paragraph sets what it
1947/// queued. The list starts with an empty queue and the paragraph's is put back after (KNOWN_PERL_ERRORS #441; guard
1948/// `box_primitives::vadjust`). Residuals: a vertical-mode `\hbox` (§1076 `adjusted_hbox_group`) drops it too, where
1949/// TeX sets it after the box; a tabular's cells inside the box lose theirs (§799 sets it after the row); hboxes built
1950/// outside the box reader (`\phantom`, `\text`, `\resizebox`, `\underline`) keep printing theirs (RED
1951/// boxes-groups/vadjust_material_stays_in_its_hbox).
1952pub fn with_own_adjust_queue<R>(f: impl FnOnce() -> R) -> R {
1953  let outer = take_pushed("vAdjust");
1954  let result = f();
1955  restore_pushed("vAdjust", outer);
1956  result
1957}
1958
1959/// Begin processing in `mode`; one of "text", "display-math" or "inline-math".
1960/// This also begins a new level of grouping and switches to a font
1961/// appropriate for the mode.
1962/// If `noframe` is true, skip pushing a stack frame (e.g. for \begin{document}).
1963/// Perl: sub beginMode (Stomach.pm lines 474-517)
1964pub fn begin_mode(mode: &str) -> Result<()> { begin_mode_opt(mode, false) }
1965/// Like `begin_mode`, but with an explicit `noframe` option.
1966/// When `noframe` is true, no stack frame is pushed (the caller already did bgroup).
1967pub fn begin_mode_opt(mode: &str, noframe: bool) -> Result<()> {
1968  if let Some(bound_mode) = bindable_mode(mode) {
1969    // Perl #2798: beginning a vertical or display-math mode ends the current
1970    // paragraph first (leaveHorizontal), UNLESS the *user* mode is an inline
1971    // form (inline_internal_vertical / inline_math) — inline blocks must not
1972    // break the surrounding paragraph. `leave_horizontal` is itself a no-op
1973    // unless mid-paragraph (MODE==horizontal), so this only fires when a
1974    // vertical/display construct is encountered inside a paragraph.
1975    let is_display = bound_mode.starts_with("display");
1976    let is_vertical = is_display || bound_mode.contains("vertical");
1977    let is_inline = mode.contains("inline");
1978    if is_display {
1979      // tex.web §1145 `init_math`: a display ends the paragraph by `line_break`, never by the `\par` meaning, which
1980      // Perl expands here (Stomach.pm:501, :436-446; OXIDIZED_DESIGN_DIVERGENCES #1206; witness 2106.02379).
1981      leave_horizontal_with(T_CS!("\\lx@normal@par"))?;
1982    } else if is_vertical && !is_inline {
1983      leave_horizontal()?;
1984    }
1985    if !noframe {
1986      push_stack_frame(false); // Effectively bgroup
1987    }
1988    // Diagnostic: tracking who binds BOUND_MODE during raw .sty load
1989    // (gated by LXML_TRACE_BOUND_MODE env var to avoid noise in normal runs).
1990    // See project_explsyntax_midload.md memory for the active investigation.
1991    if *TRACE_BOUND_MODE {
1992      eprintln!(
1993        "[trace] begin_mode_opt mode={mode} noframe={noframe} bound_mode={bound_mode}\n{}",
1994        std::backtrace::Backtrace::force_capture()
1995      );
1996    }
1997    let prevbound = lookup_string_from_sym(crate::pin!("BOUND_MODE"));
1998    // Perl: $STATE->assignValue(BOUND_MODE => $mode, 'local');
1999    assign_frame_value("BOUND_MODE", arena::pin(bound_mode));
2000    // tex.web §211's inner sign, kept as a frame-bound flag: a FRAMED mode
2001    // switch is a box or math interior (`\hbox`/`\vbox`/`\parbox`/minipage,
2002    // `$…$`), where `\ifinner` is true; display math is positive `mmode`
2003    // (outer); the document body's frameless `internal_vertical` and plain
2004    // `{…}` groups bind nothing, so the main galley stays outer. The mode
2005    // STRINGS serve both galley and box (`internal_vertical`), so `\ifinner`
2006    // on them said inner at the body top after `\par` — paracol.sty:1996
2007    // `\ifinner\@parmoderr` (tidyres); Perl identical. The binding is
2008    // undone with the frame at `end_mode`. Guard:
2009    // `perfect_kernel_batch54::ifinner_is_the_box_frame_sign`.
2010    if !noframe {
2011      assign_frame_value_sym(crate::pin!("INNER_BOX"), bound_mode != "display_math");
2012    }
2013    set_mode_from(bound_mode, &prevbound)?;
2014    // Perl Stomach.pm lines 527-530: inject \everymath or \everydisplay tokens
2015    // Display math gets \everydisplay, inline math gets \everymath (not both). Perl reads them
2016    // only when they are registers (`$ereg->isRegister`), quietly: a package that redefines
2017    // `\everymath` as a macro does not warn at every formula.
2018    if bound_mode.contains("math") {
2019      let is_display = bound_mode == "display_math";
2020      let reg_name = if is_display {
2021        "\\everydisplay"
2022      } else {
2023        "\\everymath"
2024      };
2025      if let Some(RegisterValue::Tokens(toks)) = lookup_register_quiet(reg_name) {
2026        let toks = toks.unlist();
2027        if !toks.is_empty() {
2028          gullet::unread(Tokens::new(toks));
2029        }
2030      }
2031    }
2032    Ok(())
2033  } else {
2034    Warn!("unexpected", mode, s!("Cannot enter {mode} mode"));
2035    Ok(())
2036  }
2037}
2038/// End processing in `mode`; an error is signalled if `stomach` is not
2039/// currently in `mode`.  This also ends a level of grouping.
2040/// Perl: sub endMode (Stomach.pm lines 522-541)
2041pub fn end_mode(mode: &str) -> Result<()> { end_mode_opt(mode, false) }
2042/// Like `end_mode`, but with an explicit `noframe` option.
2043/// When `noframe` is true, executeBeforeAfterGroup is run but the stack frame is not popped.
2044pub fn end_mode_opt(mode: &str, noframe: bool) -> Result<()> {
2045  if let Some(bound_mode) = bindable_mode(mode) {
2046    // Perl Stomach.pm L527-528:
2047    //   if ((!$STATE->isValueBound('BOUND_MODE', 0))     # Last stack frame was NOT a mode switch
2048    //     || ($STATE->lookupValue('BOUND_MODE') ne $mode))  # OR switch to a different mode
2049    // Strict Perl-faithful: error if BOUND_MODE is not bound on the top
2050    // frame, OR if its value doesn't match the mode being closed. (Earlier
2051    // versions of this file used a lax value-only check as a workaround
2052    // for the 1112.6246 halign frame-balance issue, since fixed in
2053    // d162803d2.)
2054    let current_bound = lookup_string_from_sym(crate::pin!("BOUND_MODE"));
2055    let bound_on_top = is_value_bound("BOUND_MODE", Some(0));
2056    let make_mode_error = || {
2057      // Perl Stomach.pm:550: Error('unexpected', $CURRENT_TOKEN, $self,
2058      //   "Attempt to end mode $mode", currentFrameMessage($self)) — where
2059      // $mode is the BOUND (bindable) mode, and currentFrameMessage is a
2060      // SEPARATE detail (added at the call sites below). The earlier Rust
2061      // wording ("...mode `X` in `Y`") was not Perl-faithful.
2062      let message = s!("Attempt to end mode {}", bound_mode);
2063      let category = match get_current_token() {
2064        Some(ref token) => token.to_string(),
2065        None => String::from("mode"),
2066      };
2067      (category, message)
2068    };
2069    if !bound_on_top || current_bound != bound_mode {
2070      // Last stack frame was NOT a mode switch, or was a switch to a different mode.
2071      // Perl: Don't pop if there's an error; maybe we'll recover?
2072      if *TRACE_BOUND_MODE {
2073        let cur_tok = get_current_token()
2074          .map(|t| t.to_string())
2075          .unwrap_or_default();
2076        eprintln!(
2077          "[trace] end_mode ERROR: mode={mode} cur_tok={cur_tok} bound_on_top={bound_on_top} current_bound={current_bound} depth={}\n  {}\n{}",
2078          get_frame_depth(),
2079          current_frame_message(),
2080          std::backtrace::Backtrace::force_capture()
2081        );
2082      }
2083      let (category, message) = make_mode_error();
2084      Error!("unexpected", category, &message, current_frame_message());
2085    } else {
2086      // Perl: leaveHorizontal_internal($self) if $mode =~ /vertical$/;
2087      if bound_mode.ends_with("vertical") {
2088        leave_horizontal_internal();
2089      }
2090      if noframe {
2091        // No pop, but at least do beforeAfterGroup
2092        execute_before_after_group()?;
2093      } else if current_frame_locked() {
2094        // After `leave_horizontal_internal` the only frame left is the LOCKED
2095        // bottom frame — there is no mode-switch frame to pop, so
2096        // `pop_stack_frame` → `pop_frame` would FATAL ("pop last locked stack
2097        // frame"). This happens on a STRAY mode-ender with no matching begin:
2098        // e.g. `$Proof.$ … \quad \endproof` (no `\begin{proof}`) leaves
2099        // BOUND_MODE bound on the bottom frame, so the value-guard above passes
2100        // but the pop is illegal. Emit a recoverable Error and DON'T pop (Perl's
2101        // "maybe we'll recover" intent — Perl completes such papers; Rust used
2102        // to crash). Note the check is HERE (after `leave_horizontal_internal`,
2103        // which can repack a horizontal frame that legitimately becomes the
2104        // pop target — e.g. a normal document's `\end{document}`), not at the
2105        // value-guard above. Witness 1703.05010 (svjour3 + bare `\endproof`).
2106        let (category, message) = make_mode_error();
2107        Error!("unexpected", category, &message);
2108      } else {
2109        pop_stack_frame(false)?;
2110      }
2111    }
2112  } else {
2113    Warn!("unexpected", mode, s!("Cannot end {mode} mode"));
2114  }
2115  Ok(())
2116}
2117
2118thread_local! {
2119  // Re-entrancy guard so `\everypar`'s own digestion can't recursively re-fire it.
2120  static EVERYPAR_FIRING: Cell<bool> = const { Cell::new(false) };
2121  // How many isolated argument digestions (`digest(tokens)`) are open, with
2122  // `digest_next_body` resetting the count to 0 for the list it captures.
2123  // tex.web §1091 `new_graf` fires `\everypar` when a *list* — the main
2124  // vertical list or a `\vbox`'s internal one — starts a paragraph; a
2125  // constructor's digested `{}` argument is macro-parameter text that TeX
2126  // never typesets as such, so a paragraph "started" while reverting it is
2127  // not a `new_graf`. An armed `\everypar` (latex.ltx `\@afterheading`'s
2128  // `{\setbox\z@\lastbox}`, left by ltugboat.cls:1214 `\aftergroup
2129  // \@afterheading` in `\@maketitle`) used to fire inside
2130  // `\@@numbered@section`'s *type* argument and revert into it as
2131  // `{}section` — counter `\c@{}section`, tag `ltx:{}section` (lazylist,
2132  // parnotes; guard
2133  // `perfect_kernel_batch54::everypar_does_not_fire_inside_a_constructor_argument`).
2134  static ARG_DIGEST_DEPTH: Cell<u32> = const { Cell::new(0) };
2135}
2136
2137/// RAII bookkeeping for `ARG_DIGEST_DEPTH`: restores the saved depth on
2138/// drop, so early `?` returns inside a digestion loop cannot leave the count
2139/// skewed.
2140struct ArgDigestScope(u32);
2141
2142impl ArgDigestScope {
2143  /// Enter an isolated argument digestion (depth + 1).
2144  fn enter_argument() -> Self {
2145    let saved = ARG_DIGEST_DEPTH.with(|d| d.replace(d.get() + 1));
2146    ArgDigestScope(saved)
2147  }
2148
2149  /// Enter a body capture: the captured material is a list of its own
2150  /// (a box, an environment body), so `new_graf` applies again inside it.
2151  fn enter_body() -> Self {
2152    let saved = ARG_DIGEST_DEPTH.with(|d| d.replace(0));
2153    ArgDigestScope(saved)
2154  }
2155}
2156
2157impl Drop for ArgDigestScope {
2158  fn drop(&mut self) { ARG_DIGEST_DEPTH.with(|d| d.set(self.0)); }
2159}
2160
2161/// Fire `\the\everypar` when a paragraph enters horizontal mode, the way tex.web's
2162/// `new_graf` (background/tex.web L21117) does `begin_token_list(every_par)`.
2163///
2164/// Guarded two ways, because LaTeXML's `\everypar` is not TeX's:
2165/// * `\everypar` is empty for most paragraphs (`\begin{document}` clears it — see
2166///   `latex_constructs/sect02.rs`), so this is a cheap early return except where a document or
2167///   package populates it (algorithm2e line numbering sets `\everypar`→`\algocf@everypar`→`\nl`
2168///   inside a listing; a preamble chain such as arabicore's keeps its own hook there).
2169/// * We fire ONLY in the document body. In the preamble the list holds
2170///   latex.ltx:9137's `\@nodocument` ("Missing \begin{document}"); `\begin{document}`
2171///   lets `\@nodocument`→`\relax`, so "document started" is exactly that test.
2172///
2173/// The digested boxes are pushed to the current box list BEFORE the triggering box
2174/// (the caller `extend_box_list`s that after), so `\nl`'s tag lands at the head of
2175/// the listingline. Errors are swallowed (this rides the infallible mode-switch
2176/// path); a genuine fatal is re-detected at the next digest-loop checkpoint.
2177fn fire_everypar() {
2178  let Some(toks) = pending_everypar() else {
2179    return;
2180  };
2181  struct ResetEverypar;
2182  impl Drop for ResetEverypar {
2183    fn drop(&mut self) { EVERYPAR_FIRING.with(|f| f.set(false)); }
2184  }
2185  EVERYPAR_FIRING.with(|f| f.set(true));
2186  let _guard = ResetEverypar;
2187  if let Ok(digested) = digest(toks) {
2188    // A List box is unwound (flattened) on absorption, so `\nl`'s tag-whatsit runs
2189    // inline in the current listingline rather than under a wrapper.
2190    push_box_list(digested);
2191  }
2192}
2193
2194/// The `\everypar` a paragraph started here would fire (see `fire_everypar` for
2195/// the two guards), or `None`.
2196fn pending_everypar() -> Option<Tokens> {
2197  if EVERYPAR_FIRING.with(|f| f.get()) || ARG_DIGEST_DEPTH.with(|d| d.get()) > 0 {
2198    return None;
2199  }
2200  // tex.web §1091: `new_graf` runs the every_par slot, whatever `\everypar` means now. Under
2201  // LaTeX that slot is the para hook, which runs the register latex.ltx:9070 allocated, named by
2202  // number (:9072-9077) — `\lx@para@everypar` (latex_constructs_rust_only.rs) — so a package's
2203  // `\def\everypar` (rlbicig.sty:62-64, witness: montex manual) or `\let\everypar\othertoks`
2204  // leaves it in place. Without LaTeX there is no document body (the `\@nodocument` test below),
2205  // so nothing fires.
2206  let register = lookup_register_definition(&T_CS!("\\lx@para@everypar"))?;
2207  let Some(RegisterValue::Tokens(toks)) = register.value_of(Vec::new()) else {
2208    return None;
2209  };
2210  if toks.is_empty() {
2211    return None; // empty \everypar — the normal body paragraph
2212  }
2213  // Skip the preamble/kernel-load para-hook \everypar (see doc comment).
2214  if !x_equals(&T_CS!("\\@nodocument"), &T_CS!("\\relax")) {
2215    return None;
2216  }
2217  Some(toks)
2218}
2219
2220/// tex.web §1090-1091: a character in vertical mode is backed up (`back_input`)
2221/// and `new_graf` inserts `\everypar` IN FRONT of it, so the paragraph hook reads
2222/// the very token that started the paragraph, its catcode already fixed.
2223/// syntax.sty:264-274's grammar relies on it — `\everypar{…\catcode`\<\active
2224/// \gr@implitem}` whose `\gr@implitem<#1> #2 ` then reads the catcode-12 `<`
2225/// that began the line; digesting `\everypar` beside an already-absorbed `<` left
2226/// the macro nothing to match (`¡ab¿`). Returns whether it backed the token up: the
2227/// mode is horizontal, and `\everypar` then `token` are the next input.
2228/// `\indent`/`\noindent` unread `\everypar` after their listed indent box
2229/// ([`enter_horizontal_listed_indent`]); other paragraph starters (constructors,
2230/// `\leavevmode`) still fire it in place (`fire_everypar`). OXIDIZED_DESIGN #267; guard
2231/// `perfect_kernel_batch56::everypar_reads_the_token_that_started_the_paragraph`.
2232fn back_input_for_new_graf(token: Token) -> bool {
2233  if !mode_ends_with("vertical") {
2234    return false;
2235  }
2236  let Some(toks) = pending_everypar() else {
2237    return false;
2238  };
2239  assign_value_inplace_sym(crate::pin!("MODE"), crate::pin!("horizontal"));
2240  mark_paragraph_start(true);
2241  gullet::unread_one(token);
2242  gullet::unread(toks);
2243  true
2244}
2245
2246/// tex.web §1090: the commands that, met in vertical mode, are backed up while `new_graf` (§1091) puts `\everypar`
2247/// in front of them, as a character is ([`back_input_for_new_graf`]) — `hskip` (`\hskip`, `\hfil`, `\hfill`, `\hss`,
2248/// `\hfilneg`), `un_hbox` (`\unhbox`, `\unhcopy`, and `\leavevmode`, plain's and LaTeX's `\unhbox\voidb@x`), `vrule`,
2249/// `char_num`, `accent`, `discretionary` (`\-`), `ex_space` (`\ `), `valign`, `no_boundary`. A hook that opens a box
2250/// for the paragraph's material — a Maple session transcript's `\everypar{\setbox0=\hbox\bgroup}`, closed by its
2251/// active end of line (`\leavevmode\egroup\box0\par`) — then holds the command too; digested in place, ahead of the
2252/// command's own mode switch, it left the box's group under the paragraph's ("Attempt to close a group that switched to
2253/// mode horizontal" at every line opening with a space, gr-qc9505014: 100 errors and a Fatal). `\indent`/`\noindent`
2254/// (`start_par`) list their indent box first ([`enter_horizontal_listed_indent`]); math shift and the constructors keep
2255/// the in-place hook ([`fire_everypar`]), as does the rule a `\leaders` reads. Matched by the definition's own name, so
2256/// a `\let` copy is the same command.
2257/// Guard `perfect_kernel_batch80a::everypar_box_holds_a_line_opened_by_a_control_space`.
2258fn starts_new_graf(cs: &Token) -> bool {
2259  mode_ends_with("vertical")
2260    && cs.with_str(|name| {
2261      matches!(
2262        name,
2263        "\\hskip"
2264          | "\\hfil"
2265          | "\\hfill"
2266          | "\\hss"
2267          | "\\hfilneg"
2268          | "\\unhbox"
2269          | "\\unhcopy"
2270          | "\\leavevmode"
2271          | "\\vrule"
2272          | "\\char"
2273          | "\\accent"
2274          | "\\discretionary"
2275          | "\\-"
2276          | "\\ "
2277          | "\\valign"
2278          | "\\noboundary"
2279      )
2280    })
2281    // the rule `\leaders` reads is a rule specification, not a command (tex.web §1078, §1084: `scan_box` reads it, and
2282    // it starts no paragraph); `\leaders` marks it (tex_box.rs)
2283    && !lookup_bool("lx@leaders@rule")
2284}
2285
2286/// Switch to horizontal mode without stacking the mode.
2287/// Can only switch from vertical|internal_vertical to horizontal.
2288/// Perl: sub enterHorizontal.
2289/// tex.web `new_graf` (L21117) fires `\everypar` here (`begin_token_list`).
2290pub fn enter_horizontal() { enter_horizontal_graf(true, true) }
2291
2292/// [`enter_horizontal`] for `\noindent` and `\indent`: a paragraph whose indent box, if any, is on the list — none for
2293/// `\noindent` (tex.web §1091 `new_graf(false)`), `\indent`'s own whatsit — with `\everypar` read after it.
2294pub fn enter_horizontal_listed_indent() { enter_horizontal_graf(false, true) }
2295
2296/// [`enter_horizontal`] without `\everypar`, as Perl's `enterHorizontal` (Stomach.pm:422-433): the paragraph of a
2297/// box LaTeX resets `\everypar` in, a float's caption (`PBoxContents`; latex.ltx `\@floatboxreset` → `\@setminipage`
2298/// leaves only `\@minipagefalse` there), where a hook an enclosing list armed — aasms4's `\references`, whose
2299/// paragraphs are entries — does not run.
2300pub fn enter_horizontal_without_everypar() { enter_horizontal_graf(true, false) }
2301
2302fn enter_horizontal_graf(implicit_indent: bool, everypar: bool) {
2303  let mode = lookup_mode();
2304  if arena::with(mode, |mode| mode.ends_with("vertical")) {
2305    assign_value_inplace_sym(crate::pin!("MODE"), crate::pin!("horizontal"));
2306    mark_paragraph_start(implicit_indent);
2307    if everypar && implicit_indent {
2308      fire_everypar();
2309    } else if everypar && let Some(toks) = pending_everypar() {
2310      // `\indent`/`\noindent` (tex.web §1088 `start_par`): `new_graf` lists the indent box, if any, and THEN
2311      // `begin_token_list(every_par)`, so the hook is the next input, read after the command — its whatsit precedes
2312      // the hook's material, and `\noindent` finds the paragraph it marks `ltx_noindent` (digested here, the hook's
2313      // text opened the `ltx:p` first and the class was lost). Repro block-model/noindent_class_survives_everypar.
2314      gullet::unread(toks);
2315    }
2316  } else if arena::with(mode, |mode| {
2317    !mode.ends_with("horizontal") && !mode.ends_with("math")
2318  }) {
2319    // Perl L420-422: warn on unexpected mode
2320    Warn!(
2321      "unexpected",
2322      "enterHorizontal",
2323      s!(
2324        "Unexpected mode '{}' for enterHorizontal",
2325        arena::to_string(mode)
2326      )
2327    );
2328  }
2329  // else: already horizontal or math — fine
2330}
2331
2332/// Resume vertical mode by executing \par, in TeX-like fashion.
2333/// Perl: sub leaveHorizontal
2334pub fn leave_horizontal() -> Result<()> { leave_horizontal_with(T_CS!("\\par")) }
2335
2336fn leave_horizontal_with(par: Token) -> Result<()> {
2337  if lookup_mode() == crate::pin!("horizontal")
2338    && arena::with(
2339      lookup_string_sym_from_sym(crate::pin!("BOUND_MODE")),
2340      |bound| bound.ends_with("vertical"),
2341    )
2342  {
2343    // This needs to be an invisible, and slightly gentler, \par
2344    assign_value("INTERNAL_PAR", true, Some(Scope::Local));
2345    if matches!(lookup_meaning(&par), Some(Stored::Expandable(_))) {
2346      // tex.web §1094 `head_for_vmode`: TeX backs the vertical command up and
2347      // inserts `\par` in front of it, so a redefined `\par` runs its WHOLE
2348      // body before the command reads its arguments. `invoke_token` stops at
2349      // the macro's first primitive and leaves the rest in the gullet, where
2350      // `\vskip`'s glue scan read it: syntax.sty:264-273's grammar `\par`
2351      // (`\parshape…\@@par \catcode`\<12 \everypar{…}`) lost `\@@par` to the
2352      // scan ("Missing number"), and the glue's stray digit then started a
2353      // paragraph that fired the re-armed `\everypar`, whose `\gr@implitem`
2354      // never found its catcode-12 `<` (2605.07451: `\grammarShrink` =
2355      // `\vspace` between productions). The body is read from a mouth of its
2356      // own, in no group (its assignments stand), and invoked against the
2357      // CURRENT box list, so `\@@par`'s repack still sees the paragraph and
2358      // the vertical-mode `\par` whatsit stays a bare paragraph boundary. The
2359      // one departure from §1094: a body that reads past its own end finds
2360      // end of input here, not the vertical command behind it.
2361      gullet::reading_from_mouth(Mouth::default(), || {
2362        gullet::unread(Tokens!(par));
2363        while let Some(token) = gullet::read_x_token(Some(true), false, None)? {
2364          check_timeout()?;
2365          let invoked = invoke_token(&token)?;
2366          extend_box_list(invoked);
2367        }
2368        Ok(())
2369      })?;
2370    } else {
2371      let par_result = invoke_token(&par)?;
2372      push_box_list_vec(par_result);
2373    }
2374    assign_value("INTERNAL_PAR", false, Some(Scope::Local));
2375  }
2376  Ok(())
2377}
2378
2379/// Resume vertical mode internally: reset mode without firing \par.
2380/// Used within argument digestion, e.g. endMode for vertical modes.
2381/// Perl: sub leaveHorizontal_internal
2382pub fn leave_horizontal_internal() {
2383  if lookup_mode() != crate::pin!("horizontal") {
2384    return;
2385  }
2386  let bound = lookup_string_sym_from_sym(crate::pin!("BOUND_MODE"));
2387  if arena::with(bound, |bound| bound.ends_with("vertical")) {
2388    repack_horizontal();
2389    assign_value_inplace_sym(crate::pin!("MODE"), bound);
2390  }
2391}
2392
2393/// Repack recently digested horizontal items into single horizontal List.
2394/// Note that TeX would have done paragraph line-breaking, resulting in essentially
2395/// a vertical list.
2396/// Perl: sub repackHorizontal (Stomach.pm lines 440-454)
2397pub fn repack_horizontal() { repack_paragraph(false) }
2398
2399/// tex.web §1096 `end_graf`, for an explicit `\par`: the paragraph ends and its material goes on the vertical list as
2400/// its line ([`repack_horizontal`]). A paragraph that holds nothing still makes a line — `\leavevmode\par` an indent box
2401/// alone, which `\lastbox` takes and `\unskip` cannot reach past (Rust kept nothing, so `\vskip3pt
2402/// \leavevmode\par\unskip` removed the `\vskip`) — unless it is null: no indent box and nothing listed
2403/// (`\noindent\par`, `\indent\setbox0\lastbox\par`; `ParagraphStart`). Only spaces are kept out of the line (Perl
2404/// `repackHorizontal`: they would make an empty `ltx:p`), so it absorbs to nothing; the sizing pass gives it a line's
2405/// height (font.rs). Every `\par` that `leave_horizontal` inserts only repacks: before a block LaTeXML sets apart (a
2406/// minipage), where TeX's paragraph goes on, and also TeX's own §1094 `head_for_vmode` `\par` (`\vskip`, `\hrule`,
2407/// `\unvbox` in a paragraph), which does end it — residual: `\vbox{\leavevmode\vskip3pt\hbox{B}}` is 9.83pt high, TeX
2408/// 15pt. The end of a box's contents (`leave_horizontal_internal`, §1085) only repacks too. Residual: LaTeX's `\par`
2409/// (`\para_end:`, latex.ltx:9088) `\unskip`s first, so `\noindent\hfill\par` is null there too; here it makes a line.
2410pub fn end_graf() { repack_paragraph(true) }
2411
2412fn repack_paragraph(end_graf: bool) {
2413  let mut stomach = stomach_mut!();
2414  let mut para: Vec<Digested> = Vec::new();
2415  let mut keep = false;
2416
2417  loop {
2418    let should_pop = if let Some(item) = stomach.box_list.last() {
2419      // Perf: compare as &str via with() instead of allocating a String each iter.
2420      // Default mode is "horizontal" (matches previous unwrap_or).
2421      let mode_prop = item.get_property("mode");
2422      let (is_horiz_family, is_plain_horizontal) = match mode_prop.as_deref() {
2423        Some(Stored::String(sym)) => arena::with(*sym, |s| {
2424          let plain = s == "horizontal";
2425          let fam = plain || s == "restricted_horizontal" || s == "math";
2426          (fam, plain)
2427        }),
2428        None => (true, true), // default "horizontal"
2429        Some(other) => {
2430          // Rare path — fall back to Display formatting.
2431          let s = other.to_string();
2432          let plain = s == "horizontal";
2433          let fam = plain || s == "restricted_horizontal" || s == "math";
2434          (fam, plain)
2435        },
2436      };
2437      // A box `\unhbox` put into this paragraph is an item of its line whatever its own mode (`in_hlist`, tex.web
2438      // §1076; tex_box.rs `hlist_of`): tcolorbox's `sidebyside` halves, 2605.11712, 2605.31228. Only while it is in
2439      // this paragraph: one `\lastbox` took and `\box` put on the vertical list is no item of the next.
2440      let own_item = stomach
2441        .paragraph_start
2442        .is_some_and(|start| stomach.box_list.len() > start.index);
2443      if is_horiz_family || (own_item && item.get_property_bool("in_hlist")) {
2444        if !is_plain_horizontal || !item.get_property_bool("isSpace") {
2445          keep = true;
2446        }
2447        true
2448      } else {
2449        false
2450      }
2451    } else {
2452      false
2453    };
2454
2455    if should_pop {
2456      para.push(stomach.box_list.pop().unwrap());
2457    } else {
2458      break;
2459    }
2460  }
2461
2462  // Items were popped in reverse order, so reverse them back
2463  para.reverse();
2464  // Run off the bottom of a text group's list: Perl's pop goes on to the group's open-brace box, which is no space, so
2465  // the paragraph is kept (`x{\phantom{Ca}\par Cb}`; 2410.06985 `\node{\phantom{Cpd}\\…}`) — unless the group added
2466  // only spaces, glue and kerns (1602.08755 `x\footnotesize{⏎`): no box, so nothing that gives x's line, the one line
2467  // TeX makes, height or depth (§816 deletes a final glue; a kern stays, and `\penalty` lists nothing here).
2468  if !keep
2469    && stomach.box_list.is_empty()
2470    && stomach.paragraph_start.is_some_and(|start| start.in_group)
2471    && !para.iter().all(adds_no_line_material)
2472  {
2473    keep = true;
2474  }
2475
2476  // A paragraph that kept nothing but owns the list's tail (no vertical-mode item of its own stands for its line),
2477  // unless it is null: begun by `\noindent` with nothing in it (§1096 `head=tail`). A text group's list owns no line:
2478  // its paragraph's line is in the list outside the group (`\vbox{x{ \par}}` is 4.31pt high).
2479  let empty_line = !keep
2480    && end_graf
2481    && stomach.paragraph_start.is_some_and(|start| {
2482      !start.in_group
2483        && stomach.box_list.len() <= start.index
2484        && (start.implicit_indent || !para.iter().all(is_list_tail_transparent))
2485    });
2486  if keep || empty_line {
2487    let mut list = List::new(if keep { para } else { Vec::new() });
2488    list.mode = Some(TexMode::Text); // "horizontal" in Perl
2489    // Perl: List(@para, mode => 'horizontal') — set mode property string
2490    // This is needed for compute_boxes_size vertical layout to detect paragraph Lists
2491    list.set_property("mode", Stored::String(pin!("horizontal")));
2492    // Perl #2798 (S4): a finished paragraph List records BOTH the fill width
2493    // (\hsize) and the \baselineskip, so the sizing pass (compute_boxes_size)
2494    // can line-break and stack with the right inter-line spacing.
2495    //   $list->setProperty(width    => LookupDimension('\hsize'));
2496    //   $list->setProperty(baseline => LookupDimension('\baselineskip', 1));
2497    if let Some(hsize) = lookup_dimension("\\hsize") {
2498      list.set_property("width", hsize);
2499    }
2500    if let Some(baseline) = lookup_dimension("\\baselineskip") {
2501      list.set_property("baseline", baseline);
2502    }
2503    stomach.box_list.push(Digested::from(list));
2504  }
2505}
2506
2507pub fn new_local_box_list() {
2508  let mut buffer = Vec::new();
2509  let mut stomach = stomach_mut!();
2510  // Guard the OTHER aberrant accumulation path: the boxing stack. When a loop
2511  // builds *inside* boxes (`\setbox`/`\hbox`), each nesting suspends the partial
2512  // outer list here and opens a fresh `box_list`; an unbounded `\hbox{\hbox{…}}`
2513  // nest grows this stack without ever touching the byte/cycle guards on the
2514  // (small, innermost) `box_list`. A depth cap is O(1) and safe — no real
2515  // document nests boxes anywhere near this deep (typical depth is tens; the
2516  // math0102053 line-drawing loop sits at 13). Platform-independent, fires long
2517  // before any RSS/OOM ceiling.
2518  if stomach.localized_box_list.len() > STOMACH_BOXING_DEPTH_CAP
2519    && stomach.pending_cycle_fatal.is_none()
2520  {
2521    stomach.pending_cycle_fatal = Some((
2522      ErrorCategory::MemoryBudget,
2523      s!(
2524        "Boxing-stack runaway: box nesting depth exceeded {} \
2525         (unbounded \\hbox/\\setbox nesting)",
2526        STOMACH_BOXING_DEPTH_CAP
2527      ),
2528    ));
2529  }
2530  std::mem::swap(&mut stomach.box_list, &mut buffer);
2531  let paragraph_start = stomach.paragraph_start.take();
2532  stomach.localized_box_list.push(SuspendedList {
2533    list: buffer,
2534    paragraph_start,
2535    closer: None,
2536    in_formula: false,
2537    vertical: mode_ends_with("vertical"),
2538  });
2539}
2540
2541/// Hard cap on box-nesting depth (the `localized_box_list` boxing stack). No
2542/// real document nests `\hbox`/`\setbox` more than tens deep; a runaway nest
2543/// grows this without bound while the per-level `box_list` stays small, evading
2544/// the byte/cycle guards. Platform-independent.
2545const STOMACH_BOXING_DEPTH_CAP: usize = 100_000;
2546pub fn expire_local_box_list() -> Vec<Digested> {
2547  let mut stomach = stomach_mut!();
2548  let SuspendedList {
2549    list: mut buffer,
2550    paragraph_start,
2551    ..
2552  } = stomach.localized_box_list.pop().unwrap_or_default();
2553  std::mem::swap(&mut stomach.box_list, &mut buffer);
2554  stomach.paragraph_start = paragraph_start;
2555  buffer
2556}
2557
2558/// The depth of the box lists suspended by [`new_local_box_list`] and of the boxing stack: a mark for
2559/// [`unwind_box_lists_to`].
2560pub fn box_lists_mark() -> (usize, usize) {
2561  let stomach = stomach!();
2562  (stomach.localized_box_list.len(), stomach.boxing.len())
2563}
2564
2565/// Back to the box lists and boxing depth of `mark` ([`box_lists_mark`]), what was digested since discarded: the
2566/// lists a failed digestion left suspended (an `Err` leaves each `new_local_box_list` it was in unexpired) for a run
2567/// that is undone (sect05.rs `title_page_probe_run`).
2568pub fn unwind_box_lists_to(mark: (usize, usize)) {
2569  let mut stomach = stomach_mut!();
2570  while stomach.localized_box_list.len() > mark.0
2571    && let Some(parent) = stomach.localized_box_list.pop()
2572  {
2573    stomach.box_list = parent.list;
2574    stomach.paragraph_start = parent.paragraph_start;
2575  }
2576  stomach.boxing.truncate(mark.1);
2577}
2578
2579/// Recover the boxes a failed `digest_next_body` left stranded, in document
2580/// order, and reset the accumulation stack.
2581///
2582/// `digest_next_body` accumulates into `box_list` (with outer levels suspended
2583/// on `localized_box_list`) and only hands them back via `expire_local_box_list`
2584/// on the SUCCESS path — so a mid-body Fatal drops every box digested during
2585/// that call. `digest_internal` is written to keep partial output after a
2586/// recoverable Fatal ("Perl finishDigestion L219-220: loop consuming input even
2587/// after errors"), but that intent was defeated whenever the failure landed in
2588/// the FIRST body: the caller's `boxes` was still empty, so the run produced a
2589/// 39-byte empty document instead of the text preceding the bad construct.
2590/// Witness arXiv:2508.07407 (ar5iv #556) — its whole document was lost, though
2591/// only one `\tikz` picture is pathological.
2592///
2593/// `drop_innermost` is for the runaway guards (`Stomach:Recursion`), where the
2594/// innermost level IS the pathology — a 50k-box repeating window. Salvaging it
2595/// would graft the garbage into the document, so drop that level and keep the
2596/// suspended outer ones, which is precisely "drop the offending construct, keep
2597/// the document". For every other recoverable Fatal the current level is honest
2598/// content and is kept.
2599///
2600/// Each level closes as the construct that opened it would ([`close_pending_list_as`]: a constructor's argument or
2601/// body as its whatsit, an `\author` as its frontmatter entry), innermost first; a level with no closer joins its
2602/// enclosing list (a body, a group). Returns the boxes and how many levels a construct closed.
2603pub fn salvage_pending_box_lists(drop_innermost: bool) -> (Vec<Digested>, usize) {
2604  let (mut acc, mut levels) = {
2605    let mut stomach = stomach_mut!();
2606    stomach.paragraph_start = None;
2607    (
2608      std::mem::take(&mut stomach.box_list),
2609      std::mem::take(&mut stomach.localized_box_list),
2610    )
2611  };
2612  if drop_innermost {
2613    acc.clear();
2614    // (the construct the runaway window was in goes with it)
2615    if let Some(innermost) = levels.last_mut() {
2616      innermost.closer = None;
2617      innermost.in_formula = false;
2618    }
2619  }
2620  // Refuse a salvage that is itself pathological. `drop_innermost` removes the
2621  // runaway level for the STOMACH box-cycle guard, where that level is the
2622  // pathology — but the GULLET cycle guard (`Timeout:Recursion`) fires on the
2623  // token stream, and there the bloated boxes can sit in the suspended outer
2624  // levels instead, so dropping the innermost does not bound anything.
2625  //
2626  // `STOMACH_CYCLE_ACTIVATE` is exactly the engine's own "no honest document
2627  // accumulates this many undrained boxes" line, so reuse it rather than invent
2628  // a second threshold: a salvage at or past it is runaway output, and handing
2629  // it to the builder is worse than handing over nothing. Measured on
2630  // arXiv:2605.25400, where an unbounded salvage turned a 9.7 s fatal into a
2631  // 120 s wall-clock timeout that wrote a ZERO-byte file — strictly worse than
2632  // the 39-byte stub it replaced. (Counted before any closer wraps a level.)
2633  if acc.len() + levels.iter().map(|level| level.list.len()).sum::<usize>()
2634    >= STOMACH_CYCLE_ACTIVATE
2635  {
2636    return (Vec::new(), 0);
2637  }
2638  // Unwind the suspended levels innermost-parent first, each time closing the level above and prefixing the parent's
2639  // own content, so the result stays in document order. (A closer may digest: no stomach borrow is held.) A list in a
2640  // formula that cannot hold paragraphs closes over what precedes its first paragraph end; that and the rest are
2641  // carried past every level of the formula and follow it ([`split_off_vertical_material`]).
2642  let outermost_formula = levels.iter().position(|level| level.in_formula);
2643  let mut carried = Vec::new();
2644  let mut closed = 0;
2645  while let Some(SuspendedList {
2646    list: mut parent,
2647    closer,
2648    vertical,
2649    ..
2650  }) = levels.pop()
2651  {
2652    if outermost_formula.is_some_and(|outermost| levels.len() >= outermost) && !vertical {
2653      let mut rest = split_off_vertical_material(&mut acc);
2654      rest.append(&mut carried);
2655      carried = rest;
2656    }
2657    if let Some(close) = closer {
2658      acc = close(acc);
2659      closed += 1;
2660      if vertical {
2661        for item in &acc {
2662          if let DigestedData::Whatsit(whatsit) = item.data()
2663            && whatsit.borrow().get_property_bool(SALVAGED)
2664          {
2665            whatsit.borrow_mut().set_property(SALVAGED_VERTICAL, true);
2666          }
2667        }
2668      }
2669    }
2670    parent.append(&mut acc);
2671    if outermost_formula == Some(levels.len()) {
2672      parent.append(&mut carried);
2673    }
2674    acc = parent;
2675  }
2676  (acc, closed)
2677}
2678
2679/// The boxes a list in a formula hands on from its first box that ends the paragraph in TeX ([`ends_paragraph`]): a
2680/// formula holds no paragraphs (tex.web §1094: a `\par` in a box is ignored; §1047: in math it ends the formula), so
2681/// the list swallowed the text after an unfinished construct (2508.07005's `\xymatrix` in `align`, 2512.02946). A
2682/// salvaged math construct among them opens into what it digested ([`open_for_text`]).
2683fn split_off_vertical_material(boxes: &mut Vec<Digested>) -> Vec<Digested> {
2684  let Some(at) = boxes.iter().position(ends_paragraph) else {
2685    return Vec::new();
2686  };
2687  let mut rest = Vec::new();
2688  for item in boxes.split_off(at) {
2689    open_for_text(item, &mut rest);
2690  }
2691  rest
2692}
2693
2694/// Whether a box ends the paragraph: a non-noop `\lx@normal@par`, a display, or a group, unfinished part or text
2695/// between two math shifts holding one; a finished box's own `\par`s are its own (OD #251).
2696fn ends_paragraph(item: &Digested) -> bool {
2697  if let DigestedData::List(list) = item.data()
2698    && !is_math_material(item)
2699    && !is_vertical_list(&list.borrow())
2700    && list.borrow().boxes.iter().any(ends_paragraph)
2701  {
2702    return true;
2703  }
2704  if let DigestedData::Whatsit(whatsit) = item.data() {
2705    let whatsit = whatsit.borrow();
2706    // (the box is a paragraph end by what built it, as `is_list_tail_transparent` reads it)
2707    if whatsit.get_definition().get_cs_name() == "\\lx@normal@par" {
2708      return !whatsit.get_property_bool("noop");
2709    }
2710    let part = if is_math_shift_text(&whatsit) {
2711      BoxOps::get_body(&*whatsit).ok().flatten()
2712    } else if whatsit.get_property_bool(SALVAGED) && !keeps_its_paragraphs(&whatsit) {
2713      match whatsit.properties.get(SALVAGED_PART) {
2714        Some(Stored::String(part)) if *part == pin!("body") => {
2715          BoxOps::get_body(&*whatsit).ok().flatten()
2716        },
2717        Some(Stored::String(part)) if *part == pin!("argument") => {
2718          whatsit.args.last().cloned().flatten()
2719        },
2720        _ => None,
2721      }
2722    } else {
2723      None
2724    };
2725    if part.is_some_and(|part| match part.data() {
2726      DigestedData::List(list) => list.borrow().boxes.iter().any(ends_paragraph),
2727      _ => ends_paragraph(&part),
2728    }) {
2729      return true;
2730    }
2731  }
2732  holds_display(item)
2733}
2734
2735/// Whether a box is a display or holds one outside math (or in the text between two math shifts) and outside a
2736/// vertical list. A display interrupts the paragraph in TeX (tex.web §1145, `line_break(display_widow_penalty)`):
2737/// latex.ltx's displays and its and amsmath's display alignments are `$$` ([`is_display`]); a construct outside math
2738/// may wrap one (`\@@eqnarray`'s argument).
2739fn holds_display(item: &Digested) -> bool {
2740  match item.data() {
2741    DigestedData::Whatsit(whatsit) => {
2742      let whatsit = whatsit.borrow();
2743      is_display(&whatsit)
2744        || ((!whatsit.is_math() || is_math_shift_text(&whatsit))
2745          && !keeps_its_paragraphs(&whatsit)
2746          && (whatsit.args.iter().flatten().any(holds_display)
2747            || BoxOps::get_body(&*whatsit)
2748              .ok()
2749              .flatten()
2750              .is_some_and(|body| holds_display(&body))))
2751    },
2752    DigestedData::Alignment(alignment) => is_display_alignment(alignment),
2753    DigestedData::List(list) => {
2754      !is_math_material(item) && {
2755        let list = list.borrow();
2756        !is_vertical_list(&list) && list.boxes.iter().any(holds_display)
2757      }
2758    },
2759    _ => false,
2760  }
2761}
2762
2763/// Whether a list was digested in a vertical mode: its paragraphs are its own.
2764fn is_vertical_list(list: &List) -> bool {
2765  matches!(list.properties.get("mode"), Some(Stored::String(mode))
2766    if arena::with(*mode, |mode| mode.ends_with("vertical")))
2767}
2768
2769/// Whether a whatsit is a display: its definition begins display math (`{equation}`, `{displaymath}`), it began
2770/// display math outside math (`\lx@begin@display@math`, which begins its mode in its own code), or its alignment is a
2771/// display by itself ([`crate::alignment::ALIGNMENT_IS_DISPLAY`]: `eqnarray`, `align`). Not an inline math alignment
2772/// (`aligned`, `cases`, `array`).
2773fn is_display(whatsit: &crate::whatsit::Whatsit) -> bool {
2774  let display_math = pin!("display_math");
2775  whatsit
2776    .get_definition()
2777    .declared_mode()
2778    .and_then(|declared| declared.mode)
2779    .is_some_and(|mode| mode == display_math)
2780    || (!whatsit.is_math()
2781      && matches!(whatsit.properties.get("mode"), Some(Stored::String(mode)) if *mode == display_math))
2782    || matches!(whatsit.properties.get("alignment"), Some(Stored::Digested(alignment))
2783      if alignment.alignment_cell().is_some_and(is_display_alignment))
2784}
2785
2786fn is_display_alignment(alignment: &RefCell<crate::alignment::Alignment>) -> bool {
2787  matches!(
2788    alignment
2789      .borrow()
2790      .get_property(crate::alignment::ALIGNMENT_IS_DISPLAY)
2791      .as_deref(),
2792    Some(Stored::Bool(true))
2793  )
2794}
2795
2796/// Whether a whatsit is the text a `$` opened in math (`\lx@begin@inmath@text`, alias `$`), in a math alignment cell or
2797/// an `\lx@math@in@hbox` frame: restricted horizontal in TeX too, which ignores its `\par` (§1094), but the salvage reads
2798/// a stray `$` as the author's paragraphs, which follow the formula as text (2512.02946's items).
2799fn is_math_shift_text(whatsit: &crate::whatsit::Whatsit) -> bool {
2800  whatsit.get_definition().get_cs_name() == "\\lx@begin@inmath@text"
2801}
2802
2803/// Whether a whatsit's paragraphs are its own: it was digested in a vertical mode, as declared (a `\parbox`) or as the
2804/// salvage found its unfinished part ([`SALVAGED_VERTICAL`]).
2805fn keeps_its_paragraphs(whatsit: &crate::whatsit::Whatsit) -> bool {
2806  whatsit.get_property_bool(SALVAGED_VERTICAL)
2807    || whatsit
2808      .get_definition()
2809      .declared_mode()
2810      .and_then(|declared| declared.mode)
2811      .is_some_and(|mode| arena::with(mode, |mode| mode.ends_with("vertical")))
2812}
2813
2814/// A box handed on out of a formula into text: the text between two math shifts opens into its body, and a salvaged
2815/// math construct that ends the paragraph into every argument, in order, then its body (an `<ltx:XMText>` cannot be
2816/// built outside its formula); any other box as one the salvage closed does ([`unclose_salvaged`]). A finished math
2817/// construct never ends the paragraph: it stays whole.
2818fn open_for_text(item: Digested, into: &mut Vec<Digested>) {
2819  let parts: Option<Vec<Digested>> = match item.data() {
2820    DigestedData::Whatsit(whatsit) => {
2821      let whatsit = whatsit.borrow();
2822      (is_math_shift_text(&whatsit)
2823        || (is_math_material(&item)
2824          && whatsit.get_property_bool(SALVAGED)
2825          && ends_paragraph(&item)))
2826      .then(|| {
2827        whatsit
2828          .args
2829          .iter()
2830          .flatten()
2831          .cloned()
2832          .chain(BoxOps::get_body(&*whatsit).ok().flatten())
2833          .collect()
2834      })
2835    },
2836    _ => None,
2837  };
2838  match parts {
2839    Some(parts) => {
2840      for part in parts {
2841        match part.data() {
2842          DigestedData::List(list) => {
2843            let boxes = list.borrow().boxes.clone();
2844            for inner in boxes {
2845              open_for_text(inner, into);
2846            }
2847          },
2848          _ => open_for_text(part, into),
2849        }
2850      }
2851    },
2852    None => unclose_salvaged(item, into),
2853  }
2854}
2855
2856/// Drop every pending box list unclosed: a run abandoned for a rerun (`streaming_restart::release_before_rerun`).
2857pub fn drop_pending_box_lists() {
2858  let mut stomach = stomach_mut!();
2859  stomach.box_list.clear();
2860  stomach.localized_box_list.clear();
2861  stomach.paragraph_start = None;
2862}
2863
2864/// The depth at which a box list opened now is suspended: the mark a construct takes before it digests, for
2865/// [`close_pending_list_as`].
2866pub fn pending_list_mark() -> usize { stomach!().localized_box_list.len() }
2867
2868/// As a Fatal leaves the construct that took `mark` ([`pending_list_mark`]): how the box list it opened there, still
2869/// pending, closes if a salvage keeps it ([`salvage_pending_box_lists`]). A closer a construct inside it set on the same
2870/// list (one that opened none of its own) runs first. Nothing when no list is pending at `mark`.
2871pub fn close_pending_list_as(
2872  mark: usize,
2873  in_formula: bool,
2874  closer: impl FnOnce(Vec<Digested>) -> Vec<Digested> + 'static,
2875) {
2876  let mut stomach = stomach_mut!();
2877  if let Some(level) = stomach.localized_box_list.get_mut(mark) {
2878    level.in_formula |= in_formula;
2879    level.closer = Some(match level.closer.take() {
2880      Some(inner) => Box::new(move |boxes| closer(inner(boxes))),
2881      None => Box::new(closer),
2882    });
2883  }
2884}
2885
2886/// As a Fatal leaves a construct that took `mark` ([`pending_list_mark`]) and closes nothing of its own: the closers
2887/// set inside it go, so its text joins the enclosing list as it is (an `\item`'s label, digested in its properties: a
2888/// tag closed there landed in the item before it).
2889pub fn clear_pending_list_closers(mark: usize) {
2890  let mut stomach = stomach_mut!();
2891  for level in stomach.localized_box_list.iter_mut().skip(mark) {
2892    level.closer = None;
2893    level.in_formula = false;
2894  }
2895}
2896
2897/// Whether a box is math material: Perl's `isMath` (Box.pm:81 the box's mode, Whatsit.pm:51 its `isMath`), a list by
2898/// its mode (List.pm:39) or else by its boxes. A comment, a register value, keyvals or postponed tokens have no mode.
2899fn is_math_material(item: &Digested) -> bool {
2900  match item.data() {
2901    DigestedData::TBox(tbox) => tbox.borrow().is_math(),
2902    DigestedData::Whatsit(whatsit) => whatsit.borrow().is_math(),
2903    DigestedData::Alignment(alignment) => alignment.borrow().is_math(),
2904    DigestedData::List(list) => {
2905      let list = list.borrow();
2906      match (list.properties.get("mode"), &list.mode) {
2907        (Some(Stored::String(mode)), _) => arena::with(*mode, |mode| mode.ends_with("math")),
2908        (_, Some(mode)) => *mode == TexMode::Math,
2909        (_, None) => list.boxes.iter().all(is_math_material),
2910      }
2911    },
2912    _ => true,
2913  }
2914}
2915
2916/// The boxes of an unfinished math list a Fatal left pending that its construct does not own (OD #251): from the first
2917/// box that is not math material on, when the list leads with math. A math construct whose ender failed (a stray `$`, an
2918/// `\end` against an open group) takes in the text, displays and sections after it, where the formula drops them
2919/// (2203.12624, cond-mat9807003); they go back to the enclosing list, in order, as the salvage did before closers.
2920pub fn split_off_after_leading_math(boxes: &mut Vec<Digested>) -> Vec<Digested> {
2921  if !boxes.first().is_some_and(is_math_material) {
2922    return Vec::new();
2923  }
2924  let owned = boxes
2925    .iter()
2926    .position(|item| !is_math_material(item))
2927    .unwrap_or(boxes.len());
2928  let mut rest = Vec::new();
2929  for item in boxes.split_off(owned) {
2930    unclose_salvaged(item, &mut rest);
2931  }
2932  rest
2933}
2934
2935/// A construct the salvage closed among the boxes a math construct hands back opens into the part its closer took
2936/// ([`SALVAGED_PART`]; 2203.12624, 1903.08357); an alignment stays closed, and a math construct too, as a formula of its
2937/// own (`constructor::salvaged_formula`), unless it ends the paragraph (OD #251).
2938fn unclose_salvaged(item: Digested, into: &mut Vec<Digested>) {
2939  let mut formula = false;
2940  let part = match item.data() {
2941    DigestedData::Whatsit(whatsit) => {
2942      let whatsit = whatsit.borrow();
2943      formula = whatsit.get_property_bool(SALVAGED)
2944        && whatsit.is_math()
2945        && !is_math_shift_text(&whatsit)
2946        && !ends_paragraph(&item);
2947      if whatsit.get_property_bool(SALVAGED)
2948        && !whatsit.properties.contains_key("alignment")
2949        && !formula
2950      {
2951        match whatsit.properties.get(SALVAGED_PART) {
2952          Some(Stored::String(part)) if *part == pin!("body") => {
2953            BoxOps::get_body(&*whatsit).ok().flatten()
2954          },
2955          Some(Stored::String(part)) if *part == pin!("argument") => {
2956            whatsit.args.last().cloned().flatten()
2957          },
2958          _ => None,
2959        }
2960      } else {
2961        None
2962      }
2963    },
2964    _ => None,
2965  };
2966  match part {
2967    Some(part) => match part.data() {
2968      DigestedData::List(list) => {
2969        let boxes = list.borrow().boxes.clone();
2970        for inner in boxes {
2971          unclose_salvaged(inner, into);
2972        }
2973      },
2974      _ => unclose_salvaged(part, into),
2975    },
2976    None if formula => into.push(crate::definition::constructor::salvaged_formula(item)),
2977    None => into.push(item),
2978  }
2979}
2980
2981/// Empty the stack of tokens being invoked, after a recovered Fatal (Perl `hardYankProcessing`, Common/Error.pm:329
2982/// `$$stomach{token_stack} = []`, run for every Fatal). `invoke_token` pops its entry only on a normal exit, so every
2983/// `?` exit between the push and the pop leaves one: a `Stomach:Recursion` Fatal leaves the whole `MAXSTACK` of them,
2984/// and the next digestion after the recovery — the build's own, a frontmatter name read at insert time — failed its
2985/// first push with a second, ghost Fatal and stopped the build (2410.07647: 886 words to 96; 2105.02599). Called by the
2986/// recovery arms beside [`salvage_pending_box_lists`], after the Fatal is logged (the message lists the stack).
2987pub fn clear_token_stack() { stomach_mut!().token_stack.clear(); }
2988
2989/// Whether a token with a field provenance (`Token::prov`) is being invoked around the one on top of the stack, from
2990/// `depth` up, a box made of what it digests (its argument, an environment's body); a group's opening is none, though `{`
2991/// digests up to its `}` too.
2992pub fn field_token_encloses(depth: usize) -> bool {
2993  let stomach = stomach!();
2994  let stack = &stomach.token_stack;
2995  stack
2996    .get(depth..stack.len().saturating_sub(1))
2997    .is_some_and(|below| {
2998      below
2999        .iter()
3000        .any(|t| t.prov != 0 && t.get_catcode() != Catcode::BEGIN && !t.defined_as(&T_BEGIN!()))
3001    })
3002}
3003
3004/// Whether a token of field position `pos` is being invoked around the one on top of the stack, from `depth` up
3005/// ([`field_token_encloses`]): a call at that position still digesting what it reads (an environment's `\begin`, its body).
3006pub fn field_position_encloses(depth: usize, pos: u16) -> bool {
3007  let stomach = stomach!();
3008  let stack = &stomach.token_stack;
3009  stack
3010    .get(depth..stack.len().saturating_sub(1))
3011    .is_some_and(|below| {
3012      below
3013        .iter()
3014        .any(|t| t.prov != 0 && crate::token::field_prov_pos(t.prov) == pos)
3015    })
3016}
3017
3018/// The depth of the stack of tokens being invoked, for [`truncate_token_stack`] to put back.
3019pub fn token_stack_depth() -> usize { stomach!().token_stack.len() }
3020
3021/// Drop the tokens above `depth` ([`token_stack_depth`]) that failed invocations left on the stack of tokens being
3022/// invoked (see [`clear_token_stack`]).
3023pub fn truncate_token_stack(depth: usize) { stomach_mut!().token_stack.truncate(depth); }
3024
3025/// What a speculative digestion — one whose output is discarded and whose assignments its journal undoes (the
3026/// frontmatter's title-page runs, rehearsals and label reads) — must leave as it found it besides its assignments: the
3027/// stack of tokens being invoked and the active conditionals. Taken before the run, put back however it ends
3028/// ([`StomachMark::restore`]): the document never runs the run's tokens. A runaway Fatal the run raised and discarded
3029/// (a `Stomach:Recursion`) left the whole `MAXSTACK` of tokens on the stack, and the document's next digestion failed
3030/// its first push with a ghost Fatal of its own (2502.10606's `\thanks` inside a `\thanks`, all 8,054 words lost, as
3031/// [`clear_token_stack`]'s 2410.07647); a `\fi` of the run's closing a conditional the document opened before it left
3032/// that conditional closed for the document, whose own `\fi` then had none (2003.03814: CUP-JNL-DCE.cls:505 `\keywords`
3033/// leaves its `\ifx` open, `\fi` inside `\@keywords`, which `\printkeywords` balances; the title-page run's
3034/// `\printkeywords` closed it and the class's real `\maketitle` raised "Didn't expect a \fi"). Runs that read one text
3035/// in pieces share its conditionals as TeX reads it, in one pass: the observer rehearses an author list block by block,
3036/// a conditional opened in one block's run closed in the next's (2606.17718's `\IEEEauthorblockA{… \if… E-mail: …}
3037/// \else … \fi`), so its shadow takes the mark around the whole sequence and each rehearsal puts back only its token
3038/// stack ([`truncate_token_stack`]).
3039/// Put back on drop too, so every exit restores — a `?` that propagates a run's Fatal included (review rev135c S1) —,
3040/// except while a panic unwinds (the state may be borrowed).
3041pub struct StomachMark {
3042  saved: Option<(usize, StackedConditionals)>,
3043}
3044
3045/// The active conditionals, each with its state ([`if_stack_snapshot`]).
3046type StackedConditionals = Vec<(
3047  Rc<RefCell<crate::definition::conditional::IfFrame>>,
3048  crate::definition::conditional::IfFrame,
3049)>;
3050
3051impl StomachMark {
3052  /// The stack of tokens being invoked and the active conditionals as they are now.
3053  pub fn take() -> StomachMark {
3054    StomachMark {
3055      saved: Some((token_stack_depth(), if_stack_snapshot())),
3056    }
3057  }
3058
3059  /// Put both back as [`StomachMark::take`] found them: the tokens a failed invocation left on the stack dropped, the
3060  /// conditionals the run opened dropped and those it closed open again.
3061  pub fn restore(mut self) { self.put_back(); }
3062
3063  fn put_back(&mut self) {
3064    if let Some((tokens, conditionals)) = self.saved.take() {
3065      truncate_token_stack(tokens);
3066      restore_if_stack(conditionals);
3067    }
3068  }
3069}
3070
3071impl Drop for StomachMark {
3072  fn drop(&mut self) {
3073    if !std::thread::panicking() {
3074      self.put_back();
3075    }
3076  }
3077}
3078
3079/// What [`digest_speculatively`] read of its run.
3080pub struct SpeculativeDigest<T> {
3081  /// What `read` made of the digested boxes; `None` when the run raised an error it undid.
3082  pub read:   Option<T>,
3083  /// Errors the run raised (held, never reported when the run was undone).
3084  pub errors: usize,
3085  /// Whether the run's assignments were all undone (a journal that could not roll back keeps them, and its diagnostics).
3086  pub undone: bool,
3087}
3088
3089/// `tokens` digested in a run of their own, in a group, from a mouth of their own (an argument read past their end reads
3090/// nothing of the document's), the boxes read by `read`; nothing else of the run stays — its assignments undone, local
3091/// and global, its diagnostics held and discarded, the frames it left open popped, the tokens being invoked and the
3092/// conditionals put back ([`StomachMark`]), the field ledger too ([`crate::token::FieldLedgerScope`]). `None` when no
3093/// journal opens (journals do not nest); a resource Fatal, or an error a run that could not be undone raised, propagates
3094/// (Fatal stays Fatal). The frontmatter's label reads (queue_digest.rs
3095/// `speculative_label_ink`) and the reference forms of a label the document wrote (`\lx@reread@speculative`).
3096pub fn digest_speculatively<T>(
3097  tokens: Tokens,
3098  read: impl FnOnce(&Digested) -> T,
3099) -> Result<Option<SpeculativeDigest<T>>> {
3100  let Some(journal) = begin_assignment_journal() else {
3101    return Ok(None);
3102  };
3103  let _speculative = gullet::speculative_digestion();
3104  let hold = crate::util::logger::DiagnosticsHold::begin();
3105  let resource_fatal_before = resource_fatal_latched();
3106  let muted = SuppressLogOutputGuard::new(true);
3107  let depth = get_frame_depth();
3108  let boxes = box_lists_mark();
3109  let stomach_mark = StomachMark::take();
3110  // (the field ledger put back and the boxes it stamped unstamped, as the observer's rehearsal does: a `\usebox` in
3111  // the tokens hands back a register's box, which the run's serial would otherwise stay on)
3112  let ledger_scope = crate::token::FieldLedgerScope::begin();
3113  let result = gullet::reading_from_mouth(Mouth::default(), || -> Result<Digested> {
3114    bgroup();
3115    let digested = digest(tokens)?;
3116    egroup()?;
3117    Ok(digested)
3118  });
3119  let unwound = gullet::reading_from_mouth(Mouth::default(), || {
3120    new_local_box_list();
3121    while get_frame_depth() > depth {
3122      let before = get_frame_depth();
3123      let nobox = lookup_bool("groupNonBoxing");
3124      if pop_stack_frame(nobox).is_err() || get_frame_depth() >= before {
3125        break;
3126      }
3127    }
3128    expire_local_box_list();
3129    Ok(())
3130  });
3131  stomach_mark.restore();
3132  let read = result.as_ref().ok().map(read);
3133  drop(ledger_scope);
3134  drop(muted);
3135  let errors = hold.errors_raised();
3136  let undone = journal.rollback();
3137  if let Err(err) = result {
3138    if !undone || (resource_fatal_latched() && !resource_fatal_before && !unlatch_runaway_fatal()) {
3139      hold.commit();
3140      return Err(err);
3141    }
3142    hold.discard();
3143    unwound?;
3144    unwind_box_lists_to(boxes);
3145    return Ok(Some(SpeculativeDigest { read: None, errors, undone }));
3146  }
3147  if undone {
3148    hold.discard();
3149  } else {
3150    hold.commit();
3151  }
3152  unwound?;
3153  Ok(Some(SpeculativeDigest { read, errors, undone }))
3154}
3155
3156/// Stomach-level cycle guard: only once `box_list` has grown far past any
3157/// flushed-document size (a normal `box_list` is drained as paragraphs/boxes
3158/// complete and stays small) do we record the digest-push stream and look for
3159/// a short repeating window — a box-accumulation infinite loop. Cuts it off
3160/// with a clean Fatal long before the RSS soft cap. Caller must already hold
3161/// the stomach borrow and have appended past the activation size.
3162#[inline]
3163fn cycle_guard_record(st: &mut Stomach, d: &Digested, progress: usize) {
3164  // Once a fatal is pending, further detection work is pointless — the raise
3165  // happens at the NEXT `check_timeout` tick, which (since PR #249 review
3166  // P2-6) every digestion loop runs per iteration (`digest_next_body`,
3167  // `digest`, `raw_tex`), so the window between detection and raise is at
3168  // most one `invoke_token`. (Before that fix, a runaway confined to
3169  // `digest()` set the flag and the guards then self-disabled while the list
3170  // grew unbounded — the flag was never raised on that path.)
3171  if st.pending_cycle_fatal.is_none() {
3172    // Hard size backstop — platform-INDEPENDENT (the RSS soft cap in
3173    // `check_timeout` reads `/proc/self/statm` and is therefore Linux-only;
3174    // on macOS/Windows it is inactive). This bounds `box_list` everywhere and
3175    // also catches APERIODIC runaways the windowed cycle detector cannot
3176    // (boxes that vary per iteration, e.g. a `\@whilenum` loop with a
3177    // counter, or period > MAX_WINDOW). 40× the validated cycle-activation
3178    // size, far past any flushed-document list. Analogous to the gullet's
3179    // platform-independent `token_limit`.
3180    if let Some(cap) = box_count_cap()
3181      && st.box_list.len() > cap
3182    {
3183      st.pending_cycle_fatal = Some((
3184        ErrorCategory::MemoryBudget,
3185        box_count_runaway_message(st.box_list.len(), cap),
3186      ));
3187      return;
3188    }
3189    // Portable, BYTE-based memory guard. The count caps above are a proxy for
3190    // memory, but per-box weight varies several-fold (a bare text box vs a
3191    // deeply nested `\hbox{\raise…\hbox{…}}`), so a count calibrated for light
3192    // boxes lets a HEAVY-box runaway sail past it — only the Linux-only RSS cap
3193    // in `check_timeout` (4.5 GB) then catches it, late and non-portably.
3194    // Here we estimate the box list's actual heap footprint (by sampling, so
3195    // it stays O(1) amortised) and `Fatal` once it crosses a budget set BELOW
3196    // the RSS cap. This fires EARLIER than the external RSS guard AND works on
3197    // macOS/Windows where `/proc/self/statm` is unavailable. Driver:
3198    // math0102053 (plain-TeX `\@whiledim` line-drawing loop — Perl OOMs too;
3199    // ~1.87 M heavy line-segment boxes reached 4.5 GB RSS before the 2 M count
3200    // cap could fire).
3201    let len = st.box_list.len();
3202    if let Some(budget) = box_bytes_budget()
3203      && len >= BYTE_CHECK_ACTIVATE
3204      && len.is_multiple_of(BYTE_CHECK_EVERY)
3205    {
3206      let est = estimate_box_list_bytes(&st.box_list);
3207      if est > budget {
3208        st.pending_cycle_fatal = Some((
3209          ErrorCategory::MemoryBudget,
3210          box_bytes_runaway_message(est, len, budget),
3211        ));
3212        return;
3213      }
3214    }
3215    // A repeating box window is a loop only when the input behind it repeats
3216    // too: every point of a pgf `plot[smooth]` digests the same content-free
3217    // boxes (empty `\pgf@process` groups, a stray space;
3218    // pgflibraryplothandlers.code.tex:37-77) from coordinates of varying
3219    // length, so an 11,000-point plot is no cycle (tkz-grapheur-doc-en/-fr,
3220    // sweep #126), where ` {}\x` reads the same tokens each time. The box
3221    // window keeps its uniform-run exemption (a finite `\loop` printing one
3222    // letter). Excluding content-free boxes instead blinded the guard to that
3223    // runaway and to 2508.07407's cloud loop; mixing the span into the box
3224    // fingerprint defeated the uniform-run exemption. DIVERGENCES #326.
3225    //
3226    // A period is a loop only once it has held (OD #538): for `STOMACH_CYCLE_HOLD_STUCK` boxes when the spans repeat
3227    // with the register values read for them (a finite run of repeated data shorter than the hold ends first:
3228    // 2210.07754's pgfplots table repeats one row), for `STOMACH_CYCLE_HOLD_MOVING` tokens read when they repeat only
3229    // without them, and then only in a window of at most `STOMACH_CYCLE_MOVING_MAX_WINDOW` boxes, where 0.8.0 called it
3230    // a loop at once: a moving counter cannot tell a finite `\loop` from Paul Taylor's diagram macros'
3231    // `\advance\cdbfl1 \repeat` (0805.0686, 0808.1477, 1812.11491, math0609583), so a longer finite loop is left to run.
3232    // A line read by `\read`/`\readline` moves both spans, so a loop over a file's equal lines is no loop
3233    // (repro expansion-primitives/cycle_guard_read_loop_lines).
3234    let span = progress.saturating_sub(st.cycle_progress);
3235    st.cycle_spans
3236      .push(span, crate::cycle_guard::take_span_salt());
3237    st.cycle_spans_raw
3238      .push(span, crate::cycle_guard::take_input_salt());
3239    st.cycle_progress = progress;
3240    st.cycle_records += 1;
3241    let period = st.cycle_guard.push(d.cycle_fingerprint(), 0);
3242    if st.cycle_guard.checked() {
3243      let stuck = period.and_then(|w| st.cycle_spans.input_period(w));
3244      let moving = period
3245        .filter(|&w| w <= STOMACH_CYCLE_MOVING_MAX_WINDOW)
3246        .and_then(|w| stuck.or_else(|| st.cycle_spans_raw.input_period(w)));
3247      let now = st.cycle_records;
3248      let stuck_for = st.cycle_stuck.note(stuck.is_some(), now);
3249      let moving_for = st.cycle_moving.note(moving.is_some(), progress);
3250      let verdict = if stuck_for >= STOMACH_CYCLE_HOLD_STUCK {
3251        stuck.map(|p| (p, "", stuck_for, "boxes"))
3252      } else if moving_for >= STOMACH_CYCLE_HOLD_MOVING {
3253        moving.map(|p| {
3254          (
3255            p,
3256            " but for the register values read",
3257            moving_for,
3258            "tokens read",
3259          )
3260        })
3261      } else {
3262        None
3263      };
3264      if let (Some(period), Some((input_period, moving, held, unit))) = (period, verdict) {
3265        st.pending_cycle_fatal = Some((
3266          ErrorCategory::Recursion,
3267          s!(
3268            "Infinite digestion loop: a window of {} box(es) repeated {}+ times from \
3269             input that repeats every {} box(es){}, for {} {}, while the box list grew past {}",
3270            period,
3271            crate::cycle_guard::REPEAT,
3272            input_period,
3273            moving,
3274            held,
3275            unit,
3276            STOMACH_CYCLE_ACTIVATE
3277          ),
3278        ));
3279      }
3280    }
3281  }
3282}
3283
3284/// How to raise the memory ceiling the box caps ride: `--max-memory` only when that flag set the fuse
3285/// (`MEMORY_CEILING_MIB`); `cortex_worker`'s fuse is its `--max-rss-mb`, an embedder's the env (row R CORTEXRSS).
3286fn memory_ceiling_advice() -> &'static str {
3287  match MEMORY_CEILING_MIB.get() {
3288    Some(_) => "raise --max-memory, or --max-memory=0 to lift the ceiling",
3289    None => "the cap rides the cooperative memory fuse; raise that ceiling",
3290  }
3291}
3292
3293fn box_count_runaway_message(len: usize, cap: usize) -> String {
3294  format!(
3295    "Box-list runaway: {len} accumulated boxes exceeded the hard cap of {cap} (unbounded digestion with no \
3296     detectable cycle); {}",
3297    memory_ceiling_advice()
3298  )
3299}
3300
3301fn box_bytes_runaway_message(est: usize, len: usize, budget: usize) -> String {
3302  format!(
3303    "Box-list memory runaway: ~{} MB estimated across {len} boxes exceeded the {} MB budget (unbounded \
3304     accumulation); {}. NOTE: the estimate is a LOWER BOUND (each box is walked at most {} nodes deep), so true \
3305     RSS at this point is typically several times larger",
3306    est / 1_000_000,
3307    budget / 1_000_000,
3308    memory_ceiling_advice(),
3309    crate::digested::EB_BUDGET
3310  )
3311}
3312
3313/// Hard, platform-independent ceiling on `box_list` length — `None` when the
3314/// memory limit is disabled. A normal list is flushed continuously and stays
3315/// tiny; reaching this is an unbounded accumulation. The backstop for
3316/// very-LIGHT-box runaways, which the byte budget below can under-weigh.
3317///
3318/// **Rides `--max-memory`**, like every other memory ceiling: the resolved soft
3319/// cap divided by [`BYTES_PER_LIGHT_BOX`], which reproduces the historical fixed
3320/// 2 M at the stock `--max-memory=6144` (soft cap 4608 MiB), scales linearly
3321/// with the flag, and is `None` at `--max-memory=0`.
3322///
3323/// It used to be a hardcoded `const`, which made `--max-memory=0` a documented
3324/// lie: the binary prints "memory limiting disabled entirely" and then Fatal'd
3325/// on a memory ceiling anyway, with no flag able to raise it. Witness: a
3326/// ~10 000-page notes document (Nasser Abbasi, rc4 report 2026-07-28) died on
3327/// the byte budget below after 8 h at ~58 GB RSS having explicitly passed
3328/// `--max-memory=0`. Guard: `box_ceilings_follow_the_memory_knob`.
3329fn box_count_cap() -> Option<usize> {
3330  resolve_rss_cap().map(|cap| (cap / BYTES_PER_LIGHT_BOX) as usize)
3331}
3332
3333/// Calibration for [`box_count_cap`]: the per-box footprint of a *light* box,
3334/// chosen so the stock ceiling yields the validated 2 M-box cap.
3335const BYTES_PER_LIGHT_BOX: u64 = 2_416;
3336
3337/// Portable byte-budget for the accumulated `box_list` — `None` when the memory
3338/// limit is disabled. `estimate_bytes` counts each box's OWNED heavy data (the
3339/// `properties` HashMap, the `Tbox` `tokens` source-TeX vector, args/children
3340/// vectors + nested children). Works on macOS/Windows, where the `/proc` RSS
3341/// check is inactive and this is the ONLY memory guard for a heavy-box runaway.
3342///
3343/// **Rides `--max-memory`** (see [`box_count_cap`]): two thirds of the resolved
3344/// soft cap, i.e. 3.22 GB at the stock `--max-memory=6144` — the historical
3345/// fixed 3.2 GB — so on Linux it still `Fatal`s well before the RSS fuse, and
3346/// `None` at `--max-memory=0`.
3347///
3348/// **The estimate is a LOWER BOUND, not an RSS prediction.**
3349/// [`Digested::estimate_bytes`] walks at most `EB_BUDGET` (256) nodes per box,
3350/// so a deep document tree is undercounted by however much hangs below that
3351/// horizon — and the shortfall is content-dependent, not a constant. Measured:
3352/// a flat 600 k-paragraph synthetic crosses the 3.2 GB budget at 5.8 GB true RSS
3353/// (est ≈ 58 % of RSS), while Nasser's deeply-nested notes crossed the *same*
3354/// budget at ~58 GB (est ≈ 6 %). A ~10× spread — so do not read the budget as a
3355/// megabyte ceiling on the process. (The "tracks true RSS within ~10 %" claim
3356/// this doc used to carry held only for its calibration paper, math0102053: a
3357/// plain-TeX `\@whiledim` line-drawing loop whose ~1.87 M boxes are shallow.)
3358fn box_bytes_budget() -> Option<usize> { resolve_rss_cap().map(|cap| (cap / 3 * 2) as usize) }
3359/// Don't bother byte-sampling until the list is already well past the cycle
3360/// activation size (a normal list never gets here).
3361const BYTE_CHECK_ACTIVATE: usize = 200_000;
3362/// Re-estimate the box-list footprint every this-many boxes (amortises the
3363/// sampling cost to O(1) per push).
3364const BYTE_CHECK_EVERY: usize = 50_000;
3365/// Boxes sampled per byte estimate. Box weights are bimodal (light text
3366/// segments vs heavy nested structures), so a *dense* sample is needed to keep
3367/// the extrapolation from aliasing against the heavy-box stride.
3368const BYTE_SAMPLE_N: usize = 8192;
3369
3370/// Cost-bounded estimate of the heap bytes held by `list`, via even sampling +
3371/// extrapolation (each sampled box is itself depth-bounded — see
3372/// [`crate::digested::Digested::estimate_bytes`]). O(`BYTE_SAMPLE_N`) regardless
3373/// of list length. The sample is taken as contiguous *blocks* spread across the
3374/// list rather than a single large stride, which is far more robust to clustered
3375/// heavy boxes than evenly-strided point sampling.
3376fn estimate_box_list_bytes(list: &[Digested]) -> usize {
3377  let len = list.len();
3378  if len == 0 {
3379    return 0;
3380  }
3381  if len <= BYTE_SAMPLE_N {
3382    return list.iter().map(Digested::estimate_bytes).sum();
3383  }
3384  // 32 blocks of (BYTE_SAMPLE_N/32) contiguous boxes, evenly spaced — captures
3385  // local clustering of heavy boxes that point sampling misses.
3386  const BLOCKS: usize = 32;
3387  let block = (BYTE_SAMPLE_N / BLOCKS).max(1);
3388  let gap = len / BLOCKS;
3389  let mut sum = 0usize;
3390  let mut n = 0usize;
3391  for b in 0..BLOCKS {
3392    let start = b * gap;
3393    let end = (start + block).min(len);
3394    for d in &list[start..end] {
3395      sum += d.estimate_bytes();
3396      n += 1;
3397    }
3398  }
3399  // average-per-box × len; usize (64-bit) cannot overflow at realistic sizes.
3400  (sum / n.max(1)) * len
3401}
3402
3403pub fn extend_box_list<I>(arg: I)
3404where I: IntoIterator<Item = Digested> {
3405  let mut st = stomach_mut!();
3406  // Fast path (the overwhelming common case): box list still small — just
3407  // extend, no per-box fingerprinting.
3408  if st.box_list.len() <= STOMACH_CYCLE_ACTIVATE {
3409    st.box_list.extend(arg);
3410    return;
3411  }
3412  // Runaway territory: record each appended box into the cycle guard, with
3413  // the gullet's progress (read outside the stomach borrow).
3414  drop(st);
3415  let progress = gullet::token_progress();
3416  let mut st = stomach_mut!();
3417  for d in arg {
3418    cycle_guard_record(&mut st, &d, progress);
3419    st.box_list.push(d);
3420  }
3421}
3422pub fn push_box_list(arg: Digested) {
3423  let mut st = stomach_mut!();
3424  if st.box_list.len() > STOMACH_CYCLE_ACTIVATE {
3425    drop(st);
3426    let progress = gullet::token_progress();
3427    st = stomach_mut!();
3428    cycle_guard_record(&mut st, &arg, progress);
3429  }
3430  st.box_list.push(arg);
3431}
3432fn push_box_list_vec(args: Vec<Digested>) { extend_box_list(args) }
3433
3434/// Engage the stomach's box-list cycle guard only once the (normally
3435/// flushed-small) `box_list` has grown past this. A real document's list is
3436/// drained continuously; a runaway accumulates boxes without bound. Keeps the
3437/// guard inert for every ordinary conversion. (~50k boxes is already well past
3438/// any sane un-flushed list yet ~30× below the 4.5 GB OOM ceiling.)
3439const STOMACH_CYCLE_ACTIVATE: usize = 50_000;
3440/// How long, in boxes recorded, a box period from repeating input — register values and all — must hold before it
3441/// is a loop: as long again as the activation size, so a finite run of repeated data (2210.07754's pgfplots table,
3442/// a thousand equal rows of 13 boxes) ends first, and a loop that changes nothing still stops near 100k boxes.
3443const STOMACH_CYCLE_HOLD_STUCK: usize = STOMACH_CYCLE_ACTIVATE;
3444/// How long, in tokens read, a box period from input that repeats only register values aside must hold: a counter
3445/// moves, so the period cannot tell a finite `\loop` from a runaway (TeX itself stops an unshipped list only at main
3446/// memory, "TeX capacity exceeded"). Measured in work, not boxes: a finite loop printing letters reads ~3 tokens a box
3447/// (190k tokens for 66k boxes, `cycle_guard_counter_loop_boxes`), Taylor's `\reformatrow` ~150 and its cost grows
3448/// with the list (150k boxes took 100 s), so a box count long enough for the one kept the other past the deadline.
3449const STOMACH_CYCLE_HOLD_MOVING: usize = 2_000_000;
3450/// The longest box window the moving class looks at: 0.8.0's `cycle_guard::MAX_WINDOW`, where every such period was
3451/// a loop at once, so the hold only makes it later. Past it a finite counter loop of 12 boxes can run past both
3452/// the activation and the hold (30,000 × 12 boxes) and end. A finite 2-box counter loop still Fatals past about
3453/// 85,000 iterations (80,000 end clear), where 0.8.0 Fatalled it at activation, 25,000 (OD #538).
3454const STOMACH_CYCLE_MOVING_MAX_WINDOW: usize = 10;
3455pub fn pop_box_list() -> Option<Digested> { stomach_mut!().box_list.pop() }
3456
3457/// Items the list-tail primitives see through, being no node in TeX: a comment, a paragraph's closing `\par`
3458/// marker (`\lx@normal@par`) — `\lastbox` after a paragraph takes its line ([`end_graf`]), and `\unskip`,
3459/// `\lastskip` and the rest act on what came before the marker —, `\noindent`, which only starts a paragraph
3460/// (tex.web §1091), and the boundary marks of a list `\unvbox` spliced (`\lx@splice@begin`, `\lx@splice@end`;
3461/// tex_box.rs `vlist_of`): `\lastbox` after `\unvbox` takes the list's last box (§1080, §1110).
3462pub fn is_list_tail_transparent(item: &Digested) -> bool {
3463  match item.data() {
3464    DigestedData::Comment(_) => true,
3465    DigestedData::Whatsit(w) => w.try_borrow().is_ok_and(|w| {
3466      matches!(
3467        w.get_definition().get_cs_name().as_ref(),
3468        "\\lx@normal@par" | "\\noindent" | "\\lx@splice@begin" | "\\lx@splice@end"
3469      )
3470    }),
3471    _ => false,
3472  }
3473}
3474
3475/// A space character, glue (`isSkip`: `\hskip`, `\quad`) or a kern (`isKern`), not an `isSpace` box like `\phantom`'s
3476/// (math_common.pool.ltxml:645-648): an item with no height or depth of its own in a line.
3477fn adds_no_line_material(item: &Digested) -> bool {
3478  item.get_property_bool("isSpace")
3479    && (matches!(item.data(), DigestedData::TBox(_))
3480      || item.get_property_bool("isSkip")
3481      || item.get_property_bool("isKern"))
3482}
3483
3484/// The lowest index of the current list the list-tail primitives may reach: in a paragraph, only what it added
3485/// (tex.web §1080, §1105: TeX's list holds only the paragraph's own nodes, `paragraph_start`).
3486fn own_list_floor(stomach: &Stomach) -> usize {
3487  let in_paragraph = lookup_mode() == crate::pin!("horizontal");
3488  match stomach.paragraph_start {
3489    Some(start) if in_paragraph => start.index.min(stomach.box_list.len()),
3490    _ => 0,
3491  }
3492}
3493
3494/// The index of the last item the list-tail primitives act on: past transparent items
3495/// ([`is_list_tail_transparent`]), never below [`own_list_floor`].
3496fn last_own_index(stomach: &Stomach) -> Option<usize> {
3497  let floor = own_list_floor(stomach);
3498  stomach.box_list[floor..]
3499    .iter()
3500    .rposition(|item| !is_list_tail_transparent(item))
3501    .map(|i| floor + i)
3502}
3503
3504/// The last item of the current list for `\lastbox`, `\unskip`, `\unkern` and `\unpenalty` (tex.web §1080, §1105
3505/// `delete_last`), left in place: they look first and remove it only when it is theirs, so nothing they pass over
3506/// moves. reledmac's `\autopar` does `\everypar{\setbox0=\lastbox …}` to drop the indent box TeX puts there;
3507/// reaching past the paragraph's start took the previous paragraph's line instead (reledmac.sty:2179; reledmac and
3508/// eledmac 2-line_numbers_in_header lost 1,448 of ~1,600 words; KNOWN_PERL_ERRORS #401), and `\everypar{\unskip}`
3509/// removed the `\vskip` before the paragraph.
3510pub fn peek_own_box() -> Option<Digested> {
3511  let stomach = stomach!();
3512  last_own_index(&stomach).map(|i| stomach.box_list[i].clone())
3513}
3514
3515/// Remove the item [`peek_own_box`] returns; transparent items after it stay where they are.
3516pub fn pop_own_box() -> Option<Digested> {
3517  let mut stomach = stomach_mut!();
3518  let index = last_own_index(&stomach)?;
3519  Some(stomach.box_list.remove(index))
3520}
3521
3522/// The current list's own items, as [`pop_own_box`] sees them: in a paragraph only what the paragraph added. What
3523/// `\lastpenalty`, `\lastkern` and `\lastskip` read (tex.web §424, the tail of the current list) must be what
3524/// `\unpenalty`, `\unkern` and `\unskip` can remove: reading a vertical penalty from before the paragraph that
3525/// `\unpenalty` could not remove looped diagram.sty's `\ifnum\lastpenalty…\unpenalty` (2605.02221, 2605.25087).
3526/// The readers skip [`is_list_tail_transparent`] items.
3527pub fn with_own_box_list<R, FnR>(caller: FnR) -> R
3528where FnR: FnOnce(&[Digested]) -> R {
3529  let stomach = stomach!();
3530  let floor = own_list_floor(&stomach);
3531  caller(&stomach.box_list[floor..])
3532}
3533
3534/// `\lastbox` at the start of a paragraph begun by a letter or `\leavevmode` takes its indent box (tex.web §1080),
3535/// which LaTeXML does not list: the paragraph is then without one, and null if nothing follows (§1096). True when
3536/// there was one to take.
3537pub fn take_implicit_indent() -> bool {
3538  let in_paragraph = lookup_mode() == crate::pin!("horizontal");
3539  let mut stomach = stomach_mut!();
3540  let floor = own_list_floor(&stomach);
3541  let own_empty = stomach.box_list[floor..]
3542    .iter()
3543    .all(is_list_tail_transparent);
3544  match stomach.paragraph_start.as_mut() {
3545    Some(start) if in_paragraph && own_empty && start.implicit_indent => {
3546      start.implicit_indent = false;
3547      true
3548    },
3549    _ => false,
3550  }
3551}
3552
3553/// Note that a paragraph begins here (tex.web §1091 `new_graf`): see [`ParagraphStart`].
3554fn mark_paragraph_start(implicit_indent: bool) {
3555  let mut stomach = stomach_mut!();
3556  let index = stomach.box_list.len();
3557  stomach.paragraph_start = Some(ParagraphStart {
3558    index,
3559    implicit_indent,
3560    in_group: false,
3561  });
3562}
3563pub fn with_box_list<R, FnR>(caller: FnR) -> R
3564where FnR: FnOnce(&[Digested]) -> R {
3565  let stomach = stomach!();
3566  let list = &stomach.box_list;
3567  caller(list)
3568}
3569/// The box lists being built, innermost first: the current `box_list`, then each outer one suspended on
3570/// `localized_box_list` (by `new_local_box_list`), outward. A binding asking what an enclosing construct has digested so
3571/// far (sect11.rs `holds_nothing_yet`) reads them from where it is, inside an environment's or a box's own list.
3572pub fn with_box_list_levels<R, FnR>(caller: FnR) -> R
3573where FnR: FnOnce(&[&[Digested]]) -> R {
3574  let stomach = stomach!();
3575  let mut levels: Vec<&[Digested]> = Vec::with_capacity(stomach.localized_box_list.len() + 1);
3576  levels.push(&stomach.box_list);
3577  levels.extend(
3578    stomach
3579      .localized_box_list
3580      .iter()
3581      .rev()
3582      .map(|level| level.list.as_slice()),
3583  );
3584  caller(&levels)
3585}
3586pub fn with_box_list_mut<R, FnR>(caller: FnR) -> R
3587where FnR: FnOnce(&mut [Digested]) -> R {
3588  let mut stomach = stomach_mut!();
3589  let list = &mut stomach.box_list;
3590  caller(list)
3591}
3592/// Access to the current box_list as a `&mut Vec` — allows push/pop operations.
3593pub fn with_box_list_mut_vec<R, FnR>(caller: FnR) -> R
3594where FnR: FnOnce(&mut Vec<Digested>) -> R {
3595  let mut stomach = stomach_mut!();
3596  caller(&mut stomach.box_list)
3597}
3598
3599// **********************************************************************
3600// Deferred printing (OXIDIZED_DESIGN_DIVERGENCES #738)
3601// **********************************************************************
3602
3603/// Material TeX writes out raw for a later run to print — an `\index` phrase (latex.ltx:17713-17726 `\@sanitize` and
3604/// `\protected@write` to the `.idx`), a `\nomenclature` entry (nomencl.sty:208-219, the `.nlo`) — is typeset only when
3605/// the document prints that list (`\printindex`, `\printnomenclature`); without one it is never typeset, and its
3606/// errors are never TeX's. `defer_print` keeps the entry's tokens (already expanded as the write expands them) under a
3607/// fresh id and returns that id for the anchor (`\lx@deferred@print{id}`, which marks the entry's place);
3608/// [`resolve_deferred_prints`] digests them when the list is printed, and the anchor absorbs what was digested.
3609/// Witnesses 1112.3972, 2506.02168 (user ruling 2026-10-18).
3610pub fn defer_print(list: &str, tokens: Tokens) -> i64 {
3611  let id = lookup_int("lx@deferred@print@count") + 1;
3612  assign_value(
3613    "lx@deferred@print@count",
3614    Stored::Int(id),
3615    Some(Scope::Global),
3616  );
3617  let unresolved = lookup_int("lx@deferred@print@unresolved") + 1;
3618  assign_value(
3619    "lx@deferred@print@unresolved",
3620    Stored::Int(unresolved),
3621    Some(Scope::Global),
3622  );
3623  assign_value(
3624    &s!("lx@deferred@print@tokens@{id}"),
3625    Stored::Tokens(tokens),
3626    Some(Scope::Global),
3627  );
3628  assign_value(
3629    &s!("lx@deferred@print@list@{id}"),
3630    Stored::String(arena::pin(list)),
3631    Some(Scope::Global),
3632  );
3633  let pending = lookup_int(&s!("lx@deferred@print@pending@{list}")) + 1;
3634  assign_value(
3635    &s!("lx@deferred@print@pending@{list}"),
3636    Stored::Int(pending),
3637    Some(Scope::Global),
3638  );
3639  id
3640}
3641
3642/// Whether the list `list` has been printed: an entry made after that is typeset at once (TeX's `.ind` of the earlier
3643/// run holds every entry of the document, the later ones too).
3644pub fn deferred_list_is_printed(list: &str) -> bool {
3645  lookup_bool(&s!("lx@deferred@print@printed@{list}"))
3646}
3647
3648/// What the deferred entry `id` digested to, once its list was printed (`None` while it is not).
3649pub fn deferred_print_content(id: &str) -> Option<Digested> {
3650  match lookup_value(&s!("lx@deferred@print@content@{id}")) {
3651    Some(Stored::Digested(content)) => Some(content),
3652    _ => None,
3653  }
3654}
3655
3656/// Print the list `list`: digest every entry deferred for it, in document order, and mark it printed. With `None`, digest
3657/// every deferred entry of every list without marking any printed — the streaming yield's fallback (an anchor is built
3658/// and spilled with the fragment it is in, before a later `\printindex` could fill it), where the entries are typeset
3659/// as Perl typesets them, at once.
3660pub fn resolve_deferred_prints(list: Option<&str>) -> Result<()> {
3661  if let Some(list) = list {
3662    assign_value(
3663      &s!("lx@deferred@print@printed@{list}"),
3664      Stored::Bool(true),
3665      Some(Scope::Global),
3666    );
3667  }
3668  if lookup_int("lx@deferred@print@unresolved") <= 0 {
3669    return Ok(());
3670  }
3671  // A list with nothing pending has nothing to scan for: a `\cite` of a key whose `\bibitem` comes later (70c's
3672  // `b@<key>` lists), with a document's unprinted `\index` entries pending, would otherwise rescan them all, once per
3673  // cite (40k entries and 5k cites, release build: 20.9 s → 0.99 s).
3674  if let Some(list) = list
3675    && lookup_int(&s!("lx@deferred@print@pending@{list}")) <= 0
3676  {
3677    return Ok(());
3678  }
3679  // The entries below the low-water mark are all resolved: a scan starts at the first one still pending, so the
3680  // streaming yields, which resolve every list, scan each entry once; one list's scan stops at its last entry.
3681  let count = lookup_int("lx@deferred@print@count");
3682  let low = lookup_int("lx@deferred@print@low").max(1);
3683  let mut first_pending: Option<i64> = None;
3684  let mut scanned_to = count;
3685  for id in low..=count {
3686    let key = s!("lx@deferred@print@tokens@{id}");
3687    let Some(Stored::Tokens(tokens)) = lookup_value(&key) else {
3688      continue;
3689    };
3690    let entry_list = lookup_string(&s!("lx@deferred@print@list@{id}"));
3691    if let Some(list) = list
3692      && entry_list != list
3693    {
3694      first_pending.get_or_insert(id);
3695      continue;
3696    }
3697    assign_value(&key, Stored::None, Some(Scope::Global));
3698    let unresolved = lookup_int("lx@deferred@print@unresolved") - 1;
3699    assign_value(
3700      "lx@deferred@print@unresolved",
3701      Stored::Int(unresolved),
3702      Some(Scope::Global),
3703    );
3704    let pending_key = s!("lx@deferred@print@pending@{entry_list}");
3705    let pending = lookup_int(&pending_key) - 1;
3706    assign_value(&pending_key, Stored::Int(pending), Some(Scope::Global));
3707    let content = digest(tokens)?;
3708    assign_value(
3709      &s!("lx@deferred@print@content@{id}"),
3710      Stored::Digested(content),
3711      Some(Scope::Global),
3712    );
3713    if list.is_some() && pending <= 0 {
3714      scanned_to = id;
3715      break;
3716    }
3717  }
3718  assign_value(
3719    "lx@deferred@print@low",
3720    Stored::Int(first_pending.unwrap_or(scanned_to + 1)),
3721    Some(Scope::Global),
3722  );
3723  Ok(())
3724}
3725
3726// **********************************************************************
3727// Digestion
3728// **********************************************************************
3729
3730/// Digest a list of tokens independent from any current Gullet.
3731/// Typically used to digest arguments to primitives or constructors.
3732/// Returns a List containing the digested material.
3733pub fn digest<T: Into<Tokens>>(tokens: T) -> Result<Digested> {
3734  digest_tokens::<true>(tokens.into())
3735}
3736
3737/// [`digest`] a hook's code as the plain input it is in TeX: a group it closes that was opened before it (an end
3738/// hook's `\egroup` closing its begin hook's `\bgroup`) does not end the digestion; the rest of the code is digested
3739/// in the enclosing group (Perl's `digest` stops there, Stomach.pm:150; OD #1248).
3740pub fn digest_hook_code<T: Into<Tokens>>(tokens: T) -> Result<Digested> {
3741  digest_tokens::<false>(tokens.into())
3742}
3743
3744fn digest_tokens<const STOP_AT_OUTER_CLOSE: bool>(tokens: Tokens) -> Result<Digested> {
3745  if tokens.is_empty() {
3746    return Ok(Digested::default());
3747  }
3748  // Digestion is no part of an enclosing number scan (calc's `\widthof`
3749  // inside `\makebox[…]`'s width; see `gullet::NumberScan::suspend`).
3750  let _outside_scan = gullet::NumberScan::suspend();
3751  gullet::reading_from_mouth(Mouth::default(), || {
3752    gullet::unread(tokens);
3753    clear_prefixes(); // prefixes shouldn't apply here.
3754    let _arg_scope = ArgDigestScope::enter_argument();
3755    let mode = if lookup_bool_sym(crate::pin!("IN_MATH")) {
3756      TexMode::Math
3757    } else {
3758      TexMode::Text
3759    };
3760    let mut initdepth = stomach!().boxing.len();
3761    new_local_box_list();
3762    while let Some(token) = match gullet::get_pending_comment() {
3763      Some(comment) => Some(comment),
3764      None => gullet::read_x_token(Some(true), false, None)?,
3765    } {
3766      // Raise any pending stomach-guard fatal + deadline/RSS checks. This
3767      // loop is a digestion path of its own — without a tick here, a runaway
3768      // confined to constructor-argument digestion set `pending_cycle_fatal`
3769      // at detection but nothing ever RAISED it (check_timeout's only call
3770      // site was digest_next_body), and the RSS soft cap / wall-clock
3771      // deadline were equally dead on this path. PR #249 review P2-6.
3772      check_timeout()?;
3773      if delete_extra_brace(&token)? {
3774        continue;
3775      }
3776      // Done if we run out of tokens
3777      let invoked = invoke_token(&token)?;
3778      extend_box_list(invoked);
3779
3780      let now = stomach!().boxing.len();
3781      if initdepth > now {
3782        // if we've closed the initial mode.
3783        if STOP_AT_OUTER_CLOSE {
3784          break;
3785        }
3786        initdepth = now;
3787      }
3788    }
3789
3790    let mut digested_list = List::new(expire_local_box_list());
3791    digested_list.mode = Some(mode);
3792    digested_list.into()
3793  })
3794}
3795
3796/// Whether the open until-body's own loop reads the next token: no group of the body is open inside it (an
3797/// unbalanced `\abstract{` has its `{` open), so its terminal ends it without closing one ([`until_terminal_inside_group`]).
3798pub fn until_body_at_own_level() -> bool {
3799  match lookup_value("lx@until@depth") {
3800    Some(Stored::Number(n)) => stomach!().boxing.len() <= n.0 as usize,
3801    _ => false,
3802  }
3803}
3804
3805/// The environment begun with `\begin` that the open until-body is read in — LaTeX's `\@currenvir`, whose end
3806/// `\@checkend` checks — or `None` when the body is a begin code called as a command: a bare begin code
3807/// (`lx@env@bare@end`), or one whose innermost recorded environment is `{document}` (mn2e `\keywords{…}`,
3808/// mn2e.cls:993-1003, opens its body in the document's own environment, which LaTeX never checks against it). The
3809/// innermost frame that records an environment names it: `\begin`'s `current_environment`, or `lx@until@begun`, which
3810/// the kernel's `\begin{abstract}` (no environment frame of its own) leaves in its body's frame.
3811pub fn begun_environment() -> Option<String> {
3812  if lookup_value("lx@env@bare@end").is_some() || !until_body_at_own_level() {
3813    return None;
3814  }
3815  for frame in 0..=get_frame_depth() {
3816    if is_value_bound("lx@until@begun", Some(frame)) {
3817      return Some(lookup_string("lx@until@begun"));
3818    }
3819    if is_value_bound("current_environment", Some(frame)) {
3820      let open = lookup_string("current_environment");
3821      return (!open.is_empty() && open != "document").then_some(open);
3822    }
3823  }
3824  None
3825}
3826
3827/// Return the digested `List` after reading and digesting a body from the its Gullet.
3828/// The body extends until the current level of boxing or environment is closed.
3829/// A bounded body's terminal token (`\lx@add@frontmatter@until`'s
3830/// `\lx@end@abstract`…) invoked INSIDE a group opened within that body — a
3831/// `{` group is a nested digest body here (and in Perl, TeX_Box.pool.ltxml:
3832/// 30-41), so the body's own loop never sees the token. LaTeX's rule for an
3833/// environment end met inside an open group is `\@checkend`'s "\begin{X}
3834/// ended by \end{Y}" (latex.ltx:15394) with the groups closed by the error
3835/// recovery; here the groups above the body are abandoned ([`abandon_stack_frame`]:
3836/// popped, `\aftergroup` discarded) with a Warning, and the body's
3837/// loop is told its terminal arrived (`lx@until@terminal@hit`). Returns true
3838/// when it acted. Witness: screenplay-pkg.tex:67 `\abstract{…\section` —
3839/// the section then lands at document level, as the brace-less form does.
3840pub fn until_terminal_inside_group(terminal: &Token) -> Result<bool> {
3841  if lookup_token("lx@until@terminal").as_ref() != Some(terminal) {
3842    return Ok(false);
3843  }
3844  let depth = match lookup_value("lx@until@depth") {
3845    Some(Stored::Number(n)) => n.0 as usize,
3846    _ => return Ok(false),
3847  };
3848  if stomach!().boxing.len() <= depth {
3849    return Ok(false); // the body's own loop will see it
3850  }
3851  let mut popped = 0usize;
3852  while !is_value_bound("lx@until@terminal", Some(0)) && get_frame_depth() > 0 && popped < 64 {
3853    abandon_stack_frame()?;
3854    popped += 1;
3855  }
3856  Warn!(
3857    "unexpected",
3858    terminal,
3859    s!(
3860      "{} inside {popped} open group(s): closing them (LaTeX: environment ended inside a group)",
3861      terminal.stringify()
3862    )
3863  );
3864  assign_value(
3865    "lx@until@terminal@hit",
3866    Stored::Token(*terminal),
3867    Some(Scope::Global),
3868  );
3869  Ok(true)
3870}
3871
3872thread_local! {
3873  /// How many stack frames [`abandon_stack_frame`] has popped on this thread: a body whose
3874  /// boxing level was popped by an abandonment ends as at end of input (`digest_next_body`).
3875  static ABANDONED_FRAMES: Cell<u64> = const { Cell::new(0) };
3876}
3877
3878/// Abandons the current group, tex.web §1335 `final_cleanup` style: the stack frame (and its
3879/// `boxing` entry, unless the group is non-boxing) is popped and its `\aftergroup` list is
3880/// discarded, never run. Used where open groups are unwound wholesale — `\end{document}`
3881/// (`\lx@finalize@document`, Perl latex_constructs.pool.ltxml:353-386) and a bounded body's
3882/// terminal met inside a group ([`until_terminal_inside_group`]).
3883///
3884/// Every body digesting inside an abandoned group then ends the way Perl's does: Perl pops only
3885/// the undo frame (`$STATE->popFrame`, latex_constructs.pool.ltxml:373) and flushes the gullet
3886/// (:386), so each enclosing `digestUntil` reads END OF INPUT (Stomach.pm:111) and pushes a dummy
3887/// trailer (Stomach.pm:130) — every body keeps its boxes. Here the `boxing` entry goes too (an
3888/// unbalanced `\abstract{…` otherwise leaves a bounded primitive closing the document frame,
3889/// screenplay-pkg.tex:67), so the bodies stop on the depth check instead; `digest_next_body`
3890/// counts that exit as running out, not as a close whose last box is the closer. Without it the
3891/// trailer split took each enclosing body's LAST REAL BOX: two nested environments open at
3892/// `\end{document}` lost the inner one whole (`\begin{quote}Q1. \begin{quote}Q2. After.`), and a
3893/// list or math left open by an upstream defect lost the rest of the document. Witnesses: the
3894/// powerdotDE manual (recall 26% → 98%), arXiv 1902.00853 (27,484 words), 2110.01778.
3895///
3896/// The frame's beforeAfterGroup hooks still run, and what they queue on `\aftergroup` is
3897/// discarded with the rest (setspace's `\lx@setspace@rearm`). This is a LaTeXML recovery
3898/// modelled on §1335 (groups left open, `\aftergroup` never run); TeX itself recovers a closer
3899/// met inside a group by `off_save`, whose inserted closer runs `unsave` and so does run
3900/// `\aftergroup`. Guard: `perfect_kernel_batch64zf::abandoned_group_discards_hook_queued_aftergroup`.
3901pub fn abandon_stack_frame() -> Result<()> {
3902  let nonboxing = lookup_bool_sym(crate::pin!("groupNonBoxing"));
3903  pop_stack_frame_with(nonboxing, false)?;
3904  ABANDONED_FRAMES.with(|count| count.set(count.get() + 1));
3905  Ok(())
3906}
3907
3908fn abandoned_frame_count() -> u64 { ABANDONED_FRAMES.with(Cell::get) }
3909
3910/// Runs `digestion` in a group of its own, as a text built ahead of its use and not read from the document: a tag a
3911/// reference prints (latexml_engine tags_refnums.rs `\lx@tag@intags@held`), a form cleveref typesets only at a reference
3912/// (latexml_package cleveref_sty.rs `\lx@cref@docformat`), whose text need not
3913/// close what it opens — the derived `\Cref` format `\MakeUppercase#2\color{blue}…`, whose `\MakeUppercase` takes
3914/// `\color` alone (2008.12750, 2604.24399). Whatever the digestion leaves is undone, so the document reads on as it
3915/// was: the groups it left open are popped as [`abandon_stack_frame`] pops one, their `\aftergroup` discarded, but not
3916/// counted as an abandonment, and the group is closed; the alignment brace count (tex.web's `align_state`, §789) is put
3917/// back, as the `{` such a text scanned is not the document's — left counted, a figure's tabular of two captioned
3918/// minipages read its next `&` as text and moved the following cell into the row above ("Missing } inserted",
3919/// "Extra alignment tab"; guards `perfect_kernel_batch78j::cleveref_format_form_keeps_the_alignment_brace_count`,
3920/// `::cleveref_format_form_keeps_an_alignment_row_end`). Returns the digestion's result and the group balance: the
3921/// groups it left open, or, negative, how many it closed that it did not open.
3922pub fn digest_in_own_group<T>(digestion: impl FnOnce() -> Result<T>) -> Result<(Result<T>, isize)> {
3923  let depth = get_frame_depth();
3924  let align = mark_align_group_count();
3925  bgroup();
3926  let value = digestion();
3927  let after = get_frame_depth();
3928  let balance = after as isize - (depth + 1) as isize;
3929  let closed = if after > depth {
3930    unwind_stack_frames_to(depth + 1).and_then(|_| egroup())
3931  } else {
3932    Ok(())
3933  };
3934  restore_align_group_count(align);
3935  closed?;
3936  Ok((value, balance))
3937}
3938
3939/// Pops the groups above frame depth `depth` ([`digest_in_own_group`]). Returns how many it popped.
3940fn unwind_stack_frames_to(depth: usize) -> Result<usize> {
3941  let mut popped = 0;
3942  while get_frame_depth() > depth {
3943    let before = get_frame_depth();
3944    let nonboxing = lookup_bool_sym(crate::pin!("groupNonBoxing"));
3945    pop_stack_frame_with(nonboxing, false)?;
3946    popped += 1;
3947    if get_frame_depth() >= before {
3948      break;
3949    }
3950  }
3951  Ok(popped)
3952}
3953
3954thread_local! {
3955  /// How many times the document ended inside open groups on this thread ([`end_inside_groups`]).
3956  static ENDS_INSIDE_GROUPS: Cell<u64> = const { Cell::new(0) };
3957}
3958
3959/// The whatsit property of a construct a Fatal left unfinished, made by the salvage with what it had digested
3960/// ([`close_pending_list_as`], OD #251): a binding whose element the HTML does not show counts the words it keeps there.
3961/// The list a constructor's last argument closed carries it too, for the constructor's properties (OD #1185).
3962pub const SALVAGED: &str = "lx@salvaged";
3963/// Which part of a [`SALVAGED`] whatsit its closer filled with the boxes digested before the Fatal: `"argument"` (its
3964/// last) or `"body"`; none where its after-digest code failed (its arguments are whole).
3965pub const SALVAGED_PART: &str = "lx@salvaged@part";
3966/// A [`SALVAGED`] whatsit whose part was digested in a vertical mode: its paragraphs are its own ([`ends_paragraph`]).
3967const SALVAGED_VERTICAL: &str = "lx@salvaged@vertical";
3968
3969/// The whatsit property of a construct the document ended inside of: `\end{document}` came while
3970/// its arguments or body were still being digested and abandoned their groups (tex.web §1335), so
3971/// it never ended — whatever came after the defect that left it open (a section, a bibliography)
3972/// is inside it. `Constructor::digest_to_whatsit` sets it ([`ends_inside_groups`] moved during the
3973/// digestion); the document lets every element such a whatsit opens auto-close
3974/// (`Document::open_element`), Perl's per-node `_autoclose` (Document.pm `canAutoClose`), so that
3975/// structure closes it instead of being held inside as `malformed:*` (1611.05714, 1101.1959,
3976/// physics0505113, math9805003). OXIDIZED_DESIGN #542.
3977pub const UNENDED: &str = "lx@unended";
3978
3979/// Records that the document ended inside open groups (`\lx@finalize@document`): every
3980/// construct still digesting is [`UNENDED`].
3981pub fn end_inside_groups() { ENDS_INSIDE_GROUPS.with(|count| count.set(count.get() + 1)); }
3982
3983/// How many times the document ended inside open groups on this thread, for [`UNENDED`].
3984pub fn ends_inside_groups() -> u64 { ENDS_INSIDE_GROUPS.with(Cell::get) }
3985
3986/// The closers a frame owes: `off_save` (tex.web §1064-1065, latexml_engine tex_math.rs `left_right_group`) inserted
3987/// a `}` or `\endgroup` for a `\right`/`\middle` that met this group, so the author's own closer, when it comes, has
3988/// already been used. The debt is a frame value; at every pop it moves to the frame then innermost
3989/// ([`pop_stack_frame`]), so it follows the stack to wherever that closer arrives. OXIDIZED_DESIGN #530.
3990pub const OWED_BRACES: &str = "lx@owed@braces";
3991/// Bound in an alignment cell's frame while its template's `{` (`$\displaystyle{##}$`) is open — latexml_engine
3992/// tex_box.rs `\lx@template@bgroup`/`\lx@template@egroup`; a `}` that would close the frame closes it
3993/// ([`close_template_brace`]).
3994pub const TEMPLATE_BRACE_OPEN: &str = "lx@template@brace@open";
3995
3996/// A `}` met at the frame of an alignment cell whose template's `{` is open (`$\displaystyle{##}$`, [`TEMPLATE_BRACE_OPEN`]):
3997/// it closes that `{` (tex.web §789, the u-part's brace), the frame stays — `G_t(h)=}\det…` in an eqnarray cell
3998/// (2207.06932, 1912.10594). Whether it did.
3999pub fn close_template_brace() -> bool {
4000  if is_value_bound(TEMPLATE_BRACE_OPEN, Some(0)) && lookup_bool(TEMPLATE_BRACE_OPEN) {
4001    assign_value(TEMPLATE_BRACE_OPEN, false, None);
4002    true
4003  } else {
4004    false
4005  }
4006}
4007/// Whether `token`, read by the digestion loop, is a `}` — or a control sequence `\let` to one, `\egroup` — that
4008/// closes the template's `{` ([`close_template_brace`]); TeX makes no difference between them (tex.web §1067
4009/// `right_brace` is the command, whatever the token), so `$\displaystyle{a\egroup}$` closes the template's `{` and
4010/// meets the v-part's `}` at the math shift: "Extra }, or forgotten $", deleted (latexml_engine tex_box.rs
4011/// `\lx@template@egroup`). The common case — no mark live — costs one value lookup per control sequence.
4012fn closes_template_brace(token: &Token) -> bool {
4013  match token.get_catcode() {
4014    Catcode::END => close_template_brace(),
4015    cc if cc.is_active_or_cs() => {
4016      lookup_bool_sym(crate::pin!("lx@template@brace@open"))
4017        && gullet::is_right_brace(token)
4018        && close_template_brace()
4019    },
4020    _ => false,
4021  }
4022}
4023/// The `\endgroup` twin of [`OWED_BRACES`].
4024pub const OWED_ENDGROUPS: &str = "lx@owed@endgroups";
4025
4026/// The debt `key` bound on the innermost frame (0 when none).
4027pub fn owed_closers(key: &str) -> i64 {
4028  if is_value_bound(key, Some(0)) {
4029    lookup_int(key)
4030  } else {
4031    0
4032  }
4033}
4034
4035/// Whether the innermost group is the `math_left_group` a `\left` opened (its group code, latexml_engine tex_math.rs
4036/// `\lx@math@left@group`).
4037pub fn in_left_group() -> bool {
4038  is_value_bound("lx@group@code", Some(0)) && lookup_token("lx@group@code") == Some(T_CS!("\\left"))
4039}
4040
4041/// Whether the innermost group is the formula's own math shift (a frame that switched to math mode).
4042fn in_math_shift_group() -> bool {
4043  is_value_bound("MODE", Some(0))
4044    && matches!(lookup_mode(), m if m == crate::pin!("math") || m == crate::pin!("display_math"))
4045}
4046
4047/// The closer a `}` is missing in the innermost group when that group is one `}` cannot close (tex.web §1069
4048/// `extra_right_brace`) — any group not opened by a begin-group token: the formula's math shift (`$`), the `\left`
4049/// group (`\right.`), a `\begingroup` group (`\endgroup`), and an argument group the engine opens to digest a
4050/// constructor's argument (a K9 group code: `\frac`, `\sqrt`, `\mathbf`), whose closer is its constructor's own. TeX
4051/// has no such group: LaTeX's `\frac` digests its argument inside `\begingroup…\endgroup`, so the message is TeX's for
4052/// that (`\endgroup`), where for `\sqrt`/`\mathbf` TeX's group is a math group its `}` would close. `None` for a group
4053/// `}` closes. OXIDIZED_DESIGN #530.
4054fn brace_cannot_close() -> Option<&'static str> {
4055  if in_math_shift_group() {
4056    Some("$")
4057  } else if in_left_group() {
4058    Some("\\right.")
4059  } else if (lookup_bool_sym(crate::pin!("groupNonBoxing"))
4060    && lookup_token_sym(crate::pin!("groupInitiator"))
4061      .is_some_and(|t| t.defined_as(&T_CS!("\\begingroup"))))
4062    || is_value_bound("lx@group@code", Some(0))
4063  {
4064    Some("\\endgroup")
4065  } else {
4066    None
4067  }
4068}
4069
4070/// Whether stack frame `n` (0 = innermost) is a group the document opened that tex.web §1064-1065 `off_save` closes:
4071/// a `{`/`\bgroup` group (`simple_group`, closer `}`), a `\begingroup` group (`semi_simple_group`, `\endgroup`) or a
4072/// `\left` group (`math_left_group`, `\right.`). The closer, or `None` for a frame LaTeXML's machinery opened — a
4073/// mode switch (box, formula, cell), an environment, a constructor's argument (a K9 group code) — which TeX has no
4074/// such group for. OXIDIZED_DESIGN #553.
4075fn off_save_closer_at(n: usize) -> Option<Token> {
4076  if is_value_bound("BOUND_MODE", Some(n)) {
4077    return None;
4078  }
4079  if is_value_bound("lx@group@code", Some(n)) {
4080    return value_in_frame("lx@group@code", n)
4081      .is_some_and(|code| matches!(code, Stored::Token(t) if t == T_CS!("\\left")))
4082      .then(|| T_CS!("\\right"));
4083  }
4084  if !is_value_bound("groupInitiator", Some(n)) {
4085    return None;
4086  }
4087  match value_in_frame("groupInitiator", n) {
4088    Some(Stored::Token(opener))
4089      if opener.get_catcode() == Catcode::BEGIN || opener.defined_as(&T_BEGIN!()) =>
4090    {
4091      Some(T_END!())
4092    },
4093    Some(Stored::Token(opener)) if opener.defined_as(&T_CS!("\\begingroup")) => {
4094      Some(T_CS!("\\endgroup"))
4095    },
4096    _ => None,
4097  }
4098}
4099
4100/// The closer tex.web §1064-1065 `off_save` inserts for the innermost group when the document opened it: `}` for a
4101/// `{`/`\bgroup` group, `\endgroup` for a `\begingroup` group (`off_save_closer_at`; the `\left` group's `\right.`
4102/// has its own callers, `insert_missing_right_before`). OXIDIZED_DESIGN #553.
4103pub fn off_save_closer() -> Option<Token> {
4104  off_save_closer_at(0).filter(|closer| *closer != T_CS!("\\right"))
4105}
4106
4107/// Record that an inserted `closer` (`}` or `\endgroup`) took the place of the author's own: the innermost group owes
4108/// it ([`OWED_BRACES`] / [`OWED_ENDGROUPS`]), so that closer, when it comes and meets a group it cannot close, is
4109/// deleted as tex.web §1069 deletes it. OXIDIZED_DESIGN #530.
4110pub fn owe_inserted_closer(closer: &Token) {
4111  let owed = if *closer == T_END!() {
4112    OWED_BRACES
4113  } else {
4114    OWED_ENDGROUPS
4115  };
4116  assign_frame_value(owed, Stored::Int(owed_closers(owed) + 1));
4117}
4118
4119/// Marks the frame of a formula `$…$` (or `\(…\)`) opened by `\lx@begin@inline@math` (latexml_engine tex_math.rs):
4120/// the inline formula tex.web §1046-1047 `insert_dollar_sign` ends. OXIDIZED_DESIGN #553.
4121pub const INLINE_FORMULA: &str = "lx@inline@formula";
4122
4123/// Whether the innermost mode is an inline formula ([`INLINE_FORMULA`]) that a math shift read now would end: every
4124/// group opened inside it is one `off_save` closes on the way (`off_save_closer_at`), so the `$` tex.web §1047
4125/// inserts closes those groups (§1193 + §1064-1065) and then the formula. A formula held by a frame LaTeXML's
4126/// machinery opened (a constructor's argument, an environment, an alignment inside it) is not reached, nor is a
4127/// formula in an alignment, unmarked (latexml_engine tex_math.rs `\lx@begin@inline@math`).
4128pub fn inline_formula_reachable() -> bool { formula_reachable(INLINE_FORMULA) }
4129
4130/// Marks the frame of a display `$$…$$` opened by `\lx@begin@display@math` outside an alignment (latexml_engine
4131/// tex_math.rs, latex_constructs sect07.rs): the display a math shift ends through the groups opened in it (tex.web
4132/// §1193 + §1064-1065), as [`INLINE_FORMULA`] marks an inline formula.
4133pub const DISPLAY_FORMULA: &str = "lx@display@formula";
4134
4135/// Whether the innermost mode is a formula whose frame carries `flag` ([`INLINE_FORMULA`], [`DISPLAY_FORMULA`]) and
4136/// every group opened inside it is one `off_save` closes on the way (`off_save_closer_at`).
4137pub fn formula_reachable(flag: &str) -> bool {
4138  let depth = get_frame_depth();
4139  for n in 0..depth {
4140    if is_value_bound("BOUND_MODE", Some(n)) {
4141      return is_value_bound(flag, Some(n));
4142    }
4143    if off_save_closer_at(n).is_none() {
4144      return false;
4145    }
4146  }
4147  false
4148}
4149
4150/// tex.web §1046-1047 `insert_dollar_sign`: a command inline math cannot hold (`mmode+par_end`; an environment's end,
4151/// whose `\endgroup` meets the math shift group, §1064) arriving in an inline formula — "Missing $ inserted", the
4152/// formula's end read first and `again` after it. Returns whether it was inserted. An Error, as TeX's; Perl has no
4153/// such recovery, and the formula ran on through the paragraphs to the next `$`, its text and the document's math
4154/// swapped (OXIDIZED_DESIGN #553; 65d review probes f4, a18, a19). Guards
4155/// `perfect_kernel_batch65n::{par_in_inline_math_ends_the_formula, environment_end_in_inline_math_ends_the_formula}`.
4156pub fn insert_dollar_sign(again: Tokens) -> Result<bool> {
4157  if lookup_mode() != crate::pin!("math") || !inline_formula_reachable() {
4158    return Ok(false);
4159  }
4160  Error!(
4161    "expected",
4162    "$",
4163    "Missing $ inserted",
4164    s!(
4165      "I've inserted an end-math symbol before {}, which inline math cannot hold.",
4166      again
4167    )
4168  );
4169  let mut tokens = vec![T_CS!("\\lx@end@inline@math@inserted")];
4170  tokens.extend(again.unlist());
4171  gullet::unread(Tokens::new(tokens));
4172  Ok(true)
4173}
4174
4175/// How many source lines past a `\par` read in an inline formula [`formula_continues_past_par`] looks at.
4176const PAR_LOOKAHEAD_LINES: usize = 40;
4177/// How many tokens past such a `\par` it looks at.
4178const PAR_LOOKAHEAD_TOKENS: usize = 2000;
4179/// How many characters of source text it copies to tokenize (a one-line source holds the whole document on its
4180/// current line), so that a `\par` costs at most this much however long the line.
4181const PAR_LOOKAHEAD_CHARS: usize = 16_000;
4182/// How deep it follows a macro into the macros of its body ([`lookahead_command`]).
4183const PAR_LOOKAHEAD_DEPTH: usize = 3;
4184/// How many body tokens it examines in all, following macros.
4185const PAR_LOOKAHEAD_BODY_TOKENS: usize = 512;
4186
4187/// The primitives tex.web §1046 makes a non-math mode meet with `insert_dollar_sign` — math-only commands, whatever
4188/// LaTeXML defines them as: `\left`/`\middle`/`\right` (`left_right`), the generalized fractions (`above`),
4189/// `\mathchar`, `\delimiter`, `\radical`, `\mathaccent`, the math classes (`math_comp`; not `\underline`, which LaTeX
4190/// makes good in text), `\mathchoice`, `\vcenter`, `\nonscript`, `\mkern`, `\mskip`, the limit switches and the
4191/// styles. A token is matched by its meaning's own name, so `\let\lft\left` is one too.
4192const MATH_ONLY_PRIMITIVES: &[&str] = &[
4193  "\\left",
4194  "\\middle",
4195  "\\right",
4196  "\\over",
4197  "\\atop",
4198  "\\above",
4199  "\\overwithdelims",
4200  "\\atopwithdelims",
4201  "\\abovewithdelims",
4202  "\\mathchar",
4203  "\\delimiter",
4204  "\\radical",
4205  "\\mathaccent",
4206  "\\mathord",
4207  "\\mathop",
4208  "\\mathbin",
4209  "\\mathrel",
4210  "\\mathopen",
4211  "\\mathclose",
4212  "\\mathpunct",
4213  "\\mathinner",
4214  "\\overline",
4215  "\\mathchoice",
4216  "\\vcenter",
4217  "\\nonscript",
4218  "\\mkern",
4219  "\\mskip",
4220  "\\limits",
4221  "\\nolimits",
4222  "\\displaylimits",
4223  "\\displaystyle",
4224  "\\textstyle",
4225  "\\scriptstyle",
4226  "\\scriptscriptstyle",
4227];
4228
4229/// What the look-ahead past a `\par` stops at undecided, by name or by meaning (`\let\endgraf\par`, a macro whose
4230/// body holds one — `\medskip`'s `\vskip`, `\section`'s `\par`): a paragraph's end, or a command inline math cannot
4231/// hold (tex.web §1046 `mmode+par_end`, `stop`, `vskip`, `hrule`, `un_vbox`, `valign`; an environment's end or begin;
4232/// an alignment's `\cr`), or a formula's opener. And `\catcode`: TeX tokenizes what follows it under the new codes,
4233/// so the look-ahead's tokens past it are not the ones TeX reads (`\catcode`\_=12 a_b`; a macro whose body holds one).
4234/// A primitive that changes codes in its closure (`\makeatletter`, `\obeylines`) is not seen; only `\catcode` is.
4235const PAR_LOOKAHEAD_STOPS: &[&str] = &[
4236  "\\par",
4237  "\\lx@normal@par",
4238  "\\endgraf",
4239  "\\end",
4240  "\\begin",
4241  "\\vskip",
4242  "\\vfil",
4243  "\\vfill",
4244  "\\vss",
4245  "\\vfilneg",
4246  "\\hrule",
4247  "\\unvbox",
4248  "\\unvcopy",
4249  "\\valign",
4250  "\\cr",
4251  "\\crcr",
4252  "\\(",
4253  "\\[",
4254  "\\]",
4255  "\\catcode",
4256];
4257
4258/// What a control sequence met by the look-ahead past a `\par` tells it ([`lookahead_command`]).
4259#[derive(Clone, Copy, PartialEq, Eq)]
4260enum LookaheadCommand {
4261  /// Math-only by its current meaning — what tex.web §1046 meets with `insert_dollar_sign` outside math: a control
4262  /// sequence (`\let` to a sub- or superscript mark included) whose definition is LaTeXML's for math only (a DefMath
4263  /// symbol; a constructor or primitive that requires math, Perl's `requireMath`) or one of TeX's math-only
4264  /// primitives ([`MATH_ONLY_PRIMITIVES`]).
4265  MathOnly,
4266  /// Neither: typeset in text, its arguments (if any) braced or bracketed groups the look-ahead steps over.
4267  Neutral,
4268  /// The look-ahead cannot go past it: it ends the paragraph or the formula ([`PAR_LOOKAHEAD_STOPS`], a definition
4269  /// that leaves horizontal mode), or it reads what follows in a way the look-ahead cannot follow — a verbatim,
4270  /// semi-verbatim or delimited parameter (`\url`, `\ref`, `\def\a#1.{…}`), a macro whose expansion is code
4271  /// (`\verb`, whose argument's delimiter is any character), a `$` or `&` in its body, or bounds run out.
4272  GiveUp,
4273}
4274
4275/// What the control sequence or active character `token` tells the look-ahead past a `\par`, by its current meaning
4276/// ([`LookaheadCommand`]), nothing expanded. A definition's parameters are read from its parameter list: any verbatim,
4277/// semi-verbatim or delimited one gives up. A macro whose body is tokens is followed into the control sequences of
4278/// that body, `depth` levels deep, for what it stops at or cannot follow (`\lstinline` = `\leavevmode\lx@lstinline`,
4279/// whose code reads a verbatim argument; `\medskip` = `\vskip…`); `budget` bounds the body tokens examined.
4280fn lookahead_command(token: &Token, depth: usize, budget: &mut usize) -> LookaheadCommand {
4281  use LookaheadCommand::*;
4282  if token.with_str(|name| PAR_LOOKAHEAD_STOPS.contains(&name)) {
4283    return GiveUp;
4284  }
4285  let defn: Rc<dyn Definition> = match lookup_meaning(token) {
4286    None => return Neutral,
4287    Some(Stored::Token(t)) => {
4288      return match t.get_catcode() {
4289        Catcode::SUPER | Catcode::SUB => MathOnly,
4290        Catcode::MATH | Catcode::ALIGN => GiveUp,
4291        _ => Neutral,
4292      };
4293    },
4294    Some(Stored::MathPrimitive(_)) => return MathOnly,
4295    Some(Stored::Constructor(d)) => d,
4296    Some(Stored::Primitive(d)) => d,
4297    Some(Stored::Expandable(d)) => d,
4298    Some(Stored::Conditional(d)) => d,
4299    Some(_) => return Neutral,
4300  };
4301  if defn
4302    .get_cs()
4303    .with_str(|name| PAR_LOOKAHEAD_STOPS.contains(&name))
4304  {
4305    return GiveUp;
4306  }
4307  let mode = defn.declared_mode();
4308  if mode.as_ref().is_some_and(|mode| mode.leave_horizontal) {
4309    return GiveUp;
4310  }
4311  if defn.get_parameters().is_some_and(|params| {
4312    params.get_parameters().iter().any(|param| {
4313      param.semiverbatim.is_some()
4314        || arena::with(param.name, |name| {
4315          name.contains("erbatim") || name.contains("Until") || name == "Match"
4316        })
4317    })
4318  }) {
4319    return GiveUp;
4320  }
4321  if mode.is_some_and(|mode| mode.require_math)
4322    || defn
4323      .get_cs()
4324      .with_str(|name| MATH_ONLY_PRIMITIVES.contains(&name))
4325  {
4326    return MathOnly;
4327  }
4328  match defn.get_expansion() {
4329    Some(ExpansionBody::Closure(_)) => GiveUp,
4330    Some(ExpansionBody::Tokens(body)) => {
4331      if depth >= PAR_LOOKAHEAD_DEPTH {
4332        return GiveUp;
4333      }
4334      for inner in body.unlist_ref() {
4335        if *budget == 0 {
4336          return GiveUp;
4337        }
4338        *budget -= 1;
4339        match inner.get_catcode() {
4340          Catcode::MATH | Catcode::ALIGN => return GiveUp,
4341          code
4342            if code.is_active_or_cs()
4343              && inner != token
4344              && lookahead_command(inner, depth + 1, budget) == GiveUp =>
4345          {
4346            return GiveUp;
4347          },
4348          _ => {},
4349        }
4350      }
4351      Neutral
4352    },
4353    None => Neutral,
4354  }
4355}
4356
4357/// Whether the inline formula a `\par` is read in goes on past it: OXIDIZED_DESIGN #553 as narrowed (66w). The
4358/// input is looked at, not read ([`gullet::peek_upcoming_tokens`], unexpanded, each token by its current meaning),
4359/// as far as the formula's would-be closer — the next `$` or `\)` — within the paragraph after the `\par`. The
4360/// formula continues when the material before that closer holds a math-only token (a `_`/`^`, or a command that is
4361/// `LookaheadCommand::MathOnly`): the author split the formula with a blank line and the math goes on (hep-th9402135
4362/// `$Z_{YM}(\epsilon) =` ⏎⏎ `\int_{\cal A} … D A$`, whose ending put every later `$` of the paragraph out of step,
4363/// Fatal TooManyErrors). It does not when no math-only token comes first — that `$` opens the next paragraph's own
4364/// formula, and the `\par` ends this one (tex.web §1047, a forgotten `$`) — nor on any doubt: no closer before the
4365/// paragraph's end (`PAR_LOOKAHEAD_STOPS`), the bounds (`PAR_LOOKAHEAD_LINES`, `PAR_LOOKAHEAD_TOKENS`,
4366/// `PAR_LOOKAHEAD_CHARS`), a closer inside a group, a bracket or a `$$`, a `}` closing a group the look-ahead did not
4367/// see open, an `&`, a command it cannot follow (`LookaheadCommand::GiveUp`: `\verb|make_all|`, `\lstinline`, `\url`).
4368/// The arguments of a command that is not math-only are not looked into: a `*` right after it, then every `[…]` and
4369/// `{…}` group in a row (`\cite[p.~2]{smith_2001}`, `\ref*{eq_1}`, `\includegraphics[width=1cm]{fig_1}`,
4370/// `\citep[e.g.][]{a_b}`) — their scripts may be a key's or a file name's, never typeset; any other group is
4371/// (`{\cf^{1}/G}$`, `\left[0,1\right)`). The look-ahead starts after the judged `\par`, its leading `\par`s and spaces
4372/// skipped — an `\obeylines` line end's active `^^M` among them (hep-ph9809328).
4373pub fn formula_continues_past_par() -> bool {
4374  if lookup_mode() != crate::pin!("math") || !inline_formula_reachable() {
4375    return false;
4376  }
4377  let upcoming = gullet::peek_upcoming_tokens(
4378    PAR_LOOKAHEAD_LINES,
4379    PAR_LOOKAHEAD_CHARS,
4380    PAR_LOOKAHEAD_TOKENS,
4381  );
4382  par_lookahead_verdict(upcoming) == Some(true)
4383}
4384
4385/// Whether `token` is `\par` or means it (`\endgraf`, an active `^^M` under plain's `\obeylines`).
4386fn means_par(token: &Token) -> bool {
4387  *token == T_CS!("\\par")
4388    || matches!(lookup_meaning(token), Some(Stored::Constructor(d))
4389      if d.get_cs().with_str(|name| name == "\\lx@normal@par"))
4390}
4391
4392/// Where the look-ahead past a `\par` is relative to a command's arguments.
4393#[derive(Clone, Copy, PartialEq, Eq)]
4394enum ArgumentPosition {
4395  /// Not after a command.
4396  None,
4397  /// Right after a control sequence that is not math-only: a `*`, a `[…]` or a `{…}` is its argument.
4398  Command,
4399  /// Right after such an argument: a `[…]` or a `{…}` is its next one.
4400  Argument,
4401}
4402
4403/// [`formula_continues_past_par`]'s decision over the `upcoming` tokens: `Some(math_only_seen)` at the closer,
4404/// `None` when undecided.
4405fn par_lookahead_verdict(upcoming: impl Iterator<Item = Token>) -> Option<bool> {
4406  let mut tokens = upcoming.peekable();
4407  let mut math_only = false;
4408  let mut depth = 0usize;
4409  // The brace depth below which every group is an argument, not looked into (`None`: none open).
4410  let mut opaque_from: Option<usize> = None;
4411  // The brace depth of an open bracketed argument `[…]`, not looked into.
4412  let mut bracket_at: Option<usize> = None;
4413  let mut position = ArgumentPosition::None;
4414  let mut leading = true;
4415  let mut budget = PAR_LOOKAHEAD_BODY_TOKENS;
4416  // The commands already classified, so a repeated macro costs its body once.
4417  let mut seen: Vec<(Token, LookaheadCommand)> = Vec::new();
4418  while let Some(token) = tokens.next() {
4419    let code = token.get_catcode();
4420    // The `\par`s and spaces of the blank lines themselves (an active `^^M` let to `\par` under `\obeylines`).
4421    if leading && (code == Catcode::SPACE || means_par(&token)) {
4422      continue;
4423    }
4424    leading = false;
4425    let opaque = opaque_from.is_some() || bracket_at.is_some();
4426    let after_command = position != ArgumentPosition::None;
4427    match code {
4428      Catcode::SPACE | Catcode::COMMENT | Catcode::MARKER => continue,
4429      // TeX's alphabetic constant: a `_` or `^` after a `` ` `` is a character code (`\char`_`, `\lccode`^`),
4430      // inert. Only those two are stepped over: a quoted `` `$x_1$' `` or `` `\ref{a_b}' `` keeps its `$` or its
4431      // command, which decide as they would anywhere else.
4432      Catcode::OTHER if token == T_OTHER!("`") => {
4433        if tokens
4434          .peek()
4435          .is_some_and(|next| matches!(next.get_catcode(), Catcode::SUB | Catcode::SUPER))
4436        {
4437          tokens.next();
4438        }
4439        position = ArgumentPosition::None;
4440        continue;
4441      },
4442      Catcode::MATH => {
4443        let display = tokens
4444          .peek()
4445          .is_some_and(|next| next.get_catcode() == Catcode::MATH);
4446        return (depth == 0 && !opaque && !display).then_some(math_only);
4447      },
4448      Catcode::ALIGN => return None,
4449      Catcode::BEGIN => {
4450        if after_command && !opaque {
4451          opaque_from = Some(depth);
4452        }
4453        depth += 1;
4454        position = ArgumentPosition::None;
4455        continue;
4456      },
4457      Catcode::END => {
4458        depth = depth.checked_sub(1)?;
4459        if bracket_at.is_some_and(|at| at > depth) {
4460          return None;
4461        }
4462        position = ArgumentPosition::None;
4463        if opaque_from == Some(depth) {
4464          opaque_from = None;
4465          position = ArgumentPosition::Argument;
4466        }
4467        continue;
4468      },
4469      Catcode::OTHER if !opaque && after_command => {
4470        if position == ArgumentPosition::Command && token == T_OTHER!("*") {
4471          continue;
4472        }
4473        if token == T_OTHER!("[") {
4474          bracket_at = Some(depth);
4475          position = ArgumentPosition::None;
4476          continue;
4477        }
4478      },
4479      Catcode::OTHER if bracket_at == Some(depth) && token == T_OTHER!("]") => {
4480        bracket_at = None;
4481        position = ArgumentPosition::Argument;
4482        continue;
4483      },
4484      _ => {},
4485    }
4486    position = ArgumentPosition::None;
4487    if code.is_active_or_cs() {
4488      if token == T_CS!("\\)") {
4489        return (depth == 0 && !opaque).then_some(math_only);
4490      }
4491      let command = match seen.iter().find(|(known, _)| *known == token) {
4492        Some((_, command)) => *command,
4493        None => {
4494          let command = lookahead_command(&token, 0, &mut budget);
4495          seen.push((token, command));
4496          command
4497        },
4498      };
4499      match command {
4500        LookaheadCommand::GiveUp => return None,
4501        LookaheadCommand::MathOnly => math_only |= !opaque,
4502        // A math-only command's groups and brackets are math, looked into (`\left[0,1\right)`, `\in [0,1)`).
4503        LookaheadCommand::Neutral if code == Catcode::CS => position = ArgumentPosition::Command,
4504        LookaheadCommand::Neutral => {},
4505      }
4506    } else if !opaque && matches!(code, Catcode::SUPER | Catcode::SUB) {
4507      math_only = true;
4508    }
4509  }
4510  None
4511}
4512
4513/// The `}` a `\left`/`\middle`/`\right` delimiter scan put back after "Missing delimiter" (latexml_engine tex_math.rs
4514/// `missing_delimiter`, [`mark_put_back_brace`]). The mark lives as long as that brace: a serial bound on the frame
4515/// innermost when it was put back — inside the formula, so it dies with the formula at the latest — and valid only
4516/// while it equals the live serial ([`PUT_BACK_LIVE`]), which the next `}` digested anywhere clears
4517/// (`take_put_back_mark` in `delete_extra_brace` and at [`invoke_token`]). OXIDIZED_DESIGN #530.
4518pub const PUT_BACK_BRACE: &str = "lx@putback@brace";
4519/// The serial of the one live put-back mark (0: none), global.
4520pub const PUT_BACK_LIVE: &str = "lx@putback@live";
4521
4522/// Mark the `}` a delimiter scan is putting back ([`PUT_BACK_BRACE`]).
4523pub fn mark_put_back_brace() {
4524  let serial = lookup_int("lx@putback@serial") + 1;
4525  assign_value(
4526    "lx@putback@serial",
4527    Stored::Int(serial),
4528    Some(Scope::Global),
4529  );
4530  assign_value(PUT_BACK_LIVE, Stored::Int(serial), Some(Scope::Global));
4531  assign_frame_value(PUT_BACK_BRACE, Stored::Int(serial));
4532}
4533
4534/// Whether `token` is the `}` a delimiter scan put back; any `}` clears the mark.
4535fn take_put_back_mark(token: &Token) -> bool {
4536  // The hottest digestion path: no live mark (almost always) answers before the brace test's meaning lookup.
4537  let live = lookup_int_sym(crate::pin!("lx@putback@live"));
4538  if live == 0 || !gullet::is_right_brace(token) {
4539    return false;
4540  }
4541  assign_value(PUT_BACK_LIVE, Stored::Int(0), Some(Scope::Global));
4542  lookup_int(PUT_BACK_BRACE) == live
4543}
4544
4545/// The put-back `}` meeting the formula's own math shift: deleted per §1069, "Extra }, or forgotten $", an Error, as TeX
4546/// and Perl err there.
4547fn delete_put_back_brace() -> Result<bool> {
4548  if !in_math_shift_group() {
4549    return Ok(false);
4550  }
4551  Error!(
4552    "unexpected",
4553    "}",
4554    "Extra }, or forgotten $",
4555    "The } a delimiter scan put back has no group to close in the formula; it is deleted."
4556  );
4557  Ok(true)
4558}
4559
4560/// An author's `}` that tex.web §1069 `extra_right_brace` deletes:
4561/// * one whose place an inserted one took (frame debt [`OWED_BRACES`]) meeting a group `}` cannot close — "Extra },
4562///   or forgotten $" / "\right." / "\endgroup", a Warning (user ruling 2026-10-11: TeX-only, and the deletion is TeX's
4563///   recovery for our own insertion);
4564/// * the `}` a delimiter scan put back ([`PUT_BACK_BRACE`]: `$\left\{ x \right}$`, `\mbox{$\left\{ x \right}$}`)
4565///   meeting the formula's own math shift — "Extra }, or forgotten $", an Error, as TeX and Perl err there.
4566///
4567/// Any other `}` at the formula's frame is `digest_next_body`'s (the general §1069 deletion of an inline formula's stray
4568/// brace, OXIDIZED_DESIGN #553). Checked before the digestion loops could take the brace for a group end (65d reviews
4569/// r1/r3/r5). OXIDIZED_DESIGN #530.
4570fn delete_extra_brace(token: &Token) -> Result<bool> {
4571  if !gullet::is_right_brace(token) {
4572    return Ok(false);
4573  }
4574  let put_back = take_put_back_mark(token);
4575  if owed_closers(OWED_BRACES) > 0
4576    && let Some(forgotten) = brace_cannot_close()
4577  {
4578    assign_frame_value(OWED_BRACES, Stored::Int(owed_closers(OWED_BRACES) - 1));
4579    Warn!(
4580      "unexpected",
4581      "}",
4582      s!("Extra }}, or forgotten {forgotten}"),
4583      "The } of a group closed earlier by an inserted } is deleted."
4584    );
4585    return Ok(true);
4586  }
4587  if put_back {
4588    return delete_put_back_brace();
4589  }
4590  Ok(false)
4591}
4592
4593/// The reading context a `\left` was read in ([`gullet::reading_context`]: serial and depth), bound on its group's
4594/// frame by `\lx@math@left@group` (latexml_engine tex_math.rs) through [`record_left_group_input`].
4595const LEFT_INPUT: &str = "lx@left@input";
4596/// The depth half of [`LEFT_INPUT`].
4597const LEFT_INPUT_DEPTH: &str = "lx@left@input@depth";
4598/// Set in a `\left` group's frame once input ending in it has had its `\right.` inserted.
4599const LEFT_RIGHT_INSERTED: &str = "lx@left@right@inserted";
4600
4601/// Record on the innermost frame — the `\left` group, whose group code `\lx@math@left@group` has just set — the reading
4602/// context the `\left` was read in, for `close_left_group_at_input_end`.
4603pub fn record_left_group_input() {
4604  let (serial, depth) = gullet::reading_context();
4605  assign_frame_value(LEFT_INPUT, Stored::Int(serial as i64));
4606  assign_frame_value(LEFT_INPUT_DEPTH, Stored::Int(depth as i64));
4607}
4608
4609/// Whether the input that just ran out is the one the innermost `\left` group was opened in, or encloses it: the
4610/// group's recorded reading context ([`record_left_group_input`]) is the current one, or one nested in it that has
4611/// ended. Not when the `\left` was read outside the input that ended — a binding's `\left( \lx@xmarg{…}{#1} \right)`
4612/// (physics.sty's `\left(#1\right)`, 2605.02768 `\cosh(a\over 2)`, 2606.01486 `\expval{a \over b}`) digests its
4613/// argument from a mouth of its own, and that argument's end is no end of the `\left`'s input. A group without a
4614/// record (none bound on its frame) counts as opened here.
4615fn left_group_input_ended() -> bool {
4616  let (Some(Stored::Int(serial)), Some(Stored::Int(depth))) = (
4617    value_in_frame(LEFT_INPUT, 0),
4618    value_in_frame(LEFT_INPUT_DEPTH, 0),
4619  ) else {
4620    return true;
4621  };
4622  let (current, current_depth) = gullet::reading_context();
4623  serial == current as i64 || depth > current_depth as i64
4624}
4625
4626/// Input ending inside a `\left` group (its group code, latexml_engine tex_math.rs `\lx@math@left@group`) that was
4627/// opened in that input ([`left_group_input_ended`]) — an argument such as `\frac{\left( a}{b}`, whose digestion reads
4628/// its own tokens only, or the document's end: tex.web §1065 `off_save` inserts `\right.` ("Missing \right. inserted"),
4629/// which closes the group where it stands; without it the group stayed open past the argument and the formula
4630/// swallowed the paragraphs after it. A `\left` read outside the ending input stays open: tex.web §1191-1192, only its
4631/// `\right` or an error closes the `math_left_group`, and an argument's end is no end of input for TeX at all — the
4632/// argument is a `{…}` group inside the `\left` group (physics.sty's `\left(#1\right)`: closing the outer group there
4633/// made the binding's own `\right` "Extra \right.", 2605.02768, or a later `\lx@hidden@egroup` meet an `aligned` row's
4634/// `\begingroup`, 2606.01486). A Warning: TeX errs, Perl reports the open group only at the document's end, and the
4635/// inserted `\right.` is TeX's recovery (user ruling 2026-10-11 on TeX-only errors). Returns whether `\right.` was
4636/// inserted. OXIDIZED_DESIGN #530. Guards `perfect_kernel_batch65d::formula_end_closes_an_open_left`,
4637/// `perfect_kernel_batch66g::*`.
4638fn close_left_group_at_input_end() -> bool {
4639  if !in_left_group()
4640    || !left_group_input_ended()
4641    || value_in_frame(LEFT_RIGHT_INSERTED, 0).is_some()
4642  {
4643    return false;
4644  }
4645  // Once per group: a `\left` read in text (a document's `\newcommand\at[2]{\left.#1\right|_{#2}}` met outside math:
4646  // svjour3 1404.4148 and 8 more) opens a group the inserted `\right.` cannot close, which then met every later end of
4647  // input and inserted it again without end (Fatal Stomach:Recursion after 25,640 Warnings).
4648  assign_frame_value(LEFT_RIGHT_INSERTED, Stored::Int(1));
4649  insert_missing_right_before(Tokens!());
4650  true
4651}
4652
4653/// tex.web §1065 `off_save` for the `\left` group: "Missing \right. inserted", and `\right.` read before `again` (the
4654/// primitive that met the group, read again). A Warning: TeX errs, Perl does not model it, and the inserted `\right.`
4655/// is TeX's recovery (user ruling 2026-10-11). OXIDIZED_DESIGN #530.
4656pub fn insert_missing_right_before(again: Tokens) {
4657  Warn!(
4658    "expected",
4659    "\\right",
4660    "Missing \\right. inserted",
4661    "A \\left group ended without its \\right; a null \\right. closes it."
4662  );
4663  let mut tokens = vec![T_CS!("\\right"), T_OTHER!(".")];
4664  tokens.extend(again.unlist());
4665  gullet::unread(Tokens::new(tokens));
4666}
4667
4668/// Whether a `}` meeting the formula's math shift group closes a construct digested as a unit that holds the formula:
4669/// a box body (the mode frame just outside the formula, frame 1, switched by a command on its own `{` — `\mbox{$x}`,
4670/// `\hbox{$x}`, `\fbox{$x}`; not an environment `\begin{X}`) or an argument digested on its own (`\caption{$x} cap}`,
4671/// `\section{$x} sec}`: the `}` is the argument's own closing brace, [`gullet::isolated_input_ends_here`]). The formula
4672/// cannot escape such a construct, so it ends at the `}` with it. Any other `}` there — at the paragraph's level, in an
4673/// environment, in a plain `{…}` group (`{\bf $x} y$`) — is the extra brace tex.web §1069 deletes, and the formula goes on.
4674/// OXIDIZED_DESIGN #553.
4675fn formula_ends_with_its_unit() -> bool {
4676  let box_body = get_frame_depth() > 1
4677    && is_value_bound("BOUND_MODE", Some(1))
4678    && match value_in_frame("groupInitiator", 1) {
4679      Some(Stored::Token(opener)) => !opener.with_str(|name| name.starts_with("\\begin{")),
4680      // A mode frame with no recorded opener: machinery's, ended with the formula as before.
4681      _ => true,
4682    };
4683  box_body || gullet::isolated_input_ends_here()
4684}
4685
4686/// Whether `token` is a DefEnvironment's own end: the constructor `\end{X}` that pops the environment's frame.
4687fn is_environment_end(token: &Token) -> bool {
4688  token.get_catcode() == Catcode::CS
4689    && token.with_str(|name| name.starts_with("\\end{"))
4690    && with_meaning(token, |meaning| {
4691      matches!(meaning, Some(Stored::Constructor(_)))
4692    })
4693}
4694
4695/// [`insert_missing_right_before`] the one token `again`.
4696fn insert_missing_right(again: Token) { insert_missing_right_before(Tokens!(again)); }
4697
4698pub fn digest_next_body(terminal_opt: Option<Token>) -> Result<Vec<Digested>> {
4699  digest_body(terminal_opt, false)
4700}
4701
4702/// The body of a text-mode `{` opened in a paragraph. Perl digests it flat into the paragraph's list, after an open-brace
4703/// box (TeX_Box.pool.ltxml:30-42); here it has a list of its own, continuing the paragraph (`ParagraphStart::in_group`).
4704pub fn digest_group_body_in_paragraph() -> Result<Vec<Digested>> { digest_body(None, true) }
4705
4706fn digest_body(terminal_opt: Option<Token>, in_paragraph: bool) -> Result<Vec<Digested>> {
4707  let start_location = { gullet::get_locator() };
4708  // A box body digested for a binding in mid-scan runs outside the scan
4709  // (`gullet::NumberScan::suspend`).
4710  let _outside_scan = gullet::NumberScan::suspend();
4711
4712  let init_depth = { stomach!().boxing.len() };
4713  // Every bounded body records its terminal and depth on the current frame
4714  // (the caller's own `bounded => true` frame), for
4715  // `until_terminal_inside_group`; a terminal primitive that never calls it
4716  // (`\endgroup` for url.sty's body) leaves the record inert.
4717  if let Some(ref terminal) = terminal_opt {
4718    assign_frame_value("lx@until@terminal", Stored::Token(*terminal));
4719    assign_frame_value(
4720      "lx@until@depth",
4721      Stored::Number(crate::common::number::Number(init_depth as i64)),
4722    );
4723  }
4724  if *TRACE_TERMINAL {
4725    eprintln!("[terminal] enter body terminal={terminal_opt:?} init_depth={init_depth}");
4726  }
4727  // Did the loop end because the INPUT RAN OUT (as opposed to reaching the
4728  // terminal or closing the initial mode)? Perl `Stomach.pm` L130 keys the
4729  // trailer box on `unless $token`, and `$token` is undef exactly when the
4730  // `while (defined($token = ...))` condition failed — i.e. on EOF, whether or
4731  // not tokens were read before it. See the trailer push below.
4732  let mut ran_out = true;
4733  let mut found_terminal = false;
4734  let _body_scope = ArgDigestScope::enter_body();
4735  new_local_box_list();
4736  if in_paragraph {
4737    stomach_mut!().paragraph_start = Some(ParagraphStart {
4738      index:           0,
4739      implicit_indent: false,
4740      in_group:        true,
4741    });
4742  }
4743  let alignment_opt = lookup_alignment();
4744  // TODO: bookkeep for "expected" warning
4745  //let mut aug = Vec::new();
4746
4747  // try reading a executable token
4748  while let Some(token) = match gullet::get_pending_comment() {
4749    Some(comment) => Some(comment),
4750    None => match gullet::read_x_token(Some(true), false, None)? {
4751      None if close_left_group_at_input_end() => gullet::read_x_token(Some(true), false, None)?,
4752      next => next,
4753    },
4754  } {
4755    // Check conversion timeout
4756    check_timeout()?;
4757    if delete_extra_brace(&token)? {
4758      continue;
4759    }
4760    if closes_template_brace(&token) || align_error(&token)? {
4761      continue;
4762    }
4763    // A DefEnvironment's own end (`\end{X}`, the constructor that pops the environment's frame; no TeX-level `\endX`
4764    // exists to read again) met inside an open `\left` group: §1065 `off_save` at the primitive that mismatches —
4765    // "Missing \right. inserted", `\right.` read first (`\begin{equation}\left( x \end{equation}`). Before, the end met
4766    // the `\left` group ("Attempt to end mode display_math") and the formula ran on through the document. Guard
4767    // `perfect_kernel_batch65d::environment_end_closes_an_open_left`.
4768    if in_left_group() && is_environment_end(&token) {
4769      insert_missing_right(token);
4770      continue;
4771    }
4772    // The same end met inside an inline formula (`\begin{center}Before $x} after.\end{center}`, 65d review a12): the
4773    // environment's `\endgroup` meets the math shift group, and §1064 `off_save` inserts the `$` — "Missing $ inserted",
4774    // the formula ended first ([`insert_dollar_sign`]). Before, the end popped the formula's frame as its own.
4775    if is_environment_end(&token) && insert_dollar_sign(Tokens!(token))? {
4776      continue;
4777    }
4778    // The end of the environment around a bare `\X` left open ends X first, as TeX's group does
4779    // ([`end_command_form_before_enclosing_end`]).
4780    if is_environment_end(&token) && end_command_form_before_enclosing_end(&token)? {
4781      continue;
4782    }
4783    // first, check for alignment case
4784    // Perl #2775: only fire at the original alignment nesting level,
4785    // not inside deeper boxing groups (e.g. \vbox inside a tabular cell).
4786    // The tokens themselves, as Perl's `Equals` (Stomach.pm:114-116).
4787    if alignment_opt.is_some()
4788      && !stomach!().box_list.is_empty()
4789      && (stomach!().boxing.len() <= init_depth)
4790      && (token == T_ALIGN!()
4791        || token == T_CS!("\\cr")
4792        || token == T_CS!("\\lx@hidden@cr")
4793        || token == T_CS!("\\lx@hidden@crcr"))
4794    {
4795      gullet::unread_one(token);
4796      return Ok(expire_local_box_list());
4797    }
4798    // A `}` meeting the formula's own math shift group (tex.web §1069 "Extra }, or forgotten $") — one Error, TeX's
4799    // message, and one rule for an author's inline formula outside alignments:
4800    // * the `}` closes a construct digested as a unit ([`formula_ends_with_its_unit`]: a box body `\mbox{$x}`,
4801    //   `\hbox{$}`, `\fbox{$x}`; an argument digested on its own `\caption{$x} cap}`, `\section{$x} sec}`): the formula
4802    //   cannot escape the construct, so it ends at the `}` (its end inserted, the `}` read again) and the text after the
4803    //   construct stays text (65d review a6, a7, a9, a10, a14). pdflatex deletes the `}` and lets the box swallow the
4804    //   following text up to a later `}` (`\mbox{$x}`: "Before xafterone.Second para.") — the content-first divergence
4805    //   of OXIDIZED_DESIGN #553. Perl (Stomach.pm digestNextBody + egroup :339-349) reported the mismatch and read on,
4806    //   the math swallowing the rest of the document (`\hbox{$}`: Perl 7 errors + Fatal, `<ltx:Math>` at the root).
4807    //   Guard `perfect_kernel_batch56::box_end_over_leaked_math_closes_it_into_the_box`.
4808    // * every other `}` (`$x}$ text`, `{\it a $x}$ y}`, `{\bf $x} y$`, `Before $x} after.`): deleted as TeX deletes it;
4809    //   the formula goes on to its own `$` — or, missing that, to the `\par` or environment end where §1047 inserts it
4810    //   ([`insert_dollar_sign`]), keeping a wrong guess inside the paragraph (65d review a1, a2, a8, a11, a12, a16,
4811    //   a17, a18, f4). Guard `perfect_kernel_batch65n::stray_brace_in_a_formula_is_deleted`.
4812    // Display math (§1047 not applied to it — a blank line in an `equation` is common and tolerated — so a deleted brace
4813    // would run `{\equation x=1}` on through the document) and a formula in an alignment cell (its `$` may be the cell
4814    // template's; RED paragraph-mode/cell_end_in_inline_math_inserts_dollar) end at the `}` whatever it closes.
4815    if gullet::is_right_brace(&token) && is_value_bound("BOUND_MODE", Some(0)) {
4816      let mode = lookup_string_from_sym(crate::pin!("MODE"));
4817      let ender = match mode.as_str() {
4818        "math" => Some("\\lx@end@inline@math"),
4819        "display_math" => Some("\\lx@end@display@math"),
4820        _ => None,
4821      };
4822      if let Some(ender) = ender {
4823        let deleted = is_value_bound(INLINE_FORMULA, Some(0)) && !formula_ends_with_its_unit();
4824        Error!(
4825          "unexpected",
4826          "}",
4827          "Extra }, or forgotten $",
4828          if deleted {
4829            "I've deleted a group-closing symbol because it seems to be spurious, as in `$x}$'."
4830              .to_string()
4831          } else {
4832            s!("I've ended the {mode} formula before this group-closing symbol.")
4833          }
4834        );
4835        if !deleted {
4836          gullet::unread(Tokens::new(vec![T_CS!(ender), token]));
4837        }
4838        continue;
4839      }
4840    }
4841    // normal case
4842    if *TRACE_TERMINAL && terminal_opt.is_some() {
4843      eprintln!(
4844        "[terminal] read {token:?} depth={} init={}",
4845        stomach!().boxing.len(),
4846        init_depth
4847      );
4848    }
4849    if *TRACE_TERMINAL
4850      && let Some(ref terminal) = terminal_opt
4851      && token.get_catcode() == Catcode::CS
4852      && token.with_str(|a| terminal.with_str(|b| a == b))
4853    {
4854      eprintln!(
4855        "[terminal] candidate {token:?} vs {terminal:?} eq={} depth={} init={}",
4856        &token == terminal,
4857        stomach!().boxing.len(),
4858        init_depth
4859      );
4860    }
4861    let abandoned_before = abandoned_frame_count();
4862    let invoked = invoke_token(&token)?;
4863    extend_box_list(invoked);
4864
4865    if let Some(ref terminal) = terminal_opt
4866      && &token == terminal
4867    {
4868      found_terminal = true;
4869      ran_out = false;
4870      break;
4871    }
4872    // The terminal arrived inside a nested group and ended the body from
4873    // there (`until_terminal_inside_group`).
4874    if let Some(ref terminal) = terminal_opt
4875      && lookup_token("lx@until@terminal@hit").as_ref() == Some(terminal)
4876    {
4877      assign_value("lx@until@terminal@hit", Stored::None, Some(Scope::Global));
4878      found_terminal = true;
4879      ran_out = false;
4880      break;
4881    }
4882    if init_depth > stomach!().boxing.len() {
4883      if *TRACE_TERMINAL && terminal_opt.is_some() {
4884        eprintln!(
4885          "[terminal] EXIT depth {} < init {} after {token:?}",
4886          stomach!().boxing.len(),
4887          init_depth
4888        );
4889      }
4890      // A level popped by an abandonment during THIS token (`\end{document}` with the
4891      // environment still open, a bounded terminal inside a group) did not close the body: it
4892      // ends as Perl's does at end of input, with the dummy trailer below
4893      // (`abandon_stack_frame`; witnesses powerdotDE, arXiv 1902.00853). Keyed on the token, so
4894      // a body that merely ran BEFORE an abandonment elsewhere (a `{quote}` around a runaway
4895      // `\abstract{…`, screenplay-pkg.tex:67) still ends on its own `\end`, its trailer the
4896      // closer.
4897      ran_out = abandoned_frame_count() != abandoned_before;
4898      break;
4899    }
4900    // Fragment yield (streaming pass 1): between top-level constructs, at a
4901    // legal seam, hand back the boxes accumulated so far so the driver can
4902    // build + spill and re-enter. Everything digestion carries — gullet mouth
4903    // stack, State undo frames, mode, fonts — is thread-local and survives
4904    // between `digest_next_body` calls by construction, so resuming is the
4905    // same operation `digest_internal`'s outer loop already performs; the
4906    // alignment early-return above is the established precedent for
4907    // returning early with a partial list.
4908    //
4909    // Seam legality (probed 2026-07-29 on a real conversion, not assumed):
4910    // only the DRIVER call — `digest_internal` is the one caller that enters
4911    // with an empty boxing stack (`init_depth == 0`); constructor argument
4912    // digests also pass `None` but always sit inside an open box. The boxing
4913    // stack must be back at 0, and the mode VERTICAL-family: the document
4914    // body runs in `internal_vertical` (the `\begin{document}` environment's
4915    // mode — plain `vertical` occurs only before it), and at depth 0 that
4916    // cannot be a vbox/minipage interior, which always sits at deeper boxing.
4917    // A horizontal-mode cut would split the run `repack_horizontal` folds
4918    // into one paragraph; alignment, math, and open conditionals must all be
4919    // closed. A single construct larger than the whole budget simply digests
4920    // through — the existing hard ceilings still protect.
4921    //
4922    // Checked AFTER the terminal/depth exits so a real exit always wins, and
4923    // before the next `read_x_token` so nothing is consumed-then-unread.
4924    if (FRAGMENT_YIELD_BUDGET.get().is_some() || FRAGMENT_YIELD_RSS_SOFT_KB.get().is_some())
4925      && init_depth == 0
4926      && terminal_opt.is_none()
4927      && alignment_opt.is_none()
4928      && {
4929        // The box budget yields on its own, and so does a construct's seam
4930        // request (`\pgfsys@endpicture`) — both only while a box budget is
4931        // armed (streaming pass 1). The soft-RSS branch is armed on its own by
4932        // the adaptive eager phase (`digest_adaptive`): there, a picture seam
4933        // with room to spare must NOT yield, only crossing the watermark does.
4934        // The soft branch additionally requires a MINIMUM accumulation: it is
4935        // a level test (`rss > soft`) with no hysteresis, so a document whose
4936        // resident floor sits above the watermark latches it on for the whole
4937        // run and yields at every seam with nothing accumulated — see
4938        // `soft_yield_min_boxes` for the measured degeneracy (24 M yields /
4939        // 5.5 KB segments on the witness).
4940        let accumulated = stomach!().box_list.len();
4941        let rss_kb = LAST_SAMPLED_RSS_KB.get();
4942        let budget = FRAGMENT_YIELD_BUDGET.get();
4943        budget.is_some_and(|b| accumulated >= b)
4944          || (budget.is_some() && FRAGMENT_YIELD_REQUESTED.get() && accumulated > 0)
4945          || (FRAGMENT_YIELD_RSS_SOFT_KB
4946            .get()
4947            .is_some_and(|soft| rss_kb > soft)
4948            // The floor is waived once pressure is urgent, so pathological
4949            // per-box footprints keep the immediate response this branch
4950            // exists to give (`soft_yield_is_urgent`) — and once the
4951            // accumulation is WORTH a spill by size: a few huge top-level
4952            // bodies (pgf-spectra LSE: ~194 pictures, 6.4 GB) never reach a
4953            // box-count floor, and with no fuse (`--max-memory=0`) nothing
4954            // is ever "urgent", so the adaptive transition never fired on
4955            // its own witness. The GROWTH floor (resident memory gained since
4956            // the last yield) keeps the degenerate regime out (5.5 KB segments
4957            // ≪ 64 MB) and measures the retention a spill would free.
4958            && (accumulated >= soft_yield_min_boxes()
4959              || soft_yield_is_urgent(rss_kb)
4960              || rss_kb.saturating_sub(LAST_YIELD_RSS_KB.get()) >= SOFT_YIELD_MIN_GROWTH_KB))
4961      }
4962      && stomach!().boxing.is_empty()
4963      && lookup_alignment().is_none()
4964      && !lookup_bool_sym(crate::pin!("IN_MATH"))
4965      && open_conditional_count() == 0
4966      && matches!(lookup_mode(), m if m == crate::pin!("vertical") || m == crate::pin!("internal_vertical"))
4967    {
4968      FRAGMENT_YIELDED.set(true);
4969      FRAGMENT_YIELD_REQUESTED.set(false);
4970      FRAGMENT_YIELD_COUNT.set(FRAGMENT_YIELD_COUNT.get() + 1);
4971      note_yield_rss_baseline(LAST_SAMPLED_RSS_KB.get());
4972      // A deferred `\index`/`\nomenclature` entry is built with this fragment: typeset now, as Perl does
4973      // (`resolve_deferred_prints`; OXIDIZED_DESIGN_DIVERGENCES #738).
4974      resolve_deferred_prints(None)?;
4975      // No EOF trailer (`ran_out` stays true only through the loop's own
4976      // exhaustion path — we return before reaching it), and no
4977      // `gullet::flush()`: both are end-of-input actions, and input remains.
4978      return Ok(expire_local_box_list());
4979    }
4980  }
4981
4982  if let Some(ref terminal) = terminal_opt
4983    && !found_terminal
4984  {
4985    let message = s!(
4986      "body should have ended with {:?}. current body started at {:?}",
4987      terminal,
4988      start_location
4989    );
4990    Warn!("expected", terminal, message);
4991  }
4992  // and add a Dummy `trailer' if none explicit — Perl `Stomach.pm` L130,
4993  // `push(@LaTeXML::LIST, Box()) unless $token;`.
4994  //
4995  // This was mistranslated as "if we never read ANY token", which is a strictly
4996  // narrower condition: it agrees with Perl only on a body that was empty from
4997  // the start. The case it missed is a body that read content and THEN hit EOF —
4998  // and that is the case the trailer exists for. `readDigested`
4999  // (`Base_ParameterTypes.pool.ltxml` L374, ported in `base_parameter_types.rs`)
5000  // does `push(@list, digestNextBody()); pop(@list);` to strip the closing `}`
5001  // box; with no trailer pushed, that `pop` silently ate a box of REAL CONTENT.
5002  // Concretely: one runaway `.bib` field swallowed the rest of the entry into
5003  // its own argument, and the `pop` then removed the boxes carrying every
5004  // following entry — an empty bibliography where Perl renders all of them.
5005  if ran_out {
5006    push_box_list(Digested::from(Tbox::default()));
5007  }
5008  Ok(expire_local_box_list())
5009}
5010
5011/// Perl `RawTeX` (Package.pm:981-997): a convenience function for including chunks of raw TeX (or LaTeX) code
5012/// It is useful for copying portions of the normal
5013/// implementation that can be handled simply using macros and primitives.
5014pub fn raw_tex(text: &str) -> Result<()> {
5015  // It could be as simple as this, except if catcodes get changed, it's too late!!!
5016  //  Digest(TokenizeInternal($text));
5017  let raw_tex_mouth = Mouth::new(
5018    text,
5019    Some(MouthOptions {
5020      fordefinitions: true,
5021      at_letter: true,
5022      ..MouthOptions::default()
5023    }),
5024  )?;
5025  gullet::reading_from_mouth(raw_tex_mouth, || -> Result<()> {
5026    while let Some(token) = gullet::read_x_token(Some(false), false, None)? {
5027      // Same per-iteration guard tick as digest()/digest_next_body — see the
5028      // comment in `digest` (PR #249 review P2-6): raw-loaded .sty/.cls
5029      // digestion must raise pending stomach fatals and honor the deadline
5030      // and RSS caps too.
5031      check_timeout()?;
5032      if token.get_catcode() != Catcode::SPACE {
5033        invoke_token(&token)?;
5034      }
5035    }
5036    Ok(())
5037  })?;
5038  // Perl Package.pm:996: RawTeX ends in vertical mode, whatever mode it began in (mid-paragraph too); a caller that
5039  // runs inside a paragraph digests through `Digest` instead, which leaves only a horizontal mode it entered.
5040  leave_horizontal_internal();
5041  Ok(())
5042}
5043
5044/// The token that takes the place of an expansion made here, in the stomach (Perl Stomach.pm:204-209 `invokeToken`
5045/// re-reads with `readXToken` and invokes what it finds), unless that token ends the alignment cell being read.
5046///
5047/// A tab or `\cr` that an expansion yields at `align_state` 0 ends the cell (tex.web §789 `insert_v_part`): the gullet
5048/// takes it as the column's end, raises the count to 1000000, and puts it back behind the column's v-part
5049/// (`handle_template`). The cell's own reader then meets the v-part and, after it, the end. When the column has no
5050/// v-part (`\omit`, so every `\multicolumn` cell), the end itself is the next token, and it comes back to this
5051/// re-read instead: it goes back to the cell's reader, which ends the column on it, rather than being digested as a
5052/// stray `&`. A cell reader hands a protected macro to the stomach unexpanded (it reads as Perl's `readXToken(0)`
5053/// does), so `\protected\def\cellx#1{& #1}` after a `\multicolumn` (sgamex.sty:56-58) reaches this path; pdflatex
5054/// gives three cells (witness 2410.16600), and Perl too only because its `\multicolumn` keeps a v-part
5055/// (OXIDIZED_DESIGN_DIVERGENCES #474). Guard:
5056/// `perfect_kernel_batch63::protected_tab_after_multicolumn_ends_the_cell`.
5057fn read_x_token_after_expansion() -> Result<Option<Token>> {
5058  let next = gullet::read_x_token(None, false, None)?;
5059  if let Some(token) = next
5060    && align_group_count() == 1_000_000
5061    && has_reading_alignment()
5062    && gullet::is_column_end(&token).is_some()
5063  {
5064    gullet::unread_one(token);
5065    return Ok(None);
5066  }
5067  Ok(next)
5068}
5069
5070/// tex.web §1127 `align_error`: a tab, `\cr` or `\span` that reaches the stomach while the alignment count is not 0
5071/// — the cell left a brace unbalanced, so the gullet did not take it for the cell's end (§342) — gets the brace TeX
5072/// supposes was omitted: count −1 or −2 (the cell's `}` closed one more group than it opened, `a} &=& b`) inserts a
5073/// `{` ("Missing { inserted"), count +1 or +2 (`{a & b}`, `\textbf{a & b}`) a `}` ("Missing } inserted"), and the
5074/// column end is read again behind it, now at count 0, so the v-part runs and the cell ends as the template says
5075/// (§789). The ledger moves as TeX's does: `align_error` steps the count towards 0 and `ins_error`'s `back_input`
5076/// (§325) retracts the inserted brace, which counts again when it is read. A larger count (`abs(align_state)>2`,
5077/// "Misplaced &") is left to the cell's reader, as is a count past the v-part's 1000000 (the column's own end).
5078/// Before, the column end was taken for the cell's end with no v-part: an eqnarray/amsmath cell left its template's
5079/// math open (pdflatex 1 error, ours 17: "Attempt to close a group that switched to mode math"), and a tabular cell's
5080/// `{a & b}` lost `a` without a word. Perl has no `align_error` (KNOWN_PERL_ERRORS #923). Whether it fired. Guards
5081/// `perfect_kernel_batch70b::{eqnarray_stray_close_brace_inserts_a_left_brace,
5082/// tabular_open_brace_at_a_cell_end_inserts_a_right_brace}`.
5083pub fn align_error(token: &Token) -> Result<bool> {
5084  let count = align_group_count();
5085  if count == 0
5086    || count.abs() > 2
5087    || !has_reading_alignment()
5088    || gullet::is_column_end(token).is_none()
5089    || !is_tab_mark_command(token)
5090  {
5091    return Ok(false);
5092  }
5093  if count < 0 {
5094    Error!(
5095      "expected",
5096      "{",
5097      "Missing { inserted",
5098      "I've put in what seems to be necessary to fix the current column of the current alignment."
5099    );
5100    set_align_group_count(count + 1);
5101    gullet::unread_one(*token);
5102    gullet::unread_one(T_BEGIN!());
5103  } else {
5104    Error!(
5105      "expected",
5106      "}",
5107      "Missing } inserted",
5108      "I've put in what seems to be necessary to fix the current column of the current alignment."
5109    );
5110    set_align_group_count(count - 1);
5111    gullet::unread_one(*token);
5112    gullet::unread_one(T_END!());
5113  }
5114  Ok(true)
5115}
5116
5117/// Whether a column-end token reaches the stomach as the tab-mark command (tex.web's `cur_cmd=tab_mark`): an `&`
5118/// character means one unless a binding gave the character another meaning (LaTeXML lets non-active characters have
5119/// one): `\@index`'s entry, read as `\@wrindex` writes it under `\@sanitize`, lets `&` to `\&` (sect11.rs; TeX's
5120/// `&` is catcode 12 there), and a stray `&` deactivates itself to `\relax`. A control sequence is a column end only
5121/// by its meaning already (`gullet::is_column_end`).
5122fn is_tab_mark_command(token: &Token) -> bool {
5123  token.get_catcode() != Catcode::ALIGN
5124    || match lookup_digestable_definition(token) {
5125      None | Some(Stored::None) => true,
5126      Some(Stored::Constructor(defn)) => defn.cs == *token,
5127      Some(Stored::Token(meaning)) => meaning.get_catcode() == Catcode::ALIGN,
5128      Some(_) => false,
5129    }
5130}
5131
5132/// A token of a frontmatter field's stored value (its out-of-band provenance, `Token::prov`) was invoked: what it digests to
5133/// is that field's ink (`Document::absorb`'s field runs, OXIDIZED_DESIGN #715). What it consumed of the value is covered by
5134/// them (its arguments; a font switch or `\relax` before it that made no box), recorded in digestion order
5135/// (`token::field_ledger_push`, the box's `fieldSerial`), so a whole print is told from a fragment by every position of the
5136/// value (`gullet::field_cover_of`). Only while the field ledger is live: nothing is marked once the frontmatter placement
5137/// settled the field ink (`token::field_ledger_live`). Out of line: no token of a paper's body is a field's, so
5138/// [`invoke_token`] pays one test for it.
5139#[cold]
5140#[inline(never)]
5141fn note_field_token(token: &Token, result: &[Digested]) {
5142  let cover = if matches!(
5143    token.get_catcode(),
5144    Catcode::LETTER | Catcode::OTHER | Catcode::SPACE
5145  ) {
5146    let pos = crate::token::field_prov_pos(token.prov);
5147    crate::token::FieldCover {
5148      field: crate::token::field_prov_field(token.prov),
5149      start: pos,
5150      end:   pos + 1,
5151    }
5152  } else {
5153    gullet::field_cover_of(token.prov)
5154  };
5155  // (a rehearsal's notes on what its boxes do not hold: `token::FieldNotesHook`)
5156  if let Some(notes) = crate::token::field_notes_hook() {
5157    notes(
5158      token,
5159      cover,
5160      crate::token::FieldInvocation::Digested(result),
5161    );
5162  }
5163  if result.is_empty() {
5164    crate::token::field_cover_set_pending(cover);
5165  } else {
5166    let serial = crate::token::field_ledger_push(crate::token::field_cover_pending_merge(cover));
5167    for digested in result {
5168      if !digested.has_property(crate::document::FIELD_PROV_PROPERTY) {
5169        digested.try_set_property(crate::document::FIELD_PROV_PROPERTY, i64::from(token.prov));
5170        if let Some(serial) = serial {
5171          digested.try_set_property(crate::document::FIELD_SERIAL_PROPERTY, i64::from(serial));
5172        }
5173        crate::token::field_stamp_noted(digested);
5174      }
5175    }
5176  }
5177}
5178
5179/// Invoke a token
5180///
5181/// If it is a primitive or constructor, the definition will be invoked,
5182/// possibly arguments will be parsed from the Gullet.
5183/// Otherwise, the token is simply digested: turned into an appropriate box.
5184/// Returns a list of boxes/whatsits.
5185pub fn invoke_token(input_token: &Token) -> Result<Vec<Digested>> {
5186  // The choke point: a cell's `}` and any `}` inside a `\noalign` body pass it, clearing the live put-back mark, and a
5187  // put-back `}` is deleted here at the formula's own math shift ([`PUT_BACK_BRACE`]). A loop's own closing `}` (the
5188  // `\noalign` loop, tex_tables.rs:1291; the box-body loop, base_utilities.rs:7083) does not pass it and leaves the
5189  // live serial set, which is harmless: the frame holding the mark closes with that `}` (probe B1).
5190  if take_put_back_mark(input_token) && delete_put_back_brace()? {
5191    return Ok(Vec::new());
5192  }
5193  // Perf: Token is Copy (SymStr + Catcode, ~5 bytes), so we pass by value
5194  // directly instead of wrapping in Cow<Token>.
5195  let mut maybe_token: Option<Token> = Some(*input_token);
5196  let mut result: Vec<Digested> = Vec::new();
5197  // INVOKE:
5198  while let Some(token) = maybe_token.take() {
5199    if align_error(&token)? {
5200      return Ok(Vec::new());
5201    }
5202    // RAII guard: auto-pops current_token on scope exit (even on early return/panic)
5203    let _token_guard = local_current_token_guard(token);
5204    {
5205      stomach_mut!().token_stack.push(token);
5206    }
5207    if { stomach!().token_stack.len() } > MAXSTACK {
5208      fatal!(
5209        Stomach,
5210        Recursion,
5211        s!(
5212          "Excessive recursion(?): Tokens on stack: {:?}",
5213          stomach!().token_stack
5214        )
5215      );
5216    }
5217    result.clear();
5218
5219    // Rust notes: It would be ideal if we could unify the cases for (Primtive, Constructor,
5220    // MathPrimitive), as well as (Expandable, Conditional) since the
5221    // API is identical. However, as the types are different, Rust
5222    // constrains us here, we need separate match arms for each
5223    // distinctly typed enum case.
5224    let digestable_def = lookup_digestable_definition(&token);
5225    match digestable_def {
5226      None | Some(Stored::None) => {
5227        result = invoke_token_undefined(&token)?;
5228      },
5229      Some(Stored::Token(meaning)) => {
5230        // Common case
5231        let cc = meaning.get_catcode();
5232        if cc == Catcode::CS {
5233          result = invoke_token_undefined(&token)?;
5234        } else if cc.is_absorbable() {
5235          let starts_paragraph = matches!(cc, Catcode::LETTER | Catcode::OTHER)
5236            && !lookup_bool_sym(crate::pin!("IN_MATH"));
5237          if starts_paragraph && back_input_for_new_graf(token) {
5238            // `\everypar`, then this token again, in horizontal mode.
5239          } else if let Some(digested) = invoke_token_simple(meaning)? {
5240            result.push(digested);
5241          }
5242        } else {
5243          // Perl L187-189: deactivate T_ALIGN to prevent error flood in tables
5244          if token.get_catcode() == Catcode::ALIGN
5245            && let Some(relax_meaning) = lookup_meaning(&T_CS!("\\relax"))
5246          {
5247            assign_meaning(&token, relax_meaning, Some(Scope::Local));
5248          }
5249          let message = s!(
5250            "The token {:?} (catcode {:?}) should never reach Stomach!",
5251            token,
5252            cc
5253          );
5254          Error!("misdefined", token, &message);
5255          if let Some(digested) = invoke_token_simple(meaning)? {
5256            result.push(digested);
5257          }
5258        }
5259      },
5260      Some(Stored::Expandable(meaning)) => {
5261        // A math-active character will (typically) be a macro,
5262        // but it isn't expanded in the gullet, but later when digesting, in math mode
5263        // (? I think)
5264        let mut invoked_meaning = meaning.invoke(false)?;
5265        crate::token::inherit_field_prov(token.prov, &mut invoked_meaning);
5266        if !invoked_meaning.is_empty() {
5267          {
5268            gullet::unread(invoked_meaning);
5269          }
5270        }
5271        // replace the token by it's expansion!!!
5272        maybe_token = read_x_token_after_expansion()?;
5273        {
5274          stomach_mut!().token_stack.pop();
5275        }
5276        drop(_token_guard); // expire current token via RAII
5277        continue;
5278      },
5279      Some(Stored::Conditional(meaning)) => {
5280        // Conditionals are "expandable", use the regular invoke.
5281        let invoked_meaning = meaning.invoke(false)?;
5282        gullet::unread(invoked_meaning);
5283        maybe_token = read_x_token_after_expansion()?;
5284        {
5285          stomach_mut!().token_stack.pop();
5286        }
5287        drop(_token_guard); // expire current token via RAII
5288        continue;
5289      },
5290      Some(Stored::Constructor(meaning))
5291        if starts_new_graf(&meaning.get_cs()) && back_input_for_new_graf(token) =>
5292      {
5293        // `\hskip`, `\vrule`, `\valign`: `\everypar`, then this token again, in horizontal mode (tex.web §1090).
5294      },
5295      Some(Stored::Constructor(meaning)) => {
5296        // Perl Stomach.pm L187-189: deactivate T_ALIGN to `\relax` LOCAL
5297        // on first non-table encounter, to prevent error flood. The
5298        // existing guard at the Stored::Token branch (above) only fires
5299        // when `&` has been Let'd to another token, but the `&`
5300        // CC_ALIGN char-token is bound to a Constructor (TeX_Tables.pool
5301        // L49: `DefConstructorI('&', undef, sub { Error('unexpected', '&',
5302        // $_[0], "Stray alignment \"&\"") })`), so it falls into THIS
5303        // branch instead. Without this guard, papers with multiple stray
5304        // `&` (e.g. astro-ph0107583's bibitem with unescaped `Hirose &
5305        // Osaki`) emit one Error per occurrence; Perl emits ONE total
5306        // because of the LOCAL `\relax` rebinding. Self-deactivate here
5307        // too so subsequent `&` invocations no-op.
5308        if token.get_catcode() == Catcode::ALIGN
5309          && let Some(relax_meaning) = lookup_meaning(&T_CS!("\\relax"))
5310        {
5311          assign_meaning(&token, relax_meaning, Some(Scope::Local));
5312        }
5313        // `meaning` IS the state table's `Rc<Constructor>`, so hand it to the
5314        // Whatsit rather than letting `invoke_primitive` deep-clone the
5315        // definition once per invocation (see `Constructor::invoke_primitive_shared`).
5316        result = Constructor::invoke_primitive_shared(&meaning)?;
5317        if !meaning.is_prefix() {
5318          clear_prefixes(); // Clear prefixes unless we just set one.
5319        }
5320      },
5321      Some(Stored::Primitive(meaning))
5322        if starts_new_graf(&meaning.get_cs()) && back_input_for_new_graf(token) =>
5323      {
5324        // `\everypar`, then this token again, in horizontal mode (tex.web §1090).
5325      },
5326      Some(Stored::Primitive(meaning)) => {
5327        // Otherwise, a normal primitive or constructor
5328        result = meaning.invoke_primitive()?;
5329        // After a prefix TeX reads on to the next non-blank non-relax token
5330        // (tex.web §1211, §404), so a `\relax` there keeps the prefixes:
5331        // catoptions' `\protected\relax\def` (its `\robust@def*`, :375-381)
5332        // defines a protected macro. Perl clears them (Stomach.pm:212), and the
5333        // unprotected `\cpt@newv@riables` ran inside an `\edef`: 70 errors per
5334        // `\usepackage{catoptions}` (keyval2e, concepts, ltxkeys). KPE #223.
5335        if !meaning.is_prefix() && !(has_tex_prefixes() && *meaning.get_cs() == T_CS!("\\relax")) {
5336          clear_prefixes(); // Clear prefixes unless we just set one.
5337        }
5338      },
5339      Some(Stored::MathPrimitive(meaning)) => {
5340        // Copy of regular Primitive
5341        // Otherwise, a normal primitive or constructor
5342        result = meaning.invoke_primitive()?;
5343        if !meaning.is_prefix() {
5344          clear_prefixes(); // Clear prefixes unless we just set one.
5345        }
5346      },
5347      Some(Stored::Register(meaning)) => {
5348        // Registers are special primitives
5349        result = meaning.invoke_primitive()?;
5350        if !meaning.is_prefix() {
5351          clear_prefixes(); // Clear prefixes unless we just set one.
5352        }
5353      },
5354      meaning => {
5355        // Perl: Error + makeMisdefinedError (non-fatal). Don't crash.
5356        Error!(
5357          "misdefined",
5358          token,
5359          s!("Unexpected object in Stomach: {:?}", meaning)
5360        );
5361      },
5362    }
5363    if token.prov != 0 && crate::token::field_ledger_live() {
5364      note_field_token(&token, &result);
5365    }
5366    // _token_guard drops here, auto-expiring current token
5367    break;
5368  }
5369  stomach_mut!().token_stack.pop();
5370  Ok(result)
5371}
5372
5373fn invoke_token_undefined(token: &Token) -> Result<Vec<Digested>> {
5374  // The LaTeX format may not be loaded yet (a document may use a kernel CS
5375  // before `\documentclass` — real LaTeX has no "before the kernel"). If this
5376  // is a kernel CS, pull the format in and re-digest instead of stubbing it as
5377  // `<ltx:ERROR/>`. Fires at most once per session; see
5378  // `binding::kernel_autoload`. Same retry shape as the `\ifsomething` arm below.
5379  if crate::binding::kernel_autoload::try_autoload(token) {
5380    gullet::unread_one(*token); // Retry, now that the kernel is in state.
5381    return Ok(Vec::new());
5382  }
5383  // An environment the class redefined, whose begin defines this command for its body, but whose definition the
5384  // kernel's lock refused (`kernel_autoload::try_refused_environment_definition`).
5385  if crate::binding::kernel_autoload::try_refused_environment_definition(token) {
5386    gullet::unread_one(*token);
5387    return Ok(Vec::new());
5388  }
5389  // a stand-in named for the undefined name (`kernel_autoload::undefined_fallback`, OXIDIZED_DESIGN #734)
5390  if let Some(stand_in) = crate::binding::kernel_autoload::undefined_fallback(token) {
5391    gullet::unread_one(stand_in);
5392    return Ok(Vec::new());
5393  }
5394  // a family the ar5iv preload provides on first use (`kernel_autoload::provide_on_first_use`)
5395  if crate::binding::kernel_autoload::provide_on_first_use(token)? {
5396    gullet::unread_one(*token);
5397    return Ok(Vec::new());
5398  }
5399  let cs = token.with_cs_name(|cs| String::from(cs));
5400  // Gate the undefined-CS summary tally and the Error! emission by
5401  // SUPPRESS_UNDEFINED_ERRORS. During expl3-code.tex raw load we install
5402  // the ERROR stub silently — forward references resolve when subsequent
5403  // post-load fixups rebind the canonical CS (see expl3_sty.rs L161-167
5404  // for \iow_wrap stubs that overwrite ERROR after the raw load). Mirrors
5405  // the existing gate at state.rs::generate_error_stub L1018-L1030.
5406  let suppressed = lookup_bool_sym(crate::pin!("SUPPRESS_UNDEFINED_ERRORS"));
5407  if !suppressed {
5408    note_status(LogStatus::Undefined, Some(&cs));
5409  }
5410
5411  // To minimize chatter, go ahead and define it...
5412  if cs.starts_with("\\if") {
5413    // Apparently an \ifsomething ???
5414    let name = cs.replace("\\if", "");
5415    if !suppressed {
5416      let message = s!("The token {} is not defined.", token.stringify());
5417      Error!(
5418        "undefined",
5419        token,
5420        &message,
5421        "Defining it now as with \\newif"
5422      );
5423    }
5424    // install stub definitions for new conditional
5425    install_definition(
5426      Expandable::new(
5427        T_CS!(s!("\\{}true", name)),
5428        None,
5429        Tokens!(T_CS!("\\let"), T_CS!(&cs), T_CS!("\\iftrue")).into(),
5430        None,
5431      )?,
5432      None,
5433    );
5434    install_definition(
5435      Expandable::new(
5436        T_CS!(s!("\\{}false", name)),
5437        None,
5438        Tokens!(T_CS!("\\let"), T_CS!(cs), T_CS!("\\iffalse")).into(),
5439        None,
5440      )?,
5441      None,
5442    );
5443
5444    let_i(token, &T_CS!("\\iffalse"), None);
5445    gullet::unread_one(*token); // Retry
5446    Ok(Vec::new())
5447  } else {
5448    if !suppressed {
5449      let message = s!("The token {} is not defined.", token.stringify());
5450      Error!(
5451        "undefined",
5452        token,
5453        &message,
5454        "Defining it now as <ltx:ERROR/>"
5455      );
5456    }
5457    install_definition(
5458      Constructor {
5459        cs: *token,
5460        paramlist: None,
5461        replacement: Some(Rc::new(move |document, _args, _props| {
5462          document.make_error("undefined", &cs)
5463        })),
5464        ..Constructor::default()
5465      },
5466      Some(Scope::Global),
5467    );
5468    // Perl: unread the token and return empty, so the outer loop re-reads
5469    // and dispatches through the normal path (with the newly installed stub).
5470    // This ensures gullet-level side effects (filtering, expansion) are applied.
5471    gullet::unread_one(*token);
5472    Ok(Vec::new())
5473  }
5474}
5475
5476fn invoke_token_simple(meaning: Token) -> Result<Option<Digested>> {
5477  let cc = meaning.get_catcode();
5478  let font = lookup_font();
5479  // token-locators: the leaf char box's exact source position comes from the
5480  // token's origin handle — the position that survived expansion to digestion
5481  // (Experiments 1–3 showed it cannot be re-derived from the mouth here, which
5482  // is past the construct). `None` → `Tbox::new` falls back to the gullet's
5483  // current locator (the eating-disorder heuristic). See SOURCE_PROVENANCE §3.1.1.
5484  // Stamp a leaf box only from a *genuine* (read-from-source) origin. An
5485  // inherited origin — a macro's expansion attributed to its call site, e.g.
5486  // `\section`'s structural body literals at the `\section` column — must not
5487  // become a located leaf, or box-level `get_locator()` aggregation would widen
5488  // a construct past its content (the `\section{Intro}` title would start at the
5489  // command, not at "Intro"). The inherited origin still rides the token, so
5490  // `constructor::child_span`'s genuine-first scan can recover it as the
5491  // fallback for the origin-less case (`\today`). See SOURCE_PROVENANCE §3.1.3.
5492  #[cfg(feature = "token-locators")]
5493  let origin_loc: Option<crate::common::locator::Locator> =
5494    crate::token::get_token_origin(meaning.loc)
5495      .filter(|o| !o.inherited)
5496      .map(|o| {
5497        crate::common::arena::with(o.source, |s| {
5498          crate::common::locator::Locator::new(s, o.line, o.col, o.line, o.col)
5499        })
5500      });
5501  #[cfg(not(feature = "token-locators"))]
5502  let origin_loc: Option<crate::common::locator::Locator> = None;
5503  match cc {
5504    Catcode::SPACE => {
5505      // A space after a prefix is skipped, not typeset (tex.web §1211, §404).
5506      if has_tex_prefixes() {
5507        return Ok(None);
5508      }
5509      clear_prefixes(); // Perl Stomach.pm line 234: prefixes shouldn't apply here.
5510      // Perl: if($STATE->lookupValue('MODE') =~ /(?:math|vertical)$/) { return (); }
5511      if arena::with(lookup_mode(), |mode| {
5512        mode.ends_with("math") || mode.ends_with("vertical")
5513      }) {
5514        Ok(None)
5515      } else {
5516        enter_horizontal();
5517        // An interword space is glue (tex.web §1041 `app_space`): `\unskip` removes it, `\lastskip` reads it
5518        // (KNOWN_PERL_ERRORS #436). Perl's space box carries no `isSkip` (Stomach.pm:244-250), so `a \unskip,`
5519        // kept the space before the comma (witness 2605.02925, its `\and` author list).
5520        let mut properties = HashMap::default();
5521        properties.insert("isSkip", Stored::Bool(true));
5522        Ok(Some(Digested::from(Tbox::new(
5523          meaning.get_sym(),
5524          font,
5525          origin_loc,
5526          Tokens!(meaning),
5527          properties,
5528        ))))
5529      }
5530    },
5531    Catcode::COMMENT => {
5532      // Perl Stomach.pm lines 241-244: decode comment via font encoding
5533      let decoded = font::decode_string(meaning.get_sym(), None, true);
5534      let comment = arena::with(decoded, |s| {
5535        // However, spaces normally would have be digested away as positioning...
5536        // Replace NBSP + combining strikethrough (OT1 space position) with actual space
5537        s.replace("\u{00A0}\u{0335}", " ")
5538      });
5539      // Perl: returns LaTeXML::Core::Comment->new($comment)
5540      // which gets absorbed as an XML comment node via Document::insertComment
5541      Ok(Some(Digested::from(Comment(comment))))
5542    },
5543    _ => {
5544      clear_prefixes(); // Perl Stomach.pm line 247: prefixes shouldn't apply here.
5545      // Perl: check mathcode for IN_MATH characters (Stomach.pm lines 248-251)
5546      // In Perl, all math chars go through decodeMathChar which decodes via
5547      // the font encoding. In Rust, Tbox::new already handles IN_MATH:
5548      // it sets mode="math", looks up math_token_attributes for role/meaning/name,
5549      // and specializes the font. This produces the correct LaTeXML-level properties.
5550      // The mathchar parsing handles non-ASCII chars needing font map lookup.
5551      // TODO: Use for chars where font-encoding glyph differs from input.
5552      // Perl L248-257: if IN_MATH && mathcode → decodeMathChar (math box)
5553      // else → enterHorizontal + text box (covers non-math AND math-but-no-mathcode)
5554      // A math-active character ("8000) digested as itself has no math character to decode; it is the plain character:
5555      // a delimiter (`digest_as_delimiter`), or one whose active meaning is undefined and self-inserts
5556      // (`lookup_digestable_definition`, braket's `\Pr{A|B}`, 1602.01342). `decode_math_char` of "8000 is class 8, which
5557      // dropped the character here before, and is Γ in Perl (KNOWN_PERL_ERRORS #495).
5558      if lookup_bool_sym(crate::pin!("IN_MATH"))
5559        && let Some(mathcode) = lookup_mathcode_sym(meaning.get_sym())
5560        && mathcode != 0x8000
5561      {
5562        return crate::common::mathchar::decode_math_char_for_stomach(mathcode, meaning);
5563      }
5564      // Fallthrough: either not in math, or in math but no mathcode
5565      enter_horizontal();
5566      let text = font::decode_string(meaning.get_sym(), None, true);
5567      // A raw `\font`'s slot is measured from its TFM (`Tbox::with_tfm_slot`).
5568      let slot = meaning.with_str(|s| {
5569        let mut chars = s.chars();
5570        match (chars.next(), chars.next()) {
5571          (Some(c), None) => u32::from(c),
5572          _ => u32::MAX,
5573        }
5574      });
5575      Ok(Some(Digested::from(
5576        Tbox::new(
5577          text,
5578          None,
5579          origin_loc,
5580          Tokens!(meaning),   // tokens
5581          HashMap::default(), // properties
5582        )
5583        .with_tfm_slot(slot),
5584      )))
5585    },
5586  }
5587}
5588
5589pub fn set_stomach(new_stomach: Stomach) {
5590  let mut singleton = stomach_mut!();
5591  *singleton = new_stomach;
5592}
5593pub fn clone_box_list() -> Vec<Digested> { stomach!().box_list.clone() }
5594
5595/// get the current boxing level
5596pub fn get_boxing_level() -> usize { stomach!().boxing.len() }
5597
5598/// ScriptLevel is similar to boxing level, but relative to current Math mode's level
5599///
5600/// This is used for the scriptpos attribute to recognize overlapping sccripts.
5601/// Making it relative to the math's level avoids unnecessary changes
5602pub fn get_script_level() -> usize {
5603  let boxlevel = get_boxing_level();
5604  with_value("script_base_level", |val_opt| {
5605    if let Some(Stored::Int(prevlevel)) = val_opt {
5606      boxlevel - (*prevlevel as usize) + 1
5607    } else {
5608      boxlevel
5609    }
5610  })
5611}
5612
5613#[cfg(test)]
5614mod resource_fatal_teardown_tests {
5615  use super::{egroup, endgroup};
5616  use crate::{
5617    common::error::{LogStatus, Result, get_status, initialize_report, resource_fatal_latched},
5618    state::{Scope, assign_value, push_frame},
5619  };
5620
5621  /// Once a resource Fatal is latched the document is aborted and the
5622  /// recovery pass only drains what is pending; the group closers it meets
5623  /// on a mode-switch frame (a box body the fuse interrupted) must not be
5624  /// reported — 11-13 non-deterministic `Attempt to close a group that
5625  /// switched to mode` lines after glossaries-user's MemoryBudget Fatal
5626  /// (sweep 82) made a phantom regression. Before the latch the same closer
5627  /// IS an error (Perl Stomach.pm:347-349).
5628  #[test]
5629  fn group_closers_are_silent_once_a_resource_fatal_is_latched() {
5630    initialize_report();
5631    // The shape the fuse leaves behind: a mode-switch frame on top.
5632    push_frame();
5633    assign_value("BOUND_MODE", "restricted_horizontal", Some(Scope::Local));
5634    let before = get_status(LogStatus::Error);
5635    let _ = egroup();
5636    assert_eq!(
5637      get_status(LogStatus::Error),
5638      before + 1,
5639      "a closer on a mode-switch frame is an error before any Fatal"
5640    );
5641    fn raise() -> Result<()> {
5642      Fatal!(Timeout, MemoryBudget, "Memory budget exceeded (synthetic)");
5643    }
5644    let _ = raise();
5645    assert_eq!(
5646      get_status(LogStatus::Fatal),
5647      1,
5648      "the Fatal itself is reported"
5649    );
5650    let after_fatal = get_status(LogStatus::Error);
5651    let _ = egroup();
5652    let _ = endgroup();
5653    assert_eq!(
5654      get_status(LogStatus::Error),
5655      after_fatal,
5656      "post-Fatal draining of the closers reports nothing"
5657    );
5658    initialize_report();
5659  }
5660
5661  /// A non-resource Fatal (a Stomach-target box ceiling) does not set the resource latch the frontmatter probes
5662  /// unlatch, but it mutes the closers all the same: Perl ignores every Error after any Fatal (Common/Error.pm:315,
5663  /// :362; 1702.08816's 96 closer Errors after `Fatal:Stomach:Recursion`).
5664  #[test]
5665  fn non_resource_fatals_mute_closers_too() {
5666    initialize_report();
5667    push_frame();
5668    assign_value("BOUND_MODE", "restricted_horizontal", Some(Scope::Local));
5669    fn raise() -> Result<()> {
5670      Fatal!(Stomach, Recursion, "Infinite digestion loop (synthetic)");
5671    }
5672    let _ = raise();
5673    assert!(
5674      !resource_fatal_latched(),
5675      "a Stomach-target Fatal is not a resource Fatal"
5676    );
5677    let before = get_status(LogStatus::Error);
5678    let muted_before = crate::common::error::muted_errors();
5679    let _ = egroup();
5680    assert_eq!(
5681      (
5682        get_status(LogStatus::Error),
5683        crate::common::error::muted_errors()
5684      ),
5685      (before, muted_before + 1),
5686      "the closer errs, silently, after any Fatal"
5687    );
5688    initialize_report();
5689  }
5690}
5691
5692#[cfg(test)]
5693mod memory_cap_tests {
5694  use std::time::{Duration, Instant};
5695
5696  use super::{
5697    CONVERSION_DEADLINE, ConversionDeadline, apply_memory_ceiling, box_bytes_budget,
5698    box_bytes_runaway_message, box_count_cap, box_count_runaway_message, check_timeout,
5699    check_timeout_now, resolve_rss_cap, set_memory_cap, set_timeout, soft_cap_from_ceiling,
5700    soft_yield_urgency, spill_mark, take_streaming_restart_signal,
5701  };
5702  use crate::common::error::initialize_report;
5703
5704  // The box-list ceilings are memory ceilings, so they must ride the SAME
5705  // `--max-memory` knob as the RSS fuse — including its "0 = no limit" meaning.
5706  // They were hardcoded `const`s (2 M boxes / 3.2 GB estimate) read
5707  // unconditionally, which made `--max-memory=0` a documented lie: the binary
5708  // prints "memory limiting disabled entirely" and then Fatal'd on a memory
5709  // ceiling no flag could raise. Witness: a ~10 000-page notes document
5710  // (Nasser Abbasi, rc4 report 2026-07-28) died on the byte budget after 8 h at
5711  // ~58 GB RSS having explicitly passed `--max-memory=0`.
5712  #[test]
5713  fn box_ceilings_follow_the_memory_knob() {
5714    // Stock ceiling reproduces the historical fixed values.
5715    apply_memory_ceiling(6144);
5716    assert_eq!(
5717      box_count_cap(),
5718      Some(1_999_933),
5719      "≈ the validated 2 M boxes"
5720    );
5721    let budget = box_bytes_budget().expect("stock ceiling has a byte budget");
5722    assert_eq!(budget, 3_221_225_472, "≈ the historical 3.2 GB");
5723
5724    // `--max-memory=0` lifts BOTH — that is the whole point of the flag.
5725    apply_memory_ceiling(0);
5726    assert_eq!(box_count_cap(), None, "--max-memory=0 lifts the count cap");
5727    assert_eq!(
5728      box_bytes_budget(),
5729      None,
5730      "--max-memory=0 lifts the byte budget"
5731    );
5732
5733    // A tighter ceiling scales them down rather than leaving them at the
5734    // stock value (which would sit far ABOVE the requested ceiling).
5735    apply_memory_ceiling(2000);
5736    assert!(box_count_cap().unwrap() < 1_999_933);
5737    assert!(box_bytes_budget().unwrap() < budget);
5738
5739    // The byte budget stays UNDER the RSS fuse, so on Linux the portable
5740    // estimate still fires first for an accurately-estimated runaway.
5741    assert!(box_bytes_budget().unwrap() < resolve_rss_cap().unwrap() as usize);
5742
5743    set_memory_cap(None);
5744  }
5745
5746  // The single knob must reach the fuse through `apply_memory_ceiling`, which is
5747  // what every conversion path calls. `--max-memory=0` has to leave NO ceiling:
5748  // the plain path, the `--server` forked body child and the in-process fallback
5749  // all rely on this one function, and the LSP pair used to skip it entirely.
5750  //
5751  // The env-precedence half is deliberately NOT asserted here: proving it needs
5752  // `set_var`, and this workspace has a standing rule against touching the
5753  // process env from tests (a concurrent read races glibc's getenv). It holds by
5754  // construction instead — `apply_memory_ceiling` sets the override
5755  // unconditionally, and `resolve_rss_cap` only consults the env when no
5756  // override is present.
5757  #[test]
5758  fn apply_memory_ceiling_drives_the_fuse() {
5759    apply_memory_ceiling(6144);
5760    assert_eq!(resolve_rss_cap(), Some(4608 * 1024 * 1024));
5761
5762    // 0 means "no limit", not "abort immediately".
5763    apply_memory_ceiling(0);
5764    assert_eq!(resolve_rss_cap(), None, "--max-memory=0 leaves no ceiling");
5765
5766    // A tight ceiling is honored rather than ignored in favour of the old
5767    // built-in 4.5 GB default, which sat far ABOVE such a ceiling.
5768    apply_memory_ceiling(2000);
5769    assert_eq!(resolve_rss_cap(), Some(1500 * 1024 * 1024));
5770
5771    set_memory_cap(None);
5772  }
5773
5774  /// A rare poller's check (once a page, the render workers' parent at 10 Hz) reads the exact clock even while a
5775  /// watchdog keeps the coarse one: just past the deadline, before the watchdog's next publish, `check_timeout` (coarse)
5776  /// still passes and `check_timeout_now` stops. Run here, it is the child (a watchdog of its own).
5777  #[test]
5778  fn check_timeout_now_stops_on_its_first_call_past_the_deadline() {
5779    const CHILD: &str = "LATEXML_CHECK_TIMEOUT_NOW_CHILD";
5780    if std::env::var_os(CHILD).is_some() {
5781      initialize_report();
5782      let _watchdog = crate::watchdog::Watchdog::new(60);
5783      let started = Instant::now();
5784      while crate::watchdog::coarse_now_ns().is_none() {
5785        assert!(started.elapsed() < Duration::from_secs(10), "no watchdog");
5786        std::thread::sleep(Duration::from_millis(1));
5787      }
5788      // Set behind the watchdog's back (no wake at it); retried when a publish lands between, at most once a poll.
5789      for _ in 0..20 {
5790        let published = crate::watchdog::coarse_now_ns();
5791        let at = Instant::now() + Duration::from_millis(1);
5792        CONVERSION_DEADLINE.with(|d| {
5793          d.set(Some(ConversionDeadline {
5794            at,
5795            off_at_set: crate::watchdog::time_off_the_clock(),
5796            coarse_ns: crate::watchdog::nanos_since_epoch(at),
5797          }))
5798        });
5799        std::thread::sleep(Duration::from_millis(5));
5800        let coarse = check_timeout().map_err(|e| format!("{e:?}"));
5801        let exact = check_timeout_now().map_err(|e| format!("{e:?}"));
5802        set_timeout(0);
5803        if crate::watchdog::coarse_now_ns() == published {
5804          assert!(coarse.is_ok(), "the coarse check stopped early: {coarse:?}");
5805          assert!(
5806            exact
5807              .as_ref()
5808              .is_err_and(|e| e.contains("Conversion timed out")),
5809            "{exact:?}"
5810          );
5811          eprintln!("checked: coarse passes, exact stops");
5812          return;
5813        }
5814      }
5815      panic!("the coarse clock moved under every try");
5816    }
5817    let out = std::process::Command::new(std::env::current_exe().unwrap())
5818      .args([
5819        "stomach::memory_cap_tests::check_timeout_now_stops_on_its_first_call_past_the_deadline",
5820        "--exact",
5821        "--nocapture",
5822        "--test-threads=1",
5823      ])
5824      .env(CHILD, "1")
5825      .output()
5826      .unwrap();
5827    let stderr = String::from_utf8_lossy(&out.stderr);
5828    assert_eq!(out.status.code(), Some(0), "{stderr}");
5829    assert!(
5830      stderr.contains("checked: coarse passes, exact stops"),
5831      "{stderr}"
5832    );
5833  }
5834
5835  /// The fuse's Fatal names `--max-memory` only when that flag set the fuse: `cortex_worker`'s fuse is its
5836  /// `--max-rss-mb` (`set_memory_cap`), where "75% of --max-memory=N" was wrong arithmetic (row R CORTEXRSS).
5837  #[test]
5838  fn the_fuse_fatal_names_the_knob_that_set_it() {
5839    initialize_report();
5840    let fuse_message = || {
5841      (0..2048)
5842        .find_map(|_| check_timeout().err())
5843        .map(|e| format!("{e:?}"))
5844        .expect("an RSS above a 1 MiB fuse stops within two samples")
5845    };
5846    apply_memory_ceiling(2); // a 1 MiB fuse
5847    let cli = fuse_message();
5848    assert!(
5849      cli.contains("> cap 1 MB (the cooperative fuse at 75% of --max-memory=2)"),
5850      "{cli}"
5851    );
5852    set_memory_cap(Some(1024 * 1024));
5853    let worker = fuse_message();
5854    assert!(
5855      worker.contains(
5856        "> cap 1 MB (the cooperative memory fuse). This document needs a larger ceiling."
5857      ) && !worker.contains("--max-memory"),
5858      "{worker}"
5859    );
5860    set_memory_cap(None);
5861    take_streaming_restart_signal();
5862    crate::watchdog::reset_memory_fatal();
5863  }
5864
5865  /// The box-list caps ride the same fuse, so their Fatals name `--max-memory` only when that flag set it too.
5866  #[test]
5867  fn the_box_cap_fatals_name_the_knob_that_set_it() {
5868    const CLI_ADVICE: &str = "raise --max-memory, or --max-memory=0 to lift the ceiling";
5869    apply_memory_ceiling(6144);
5870    assert_eq!(
5871      box_count_runaway_message(2_000_000, 1_999_933),
5872      format!(
5873        "Box-list runaway: 2000000 accumulated boxes exceeded the hard cap of 1999933 (unbounded digestion with \
5874         no detectable cycle); {CLI_ADVICE}"
5875      )
5876    );
5877    let lower_bound = format!(
5878      "NOTE: the estimate is a LOWER BOUND (each box is walked at most {} nodes deep), so true RSS at this point is \
5879       typically several times larger",
5880      crate::digested::EB_BUDGET
5881    );
5882    assert_eq!(
5883      box_bytes_runaway_message(3_300_000_000, 250_000, 3_221_225_472),
5884      format!(
5885        "Box-list memory runaway: ~3300 MB estimated across 250000 boxes exceeded the 3221 MB budget (unbounded \
5886         accumulation); {CLI_ADVICE}. {lower_bound}"
5887      )
5888    );
5889    set_memory_cap(Some(5376 * 1024 * 1024)); // cortex_worker's --max-rss-mb
5890    const FUSE_ADVICE: &str = "the cap rides the cooperative memory fuse; raise that ceiling";
5891    assert_eq!(
5892      box_count_runaway_message(2_333_158, 2_333_157),
5893      format!(
5894        "Box-list runaway: 2333158 accumulated boxes exceeded the hard cap of 2333157 (unbounded digestion with \
5895         no detectable cycle); {FUSE_ADVICE}"
5896      )
5897    );
5898    assert_eq!(
5899      box_bytes_runaway_message(3_800_000_000, 250_000, 3_758_096_384),
5900      format!(
5901        "Box-list memory runaway: ~3800 MB estimated across 250000 boxes exceeded the 3758 MB budget (unbounded \
5902         accumulation); {FUSE_ADVICE}. {lower_bound}"
5903      )
5904    );
5905    set_memory_cap(None);
5906  }
5907
5908  // The override path is thread-local (race-free across libtest threads) and
5909  // never reads the process-global env, so these assertions are deterministic.
5910  #[test]
5911  fn override_zero_disables_budget() {
5912    // `--max-memory=0` maps to `set_memory_cap(Some(0))`, which must resolve
5913    // to "no ceiling" — NOT a 0-byte cap that fatals every conversion.
5914    set_memory_cap(Some(0));
5915    assert_eq!(resolve_rss_cap(), None, "cap 0 disables the soft budget");
5916    // A positive override is honored verbatim.
5917    set_memory_cap(Some(1_000));
5918    assert_eq!(resolve_rss_cap(), Some(1_000));
5919    // Restore the default so we don't leak state onto other tests sharing
5920    // this thread.
5921    set_memory_cap(None);
5922  }
5923
5924  #[test]
5925  fn soft_cap_tracks_the_single_knob() {
5926    // 0 in → 0 out: `--max-memory=0` disables the soft fuse (and, via
5927    // resolve_rss_cap, the whole memory limit).
5928    assert_eq!(soft_cap_from_ceiling(0), 0);
5929    // The soft fuse always sits strictly below the hard ceiling (graceful
5930    // cooperative failure fires first), and reproduces the historical
5931    // ~4.5 GB-under-6 GiB relationship at the 6144 MiB default.
5932    let hard = 6144u64 * 1024 * 1024;
5933    let soft = soft_cap_from_ceiling(6144);
5934    assert_eq!(soft, 4608u64 * 1024 * 1024);
5935    assert!(soft < hard, "soft fuse must be below the hard ceiling");
5936    // It scales with the knob, so a tight ceiling still gets a cooperative
5937    // guard below it (fixing the old fixed-4.5 GB decoupling).
5938    assert!(soft_cap_from_ceiling(2000) < 2000 * 1024 * 1024);
5939    assert!(soft_cap_from_ceiling(20000) > 6144 * 1024 * 1024);
5940  }
5941
5942  /// The soft-yield floor waiver: waived at/above the watermark→fuse midpoint,
5943  /// applied below it, and never waived when either bound is absent or
5944  /// degenerate. Guards the safety valve `soft_yield_min_boxes` sits on — a
5945  /// pathological per-box footprint must regain per-seam yielding before the
5946  /// fuse fires inside one un-yielded window.
5947  #[test]
5948  fn soft_yield_floor_waiver_boundaries() {
5949    const MB: u64 = 1024 * 1024;
5950    let wm = Some(12_000 * MB); // the witness's watermark at --max-memory 48000
5951    let fuse = Some(36_000 * MB); // and its fuse; midpoint = 24_000 MB
5952    let mark_kb = 24_000 * 1024;
5953    assert!(
5954      !soft_yield_urgency(mark_kb - 1, wm, fuse),
5955      "below the midpoint the floor applies"
5956    );
5957    assert!(
5958      soft_yield_urgency(mark_kb, wm, fuse),
5959      "at the midpoint the floor is waived"
5960    );
5961    assert!(soft_yield_urgency(mark_kb + 1, wm, fuse), "above it too");
5962    // --max-memory=0 shapes: no fuse, no watermark, or fuse <= watermark
5963    // (a calibration LATEXML_SPILL_AT_MIB above the fuse) — never urgent.
5964    assert!(!soft_yield_urgency(u64::MAX / 1024, wm, None));
5965    assert!(!soft_yield_urgency(u64::MAX / 1024, None, fuse));
5966    assert!(
5967      !soft_yield_urgency(u64::MAX / 1024, fuse, wm),
5968      "fuse below watermark is degenerate"
5969    );
5970    // saturating_mul: an absurd rss_kb must not overflow into false.
5971    assert!(soft_yield_urgency(u64::MAX, wm, fuse));
5972  }
5973
5974  /// STRM: the spill mark is the watermark above the conversion's starting RSS, so a paper switches where it would
5975  /// alone; a grown process keeps a watermark below the fuse; a zero watermark marks every seam.
5976  #[test]
5977  fn spill_mark_is_the_watermark_above_the_conversions_start() {
5978    const GB: u64 = 1024 * 1024; // in KB
5979    let fuse = Some(36 * GB * 1024); // bytes; watermark a third, 12 GB
5980    assert_eq!(
5981      spill_mark(200 * 1024, 12 * GB, fuse),
5982      12 * GB,
5983      "under a fuse, the default watermark is the cap: two watermarks of headroom"
5984    );
5985    assert_eq!(spill_mark(0, 12 * GB, fuse), 12 * GB);
5986    assert_eq!(
5987      spill_mark(20 * GB, 12 * GB, fuse),
5988      12 * GB,
5989      "two watermarks below the fuse"
5990    );
5991    assert_eq!(
5992      spill_mark(200 * 1024, 4 * GB, fuse),
5993      4 * GB + 200 * 1024,
5994      "a smaller watermark moves with the conversion's start"
5995    );
5996    assert_eq!(
5997      spill_mark(20 * GB, 12 * GB, None),
5998      32 * GB,
5999      "no fuse, no cap"
6000    );
6001    assert_eq!(
6002      spill_mark(1024, 30 * GB, fuse),
6003      30 * GB,
6004      "a watermark past half the fuse stays itself"
6005    );
6006    assert_eq!(spill_mark(5 * GB, 0, fuse), 0);
6007  }
6008}