latexml/core_interface.rs
1use std::{path::Path, rc::Rc, sync::LazyLock};
2
3// Top-level macro re-exports.
4use latexml_core::{CharToken, Core, Debug, Error, Explode, Fatal, T_CS, T_SPACE, fatal, map, s};
5use latexml_core::{
6 common::{
7 DigestionMode, arena,
8 error::{self, ErrorTarget, Result, emit_info, emit_warn, note_begin, note_end},
9 model,
10 store::Stored,
11 },
12 definition::{Definition, ExpansionBody, expandable::Expandable},
13 digested::Digested,
14 document::Document,
15 gullet,
16 list::List,
17 pin,
18 rewrite::{Rewrite, RewriteOptions},
19 state::{self, Scope},
20 stomach,
21 token::Token,
22 tokens::Tokens,
23 util::{pathname, pathname::PathnameFindOptions},
24};
25use latexml_math_parser::MathParser;
26use regex::Regex;
27use rustc_hash::FxHashMap as HashMap;
28
29// Process-once cached env var (see WISDOM #56 — getenv hot-path race).
30static LATEXML_DUMP: LazyLock<Option<String>> =
31 LazyLock::new(|| std::env::var("LATEXML_DUMP").ok());
32
33/// The latexml-oxide version exposed to bindings as the state value
34/// `LATEXML_VERSION` — the Rust analog of Perl's `$LaTeXML::VERSION`. This is
35/// **our own** crate version (`latexml_oxide`), not the emulated Perl LaTeXML's,
36/// rendered as a bare `X.Y.Z`: Cargo's `_MAJOR`/`_MINOR`/`_PATCH` components drop
37/// any `-rc`/pre-release suffix, so a version-gate parser (BookML's `.ltxml`
38/// check or the XSLT `b:version-leq`) sees three integer parts. `latexml_contrib`
39/// and `latexml_post` can't read this crate's version directly (reverse dep), so
40/// it is injected via state at session init and read back where needed.
41pub const LATEXML_VERSION: &str = concat!(
42 env!("CARGO_PKG_VERSION_MAJOR"),
43 ".",
44 env!("CARGO_PKG_VERSION_MINOR"),
45 ".",
46 env!("CARGO_PKG_VERSION_PATCH"),
47);
48use latexml_package::prelude::{
49 InputDefinitionOptions, InputOptions, input_content, input_definitions,
50};
51
52/// Perl `Core.pm` L272 `s/^\[([^\]]*)\]//` — the preload option bracket, which
53/// comes at the *front* of the spec (`[twocolumn,11pt]article.cls`).
54static LATEX_OPTION_REGEX: LazyLock<Regex> =
55 LazyLock::new(|| Regex::new(r"^\[([^\]]*)\]").unwrap());
56
57// Regex for parsing DefMathRewrite calls from .latexml files
58// Matches: DefMathRewrite( ... );
59static DEF_MATH_REWRITE_RE: LazyLock<Regex> =
60 LazyLock::new(|| Regex::new(r"(?s)DefMathRewrite\(([^;]+)\);").unwrap());
61// Key-value patterns within DefMathRewrite
62static SCOPE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"scope\s*=>\s*'([^']+)'").unwrap());
63static MATCH_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"match\s*=>\s*'([^']*)'").unwrap());
64static ROLE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"role\s*=>\s*'([^']+)'").unwrap());
65static NAME_ATTR_RE: LazyLock<Regex> =
66 LazyLock::new(|| Regex::new(r"(?:^|,)\s*name\s*=>\s*'([^']*)'").unwrap());
67static MEANING_RE: LazyLock<Regex> =
68 LazyLock::new(|| Regex::new(r"meaning\s*=>\s*'([^']*)'").unwrap());
69
70#[derive(Default)]
71pub struct DigestionOptions {
72 pub mode: Option<DigestionMode>,
73 pub noinitialize: Option<bool>,
74 pub preamble: Option<String>,
75 pub postamble: Option<String>,
76}
77
78/// What `DigestionAPI::digest_adaptive` produced: the whole eager box list, or a
79/// finished streamed document when the run crossed the spill watermark.
80pub enum AdaptiveOutcome {
81 Eager(Digested),
82 /// Boxed: a `Document` is large next to the `Rc` handle (clippy
83 /// `large_enum_variant`).
84 Streamed(Box<Document>),
85}
86
87pub trait DigestionAPI {
88 fn initialize_singletons(&mut self, preloads: Vec<String>) -> Result<()>;
89 fn digest(
90 &mut self,
91 request: String,
92 preamble: Option<String>,
93 postamble: Option<String>,
94 mode: Option<DigestionMode>,
95 no_init: bool,
96 ) -> Result<Digested>;
97 fn digest_setup(
98 &mut self,
99 request: String,
100 preamble: Option<String>,
101 postamble: Option<String>,
102 mode: Option<DigestionMode>,
103 ) -> Result<String>;
104 fn digest_file(&mut self, request: String, options: DigestionOptions) -> Result<Digested>;
105 fn digest_internal(&mut self) -> Result<Digested>; // used to be "finishDigestion"
106 /// Eager digestion that turns into streaming pass 1 at an RSS-driven yield
107 /// seam (single pass, bounded memory) instead of restarting from the top;
108 /// a document that never crosses the spill watermark comes back whole as
109 /// `AdaptiveOutcome::Eager`.
110 fn digest_adaptive(
111 &mut self,
112 request: String,
113 preamble: Option<String>,
114 postamble: Option<String>,
115 mode: Option<DigestionMode>,
116 transition_budget: usize,
117 ) -> Result<AdaptiveOutcome>;
118 /// Streaming front half (spill store, deferred root, yield knobs); returns
119 /// the fragment index. See the `Core` impl.
120 fn stream_setup(
121 &mut self,
122 document: &mut Document,
123 budget: usize,
124 ) -> Result<latexml_core::sxml::FragmentIndex>;
125 /// Streaming pass 1 (digest → absorb → spill at legal seams), optionally
126 /// seeded with already-digested bodies; returns whether a fatal stopped it.
127 fn stream_pass1(
128 &mut self,
129 document: &mut Document,
130 index: &mut latexml_core::sxml::FragmentIndex,
131 seed: Option<Vec<Digested>>,
132 ) -> Result<bool>;
133 /// Streaming tail: root hooks, pass 2 over the spilled segments, finalize.
134 fn stream_finish(
135 &mut self,
136 document: Document,
137 index: latexml_core::sxml::FragmentIndex,
138 fatal_stop: bool,
139 phase_clock: std::time::Instant,
140 ) -> Result<Document>;
141 fn convert_file(&mut self, filepath: String) -> Result<Document>;
142 /// Streaming (fragmented) conversion: interleaved digest→build with
143 /// spill-to-disk, a streaming pass 2, and placeholder-spliced assembly.
144 /// The Perl-parity eager path is `digest` + `convert_document`; this is the
145 /// sanctioned bounded-memory divergence (OXIDIZED_DESIGN), activated only
146 /// via `Config::streaming`.
147 fn convert_streaming(
148 &mut self,
149 request: String,
150 preamble: Option<String>,
151 postamble: Option<String>,
152 mode: Option<DigestionMode>,
153 budget: usize,
154 ) -> Result<Document>;
155 fn convert_document(&mut self, digested: Digested) -> Result<Document>;
156 // Mocks
157 /// Load preamble content. Perl: Core.pm loadPreamble
158 fn load_preamble(&mut self, preamble: String) {
159 let content = if preamble == "standard_preamble.tex" {
160 "literal:\\documentclass{article}\\begin{document}".to_string()
161 } else {
162 preamble
163 };
164 input_content(&content, InputOptions::default()).ok();
165 }
166 /// Load postamble content. Perl: Core.pm loadPostamble
167 fn load_postamble(&mut self, postamble: String) {
168 let content = if postamble == "standard_postamble.tex" {
169 "literal:\\end{document}".to_string()
170 } else {
171 postamble
172 };
173 input_content(&content, InputOptions::default()).ok();
174 }
175}
176
177/// Parse a preload spec into `(name, ext, options)`.
178///
179/// Mirrors Perl `Core.pm:initializeState` (regexes
180/// `s/^\[([^\]]*)\]//` then `s/\.(\w+)$//`): the option bracket
181/// comes at the *front*, e.g. `[ids,mathlexemes]latexml.sty`.
182/// Defaults to `ext = "sty"` when the spec has no `.<ext>` suffix.
183pub(crate) fn parse_preload_spec(preload: &str) -> (String, String, Vec<String>) {
184 let (base, options) = match preload
185 .strip_prefix('[')
186 .and_then(|rest| rest.find(']').map(|end| (&rest[..end], &rest[end + 1..])))
187 {
188 Some((opts_str, rest)) => {
189 let opts: Vec<String> = opts_str
190 .split(',')
191 .map(|s| s.trim().to_string())
192 .filter(|s| !s.is_empty())
193 .collect();
194 (rest.to_string(), opts)
195 },
196 None => (preload.to_string(), vec![]),
197 };
198 let (name, ext) = match base.rfind('.') {
199 Some(pos) => (base[..pos].to_string(), base[pos + 1..].to_string()),
200 None => (base.clone(), String::from("sty")),
201 };
202 (name, ext, options)
203}
204
205/// One guarded digestion step: `digest_next_body(None)` under the salvage
206/// policy `digest_internal` has always applied (extracted verbatim so the
207/// eager loop and the streaming driver share ONE policy). `Ok(true)` =
208/// continue; `Ok(false)` = a Fatal was recovered (announced + latched, boxes
209/// salvaged) and digestion must stop; `Err` = a resource fatal that must not
210/// be recovered.
211/// Can we create files in `dir`? Probes by creating and removing a uniquely
212/// named entry — the only answer that is true for the actual operation, since
213/// permission bits, read-only mounts, and full filesystems all present
214/// differently and `metadata().permissions()` sees none of them reliably.
215fn dir_is_writable(dir: &Path) -> bool {
216 let probe = dir.join(format!(".latexml-writable-{}", std::process::id()));
217 match std::fs::File::create(&probe) {
218 Ok(_) => {
219 let _ = std::fs::remove_file(&probe);
220 true
221 },
222 Err(_) => false,
223 }
224}
225
226/// Diagnostic (`LXML_TRACE_FRAGMENT_RC`): after a fragment is absorbed, every
227/// box in it should be referenced by the fragment alone (plus `node_boxes`,
228/// which the streaming sweep drops). Report the boxes with extra holders, by
229/// kind and depth, so a retention can be attributed.
230fn trace_fragment_holders(boxes: &[Digested]) {
231 use latexml_core::digested::DigestedData;
232 fn walk(
233 d: &Digested,
234 depth: usize,
235 expected: usize,
236 out: &mut Vec<String>,
237 seen: &mut rustc_hash::FxHashSet<usize>,
238 ) {
239 // A whatsit reaches its content through an argument AND a property (the
240 // same handle twice): visit each allocation once, or the walk is
241 // exponential in the nesting depth.
242 if !seen.insert(d.as_ptr() as usize) {
243 return;
244 }
245 let (kind, extra) = match d.data() {
246 DigestedData::TBox(_) => ("TBox", String::new()),
247 DigestedData::List(l) => ("List", format!(" n={}", l.borrow().boxes.len())),
248 DigestedData::Whatsit(w) => ("Whatsit", format!(" {}", w.borrow().definition.get_cs())),
249 DigestedData::Alignment(_) => ("Alignment", String::new()),
250 _ => ("other", String::new()),
251 };
252 let rc = d.strong_count();
253 if rc > expected && out.len() < 40 {
254 out.push(format!(
255 " depth {depth} rc {rc} (expected {expected}) {kind}{extra}"
256 ));
257 }
258 match d.data() {
259 DigestedData::List(l) => {
260 for c in &l.borrow().boxes {
261 walk(c, depth + 1, 1, out, seen);
262 }
263 },
264 DigestedData::Whatsit(w) => {
265 let w = w.borrow();
266 for a in w.args.iter().flatten() {
267 walk(a, depth + 1, 1, out, seen);
268 }
269 for (_, v) in w.properties.iter() {
270 if let Stored::Digested(c) = v {
271 walk(c, depth + 1, 1, out, seen);
272 }
273 }
274 },
275 _ => {},
276 }
277 }
278 let mut out = Vec::new();
279 let mut seen = rustc_hash::FxHashSet::default();
280 for b in boxes {
281 walk(b, 0, 1, &mut out, &mut seen);
282 }
283 eprintln!(
284 "fragment holders: {} boxes walked, {} with extra holders",
285 seen.len(),
286 out.len()
287 );
288 for l in out {
289 eprintln!("{l}");
290 }
291}
292
293thread_local! {
294 /// How many times `digest_setup` ran on this thread: the adaptive transition
295 /// must digest ONCE (a from-scratch streaming restart runs it twice).
296 static DIGEST_SETUP_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
297}
298
299/// See `DIGEST_SETUP_COUNT`.
300pub fn digest_setup_count() -> usize { DIGEST_SETUP_COUNT.with(|c| c.get()) }
301
302thread_local! {
303 /// Perl `$$stomach{rescued_boxes}` (Common/Error.pm `hardYankProcessing`
304 /// L336-338): the bodies digested before a resource Fatal, kept for the
305 /// salvage pass that `finishDigestion` re-collects them from.
306 static RESCUED_BOXES: std::cell::RefCell<Vec<Digested>> =
307 const { std::cell::RefCell::new(Vec::new()) };
308}
309
310/// Release core TeX/LaTeX engine state before post-processing begins on large
311/// or split documents, returning freed arena/state memory to the OS while
312/// keeping end-of-run diagnostics (`REPORT`, `LOGGER`, `telemetry`, watchdog)
313/// intact. See [`latexml_core::release_core_state_for_post`].
314pub fn release_core_state_for_post() {
315 RESCUED_BOXES.with(|r| r.borrow_mut().clear());
316 latexml_core::release_core_state_for_post();
317 latexml_engine::reset_conversion_state();
318 latexml_package::reset_conversion_state();
319 latexml_math_parser::reset_conversion_notices();
320 crate::heap_trim::release_free_heap();
321}
322
323/// Perl `hardYankProcessing` (Common/Error.pm L320-348): after a Fatal there
324/// is nothing left to do in the main processing — rescue the digested bodies
325/// and reset the gullet (pushback, mouth stack, mouth), so the salvage
326/// `digest_internal` re-collects the rescue and reads NO further input. Until
327/// this existed the salvage pass kept reading the live mouth past the Fatal:
328/// jlreq's `PushbackLimit` fired inside the class, then luatexja and the whole
329/// body were converted with every Error record muted by the post-Fatal latch
330/// (asternote, hideanswer-doc, inlinelabel, jpnedumathsymbols-doc: 8 of 22
331/// undefined macros tallied with no `Error:` line — diagnostics audit
332/// 2026-09-20). Perl also `\relax`es the busy token; with the input gone the
333/// loop cannot resume, so that step is not needed here.
334fn hard_yank_processing(boxes: Vec<Digested>) {
335 RESCUED_BOXES.with(|r| *r.borrow_mut() = boxes);
336 gullet::flush();
337 // (Perl's `hardYankProcessing` empties the token stack too, Common/Error.pm:329: a re-raised resource Fatal —
338 // `Timeout:Convert`, the RSS fuse, `TokenLimit`, `PushbackLimit` — is salvaged and built, and a stale stack would
339 // fail that build's first push as a ghost recursion Fatal, as the recovery arms' clear guards against (2410.07647,
340 // 2105.02599; review rev131fix finding 1). The recursion Fatal's message already holds its stack, stomach.rs.)
341 stomach::clear_token_stack();
342}
343
344fn digest_step_guarded(boxes: &mut Vec<Digested>) -> Result<bool> {
345 match stomach::digest_next_body(None) {
346 Ok(next_bodies) => {
347 boxes.extend(next_bodies);
348 Ok(true)
349 },
350 Err(e) => finish_digestion_fatal(e, boxes).map(|()| false),
351 }
352}
353
354/// A Fatal that ended digestion: logged and latched, the boxes of every pending level added to `boxes` (Perl's
355/// `hardYankProcessing` rescues the innermost `@LaTeXML::LIST`, Common/Error.pm:336-338, and `finishDigestion` builds
356/// it, LaTeXML.pm:251-259; OD #251); the input after it stays unread. `Err` re-raises a resource Fatal.
357/// Shared by every digestion loop: the eager steps, a Fatal stashed in the last step, streaming pass 1.
358fn finish_digestion_fatal(e: Error, boxes: &mut Vec<Digested>) -> Result<()> {
359 use latexml_core::common::error::ErrorCategory;
360 // A streaming-restart stop is not a failure: the CLI reruns the document under --streaming (no salvage, no Fatal
361 // line). The resource Fatals end the run where they fire (R35.A: a runaway paper fails loudly, never as an empty
362 // document): the RSS fuse (`Timeout`-target `MemoryBudget`; the `Stomach`-target box ceilings below free their own
363 // accumulation), the wall clock, the token and pushback limits.
364 if matches!(e.category, ErrorCategory::StreamingRestart) {
365 return Err(e);
366 }
367 if matches!(
368 (&e.target, &e.category),
369 (ErrorTarget::Timeout, ErrorCategory::MemoryBudget)
370 | (ErrorTarget::Timeout, ErrorCategory::Convert)
371 | (ErrorTarget::Timeout, ErrorCategory::TokenLimit)
372 | (ErrorTarget::Timeout, ErrorCategory::PushbackLimit)
373 ) {
374 emit_warn(
375 "recovery",
376 "digest_internal",
377 &format!(
378 "digest_internal: resource failure ({:?}/{:?}) — not recovering",
379 e.target, e.category
380 ),
381 );
382 return Err(e);
383 }
384 // The Fatal's one line and its sticky status (`log_fatal` does both; a salvage never reclassifies the verdict, user
385 // policy 2026-07-28; guards `101_fatal_salvages_partial_document`, `fatal_status_is_sticky_and_returns_1`).
386 e.log_fatal();
387 // (a latched error cap is this Fatal's or came before it: the build of what is kept raises it no more, where every
388 // `Error!` past the cap returned it and stopped the build at its first dropped Error, 2203.12624)
389 error::spend_too_many_errors();
390 // (the tokens the failed invocations left on the stack go, as Perl's `hardYankProcessing` empties it for every
391 // Fatal: left there, the next digestion — the build's — failed its first push, 2410.07647, 2105.02599)
392 stomach::clear_token_stack();
393 // What the failed body digested is kept (a `document` environment is one body: without it a Fatal anywhere in the
394 // body wrote a 39-byte document; 2508.07407, ar5iv #556), with two exceptions:
395 // - the stomach's runaway guards drop the innermost level, the 50k-box repeating window, and keep the outer ones;
396 // - the token-loop guards (`Timeout:Recursion`, the mouth's input nesting) keep nothing: on 2605.25400 the salvage
397 // revived the poisoned loop in the build, an 8.7 s Fatal became a 2 m 12 s timeout writing a zero-byte file.
398 // `TooManyErrors`, `Timeout:IfLimit` (2006.14937's 24 `.pgf` figures), `Mouth:EoF`, a binding's Fatal and every
399 // other one keep it all; `salvage_pending_box_lists` still refuses a salvage that is itself runaway output.
400 let drop_innermost = match (&e.target, &e.category) {
401 (ErrorTarget::Stomach, ErrorCategory::Recursion | ErrorCategory::MemoryBudget) => Some(true),
402 (ErrorTarget::Timeout | ErrorTarget::Mouth, ErrorCategory::Recursion) => None,
403 _ => Some(false),
404 };
405 // What is kept still has to be built. The Fatal is announced and its document kept, so it leaves the latch the math
406 // parser reads a resource Fatal from (`take_last_resource_fatal`): left there, the first formula a semantic action
407 // rejects took it for its own and dropped the document; `resource_fatal_latched` stays set. A conditional of the
408 // build (a rewrite's, a constructor's) would trip the spent guard again, so the phases after digestion get its
409 // budget afresh, and a loop the build re-enters still ends at the limit.
410 if matches!(e.category, ErrorCategory::IfLimit) {
411 error::take_last_resource_fatal();
412 if state::if_limit() > 0 {
413 state::set_if_limit(state::if_count() + state::if_limit());
414 }
415 }
416 if let Some(drop_innermost) = drop_innermost {
417 let (salvaged, closed) = stomach::salvage_pending_box_lists(drop_innermost);
418 if !salvaged.is_empty() {
419 emit_info(
420 "recovery",
421 "digest_internal",
422 &format!(
423 "digest_internal: salvaged {} box(es) digested before the fatal, {closed} unfinished construct(s) closed",
424 salvaged.len()
425 ),
426 );
427 boxes.extend(salvaged);
428 }
429 }
430 Ok(())
431}
432
433/// The document head shared by the eager and streaming paths: a fresh
434/// [`Document`] with the schema model loaded and the preload PIs inserted
435/// (the front half of `convert_document`, extracted verbatim).
436fn build_document_head(preloads: &[String]) -> Result<Document> {
437 // (no `d`-token evidence carries over from an earlier document on this thread)
438 latexml_math_parser::clear_differential_evidence();
439 let mut document = Document::new();
440 {
441 // TODO: Can we disentangle the ownership to avoid the clone?
442 let paths_stored = state::get_search_paths();
443 let schema_paths = paths_stored
444 .iter()
445 .map(String::as_str)
446 .collect::<Vec<&str>>();
447 let default_model_load = model::with_schema_data(|schema_opt| match schema_opt {
448 None => true,
449 Some(v) => v.last() == Some(&pin!("LaTeXML")),
450 });
451 if default_model_load {
452 // Compile-time load of model AND indirect model. Single
453 // shared instantiation lives at `crate::load_latexml_default_model`
454 // so LTO can keep exactly one `_ModelLoader::build_model` in
455 // the final binary (~600 KiB per copy otherwise).
456 crate::load_latexml_default_model();
457 } else {
458 // Eager-load at runtime
459 model::load_schema(schema_paths.as_slice())?; // If needed?
460 }
461 if state::has_search_paths() {
462 {
463 if state::lookup_bool("INCLUDE_COMMENTS") {
464 let paths_string = state::with_search_paths(|paths| {
465 paths
466 .iter()
467 .map(String::as_str)
468 .collect::<Vec<&str>>()
469 .join(",")
470 });
471 let attributes = map! {s!("searchpaths") => paths_string};
472 document.insert_pi("latexml", Some(attributes))?;
473 }
474 }
475 }
476 }
477
478 for preload in preloads {
479 if preload.ends_with(".pool") {
480 continue;
481 }
482 // Perl `Core.pm` L268-277 rewrites `$preload` IN PLACE with `s///`, so
483 // the option bracket and the `.cls`/`.sty` suffix are gone from the
484 // string that becomes the attribute value, and the captured options ride
485 // along as a second attribute. `Regex::replace_all` RETURNS a new string
486 // rather than mutating its input, so discarding the result — as this loop
487 // did until 2026-07-29 — stripped nothing at all:
488 // `--preload=[twocolumn,11pt]article.cls` emitted
489 // `<?latexml class="[twocolumn,11pt]article.cls"?>` where Perl emits
490 // `<?latexml class="article" options="twocolumn,11pt"?>`.
491 //
492 // Deliberately NOT routed through `parse_preload_spec` above: that
493 // splits on the LAST `.` and so would also eat a non-package extension
494 // (`--preload=mystyle.tex` -> `package="mystyle"`), while Perl strips
495 // only the two literal suffixes and leaves anything else attached. It
496 // also trims/drops empty options, where Perl passes `$1` verbatim.
497 let mut spec: &str = preload;
498 let mut options: &str = "";
499 if let Some(bracket) = LATEX_OPTION_REGEX.captures(spec) {
500 options = bracket.get(1).map_or("", |m| m.as_str());
501 spec = &spec[bracket.get(0).map_or(0, |m| m.end())..];
502 }
503 let mut attributes: HashMap<String, String> = HashMap::default();
504 // Perl's `($options ? (options => $options) : ())`: an empty bracket
505 // (`[]name.sty`) is falsy, so it contributes no attribute at all.
506 if !options.is_empty() {
507 attributes.insert(s!("options"), options.to_string());
508 }
509 if let Some(class) = spec.strip_suffix(".cls") {
510 attributes.insert(s!("class"), class.to_string());
511 } else {
512 attributes.insert(
513 s!("package"),
514 spec.strip_suffix(".sty").unwrap_or(spec).to_string(),
515 );
516 }
517 document.insert_pi("latexml", Some(attributes))?;
518 }
519 Ok(document)
520}
521
522/// The `ltx:document` close that `\lx@finalize@document` defers when `\end{document}` abandoned
523/// open groups or environments (sect02.rs; tex.web §1335): its whatsit may have been built inside
524/// the innermost one's body, before the constructors around it closed their elements, so the close
525/// waits until the whole document is absorbed. Every element still open then closes with
526/// `ltx:document` — their close-time hooks run: the bibliography heading absorption (repros
527/// boxes-groups/abandoned_document_close_runs_bibliography_hooks, …_invents_no_bibliography_title),
528/// the empty-para prune (jpnedumathsymbols-doc), the `ltx:p` whitespace trim (tikz-optics), the
529/// late id hook — with an Info line, not a Warning, the abandonment having been reported already.
530fn close_abandoned_document(document: &mut Document) -> Result<()> {
531 if state::lookup_bool("lx@end@document@abandoned") {
532 document.close_abandoned_element("ltx:document")?;
533 }
534 Ok(())
535}
536
537/// Load the source-adjacent `.latexml` rewrite-rules file, if present.
538/// Perl does this during initialization; we do it post-build so the rules can
539/// compile against the built document. Extracted so the streaming path can
540/// load rules BEFORE its pass 2 (fragments must see the complete rule set)
541/// without `finish_document` loading them a second time.
542fn load_source_latexml_rules() {
543 // Load .latexml file if it exists alongside the source .tex file.
544 // Perl does this automatically during initialization; we do it post-build
545 // so the rewrite rules can be compiled against the built document.
546 if let Some(Stored::String(source_sym)) = state::lookup_value("SOURCEFILE") {
547 let source_path = arena::with(source_sym, |s| s.to_string());
548 // Replace .tex extension with .latexml
549 let latexml_path = if source_path.ends_with(".tex") {
550 source_path.replace(".tex", ".latexml")
551 } else {
552 format!("{}.latexml", source_path)
553 };
554 // (a confined conversion reads it only where its roots admit it, OXIDIZED_DESIGN_DIVERGENCES #1183)
555 if !pathname::read_allowed(&latexml_path) {
556 if pathname::refused_exists(&latexml_path) {
557 pathname::refuse(&latexml_path);
558 }
559 } else if Path::new(&latexml_path).exists() {
560 let _ = load_latexml_file(&latexml_path);
561 }
562 }
563}
564
565/// The whole-document tail shared by both paths: rewrites, `\lxDeclare`
566/// application, math parsing, finalize, XMTok-id cleanup (the back half of
567/// `convert_document`, extracted verbatim). In streaming mode this runs on
568/// the live SPINE — spilled fragments received the same phases fragment-by-
569/// fragment in `streaming_pass2` beforehand.
570fn finish_document(document: &mut Document) -> Result<()> {
571 let finished = finish_document_phases(document);
572 // (the core's end: a Fatal stashed past its last step is logged and counted, and post never raises it, as Perl
573 // post-processes the document after a core `die`, LaTeXML.pm:277-283, 327-336)
574 stomach::take_stashed_fatal();
575 finished
576}
577
578fn finish_document_phases(document: &mut Document) -> Result<()> {
579 // Every reference is built (forward ones too, the eager and streaming paths alike): the diagnostics a held tag
580 // deferred (an `\autoref` name, ruling 7e) are raised for the tags a reference prints.
581 // (every held tag is tied to its owner's labels first, which a panel got after it closed, `settle_held_tags`)
582 if let Some(root) = document.get_document().get_root_element() {
583 latexml_engine::latex_constructs::settle_held_tags(document, &root);
584 // (a `\cref` list's later types name themselves before their held diagnostics are replayed)
585 latexml_engine::latex_constructs::settle_cref_lists(document, &root)?;
586 }
587 latexml_core::util::logger::settled_empty_held_tags();
588 latexml_core::util::logger::replay_shown_deferred();
589 // Lines of nothing but float-boxes give way to their floats (57g), once the document is built;
590 // spilled streaming segments get the same pass in `streaming_pass2`.
591 if let Some(root) = document.get_document().get_root_element() {
592 latexml_engine::latex_constructs::settle_float_paragraphs(document, &root)?;
593 }
594 let has_rewrites = state::has_value("DOCUMENT_REWRITE_RULES");
595 if has_rewrites {
596 let _gp_rewrite = latexml_core::telemetry::phase(latexml_core::telemetry::Phase::Rewrite);
597 note_begin("Rewriting");
598 document.mark_xmnode_visibility()?;
599 document.load_labels_for_rewrite()?;
600 // TODO: What is the right way to do rewrites in a daemon-safe manner?
601 if let Some(Stored::VecDequeStored(rules)) = state::remove_value("DOCUMENT_REWRITE_RULES")
602 && let Some(root) = document.get_document().get_root_element()
603 {
604 apply_rewrite_rules(document, rules, &root)?;
605 }
606 note_end("Rewriting");
607 }
608
609 // Apply \lxDeclare declarations: set roles/names/meanings on matching XMTok elements.
610 // Must run BEFORE math parsing so the parser sees the updated roles.
611 apply_lx_declarations(document);
612
613 if !state::get_nomathparse_flag() {
614 // Telemetry: count formulae and time the whole Marpa parse pass.
615 // Per-formula bucket histogram requires per-call instrumentation
616 // inside latexml_math_parser::parser::parse_math; deferred.
617 let xmath_count = document.findnodes("//ltx:XMath", None).len() as u32;
618 // ADD, not set: `finish_document` runs on the streaming SPINE *after*
619 // `streaming_pass2` has already counted every spilled fragment's formulae,
620 // so a plain `set` here would clobber the segment tallies and report only
621 // the spine's own — near zero on a document that spilled most of itself.
622 // Eager is unaffected: the counter starts at 0 and this runs once.
623 latexml_core::telemetry::add_formulae(xmath_count);
624 let _gp = latexml_core::telemetry::phase(latexml_core::telemetry::Phase::MathParse);
625 let mut parser = MathParser::default();
626 let parsed = parser.parse_math(document);
627 // (the spine, or the eager document, is the last parse of the conversion)
628 latexml_math_parser::clear_differential_evidence();
629 parsed?;
630 drop(_gp);
631 // Post-parse: mark failed XMath nodes as unparsed.
632 // The parser's parse_kludge already handles OPEN/CLOSE wrapping + script attachment
633 // (parse_kludgeScripts_rec), so we only need to add the unparsed CSS class here.
634 if !parser.failed_xmath_ids.is_empty() {
635 for mut math_node in document.findnodes("descendant-or-self::ltx:Math[not(@text)]", None) {
636 for xmath_child in document.findnodes("ltx:XMath", Some(&math_node)) {
637 if parser.failed_xmath_ids.contains(&xmath_child.to_hashable()) {
638 document.add_class(&mut math_node, "ltx_math_unparsed")?;
639 break;
640 }
641 }
642 }
643 }
644 // Renumber xml:ids inside parsed XMath subtrees to be sequential in document
645 // order. The Marpa parser explores multiple parse alternatives, consuming ID
646 // counter slots for pruned nodes. This pass reassigns IDs post-parse.
647 renumber_math_ids(document);
648 // Fill in \ltx@count@parses markers with actual parse tree counts.
649 // Each marker is <ltx:text _parsetrees_marker="true">0</ltx:text>.
650 // Find the preceding ltx:Math[@_parsetrees] and copy the count.
651 let markers = document
652 .find_elements(|n| n.get_attribute_no_ns("_parsetrees_marker").as_deref() == Some("true"));
653 for mut marker in markers {
654 let count = {
655 let preceding = document.findnodes("preceding::ltx:Math[@_parsetrees][1]", Some(&marker));
656 preceding
657 .into_iter()
658 .last()
659 .and_then(|m| m.get_attribute("_parsetrees"))
660 .unwrap_or_else(|| "0".to_string())
661 };
662 // Replace the text content with the actual count
663 for mut child in marker.get_child_nodes() {
664 child.unlink_node();
665 }
666 let _ = marker.append_text(&count);
667 // Remove the marker attribute
668 let _ = marker.remove_attribute("_parsetrees_marker");
669 }
670 }
671
672 // #683 (xworld21): persist NOMINAL_FONT_SIZE as a
673 // `<?latexml nominal-font-size="X"?>` processing instruction when it differs
674 // from the 10pt default, so post-processing can size font-relative (em)
675 // external SVGs correctly (an `em` is `NOMINAL_FONT_SIZE`pt, not always 10pt).
676 // Perl does not emit this — NOMINAL_FONT_SIZE is digestion-only (`DEFSIZE`),
677 // so this is beyond-Perl. Only a0poster (25), the NNpt class options, and
678 // BookML move it off 10, so a normal document's output stays byte-identical
679 // (no new PI). `insert_pi` places it before the root, alongside the other
680 // `<?latexml …?>` metadata PIs (class/package/graphicspath).
681 if let Some(nominal) = state::lookup_float("NOMINAL_FONT_SIZE")
682 && (nominal.0 - 10.0).abs() > 1e-6
683 {
684 let mut attrs = HashMap::default();
685 attrs.insert(String::from("nominal-font-size"), nominal.0.to_string());
686 document.insert_pi("latexml", Some(attrs))?;
687 }
688
689 note_begin("Finalizing");
690 document.finalize()?;
691 note_end("Finalizing");
692 // Perl core produces role="UNKNOWN" for single-letter math tokens.
693 // Per-document .latexml files set role="ID" via DefMathRewrite BEFORE parsing.
694 // We do NOT apply a blanket conversion — roles are set by rewrite rules only.
695 // Cleanup unreferenced xml:ids on XMTok elements generated by the math parser.
696 // Must run after finalize (which includes prune_xmduals that may transfer ids).
697 document.cleanup_unreferenced_xmtok_ids();
698 Ok(())
699}
700
701/// Compile and invoke a set of `DefRewrite`/`DefMathRewrite` rules against
702/// `root` (extracted verbatim from the eager Rewriting phase). The streaming
703/// pass 2 calls this once per FRAGMENT with a snapshot of the rule set — the
704/// S2 census showed the production corpus is subtree-local, so per-fragment
705/// application is equivalent; `label:`-scoped rules resolve through the
706/// fragment's `rewrite_labels`, then the document-wide
707/// shared label map (`Document::rewrite_labels_shared`).
708fn apply_rewrite_rules(
709 document: &mut Document,
710 rules: std::collections::VecDeque<Stored>,
711 root: &libxml::tree::Node,
712) -> Result<()> {
713 // Step 1: copy the rules locally through Rc, to be able to invoke them with mutable
714 // state. (TODO: obviously, this could be avoided if they never needed mutable
715 // state. When do they?)
716 let mut rewrites = Vec::new();
717 for rule in rules {
718 if let Stored::Rewrite(mut rewrite_rule) = rule {
719 rewrite_rule.compile_clauses(document);
720 rewrites.push(rewrite_rule);
721 }
722 }
723 // 31 rules compiled for declare test; XPath matching issue prevents application
724 // Step 2: invoke the rewrite rules
725 // R35.D instrumentation: print per-rule timing if
726 // LATEXML_REWRITE_TIMING=1. Logs BEFORE the rule runs so we can
727 // identify the rule that hangs (the timeout watchdog kills
728 // mid-rule otherwise).
729 let trace_all = std::env::var_os("LATEXML_REWRITE_TIMING").is_some();
730 let n_rules = rewrites.len();
731 // Format rule diagnostics lazily (Audit F4): only allocate when tracing is
732 // enabled or a rule actually exceeds the slow-rule threshold.
733 let format_hint = |rewrite_rule: &Rewrite| -> String {
734 let opts = &rewrite_rule.options;
735 let mut xpath_hint = format!(
736 "select={:?} xpath={:?} regexp={:?} scope={:?} label={:?} clauses={}",
737 opts
738 .select
739 .as_deref()
740 .map(|s| s.chars().take(60).collect::<String>()),
741 opts
742 .xpath
743 .as_deref()
744 .map(|s| s.chars().take(60).collect::<String>()),
745 opts
746 .regexp
747 .as_deref()
748 .map(|s| s.chars().take(60).collect::<String>()),
749 opts.scope.as_ref().map(|_| "<scope>"),
750 opts.label.as_deref(),
751 rewrite_rule.clauses.len(),
752 );
753 for (ci, c) in rewrite_rule.clauses.iter().enumerate() {
754 use std::fmt::Write;
755 let _ = write!(
756 xpath_hint,
757 "\n [{ci}] op={:?} pat={:?}",
758 c.op,
759 match &c.pattern {
760 latexml_core::rewrite::RewritePattern::String(s) =>
761 format!("Str({})", s.chars().take(120).collect::<String>()),
762 latexml_core::rewrite::RewritePattern::Tokens(_) => "Tokens(..)".into(),
763 latexml_core::rewrite::RewritePattern::Closure(_) => "Closure(..)".into(),
764 latexml_core::rewrite::RewritePattern::NodeList(n) => format!("NodeList({})", n.len()),
765 _ => "??".into(),
766 }
767 );
768 }
769 xpath_hint
770 };
771 for (idx, mut rewrite_rule) in rewrites.into_iter().enumerate() {
772 if trace_all {
773 eprintln!(
774 "[rewrite-timing] rule #{}/{} START :: {}",
775 idx,
776 n_rules,
777 format_hint(&rewrite_rule)
778 );
779 // Flush stderr so it appears even if the rule hangs
780 use std::io::Write;
781 let _ = std::io::stderr().flush();
782 }
783 let started = std::time::Instant::now();
784 let invoked = rewrite_rule.invoke(document, root);
785 // A rule's Fatal (its own, or a register getter's stashed one) ends the rewrites and keeps the document, as Perl
786 // dies out of this loop (Core.pm:282-287) and post-processes the rescued one (LaTeXML.pm:277-283);
787 // rhai-bindings/rewrite_fatal_keeps_the_document.tex
788 if let Err(fatal) = invoked.and_then(|()| stomach::take_stashed_fatal().map_or(Ok(()), Err)) {
789 if fatal.is_logged_fatal() && !matches!(fatal.target, ErrorTarget::Timeout) {
790 return Ok(());
791 }
792 return Err(fatal);
793 }
794 let elapsed = started.elapsed();
795 if trace_all {
796 eprintln!(
797 "[rewrite-timing] rule #{}/{} END {:.2?}",
798 idx, n_rules, elapsed
799 );
800 } else if elapsed > std::time::Duration::from_secs(5) {
801 latexml_core::Info!(
802 "rewrite",
803 "slow",
804 s!(
805 "rule #{}/{} took {:.2?} :: {}",
806 idx,
807 n_rules,
808 elapsed,
809 format_hint(&rewrite_rule)
810 )
811 );
812 }
813 }
814 Ok(())
815}
816
817/// Absolute cap on the `node_boxes` growth that triggers a stale-entry sweep during
818/// streaming pass 1 (default 50,000 entries). The sweep runs at the smaller of this
819/// cap and an eighth of the size after the last sweep (at least 256), so
820/// `LXML_NODE_BOXES_SWEEP=<n>` can only lower the gate (memory probes).
821fn node_boxes_sweep_threshold() -> usize {
822 static THRESHOLD: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
823 *THRESHOLD.get_or_init(|| {
824 std::env::var("LXML_NODE_BOXES_SWEEP")
825 .ok()
826 .and_then(|v| v.parse().ok())
827 .unwrap_or(50_000)
828 })
829}
830
831/// Streaming pass 2: give every spilled fragment the SAME whole-document tail
832/// the spine gets — rewrites, `\lxDeclare`, math parsing, per-fragment
833/// finalize — then store its final serialized text for the assembly splice.
834/// Runs after digestion finished (so the rewrite-rule set is complete) and
835/// before `finish_document` consumes the rules for the spine.
836/// Root-level id counters (`_ID_counter_*` attrs) must run document-wide:
837/// eager mints `id1..idN` across the whole document in one walk, so pass 2
838/// seeds each fragment's parse wrapper with the counters carried out of the
839/// previous one (`counters` in/out), and the caller seeds the spine's tail
840/// from the final state (sweep witness tests/alignment/plainmath.tex, where
841/// every fragment restarted at `id1`). `shared_labels` is the document-wide
842/// label map scope labels resolve through; `root_id` joins every fragment's
843/// ancestors, the root being an ancestor of every segment.
844fn streaming_pass2(
845 store: &mut latexml_core::sxml::SegmentStore,
846 node_fonts: &rustc_hash::FxHashMap<u64, latexml_core::common::font::Font>,
847 counters: &mut Vec<(String, String)>,
848 anchors: &mut rustc_hash::FxHashMap<String, Vec<(String, String)>>,
849 index: &latexml_core::sxml::FragmentIndex,
850 shared_labels: Option<Rc<rustc_hash::FxHashMap<String, String>>>,
851 root_id: Option<String>,
852) -> Result<()> {
853 use latexml_core::common::error::{ErrorCategory, ErrorData};
854 // A non-consuming snapshot of the rules: `finish_document` will consume the
855 // live entry for the spine afterwards.
856 let rules_opt = match state::lookup_value("DOCUMENT_REWRITE_RULES") {
857 Some(Stored::VecDequeStored(rules)) => Some(rules),
858 _ => None,
859 };
860 let nomath = state::get_nomathparse_flag();
861 // The segment each spilled anchor is in: its counters there continue what earlier segments minted under it.
862 let mut anchors_in: rustc_hash::FxHashMap<u32, Vec<String>> = rustc_hash::FxHashMap::default();
863 for id in anchors.keys() {
864 if let Some(seg) = index.id_segment(id) {
865 anchors_in.entry(seg.0).or_default().push(id.clone());
866 }
867 }
868 let segments: Vec<_> = store.ids().collect();
869 // The math grammar, built once and handed from each segment's parser to the next: rebuilding it
870 // per segment cost ≈60 M instructions each, 253 segments on 2308.04512, 442 on circuitikzmanual.
871 let mut math_grammar: Option<latexml_math_parser::MathGrammar> = None;
872 // Rate-limited exactly like the pass-1 telemetry next door (see the
873 // `is_power_of_two() || is_multiple_of(65536)` gate in `convert_streaming`):
874 // the 131 MB witness spills 459,579 segments, and three ungated `info!` per
875 // segment wrote 1.38 M lines — 44% of a 161 MB log — into the in-RAM
876 // LOG_BUFFER that pass 1 exists to keep bounded. Dense at the start so short
877 // runs and tests still see every line, logarithmic after, 64k floor.
878 //
879 // The ARGUMENTS must stay inside the gate, not just the macro: each probe
880 // reads /proc/self/status, and the `parsed` line re-reads the whole segment
881 // off disk purely to print its size.
882 fn telemetry_due(n: usize) -> bool { n.is_power_of_two() || n.is_multiple_of(65536) }
883 for (seg_idx, seg) in segments.into_iter().enumerate() {
884 let due = telemetry_due(seg_idx + 1);
885 if store.is_retired(seg) {
886 // Inlined into an enclosing segment; its content is processed there.
887 continue;
888 }
889 let meta = store.meta(seg)?.clone();
890 // Segments are bounded (one spill run), so plain parsing is as bounded as
891 // streaming — and unlike `xmlTextReaderExpand`, it does not mint the
892 // libxml2 "default" namespace prefix for default-namespace content
893 // (`append_clone`'s doc-comment records the same trap). The streaming
894 // TextReader stays reserved for genuinely unbounded files (the post
895 // half's pass A over the whole core XML).
896 let wrapped = store.wrapped_segment(seg)?;
897 let has_empty_text = wrapped.contains("_lx_empty_text");
898 let frag_xml = libxml::parser::Parser::default()
899 .parse_string(&wrapped)
900 .map_err(|e| {
901 Error::from(ErrorData {
902 target: ErrorTarget::Internal,
903 category: ErrorCategory::Libxml,
904 message: s!("cannot re-parse staged segment {seg}: {e}"),
905 })
906 })?;
907 drop(wrapped);
908 let mut out = String::new();
909 {
910 let mut frag = Document::from_xml_document(frag_xml, node_fonts.clone())?;
911 if due {
912 emit_info(
913 "streaming",
914 "progress",
915 &format!(
916 "streaming pass2: segment {seg} ({} KB) parsed; RSS ~{} MB",
917 store.read_segment(seg).map(|t| t.len() / 1024).unwrap_or(0),
918 latexml_core::watchdog::process_rss_kb().unwrap_or(0) / 1024,
919 ),
920 );
921 }
922 // A fragment re-emits the (nested) placeholders it contains; only the
923 // final assembly resolves them.
924 frag.literal_placeholders = true;
925 // An ancestor-scoped rewrite covers the whole fragment (field docs).
926 frag.fragment_ancestor_ids = meta.ancestors.iter().cloned().collect();
927 // The root is every segment's ancestor, though its id — minted by the
928 // late `GenerateID` hook, after the spills — is in no segment's record:
929 // a bare `\label` before the first unit lands on it (1703.09326), and a
930 // declaration scoped to that label covers the whole document.
931 frag.fragment_ancestor_ids.extend(root_id.iter().cloned());
932 // Judge the parse wrapper as the segment's REAL parent in schema
933 // decisions (empty-`ltx:text` collapse etc.) — see the field docs.
934 frag.fragment_parent_qname = meta.parent.as_deref().map(arena::pin);
935 // Seed the wrapper root with the carried id counters of the element its top nodes are minted under (the root's
936 // when no element below it has an id), so fragment id minting continues the document-wide sequence.
937 frag.fragment_anchor_id = meta.anchor.clone();
938 let seed = match &meta.anchor {
939 Some(id) => anchors.get(id).map(Vec::as_slice).unwrap_or_default(),
940 None => counters.as_slice(),
941 };
942 if let Some(mut root) = frag.get_document().get_root_element() {
943 for (key, value) in seed {
944 let _ = root.set_attribute(key, value);
945 }
946 }
947 for id in anchors_in.get(&seg.0).into_iter().flatten() {
948 if let Some(carried) = anchors.get(id) {
949 frag.set_id_counters(id, carried);
950 }
951 }
952 // No strip needed: pass 1 serializes segments FLAT (`spill_flat`), so
953 // the indentation text nodes this used to delete are never created.
954 // `strip_indentation_whitespace` unlinked them, and unlink does not
955 // free — they were orphaned for the fragment's lifetime.
956 // Restore empty text children the parse could not represent (spill-time
957 // `_lx_empty_text` markers — see `spill_run`): `<p></p>` must not
958 // collapse to `<p/>` across the round-trip.
959 if has_empty_text {
960 for mut marked in frag.find_elements(|n| n.has_attribute_no_ns("_lx_empty_text")) {
961 let _ = marked.remove_attribute("_lx_empty_text");
962 if marked.get_child_nodes().is_empty() {
963 // `append_text("")` is a no-op (the fork guards on len > 0), so
964 // create a real text node and then empty it in place.
965 let _ = marked.append_text("x");
966 if let Some(mut text) = marked.get_first_child() {
967 let _ = text.set_content("");
968 }
969 }
970 }
971 }
972 // The segment's share of `finish_document`'s float-box pass (57g) and of its held-tag settling.
973 if let Some(root) = frag.get_document().get_root_element() {
974 latexml_engine::latex_constructs::settle_held_tags(&mut frag, &root);
975 latexml_engine::latex_constructs::settle_cref_lists(&mut frag, &root)?;
976 latexml_engine::latex_constructs::settle_float_paragraphs(&mut frag, &root)?;
977 }
978 if let Some(rules) = &rules_opt {
979 // `Phase::Rewrite` is taken in `finish_document`, which only ever runs
980 // on the SPINE — pass 2 calls `apply_rewrite_rules` directly, so every
981 // fragment's rewrite work was unattributed.
982 let _gp_rewrite = latexml_core::telemetry::phase(latexml_core::telemetry::Phase::Rewrite);
983 frag.mark_xmnode_visibility()?;
984 frag.load_labels_for_rewrite()?;
985 // Share the prebuilt index rather than copying it in; a frag-local
986 // label still wins, exactly as the `or_insert_with` copy ensured.
987 frag.rewrite_labels_shared = shared_labels.clone();
988 if let Some(root) = frag.get_document().get_root_element() {
989 apply_rewrite_rules(&mut frag, rules.clone(), &root)?;
990 }
991 }
992 apply_lx_declarations(&mut frag);
993 if !nomath {
994 // Only probed when the line will actually be emitted — this read used
995 // to sit outside the macro, so its /proc cost was paid on every
996 // segment even at `--quiet`.
997 let rss0 = if due {
998 latexml_core::watchdog::process_rss_kb().unwrap_or(0) / 1024
999 } else {
1000 0
1001 };
1002 // Same telemetry the EAGER path records (see the `//ltx:XMath` count
1003 // and `Phase::MathParse` guard above). Streaming recorded neither,
1004 // while `record_math_parse` inside the parser kept firing — so a
1005 // streamed job's telemetry.json showed thousands of
1006 // `math_parse_attempts` against `formulae: 0` and a near-zero
1007 // `phase_math_parse_us`, systematically, on the biggest papers.
1008 // Accumulated across segments, since pass 2 parses each separately.
1009 latexml_core::telemetry::add_formulae(frag.findnodes("//ltx:XMath", None).len() as u32);
1010 let _gp = latexml_core::telemetry::phase(latexml_core::telemetry::Phase::MathParse);
1011 if math_grammar.is_none() {
1012 math_grammar = latexml_math_parser::MathGrammar::new().ok();
1013 }
1014 let mut parser = match &math_grammar {
1015 Some(grammar) => MathParser::with_grammar(grammar),
1016 None => MathParser::default(),
1017 };
1018 let parsed = parser.parse_math(&mut frag);
1019 math_grammar = parser.grammar();
1020 parsed?;
1021 drop(_gp);
1022 if due {
1023 emit_info(
1024 "streaming",
1025 "progress",
1026 &format!(
1027 "streaming pass2: segment {seg} math done; RSS {} -> {} MB; arena {} syms",
1028 rss0,
1029 latexml_core::watchdog::process_rss_kb().unwrap_or(0) / 1024,
1030 arena::len(),
1031 ),
1032 );
1033 }
1034 // Mirror the eager tail: mark failed formulae, renumber math ids
1035 // (per-Math, so fragment-local by construction).
1036 if !parser.failed_xmath_ids.is_empty() {
1037 for mut math_node in frag.findnodes("descendant-or-self::ltx:Math[not(@text)]", None) {
1038 for xmath_child in frag.findnodes("ltx:XMath", Some(&math_node)) {
1039 if parser.failed_xmath_ids.contains(&xmath_child.to_hashable()) {
1040 frag.add_class(&mut math_node, "ltx_math_unparsed")?;
1041 break;
1042 }
1043 }
1044 }
1045 }
1046 renumber_math_ids(&mut frag);
1047 }
1048 // The per-fragment share of finalize: XMRef/XMDual pruning and the
1049 // font/bookkeeping walk. The root-only passes (RDFa prefixes, namespace
1050 // declarations, schema PI) belong to the SPINE root and must NOT touch
1051 // a fragment root — they would change its serialization.
1052 frag.prune_dangling_split_xmrefs()?;
1053 frag.prune_xmduals()?;
1054 if let Some(mut root) = frag.get_document().get_root_element() {
1055 let context = meta
1056 .font
1057 .as_deref()
1058 .and_then(|key| frag.decode_font(key))
1059 .cloned()
1060 .unwrap_or_else(latexml_core::common::font::Font::text_default);
1061 frag.finalize_subtree_in(&mut root, context)?;
1062 }
1063 frag.cleanup_unreferenced_xmtok_ids();
1064 // The parsed root is the `_lxfragment` wrapper; the spilled subtrees are
1065 // its children. Serialize each at the recorded position parameters.
1066 if let Some(root) = frag.get_document().get_root_element() {
1067 let _gp_ser = latexml_core::telemetry::phase(latexml_core::telemetry::Phase::Serialize);
1068 for child in root.get_child_nodes() {
1069 out.push_str(&frag.serialize_aux(&child, meta.depth, meta.noindent, false));
1070 }
1071 // Carry the wrapper's id counters to the next fragment under the same element
1072 // (finalize deliberately leaves the wrapper's bookkeeping attrs in
1073 // place — see finalize_rec's PostWork).
1074 let carried = latexml_core::document::id_counters(&root);
1075 match &meta.anchor {
1076 Some(id) => {
1077 anchors.insert(id.clone(), carried);
1078 },
1079 None => *counters = carried,
1080 }
1081 }
1082 }
1083 store.finalize_segment(seg, &out)?;
1084 if due {
1085 emit_info(
1086 "streaming",
1087 "progress",
1088 &format!(
1089 "streaming pass2: segment {seg} finalized+dropped; RSS ~{} MB",
1090 latexml_core::watchdog::process_rss_kb().unwrap_or(0) / 1024
1091 ),
1092 );
1093 }
1094 }
1095 Ok(())
1096}
1097
1098impl DigestionAPI for Core {
1099 fn initialize_singletons(&mut self, preloads: Vec<String>) -> Result<()> {
1100 // reset the error REPORT singleton
1101 error::initialize_report();
1102 // A rescue (`hard_yank_processing`) belongs to the conversion that failed,
1103 // never to the next one a long-lived worker runs — a `.bib` session's
1104 // `digest_file` propagates a resource fatal without a salvage pass.
1105 RESCUED_BOXES.with(|r| r.borrow_mut().clear());
1106 // Per-conversion notice and differential-evidence state in the math parser
1107 // (the persistent cortex_worker converts many documents per process).
1108 latexml_math_parser::reset_conversion_notices();
1109 latexml_math_parser::clear_differential_evidence();
1110 // Same reason: the only other telemetry reset is `take()`, which the
1111 // binaries skip entirely when no telemetry sink is configured.
1112 latexml_core::telemetry::reset();
1113 // reset localized variables (if_frames, current_token, align state, etc.)
1114 latexml_core::common::local_assignments::initialize_localized();
1115 // now handle conversion state
1116 gullet::initialize_gullet();
1117 stomach::initialize_stomach();
1118 // should we reset the model also?
1119 model::initialize_model();
1120 // let paths = state::search_paths;
1121 let dump_path = LATEXML_DUMP.clone();
1122 // Publish our version (Perl's `$LaTeXML::VERSION`) so bindings can read it —
1123 // e.g. the Rhai `LaTeXMLVersion()` binding, and the XSLT `LATEXML_VERSION`
1124 // parameter. Global so it survives the whole conversion.
1125 state::assign_value("LATEXML_VERSION", LATEXML_VERSION, Some(Scope::Global));
1126 state::assign_value("InitialPreloads", true, Some(Scope::Global));
1127 for preload in preloads {
1128 let (name, ext, options) = parse_preload_spec(&preload);
1129 let handleoptions = ext == "sty" || ext == "cls";
1130 // Pass package options via state (Perl: \PassOptionsToPackage equivalent).
1131 // Match `\PassOptionsToPackage` at latex_constructs.rs L3838-3842: push the
1132 // `Vec<String>` through `push_value` so it lands as a `Stored::Strings`
1133 // batch inside the `opt@<name>.<ext>` `VecDequeStored`. The batch shape is
1134 // what `collect_syms` (binding/content.rs L1157) flattens when
1135 // `\ProcessOptions*` enumerates declared options; storing a single
1136 // comma-joined `Stored::String("opt1,opt2")` instead silently bypasses
1137 // every `DeclareOption!` site, so e.g. dvipsnames/svgnames/x11names
1138 // palettes never load — visible as `Error:unexpected:Apricot Can't find
1139 // color named 'Apricot'; assuming Black` on a `[dvipsnames]color.sty`
1140 // preload.
1141 if !options.is_empty() {
1142 let opt_key = format!("opt@{name}.{ext}");
1143 state::push_value(&opt_key, options)?;
1144 }
1145 input_definitions(&name, InputDefinitionOptions {
1146 extension: Some(ext.into()),
1147 handleoptions,
1148 ..InputDefinitionOptions::default()
1149 })?;
1150 }
1151 state::assign_value("InitialPreloads", false, Some(Scope::Global));
1152
1153 // Load kernel dump AFTER pools (provides TeX/LaTeX macros the pools skipped).
1154 if let Some(ref dump_path) = dump_path {
1155 let path = Path::new(dump_path);
1156 if path.exists() {
1157 // Rust-native tab-separated format (from --init mode). The
1158 // Perl-format `dump_loader` was deleted 2026-04-18 (dead code —
1159 // we never consumed Perl-generated dumps).
1160 let result = latexml_core::dump_reader::load_native_dump(path);
1161 match result {
1162 Ok(count) => {
1163 latexml_core::Info!(
1164 "dump",
1165 "loaded",
1166 s!(
1167 "Loaded {} kernel definitions from {}",
1168 count,
1169 path.display()
1170 )
1171 );
1172 },
1173 Err(e) => {
1174 latexml_core::Warn!("dump", "load_failed", s!("failed to load dump: {}", e));
1175 },
1176 }
1177 }
1178 }
1179 Ok(())
1180 }
1181
1182 // TODO: We should choose between this function or digest_file, rather than implement twice,
1183 // right?
1184 fn digest(
1185 &mut self,
1186 request: String,
1187 preamble: Option<String>,
1188 postamble: Option<String>,
1189 mode: Option<DigestionMode>,
1190 _no_init: bool,
1191 ) -> Result<Digested> {
1192 let digestion_note = self.digest_setup(request, preamble, postamble, mode)?;
1193 let list = self.digest_internal()?;
1194 note_end(&digestion_note);
1195 Ok(list)
1196 }
1197
1198 /// The input-side half of [`DigestionAPI::digest`]: canonicalize the
1199 /// request, seed SOURCEFILE/SOURCEDIRECTORY/SEARCHPATHS/`\jobname`, queue
1200 /// postamble/source/preamble on the gullet. Returns the progress-note label
1201 /// the caller must `note_end` when digestion completes. Shared by the eager
1202 /// path and `convert_streaming` (which drives digestion itself,
1203 /// fragment-by-fragment).
1204 fn digest_setup(
1205 &mut self,
1206 request: String,
1207 preamble: Option<String>,
1208 postamble: Option<String>,
1209 mode: Option<DigestionMode>,
1210 ) -> Result<String> {
1211 DIGEST_SETUP_COUNT.with(|c| c.set(c.get() + 1));
1212 stomach::mark_conversion_rss_baseline();
1213 let mut _ext = match &mode {
1214 Some(m) => Some(m.extension()),
1215 None => Some(DigestionMode::TeX.extension()),
1216 };
1217 let mut dir_opt = None;
1218
1219 // Canonicalize relative paths so `Path::parent()` gives a real directory.
1220 // `Path::new("foo.tex").parent()` returns `Some("")` (empty string) which
1221 // poisons SEARCHPATHS / SOURCEDIRECTORY: an empty-string search-path
1222 // entry resolves files via cwd-name with no normalization, changing the
1223 // order in which resource files (e.g. `ts1enc.def` vs `t1enc.def`) are
1224 // discovered. Concrete symptom: TS1 fontmap leaks into control-sequence
1225 // construction → `cn` characters become `⚮♪` → `\c@cn` undefined →
1226 // 381-error cascade (paper 0709.2868). Canonicalizing matches Perl's
1227 // `File::Spec->splitpath` behavior which always yields a real directory.
1228 let canonical_request = if pathname::is_literaldata(&request) || pathname::is_url(&request) {
1229 request.clone()
1230 } else {
1231 pathname::canonicalize(&request)
1232 .ok()
1233 .and_then(|p| p.to_str().map(String::from))
1234 .unwrap_or_else(|| request.clone())
1235 };
1236 let name = if pathname::is_literaldata(&request) {
1237 s!("Anonymous String")
1238 } else if pathname::is_url(&request) {
1239 request.clone()
1240 } else {
1241 let path = Path::new(&canonical_request);
1242 dir_opt = path.parent();
1243 match path.file_stem() {
1244 None => String::from("missing_name"),
1245 Some(pf) => pf.to_str().unwrap().to_string(),
1246 }
1247 };
1248 // else {
1249 // $self->withState(sub {
1250 // Fatal('missing_file', $request, undef, "Can't find $mode file $request"); }); } }
1251 // };
1252 // Book-scale sources legitimately expand past the arXiv-sized 1G
1253 // runaway-token backstop; scale it to the input (never lowers, env
1254 // override wins — see gullet::scale_token_limit_to_source).
1255 // A file source is counted when its Mouth opens it (`Mouth::open_file`);
1256 // literal data has no file, so count it here.
1257 if pathname::is_literaldata(&request) {
1258 gullet::scale_token_limit_to_source(request.len());
1259 }
1260 let digestion_note = s!("Digesting {}", name);
1261 note_begin(&digestion_note);
1262 // $self->initializestate::$mode . ".pool", @{ $$self{preload} || [] }) unless
1263 // $options{noinitialize};
1264 if !pathname::is_literaldata(&request) {
1265 state::assign_value("SOURCEFILE", arena::pin(&request), None);
1266 }
1267 if let Some(dir) = dir_opt {
1268 let dir_str = dir.to_str().unwrap_or(".");
1269 // Perl Core.pm L195-200 unshifts the SOURCE file's directory onto
1270 // SEARCHPATHS so subsequent `\input`-style lookups resolve relative
1271 // to the main file. When `canonicalize` succeeded `dir_str` is the
1272 // absolute parent; if it failed (e.g. file not on disk yet at the
1273 // time we resolved — unusual for normal latexml CLI invocations
1274 // but possible for `literal:` etc.) `dir_str` may be empty and an
1275 // empty entry on SEARCHPATHS is useless. Fall back to CWD in that
1276 // case so paper-local files (`\input{Chapter/Abstract}` etc.) are
1277 // discoverable. Witness: arXiv:2604.09744, 2603.04457 (papers
1278 // bundling subdirectory `\subimport` chains).
1279 let resolved_dir = if dir_str.is_empty() {
1280 std::env::current_dir()
1281 .ok()
1282 .and_then(|cwd| cwd.to_str().map(String::from))
1283 .unwrap_or_else(|| ".".to_string())
1284 } else {
1285 dir_str.to_string()
1286 };
1287 state::assign_value("SOURCEDIRECTORY", arena::pin(&resolved_dir), None);
1288 establish_pdf_output_mode(&resolved_dir);
1289 // Perl Core.pm L195-200: `$state->unshiftValue(SEARCHPATHS => $dir)`.
1290 // `unshift` puts the source dir at the FRONT so it's the new "lead"
1291 // — the same lead `\lx@append@path` reads as the basis for
1292 // appended subdir paths. Pushing to BACK (`add_search_path`) left
1293 // the lead as whatever the CLI's `--path` provided (typically
1294 // `ar5iv-bindings/bindings`); `\subimport{Chapter/}{Abstract}`
1295 // then appended Chapter/ to ar5iv-bindings/bindings instead of to
1296 // the paper's directory, and `\input{Abstract}` couldn't resolve.
1297 // Witness: arXiv:2604.09744, 2603.04457.
1298 state::search_paths_push_front(resolved_dir);
1299 }
1300 // if defined $dir && !grep { $_ eq $dir } @{ $state->lookupValue('SEARCHPATHS') };
1301 // $state->unshiftValue(GRAPHICSPATHS => $dir)
1302
1303 // if defined $dir && !grep { $_ eq $dir } @{ $state->lookupValue('GRAPHICSPATHS') };
1304
1305 install_jobname(&name);
1306
1307 // Reverse order, since last opened is first read!
1308 // (Perl: Core.pm L154-157 in `digestFile`.)
1309 if let Some(postamble) = postamble {
1310 self.load_postamble(postamble);
1311 }
1312 input_content(&request, InputOptions::default())?;
1313 if let Some(preamble) = preamble {
1314 self.load_preamble(preamble);
1315 }
1316 // The format a first line `%&amstex` requests (`converter::requests_amstex_format`, OD #1194) is read before the
1317 // document, in its scope, as amstex.ini's `\input amstex`: a `\TagsOnRight` before `\documentstyle` holds.
1318 if state::lookup_bool("lx@format@amstex") {
1319 input_content("literal:\\input amstex ", InputOptions::default())?;
1320 }
1321
1322 // Now for the Hacky part for BibTeX!!!
1323 // Perl `Core.pm` L160-162: drain the .bib mouth via the Pre::BibTeX
1324 // parser, register each entry in the bibtex.rs thread-local
1325 // registry, and push back a `literal:` wrapper that produces a
1326 // `\begin{bibtex@bibliography}...\end{bibtex@bibliography}` block
1327 // for the digester to process.
1328 if matches!(mode, Some(DigestionMode::BibTeX)) {
1329 use latexml_engine::pre_bibtex::PreBibTeX;
1330 let mut bib = PreBibTeX::new_from_gullet(&name);
1331 match bib.to_tex() {
1332 Ok(tex) => {
1333 input_content(&s!("literal:{tex}"), InputOptions::default())?;
1334 },
1335 Err(parse_err) => {
1336 Error!(
1337 "bibtex",
1338 "parse_failed",
1339 s!("Failed to parse BibTeX file {}: {:?}", name, parse_err)
1340 );
1341 },
1342 }
1343 }
1344
1345 Ok(digestion_note)
1346 }
1347
1348 fn convert_file(&mut self, filepath: String) -> Result<Document> {
1349 match self.digest_file(filepath, DigestionOptions::default()) {
1350 Err(e) => Err(e),
1351 Ok(digested) => self.convert_document(digested),
1352 }
1353 }
1354
1355 /// The streaming front half: spill store + disk gate, deferred root,
1356 /// literal placeholders, flat spill, the fragment index and the yield
1357 /// knobs. Shared by `convert_streaming` and the adaptive transition.
1358 fn stream_setup(
1359 &mut self,
1360 document: &mut Document,
1361 budget: usize,
1362 ) -> Result<latexml_core::sxml::FragmentIndex> {
1363 use latexml_core::sxml::{FragmentIndex, SegmentStore};
1364 latexml_core::document::reset_spilled_segment_count();
1365 // The spill area lives beside the source when that directory is WRITABLE
1366 // (same volume as the output in the by-far-common layout, so the
1367 // disk-headroom check measures the filesystem the spill actually
1368 // consumes), else the system temp dir. The writability test is not
1369 // hypothetical: auto-activation fires on exactly the large documents that
1370 // get processed from read-only trees — an arXiv bulk mount, a CI
1371 // checkout — and creating the directory unconditionally failed the whole
1372 // conversion there. Literal input has no source directory at all.
1373 let spill_anchor = match state::lookup_value("SOURCEDIRECTORY") {
1374 Some(Stored::String(dir)) => {
1375 let dir = arena::with(dir, |s: &str| std::path::PathBuf::from(s));
1376 if dir_is_writable(&dir) {
1377 dir
1378 } else {
1379 emit_info(
1380 "streaming",
1381 "progress",
1382 &format!(
1383 "streaming: {} is not writable; spilling to {} instead",
1384 dir.display(),
1385 std::env::temp_dir().display()
1386 ),
1387 );
1388 std::env::temp_dir()
1389 }
1390 },
1391 _ => std::env::temp_dir(),
1392 };
1393 let store = SegmentStore::create(&spill_anchor)?;
1394 // Disk-headroom gate (user requirement 2026-07-29): the spill needs
1395 // roughly the core-XML size on disk — measured ~12x the source bytes on
1396 // math-heavy content — and a silent mid-conversion ENOSPC would be the
1397 // OOM-kill failure mode all over again. Verify up front and raise a
1398 // Fatal that NAMES the shortfall and the requirement, so the user can
1399 // free space (or point --dest at a roomier volume) with numbers in hand.
1400 {
1401 use latexml_core::common::error::{ErrorCategory, ErrorData, ErrorTarget};
1402 const SPILL_BYTES_PER_SOURCE_BYTE: u64 = 16; // ~12x measured + slack
1403 let src_bytes = match state::lookup_value("SOURCEFILE") {
1404 Some(Stored::String(f)) => {
1405 arena::with(f, |f| std::fs::metadata(f).map(|m| m.len()).unwrap_or(0))
1406 },
1407 _ => 0,
1408 };
1409 let need = src_bytes.saturating_mul(SPILL_BYTES_PER_SOURCE_BYTE);
1410 if let Some(avail) = latexml_core::watchdog::available_disk_bytes(store.dir())
1411 && avail < need
1412 {
1413 stomach::set_fragment_yield_budget(None);
1414 return Err(Error::from(ErrorData {
1415 target: ErrorTarget::Timeout,
1416 category: ErrorCategory::MemoryBudget,
1417 message: s!(
1418 "streaming spill needs ~{} MB free under {} but only {} MB is available — free disk space there, or convert with a destination on a roomier volume",
1419 need / (1024 * 1024),
1420 store.dir().display(),
1421 avail / (1024 * 1024)
1422 ),
1423 }));
1424 }
1425 }
1426 document.set_spill_store(store);
1427 document.set_defer_root_after_open(true);
1428 // Pass 1 serializes placeholders literally (nested spills stay nested;
1429 // the final assembly resolves them recursively — see the field docs).
1430 document.literal_placeholders = true;
1431 // The math parser's `d`-token evidence is the whole document's, read before its rewrites (as the eager path
1432 // reads it): each subtree's as it spills, the spine's before pass 2.
1433 // So are the output's words the title-page check looks for (latexml_engine `title_page_check`): each subtree's
1434 // as it spills, the spine's when the document closes.
1435 document.spill_observer = Some(if state::get_nomathparse_flag() {
1436 observe_spilled_words
1437 } else {
1438 observe_spilled_evidence_and_words
1439 });
1440 // Spill segments are an intermediate that pass 2 re-serializes; the
1441 // indentation pass 1 used to emit was generated, written, read back,
1442 // parsed into ~40M text nodes and then deleted again. See `spill_flat`.
1443 document.spill_flat = true;
1444 let index = FragmentIndex::default();
1445 stomach::set_fragment_yield_budget(Some(budget));
1446 // Soft-RSS yield: fire regardless of box count once RSS crosses the
1447 // watermark — the box budget assumes a per-box footprint, and math-dense
1448 // content blows past it (witness: fuse at 18.8 GB with the box budget
1449 // untouched). `spill_watermark_bytes` owns the policy, including the
1450 // `--max-memory=0` case where there is no fuse to divide.
1451 if let Some(mark_kb) = stomach::spill_mark_kb() {
1452 stomach::set_fragment_yield_rss_soft_kb(Some(mark_kb));
1453 }
1454
1455 Ok(index)
1456 }
1457
1458 /// Streaming pass 1: interleaved digest → absorb → spill, at legal seams only.
1459 /// `seed` = bodies already digested by the eager loop (the adaptive
1460 /// transition), absorbed as fragment 1. Returns whether a fatal stopped it.
1461 fn stream_pass1(
1462 &mut self,
1463 document: &mut Document,
1464 index: &mut latexml_core::sxml::FragmentIndex,
1465 mut seed: Option<Vec<Digested>>,
1466 ) -> Result<bool> {
1467 let mut fatal_stop = false;
1468 loop {
1469 let mut boxes = Vec::new();
1470 // A seeded first iteration (the adaptive eager→streaming transition,
1471 // `digest_adaptive`) absorbs the bodies the eager loop had already
1472 // accumulated instead of digesting: they were cut at a legal yield seam,
1473 // so they are fragment 1, and the gullet continues where it stopped.
1474 let (step, yielded) = if let Some(seed_boxes) = seed.take() {
1475 boxes = seed_boxes;
1476 (Ok(true), true)
1477 } else {
1478 let step = {
1479 // Streaming had NO telemetry phases at all — every `phase()` guard in
1480 // the tree is on the eager path — so `TELEMETRY.md`'s "sum of phase
1481 // wall ≈ total wall, median ≥ 0.92" was silently unmet for every
1482 // streamed conversion. Reuse the eager phases rather than adding
1483 // streaming-specific ones: pass 1 IS digest + build, interleaved.
1484 let _g = latexml_core::telemetry::phase(latexml_core::telemetry::Phase::Digest);
1485 digest_step_guarded(&mut boxes)
1486 };
1487 (step, stomach::take_fragment_yielded())
1488 };
1489 let mut stopped = match step {
1490 Ok(keep_going) => !keep_going,
1491 Err(e) => {
1492 // Under EAGER digestion a resource fatal (the RSS fuse) is
1493 // deliberately not recovered — continuing would allocate straight
1494 // into an OOM. Under STREAMING the calculus inverts: stopping
1495 // digestion here FREES the box list, the spill below releases the
1496 // DOM, and the pipeline finishes on already-spilled content — so
1497 // recovery is not just safe, it is the feature this mode exists
1498 // for. The Fatal contract still holds: announce + latch the
1499 // verdict, keep the partial document (user policy 2026-07-28).
1500 e.log_fatal();
1501 emit_warn(
1502 "internal",
1503 "core_interface",
1504 &format!(
1505 "convert_streaming: digestion stopped by a resource fatal ({:?}/{:?}) — keeping the document built so far",
1506 e.target, e.category
1507 ),
1508 );
1509 // Recover what the interrupted step had digested. Unlike the eager
1510 // Stomach-target salvage, drop_innermost is FALSE: there is no
1511 // runaway construct to excise here — the innermost level IS the
1512 // healthy top-level accumulation, and the budget simply ran out.
1513 // Safe because everything salvaged is absorbed, spilled and freed
1514 // immediately below.
1515 boxes.extend(stomach::salvage_pending_box_lists(false).0);
1516 // (and the stack of tokens being invoked, which the build's digestion pushes onto again: 2410.07647)
1517 stomach::clear_token_stack();
1518 fatal_stop = true;
1519 true
1520 },
1521 };
1522 let mut fragment: Option<Digested> = None;
1523 if !boxes.is_empty() {
1524 let digested = Digested::from(List::new(boxes));
1525 let _g_build = latexml_core::telemetry::phase(latexml_core::telemetry::Phase::Build);
1526 // Interleaved with digestion: base-level build bindings must not
1527 // pop with the digestion group open at this seam (`with_build_floor`).
1528 if let Err(e) = state::with_build_floor(|| document.absorb(&digested, None)) {
1529 // Same Fatal contract as the eager Build: announce, latch, keep the
1530 // partial document (recovery is a FEATURE of Fatal).
1531 e.log_fatal();
1532 emit_warn(
1533 "internal",
1534 "core_interface",
1535 &format!(
1536 "convert_streaming: build stopped early ({:?}/{:?}) — keeping the document built so far",
1537 e.target, e.category
1538 ),
1539 );
1540 fatal_stop = true;
1541 stopped = true;
1542 }
1543 fragment = Some(digested);
1544 }
1545 // Perl inserts resources directly once a document exists; the eager
1546 // path's root-hook drain is deferred here, so fold fresh arrivals in
1547 // per fragment — mid-digestion consumers (the frontmatter fallback's
1548 // resource[last()] anchor) depend on them being placed.
1549 document.process_pending_resources_at_top()?;
1550 if std::env::var_os("LXML_TRACE_FRAGMENT_RC").is_some()
1551 && let Some(f) = fragment.as_ref()
1552 {
1553 trace_fragment_holders(std::slice::from_ref(f));
1554 }
1555 drop(fragment);
1556 let finishing = stopped || (!yielded && !gullet::has_more_input());
1557 if finishing
1558 && !fatal_stop
1559 && let Err(e) = state::with_build_floor(|| close_abandoned_document(document))
1560 {
1561 e.log_fatal();
1562 }
1563 // Spill policy at the end: a conversion that NEVER yielded fits in RAM
1564 // whole — spilling it would buy no headroom and cost a full
1565 // serialize→reparse→reserialize cycle in pass 2 (measured +38% wall
1566 // time at a roomy cap). But once yields happened, the ceiling is real
1567 // and the FINAL fragment must spill like every other one: retaining it
1568 // hands the eager-style spine tail (rewrites, whole-doc math parse,
1569 // finalize) everything the last fragment held — the witness died in
1570 // exactly that tail at 24.5 GB after a perfectly bounded pass 1.
1571 let bounded_mode = stomach::fragment_yield_count() > 0;
1572 if !finishing || bounded_mode {
1573 let t_spill = std::time::Instant::now();
1574 #[cfg(target_os = "linux")]
1575 let trace_spill = std::env::var_os("LXML_TRACE_NODE_BOXES").is_some();
1576 #[cfg(target_os = "linux")]
1577 let c_live_before = if trace_spill {
1578 crate::heap_trim::c_heap_mb().0
1579 } else {
1580 0
1581 };
1582 let runs_spilled = document.spill_closed_subtrees(index)?;
1583 let t_spill_dur = t_spill.elapsed();
1584 #[cfg(target_os = "linux")]
1585 if trace_spill {
1586 let c_live_after = crate::heap_trim::c_heap_mb().0;
1587 eprintln!(
1588 "streaming: spill C-live {c_live_before} -> {c_live_after} MB ({runs_spilled} runs)"
1589 );
1590 }
1591 // Self-healing: entries for nodes that build-time discard paths
1592 // detached without purging pin whole Digested box trees (see
1593 // sweep_stale_node_boxes). Spilled subtrees are purged as they spill
1594 // (`index_and_purge_spilled`, `discard_subtree`), so the sweep is only
1595 // this backstop. It marks the whole live DOM, so it runs when
1596 // `node_boxes` has grown by an eighth since the last sweep (at least
1597 // 256 entries, and never more than the absolute threshold). That is
1598 // amortized O(1) per entry while the live DOM is proportional to
1599 // `node_boxes`; resident nodes whose entries were released make each
1600 // sweep cost more. Sweeping after every spill cost O(resident DOM) on
1601 // each of 3,000-5,500 yields once a glossary block of ~3,000
1602 // definitions stayed resident at the root (datatool-user 11.6 s,
1603 // glossaries-extra-manual 82.4 s; roadmap stream C, 2026-09-25). A
1604 // spill that purged live entries lowers the baseline with them, so
1605 // stale entries cannot regrow to the old high-water mark; and the
1606 // finishing yield sweeps, so none is pinned through pass 2 and the
1607 // spine tail.
1608 document.last_swept_node_boxes_len = document
1609 .last_swept_node_boxes_len
1610 .min(document.node_boxes.len());
1611 let growth = document
1612 .node_boxes
1613 .len()
1614 .saturating_sub(document.last_swept_node_boxes_len);
1615 let relative = (document.last_swept_node_boxes_len / 8).max(256);
1616 let should_sweep =
1617 (finishing && runs_spilled > 0) || growth >= relative.min(node_boxes_sweep_threshold());
1618 if should_sweep {
1619 let t_sweep = std::time::Instant::now();
1620 document.sweep_stale_node_boxes();
1621 let t_sweep_dur = t_sweep.elapsed();
1622 if std::env::var_os("LXML_TRACE_NODE_BOXES").is_some() {
1623 eprintln!(
1624 "streaming: spill took {t_spill_dur:?} (spilled {runs_spilled} runs), sweep took {t_sweep_dur:?}"
1625 );
1626 }
1627 }
1628 // Rate-limited: a book-scale run yields MILLIONS of fragments, and
1629 // every log line lands in the in-RAM LOG_BUFFER — per-fragment
1630 // telemetry alone wrote a 1.37 GB log on the 131 MB witness,
1631 // feeding the very creep pass 1 exists to avoid.
1632 let fragments = stomach::fragment_yield_count();
1633 // Hand freed spill memory back to the OS. The spilled DOM lives on
1634 // GLIBC's heap (libxml2 allocates via libc malloc, NOT the Rust
1635 // global allocator), and glibc keeps freed mid-heap pages mapped —
1636 // measured on the 131 MB witness: every probed Rust collection flat,
1637 // C live-heap 4.45 GB peak (heaptrack), yet RSS crept 22→36 GB into
1638 // the fuse. `malloc_trim(0)` madvises free pages away (glibc ≥2.26
1639 // releases mid-heap pages too, not just the top); mimalloc (the Rust
1640 // global allocator) is collected with it. A trim walks the heap, and
1641 // a book-scale run yields millions of fragments: sampled every 4096,
1642 // it runs when RSS grew by a step (`heap_trim`).
1643 if fragments.is_multiple_of(4096) {
1644 crate::heap_trim::sample();
1645 }
1646 if fragments.is_power_of_two() || fragments.is_multiple_of(65536) {
1647 let (index_ids, index_labels, _) = index.sizes();
1648 // C-heap split (glibc only manages libxml2's allocations — Rust
1649 // goes through mimalloc): uordblks = live C bytes, fordblks =
1650 // freed-but-retained. Together with RSS this separates C live
1651 // growth / C fragmentation / Rust growth.
1652 #[cfg(target_os = "linux")]
1653 let (c_live_mb, c_free_mb) = crate::heap_trim::c_heap_mb();
1654 #[cfg(not(target_os = "linux"))]
1655 let (c_live_mb, c_free_mb) = (0usize, 0usize);
1656 let spine_children = document
1657 .get_document()
1658 .get_root_element()
1659 .map(|r| r.get_child_nodes().len())
1660 .unwrap_or(0);
1661 let (mouths, comments) = gullet::queue_sizes();
1662 emit_info(
1663 "streaming",
1664 "progress",
1665 &format!(
1666 "streaming: undo {}; mouths {}; comments {}; node_boxes {}",
1667 state::undo_depth(),
1668 mouths,
1669 comments,
1670 document.node_boxes.len(),
1671 ),
1672 );
1673 emit_info(
1674 "streaming",
1675 "progress",
1676 &format!(
1677 "streaming: fragment {} absorbed; {} segment(s) staged to disk; RSS ~{} MB; C-live {} MB; C-free {} MB; root-children {}; idstore {}; index {}+{}; arena {}; fonts {}; pending {}",
1678 fragments,
1679 latexml_core::document::spilled_segment_count(),
1680 stomach::last_sampled_rss_kb() / 1024,
1681 c_live_mb,
1682 c_free_mb,
1683 spine_children,
1684 document.idstore.len(),
1685 index_ids,
1686 index_labels,
1687 arena::len(),
1688 document.node_fonts.len(),
1689 document.pending.len(),
1690 ),
1691 );
1692 }
1693 }
1694 if finishing {
1695 break;
1696 }
1697 }
1698 Ok(fatal_stop)
1699 }
1700
1701 /// Streaming tail: root hooks, pass 2 over the spilled segments, finalize.
1702 fn stream_finish(
1703 &mut self,
1704 mut document: Document,
1705 index: latexml_core::sxml::FragmentIndex,
1706 fatal_stop: bool,
1707 phase_clock: std::time::Instant,
1708 ) -> Result<Document> {
1709 document.set_defer_root_after_open(false);
1710 // Late-arrived frontmatter first (canonically positioned after what the
1711 // mid-digestion insertion already placed), then the root's deferred late
1712 // hooks (which perform the whole insertion for documents where nothing
1713 // ran early).
1714 latexml_engine::base_utilities::insert_late_frontmatter(&mut document)?;
1715 document.dispatch_deferred_root_hooks()?;
1716 if fatal_stop {
1717 // CHEAP partial (Fatal contract under real memory pressure): every
1718 // further phase allocates while we are AT the ceiling — the first
1719 // implementation marched from the 18.8 GB cooperative fuse straight
1720 // into the 24 GB hard watchdog (SIGKILL) doing pass 2. Skip pass 2 and
1721 // the spine tail: spilled segments splice in their raw pre-finalize
1722 // form — well-formed XML that still carries `_`-bookkeeping attributes,
1723 // which a salvaged partial is allowed to. The verdict is already
1724 // latched Fatal.
1725 emit_warn(
1726 "internal",
1727 "core_interface",
1728 "convert_streaming: fatal stop — emitting the cheap partial (pass 2 and the finalize tail skipped to avoid allocating at the memory ceiling)",
1729 );
1730 // The partial's serialization must still RESOLVE placeholders (raw
1731 // segments splice recursively) — literal mode was for pass 1 only.
1732 document.literal_placeholders = false;
1733 // Flat serialization was for the spill INTERMEDIATE only — the output
1734 // keeps its formatting.
1735 document.spill_flat = false;
1736 // (the core's end, as `finish_document`'s)
1737 stomach::take_stashed_fatal();
1738 return Ok(document);
1739 }
1740 // RDFa prefixes used inside spilled content: the finalize scan can no
1741 // longer see them, so feed the spill-time record in.
1742 document.add_extra_rdfa_prefixes(index.rdfa_prefixes().map(|(p, _)| p));
1743
1744 // The rule set must be complete before ANY rewrites run: the source's
1745 // `.latexml` file loads only now (as in the eager path), and fragments
1746 // must see it too — which is exactly why pass 1 applies no rewrites.
1747 load_source_latexml_rules();
1748 // Pass 2 mutates segments while fragment documents live independently, so
1749 // it borrows the store OUT of the spine and hands it back for assembly.
1750 let mut store = document
1751 .take_spill_store()
1752 .expect("attached above; nothing detaches it during pass 1");
1753 let node_fonts = document.node_fonts.clone();
1754 // Root-level id counters run document-wide (see streaming_pass2's doc):
1755 // seed pass 2 from the spine root's pass-1 state, and hand the final
1756 // state back to the root so the spine's own tail continues the sequence.
1757 let mut counters: Vec<(String, String)> = document
1758 .get_document()
1759 .get_root_element()
1760 .map(|root| latexml_core::document::id_counters(&root))
1761 .unwrap_or_default();
1762 // So do those of each element a spilled run's top nodes are minted under (SegmentMeta::anchor).
1763 let mut anchors = document.take_spill_anchor_counters();
1764 // The document's labels, for scope resolution in every fragment and on the
1765 // spine (Document::rewrite_labels_shared, consulted on a local miss): the
1766 // spilled content's, from the pass-1 index, and those on nodes that stay on
1767 // the spine (a top-level theorem or table) — read, not minted, so pass 2's id
1768 // sequence is unchanged. Built once and shared: copying it into each
1769 // fragment's own map was quadratic (28,068 labels × 459,579 segments on the
1770 // 131 MB witness = 12.9 billion String allocations, dominating pass 2).
1771 let shared_labels: Option<Rc<rustc_hash::FxHashMap<String, String>>> = matches!(
1772 state::lookup_value("DOCUMENT_REWRITE_RULES"),
1773 Some(Stored::VecDequeStored(_))
1774 )
1775 .then(|| {
1776 let mut labels: rustc_hash::FxHashMap<String, String> = index
1777 .labels()
1778 .map(|(label, id)| (label.to_string(), id.to_string()))
1779 .collect();
1780 for node in document.find_elements(|n| n.has_attribute_no_ns("labels")) {
1781 if let (Some(node_labels), Some(id)) =
1782 (node.get_attribute("labels"), node.get_attribute("id"))
1783 {
1784 // A label carried twice (a duplicated `\label`) keeps the spilled copy's
1785 // id here, and each fragment resolves its own copy first; Perl's
1786 // `rewrite` fills its map in document order, so the last copy wins
1787 // (OXIDIZED_DESIGN #360: the index keeps no positions).
1788 for label in node_labels.split_whitespace() {
1789 labels
1790 .entry(label.to_string())
1791 .or_insert_with(|| id.clone());
1792 }
1793 }
1794 }
1795 Rc::new(labels)
1796 });
1797 let pass2_start = phase_clock.elapsed();
1798 let root_id = document
1799 .get_document()
1800 .get_root_element()
1801 .and_then(|root| root.get_attribute("id"));
1802 // The spine's share of the `d`-token evidence: with every spilled subtree's, read by the spill observer, pass 2
1803 // parses each segment against the whole document's, as the eager parse does.
1804 if !state::get_nomathparse_flag()
1805 && let Some(root) = document.get_document().get_root_element()
1806 {
1807 latexml_math_parser::read_differential_evidence(&document, &root);
1808 }
1809 streaming_pass2(
1810 &mut store,
1811 &node_fonts,
1812 &mut counters,
1813 &mut anchors,
1814 &index,
1815 shared_labels.clone(),
1816 root_id,
1817 )?;
1818 emit_info(
1819 "streaming",
1820 "progress",
1821 &format!(
1822 "streaming: PASS 2 done in {:.1?} ({:.1?} cumulative) — {} segment(s), RSS ~{} MB",
1823 phase_clock.elapsed().saturating_sub(pass2_start),
1824 phase_clock.elapsed(),
1825 latexml_core::document::spilled_segment_count(),
1826 latexml_core::watchdog::process_rss_kb().unwrap_or(0) / 1024,
1827 ),
1828 );
1829 if let Some(mut root) = document.get_document().get_root_element() {
1830 for (key, value) in &counters {
1831 let _ = root.set_attribute(key, value);
1832 }
1833 }
1834 for (id, carried) in &anchors {
1835 document.set_id_counters(id, carried);
1836 }
1837 // The spine resolves scope labels against the whole document, as the
1838 // fragments do: a label on a spilled node is not missing (its scope selects
1839 // nothing here and applies in its fragment), so only a label no element
1840 // carries reports Perl's `getLabelID` error.
1841 document.rewrite_labels_shared = shared_labels;
1842 // The spine gets the normal whole-document tail; spilled content is
1843 // invisible to it (placeholders), so root-level passes act on the live
1844 // root exactly as in the eager path.
1845 finish_document(&mut document)?;
1846 // From here serialization splices the processed segments at their
1847 // placeholders (recursively — pass 1 kept nested spills nested).
1848 document.literal_placeholders = false;
1849 // Flat serialization was for the spill INTERMEDIATE only; the spine and
1850 // the spliced segment text must carry the normal output formatting.
1851 document.spill_flat = false;
1852 document.set_spill_store(store);
1853 Ok(document)
1854 }
1855
1856 fn convert_streaming(
1857 &mut self,
1858 request: String,
1859 preamble: Option<String>,
1860 postamble: Option<String>,
1861 mode: Option<DigestionMode>,
1862 budget: usize,
1863 ) -> Result<Document> {
1864 let digestion_note = self.digest_setup(request, preamble, postamble, mode)?;
1865 let mut document = build_document_head(&self.preload)?;
1866 let mut index = self.stream_setup(&mut document, budget)?;
1867 // Phase clock starts after setup (spill store, disk gate), as it always did.
1868 let phase_clock = std::time::Instant::now();
1869 let fatal_stop = self.stream_pass1(&mut document, &mut index, None)?;
1870 stomach::set_fragment_yield_budget(None);
1871 stomach::set_fragment_yield_rss_soft_kb(None);
1872 gullet::flush();
1873 note_end(&digestion_note);
1874 let pass1_elapsed = phase_clock.elapsed();
1875 emit_info(
1876 "streaming",
1877 "progress",
1878 &format!(
1879 "streaming: PASS 1 done in {:.1?} — {} yield(s), {} segment(s) staged to disk, RSS ~{} MB",
1880 pass1_elapsed,
1881 stomach::fragment_yield_count(),
1882 latexml_core::document::spilled_segment_count(),
1883 latexml_core::watchdog::process_rss_kb().unwrap_or(0) / 1024,
1884 ),
1885 );
1886
1887 // The ROOT's after-open hooks were DEFERRED during pass 1
1888 // (`set_defer_root_after_open`): eager semantics guarantee every hook
1889 // runs with digestion complete, and firing them at fragment 1 was not
1890 // merely incomplete but harmful — the frontmatter hook consumed EMPTY
1891 // frontmatter state and marked it done (losing the abstract; sweep
1892 // witness tests/structure/abstract.tex), and the root-classes hook read
1893 // a `DOCUMENT_CLASSES` mapping `\maketitle` had not populated yet
1894 // (dropping `ltx_authors_1line`; gate witness). Dispatch exactly once,
1895 // now, with digestion finished — the eager timing.
1896 self.stream_finish(document, index, fatal_stop, phase_clock)
1897 }
1898
1899 fn digest_adaptive(
1900 &mut self,
1901 request: String,
1902 preamble: Option<String>,
1903 postamble: Option<String>,
1904 mode: Option<DigestionMode>,
1905 transition_budget: usize,
1906 ) -> Result<AdaptiveOutcome> {
1907 use latexml_core::common::error::ErrorCategory;
1908 let digestion_note = self.digest_setup(request, preamble, postamble, mode)?;
1909 // Arm the fragment-yield seam unless a caller already did (the yield
1910 // tests pre-set their own knobs): the box budget is never the trigger
1911 // here — only the soft-RSS watermark (`spill_watermark_bytes`, live at
1912 // `--max-memory=0` as RAM/8) and the constructs that request a seam
1913 // (`\pgfsys@endpicture`). A yield below the watermark just returns the
1914 // accumulated top-level bodies, which this loop keeps collecting: the
1915 // concatenation of the yielded fragments is the eager box list
1916 // (`114_streaming_*`).
1917 // Only the soft-RSS trigger is armed here — never a box budget, so a
1918 // picture seam with room to spare does not yield (the eager path stays
1919 // exactly the eager path until the watermark). A caller that pre-armed
1920 // the knobs (the yield tests) keeps pure eager yield semantics: no
1921 // transition.
1922 let armed_here =
1923 stomach::fragment_yield_budget().is_none() && stomach::fragment_yield_rss_soft_kb().is_none();
1924 if armed_here && let Some(mark_kb) = stomach::spill_mark_kb() {
1925 stomach::set_fragment_yield_rss_soft_kb(Some(mark_kb));
1926 // The growth floor measures the DOCUMENT's accumulation: baseline on
1927 // the resident set now, after the engine/dump load.
1928 stomach::rebaseline_soft_yield_growth();
1929 }
1930 let disarm = |armed: bool| {
1931 if armed {
1932 stomach::set_fragment_yield_rss_soft_kb(None);
1933 }
1934 };
1935 let mut boxes = RESCUED_BOXES.with(|r| std::mem::take(&mut *r.borrow_mut()));
1936 while gullet::has_more_input() {
1937 match digest_step_guarded(&mut boxes) {
1938 Ok(true) => {},
1939 Ok(false) => break,
1940 Err(e) => {
1941 disarm(armed_here);
1942 if !matches!(e.category, ErrorCategory::StreamingRestart) {
1943 hard_yank_processing(boxes);
1944 }
1945 return Err(e);
1946 },
1947 }
1948 // TRANSITION: an RSS-driven yield — the process is over the spill
1949 // watermark at a legal seam. Hand what is accumulated to streaming
1950 // pass 1 as fragment 1 and continue digesting from the same gullet
1951 // position: one digest, bounded memory, no from-scratch restart (which
1952 // re-read the whole source: the >180 s component on source2e/source3/
1953 // datatool/glossaries/pgf-spectra LSE). Yields below the watermark (a
1954 // picture seam with room to spare) keep accumulating — a document that
1955 // never crosses it finishes exactly as before, whole, with no spill.
1956 if stomach::take_fragment_yielded()
1957 && armed_here
1958 && stomach::fragment_yield_rss_soft_kb()
1959 .is_some_and(|soft| stomach::last_sampled_rss_kb() > soft)
1960 {
1961 stomach::set_streaming_restart_watermark(None);
1962 emit_info(
1963 "streaming",
1964 "transition",
1965 &format!(
1966 "streaming: eager digestion crossed the spill watermark at a yield seam (RSS ~{} MB, {} top-level bodies) — continuing as streaming pass 1",
1967 stomach::last_sampled_rss_kb() / 1024,
1968 boxes.len()
1969 ),
1970 );
1971 // Every failure inside the transition (the spill disk gate, a spill or
1972 // resource error in pass 1, pass 2) must leave NO yield knob armed —
1973 // they are thread-locals a persistent worker (cortex_worker) carries
1974 // into its next paper, where an armed knob would silently disable this
1975 // lever (`armed_here` false) — and must not fall into the eager
1976 // `digest_internal` salvage, which would re-digest the gullet tail
1977 // into a fresh document while the spilled front is gone: the gullet is
1978 // flushed, so the salvage finds nothing, and the Fatal is reported
1979 // exactly as `convert_streaming`'s own failure would be.
1980 let seed = std::mem::take(&mut boxes);
1981 let transition = |this: &mut Self| -> Result<(Document, bool)> {
1982 let phase_clock = std::time::Instant::now();
1983 let mut document = build_document_head(&this.preload)?;
1984 let mut index = this.stream_setup(&mut document, transition_budget)?;
1985 let fatal_stop = this.stream_pass1(&mut document, &mut index, Some(seed))?;
1986 stomach::set_fragment_yield_budget(None);
1987 stomach::set_fragment_yield_rss_soft_kb(None);
1988 gullet::flush();
1989 emit_info(
1990 "streaming",
1991 "progress",
1992 &format!(
1993 "streaming: PASS 1 done in {:.1?} — {} yield(s), {} segment(s) staged to disk, RSS ~{} MB",
1994 phase_clock.elapsed(),
1995 stomach::fragment_yield_count(),
1996 latexml_core::document::spilled_segment_count(),
1997 latexml_core::watchdog::process_rss_kb().unwrap_or(0) / 1024,
1998 ),
1999 );
2000 this
2001 .stream_finish(document, index, fatal_stop, phase_clock)
2002 .map(|document| (document, fatal_stop))
2003 };
2004 let outcome = transition(self);
2005 stomach::set_fragment_yield_budget(None);
2006 stomach::set_fragment_yield_rss_soft_kb(None);
2007 note_end(&digestion_note);
2008 return match outcome {
2009 Ok((document, false)) => {
2010 // Finished in ONE pass: a restart signal latched along the way
2011 // must not make the binary rerun the document from scratch.
2012 let _ = stomach::take_streaming_restart_signal();
2013 Ok(AdaptiveOutcome::Streamed(Box::new(document)))
2014 },
2015 Ok((document, true)) => {
2016 // Pass 1 hit the fuse: the seed (everything the eager phase held
2017 // when it crossed the watermark) plus pass 1's own growth did not
2018 // fit, and the document is the cheap partial. Leave the restart
2019 // signal alone: the binary's from-scratch `--streaming` rerun
2020 // starts far below the watermark and is the proven fallback
2021 // (pgf-spectra LSE at --max-memory=6144: transition at 1.59 GB,
2022 // pass 1 crept to 4.79 GB and stopped at 71 % of the paths; the
2023 // restart completes it in 165 s). The streaming-pass creep is
2024 // the residual to attribute next.
2025 Ok(AdaptiveOutcome::Streamed(Box::new(document)))
2026 },
2027 Err(e) => {
2028 gullet::flush();
2029 Err(e)
2030 },
2031 };
2032 }
2033 }
2034 // (a Fatal stashed in the last step is the digestion's, as in `digest_internal`: left armed, the build raised it)
2035 if let Some(fatal) = stomach::take_stashed_fatal()
2036 && let Err(e) = finish_digestion_fatal(fatal, &mut boxes)
2037 {
2038 disarm(armed_here);
2039 if !matches!(e.category, ErrorCategory::StreamingRestart) {
2040 hard_yank_processing(boxes);
2041 }
2042 return Err(e);
2043 }
2044 disarm(armed_here);
2045 gullet::flush();
2046 note_end(&digestion_note);
2047 Ok(AdaptiveOutcome::Eager(Digested::from(List::new(boxes))))
2048 }
2049
2050 /// Restriction: convert_document runs on a single thread, and should never try branching out.
2051 fn convert_document(&mut self, digested: Digested) -> Result<Document> {
2052 note_begin("Building");
2053 let mut document = build_document_head(&self.preload)?;
2054 Debug!("Doc absorb: {:?}", digested);
2055
2056 // A Build that runs out of budget KEEPS what it has already built. The
2057 // guard tick inside `absorb` (see `document.rs`) can now raise a resource
2058 // Fatal mid-build; propagating it with `?` would discard a document that is
2059 // structurally sound up to the cut and hand the user a 39-byte stub — the
2060 // same loss `digest_internal` already salvages against on the digestion
2061 // side. Recovery is a FEATURE of Fatal here (user policy 2026-07-28):
2062 // announce it, keep the partial document, finish the pipeline gracefully.
2063 // `log_fatal` both emits the `Fatal:` line and latches the status, so the
2064 // run still reports as failed and never masquerades as clean.
2065 if let Err(e) = document.absorb(&digested, None) {
2066 e.log_fatal();
2067 emit_warn(
2068 "internal",
2069 "core_interface",
2070 &format!(
2071 "convert_document: build stopped early ({:?}/{:?}) — keeping the \
2072 document built so far",
2073 e.target, e.category
2074 ),
2075 );
2076 } else if let Err(e) = close_abandoned_document(&mut document) {
2077 e.log_fatal();
2078 }
2079 note_end("Building");
2080
2081 load_source_latexml_rules();
2082 // The math parser's `d`-token evidence, read over the whole document before its rewrites (in `--streaming`, as
2083 // each subtree spills and on the spine before pass 2).
2084 if !state::get_nomathparse_flag()
2085 && let Some(root) = document.get_document().get_root_element()
2086 {
2087 latexml_math_parser::read_differential_evidence(&document, &root);
2088 }
2089 finish_document(&mut document)?;
2090 Ok(document)
2091 }
2092
2093 fn digest_internal(&mut self) -> Result<Digested> {
2094 use latexml_core::common::error::ErrorCategory;
2095 // Perl `finishDigestion` (Core.pm L214-226): re-collect what a Fatal
2096 // rescued, then digest whatever input is left — which, after
2097 // `hard_yank_processing`, is nothing.
2098 let mut boxes = RESCUED_BOXES.with(|r| std::mem::take(&mut *r.borrow_mut()));
2099 while gullet::has_more_input() {
2100 match digest_step_guarded(&mut boxes) {
2101 Ok(true) => {},
2102 Ok(false) => break,
2103 Err(e) => {
2104 // A streaming-restart stop is not a failure: the CLI reruns the
2105 // document from the top, so nothing is rescued and the gullet is
2106 // left for the rerun to rebuild.
2107 if !matches!(e.category, ErrorCategory::StreamingRestart) {
2108 hard_yank_processing(boxes);
2109 }
2110 return Err(e);
2111 },
2112 }
2113 }
2114 // (a Fatal stashed in the last step is the digestion's, its boxes kept as for any other)
2115 if let Some(fatal) = stomach::take_stashed_fatal()
2116 && let Err(e) = finish_digestion_fatal(fatal, &mut boxes)
2117 {
2118 if !matches!(e.category, ErrorCategory::StreamingRestart) {
2119 hard_yank_processing(boxes);
2120 }
2121 return Err(e);
2122 }
2123 gullet::flush();
2124 Ok(Digested::from(List::new(boxes)))
2125 }
2126
2127 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
2128 // Mid-level API.
2129
2130 // options are currently being evolved to accomodate the Daemon:
2131 // mode : the processing mode, ie the pool to preload: TeX or BibTeX
2132 // noinitialize : if defined, it does not initialize State.
2133 // preamble = names a tex file (or standard_preamble.tex)
2134 // postamble = names a tex file (or standard_postamble.tex)
2135
2136 /// Restriction: `digest_file` runs on a single thread, and should never try branching out.
2137 fn digest_file(&mut self, mut request: String, options: DigestionOptions) -> Result<Digested> {
2138 let mut dir = String::new();
2139 let name;
2140 // let mut ext = String::new();
2141 let mode = match options.mode {
2142 None => DigestionMode::TeX,
2143 Some(m) => m,
2144 };
2145
2146 if pathname::is_literaldata(&request) {
2147 // ext = mode.extension();
2148 name = s!("Anonymous String");
2149 } else if pathname::is_url(&request) {
2150 // ext = mode.extension();
2151 name = request.clone();
2152 } else {
2153 let ext_str = s!(".{}", mode.extension());
2154 let request_base = if request.ends_with(&ext_str) {
2155 request[0..request.len() - ext_str.len()].to_string()
2156 } else {
2157 request
2158 };
2159
2160 if let Some(pathname) = pathname::find(&request_base, PathnameFindOptions {
2161 extensions: Some(vec![mode.extension(), String::new()]),
2162 ..PathnameFindOptions::default()
2163 }) {
2164 request = pathname;
2165 dir = pathname::directory(&request);
2166 name = pathname::file_stem(&request);
2167 // Perl Core.pm L195-200 unshifts the SOURCE file's directory onto
2168 // SEARCHPATHS so subsequent `\input`-style lookups resolve relative
2169 // to the main file. When the user invokes with a bare filename
2170 // (e.g. `latexml_oxide neurips_2025.tex` from the paper's cwd),
2171 // `pathname::find` returns the relative match and `pathname::
2172 // directory` returns an empty string — which then gets pushed
2173 // onto SEARCHPATHS as a useless entry. Resolve to CWD in that
2174 // case so the paper-local Chapter/ etc. are reachable.
2175 if dir.is_empty()
2176 && let Ok(cwd) = std::env::current_dir()
2177 {
2178 dir = cwd.to_string_lossy().to_string();
2179 }
2180 // ext = pathname::extension(&request);
2181 } else {
2182 let message = s!("Can't find {} file {} ", mode, request_base);
2183 fatal!(Core, MissingFile, message);
2184 }
2185 }
2186 note_begin(&s!("Digesting {} {}", mode, name));
2187 let main_pool = s!("{}.pool", mode);
2188 let noinitialize = options.noinitialize.unwrap_or(false);
2189 if !noinitialize {
2190 let mut preloads = vec![main_pool];
2191 preloads.extend(self.preload.clone());
2192 self.initialize_singletons(preloads)?;
2193 }
2194 {
2195 let source_file = if pathname::is_literaldata(&request) {
2196 None
2197 } else {
2198 Some(request.as_str())
2199 };
2200 establish_source_context(source_file, &name, &dir);
2201 }
2202
2203 // Reverse order, since last opened is first read!
2204 if let Some(postamble) = options.postamble {
2205 self.load_postamble(postamble);
2206 }
2207
2208 {
2209 // Make sure the stomach trick is used very *tightly*, always with a surrounding scope.
2210 input_content(&request, InputOptions::default())?;
2211 }
2212
2213 if let Some(preamble) = options.preamble {
2214 self.load_preamble(preamble);
2215 }
2216
2217 // Now for the Hacky part for BibTeX!!!
2218 // Perl `Core.pm` L160-162: drain the mouth(s) just opened on the
2219 // .bib file, run the low-level parser to build a registry of
2220 // BibEntry objects, then push a literal wrapper TeX block that
2221 // the LaTeX-side digester reads back as
2222 // \begin{bibtex@bibliography}
2223 // \ProcessBibTeXEntry{<key1>}
2224 // ...
2225 // \end{bibtex@bibliography}
2226 if matches!(mode, DigestionMode::BibTeX) {
2227 use latexml_engine::pre_bibtex::PreBibTeX;
2228 let mut bib = PreBibTeX::new_from_gullet(&name);
2229 match bib.to_tex() {
2230 Ok(tex) => {
2231 input_content(&s!("literal:{tex}"), InputOptions::default())?;
2232 },
2233 Err(parse_err) => {
2234 Error!(
2235 "bibtex",
2236 "parse_failed",
2237 s!("Failed to parse BibTeX file {}: {:?}", name, parse_err)
2238 );
2239 },
2240 }
2241 }
2242
2243 let list = self.digest_internal()?;
2244 note_end(&s!("Digesting {} {}", mode, name));
2245 Ok(list)
2246 }
2247}
2248
2249/// The output mode a document is compiled in (K6 ruling, 2026-09-24).
2250/// pdflatex's format sets `\pdfoutput=1` (pdftexconfig.tex), and arXiv
2251/// compiles a source with pdflatex unless its figures are EPS/PS only, which it
2252/// runs through latex+dvips (a document's own `\pdfoutput=1` in its first lines
2253/// still selects pdflatex, and still sets the register here). So PDF output
2254/// is the default, DVI the exception for a source whose included figures are
2255/// PostScript only or that loads pstricks (its tree's files, when no included
2256/// figure resolves). Under the `luatex` profile the output is always PDF
2257/// (luatex85's `\pdfoutput` is `\outputmode`); under `xetex` there is no
2258/// `\pdfoutput` and `\ifpdf` stays false. arXiv 2605: 95.8 % of 30,079
2259/// sources are pdflatex ones, and 1,646 of the 1,692 that test `\ifpdf` had
2260/// taken their DVI branch here.
2261fn establish_pdf_output_mode(dir: &str) {
2262 if state::lookup_bool("XETEX_PROFILE") {
2263 return;
2264 }
2265 // The colour stacks `\pdfcolorstackinit` numbers belong to one document.
2266 state::assign_value("pdfcolorstack_count", 0i64, Some(Scope::Global));
2267 // A DVI driver class option is the same cue (stream F; `state::dvi_driver_option`): 0908.4150's
2268 // `\documentclass[12pt,dvips]{article}` ships no figures but is a latex+dvips document; the `pdftex` one the
2269 // opposite (`state::pdf_driver_option`, 2210.04612).
2270 // The figures the source includes come next (`state::figure_output_cue`, OXIDIZED_DESIGN_DIVERGENCES #537); only
2271 // when none resolves, and no pstricks is loaded, does the tree's file inventory decide.
2272 // (an author's latexml.sty option `pdfoutput`/`nopdfoutput`, preloaded, decides over every cue: OD #1046)
2273 let pdf = if state::has_value("PDFOUTPUT_OPTION") {
2274 state::lookup_int("PDFOUTPUT_OPTION") != 0
2275 } else {
2276 state::lookup_bool("LUATEX_PROFILE")
2277 || state::pdf_driver_option()
2278 || (!state::dvi_driver_option()
2279 && match state::figure_output_cue() {
2280 state::FigureOutputCue::Pdf => true,
2281 state::FigureOutputCue::Dvi => false,
2282 state::FigureOutputCue::Undecided => !source_figures_are_postscript_only(dir),
2283 })
2284 };
2285 let _ = state::assign_register(
2286 "\\pdfoutput",
2287 latexml_core::common::number::Number(i64::from(pdf)).into(),
2288 Some(Scope::Global),
2289 Vec::new(),
2290 );
2291}
2292
2293/// Whether the source directory tree's figures are PostScript only, for a source whose included figures decide nothing
2294/// (`state::FigureOutputCue::Undecided`): it holds an EPS/PS file and no PDF/PNG/JPEG one —
2295/// arXiv AutoTeX's cue for latex+dvips, which cannot include the others (a source shipping both, an MDPI template's
2296/// `logo-*.eps` beside PNG figures, 2210.04612, is a pdflatex one). The walk is bounded: a document converted from a
2297/// large directory (a home directory, say) is not read end to end.
2298fn source_figures_are_postscript_only(dir: &str) -> bool {
2299 const MAX_DEPTH: usize = 4;
2300 const MAX_ENTRIES: usize = 20_000;
2301 if dir.is_empty() {
2302 return false;
2303 }
2304 let mut stack = vec![(std::path::PathBuf::from(dir), 0usize)];
2305 let mut seen = 0usize;
2306 let mut postscript = false;
2307 while let Some((path, depth)) = stack.pop() {
2308 let Ok(entries) = std::fs::read_dir(&path) else {
2309 continue;
2310 };
2311 for entry in entries.flatten() {
2312 seen += 1;
2313 if seen > MAX_ENTRIES {
2314 return false;
2315 }
2316 let entry_path = entry.path();
2317 if entry.file_type().is_ok_and(|t| t.is_dir()) {
2318 if depth < MAX_DEPTH {
2319 stack.push((entry_path, depth + 1));
2320 }
2321 continue;
2322 }
2323 let Some(extension) = entry_path
2324 .extension()
2325 .and_then(|e| e.to_str())
2326 .map(str::to_ascii_lowercase)
2327 else {
2328 continue;
2329 };
2330 match extension.as_str() {
2331 "eps" | "ps" | "epsf" | "epsi" => postscript = true,
2332 "pdf" | "png" | "jpg" | "jpeg" => return false,
2333 _ => {},
2334 }
2335 }
2336 }
2337 postscript
2338}
2339
2340/// Establish the document-global *source context* for a **top-level** document
2341/// load — `SOURCEFILE`, `SOURCEDIRECTORY`, the front of `SEARCHPATHS`,
2342/// `GRAPHICSPATHS`, and `\jobname` (Perl Core.pm L195-200). Shared by
2343/// [`DigestionAPI::digest_file`] (content read from disk) and
2344/// [`crate::converter::Converter::digest_content_with_provenance`] (content
2345/// supplied in memory) so the two cannot drift.
2346///
2347/// `source_file` is the value for `SOURCEFILE` — the source's path/identity —
2348/// or `None` for an anonymous/literal source. `jobname` is the bare job name
2349/// (file stem). `dir` is the source directory (may be empty, e.g. a literal).
2350///
2351/// This is for the *main* document only; a nested `\input`/continuation must
2352/// not reset these document-global values.
2353pub(crate) fn establish_source_context(source_file: Option<&str>, jobname: &str, dir: &str) {
2354 if let Some(sf) = source_file {
2355 state::assign_value("SOURCEFILE", sf.to_string(), None);
2356 }
2357 if !dir.is_empty() {
2358 state::assign_value("SOURCEDIRECTORY", dir.to_string(), None);
2359 }
2360 establish_pdf_output_mode(dir);
2361 state::search_paths_push_front(dir.to_string());
2362 // Perl Core.pm L200: unshift GRAPHICSPATHS => $dir unless already present.
2363 if !state::graphics_paths_contains(dir) {
2364 state::graphics_paths_push_front(dir.to_string());
2365 }
2366 install_jobname(jobname);
2367}
2368
2369/// Install the job's `\jobname`: a token macro set per conversion, as Perl does (Core.pm:152, :204),
2370/// so `\meaning\jobname` reads `macro:->jobname`. Perl also sets it after the preloads (`initializeState`
2371/// runs first, Core.pm:143), but a Perl preload loads no format: expl3's copies of `\jobname`
2372/// (`\tex_jobname:D`, and `\c_sys_jobname_str` from the l3sys job-start hook) are taken at
2373/// `\documentclass`, once the job's name is in place. Here a `latexml.sty` / `ar5iv.sty` preload
2374/// loads the LaTeX format first, so those copies hold the engine's empty placeholder; while
2375/// `\jobname` is still that placeholder, every copy of it is re-pointed to the job's
2376/// (`state::rebind_let_copies`) — TeX's answer, since TeX knows the job name before any code runs.
2377/// That holds for a copy a user's own preload takes too (`\let\myjob\jobname`), where Perl keeps the
2378/// placeholder (OXIDIZED_DESIGN_DIVERGENCES #347). A later install — the nested `.bib` session's
2379/// (`bib_session.rs`, BibTeX mode, Core.pm:204) — leaves the document's copies alone, as Perl's
2380/// fresh definition does. Repro expl3/tex_jobname_is_the_jobname.
2381fn install_jobname(jobname: &str) {
2382 let jobname_cs = T_CS!("\\jobname");
2383 let new = Stored::Expandable(Rc::new(Expandable {
2384 cs: jobname_cs,
2385 paramlist: None,
2386 expansion: Tokens::new(Explode!(jobname)).into(),
2387 ..Expandable::default()
2388 }));
2389 let before_any_job = state::with_meaning(&jobname_cs, |meaning| {
2390 matches!(meaning, Some(Stored::Expandable(placeholder))
2391 if match placeholder.get_expansion() {
2392 None => true,
2393 Some(ExpansionBody::Tokens(body)) => body.is_empty(),
2394 Some(ExpansionBody::Closure(_)) => false,
2395 })
2396 });
2397 if before_any_job {
2398 state::rebind_let_copies(&jobname_cs, &new);
2399 }
2400 state::install_definition(new, None);
2401}
2402
2403/// Load a `.latexml` file alongside a `.tex` source file.
2404/// Parses `DefMathRewrite(...)` calls and registers them as rewrite rules.
2405/// Perl loads these automatically; this provides the equivalent for Rust tests.
2406///
2407/// Supported patterns:
2408/// - Single character: `match => 'a'` -> XPath on XMTok text content
2409/// - Complex patterns (e.g. `\hat{f}`, `f_D`, `f_\WildCard`): skipped
2410/// - `scope => 'label:...'`: scoped rewrites via label lookup
2411/// - `attributes => { role => 'FUNCTION' }`: sets role (and optionally name/meaning)
2412fn load_latexml_file(path: &str) -> Result<()> {
2413 use latexml_core::rewrite::{RewriteClause, RewriteOperator, RewritePattern};
2414
2415 let content = match std::fs::read_to_string(path) {
2416 Ok(c) => c,
2417 Err(_) => return Ok(()), // File doesn't exist or can't be read
2418 };
2419
2420 for cap in DEF_MATH_REWRITE_RE.captures_iter(&content) {
2421 let body = &cap[1];
2422
2423 // Extract match pattern
2424 let match_str = match MATCH_RE.captures(body) {
2425 Some(m) => m[1].to_string(),
2426 None => continue, // No match clause, skip
2427 };
2428
2429 // Build attributes map from the attributes => { ... } section
2430 let mut attrs = HashMap::default();
2431 if let Some(role_cap) = ROLE_RE.captures(body) {
2432 attrs.insert("role".to_string(), role_cap[1].to_string());
2433 }
2434 if let Some(name_cap) = NAME_ATTR_RE.captures(body) {
2435 attrs.insert("name".to_string(), name_cap[1].to_string());
2436 }
2437 if let Some(meaning_cap) = MEANING_RE.captures(body) {
2438 attrs.insert("meaning".to_string(), meaning_cap[1].to_string());
2439 }
2440 if attrs.is_empty() {
2441 continue; // No attributes to set
2442 }
2443
2444 // Check for optional scope
2445 let scope_str = SCOPE_RE.captures(body).map(|s| s[1].to_string());
2446
2447 // Use compile_declare_pattern for all patterns (simple + complex).
2448 // The .latexml match strings use the same format as \lxDeclare body_text:
2449 // 'f' (simple), 'f_D' (literal subscript), 'f_\WildCard' (wildcard),
2450 // '\hat{f}' (accent), "x^{\prime}" (prime).
2451 let pat = latexml_core::rewrite::declare::compile_declare_pattern(&match_str);
2452 if pat.xpath.is_empty() {
2453 continue; // Unrecognized pattern, skip
2454 }
2455
2456 // For math mode, append visibility check to XPath
2457 let xpath = format!("{}[@_pvis and @_cvis]", pat.xpath);
2458
2459 // Determine select_count based on pattern type
2460 let select_count = pat.select_count().or(Some(1usize));
2461
2462 // Build the rewrite rule
2463 let mut clauses = Vec::new();
2464
2465 // Add scope clause if present
2466 if let Some(ref scope) = scope_str {
2467 clauses.push(RewriteClause::new_uncompiled(
2468 RewriteOperator::Scope,
2469 RewritePattern::String(scope.clone()),
2470 ));
2471 }
2472
2473 // Add match clause (pre-compiled as XPath string)
2474 clauses.push(RewriteClause::new_uncompiled(
2475 RewriteOperator::Match,
2476 RewritePattern::String(xpath),
2477 ));
2478
2479 // Add attributes clause
2480 clauses.push(RewriteClause::new_compiled(
2481 RewriteOperator::Attributes,
2482 RewritePattern::String(String::new()),
2483 ));
2484
2485 let rewrite = Rewrite::from_clauses(
2486 RewriteOptions {
2487 attributes_map: Some(attrs),
2488 is_math: true,
2489 select_count,
2490 wildcard_paths: pat.wildcard_paths.clone(),
2491 declare_filter: Some(pat),
2492 ..RewriteOptions::default()
2493 },
2494 clauses,
2495 );
2496
2497 state::push_value("DOCUMENT_REWRITE_RULES", rewrite)?;
2498 }
2499
2500 Ok(())
2501}
2502
2503/// Where an `\lxDeclare` applies (Perl `Rewrite::compile_clause`'s `scope` clause, Rewrite.pm:298-311):
2504/// the whole document (no scope, or one Perl does not recognize and ignores), the element with an
2505/// id and what it holds (`id:S2`; a `label:` resolved to its element's id), or nowhere — a label no
2506/// element carries, which Perl compiles to an id-less XPath that selects nothing.
2507enum DeclarationScope {
2508 Everywhere,
2509 Within(String),
2510 Nowhere,
2511}
2512
2513impl DeclarationScope {
2514 fn resolve(document: &Document, scope: &str) -> Self {
2515 if scope.is_empty() {
2516 DeclarationScope::Everywhere
2517 } else if let Some(id) = scope.strip_prefix("id:") {
2518 DeclarationScope::Within(id.to_string())
2519 } else if let Some(label) = scope.strip_prefix("label:") {
2520 document
2521 .lookup_rewrite_label(label)
2522 .or_else(|| document.lookup_rewrite_label(&format!("LABEL:{label}")))
2523 .map_or(DeclarationScope::Nowhere, DeclarationScope::Within)
2524 } else {
2525 DeclarationScope::Everywhere
2526 }
2527 }
2528
2529 /// Does the scope hold `node`: it or an ancestor carries the id, or — in a streaming fragment —
2530 /// the id is one of the fragment's ancestors (`Document::fragment_ancestor_ids`).
2531 fn covers(&self, document: &Document, node: &libxml::tree::Node) -> bool {
2532 match self {
2533 DeclarationScope::Everywhere => true,
2534 DeclarationScope::Nowhere => false,
2535 DeclarationScope::Within(id) => {
2536 if document.fragment_ancestor_ids.contains(id) {
2537 return true;
2538 }
2539 let mut current = Some(node.clone());
2540 while let Some(element) = current {
2541 if element
2542 .get_attribute_ns("id", latexml_core::common::xml::XML_NS)
2543 .as_deref()
2544 == Some(id.as_str())
2545 || element.get_property("id").as_deref() == Some(id.as_str())
2546 {
2547 return true;
2548 }
2549 current = element.get_parent();
2550 }
2551 false
2552 },
2553 }
2554 }
2555}
2556
2557/// Apply \lxDeclare declarations to the document.
2558/// Simple fast-path: matches single-token patterns in XMTok elements
2559/// and sets role/name/meaning attributes.
2560fn apply_lx_declarations(document: &mut Document) {
2561 let decls_str = match state::lookup_value("LATEXML_DECLARATIONS") {
2562 Some(Stored::String(s)) => arena::with(s, |r| r.to_string()),
2563 _ => return,
2564 };
2565 if decls_str.is_empty() {
2566 return;
2567 }
2568
2569 // Parse declarations:
2570 // "token_text\trole\tname\tmeaning\tdecl_id\tmatch_font\tscope".
2571 // match_font (font_attribute_string of the digested pattern, e.g.
2572 // "italic"/"bold") makes matching font-aware: a plain italic `$x$` declaration
2573 // must not annotate a bold `\mathbf{x}` — different fonts denote different
2574 // meanings; empty when the pattern carried no distinguishing font.
2575 // scope is the declaration's (`get_declaration_scope`), resolved here as the
2576 // rewrite rule resolves it (`Rewrite::compile_clause`).
2577 let declarations: Vec<(&str, &str, &str, &str, &str, &str, DeclarationScope)> = decls_str
2578 .lines()
2579 .filter_map(|line| {
2580 let parts: Vec<&str> = line.splitn(7, '\t').collect();
2581 if parts.len() >= 4 {
2582 Some((
2583 parts[0],
2584 parts[1],
2585 parts[2],
2586 parts[3],
2587 *parts.get(4).unwrap_or(&""),
2588 *parts.get(5).unwrap_or(&""),
2589 DeclarationScope::resolve(document, parts.get(6).unwrap_or(&"")),
2590 ))
2591 } else {
2592 None
2593 }
2594 })
2595 .collect();
2596
2597 if declarations.is_empty() {
2598 return;
2599 }
2600
2601 // Find all XMTok elements in the document and apply matching declarations.
2602 // Skip tokens already marked by the rewrite system (_matched) — these were
2603 // handled by subscript/prime/wildcard patterns which take precedence.
2604 let xmtoks = document.findnodes("descendant-or-self::ltx:XMTok", None);
2605 for mut tok in xmtoks {
2606 if tok.has_attribute("_matched") {
2607 continue;
2608 }
2609 let content = tok.get_content();
2610 let tok_name = tok.get_attribute("name").unwrap_or_default();
2611
2612 // The latest declaration wins, as Perl's `UnshiftValue` puts each rule before the earlier ones
2613 // and a matched node is skipped by the rest (latexml.sty.ltxml:564; Rewrite.pm select).
2614 for (pattern, role, name, meaning, decl_id, match_font, scope) in declarations.iter().rev() {
2615 let (pattern, role, name, meaning, decl_id, match_font) =
2616 (*pattern, *role, *name, *meaning, *decl_id, *match_font);
2617 // Match by content text, or by XMTok name attribute (for CS patterns like \circ)
2618 let matches = content == pattern
2619 || (!tok_name.is_empty() && pattern.starts_with('\\') && pattern[1..] == tok_name);
2620 if matches {
2621 // Font-class check (mirrors declare_node_matches in the rewrite path):
2622 // discriminate only on the meaningful font *classes* — bold vs not,
2623 // caligraphic/typewriter family — NOT on an exact font-string match.
2624 // Exact equality is wrong here because the declaration's digested frame
2625 // font (e.g. "italic") differs from an upright operator token's font
2626 // even when they should match (e.g. `$*$` → the ∗ COMPOSEOP token).
2627 // A plain/italic declaration rejects bold/caligraphic/typewriter tokens
2628 // (so italic `$x$` skips bold `\mathbf{x}`); a declaration that is
2629 // itself bold/caligraphic/typewriter requires the token to share it.
2630 {
2631 let tf = document.get_node_font(&tok);
2632 let tok_bold = tf
2633 .get_series()
2634 .map(|s| s.as_ref() == "bold")
2635 .unwrap_or(false);
2636 let tok_fam = tf.get_family();
2637 let tok_cal = tok_fam
2638 .as_ref()
2639 .map(|f| f.as_ref() == "caligraphic")
2640 .unwrap_or(false);
2641 let tok_tt = tok_fam
2642 .as_ref()
2643 .map(|f| f.as_ref() == "typewriter")
2644 .unwrap_or(false);
2645 let decl_bold = match_font.contains("bold");
2646 let decl_cal = match_font.contains("caligraphic");
2647 let decl_tt = match_font.contains("typewriter");
2648 if tok_bold != decl_bold || tok_cal != decl_cal || tok_tt != decl_tt {
2649 continue;
2650 }
2651 }
2652 if !scope.covers(document, &tok) {
2653 continue; // Outside the declaration's scope
2654 }
2655 if !role.is_empty() {
2656 let _ = tok.set_attribute("role", role);
2657 }
2658 if !name.is_empty() {
2659 let _ = tok.set_attribute("name", name);
2660 }
2661 if !meaning.is_empty() {
2662 let _ = tok.set_attribute("meaning", meaning);
2663 }
2664 if !decl_id.is_empty() {
2665 let _ = tok.set_attribute("decl_id", decl_id);
2666 }
2667 break; // The latest matching declaration wins
2668 }
2669 }
2670 }
2671}
2672
2673/// Fallback parser for unparseable math expressions.
2674/// Perl: MathParser.pm parse_kludge().
2675/// Balances OPEN/CLOSE delimiters by wrapping matched groups in XMWrap.
2676/// Uses document.wrap_nodes for proper namespace handling.
2677/// Renumber xml:ids inside parsed XMath subtrees so they are sequential in
2678/// document order. The Marpa parser explores multiple parse alternatives,
2679/// consuming ID counter slots for pruned nodes (e.g. m1.1, m1.7, m1.12
2680/// instead of m1.1, m1.2, m1.3). This pure post-processing pass reassigns
2681/// IDs after all pruning is complete.
2682///
2683/// Optimized: single DFS walk per XMath (not XPath), O(1) parent-prefix
2684/// lookup via ID string parsing, and allocation reuse across Math nodes.
2685fn renumber_math_ids(document: &mut Document) {
2686 let xml_ns = "http://www.w3.org/XML/1998/namespace";
2687 let math_nodes = document.findnodes("descendant-or-self::ltx:Math[@text]", None);
2688
2689 // Reuse allocations across Math nodes
2690 let mut id_entries: Vec<(libxml::tree::Node, String)> = Vec::new();
2691 let mut idref_entries: Vec<(libxml::tree::Node, String)> = Vec::new();
2692 let mut id_map: rustc_hash::FxHashMap<String, String> = rustc_hash::FxHashMap::default();
2693 let mut referenced_ids: rustc_hash::FxHashSet<String> = rustc_hash::FxHashSet::default();
2694
2695 for mut math_node in math_nodes {
2696 let math_id = match math_node.get_attribute_ns("id", xml_ns) {
2697 Some(id) => id,
2698 None => continue,
2699 };
2700
2701 let xmath_nodes = document.findnodes("ltx:XMath", Some(&math_node));
2702 for xmath in xmath_nodes {
2703 id_entries.clear();
2704 idref_entries.clear();
2705 id_map.clear();
2706 referenced_ids.clear();
2707
2708 // Single DFS walk collects both xml:id and idref nodes in document order
2709 renumber_collect_dfs(&xmath, xml_ns, &mut id_entries, &mut idref_entries);
2710 if id_entries.is_empty() {
2711 continue;
2712 }
2713
2714 // Collect all referenced IDs (from XMRef idref attributes)
2715 for (_, idref) in &idref_entries {
2716 referenced_ids.insert(idref.clone());
2717 }
2718
2719 // Strip xml:id from XMTok elements that are not referenced by any XMRef.
2720 // The math parser assigns xml:ids to all tokens during parsing, but only
2721 // structural nodes (XMApp, XMDual) and explicitly referenced tokens need them.
2722 // Orphan XMTok ids inflate the renumbering counter causing ID gaps.
2723 {
2724 let mut stripped = false;
2725 for (node, id) in &mut id_entries {
2726 if node.get_name() == "XMTok" && !referenced_ids.contains(id.as_str()) {
2727 document.unrecord_id(id);
2728 let _ = node.remove_attribute("xml:id");
2729 let _ = node.remove_attribute_ns("id", xml_ns);
2730 id.clear(); // mark for removal
2731 stripped = true;
2732 }
2733 }
2734 if stripped {
2735 id_entries.retain(|(_, id)| !id.is_empty());
2736 }
2737 }
2738
2739 if id_entries.is_empty() {
2740 continue;
2741 }
2742
2743 // Build old→new mapping. Flat sequential numbering under the math_id prefix,
2744 // matching Perl's approach of assigning all IDs at the same level.
2745 let mut counter = 0u32;
2746 let mut any_changed = false;
2747 for (_node, old_id) in &id_entries {
2748 counter += 1;
2749 let new_id = format!("{math_id}.{counter}");
2750 if new_id != *old_id {
2751 any_changed = true;
2752 }
2753 id_map.insert(old_id.clone(), new_id);
2754 }
2755
2756 if !any_changed {
2757 continue;
2758 }
2759
2760 // Apply new xml:ids in TWO passes to avoid idstore collisions.
2761 // A new id like "m1.1" would collide with an old "m1.1" still in the
2762 // idstore if we interleave unrecord+record. Strip all first, then assign.
2763 let mut nodes_to_update: Vec<(libxml::tree::Node, String)> = Vec::new();
2764 for (mut node, old_id) in id_entries.drain(..) {
2765 if let Some(new_id) = id_map.get(&old_id)
2766 && new_id != &old_id
2767 {
2768 document.unrecord_id(&old_id);
2769 let _ = node.remove_attribute("xml:id");
2770 let _ = node.remove_attribute_ns("id", xml_ns);
2771 nodes_to_update.push((node, new_id.clone()));
2772 }
2773 }
2774 for (mut node, new_id) in nodes_to_update {
2775 let _ = document.set_attribute(&mut node, "xml:id", &new_id);
2776 }
2777
2778 // Update idrefs
2779 for (mut node, old_idref) in idref_entries.drain(..) {
2780 if let Some(new_idref) = id_map.get(&old_idref)
2781 && new_idref != &old_idref
2782 {
2783 let _ = node.set_attribute("idref", new_idref);
2784 }
2785 }
2786
2787 // Reset _ID_counter__ on the Math node to the final count
2788 let _ = math_node.set_attribute("_ID_counter__", &counter.to_string());
2789 }
2790 }
2791}
2792
2793/// DFS walk collecting nodes with xml:id and idref attributes in document order.
2794/// Stops at nested `Math` elements (which have their own parsing scope).
2795fn renumber_collect_dfs(
2796 node: &libxml::tree::Node,
2797 xml_ns: &str,
2798 id_entries: &mut Vec<(libxml::tree::Node, String)>,
2799 idref_entries: &mut Vec<(libxml::tree::Node, String)>,
2800) {
2801 if let Some(id) = node.get_attribute_ns("id", xml_ns) {
2802 id_entries.push((node.clone(), id));
2803 }
2804 if let Some(idref) = node.get_attribute("idref") {
2805 idref_entries.push((node.clone(), idref));
2806 }
2807 for child in node.get_child_elements() {
2808 // Skip nested Math elements — they have their own parsing scope
2809 if child.get_name() == "Math" {
2810 continue;
2811 }
2812 renumber_collect_dfs(&child, xml_ns, id_entries, idref_entries);
2813 }
2814}
2815
2816/// The spill observer of a `--streaming` run with no math parsing: the spilled subtree's words, for the title-page
2817/// check (latexml_engine `base_utilities::frontmatter::title_page_check`).
2818fn observe_spilled_words(_document: &Document, node: &libxml::tree::Node) {
2819 latexml_engine::base_utilities::note_spilled_words(node);
2820}
2821
2822/// The spill observer of a `--streaming` run: the math parser's `d`-token evidence, then the spilled subtree's words.
2823fn observe_spilled_evidence_and_words(document: &Document, node: &libxml::tree::Node) {
2824 latexml_math_parser::read_differential_evidence(document, node);
2825 observe_spilled_words(document, node);
2826}
2827
2828#[cfg(test)]
2829mod tests {
2830 use super::{LATEXML_VERSION, parse_preload_spec, source_figures_are_postscript_only};
2831
2832 /// arXiv's latex+dvips cue (the K6 ruling, AutoTeX): figures that are PostScript only keep DVI output; a PDF/PNG
2833 /// figure beside them (2210.04612's MDPI `logo-*.eps` beside PNG figures), a PDF/PNG-only source and a literal (no
2834 /// directory) take PDF output.
2835 #[test]
2836 fn postscript_figures_select_dvi_output() {
2837 let dir = tempfile::tempdir().expect("tempdir");
2838 let root = dir.path();
2839 std::fs::write(root.join("paper.tex"), "x").expect("write");
2840 let root_str = root.to_str().expect("utf-8 path");
2841 assert!(!source_figures_are_postscript_only(root_str));
2842 std::fs::create_dir(root.join("figs")).expect("mkdir");
2843 std::fs::write(root.join("figs").join("plot.EPS"), "x").expect("write");
2844 assert!(source_figures_are_postscript_only(root_str));
2845 std::fs::write(root.join("fig.png"), "x").expect("write");
2846 assert!(!source_figures_are_postscript_only(root_str));
2847 assert!(!source_figures_are_postscript_only(""));
2848 }
2849
2850 fn opts(v: &[&str]) -> Vec<String> { v.iter().map(|s| s.to_string()).collect() }
2851
2852 /// #320: `LATEXML_VERSION` must be a bare `X.Y.Z` (three integer components,
2853 /// no `-rc`/pre-release) so BookML's version-gate parse works. Guards against a
2854 /// future "simplify to `env!(\"CARGO_PKG_VERSION\")`" that would re-add `-rc1`.
2855 #[test]
2856 fn latexml_version_is_bare_xyz() {
2857 let parts: Vec<&str> = LATEXML_VERSION.split('.').collect();
2858 assert_eq!(
2859 parts.len(),
2860 3,
2861 "LATEXML_VERSION must be X.Y.Z, got {LATEXML_VERSION:?}"
2862 );
2863 for p in &parts {
2864 assert!(
2865 !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()),
2866 "component {p:?} is not a bare integer in {LATEXML_VERSION:?}"
2867 );
2868 }
2869 }
2870
2871 #[test]
2872 fn preload_no_brackets_no_ext() {
2873 assert_eq!(
2874 parse_preload_spec("latexml"),
2875 ("latexml".into(), "sty".into(), opts(&[]))
2876 );
2877 }
2878
2879 #[test]
2880 fn preload_no_brackets_with_ext() {
2881 assert_eq!(
2882 parse_preload_spec("ar5iv.sty"),
2883 ("ar5iv".into(), "sty".into(), opts(&[]))
2884 );
2885 assert_eq!(
2886 parse_preload_spec("TeX.pool"),
2887 ("TeX".into(), "pool".into(), opts(&[]))
2888 );
2889 }
2890
2891 #[test]
2892 fn preload_front_brackets_with_options() {
2893 // The historical-bug fixture: front-bracket form must produce a real name.
2894 assert_eq!(
2895 parse_preload_spec("[ids,mathlexemes]latexml.sty"),
2896 (
2897 "latexml".into(),
2898 "sty".into(),
2899 opts(&["ids", "mathlexemes"])
2900 )
2901 );
2902 assert_eq!(
2903 parse_preload_spec("[dvipsnames]color.sty"),
2904 ("color".into(), "sty".into(), opts(&["dvipsnames"]))
2905 );
2906 }
2907
2908 #[test]
2909 fn preload_class_with_options() {
2910 assert_eq!(
2911 parse_preload_spec("[twocolumn,11pt]article.cls"),
2912 ("article".into(), "cls".into(), opts(&["twocolumn", "11pt"]))
2913 );
2914 }
2915
2916 #[test]
2917 fn preload_options_trimmed_and_empty_stripped() {
2918 assert_eq!(
2919 parse_preload_spec("[ a , b ,, c ]name.sty"),
2920 ("name".into(), "sty".into(), opts(&["a", "b", "c"]))
2921 );
2922 }
2923
2924 #[test]
2925 fn preload_empty_brackets() {
2926 assert_eq!(
2927 parse_preload_spec("[]name.sty"),
2928 ("name".into(), "sty".into(), opts(&[]))
2929 );
2930 }
2931
2932 #[test]
2933 fn preload_unmatched_bracket_falls_through() {
2934 // No closing `]` ⇒ treat the whole spec as the base, no options.
2935 assert_eq!(
2936 parse_preload_spec("[opt"),
2937 ("[opt".into(), "sty".into(), opts(&[]))
2938 );
2939 }
2940
2941 #[test]
2942 fn preload_dot_in_name_uses_last_segment_as_ext() {
2943 assert_eq!(
2944 parse_preload_spec("foo.bar.sty"),
2945 ("foo.bar".into(), "sty".into(), opts(&[]))
2946 );
2947 }
2948}