Skip to main content

latexml_core/common/
error.rs

1use std::{
2  borrow::Cow,
3  cell::RefCell,
4  error::Error as ErrorTrait,
5  fmt, io,
6  num::{ParseFloatError, ParseIntError},
7  result,
8  sync::LazyLock,
9};
10
11use rustc_hash::FxHashSet;
12
13use crate::common::arena::SymHashMap;
14
15#[derive(Debug, Clone, Default)]
16pub struct LogState {
17  pub undefined:   SymHashMap<usize>,
18  pub missing:     SymHashMap<usize>,
19  pub debug:       usize,
20  pub info:        usize,
21  pub warning:     usize,
22  pub error:       usize,
23  pub fatal:       bool,
24  pub status_code: usize,
25}
26pub enum LogStatus {
27  Debug,
28  Info,
29  Warning,
30  Error,
31  Fatal,
32  Undefined,
33  Missing,
34}
35
36thread_static! {
37  pub static REPORT: RefCell<LogState> = RefCell::new(LogState::default());
38}
39
40thread_local! {
41  /// Depth of diagnostic-macro emission on this thread (see [`macro_diag_guard`]).
42  /// A depth counter, not a bool: `Error!` can raise `Fatal!` inside its own
43  /// scope (the too-many-errors escalation), nesting two guards.
44  static MACRO_DIAG_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
45}
46
47/// RAII marker: "the log record currently being emitted comes from a
48/// diagnostic macro that already counted itself via [`note_status`]".
49///
50/// The tally has TWO producers which must never overlap: the macros
51/// (`Info!`/`Warn!`/`Error!`/`Fatal!`/`Debug!`) count at RAISE time — even when
52/// output is suppressed, which the `MAX_ERRORS` cap depends on — and the
53/// logger backend counts every OTHER record it prints (raw `log::warn!` and
54/// friends, which previously printed `Warning:` lines that no counter ever
55/// saw: the 131 MB witness logged 12,105 `Warning:` lines and reported
56/// "2 warnings"). This guard is how the logger tells the two apart.
57pub struct MacroDiagGuard(());
58impl Drop for MacroDiagGuard {
59  fn drop(&mut self) { MACRO_DIAG_DEPTH.set(MACRO_DIAG_DEPTH.get().saturating_sub(1)); }
60}
61#[must_use = "the guard must live across the log emission it marks"]
62pub fn macro_diag_guard() -> MacroDiagGuard {
63  MACRO_DIAG_DEPTH.set(MACRO_DIAG_DEPTH.get() + 1);
64  MacroDiagGuard(())
65}
66
67/// Count a diagnostic record observed by the logger backend, unless it was
68/// emitted by a macro (already counted at raise time) or the report is
69/// mid-borrow (a raw log call from inside a `report_mut!` scope must not
70/// panic the conversion over a tally increment — matching the logger's own
71/// `try_borrow` discipline for `LOG_BUFFER`).
72pub fn note_status_from_logger(status: LogStatus) {
73  if MACRO_DIAG_DEPTH.get() > 0 || REPORT.try_borrow_mut().is_err() {
74    return;
75  }
76  note_status(status, None);
77}
78
79thread_local! {
80  /// When true, Debug!/Info!/Warn! (and their emit_* forms) still count in
81  /// the report but do **not** emit anything to stderr/log. `Error!`/`Fatal!`
82  /// are NOT suppressible — they emit unconditionally (user decision
83  /// 2026-08-03), so success-rate aggregation (cortex) never loses them.
84  /// Used by tests/dump-builds that deliberately exercise noisy paths.
85  static SUPPRESS_LOG_OUTPUT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
86}
87
88/// Set or clear the log-output suppression flag. Returns the previous value.
89pub fn set_suppress_log_output(suppress: bool) -> bool {
90  let prev = SUPPRESS_LOG_OUTPUT.get();
91  SUPPRESS_LOG_OUTPUT.set(suppress);
92  prev
93}
94
95/// The log-output suppression flag set for a scope ([`set_suppress_log_output`]) and put back as it was when the
96/// guard is dropped — at the scope's end, on an early return or while a panic unwinds — so a scope that fails cannot
97/// leave the thread's later conversions silent (a speculative title-page run, sect05.rs
98/// `title_page_probe_run`, under `cortex_worker`'s per-paper `catch_unwind`).
99#[must_use = "the suppression ends when the guard is dropped"]
100pub struct SuppressLogOutputGuard {
101  prev: bool,
102}
103
104impl SuppressLogOutputGuard {
105  /// Set the flag to `suppress` until the guard is dropped.
106  pub fn new(suppress: bool) -> Self {
107    SuppressLogOutputGuard {
108      prev: set_suppress_log_output(suppress),
109    }
110  }
111}
112
113impl Drop for SuppressLogOutputGuard {
114  fn drop(&mut self) { SUPPRESS_LOG_OUTPUT.set(self.prev); }
115}
116
117/// Clear the log-output suppression flag, the progress notes' silence ([`SilenceProgressNotesGuard`];
118/// `reset_thread_engine`) and any [`DeferredNote`] a panic left: a fresh conversion on a reused thread logs.
119pub fn reset_suppress_log_output() {
120  SUPPRESS_LOG_OUTPUT.set(false);
121  SILENCE_PROGRESS_NOTES.set(false);
122  DEFERRED_NOTES.borrow_mut().clear();
123}
124
125/// Free the [`DeferredNote`] stack and the last error's key, for a thread about to exit (`crate::shrink_thread_engine`).
126pub(crate) fn shrink_error_notes() {
127  *DEFERRED_NOTES.borrow_mut() = Vec::new();
128  *LAST_ERROR_KEY.borrow_mut() = None;
129}
130
131// Thread-local FATAL DEMOTION for bibliography post-processing (user
132// policy 2026-07-04): with the live-state field interpretation, Warn!/
133// Error! report at NATIVE severity and count normally (matching Perl's
134// MergeStatus accounting, Common/Error.pm L669) — problems in bib fields
135// are real conversion diagnostics. Only Fatal! is demoted: it notes and
136// logs as an ERROR (`demoted_fatal:` target) instead of latching the
137// document's sticky fatal — a broken bibliography must never lose the
138// document. The Err return is unchanged, so the failing digestion still
139// aborts (its caller degrades gracefully).
140thread_local! {
141  static DEMOTE_FATALS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
142}
143
144/// Set or clear the fatal-demotion flag. Returns the previous value.
145pub fn set_demote_fatals(demote: bool) -> bool {
146  DEMOTE_FATALS.with(|c| {
147    let prev = c.get();
148    c.set(demote);
149    prev
150  })
151}
152
153/// Returns true if `Fatal!` is currently demoted to Error.
154pub fn is_demote_fatals() -> bool { DEMOTE_FATALS.with(|c| c.get()) }
155
156/// Returns true if log output is currently suppressed.
157pub fn is_log_output_suppressed() -> bool { SUPPRESS_LOG_OUTPUT.get() }
158
159thread_local! {
160  static IGNORE_DIAGNOSTICS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
161}
162
163/// Perl `$LaTeXML::IGNORE_ERRORS` (Common/Error.pm L362/L380/L396: `Error`,
164/// `Warn` and `Info` all `return if $LaTeXML::IGNORE_ERRORS`): inside a probing
165/// scope every diagnostic is dropped WHOLE — neither its line nor its count —
166/// so the log and the status can never disagree about it. This is the only
167/// sanctioned way to silence a scope; muting lines while keeping counts (or
168/// the reverse) is exactly the log/status inconsistency the pipeline must not
169/// produce. Returns the previous value; restore it on every exit path.
170pub fn set_ignore_diagnostics(ignore: bool) -> bool {
171  let prev = IGNORE_DIAGNOSTICS.get();
172  IGNORE_DIAGNOSTICS.set(ignore);
173  prev
174}
175/// Whether an `IGNORE_ERRORS`-style probing scope is active (see
176/// `set_ignore_diagnostics`).
177pub fn diagnostics_ignored() -> bool { IGNORE_DIAGNOSTICS.get() }
178
179thread_local! {
180  /// The Error and Fatal records an ignoring scope has dropped on this thread, so far.
181  static IGNORED_RECORDS: std::cell::Cell<IgnoredRecords> =
182    const { std::cell::Cell::new(IgnoredRecords { errors: 0, fatals: 0 }) };
183}
184
185/// A tally of the Error and Fatal records an ignoring scope dropped.
186#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
187pub struct IgnoredRecords {
188  pub errors: usize,
189  pub fatals: usize,
190}
191
192/// Perl `local $LaTeXML::IGNORE_ERRORS = 1` as a scope: ignores diagnostics
193/// while alive and restores the previous state on drop — panic-safe, unlike a
194/// manual restore after the probed call.
195pub struct IgnoreDiagnosticsScope {
196  previous: bool,
197  before:   IgnoredRecords,
198}
199impl IgnoreDiagnosticsScope {
200  pub fn new() -> Self {
201    Self {
202      previous: set_ignore_diagnostics(true),
203      before:   IGNORED_RECORDS.get(),
204    }
205  }
206  /// The Error and Fatal records dropped while this scope was alive: a scope that mutes a load can still say what
207  /// it muted (#825).
208  pub fn dropped(&self) -> IgnoredRecords {
209    let now = IGNORED_RECORDS.get();
210    IgnoredRecords {
211      errors: now.errors - self.before.errors,
212      fatals: now.fatals - self.before.fatals,
213    }
214  }
215}
216impl Default for IgnoreDiagnosticsScope {
217  fn default() -> Self { Self::new() }
218}
219impl Drop for IgnoreDiagnosticsScope {
220  fn drop(&mut self) { set_ignore_diagnostics(self.previous); }
221}
222
223thread_local! {
224  /// The `target:category:message` of every `Fatal:` line written in this conversion, so the raise site
225  /// (`Fatal!`/`fatal!`) and the catch sites (`Error::log_fatal`) together print each exactly once, however other
226  /// Fatals interleave (a swallowing caller that meets a re-raised runaway and the cycle guard's Fatal by turns).
227  static FATALS_LOGGED: RefCell<FxHashSet<String>> = RefCell::new(FxHashSet::default());
228}
229
230thread_static! {
231  /// Per-thread tracker for the most recently emitted error's
232  /// `category:object` signature, plus the count of how many
233  /// consecutive errors share the same signature. Used to detect
234  /// runaway loops where a single pathological control-sequence (like
235  /// plain-TeX `\tabalign` invoked in math mode → unbounded `\halign`
236  /// cell loop) keeps emitting the same error indefinitely. See
237  /// `wisdom_tabalign_math_runaway.md` for the canonical witness.
238  static LAST_ERROR_KEY: RefCell<Option<String>> = RefCell::new(None);
239}
240thread_local! {
241  static CONSECUTIVE_ERROR_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
242}
243
244/// Threshold for "same error fired this many times in a row → bail."
245/// Set well above any legitimate same-error pattern (a paper with
246/// 500+ identical errors would already be near-useless output) but
247/// well below the 10000 MAX_ERRORS cap so runaway papers don't
248/// accumulate huge noise logs. Empirically, the pathological
249/// `\tabalign`-in-math-mode runaway hits >9000 consecutive same
250/// errors; this catches that at 500 instead. The threshold was
251/// tightened from an initial 2000 after verifying no test in the
252/// 1112-test suite exceeds it.
253pub const MAX_CONSECUTIVE_ERRORS: usize = 500;
254
255/// Record an error signature; returns the new consecutive count.
256/// Call from the Error! macro after note_status. Resets count to 1
257/// on a different signature, increments on a match.
258pub fn note_consecutive_error(key: &str) -> usize {
259  let mut last = LAST_ERROR_KEY.borrow_mut();
260  if last.as_deref() == Some(key) {
261    let c = CONSECUTIVE_ERROR_COUNT.get() + 1;
262    CONSECUTIVE_ERROR_COUNT.set(c);
263    c
264  } else {
265    *last = Some(key.to_string());
266    CONSECUTIVE_ERROR_COUNT.set(1);
267    1
268  }
269}
270
271/// The message of the consecutive-error cap's Fatal (the `Error!` macro) for the error signature `key`.
272pub fn runaway_message(key: &str) -> String {
273  format!("Runaway: same error '{key}' fired over {MAX_CONSECUTIVE_ERRORS} times in a row")
274}
275
276/// The consecutive-error cap's Fatal once the error cap latched (a `TooManyErrors` Fatal line, the total cap's or the
277/// runaway's, is printed and counted): an `Err` marked logged, so no sink prints a line for it; the run's status is
278/// the latched Fatal's.
279pub fn runaway_reraise(key: &str) -> Error {
280  let fatal = Error::from(ErrorData {
281    target:   ErrorTarget::TooManyErrors,
282    category: ErrorCategory::MaxLimit(MAX_CONSECUTIVE_ERRORS),
283    message:  runaway_message(key),
284  });
285  fatal.mark_logged_fatal();
286  fatal
287}
288
289/// A diagnostic's `what` field as the log line carries it: without leading blanks, and `fallback` when that leaves
290/// nothing. A field of spaces (an `\@latex@error` prefix whose indent expanded, 2606.13031) leaves `Error:latex:`
291/// followed by blanks, which a log reader keyed on `Error:<category>:<what>` misses; Perl prints it as it is. Trailing
292/// blanks stay, as Perl's `(mycls)  Class mycls Warning` (OXIDIZED_DESIGN #1175).
293pub fn message_object<'a>(object: &'a str, fallback: &'a str) -> &'a str {
294  match object.trim_start() {
295    "" => fallback,
296    trimmed => trimmed,
297  }
298}
299
300/// `target` (`[Fatal:]<category>:<object>`) with its object put through [`message_object`] (fallback `unknown`): the
301/// net under every emission site.
302fn record_target(target: &str) -> Cow<'_, str> {
303  let body = target.strip_prefix("Fatal:").unwrap_or(target);
304  let Some((category, object)) = body.split_once(':') else {
305    return Cow::Borrowed(target);
306  };
307  let what = message_object(object, "unknown");
308  // (by content, not length: a seven-blank object and its fallback `unknown` are the same length)
309  if what == object {
310    return Cow::Borrowed(target);
311  }
312  let fatal = if body.len() < target.len() {
313    "Fatal:"
314  } else {
315    ""
316  };
317  Cow::Owned(format!("{fatal}{category}:{what}"))
318}
319
320/// The ONE emission primitive every diagnostic flows through (DRY pass,
321/// user directive 2026-08-02): count on the emitting thread's `REPORT`,
322/// then log with the pre-formatted `target`, respecting output suppression —
323/// EXCEPT for `Error` and `Fatal` records, which are emitted UNCONDITIONALLY
324/// (user decision 2026-08-03): frameworks such as cortex aggregate success
325/// rates from `Error:`/`Fatal:` lines, so muting either would hide exactly
326/// the signal they measure. Suppression mutes Debug/Info/Warning only.
327/// The `MacroDiagGuard` marks the emission so the logger backend does not
328/// count it a second time.
329pub fn emit_record(status: LogStatus, target: &str, message: &str) {
330  let _diag_guard = macro_diag_guard();
331  let target = &*record_target(target);
332  // Perl `IGNORE_ERRORS`: a probing scope drops the record whole (no line, no
333  // count) — see `set_ignore_diagnostics`.
334  if diagnostics_ignored() {
335    let mut tally = IGNORED_RECORDS.get();
336    match status {
337      LogStatus::Error => tally.errors += 1,
338      LogStatus::Fatal => tally.fatals += 1,
339      _ => {},
340    }
341    IGNORED_RECORDS.set(tally);
342    return;
343  }
344  // After any Fatal, Error records are dropped, neither logged nor counted (Perl `Fatal` sets
345  // `$LaTeXML::IGNORE_ERRORS = 1` after `hardYankProcessing`, Common/Error.pm L315; `Error` returns at L362).
346  // Perl dies at the Fatal; our recovery keeps converting, so what still reaches this gate is teardown noise:
347  // the group closers (sweep 82), the gullet's drain after an RSS-fuse trip (glossaries-extra-manual, sweep 96),
348  // the 96 closers after 1702.08816's `Fatal:Stomach:Recursion`, the churn past the error cap (gckanbun 12.8k,
349  // panda-doc 3.6k, sweep 13). The Fatal line, every pre-Fatal Error, Warnings and Info still report; a pre-Fatal Error
350  // a hold deferred (an `\autoref` name's) replays at its use after the build (logger.rs `DeferredDiagnostics::replay`),
351  // unless the error cap or a resource Fatal latched (replay keeps base's gate; row DEFERCAP).
352  // (The `Error!` macro's escalation still runs at the site; with the count frozen only its consecutive-key branch can
353  // return `Err(TooManyErrors)`: an alternating-key loop has no cap, as in Perl, Error.pm:362.)
354  if matches!(status, LogStatus::Error) && errors_ignored_after_fatal() {
355    MUTED_ERRORS.set(MUTED_ERRORS.get() + 1);
356    return;
357  }
358  let level = match status {
359    LogStatus::Debug => log::Level::Debug,
360    LogStatus::Info => log::Level::Info,
361    LogStatus::Warning => log::Level::Warn,
362    _ => log::Level::Error,
363  };
364  let unconditional = matches!(status, LogStatus::Error | LogStatus::Fatal);
365  note_status(status, None);
366  if unconditional || !is_log_output_suppressed() {
367    log::log!(target: target, level, "{message}");
368  }
369}
370
371/// The single diagnostic vehicle, function form — for contexts that cannot
372/// use the `Error!`/`Warn!`/`Info!` macros because those are return-based
373/// (`Error!` escalates to `Fatal!`, which `return Err(...)`s, so it only
374/// typechecks in `Result<_, error::Error>` functions).
375///
376/// Perl LaTeXML has exactly one emission vehicle per severity (`Error.pm`),
377/// which is what lets its tally and cortex's aggregation be lossless by
378/// construction. These functions restore that property for Rust's
379/// non-`Result` contexts (post-processing drivers, workers, the LSP server):
380/// they count, emit with a proper `category:object` target, respect output
381/// suppression, and participate in the runaway circuit-breakers — everything
382/// the raw `log::warn!`-family calls they replace silently skipped. Raw
383/// `log::*!` diagnostics are BANNED in workspace crates (see
384/// `tools/lint_raw_log_diag.sh`); the logger backend's own tally
385/// (`note_status_from_logger`) remains only as the net for FOREIGN crates
386/// logging through the `log` facade, which can never use this vehicle.
387pub fn emit_info(category: &str, object: &str, message: &str) {
388  emit_record(LogStatus::Info, &format!("{category}:{object}"), message);
389}
390
391/// See [`emit_info`].
392pub fn emit_warn(category: &str, object: &str, message: &str) {
393  emit_record(LogStatus::Warning, &format!("{category}:{object}"), message);
394}
395
396/// The state key of a box whose measure a binding approximates, its value the box's name: a `breakable` tcolorbox set
397/// as one box (tcolorbox_sty.rs, Perl tcolorbox.sty.ltxml:21). Read by [`approximated_measure`].
398pub const APPROXIMATED_MEASURE: &str = "lx_approximated_measure";
399const APPROXIMATED_MEASURE_REPORTED: &str = "lx_approximated_measure_reported";
400
401/// Where an arithmetic overflow (tex.web §104, §460; etex.ch `scan_expr`), an Error as TeX's (OXIDIZED_DESIGN #519),
402/// is a Warning: inside a measure a binding approximates ([`APPROXIMATED_MEASURE`]) the size is ours, not the
403/// author's (DG 2026-11-13). The detail naming the box, and whether it is the box's first overflow (its Warning; the
404/// ones it cascades into an Info), or `None` outside one.
405pub fn approximated_measure() -> Option<(String, bool)> {
406  let name = crate::state::try_lookup_string(APPROXIMATED_MEASURE)?;
407  let first = crate::state::try_lookup_string(APPROXIMATED_MEASURE_REPORTED).as_deref()
408    != Some(name.as_str());
409  if first {
410    crate::state::try_assign_value_global(APPROXIMATED_MEASURE_REPORTED, name.clone().into());
411  }
412  Some((
413    format!("in {name}, set as one box where TeX breaks it: the size is ours"),
414    first,
415  ))
416}
417
418/// See [`emit_info`]. Unlike the `Error!` macro this cannot escalate by
419/// `return`ing — there is no `Err` channel in the contexts it serves — so
420/// when the error count or the consecutive-error count crosses its cap it
421/// emits the `Fatal:TooManyErrors` record and latches the sticky fatal
422/// instead: the run continues (its caller has no unwind path) but the
423/// conversion's verdict and status code report the fatal honestly.
424pub fn emit_error(category: &str, object: &str, message: &str) {
425  emit_record(LogStatus::Error, &format!("{category}:{object}"), message);
426  note_error_cap(&format!("{category}:{object}"));
427}
428
429/// The error cap's bookkeeping after one counted Error (`key` = `category:object`): at the crossing of `MAX_ERRORS` or
430/// of the consecutive-error limit, latch `TooManyErrors` and emit its Fatal (Perl Error.pm L362-372). Shared by
431/// [`emit_error`] and a replayed deferred error (logger.rs `DeferredDiagnostics`).
432pub fn note_error_cap(key: &str) {
433  // Perl `IGNORE_ERRORS` (Error.pm L362): an ignored record does nothing,
434  // not even cap bookkeeping.
435  if is_demote_fatals() || diagnostics_ignored() || FATAL_MUTE.with(|m| m.borrow().is_some()) {
436    return;
437  }
438  let maxerrors = match crate::state::try_lookup_int("MAX_ERRORS") {
439    None => usize::MAX, // STATE contended: skip the check for this error
440    Some(v) if v > 0 => v as usize,
441    Some(_) => 100,
442  };
443  let consec = note_consecutive_error(key);
444  // Once latched, `emit_record` drops the repeats and the count freezes at
445  // the cap, so the crossing test below would stay true and re-fire the
446  // `Fatal:TooManyErrors` line on every later call. One Fatal, like Perl.
447  if too_many_errors_latched() {
448    return;
449  }
450  let over_total = get_status(LogStatus::Error) > maxerrors;
451  let over_consec = consec > MAX_CONSECUTIVE_ERRORS;
452  // Latch exactly at the crossing, not on every error past it.
453  if (over_total && get_status(LogStatus::Error) == maxerrors + 1)
454    || (over_consec && consec == MAX_CONSECUTIVE_ERRORS + 1)
455  {
456    latch_too_many_errors();
457    emit_fatal(
458      "TooManyErrors",
459      "MaxLimit",
460      &format!(
461        "Too many errors (> {})!",
462        if over_total {
463          maxerrors
464        } else {
465          MAX_CONSECUTIVE_ERRORS
466        }
467      ),
468    );
469  }
470}
471
472/// See [`emit_info`]. Latches the sticky fatal and emits the canonical
473/// `Fatal:<category>:<object>` line — NEVER suppressed (see [`emit_record`]).
474/// The CALLER owns any early-exit control flow (e.g. `latexml_post`'s
475/// `Fatal!` returns its own `PostError` after this) — a fatal, unlike an
476/// error, needs no cap bookkeeping.
477pub fn emit_fatal(category: &str, object: &str, message: &str) {
478  mute_errors_after_fatal(format!("{category}:{object}:{message}"));
479  emit_record(
480    LogStatus::Fatal,
481    &format!("Fatal:{category}:{object}"),
482    message,
483  );
484}
485
486/// Reset the consecutive-error tracker (called from initialize_report).
487fn reset_consecutive_error_tracker() {
488  *LAST_ERROR_KEY.borrow_mut() = None;
489  CONSECUTIVE_ERROR_COUNT.set(0);
490  TOO_MANY_ERRORS_LATCHED.set(false);
491  TOO_MANY_ERRORS_SPENT.set(false);
492}
493
494thread_local! {
495  static TOO_MANY_ERRORS_LATCHED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
496}
497
498/// Latch the too-many-errors state: `emit_record` drops further Error-level
499/// records until the next conversion resets the report. Set by the
500/// `TooManyErrors` Fatal paths (the `Error!` macro cap and `emit_error`'s
501/// latch); cleared in `reset_consecutive_error_tracker`.
502pub fn latch_too_many_errors() { TOO_MANY_ERRORS_LATCHED.set(true); }
503/// Whether the too-many-errors latch is set (see `latch_too_many_errors`).
504pub fn too_many_errors_latched() -> bool { TOO_MANY_ERRORS_LATCHED.get() }
505
506thread_local! {
507  static TOO_MANY_ERRORS_SPENT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
508}
509
510/// The digestion's end has taken the latched error cap's Fatal (`core_interface::finish_digestion_fatal`, OD #251): an
511/// `Error!` of the phases after it (the build of what was kept, the rewrites, the math) no longer raises it again, as
512/// Perl's `Error` returns before its cap test once a Fatal set `IGNORE_ERRORS` (Common/Error.pm:362, :372). Until then
513/// the re-raise ends a digestion that swallowed the Fatal, our stand-in for the input `hardYankProcessing` empties.
514pub fn spend_too_many_errors() {
515  if too_many_errors_latched() {
516    TOO_MANY_ERRORS_SPENT.set(true);
517  }
518}
519/// Whether the latched error cap's Fatal is spent (see `spend_too_many_errors`).
520pub fn too_many_errors_spent() -> bool { TOO_MANY_ERRORS_SPENT.get() }
521
522/// The whole diagnostic tally of this thread: the [`REPORT`] plus the gates
523/// that live beside it — the consecutive-error runaway tracker, the
524/// too-many-errors latch and the Fatal-line dedupe. A discarded speculative
525/// scope (`logger::DiagnosticsHold`) restores all of them together, so the
526/// errors it dropped can neither count nor trip a cap that would then mute the
527/// document's own errors.
528#[derive(Clone, Default)]
529pub struct DiagnosticGates {
530  /// The report counters at the snapshot.
531  pub report:       LogState,
532  last_error_key:   Option<String>,
533  consecutive:      usize,
534  too_many_errors:  bool,
535  too_many_spent:   bool,
536  fatals_logged:    FxHashSet<String>,
537  fatal_mute:       Option<String>,
538  /// The Errors dropped after a Fatal so far: a speculative run still sees its own as failures.
539  pub muted_errors: usize,
540}
541
542/// Snapshot this thread's [`DiagnosticGates`].
543pub fn save_diagnostic_gates() -> DiagnosticGates {
544  DiagnosticGates {
545    report:          REPORT.borrow().clone(),
546    last_error_key:  LAST_ERROR_KEY.borrow().clone(),
547    consecutive:     CONSECUTIVE_ERROR_COUNT.get(),
548    too_many_errors: TOO_MANY_ERRORS_LATCHED.get(),
549    too_many_spent:  TOO_MANY_ERRORS_SPENT.get(),
550    fatals_logged:   FATALS_LOGGED.with(|c| c.borrow().clone()),
551    fatal_mute:      FATAL_MUTE.with(|m| m.borrow().clone()),
552    muted_errors:    MUTED_ERRORS.get(),
553  }
554}
555
556/// Restore this thread's [`DiagnosticGates`] from a snapshot.
557pub fn restore_diagnostic_gates(gates: DiagnosticGates) {
558  *REPORT.borrow_mut() = gates.report;
559  *LAST_ERROR_KEY.borrow_mut() = gates.last_error_key;
560  CONSECUTIVE_ERROR_COUNT.set(gates.consecutive);
561  TOO_MANY_ERRORS_LATCHED.set(gates.too_many_errors);
562  TOO_MANY_ERRORS_SPENT.set(gates.too_many_spent);
563  FATALS_LOGGED.with(|c| *c.borrow_mut() = gates.fatals_logged);
564  FATAL_MUTE.with(|m| *m.borrow_mut() = gates.fatal_mute);
565  MUTED_ERRORS.set(gates.muted_errors);
566}
567#[macro_export]
568macro_rules! report {
569  () => {
570    (*$crate::common::error::REPORT).borrow()
571  };
572}
573#[macro_export]
574macro_rules! report_mut {
575  () => {
576    (*$crate::common::error::REPORT).borrow_mut()
577  };
578}
579
580pub fn note_status(status: LogStatus, what: Option<&str>) {
581  let mut report = REPORT.borrow_mut();
582  use LogStatus::*;
583  match status {
584    Debug => report.debug += 1,
585    Info => report.info += 1,
586    Warning => report.warning += 1,
587    Error => report.error += 1,
588    Fatal => {
589      // Diagnostic for "phantom fatals" (a fatal counted in the final summary
590      // with no `Fatal:` line in the log — an `Err` raised via `Fatal!` that
591      // some caller swallowed without `log_fatal`): dump a backtrace at the
592      // moment the tally first flips. Witness math0402448.
593      if !report.fatal && debug_fatal_enabled() {
594        eprintln!("[debug-fatal] LogStatus::Fatal first noted here:");
595        eprintln!("{}", std::backtrace::Backtrace::force_capture());
596      }
597      report.fatal = true;
598    },
599    Undefined => {
600      // `what` may be lent from the arena; `entry` pins it, which under a lend never moves the buffer (the former
601      // re-entrant pin did, and a `\special_relax` family-token name became a phantom undefined).
602      let entry = report
603        .undefined
604        .entry(what.unwrap_or_default())
605        .or_insert(0);
606      *entry += 1;
607    },
608    Missing => {
609      let entry = report.missing.entry(what.unwrap_or_default()).or_insert(0);
610      *entry += 1;
611    },
612  }
613}
614
615pub fn get_status(status: LogStatus) -> usize {
616  let report = REPORT.borrow();
617  use LogStatus::*;
618  match status {
619    Debug => report.debug,
620    Info => report.info,
621    Warning => report.warning,
622    Error => report.error,
623    Fatal => {
624      if report.fatal {
625        1
626      } else {
627        0
628      }
629    },
630    Undefined => report.undefined.0.values().sum(),
631    Missing => report.missing.0.values().sum(),
632  }
633}
634
635/// One shared probe for the `LATEXML_DEBUG_FATAL` diagnostics (first-fatal
636/// backtrace, gullet pushback dump, recent-token ring). LazyLock-cached so hot
637/// paths pay a single bool test, and a single seam if the env contract grows
638/// (PR #249 review P3-13).
639pub fn debug_fatal_enabled() -> bool {
640  use std::sync::OnceLock;
641  static FLAG: OnceLock<bool> = OnceLock::new();
642  *FLAG.get_or_init(|| std::env::var_os("LATEXML_DEBUG_FATAL").is_some())
643}
644
645pub fn initialize_report() {
646  // The rest of a conversion's thread-local state dies with it too (a persistent worker's next paper starts clean).
647  crate::reset_conversion_state();
648  let mut report = REPORT.borrow_mut();
649  *report = LogState::default();
650  reset_consecutive_error_tracker();
651  LAST_RESOURCE_FATAL.with(|c| *c.borrow_mut() = None);
652  RESOURCE_FATAL_SEEN.with(|c| c.set(false));
653  FATALS_LOGGED.with(|c| c.borrow_mut().clear());
654  FATAL_MUTE.with(|m| *m.borrow_mut() = None);
655  MUTED_ERRORS.set(0);
656  // A probing scope that unwound without its restore must not silence the
657  // next conversion.
658  IGNORE_DIAGNOSTICS.set(false);
659  drop(report);
660  log_session_warnings();
661}
662
663/// Logs and counts the warnings held for the session ([`warn_at_session_start`]), into the log now bound. The
664/// report's reset does it; a run that never resets it (an XML input's post-processing) calls it once its log is bound.
665pub fn log_session_warnings() {
666  for (target, message) in SESSION_WARNINGS.with(|held| std::mem::take(&mut *held.borrow_mut())) {
667    emit_record(LogStatus::Warning, &target, &message);
668  }
669}
670
671thread_local! {
672  /// Warnings raised on this thread before its conversion's report starts.
673  static SESSION_WARNINGS: RefCell<Vec<(String, String)>> = const { RefCell::new(Vec::new()) };
674}
675
676/// Drop the warnings held for a source that never reached its report (its archive unpacked, then its job failed before
677/// the session): a persistent worker's next paper must not log them as its own. Called as each archive is unpacked.
678pub fn clear_session_warnings() { SESSION_WARNINGS.with(|held| held.borrow_mut().clear()) }
679
680/// A Warning raised before its conversion's report starts (a source archive is unpacked, a command-line option is
681/// checked, before the session): held, then logged and counted by the next [`initialize_report`] on this thread, or
682/// by [`log_session_warnings`] where post-processing opens the log of a run that has no report reset.
683pub fn warn_at_session_start(category: &str, object: &str, message: String) {
684  SESSION_WARNINGS.with(|held| {
685    held
686      .borrow_mut()
687      .push((format!("{category}:{object}"), message))
688  });
689}
690
691/// Clear the arena-`SymStr`-keyed report maps (`undefined`, `missing`). MUST be
692/// called whenever the arena is reset (see `crate::reset_thread_engine`): their
693/// keys are arena interner ids, so after `arena::reset()` a stale key resolves to
694/// whatever string now occupies that id — e.g. a `\special_relax` family-token
695/// name — producing phantom "undefined macro" reports across conversions.
696pub fn reset_arena_keyed_reports() {
697  let mut report = REPORT.borrow_mut();
698  report.undefined = Default::default();
699  report.missing = Default::default();
700}
701
702/// Run `f` (which resets the string arena) while preserving `REPORT`'s
703/// `undefined` and `missing` tallies: their `SymStr` keys are materialized to
704/// owned strings before `f` and re-interned into the fresh arena afterwards, so
705/// [`get_status_message`] / [`conversion_verdict`] remain byte-identical after
706/// dropping the core engine's arena between core and post-processing.
707pub fn preserve_arena_keyed_reports_across(f: impl FnOnce()) {
708  let (undef, miss) = {
709    let mut report = REPORT.borrow_mut();
710    let u: Vec<(String, usize)> = report
711      .undefined
712      .0
713      .drain()
714      .map(|(k, v)| (crate::common::arena::to_string(k), v))
715      .collect();
716    let m: Vec<(String, usize)> = report
717      .missing
718      .0
719      .drain()
720      .map(|(k, v)| (crate::common::arena::to_string(k), v))
721      .collect();
722    (u, m)
723  };
724  f();
725  if !undef.is_empty() || !miss.is_empty() {
726    let mut report = REPORT.borrow_mut();
727    for (s, count) in undef {
728      *report.undefined.entry(&s).or_insert(0) += count;
729    }
730    for (s, count) in miss {
731      *report.missing.entry(&s).or_insert(0) += count;
732    }
733  }
734}
735
736thread_local! {
737  /// Latch for the most recent RESOURCE-class fatal (`ErrorTarget::Timeout`
738  /// with a unit category: token/pushback/if limits, cycle-guard recursion,
739  /// memory budget, conversion deadline). Some layers flatten `Error` into a
740  /// plain string on the way up (the marpa semantics boundary turns it into
741  /// `marpa::error::Error`), destroying the structured identity — which made
742  /// resource fatals indistinguishable from semantic parse rejections and
743  /// produced "phantom fatals" (counted in the summary, never logged, parse
744  /// grinding on). The `Fatal!` macro records here at raise time; consumers
745  /// `take` it to re-classify a flattened error. PR #249 review P1-4.
746  static LAST_RESOURCE_FATAL: RefCell<Option<Error>> = const { RefCell::new(None) };
747  /// Sticky companion of `LAST_RESOURCE_FATAL` (which consumers `take`): has a
748  /// resource fatal been raised in this conversion? Once it has, the
749  /// document is aborted and the recovery pass only drains what is pending;
750  /// the group-closer errors that draining raises (`stomach::egroup` /
751  /// `endgroup` / `end_mode_opt`) are teardown noise, not findings — 11-13
752  /// non-deterministic `Attempt to close a group that switched to mode`
753  /// lines after glossaries-user's MemoryBudget Fatal (sweep 82), a phantom
754  /// regression. Cleared in `initialize_report`.
755  static RESOURCE_FATAL_SEEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
756}
757
758/// Whether a resource-class Fatal (timeout, memory budget, runaway limits)
759/// has been raised in this conversion — see `RESOURCE_FATAL_SEEN`.
760pub fn resource_fatal_latched() -> bool { RESOURCE_FATAL_SEEN.with(|c| c.get()) }
761
762thread_local! {
763  /// Perl's `$LaTeXML::IGNORE_ERRORS = 1` once a Fatal is printed (Common/Error.pm:315): the key of that Fatal.
764  /// Separate from the resource latch, which the frontmatter probes unlatch; a discarded probe restores it with its
765  /// `DiagnosticGates`; cleared in `initialize_report`.
766  static FATAL_MUTE: RefCell<Option<String>> = const { RefCell::new(None) };
767  static MUTED_ERRORS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
768}
769
770/// The Errors dropped after a Fatal on this thread so far (see `DiagnosticGates::muted_errors`).
771pub fn muted_errors() -> usize { MUTED_ERRORS.get() }
772
773fn mute_errors_after_fatal(key: String) {
774  if !diagnostics_ignored() {
775    FATAL_MUTE.with(|m| {
776      m.borrow_mut().get_or_insert(key);
777    });
778  }
779}
780
781/// Whether Error records are dropped: after any Fatal (Perl `Error` returns at Common/Error.pm:362), or once the error
782/// cap or a resource Fatal latched (those latch under an ignoring scope too).
783pub fn errors_ignored_after_fatal() -> bool {
784  FATAL_MUTE.with(|m| m.borrow().is_some()) || too_many_errors_latched() || resource_fatal_latched()
785}
786
787/// A Fatal a script binding catches is the script's to handle (DG 2026-11-14, OD #1028): when it set the mute, the
788/// later Errors print again; a Fatal the script lets through mutes them at its sink's `log_fatal`.
789pub fn unmute_errors_after_caught_fatal(e: &Error) {
790  let key = e.fatal_key();
791  FATAL_MUTE.with(|m| {
792    let mut mute = m.borrow_mut();
793    if mute.as_deref() == Some(key.as_str()) {
794      *mute = None;
795    }
796  });
797}
798
799/// Record a fatal into the resource-fatal latch — only Timeout-target fatals
800/// with payload-free categories are kept (the latch exists for resource
801/// fatals; payload-carrying `ErrorCategory` variants are not cloneable and
802/// are never resource-class).
803pub fn record_last_fatal(e: &Error) {
804  use ErrorCategory as C;
805  if !matches!(e.target, ErrorTarget::Timeout) {
806    return;
807  }
808  let category = match &e.category {
809    C::TokenLimit => C::TokenLimit,
810    C::PushbackLimit => C::PushbackLimit,
811    C::Recursion => C::Recursion,
812    C::IfLimit => C::IfLimit,
813    C::MemoryBudget => C::MemoryBudget,
814    C::Convert => C::Convert,
815    _ => return,
816  };
817  LAST_RESOURCE_FATAL.with(|c| {
818    *c.borrow_mut() = Some(Error::from(ErrorData {
819      target: ErrorTarget::Timeout,
820      category,
821      message: e.message.clone(),
822    }));
823  });
824  RESOURCE_FATAL_SEEN.with(|c| c.set(true));
825}
826
827/// Unlatch the latched resource fatal when it is a runaway limit of the expansion in progress — the pushback, a
828/// recursion — for a run the document never makes, discarded with it (`title_page_probe_run`). A limit of the
829/// conversion stays latched as the document's: its deadline, its memory budget, its token budget, its conditional
830/// ids. (The token count itself does not carry past the failed run: `reading_from_mouth`'s error path resets the
831/// gullet's `progress`, gullet.rs.) Whether it was one.
832pub fn unlatch_runaway_fatal() -> bool {
833  use ErrorCategory as C;
834  let runaway = LAST_RESOURCE_FATAL.with(|c| {
835    matches!(c.borrow().as_ref(), Some(e) if matches!(e.category, C::PushbackLimit | C::Recursion))
836  });
837  if runaway {
838    LAST_RESOURCE_FATAL.with(|c| *c.borrow_mut() = None);
839    RESOURCE_FATAL_SEEN.with(|c| c.set(false));
840  }
841  runaway
842}
843
844/// Take (and clear) the latched resource fatal, if any. Returns the
845/// structured `Error` so a boundary that received only a flattened string can
846/// propagate the real thing.
847pub fn take_last_resource_fatal() -> Option<Error> {
848  LAST_RESOURCE_FATAL.with(|c| c.borrow_mut().take())
849}
850
851/// Build a status message matching Perl's `getStatusMessage()`.
852/// Format: "N warnings; M errors; K fatal error; L undefined macros[\foo, \bar]; P missing
853/// files[x.sty]" Returns "No obvious problems" when no issues detected.
854/// The canonical machine-readable conversion-status line, `Status:conversion:N`.
855///
856/// The contract every multi-phase executable ends its log with: the cortex
857/// framework derives a task's final severity from the LAST such line in the
858/// log (and defaults to Fatal when it is absent), so `code` must be the
859/// combined `max(core, post)` verdict. Shared here so the CLI, the worker and
860/// the archive `status` member can never drift in format.
861pub fn conversion_status_line(code: usize) -> String { format!("Status:conversion:{code}") }
862
863/// The human-readable end-of-run verdict: `Conversion complete|failed: <counts>`.
864///
865/// `failed` iff `code` is fatal (>= 3), mirroring Perl LaTeXML's summary
866/// line. Callers pass their combined `max(core, post)` code; the counts come
867/// from the shared REPORT counter via [`get_status_message`].
868pub fn conversion_verdict(code: usize) -> String {
869  format!(
870    "Conversion {}: {}",
871    if code >= 3 { "failed" } else { "complete" },
872    get_status_message()
873  )
874}
875
876pub fn get_status_message() -> String {
877  let report = REPORT.borrow();
878  let mut parts = Vec::new();
879  if report.warning > 0 {
880    parts.push(format!(
881      "{} warning{}",
882      report.warning,
883      if report.warning > 1 { "s" } else { "" }
884    ));
885  }
886  if report.error > 0 {
887    parts.push(format!(
888      "{} error{}",
889      report.error,
890      if report.error > 1 { "s" } else { "" }
891    ));
892  }
893  if report.fatal {
894    parts.push("1 fatal error".to_string());
895  }
896  // (sorted, and so are the missing files: a hash map's order follows the symbols' interning history, which any
897  // work done before an error changes — the frontmatter observer's rehearsal, a new definition; Perl State.pm:771
898  // lists `keys %{$$status{undefined}}`, a random hash order)
899  let mut undef_keys: Vec<String> = report
900    .undefined
901    .keys()
902    .map(|k| crate::common::arena::to_string(*k))
903    .collect();
904  undef_keys.sort_unstable();
905  if !undef_keys.is_empty() {
906    parts.push(format!(
907      "{} undefined macro{}[{}]",
908      undef_keys.len(),
909      if undef_keys.len() > 1 { "s" } else { "" },
910      undef_keys.join(", ")
911    ));
912  }
913  let mut miss_keys: Vec<String> = report
914    .missing
915    .keys()
916    .map(|k| crate::common::arena::to_string(*k))
917    .collect();
918  miss_keys.sort_unstable();
919  if !miss_keys.is_empty() {
920    parts.push(format!(
921      "{} missing file{}[{}]",
922      miss_keys.len(),
923      if miss_keys.len() > 1 { "s" } else { "" },
924      miss_keys.join(", ")
925    ));
926  }
927  if parts.is_empty() {
928    "No obvious problems".to_string()
929  } else {
930    parts.join("; ")
931  }
932}
933
934/// Compute the status code from the report state (Perl getStatusCode).
935/// 3 = fatal, 2 = errors, 1 = warnings, 0 = clean.
936pub fn get_status_code() -> usize {
937  let report = REPORT.borrow();
938  if report.fatal {
939    3
940  } else if report.error > 0 {
941    2
942  } else if report.warning > 0 {
943    1
944  } else {
945    0
946  }
947}
948
949/// A thread-portable snapshot of the `REPORT`'s integer status counters
950/// (everything EXCEPT the arena-`SymStr`-keyed `undefined`/`missing` maps,
951/// whose keys are interner ids local to one thread's arena). Used to forward a
952/// worker thread's diagnostic tally back to the main thread: `REPORT` is
953/// per-thread, so an `Error!`/`Warn!` raised on a spawned post-processing
954/// worker increments only that worker's counters and is invisible to the
955/// main-thread `status_code` unless merged here. See
956/// [`crate::util::logger::capture`] / [`crate::util::logger::replay_captured`].
957#[derive(Default, Clone, Copy)]
958pub struct ReportCounts {
959  pub debug:   usize,
960  pub info:    usize,
961  pub warning: usize,
962  pub error:   usize,
963  pub fatal:   bool,
964}
965
966/// Snapshot the current thread's `REPORT` integer counters.
967pub fn snapshot_report_counts() -> ReportCounts {
968  let r = REPORT.borrow();
969  ReportCounts {
970    debug:   r.debug,
971    info:    r.info,
972    warning: r.warning,
973    error:   r.error,
974    fatal:   r.fatal,
975  }
976}
977
978/// Overwrite the current thread's `REPORT` counters with a prior snapshot.
979/// The isolation primitive for RECURSIVE/auxiliary digestions whose
980/// diagnostics must not count against the document (Perl analog: the
981/// recursive MakeBibliography session keeps its tally out of the outer
982/// document). Pair with [`set_suppress_log_output`] so neither the lines
983/// nor the counts leak: snapshot -> suppress -> digest -> restore.
984pub fn restore_report_counts(c: ReportCounts) {
985  let mut r = REPORT.borrow_mut();
986  r.debug = c.debug;
987  r.info = c.info;
988  r.warning = c.warning;
989  r.error = c.error;
990  r.fatal = c.fatal;
991}
992
993/// Add a worker thread's [`ReportCounts`] into the current (main) thread's
994/// `REPORT`. Only the integer counts + the sticky `fatal` flag are merged; the
995/// arena-keyed `undefined`/`missing` maps are NOT (a worker has its own
996/// thread-local arena, so those keys are not portable).
997pub fn merge_report_counts(c: ReportCounts) {
998  let mut r = REPORT.borrow_mut();
999  r.debug += c.debug;
1000  r.info += c.info;
1001  r.warning += c.warning;
1002  r.error += c.error;
1003  r.fatal |= c.fatal;
1004}
1005
1006//======================================================================
1007// Debuggable features (Perl: `DebuggableFeature($name)` registration +
1008// `$LaTeXML::DEBUG{$name}` gating, enabled by the CLI's `--debug NAME`).
1009// Process-global (not thread-local): the CLI parses args on one thread
1010// and may convert on another (e.g. the big-stack worker in
1011// bin/latexml_oxide.rs); reads only occur on gated debug paths.
1012//======================================================================
1013
1014static KNOWN_DEBUG_FEATURES: LazyLock<std::sync::RwLock<std::collections::BTreeSet<String>>> =
1015  LazyLock::new(|| std::sync::RwLock::new(std::collections::BTreeSet::new()));
1016static ENABLED_DEBUG_FEATURES: LazyLock<std::sync::RwLock<FxHashSet<String>>> =
1017  LazyLock::new(|| std::sync::RwLock::new(FxHashSet::default()));
1018
1019/// Perl: `DebuggableFeature($name)` — register a feature name so it can
1020/// be listed/validated for `--debug`.
1021pub fn debuggable_feature(name: &str) {
1022  if let Ok(mut known) = KNOWN_DEBUG_FEATURES.write() {
1023    known.insert(name.to_string());
1024  }
1025}
1026
1027/// All registered feature names (sorted), for `--debug` diagnostics.
1028pub fn known_debug_features() -> Vec<String> {
1029  KNOWN_DEBUG_FEATURES
1030    .read()
1031    .map(|k| k.iter().cloned().collect())
1032    .unwrap_or_default()
1033}
1034
1035/// Perl: `$LaTeXML::DEBUG{$name} = 1` — called by the CLI per `--debug NAME`. Raises the `log` floor to `Debug`
1036/// so the feature's records pass; un-featured ones stay `--verbose`'s (`util/logger.rs` `DEBUG_ALL`).
1037pub fn enable_debug_feature(name: &str) {
1038  if let Ok(mut enabled) = ENABLED_DEBUG_FEATURES.write() {
1039    enabled.insert(name.to_string());
1040  }
1041  log::set_max_level(log::max_level().max(log::LevelFilter::Debug));
1042}
1043
1044/// Perl `CheckDebuggable` (`Common/Error.pm` L483-492), at the end of a run: name the `--debug` features no loaded
1045/// module declared. Tests the declaration, not its description (KNOWN_PERL_ERRORS #1224).
1046pub fn check_debuggable() {
1047  let known = known_debug_features();
1048  let mut unknown: Vec<String> = ENABLED_DEBUG_FEATURES
1049    .read()
1050    .map(|enabled| {
1051      enabled
1052        .iter()
1053        .filter(|f| !known.contains(f))
1054        .cloned()
1055        .collect()
1056    })
1057    .unwrap_or_default();
1058  if !unknown.is_empty() {
1059    unknown.sort();
1060    crate::util::logger::stderr_fresh_line(&format!(
1061      "The debugging feature(s) {} were never declared\n",
1062      unknown.join(", ")
1063    ));
1064    crate::util::logger::stderr_fresh_line(&format!(
1065      "Known debugging features: {}\n",
1066      known.join(", ")
1067    ));
1068  }
1069}
1070
1071/// Whether any `--debug` feature is on.
1072pub fn any_debug_feature_enabled() -> bool {
1073  ENABLED_DEBUG_FEATURES
1074    .read()
1075    .map(|enabled| !enabled.is_empty())
1076    .unwrap_or(false)
1077}
1078
1079/// Perl: truthiness of `$LaTeXML::DEBUG{$name}`.
1080pub fn debug_enabled(name: &str) -> bool {
1081  ENABLED_DEBUG_FEATURES
1082    .read()
1083    .map(|enabled| enabled.contains(name))
1084    .unwrap_or(false)
1085}
1086
1087/// Would an un-featured `Debug`-status record actually reach the log right now? True only
1088/// under `--verbose` (`util/logger.rs` `debug_all`; a `--debug` feature does not admit them)
1089/// AND output is not suppressed.
1090/// The `Debug!` macro gates *message construction* on this: the 2026-08-23
1091/// audit measured up to ~26% of a build-bound conversion spent serializing
1092/// `node_to_string` subtrees into `Debug!` messages that `emit_record` then
1093/// discarded (PERFORMANCE.md, Open levers P0). An atomic load + thread-local
1094/// read — cheap enough for token-frequency call sites.
1095#[inline]
1096pub fn debug_record_enabled() -> bool {
1097  crate::util::logger::debug_all() && !is_log_output_suppressed()
1098}
1099
1100/// Feature-gated debug logging — Perl's `Debug(...) if $LaTeXML::DEBUG{feature}`.
1101/// Usage: `DebugFeature!("frontmatter", "FRONT Add {}", entry)`.
1102/// Logs with the feature name as the `log` target (so output matches the
1103/// previous `log::debug!(target: "frontmatter", ...)` form) and counts a
1104/// Debug in the status report, like `Debug!`. NB deliberately does NOT
1105/// forward to `Debug!` — its 3-expr `(category, object, message)` arm
1106/// would mis-capture a format string with two arguments.
1107#[macro_export]
1108macro_rules! DebugFeature {
1109  ($feature:literal, $($arg:tt)*) => {{
1110    if $crate::common::error::debug_enabled($feature) {
1111      let __diag_guard = $crate::common::error::macro_diag_guard();
1112      $crate::common::error::note_status(
1113        $crate::common::error::LogStatus::Debug, None);
1114      use log::debug;
1115      debug!(target: $feature, $($arg)*);
1116    }
1117  }};
1118}
1119
1120/// Debug-status diagnostics. **Lazy**: the argument expressions — which at
1121/// several sites build whole `node_to_string` subtree serializations — are
1122/// evaluated only when [`debug_record_enabled`] says the record would actually
1123/// be logged (2026-08-23 audit, PERFORMANCE.md Open levers P0). The Debug
1124/// status tally (`note_status`) is preserved unconditionally, so status counts
1125/// are identical to the eager form at every verbosity.
1126#[macro_export]
1127macro_rules! Debug {
1128  ($category:expr_2021, $object:expr_2021, $message:expr_2021) => {{
1129    if $crate::common::error::debug_record_enabled() {
1130      $crate::common::error::emit_record(
1131        $crate::common::error::LogStatus::Debug,
1132        &format!("{}:{}", $category, $object),
1133        &$crate::generate_message!($message))
1134    } else {
1135      $crate::common::error::note_status(
1136        $crate::common::error::LogStatus::Debug, None);
1137    }
1138  }};
1139 ($category:expr_2021, $object:expr_2021, $message:expr_2021, $($details:expr_2021),*) => {{
1140    if $crate::common::error::debug_record_enabled() {
1141      $crate::common::error::emit_record(
1142        $crate::common::error::LogStatus::Debug,
1143        &format!("{}:{}", $category, $object),
1144        &$crate::generate_message!($message, $($details),*))
1145    } else {
1146      $crate::common::error::note_status(
1147        $crate::common::error::LogStatus::Debug, None);
1148    }
1149  }};
1150  ($($simple:expr_2021),*) => {{
1151    $crate::common::error::note_status(
1152      $crate::common::error::LogStatus::Debug, None);
1153    if $crate::common::error::debug_record_enabled() {
1154      let __diag_guard = $crate::common::error::macro_diag_guard();
1155      use log::debug;
1156      debug!($($simple),*);
1157    }
1158  }};
1159
1160}
1161
1162#[macro_export]
1163macro_rules! Info {
1164  ($category:expr_2021, $object:expr_2021, $message:expr_2021) => {{
1165    $crate::common::error::emit_info(
1166      &format!("{}", $category), &format!("{}", $object),
1167      &$crate::generate_message!($message))
1168  }};
1169 ($category:expr_2021, $object:expr_2021, $message:expr_2021, $($details:expr_2021),*) => {{
1170    $crate::common::error::emit_info(
1171      &format!("{}", $category), &format!("{}", $object),
1172      &$crate::generate_message!($message, $($details),*))
1173  }};
1174  ($($simple:expr_2021),*) => {{
1175    let __diag_guard = $crate::common::error::macro_diag_guard();
1176    $crate::common::error::note_status(
1177      $crate::common::error::LogStatus::Info, None);
1178    use log::info;
1179    info!($($simple),*);
1180  }};
1181
1182}
1183
1184#[macro_export]
1185macro_rules! Warn {
1186  ($category:expr_2021, $object:expr_2021, $message:expr_2021) => {{
1187    $crate::common::error::emit_warn(
1188      &format!("{}", $category), &format!("{}", $object),
1189      &$crate::generate_message!($message))
1190  }};
1191 ($category:expr_2021, $object:expr_2021, $message:expr_2021, $($details:expr_2021),*) => {{
1192    $crate::common::error::emit_warn(
1193      &format!("{}", $category), &format!("{}", $object),
1194      &$crate::generate_message!($message, $($details),*))
1195  }}
1196}
1197
1198#[macro_export]
1199macro_rules! Error {
1200  ($category:expr_2021, $object:expr_2021, $message:expr_2021) => {{
1201    $crate::Error!($category,$object,$message,"")
1202  }};
1203 ($category:expr_2021, $object:expr_2021, $message:expr_2021, $($details:expr_2021),*) => {{
1204    $crate::common::error::emit_record(
1205      $crate::common::error::LogStatus::Error,
1206      &format!("{}:{}", $category, $object),
1207      &$crate::generate_message!($message, $($details),*),
1208    );
1209    // In the fatal-demotion scope (bibliography post-processing) the
1210    // too-many/consecutive-error escalations are SKIPPED: their Fatal!
1211    // would demote back into an Error, turning the circuit-breaker into
1212    // an error multiplier (run-233 follow-up: 470 self-feeding
1213    // "Too many errors" lines on 2605.02213). The bib interpreter has its
1214    // own bounded failure latch instead.
1215    // An ignored record (Perl `IGNORE_ERRORS`, Error.pm L362) does nothing at
1216    // all — no count, no cap bookkeeping: 500 identical forward-reference
1217    // errors inside the degraded expl3 raw-load must not trip the consecutive
1218    // cap on the first error after the scope. Once the digestion's end took the cap's Fatal, the phases after it
1219    // raise it no more (`spend_too_many_errors`, 2203.12624: the salvage build stopped at its first dropped Error).
1220    if !$crate::common::error::is_demote_fatals()
1221      && !$crate::common::error::diagnostics_ignored()
1222      && !$crate::common::error::too_many_errors_spent()
1223    {
1224    // Borrow-safe read: an Error! can be raised from inside a `state_mut()`
1225    // scope (e.g. push_value's BUG branch, a constructor's after_digest),
1226    // where a plain `lookup_int` would panic "RefCell already mutably
1227    // borrowed" and abort the conversion (tikz-cd 2001.08973).
1228    let max_from_state = $crate::state::try_lookup_int("MAX_ERRORS");
1229    // Match Perl LaTeXML default of 100 errors before Fatal('too_many_errors').
1230    // Past 100 errors a paper has already failed comprehension; continuing
1231    // produces noise without information. Override via state for tests
1232    // or specific bindings (e.g. tikz_sty raises to 1000, dump-build raises
1233    // to 1_000_000).
1234    let maxerrors = match max_from_state {
1235      // STATE contended: we cannot read the (possibly raised) cap, so skip the
1236      // too-many-errors check for *this* error rather than risk a spurious
1237      // Fatal from a stale default. The next uncontended error re-applies it.
1238      None => usize::MAX,
1239      Some(v) if v > 0 => v as usize,
1240      Some(_) => 100,
1241    };
1242    if $crate::common::error::get_status($crate::common::error::LogStatus::Error) > maxerrors {
1243      $crate::common::error::latch_too_many_errors();
1244      Fatal!(TooManyErrors, MaxLimit(maxerrors), format!("Too many errors (> {maxerrors})!"));
1245    }
1246    // Runaway-loop early-bail: if the same error signature has fired
1247    // MAX_CONSECUTIVE_ERRORS times in a row, we're stuck in a loop
1248    // (the canonical witness is plain-TeX `\tabalign` invoked in math
1249    // mode → unbounded `\halign` cell loop emitting `\hbox` end-mode
1250    // mismatches). Bail before MAX_ERRORS so logs stay short and
1251    // post-processing sees a clear cause. The threshold is well above
1252    // any legitimate same-error pattern (real papers max out at a few
1253    // hundred unique errors).
1254    let __consec_key = format!("{}:{}", $category, $object);
1255    let __consec = $crate::common::error::note_consecutive_error(&__consec_key);
1256    if __consec > $crate::common::error::MAX_CONSECUTIVE_ERRORS {
1257      // Raised again behind a caller that swallowed it (Perl dies at the first): the same Err, not a second line.
1258      if $crate::common::error::too_many_errors_latched() {
1259        return Err($crate::common::error::runaway_reraise(&__consec_key));
1260      }
1261      $crate::common::error::latch_too_many_errors();
1262      Fatal!(
1263        TooManyErrors,
1264        MaxLimit($crate::common::error::MAX_CONSECUTIVE_ERRORS),
1265        $crate::common::error::runaway_message(&__consec_key)
1266      );
1267    }
1268    }
1269  }}
1270}
1271
1272// TODO: flesh out the messages
1273#[macro_export]
1274macro_rules! Fatal {
1275  ($target:expr_2021, $category:expr_2021, $message:expr_2021) => {{
1276    {
1277      use $crate::common::error::{Error as LatexmlError, ErrorCategory::*, ErrorTarget::*};
1278      let __fatal_err = LatexmlError::from($crate::common::error::ErrorData {
1279        target:   $target,
1280        category: $category,
1281        message:  $message.to_string(),
1282      });
1283      if $crate::common::error::is_demote_fatals() {
1284        // Demoted context (bibliography post-processing): count and log as
1285        // an ERROR — the problem is real and must be visible/accounted —
1286        // but never latch the document's sticky fatal. The Err return below
1287        // still aborts the failing digestion; its caller degrades
1288        // gracefully. A document must not be lost to a broken bibliography.
1289        $crate::common::error::emit_record(
1290          $crate::common::error::LogStatus::Error,
1291          "demoted_fatal",
1292          &format!("{}", $message),
1293        );
1294      } else {
1295        // Perl `Fatal` (Common/Error.pm L297+L312) counts AND prints in the
1296        // same call, before it dies. Log here, at the raise, so a caller
1297        // that swallows the `Err` (`let _ = digest(..)` in a binding) cannot
1298        // leave a counted-but-unlogged "phantom fatal"; the catch-site
1299        // `log_fatal` is idempotent for this same fatal.
1300        __fatal_err.log_fatal();
1301      }
1302      // Latch resource-class fatals so layers that flatten errors to strings
1303      // (e.g. the marpa semantics boundary) can still recover the STRUCTURED
1304      // identity downstream. See `take_last_resource_fatal`.
1305      $crate::common::error::record_last_fatal(&__fatal_err);
1306      return Err(__fatal_err);
1307    }
1308  }};
1309}
1310
1311#[macro_export]
1312macro_rules! fatal {
1313  ($target:expr_2021, $category:expr_2021, $message:expr_2021) => {{
1314    use $crate::common::error::{Error as LatexmlError, ErrorCategory::*, ErrorTarget::*};
1315    let __fatal_err = LatexmlError::from($crate::common::error::ErrorData {
1316      target:   $target,
1317      category: $category,
1318      message:  $message.to_string(),
1319    });
1320    // Same contract as `Fatal!`: the `Fatal:` line and the sticky count are
1321    // written HERE, at the raise (Perl `Fatal` prints before it dies), so a
1322    // swallowed `Err` can neither lose the line nor the status.
1323    __fatal_err.log_fatal();
1324    // The RSS fuse and the conversion deadline (`stomach::check_timeout`)
1325    // raise through THIS form, so the resource-fatal latch must be recorded
1326    // here as in `Fatal!` — otherwise `resource_fatal_latched()` never fires
1327    // for a memory-budget abort and the post-Fatal closer noise it gates
1328    // (batch 56cm) is reported anyway (datatool-user +12,
1329    // glossaries-extra-manual +11 in sweep 84).
1330    $crate::common::error::record_last_fatal(&__fatal_err);
1331    return Err(__fatal_err);
1332  }};
1333}
1334
1335/// A message's location line, `\n\tat <locator>`; nothing before the first mouth opens (Perl Error.pm:623).
1336pub fn location_line() -> String {
1337  crate::gullet::get_location_opt()
1338    .map(|at| format!("\n\t{at}"))
1339    .unwrap_or_default()
1340}
1341
1342#[macro_export]
1343macro_rules! generate_message {
1344  ($message:expr_2021) => {
1345    format!(
1346      "{}{}\n\tIn {}:{}:{}\n",
1347      $message,
1348      $crate::common::error::location_line(),
1349      file!(),
1350      line!(),
1351      column!()
1352    )
1353  };
1354  ($message:expr_2021, $detail:expr_2021) => {
1355    format!(
1356      "{}{}\n\t{}\n\tIn {}:{}:{}\n",
1357      $message,
1358      $crate::common::error::location_line(),
1359      $detail,
1360      file!(),
1361      line!(),
1362      column!()
1363    )
1364  };
1365  ($message:expr_2021, $detail:expr_2021, $detail2:expr_2021) => {
1366    format!(
1367      "{}{}\n\t{}\n\t{}\n\tIn {}:{}:{}\n",
1368      $message,
1369      $crate::common::error::location_line(),
1370      $detail,
1371      $detail2,
1372      file!(),
1373      line!(),
1374      column!()
1375    )
1376  };
1377  ($message:expr_2021, $detail:expr_2021, $detail2:expr_2021) => {
1378    format!(
1379      "{}{}\n\t{}\n\t{}\n\tIn {}:{}:{}\n",
1380      $message,
1381      $crate::common::error::location_line(),
1382      $detail,
1383      $detail2,
1384      file!(),
1385      line!(),
1386      column!()
1387    )
1388  };
1389  ($message:expr_2021, $detail:expr_2021, $detail2:expr_2021, $location:expr_2021) => {
1390    format!(
1391      "{}\n\t{}\n\t{}\n\t{}\n\tIn {}:{}:{}\n",
1392      $message,
1393      $location,
1394      $detail,
1395      $detail2,
1396      file!(),
1397      line!(),
1398      column!()
1399    )
1400  };
1401}
1402
1403/// Progress note to BOTH the log and stderr — Perl `Note` (`_printline`): the LOG
1404/// always (if a buffer is bound, ANSI-stripped), STDERR only when the verbosity
1405/// admits it (`$USE_STDERR && $VERBOSITY>=0`). The STDERR gate is the decoupled
1406/// console verbosity ([`crate::util::logger::stderr_shows_info`]), NOT `max_level`
1407/// — under `--quiet` the log-file floor keeps `max_level` at `Info`, but the
1408/// console note must still be silenced (issue #763).
1409#[macro_export]
1410macro_rules! Note {
1411  ($input:expr_2021) => {{
1412    let msg = $input;
1413    $crate::util::logger::note_to_log(&msg.to_string());
1414    if !$crate::common::error::is_log_output_suppressed()
1415      && $crate::util::logger::stderr_shows_info()
1416    {
1417      // (on a fresh line, as Perl's `_freshline`: not glued to a progress note's ` )`)
1418      $crate::util::logger::stderr_fresh_line(&format!("{msg}\n"));
1419    }
1420  }};
1421}
1422
1423/// Progress note to the LOG only — Perl `NoteLog` (`print $LOG … if $LOG`). Always
1424/// written to the bound log buffer (the log is the verbose record), never stderr.
1425#[macro_export]
1426macro_rules! NoteLog {
1427  ($input:expr_2021) => {
1428    $crate::util::logger::note_to_log(&($input).to_string());
1429  };
1430}
1431
1432/// Progress note to STDERR only — Perl `NoteSTDERR` (`if $USE_STDERR &&
1433/// $VERBOSITY>=0`). Never touches the log. Gated on the decoupled console
1434/// verbosity ([`crate::util::logger::stderr_shows_info`]), not `max_level`
1435/// (issue #763).
1436#[macro_export]
1437macro_rules! NoteSTDERR {
1438  ($input:expr_2021) => {
1439    if !$crate::common::error::is_log_output_suppressed()
1440      && $crate::util::logger::stderr_shows_info()
1441    {
1442      let msg = $input;
1443      // A binding's message lands inside its `(Loading …` note, as a logged line does (#945).
1444      $crate::common::error::print_deferred_notes();
1445      $crate::util::logger::stderr_fresh_line(&format!("{msg}\n"));
1446    }
1447  };
1448}
1449
1450pub type Result<T> = result::Result<T, Error>;
1451
1452pub struct Error(Box<ErrorData>);
1453
1454/// As a plain struct would print, since this text reaches the log (`Error:document:convert`) and a panic message:
1455/// the box is no part of what an error says.
1456impl fmt::Debug for Error {
1457  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1458    f.debug_struct("Error")
1459      .field("target", &self.target)
1460      .field("category", &self.category)
1461      .field("message", &self.message)
1462      .finish()
1463  }
1464}
1465
1466/// What an [`struct@Error`] says. Boxed there so that a `Result` costs a pointer: the interpreter's hottest calls
1467/// (`read_token`, `read_x_token`, an argument's read) return `Result`s, and at this struct's size each went through
1468/// stack memory instead of registers (`clippy::result_large_err`).
1469#[derive(Debug)]
1470pub struct ErrorData {
1471  pub target:   ErrorTarget,
1472  pub category: ErrorCategory,
1473  pub message:  String,
1474}
1475
1476impl From<ErrorData> for Error {
1477  fn from(data: ErrorData) -> Self { Error(Box::new(data)) }
1478}
1479
1480impl std::ops::Deref for Error {
1481  type Target = ErrorData;
1482
1483  fn deref(&self) -> &ErrorData { &self.0 }
1484}
1485
1486impl std::ops::DerefMut for Error {
1487  fn deref_mut(&mut self) -> &mut ErrorData { &mut self.0 }
1488}
1489impl ErrorTrait for Error {}
1490
1491#[derive(Debug)]
1492pub enum ErrorCategory {
1493  Init,
1494  Io(io::Error),
1495  NotFound,
1496  Unexpected,
1497  Expected,
1498  Misdefined,
1499  Unknown,
1500  MissingFile,
1501  Malformed,
1502  Libxml,
1503  Convert,
1504  Recursion,
1505  EoF,
1506  Endgroup,
1507  FailedParse,
1508  MaxLimit(usize),
1509  Generic(Box<dyn ErrorTrait + Send + Sync>),
1510  Filename(String),
1511  ToDo,
1512  TokenLimit,
1513  PushbackLimit,
1514  IfLimit,
1515  MemoryBudget,
1516  /// A budgeted run of digestion read all it may ([`crate::gullet::read_budget`]): the run ends, nothing else does. No
1517  /// Fatal: never logged, never latched.
1518  ReadBudget,
1519  /// Not a failure: an eager digestion stopped at the streaming-restart
1520  /// watermark so the CLI can rerun the document under `--streaming` before
1521  /// the memory fuse (batch 56dz). Reported as an Info, never a Fatal.
1522  StreamingRestart,
1523  /// A binding's own object, logged as spelled (Perl `Fatal(…, $object, …)`, Error.pm:271).
1524  Named(String),
1525}
1526
1527#[derive(Debug)]
1528pub enum ErrorTarget {
1529  Package,
1530  Parameter,
1531  ParamSpec,
1532  Prototype,
1533  Converter,
1534  Mouth,
1535  Core,
1536  State,
1537  Stomach,
1538  Codegen,
1539  Macro,
1540  XMath,
1541  MathParser,
1542  Document,
1543  Definition,
1544  TexPool,
1545  Internal,
1546  TargetUnexpected,
1547  TooManyErrors,
1548  Timeout,
1549  /// A binding's own category, logged as spelled (Perl `Fatal($category, …)`, Error.pm:271): a runtime binding's.
1550  Named(String),
1551}
1552
1553impl ErrorTarget {
1554  /// The category slot of a `Fatal:<category>:<object>` line.
1555  pub fn log_name(&self) -> String {
1556    match self {
1557      ErrorTarget::Named(name) => name.clone(),
1558      other => format!("{other:?}"),
1559    }
1560  }
1561}
1562
1563impl ErrorCategory {
1564  /// The object slot of a `Fatal:<category>:<object>` line.
1565  pub fn log_name(&self) -> String {
1566    match self {
1567      ErrorCategory::Named(name) => name.clone(),
1568      other => format!("{other:?}"),
1569    }
1570  }
1571}
1572
1573impl fmt::Display for ErrorCategory {
1574  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1575    use ErrorCategory::*;
1576    match self {
1577      Init => write!(f, "Init"),
1578      Io(err) => err.fmt(f),
1579      NotFound => write!(f, "No matching cities with a population were found."),
1580      MissingFile => write!(f, "missing file"),
1581      Misdefined => write!(f, "misdefined"),
1582      Unknown => write!(f, "unknown"),
1583      Malformed => write!(f, "malformed"),
1584      Expected => write!(f, "expected"),
1585      Unexpected => write!(f, "unexpected"),
1586      Libxml => write!(f, "libxml error"),
1587      Recursion => write!(f, "<recursion>"),
1588      EoF => write!(f, "<EOF>"),
1589      ToDo => write!(f, "TODO"),
1590      Convert => write!(f, "conversion"),
1591      Endgroup => write!(f, "<endgroup>"),
1592      FailedParse => write!(f, "failed to parse"),
1593      MaxLimit(num) => write!(f, "{}", num),
1594      Generic(err) => err.fmt(f),
1595      Filename(name) => write!(f, "file:{name}"),
1596      TokenLimit => write!(f, "token_limit"),
1597      PushbackLimit => write!(f, "pushback_limit"),
1598      IfLimit => write!(f, "if_limit"),
1599      MemoryBudget => write!(f, "memory_budget"),
1600      ReadBudget => write!(f, "read_budget"),
1601      StreamingRestart => write!(f, "streaming-restart"),
1602      Named(name) => write!(f, "{name}"),
1603    }
1604  }
1605}
1606impl fmt::Display for Error {
1607  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1608    write!(
1609      f,
1610      "Error:{}:{:?} {}",
1611      self.category, self.target, self.message
1612    )
1613  }
1614}
1615
1616impl Error {
1617  pub fn log_fatal(&self) {
1618    // One primitive does both halves: the `Fatal:<target>:<category>` line
1619    // AND the sticky `LogStatus::Fatal` latch. Without the latch,
1620    // `Fatal:Timeout:MemoryBudget` etc. printed but the runtime status_code
1621    // stayed at 0 — canvas would classify the worker as OK with an empty
1622    // HTML output. R35.A.
1623    //
1624    // Idempotent per fatal: `Fatal!`/`fatal!` log at the raise and the
1625    // converter/post sinks call this again on the propagated `Err`; the
1626    // same `target:category:message` prints once. A fatal built by hand
1627    // (`Error { .. }` literals) is logged here for the first time.
1628    let key = self.fatal_key();
1629    mute_errors_after_fatal(key.clone());
1630    if self.is_logged_fatal() {
1631      return;
1632    }
1633    emit_record(
1634      LogStatus::Fatal,
1635      &s!(
1636        "Fatal:{}:{}",
1637        self.target.log_name(),
1638        self.category.log_name()
1639      ),
1640      &self.message,
1641    );
1642    FATALS_LOGGED.with(|c| c.borrow_mut().insert(key));
1643  }
1644  fn fatal_key(&self) -> String {
1645    s!(
1646      "{}:{}:{}",
1647      self.target.log_name(),
1648      self.category.log_name(),
1649      self.message
1650    )
1651  }
1652  /// Whether `log_fatal` printed this Fatal in this conversion: an `Err` carrying an already-reported Fatal.
1653  pub fn is_logged_fatal(&self) -> bool {
1654    let key = self.fatal_key();
1655    FATALS_LOGGED.with(|c| c.borrow().contains(&key))
1656  }
1657  /// Record this Fatal as printed, so a sink's `log_fatal` does not print it (a stashed Fatal raised later,
1658  /// `stomach::check_timeout`'s; the runaway re-raise, `runaway_reraise`).
1659  pub fn mark_logged_fatal(&self) {
1660    let key = self.fatal_key();
1661    FATALS_LOGGED.with(|c| c.borrow_mut().insert(key));
1662  }
1663  pub fn todo() -> Self {
1664    Error::from(ErrorData {
1665      target:   ErrorTarget::Internal,
1666      category: ErrorCategory::ToDo,
1667      message:  String::from(
1668        "This section of the code is not yet implemented / ported over from Perl.",
1669      ),
1670    })
1671  }
1672}
1673
1674#[macro_export]
1675macro_rules! unported {
1676  () => {{ ::latexml_core::common::error::Error::todo() }};
1677}
1678
1679impl From<io::Error> for Error {
1680  fn from(err: io::Error) -> Error {
1681    Error::from(ErrorData {
1682      target:   ErrorTarget::Mouth,
1683      category: ErrorCategory::Io(err),
1684      message:  s!("IO error"),
1685    })
1686  }
1687}
1688
1689impl From<Box<dyn ErrorTrait>> for Error {
1690  fn from(err: Box<dyn ErrorTrait>) -> Error {
1691    let message = err.to_string();
1692    Error::from(ErrorData {
1693      target: ErrorTarget::Document,
1694      category: ErrorCategory::Generic(From::from(message.clone())),
1695      message,
1696    })
1697  }
1698}
1699impl From<Box<dyn ErrorTrait + Send + Sync>> for Error {
1700  fn from(err: Box<dyn ErrorTrait + Send + Sync>) -> Error {
1701    Error::from(ErrorData {
1702      target:   ErrorTarget::Document,
1703      message:  err.to_string(),
1704      category: ErrorCategory::Generic(err),
1705    })
1706  }
1707}
1708
1709impl From<String> for Error {
1710  fn from(err: String) -> Error {
1711    Error::from(ErrorData {
1712      target:   ErrorTarget::Document,
1713      category: ErrorCategory::Generic(From::from(err.clone())),
1714      message:  err,
1715    })
1716  }
1717}
1718
1719impl<'a> From<&'a str> for Error {
1720  fn from(err: &'a str) -> Error {
1721    Error::from(ErrorData {
1722      target:   ErrorTarget::Document,
1723      category: ErrorCategory::Generic(From::from(err.to_owned())),
1724      message:  err.to_owned(),
1725    })
1726  }
1727}
1728
1729impl From<()> for Error {
1730  fn from(_e: ()) -> Error {
1731    Error::from(ErrorData {
1732      target:   ErrorTarget::Document,
1733      category: ErrorCategory::Libxml,
1734      message:  s!("LibXML error"),
1735    })
1736  }
1737}
1738
1739impl From<ParseIntError> for Error {
1740  fn from(err: ParseIntError) -> Error {
1741    Error::from(ErrorData {
1742      target:   ErrorTarget::Document,
1743      message:  err.to_string(),
1744      category: ErrorCategory::Generic(Box::new(err)),
1745    })
1746  }
1747}
1748
1749impl From<ParseFloatError> for Error {
1750  fn from(err: ParseFloatError) -> Error {
1751    Error::from(ErrorData {
1752      target:   ErrorTarget::Document,
1753      message:  err.to_string(),
1754      category: ErrorCategory::Generic(Box::new(err)),
1755    })
1756  }
1757}
1758
1759//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1760// Progress Reporting
1761//**********************************************************************
1762// Progress reporting.
1763
1764thread_local! {
1765  /// When true, the progress notes ([`note_begin`]/[`note_end`], [`note_progress`], [`note_progress_detailed`]) log
1766  /// nothing: a digestion the conversion discards reads a file (an `\input` in an author field rehearsed by the
1767  /// frontmatter observer, OXIDIZED_DESIGN_DIVERGENCES #837) or skips a `{comment}`, and its log must be the one without
1768  /// the rehearsal. Not Perl's (it has no rehearsal).
1769  static SILENCE_PROGRESS_NOTES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1770}
1771
1772/// The progress notes silenced for a scope and put back as they were when the guard is dropped (a panic unwinding
1773/// included).
1774#[must_use = "the silence ends when the guard is dropped"]
1775pub struct SilenceProgressNotesGuard {
1776  prev: bool,
1777}
1778
1779impl SilenceProgressNotesGuard {
1780  /// Silence the progress notes until the guard is dropped.
1781  pub fn new() -> Self {
1782    let prev = SILENCE_PROGRESS_NOTES.get();
1783    SILENCE_PROGRESS_NOTES.set(true);
1784    SilenceProgressNotesGuard { prev }
1785  }
1786}
1787
1788impl Default for SilenceProgressNotesGuard {
1789  fn default() -> Self { Self::new() }
1790}
1791
1792impl Drop for SilenceProgressNotesGuard {
1793  fn drop(&mut self) { SILENCE_PROGRESS_NOTES.set(self.prev); }
1794}
1795
1796/// Advance the progress indicator by one step.
1797///
1798/// Perl `Common/Error.pm:ProgressStep` L430-433 ticks a terminal spinner. This
1799/// port draws no spinner — conversion steps go by faster than a spinner can
1800/// usefully render — so the call is a deliberate no-op, kept as the seam Perl
1801/// bindings call through. The reporting that does reach the log is
1802/// [`note_progress`] and the [`note_begin`]/[`note_end`] pair.
1803pub fn progress_step(_note: &str) {
1804  // should we also do a spinner? It's often too fast to spin
1805  // _spinnerstep(note)
1806}
1807
1808pub fn note_progress(stuff: &str) {
1809  use log::info;
1810  if SILENCE_PROGRESS_NOTES.get() {
1811    return;
1812  }
1813  info!(target: "note", "{}", stuff);
1814}
1815
1816// TODO: Rethink this reporting
1817pub fn note_progress_detailed(stuff: &str) {
1818  use log::debug;
1819  if SILENCE_PROGRESS_NOTES.get() {
1820    return;
1821  }
1822  debug!(target: "note", "{}", stuff);
1823}
1824
1825/// Open a named progress stage, logging `(stage...`.
1826///
1827/// Perl `Common/Error.pm:ProgressSpinup` L435ff. Pair every call with
1828/// [`note_end`], which closes the parenthesis — the nesting of those
1829/// parentheses is what makes a conversion log readable as a phase tree.
1830/// Perl also stamps a `NOTE_TIMERS` entry here so the close can report elapsed
1831/// time; this port logs the structure without the timing (per-phase wall times
1832/// are the telemetry module's job; OXIDIZED_DESIGN #1102).
1833pub fn note_begin(stage: &str) {
1834  if SILENCE_PROGRESS_NOTES.get() {
1835    return;
1836  }
1837  // $state->assignMapping('NOTE_TIMERS', $stage, [Time::HiRes::gettimeofday]);
1838  use log::info;
1839  info!(target: "note", "\n({}...", stage);
1840}
1841
1842/// Close the progress stage opened by [`note_begin`], logging the matching `)`.
1843///
1844/// Perl `Common/Error.pm:ProgressSpindown` additionally prints the stage's
1845/// elapsed time from its `NOTE_TIMERS` entry; see [`note_begin`] for why this
1846/// port does not.
1847pub fn note_end(_stage: &str) {
1848  if SILENCE_PROGRESS_NOTES.get() {
1849    return;
1850  }
1851  // if (my $start = $state && $state->lookupMapping('NOTE_TIMERS', $stage)) {
1852  //   $state->assignMapping('NOTE_TIMERS', $stage, undef);
1853
1854  // my $elapsed = Time::HiRes::tv_interval($start, [Time::HiRes::gettimeofday]);
1855  // info!(target: "note", " %.2f sec)", elapsed);
1856  use log::info;
1857  info!(target: "note", " )");
1858}
1859
1860thread_static! {
1861  /// A stage of a [`DeferredNote`]: its text, and whether its `(stage...` is printed (`None`: silenced when it began).
1862  static DEFERRED_NOTES: RefCell<Vec<(String, Option<bool>)>> = RefCell::new(Vec::new());
1863}
1864
1865/// A progress stage that may not happen: a binding load, whose dispatcher both finds the binding and runs it, where
1866/// Perl opens `(Loading <path>...` once `FindFile` found the `.ltxml` (`Core/Mouth/Binding.pm:31`, `Package.pm:2336`).
1867/// Its `(stage...` prints before the first line logged inside it ([`print_deferred_notes`]) or at its end if it
1868/// happened, so what it triggers nests inside it (#945); a stage that did not happen and logged nothing leaves no
1869/// trace (one that logged a line and then declined still shows its note).
1870#[must_use = "the stage ends when the note is dropped"]
1871pub struct DeferredNote {
1872  depth:    usize,
1873  happened: bool,
1874}
1875
1876impl DeferredNote {
1877  /// Begin the stage (a [`note_begin`] held back until it is known to happen).
1878  pub fn begin(stage: &str) -> Self {
1879    let silenced = SILENCE_PROGRESS_NOTES.get();
1880    let mut notes = DEFERRED_NOTES.borrow_mut();
1881    notes.push((stage.to_string(), (!silenced).then_some(false)));
1882    DeferredNote {
1883      depth:    notes.len() - 1,
1884      happened: false,
1885    }
1886  }
1887
1888  /// End the stage; `happened` says the stage took place (a binding was found), so its note prints if it has not.
1889  pub fn end(mut self, happened: bool) { self.happened = happened; }
1890}
1891
1892impl Drop for DeferredNote {
1893  fn drop(&mut self) {
1894    let unprinted = matches!(
1895      DEFERRED_NOTES.borrow().get(self.depth),
1896      Some((_, Some(false)))
1897    );
1898    if self.happened && unprinted {
1899      print_deferred_notes();
1900    }
1901    let stage = {
1902      let mut notes = DEFERRED_NOTES.borrow_mut();
1903      let stage = notes.get(self.depth).cloned();
1904      notes.truncate(self.depth);
1905      stage
1906    };
1907    if let Some((stage, Some(true))) = stage {
1908      note_end(&stage);
1909    }
1910  }
1911}
1912
1913/// Rename the innermost unprinted [`DeferredNote`]: a binding's dispatcher names the file it found
1914/// (a runtime `.rhai` binding's path, #560).
1915pub fn rename_deferred_note(stage: &str) {
1916  if let Some((text, Some(false))) = DEFERRED_NOTES.borrow_mut().last_mut() {
1917    *text = stage.to_string();
1918  }
1919}
1920
1921/// Print every begun, unprinted [`DeferredNote`], outermost first: the logger calls it before it writes a line, so
1922/// the line lands inside them.
1923pub fn print_deferred_notes() {
1924  let pending: Vec<String> = DEFERRED_NOTES
1925    .borrow_mut()
1926    .iter_mut()
1927    .filter(|(_, printed)| *printed == Some(false))
1928    .map(|(stage, printed)| {
1929      *printed = Some(true);
1930      stage.clone()
1931    })
1932    .collect();
1933  for stage in pending {
1934    log::info!(target: "note", "\n({}...", stage);
1935  }
1936}
1937
1938#[cfg(test)]
1939mod tests {
1940  use super::*;
1941
1942  /// The text the log carries (`Error:document:convert`) and a panic prints.
1943  #[test]
1944  fn an_error_debugs_as_a_plain_struct() {
1945    let error = Error::from(ErrorData {
1946      target:   ErrorTarget::Mouth,
1947      category: ErrorCategory::Expected,
1948      message:  "m".into(),
1949    });
1950    assert_eq!(
1951      format!("{error:?}"),
1952      r#"Error { target: Mouth, category: Expected, message: "m" }"#
1953    );
1954  }
1955
1956  // These tests share a thread-local `REPORT`, so each test must
1957  // `initialize_report()` first. They must NOT run truly in parallel
1958  // over the same thread, but cargo's default harness only runs tests
1959  // in parallel on separate threads (each with its own thread-local),
1960  // so this is safe.
1961
1962  #[test]
1963  fn initialize_report_clears_state() {
1964    note_status(LogStatus::Warning, None);
1965    initialize_report();
1966    assert_eq!(get_status(LogStatus::Warning), 0);
1967  }
1968
1969  #[test]
1970  fn note_status_increments_counters() {
1971    initialize_report();
1972    note_status(LogStatus::Warning, None);
1973    note_status(LogStatus::Warning, None);
1974    note_status(LogStatus::Error, None);
1975    assert_eq!(get_status(LogStatus::Warning), 2);
1976    assert_eq!(get_status(LogStatus::Error), 1);
1977    assert_eq!(get_status(LogStatus::Fatal), 0);
1978  }
1979
1980  /// Each Fatal prints once per conversion, however two of them come back by turns (a swallowing caller meeting the
1981  /// runaway re-raise and the cycle guard's Fatal on each pass); a new conversion prints it again.
1982  #[test]
1983  fn each_fatal_prints_once_however_two_alternate() {
1984    let fatal = |target, category| {
1985      Error::from(ErrorData {
1986        target,
1987        category,
1988        message: "m".into(),
1989      })
1990    };
1991    let fatal_lines = |log: String| log.lines().filter(|l| l.starts_with("Fatal:")).count();
1992    let _ = crate::util::logger::init(log::LevelFilter::Warn);
1993    initialize_report();
1994    crate::util::logger::bind_log();
1995    let runaway = runaway_reraise("expected:<relationaltoken>");
1996    for _ in 0..3 {
1997      runaway.log_fatal();
1998      fatal(ErrorTarget::Timeout, ErrorCategory::Recursion).log_fatal();
1999      fatal(ErrorTarget::Mouth, ErrorCategory::Expected).log_fatal();
2000    }
2001    assert_eq!(fatal_lines(crate::util::logger::flush_log()), 2);
2002    initialize_report();
2003    crate::util::logger::bind_log();
2004    fatal(ErrorTarget::Timeout, ErrorCategory::Recursion).log_fatal();
2005    assert_eq!(fatal_lines(crate::util::logger::flush_log()), 1);
2006  }
2007
2008  /// The lowercase `fatal!` form (the RSS fuse, the conversion deadline)
2009  /// latches too; a non-resource target still does not.
2010  #[test]
2011  fn lowercase_fatal_macro_latches_resource_fatals() {
2012    initialize_report();
2013    fn fuse() -> Result<()> {
2014      fatal!(Timeout, MemoryBudget, "Memory budget exceeded (synthetic)");
2015    }
2016    let err = fuse().unwrap_err();
2017    assert!(matches!(err.category, ErrorCategory::MemoryBudget));
2018    assert!(
2019      resource_fatal_latched(),
2020      "the fuse's fatal must set the latch"
2021    );
2022    let latched = take_last_resource_fatal().expect("latch holds the fuse's fatal");
2023    assert!(matches!(latched.category, ErrorCategory::MemoryBudget));
2024    initialize_report();
2025    assert!(!resource_fatal_latched(), "cleared per conversion");
2026    fn missing() -> Result<()> {
2027      fatal!(Mouth, MissingFile, "Can't find file x");
2028    }
2029    let _ = missing();
2030    assert!(
2031      !resource_fatal_latched(),
2032      "a Mouth-target fatal is not a resource fatal"
2033    );
2034    initialize_report();
2035  }
2036
2037  /// An ignoring scope drops its Error and Fatal records whole and tallies them (#825: expl3_sty.rs reports what
2038  /// the no-dump expl3-code.tex reload muted); a nested scope tallies only its own, and counting stops at its end.
2039  #[test]
2040  fn an_ignoring_scope_tallies_what_it_drops() {
2041    initialize_report();
2042    let outer = IgnoreDiagnosticsScope::new();
2043    emit_record(LogStatus::Error, "undefined:\\x", "synthetic");
2044    emit_record(LogStatus::Warning, "w:w", "synthetic");
2045    {
2046      let inner = IgnoreDiagnosticsScope::new();
2047      emit_record(LogStatus::Error, "undefined:\\y", "synthetic");
2048      emit_record(LogStatus::Fatal, "Fatal:Internal:Unexpected", "synthetic");
2049      assert_eq!(inner.dropped(), IgnoredRecords { errors: 1, fatals: 1 });
2050    }
2051    assert!(
2052      diagnostics_ignored(),
2053      "the inner scope restores the outer one's ignoring"
2054    );
2055    assert_eq!(outer.dropped(), IgnoredRecords { errors: 2, fatals: 1 });
2056    drop(outer);
2057    assert_eq!(get_status(LogStatus::Error), 0, "dropped, not counted");
2058    assert_eq!(get_status(LogStatus::Fatal), 0, "dropped, not counted");
2059    let after = IgnoreDiagnosticsScope::new();
2060    drop(after);
2061    emit_record(LogStatus::Error, "undefined:\\z", "synthetic");
2062    assert_eq!(
2063      get_status(LogStatus::Error),
2064      1,
2065      "outside a scope a record counts"
2066    );
2067    initialize_report();
2068  }
2069
2070  /// Once a resource Fatal is latched, an `Error!` raised by the recovery
2071  /// drain is neither counted nor logged (the one rule the six stomach
2072  /// closer guards were instances of; Perl `IGNORE_ERRORS`); before the
2073  /// latch it is.
2074  #[test]
2075  fn errors_are_silent_once_a_resource_fatal_is_latched() {
2076    initialize_report();
2077    let before = get_status(LogStatus::Error);
2078    emit_record(
2079      LogStatus::Error,
2080      "expected:\\fi",
2081      "Missing \\fi (synthetic)",
2082    );
2083    assert_eq!(
2084      get_status(LogStatus::Error),
2085      before + 1,
2086      "counted before any Fatal"
2087    );
2088    fn raise() -> Result<()> {
2089      Fatal!(Timeout, MemoryBudget, "Memory budget exceeded (synthetic)");
2090    }
2091    let _ = raise();
2092    assert!(resource_fatal_latched());
2093    let after_fatal = get_status(LogStatus::Error);
2094    emit_record(
2095      LogStatus::Error,
2096      "expected:\\fi",
2097      "Missing \\fi (synthetic drain)",
2098    );
2099    assert_eq!(
2100      get_status(LogStatus::Error),
2101      after_fatal,
2102      "not counted after the latch"
2103    );
2104    initialize_report();
2105  }
2106
2107  /// Any Fatal mutes the Errors after it (Perl Common/Error.pm:315, :362), but a Fatal of a discarded probe
2108  /// (`DiagnosticsHold::discard`, the frontmatter rehearsal's) or of an ignoring scope does not outlive it.
2109  #[test]
2110  fn any_fatal_mutes_later_errors_unless_its_probe_is_discarded() {
2111    fn raise(message: &str) -> Result<()> {
2112      Fatal!(Stomach, Recursion, message);
2113    }
2114    let error_counted = || {
2115      let before = get_status(LogStatus::Error);
2116      emit_error("expected:\\fi", "x", "Missing \\fi (synthetic)");
2117      get_status(LogStatus::Error) > before
2118    };
2119    initialize_report();
2120    let hold = crate::util::logger::DiagnosticsHold::begin();
2121    let _ = raise("in a discarded probe");
2122    assert!(!error_counted(), "muted inside the probe");
2123    hold.discard();
2124    assert!(
2125      error_counted(),
2126      "a discarded probe's Fatal does not mute the document's Errors"
2127    );
2128    {
2129      let _scope = IgnoreDiagnosticsScope::new();
2130      let _ = raise("in an ignoring scope");
2131    }
2132    assert!(error_counted(), "an ignored Fatal does not mute");
2133    // (a Fatal a script catches, `script_bindings::rhai_err`; one it lets through reaches its sink's `log_fatal`)
2134    let caught = raise("caught by a script").unwrap_err();
2135    unmute_errors_after_caught_fatal(&caught);
2136    assert!(error_counted(), "a caught Fatal does not mute");
2137    caught.log_fatal();
2138    assert!(!error_counted(), "a Fatal let through mutes at its sink");
2139    initialize_report();
2140    let _ = raise("the document's");
2141    assert!(
2142      !resource_fatal_latched() && !error_counted(),
2143      "any Fatal mutes"
2144    );
2145    let hold = crate::util::logger::DiagnosticsHold::begin();
2146    assert!(
2147      !error_counted() && hold.errors_raised() == 1,
2148      "a probe still sees its own muted Error"
2149    );
2150    hold.discard();
2151    initialize_report();
2152    assert!(error_counted(), "cleared per conversion");
2153    initialize_report();
2154  }
2155
2156  /// The Errors a hold drops after a Fatal are its own like its counted ones: a discarded inner hold takes them back
2157  /// from an enclosing hold's `errors_raised`, and `is_empty` sees them (`footnote_number`); `is_empty_but_debug`
2158  /// does not, as they leave nothing to defer. The count resets per conversion.
2159  #[test]
2160  fn a_discarded_inner_hold_takes_back_its_muted_errors() {
2161    use crate::util::logger::DiagnosticsHold;
2162    fn raise() -> Result<()> {
2163      Fatal!(Stomach, Recursion, "the document's");
2164    }
2165    let muted_error = || emit_error("expected:\\fi", "x", "Missing \\fi (synthetic)");
2166    initialize_report();
2167    let _ = raise();
2168    let outer = DiagnosticsHold::begin();
2169    let inner = DiagnosticsHold::begin();
2170    muted_error();
2171    assert!(!inner.is_empty() && inner.is_empty_but_debug());
2172    inner.discard();
2173    assert_eq!(
2174      outer.errors_raised(),
2175      0,
2176      "the inner hold's muted Error is taken back"
2177    );
2178    muted_error();
2179    assert_eq!(outer.errors_raised(), 1);
2180    outer.discard();
2181    muted_error();
2182    assert_eq!(muted_errors(), 1);
2183    initialize_report();
2184    assert_eq!(muted_errors(), 0, "reset per conversion");
2185  }
2186
2187  fn fatal_lines(log: &str) -> usize { log.matches("Fatal:").count() }
2188
2189  /// `Fatal!` prints its `Fatal:` line AT THE RAISE (Perl `Fatal` prints
2190  /// before it dies), so a caller that swallows the `Err` cannot leave a
2191  /// counted-but-unlogged "phantom fatal"; the catch-site `log_fatal` on the
2192  /// same fatal is a no-op. Witness 1903.01633 (`base_utilities.rs`), the 11
2193  /// `let _ = digest(..)` sites in bindings.
2194  #[test]
2195  fn fatal_macro_logs_its_line_at_the_raise_exactly_once() {
2196    let _ = crate::util::logger::init(log::LevelFilter::Warn);
2197    initialize_report();
2198    crate::util::logger::bind_log();
2199    fn raise() -> Result<()> {
2200      Fatal!(Internal, EoF, "synthetic fatal, swallowed by the caller");
2201    }
2202    let err = raise().unwrap_err();
2203    assert_eq!(
2204      fatal_lines(&crate::util::logger::flush_log()),
2205      1,
2206      "logged at the raise"
2207    );
2208    assert_eq!(get_status(LogStatus::Fatal), 1, "and counted");
2209    crate::util::logger::bind_log();
2210    err.log_fatal();
2211    assert_eq!(
2212      fatal_lines(&crate::util::logger::flush_log()),
2213      0,
2214      "the sink does not print it twice"
2215    );
2216    // The lowercase form (RSS fuse, deadline) has the same contract.
2217    crate::util::logger::bind_log();
2218    fn raise_lower() -> Result<()> {
2219      fatal!(Internal, EoF, "synthetic lowercase fatal");
2220    }
2221    let _ = raise_lower();
2222    assert_eq!(fatal_lines(&crate::util::logger::flush_log()), 1);
2223    initialize_report();
2224  }
2225
2226  /// Perl `IGNORE_ERRORS`: a probing scope drops line AND count together.
2227  #[test]
2228  fn ignored_diagnostics_scope_drops_line_and_count_together() {
2229    let _ = crate::util::logger::init(log::LevelFilter::Warn);
2230    initialize_report();
2231    crate::util::logger::bind_log();
2232    let prev = set_ignore_diagnostics(true);
2233    emit_record(LogStatus::Error, "undefined:\\probe", "probe (ignored)");
2234    emit_record(LogStatus::Warning, "expected:probe", "probe (ignored)");
2235    set_ignore_diagnostics(prev);
2236    emit_record(LogStatus::Error, "undefined:\\real", "real");
2237    let log = crate::util::logger::flush_log();
2238    assert_eq!(get_status(LogStatus::Error), 1);
2239    assert_eq!(get_status(LogStatus::Warning), 0);
2240    assert!(
2241      !log.contains("probe"),
2242      "ignored records leave no line:\n{log}"
2243    );
2244    assert!(log.contains("undefined:\\real"), "{log}");
2245    initialize_report();
2246  }
2247
2248  /// A speculative scope's diagnostics (`DiagnosticsHold`): a discard drops
2249  /// its lines AND restores its counts; a commit writes the held lines in
2250  /// order, counted once; a nested hold commits into the enclosing one.
2251  #[test]
2252  fn diagnostics_hold_commits_or_discards_lines_and_counts_together() {
2253    use crate::util::logger::DiagnosticsHold;
2254    let _ = crate::util::logger::init(log::LevelFilter::Warn);
2255    initialize_report();
2256    crate::util::logger::bind_log();
2257    let hold = DiagnosticsHold::begin();
2258    emit_record(LogStatus::Error, "recursion:\\q_no_value", "speculative");
2259    emit_record(LogStatus::Warning, "expected:held", "speculative");
2260    latch_too_many_errors();
2261    assert_eq!(hold.errors_raised(), 1);
2262    assert_eq!(hold.discard(), 2);
2263    assert_eq!(get_status(LogStatus::Error), 0);
2264    assert_eq!(get_status(LogStatus::Warning), 0);
2265    // The runaway gates are restored too: a latch the discarded scope tripped
2266    // must not mute the document's own errors.
2267    assert!(!too_many_errors_latched());
2268    assert_eq!(CONSECUTIVE_ERROR_COUNT.get(), 0);
2269    let outer = DiagnosticsHold::begin();
2270    emit_record(LogStatus::Warning, "expected:first", "kept");
2271    let inner = DiagnosticsHold::begin();
2272    emit_record(LogStatus::Error, "undefined:\\second", "kept");
2273    assert_eq!(inner.errors_raised(), 1);
2274    inner.commit();
2275    assert!(
2276      !crate::util::logger::flush_log().contains("kept"),
2277      "an inner commit writes into the enclosing hold"
2278    );
2279    crate::util::logger::bind_log();
2280    outer.commit();
2281    let log = crate::util::logger::flush_log();
2282    assert!(!log.contains("speculative"), "{log}");
2283    let first = log.find("expected:first").expect("first record written");
2284    let second = log
2285      .find("undefined:\\second")
2286      .expect("second record written");
2287    assert!(first < second, "held records keep their order:\n{log}");
2288    assert_eq!(get_status(LogStatus::Error), 1);
2289    assert_eq!(get_status(LogStatus::Warning), 1);
2290    initialize_report();
2291  }
2292
2293  /// A `what` field of spaces (an `\@latex@error` prefix whose indent expanded, 2606.13031) is never printed blank:
2294  /// `make_generic_message` falls back to its command, every other site to `unknown` (OXIDIZED_DESIGN #1175).
2295  #[test]
2296  fn a_blank_what_field_is_never_logged() {
2297    assert_eq!(
2298      message_object("                ", "\\GenericError"),
2299      "\\GenericError"
2300    );
2301    assert_eq!(message_object(" (mycls) ", "\\ClassError"), "(mycls) ");
2302    assert_eq!(record_target("latex:   "), "latex:unknown");
2303    assert_eq!(record_target("latex:       "), "latex:unknown");
2304    assert_eq!(record_target("latex: "), "latex:unknown");
2305    assert!(matches!(
2306      record_target("latex:(mycls) "),
2307      Cow::Borrowed("latex:(mycls) ")
2308    ));
2309    assert_eq!(record_target("Fatal:timeout: "), "Fatal:timeout:unknown");
2310    assert!(matches!(
2311      record_target("undefined:\\num"),
2312      Cow::Borrowed("undefined:\\num")
2313    ));
2314    let _ = crate::util::logger::init(log::LevelFilter::Warn);
2315    initialize_report();
2316    crate::util::logger::bind_log();
2317    emit_error(
2318      "latex",
2319      "                ",
2320      "LaTeX Error: Unicode character ^^B (U+0002)",
2321    );
2322    let log = crate::util::logger::flush_log();
2323    initialize_report();
2324    let line = log
2325      .lines()
2326      .find(|l| l.starts_with("Error:"))
2327      .unwrap_or_default();
2328    assert!(line.starts_with("Error:latex:unknown LaTeX Error"), "{log}");
2329  }
2330
2331  /// The function-form cap fires `Fatal:TooManyErrors` exactly once.
2332  #[test]
2333  fn emit_error_fires_the_too_many_errors_fatal_once() {
2334    let _ = crate::util::logger::init(log::LevelFilter::Warn);
2335    initialize_report();
2336    crate::util::logger::bind_log();
2337    for _ in 0..(MAX_CONSECUTIVE_ERRORS + 60) {
2338      emit_error("unexpected", "}", "synthetic repeat");
2339    }
2340    let log = crate::util::logger::flush_log();
2341    assert_eq!(
2342      log.matches("Fatal:TooManyErrors").count(),
2343      1,
2344      "{}",
2345      log.len()
2346    );
2347    // With `MAX_ERRORS` unset the total cap (100) fires before the consecutive one.
2348    assert!(log.contains("(> 100)"), "{}", log.len());
2349    assert!(too_many_errors_latched());
2350    initialize_report();
2351  }
2352
2353  /// Past the cap every `Error!` raised `Err(TooManyErrors)` again (its record dropped): the build of what a Fatal kept
2354  /// stopped at its first Error (2203.12624). Once the digestion's end spent the cap, an `Error!` returns `Ok`.
2355  #[test]
2356  fn an_error_past_the_spent_cap_raises_nothing() {
2357    let _ = crate::util::logger::init(log::LevelFilter::Warn);
2358    initialize_report();
2359    crate::util::logger::bind_log();
2360    fn raise(i: usize) -> Result<()> {
2361      Error!("unexpected", format!("\\e{i}"), "synthetic distinct error");
2362      Ok(())
2363    }
2364    let outcomes: Vec<bool> = (0..102).map(|i| raise(i).is_err()).collect();
2365    assert_eq!(
2366      outcomes.iter().position(|&err| err),
2367      Some(100),
2368      "the 101st raises the cap"
2369    );
2370    assert!(outcomes[101], "the cap re-raises until it is spent");
2371    spend_too_many_errors();
2372    assert!(raise(102).is_ok() && raise(103).is_ok());
2373    let log = crate::util::logger::flush_log();
2374    assert_eq!(log.matches("Fatal:TooManyErrors").count(), 1, "{log}");
2375    assert_eq!(log.matches("Error:unexpected").count(), 101, "{log}");
2376    initialize_report();
2377    assert!(!too_many_errors_spent());
2378  }
2379
2380  #[test]
2381  fn fatal_macro_latches_resource_fatals() {
2382    // The `Fatal!` macro must record Timeout-target fatals in the
2383    // resource-fatal latch so boundaries that flatten errors to strings
2384    // (marpa semantics) can recover the structured identity (P1-4).
2385    initialize_report();
2386    fn raise() -> Result<()> {
2387      Fatal!(
2388        Timeout,
2389        TokenLimit,
2390        "Token limit of 5 exceeded, infinite loop?"
2391      );
2392    }
2393    let err = raise().unwrap_err();
2394    assert!(matches!(err.target, ErrorTarget::Timeout));
2395    let latched = take_last_resource_fatal().expect("latch must hold the fatal");
2396    assert!(matches!(latched.target, ErrorTarget::Timeout));
2397    assert!(matches!(latched.category, ErrorCategory::TokenLimit));
2398    assert_eq!(latched.message, "Token limit of 5 exceeded, infinite loop?");
2399    // take() clears the latch.
2400    assert!(take_last_resource_fatal().is_none());
2401    // Non-Timeout fatals are NOT latched (the latch serves resource fatals).
2402    fn raise_other() -> Result<()> {
2403      Fatal!(Internal, EoF, "fell off the end");
2404    }
2405    let _ = raise_other().unwrap_err();
2406    assert!(take_last_resource_fatal().is_none());
2407    // initialize_report clears a stale latch.
2408    let _ = raise().unwrap_err();
2409    initialize_report();
2410    assert!(take_last_resource_fatal().is_none());
2411  }
2412
2413  #[test]
2414  fn fatal_status_is_sticky_and_returns_1() {
2415    initialize_report();
2416    note_status(LogStatus::Fatal, None);
2417    note_status(LogStatus::Fatal, None);
2418    // get_status for Fatal returns 0 or 1, not a counter.
2419    assert_eq!(get_status(LogStatus::Fatal), 1);
2420  }
2421
2422  #[test]
2423  fn get_status_code_priority_order() {
2424    initialize_report();
2425    assert_eq!(get_status_code(), 0, "clean state → 0");
2426    note_status(LogStatus::Warning, None);
2427    assert_eq!(get_status_code(), 1, "warning → 1");
2428    note_status(LogStatus::Error, None);
2429    assert_eq!(get_status_code(), 2, "error wins over warning → 2");
2430    note_status(LogStatus::Fatal, None);
2431    assert_eq!(get_status_code(), 3, "fatal wins over error → 3");
2432  }
2433
2434  #[test]
2435  fn status_message_clean_is_no_obvious_problems() {
2436    initialize_report();
2437    assert_eq!(get_status_message(), "No obvious problems");
2438  }
2439
2440  #[test]
2441  fn status_message_plural_warnings() {
2442    initialize_report();
2443    note_status(LogStatus::Warning, None);
2444    let m = get_status_message();
2445    assert_eq!(m, "1 warning", "singular form");
2446
2447    note_status(LogStatus::Warning, None);
2448    let m = get_status_message();
2449    assert_eq!(m, "2 warnings", "plural form");
2450  }
2451
2452  #[test]
2453  fn status_message_multiple_categories_joined() {
2454    initialize_report();
2455    note_status(LogStatus::Warning, None);
2456    note_status(LogStatus::Warning, None);
2457    note_status(LogStatus::Error, None);
2458    let m = get_status_message();
2459    assert!(
2460      m.contains("2 warnings") && m.contains("1 error") && m.contains("; "),
2461      "got {m:?}"
2462    );
2463  }
2464
2465  #[test]
2466  fn suppress_log_output_returns_prior_value() {
2467    let prior = set_suppress_log_output(true);
2468    assert!(is_log_output_suppressed());
2469    let prior2 = set_suppress_log_output(false);
2470    assert!(prior2, "round-trip prior value");
2471    assert!(!is_log_output_suppressed());
2472    // Clean up to original state.
2473    set_suppress_log_output(prior);
2474  }
2475
2476  /// The guard puts the flag back on drop — also when the scope panics (77i r3: a speculative title-page run that
2477  /// panicked left the thread's later conversions without Info/Warning lines).
2478  #[test]
2479  fn suppress_log_output_guard_restores_on_drop_and_unwind() {
2480    set_suppress_log_output(false);
2481    {
2482      let _guard = SuppressLogOutputGuard::new(true);
2483      assert!(is_log_output_suppressed());
2484    }
2485    assert!(!is_log_output_suppressed());
2486    let unwound = std::panic::catch_unwind(|| {
2487      let _guard = SuppressLogOutputGuard::new(true);
2488      panic!("speculative run panicked");
2489    });
2490    assert!(unwound.is_err());
2491    assert!(!is_log_output_suppressed());
2492    set_suppress_log_output(true);
2493    reset_suppress_log_output();
2494    assert!(!is_log_output_suppressed());
2495  }
2496}