latexml/converter.rs
1#[cfg(feature = "runtime-bindings")]
2use std::sync::atomic::{AtomicBool, Ordering};
3use std::{rc::Rc, sync::LazyLock};
4
5use latexml_core::{
6 Core, CoreOptions, Debug, Error, Fatal, Info, Note, Warn,
7 common::{
8 BindingDispatcher, BindingSource, Config, DataSize, DigestionMode, OutputFormat, arena,
9 error::*, object::Object,
10 },
11 digested::Digested,
12 document::Document,
13 list::List,
14 report_mut, s,
15 state::{
16 self, add_binding_names, set_bindings_dispatch, source_map_enabled, source_table_snapshot,
17 },
18 telemetry::{self, Phase},
19 util::pathname,
20};
21use regex::Regex;
22
23use crate::core_interface::DigestionAPI;
24
25/// Where a runtime `.rhai` binding may be looked up — the two tiers differ in
26/// *cost* and in *authority*, so they sit at opposite ends of the dispatch
27/// chain (see [`install_binding_dispatch`]).
28#[cfg(feature = "runtime-bindings")]
29#[derive(Clone, Copy)]
30enum RhaiScope {
31 /// The local search paths only (source directory + `--path`) — a cheap
32 /// `pathname::find`, no kpsewhich. Checked FIRST, so a `.rhai` a user put
33 /// beside their document *overrides* a compiled binding of the same name.
34 LocalPaths,
35 /// Additionally the host TeX tree, via kpsewhich (`$TEXINPUTS`). Checked
36 /// LAST, only once every compiled dispatcher has declined (#345).
37 TeXTree,
38}
39
40/// The runtime `<request>.rhai` binding within `scope`, if there is one.
41#[cfg(feature = "runtime-bindings")]
42fn find_rhai_binding(request: &str, scope: RhaiScope) -> Option<String> {
43 use latexml_core::binding::content::{FindFileOptions, find_file};
44 find_file(
45 request,
46 Some(FindFileOptions {
47 // Append `.rhai`, so `foo.sty` resolves `foo.sty.rhai`.
48 ext_type: Some("rhai".into()),
49 // `TeXTree` lets the search fall through to kpsewhich, which is what
50 // honours `$TEXINPUTS` — so a `<pkg>.sty.rhai` distributed in a texmf
51 // tree is found by `\usepackage{pkg}` with no `--path` (#345). kpsewhich
52 // locates it fine (the extension is irrelevant to a `//` recursive
53 // search). This tier is deliberately NOT used for the first-priority
54 // probe: that one runs on EVERY package/class request (64 of them on a
55 // plain acmart paper), and a kpathsea miss is a directory-tree probe —
56 // or a full fork-exec on the subprocess-`kpsewhich` backend. The memo
57 // in `pathname::kpsewhich` is keyed by candidate name, so distinct
58 // package names never share a hit.
59 search_paths_only: matches!(scope, RhaiScope::LocalPaths),
60 ..FindFileOptions::default()
61 }),
62 )
63}
64
65/// Set by [`forbid_runtime_bindings`]: the chain then has no runtime tier.
66#[cfg(feature = "runtime-bindings")]
67static RUNTIME_BINDINGS_FORBIDDEN: AtomicBool = AtomicBool::new(false);
68
69/// Never load a runtime `.rhai` binding in this process: every binding chain installed after this call resolves as in
70/// a build without `runtime-bindings`. One-way and process-wide, for a front end converting untrusted sources
71/// (`cortex_worker`: a `<pkg>.sty.rhai` shipped in an arXiv source would otherwise load and run; SAFETY.md).
72pub fn forbid_runtime_bindings() {
73 #[cfg(feature = "runtime-bindings")]
74 RUNTIME_BINDINGS_FORBIDDEN.store(true, Ordering::Relaxed);
75}
76
77/// Resolve a runtime `<request>.rhai` binding within `scope` and load it if
78/// present. Returns `None` when no such file exists, so the caller falls
79/// through to the next tier of the chain.
80/// See `docs/parity/script_bindings_plan.md` §7.
81#[cfg(feature = "runtime-bindings")]
82fn rhai_dispatch(request: &str, scope: RhaiScope) -> Option<Result<BindingSource>> {
83 use latexml_core::state::record_opened_source;
84 let path = find_rhai_binding(request, scope)?;
85 // Pin the resolved `.rhai` in the opened-sources read-log. `load_file`
86 // below reads it with a raw `std::fs::read_to_string` (it is not opened
87 // through a `Mouth`, so `Mouth::create`'s `record_opened_source` never
88 // fires for it). Without this, an edited binding is invisible to the warm
89 // LSP preamble cache (`warmup_dep_snapshot` / `deps_still_current`) and the
90 // stale macros survive every reconversion. Recording the resolved path lets
91 // the cache invalidate on the file's mtime change.
92 record_opened_source(arena::pin(&path));
93 latexml_core::binding::content::name_loading_binding(&path);
94 // #560: report the resolved on-disk path as the load's `BindingSource`, so
95 // the "(Loading …)" note names the real `.rhai` file rather than the
96 // synthesized `<name>_sty.rs` compiled-module proxy name — more useful, and
97 // closer to Perl, which names the actual binding file.
98 Some(latexml_contrib::script_bindings::load_file(&path).map(|_| Some(path)))
99}
100
101/// The DVI drivers a class option can name (graphics.cfg / the `*.def` drivers that write DVI specials).
102const DVI_DRIVER_OPTIONS: [&str; 15] = [
103 "dvips",
104 "dvipdfm",
105 "dvipdfmx",
106 "dvisvgm",
107 "xdvi",
108 "dvipsone",
109 "dviwindo",
110 "emtex",
111 "dvitops",
112 "dvitoln03",
113 "pctexps",
114 "pctexwin",
115 "pctexhp",
116 "pctex32",
117 "truetex",
118];
119
120/// `text` as TeX reads its code: each line (ended by CR, LF or CRLF, as the Mouth splits them) up to its first `%`
121/// that an even run of backslashes precedes (`\%` is a character, `\\%` a control symbol then a comment), without the
122/// files its `filecontents` environments write (a shipped `.sty` ends with its own `\endinput`), up to the first
123/// `\endinput` control word (TeX reads no further of the file).
124fn uncommented_code(text: &str) -> String {
125 static FILECONTENTS: LazyLock<Regex> = LazyLock::new(|| {
126 Regex::new(r"(?s)\\begin\s*\{\s*filecontents\*?\s*\}.*?\\end\s*\{\s*filecontents\*?\s*\}")
127 .unwrap()
128 });
129 static ENDINPUT: LazyLock<Regex> =
130 LazyLock::new(|| Regex::new(r"\\endinput(?:[^A-Za-z@]|$)").unwrap());
131 let mut code = String::with_capacity(text.len());
132 for line in text.split(['\n', '\r']) {
133 let bytes = line.as_bytes();
134 let mut backslashes = 0;
135 let mut end = bytes.len();
136 for (i, &b) in bytes.iter().enumerate() {
137 match b {
138 b'\\' => backslashes += 1,
139 b'%' if backslashes % 2 == 0 => {
140 end = i;
141 break;
142 },
143 _ => backslashes = 0,
144 }
145 }
146 code.push_str(&line[..end]);
147 code.push('\n');
148 }
149 let mut code = FILECONTENTS.replace_all(&code, "").into_owned();
150 if let Some(at) = ENDINPUT.find(&code) {
151 code.truncate(at.start());
152 }
153 code
154}
155
156/// Whether `code` names a LaTeX document's cue: `\documentclass`, `\documentstyle` or `\begin{document}`, or a
157/// command plain TeX cannot run (`\usepackage`, `\RequirePackage`, `\include`).
158fn has_latex_cue(code: &str) -> bool {
159 static LATEX_CUE: LazyLock<Regex> = LazyLock::new(|| {
160 Regex::new(
161 r"\\document(?:class|style)|\\begin\s*\{\s*document\s*\}|\\(?:usepackage|RequirePackage|include)(?:[^A-Za-z@]|$)",
162 )
163 .unwrap()
164 });
165 LATEX_CUE.is_match(code)
166}
167
168/// The text of `path.tex` or, failing that, of `path` (TeX tries the `.tex` name first): a regular file of at most
169/// 4 MB, so a device or a FIFO named by an `\input` is never read. A confined conversion's pre-scan reads only what
170/// its roots admit, silently: the engine's own `\input` reports a refusal (OXIDIZED_DESIGN_DIVERGENCES #1183).
171fn read_source_file(path: &std::path::Path) -> Option<String> {
172 const MAX_SOURCE_BYTES: u64 = 4 * 1024 * 1024;
173 [
174 std::path::PathBuf::from(format!("{}.tex", path.display())),
175 path.to_path_buf(),
176 ]
177 .into_iter()
178 .find(|candidate| {
179 pathname::read_allowed(&candidate.to_string_lossy())
180 && std::fs::metadata(candidate).is_ok_and(|m| m.is_file() && m.len() <= MAX_SOURCE_BYTES)
181 })
182 .and_then(|candidate| std::fs::read(candidate).ok())
183 .map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
184}
185
186/// How arXiv's AutoTeX compiles a main file: with plain TeX or LaTeX (which format a session preloads), and to DVI
187/// (latex+dvips) or PDF (`\pdfoutput`, `core_interface::establish_pdf_output_mode`).
188#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
189pub struct CompileRoute {
190 /// A plain TeX document: latexml.sty's preload must not load the LaTeX format for it.
191 pub plain_tex: bool,
192 /// A latex+dvips document by its class options.
193 pub dvi: bool,
194 /// A pdflatex document by its class options (`pdftex`), or one whose text only PDF output reads
195 /// (`begins_document_in_pdf_branch`).
196 pub pdf: bool,
197 /// What the figures the source includes say of its output mode (`figure_output_cue`).
198 pub figures: state::FigureOutputCue,
199 /// The first line requests the AMS-TeX format, `%&amstex` (`requests_amstex_format`).
200 pub amstex: bool,
201}
202
203/// The [`CompileRoute`] of the main file `source` (a path, `.tex` resolved as the Mouth does, or `literal:` content).
204/// A LaTeX document names `\documentclass` or `\documentstyle` outside a comment
205/// (AutoTeX's tex-vs-latex test) or `\begin{document}` (a main file `\input`ting its preamble), in the main file or,
206/// when it names none, in a file it `\input`s or `\include`s (a wrapper naming its preamble and body). AMSTeX's own
207/// `\documentstyle{amsppt}` (after `\input amstex`) still counts as LaTeX, though Perl reads it plain: kept plain, 64
208/// sampled 1996-99 amsppt papers went 192 → 319 errors (math9806005 0 → TooManyErrors), AMSTeX's plain-mode gaps. The
209/// first `\documentclass`, its options naming a DVI driver, in a file setting no `\pdfoutput=1`, makes it a latex+dvips one:
210/// 0908.4150's `\documentclass[12pt,dvips]{article}` (stopped full-arXiv run 329), which pdflatex stops on with
211/// l3backend's "Backend request inconsistent with engine" for `dvips`, `dvipdfmx` and `dvisvgm` (expl3-code.tex's
212/// backend options) and whose specials it drops for the other graphics drivers. An unreadable source counts as
213/// LaTeX, PDF.
214fn compile_route(source: &str) -> CompileRoute {
215 static PDFOUTPUT_ONE: LazyLock<Regex> =
216 LazyLock::new(|| Regex::new(r"\\pdfoutput\s*=?\s*1(?:[^0-9]|$)").unwrap());
217 static INPUT: LazyLock<Regex> = LazyLock::new(|| {
218 Regex::new(r"\\(?:input|include)(?:\s*\{\s*([^}]+?)\s*\}|\s+([^\s{}\\]+))").unwrap()
219 });
220 static IFFALSE: LazyLock<Regex> =
221 LazyLock::new(|| Regex::new(r"(?s)\\iffalse\b.*?\\(?:else|fi)\b").unwrap());
222 // A followed file's class cue must be one in use, not a dual-mode test (`\ifx\documentclass\undefined`).
223 static CLASS_IN_USE: LazyLock<Regex> = LazyLock::new(|| {
224 Regex::new(r"\\document(?:class|style)\s*[\[{]|\\begin\s*\{\s*document\s*\}").unwrap()
225 });
226 const MAX_INPUT_DEPTH: usize = 3;
227 let (text, dir) = match source.strip_prefix("literal:") {
228 Some(content) => (content.to_string(), None),
229 None => {
230 let path = std::path::Path::new(source);
231 match read_source_file(path) {
232 Some(text) => (text, path.parent().map(std::path::Path::to_path_buf)),
233 None => return CompileRoute::default(),
234 }
235 },
236 };
237 let mut code = uncommented_code(&text);
238 let pdf_only = begins_document_in_pdf_branch(&code);
239 let figures = figure_output_cue(&code, dir.as_deref());
240 let mut latex = has_latex_cue(&code);
241 // A main file naming no class: the files it inputs (not in `\iffalse … \fi`), breadth first, a few levels deep,
242 // until one names the class; each using a LaTeX cue joins the main file's code for the DVI test.
243 if !code.contains("\\documentclass")
244 && let Some(dir) = dir
245 {
246 let mut visited = std::collections::HashSet::new();
247 let mut level = vec![IFFALSE.replace_all(&code, "").into_owned()];
248 'levels: for _ in 0..MAX_INPUT_DEPTH {
249 let mut next_level = Vec::new();
250 for parent in &level {
251 for captures in INPUT.captures_iter(parent) {
252 let Some(name) = captures.get(1).or_else(|| captures.get(2)) else {
253 continue;
254 };
255 // A name only TeX can resolve (`\input{\pre}`) may be the preamble: lean to LaTeX, the previous default. A `#`
256 // name is a macro's call-time argument (hep-ph9210212 `\def\inputrefs#1{…\input #1…}`, hep-th0703274
257 // `\input #1.aux`), no preamble: leaning to LaTeX there read a plain paper as LaTeX, whose locked `\chapter`
258 // refused its own (`\thechapter` undefined).
259 if name.as_str().contains('#') {
260 continue;
261 }
262 if name.as_str().contains('\\') {
263 latex = true;
264 continue;
265 }
266 if !visited.insert(name.as_str().to_string()) {
267 continue;
268 }
269 let Some(input) = read_source_file(&dir.join(name.as_str())) else {
270 continue;
271 };
272 let input_code = IFFALSE
273 .replace_all(&uncommented_code(&input), "")
274 .into_owned();
275 if CLASS_IN_USE.is_match(&input_code) {
276 latex = true;
277 code = format!("{code}\n{input_code}");
278 if input_code.contains("\\documentclass") {
279 break 'levels;
280 }
281 }
282 next_level.push(input_code);
283 }
284 }
285 level = next_level;
286 }
287 }
288 let class_option = |driver: &dyn Fn(&str) -> bool| {
289 code.find("\\documentclass").is_some_and(|at| {
290 let rest = code[at + "\\documentclass".len()..].trim_start();
291 rest
292 .strip_prefix('[')
293 .and_then(|r| r.split_once(']'))
294 .is_some_and(|(options, _)| options.split(',').any(|o| driver(o.trim())))
295 })
296 };
297 let dvi = !pdf_only
298 && !PDFOUTPUT_ONE.is_match(&code)
299 && class_option(&|o| DVI_DRIVER_OPTIONS.contains(&o));
300 // the `pdftex` driver option: a pdflatex document whatever PostScript it also ships (MDPI templates' `logo-*.eps`
301 // beside PNG figures, 2210.04612: expl3's backend check, expl3-code.tex:8036-8041, errs under DVI output)
302 let pdf = pdf_only || (!dvi && class_option(&|o| o == "pdftex"));
303 CompileRoute {
304 plain_tex: !latex,
305 dvi,
306 pdf,
307 figures,
308 amstex: requests_amstex_format(&text),
309 }
310}
311
312/// Whether the first line of `text` is a format request (web2c's `parse_first_line`, on for pdftex and etex in TeX
313/// Live's texmf.cnf) naming AMS-TeX's format, amstex.ini's `\input plain` then `\input amstex` (q-alg9501008:
314/// `%&amstex`, no `\input amstex`). pdftex reads the name after `%&` and any spaces or tabs up to the next space: `%& amstex`
315/// and `%&amstex -translate-file=cp227.tcx` load it; `%&AMSTeX`, `%&amstex,` and a tab after the name do not.
316fn requests_amstex_format(text: &str) -> bool {
317 let first_line = text.split(['\n', '\r']).next().unwrap_or_default();
318 first_line
319 .strip_prefix("%&")
320 .and_then(|request| request.trim_start_matches([' ', '\t']).split(' ').next())
321 == Some("amstex")
322}
323
324/// Whether the main file's code `code` opens `\begin{document}` inside the true branch of an `\ifpdf` (ifpdf.sty,
325/// iftex.sty) or IEEEtran's `\ifCLASSINFOpdf` that is still open there: DVI output skips the whole text, so the
326/// document is a pdflatex one whatever its figures say (DG 2026-11-23, OXIDIZED_DESIGN_DIVERGENCES #1154).
327/// 2105.10205 and 2502.09129 deleted the IEEEtran template's `\else…\fi` and name every figure `X.eps`; pdflatex
328/// ends them with "(\end occurred when \iftrue … incomplete)". Conservative: the switch stands at brace depth 0, not
329/// after a control word (`\newif\ifpdf`, `\let\ifpdf`), and no other conditional token (`\if…`, `\else`, `\or`,
330/// `\fi`) and no second `\begin{document}` follows it; 1012.0815's `\ifCLASSINFOpdf … \else` stays a DVI one.
331fn begins_document_in_pdf_branch(code: &str) -> bool {
332 static BEGIN_DOCUMENT: LazyLock<Regex> =
333 LazyLock::new(|| Regex::new(r"\\begin\s*\{\s*document\s*\}").unwrap());
334 static PDF_SWITCH: LazyLock<Regex> =
335 LazyLock::new(|| Regex::new(r"\\if(?:pdf|CLASSINFOpdf)(?:[^A-Za-z@]|$)").unwrap());
336 static CONDITIONAL: LazyLock<Regex> =
337 LazyLock::new(|| Regex::new(r"\\(?:if[A-Za-z@]*|unless|else|or|fi)(?:[^A-Za-z@]|$)").unwrap());
338 static AFTER_CONTROL_WORD: LazyLock<Regex> =
339 LazyLock::new(|| Regex::new(r"\\[A-Za-z@]+\s*$").unwrap());
340 let Some(begin) = BEGIN_DOCUMENT.find(code) else {
341 return false;
342 };
343 let preamble = &code[..begin.start()];
344 let Some(switch) = PDF_SWITCH.find_iter(preamble).last() else {
345 return false;
346 };
347 // The opener's own name ends where its delimiter starts.
348 let opened = &preamble[switch.start() + 1..];
349 let name_end = opened
350 .find(|c: char| !(c.is_ascii_alphabetic() || c == '@'))
351 .map_or(preamble.len(), |at| switch.start() + 1 + at);
352 // Braces outside control symbols (`\{` is a character).
353 let depth = |text: &str| {
354 let (mut depth, mut escaped) = (0i64, false);
355 for c in text.chars() {
356 match c {
357 _ if escaped => escaped = false,
358 '\\' => escaped = true,
359 '{' => depth += 1,
360 '}' => depth -= 1,
361 _ => {},
362 }
363 }
364 depth
365 };
366 depth(&preamble[..switch.start()]) == 0
367 && !AFTER_CONTROL_WORD.is_match(&preamble[..switch.start()])
368 && depth(&preamble[name_end..]) == 0
369 && !CONDITIONAL.is_match(&preamble[name_end..])
370 && !BEGIN_DOCUMENT.is_match(&code[begin.end()..])
371}
372
373/// The output mode the figures a source includes call for (the K6 ruling's figure cue, OXIDIZED_DESIGN_DIVERGENCES
374/// #537): the targets of `\includegraphics`, `\epsfig`/`\psfig`, `\epsfbox`/`\epsffile` and AASTeX's
375/// `\plotone`/`\plottwo` in the main file's code `main_code` and the files it inputs (not in `\iffalse … \fi`, a few
376/// levels deep), each resolved in the source directory `dir` and the `\graphicspath` directories, as the name stands
377/// and with the extensions pdfTeX and dvips try.
378/// - PDF: a figure that exists only as PDF/PNG/JPEG (latex+dvips cannot include it).
379/// - DVI: a pstricks load (pstricks draws with PostScript specials; pst-pdf, auto-pst-pdf and pdftricks are its
380/// pdflatex front ends), or every included figure resolved and each PostScript only — whatever epstopdf
381/// conversions (`<stem>-eps-converted-to.pdf`) or epstopdf load the source also carries: arXiv compiled 1806.00093,
382/// 1806.00188, 1806.00370, 1804.02991, 2104.01314, 1209.6096, 2210.10273 and 1701.08490 with latex+dvips (their
383/// PDFs' Producer is "dvips + GPL Ghostscript"), and 1806.00284 (Producer "GPL Ghostscript", Creator dvips(k)).
384/// - Otherwise undecided, and the tree's files decide: a figure that does not resolve (a name TeX builds at run time,
385/// `\figdir/a`, `#1`; a missing file), or one held in both forms.
386///
387/// A file the source never includes decides nothing: 1012.0815's EPS figures beside an IEEEtran manual PDF are a
388/// latex+dvips document whose `\ifCLASSINFOpdf` (unclosed) swallowed the whole text in PDF mode, and 1002.1751 loads
389/// pstricks only in its `\ifpdf` false branch, its tree's stale PDFs included by nothing.
390fn figure_output_cue(main_code: &str, dir: Option<&std::path::Path>) -> state::FigureOutputCue {
391 use state::FigureOutputCue;
392 static IFFALSE: LazyLock<Regex> =
393 LazyLock::new(|| Regex::new(r"(?s)\\iffalse\b.*?\\(?:else|fi)\b").unwrap());
394 static INPUT: LazyLock<Regex> = LazyLock::new(|| {
395 Regex::new(r"\\(?:input|include|subfile)(?:\s*\{\s*([^}]+?)\s*\}|\s+([^\s{}\\]+))").unwrap()
396 });
397 static FIGURE: LazyLock<Regex> = LazyLock::new(|| {
398 Regex::new(concat!(
399 r"\\includegraphics\*?\s*(?:<[^>]*>\s*)?(?:\[[^\]]*\]\s*){0,2}\{\s*([^}]+?)\s*\}",
400 r"|\\(?:epsfig|psfig)\s*\{[^}]*?\b(?:file|figure)\s*=\s*([^,}\s]+)",
401 r"|\\(?:epsfbox|epsffile)\s*(?:\[[^\]]*\]\s*)?\{\s*([^}]+?)\s*\}",
402 r"|\\plotone\s*\{\s*([^}]+?)\s*\}",
403 r"|\\plottwo\s*\{\s*([^}]+?)\s*\}\s*\{\s*([^}]+?)\s*\}",
404 ))
405 .unwrap()
406 });
407 static GRAPHICSPATH: LazyLock<Regex> =
408 LazyLock::new(|| Regex::new(r"\\graphicspath\s*\{((?:\s*\{[^{}]*\})+)\s*\}").unwrap());
409 static BRACED: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\{([^{}]*)\}").unwrap());
410 static PACKAGES: LazyLock<Regex> = LazyLock::new(|| {
411 Regex::new(r"\\(?:usepackage|RequirePackage)\s*(?:\[[^\]]*\]\s*)?\{([^}]*)\}|\\input\s*\{?\s*(pstricks)\b").unwrap()
412 });
413 const MAX_INPUT_DEPTH: usize = 4;
414 const MAX_FILES: usize = 200;
415 // A name TeX resolves at run time (`#1`, `\figdir`), or one outside the source tree (absolute, `..`), is not read.
416 let outside_the_tree = |name: &str| {
417 name.contains(['#', '\\']) || name.starts_with('/') || name.split('/').any(|part| part == "..")
418 };
419 const POSTSCRIPT: [&str; 6] = ["eps", "ps", "epsf", "epsi", "eps.gz", "ps.gz"];
420 const NOT_POSTSCRIPT: [&str; 4] = ["pdf", "png", "jpg", "jpeg"];
421 // The source's code: the main file's and that of the files it inputs, breadth first.
422 let mut codes = vec![IFFALSE.replace_all(main_code, "").into_owned()];
423 if let Some(dir) = dir {
424 let mut visited = std::collections::HashSet::new();
425 let mut level = 0..1;
426 for _ in 0..MAX_INPUT_DEPTH {
427 let mut names = Vec::new();
428 for code in &codes[level.clone()] {
429 for captures in INPUT.captures_iter(code) {
430 if let Some(name) = captures.get(1).or_else(|| captures.get(2)) {
431 names.push(name.as_str().to_string());
432 }
433 }
434 }
435 let start = codes.len();
436 for name in names {
437 if codes.len() >= MAX_FILES {
438 break;
439 }
440 if outside_the_tree(&name) || !visited.insert(name.clone()) {
441 continue;
442 }
443 if let Some(input) = read_source_file(&dir.join(&name)) {
444 codes.push(
445 IFFALSE
446 .replace_all(&uncommented_code(&input), "")
447 .into_owned(),
448 );
449 }
450 }
451 level = start..codes.len();
452 if level.is_empty() {
453 break;
454 }
455 }
456 }
457 let mut pstricks = false;
458 let mut pstricks_for_pdf = false;
459 for captures in codes.iter().flat_map(|code| PACKAGES.captures_iter(code)) {
460 if captures.get(2).is_some() {
461 pstricks = true;
462 }
463 for package in captures
464 .get(1)
465 .map_or("", |m| m.as_str())
466 .split(',')
467 .map(str::trim)
468 {
469 match package {
470 "pst-pdf" | "auto-pst-pdf" | "pdftricks" => pstricks_for_pdf = true,
471 _ if package == "pstricks" || package.starts_with("pst-") => pstricks = true,
472 _ => {},
473 }
474 }
475 }
476 // Every included figure, resolved: how many, how many PostScript only, and whether one did not resolve.
477 let (mut figures, mut postscript_only, mut unresolved) = (0usize, 0usize, false);
478 if let Some(dir) = dir {
479 let mut search = vec![dir.to_path_buf()];
480 for captures in codes
481 .iter()
482 .flat_map(|code| GRAPHICSPATH.captures_iter(code))
483 {
484 for path in BRACED.captures_iter(&captures[1]) {
485 let path = path[1].trim();
486 if !path.is_empty() && !outside_the_tree(path) {
487 search.push(dir.join(path));
488 }
489 }
490 }
491 let is_file = |name: &str| {
492 search.iter().any(|base| {
493 let path = base.join(name);
494 pathname::read_allowed(&path.to_string_lossy()) && path.is_file()
495 })
496 };
497 for captures in codes.iter().flat_map(|code| FIGURE.captures_iter(code)) {
498 for name in captures.iter().skip(1).flatten() {
499 let name = name.as_str().trim_matches('"');
500 if name.is_empty() {
501 continue;
502 }
503 if outside_the_tree(name) {
504 unresolved = true;
505 continue;
506 }
507 figures += 1;
508 let exists = |ext: &str| {
509 is_file(&format!("{name}.{ext}"))
510 || is_file(&format!("{name}.{}", ext.to_ascii_uppercase()))
511 };
512 let named = name.to_ascii_lowercase();
513 let named_ext = POSTSCRIPT
514 .iter()
515 .chain(NOT_POSTSCRIPT.iter())
516 .find(|ext| named.ends_with(&format!(".{ext}")));
517 let (ps, other) = match named_ext {
518 // A name with its extension is that file (graphicx, `\epsfbox`).
519 Some(ext) if is_file(name) => (POSTSCRIPT.contains(ext), NOT_POSTSCRIPT.contains(ext)),
520 Some(_) => (false, false),
521 None => (
522 POSTSCRIPT.iter().any(|ext| exists(ext)),
523 NOT_POSTSCRIPT.iter().any(|ext| exists(ext)),
524 ),
525 };
526 if other && !ps {
527 return FigureOutputCue::Pdf;
528 }
529 if ps && !other {
530 postscript_only += 1;
531 }
532 unresolved |= !ps && !other;
533 }
534 }
535 }
536 if (pstricks && !pstricks_for_pdf) || (figures > 0 && !unresolved && postscript_only == figures) {
537 FigureOutputCue::Dvi
538 } else {
539 FigureOutputCue::Undecided
540 }
541}
542
543/// Install the binding-resolution **priority chain** as the single dispatcher
544/// and register the `latexml_package` binding-name registry.
545///
546/// This is the one definition of binding-resolution policy, shared by
547/// [`Converter::initialize_session`] and the integration-test harness
548/// (`util::test::process_texfile`) — so a test exercises the *same* chain a real
549/// conversion does, and local `.rhai` fixtures are discovered identically.
550///
551/// Priority, highest first (installed in ONE slot, so call-site ordering can't
552/// reshuffle it):
553/// 1. a local `<request>.rhai` in the search paths — lets a user (or a test
554/// fixture next to its `.tex`) OVERRIDE any compiled binding of the same
555/// name (e.g. `article.cls.rhai` shadows `article_cls`). `runtime-bindings`
556/// only, and not after [`forbid_runtime_bindings`] (nor is tier 4).
557/// 2. the `extra` dispatcher (`latexml_contrib` for our binaries) — consulted
558/// before `latexml_package` to preserve the prior external-before-internal
559/// order; the two registries are disjoint, so the order is immaterial.
560/// Compiled `.rs` bindings keep precedence even under the raw-
561/// interpretation preloads (`rawstyles`/`rawclasses`) — user directive
562/// 2026-08-31 (perfect-kernel mission): raw mode governs what happens for
563/// names with NO binding (raw-load instead of the OmniBus fallback), it
564/// never demotes an existing binding.
565/// 3. `latexml_package` — core compiled engine bindings.
566/// 4. a `<request>.rhai` on the host TeX tree (`$TEXINPUTS`, via kpsewhich) —
567/// a binding *distributed* with a package, so it FILLS A GAP rather than
568/// overriding: `\usepackage{X}` finds `X.sty.rhai` in a texmf tree with no
569/// `--path` (#345), while a stray `amsmath.sty.rhai` left on that tree
570/// cannot silently displace the compiled `amsmath` binding. Last, so the
571/// kpathsea probe is paid only by requests nothing else could answer.
572/// `runtime-bindings` only.
573///
574/// Tier 1's binding is the only one loaded for its name, and is the file itself:
575/// what a compiled binding does as a stand-in for an author's file (reading the
576/// paper's shipped copy after it) does not follow it either, so the core asks
577/// tier 1 first ([`state::set_local_binding_finder`]; #947).
578pub(crate) fn install_binding_dispatch(extra: Option<BindingDispatcher>) {
579 #[cfg(feature = "runtime-bindings")]
580 let runtime_bindings = !RUNTIME_BINDINGS_FORBIDDEN.load(Ordering::Relaxed);
581 #[cfg(feature = "runtime-bindings")]
582 if runtime_bindings {
583 state::set_local_binding_finder(Rc::new(|request: &str| {
584 find_rhai_binding(request, RhaiScope::LocalPaths)
585 }));
586 }
587 set_bindings_dispatch(Rc::new(move |request: &str| {
588 #[cfg(feature = "runtime-bindings")]
589 if runtime_bindings && let Some(result) = rhai_dispatch(request, RhaiScope::LocalPaths) {
590 return Some(result);
591 }
592 // The compiled tiers (contrib `extra`, then `latexml_package`) load
593 // in-memory bindings with no source file, so they report `None` source.
594 if let Some(extra) = extra.as_ref()
595 && let Some(result) = extra(request)
596 {
597 return Some(result.map(|()| None));
598 }
599 if let Some(result) = latexml_package::dispatch(request) {
600 return Some(result.map(|()| None));
601 }
602 #[cfg(feature = "runtime-bindings")]
603 if runtime_bindings && let Some(result) = rhai_dispatch(request, RhaiScope::TeXTree) {
604 return Some(result);
605 }
606 None
607 }));
608 // Register every (name, ext) binding pair so `find_file(notex=true)` can
609 // resolve compile-time bindings across all extensions
610 // (.cls/.sty/.def/.pool/code.tex/...). This also feeds `load_class`'s
611 // Perl-parity prefix-match fallback (Package.pm L2702-2706) via the
612 // class-filtered `state::get_class_binding_names()` view. Source of
613 // truth: `latexml_package::BINDINGS`.
614 add_binding_names(latexml_package::binding_names());
615}
616
617/// Everything a fresh `Core` needs before its first `input_definitions`:
618/// the resolution chain above plus contrib's (name, ext) pairs. `Core::new`
619/// resets the State, which starts with NO dispatch, so every site that
620/// constructs an engine and loads pools must call this — the converter's
621/// `initialize_session` and the post-only recursive bibliography session
622/// (`bib_session::ensure_session`); omitting it there once left `TeX.pool`
623/// "missing" and every post-only bibliography empty.
624///
625/// contrib (memoir / siamltex / scrbook / etc.) is registered unconditionally
626/// because the canonical setup for both `latexml_oxide` and `cortex_worker`
627/// loads it — downstream embedders that replace the dispatchers can register
628/// their own (name, ext) slice the same way via `add_binding_names`.
629pub(crate) fn install_default_binding_chain(extra: Option<BindingDispatcher>) {
630 install_binding_dispatch(extra);
631 add_binding_names(latexml_contrib::binding_names());
632}
633
634/// Warns, in the conversion's log, that the format loaded from the engine's own definitions because
635/// no dump matching this TeX tree could be built (`format_dumps`): format loading precedes the log,
636/// so each conversion says so where its status is counted.
637pub fn note_format_build_failure() {
638 if let Some(reason) = latexml_engine::dump_paths::format_build_failure() {
639 Warn!(
640 "dump",
641 "build_failed",
642 s!(
643 "No format dump matches this TeX tree and none could be built ({reason}); the format was \
644 loaded from the engine's own definitions"
645 )
646 );
647 }
648}
649
650pub struct ConversionResponse {
651 pub result: Option<String>,
652 pub log: String,
653 pub status: String,
654 pub status_code: usize,
655 /// The file the core result was serialized into ([`Config::handoff_file`]); `result` is then `Some("")`.
656 pub handoff_file: Option<String>,
657}
658pub struct Runtime {
659 pub status: String,
660 pub status_code: usize,
661}
662pub struct Converter {
663 runtime: Runtime,
664 ready: bool,
665 opts: Config,
666 core: Core,
667 /// How arXiv compiles the main source ([`Converter::note_main_source`]); a session applies it before its preloads,
668 /// and a converter never told its source is a LaTeX, PDF one.
669 compile_route: CompileRoute,
670 /// The session's own log (its preloads), which the next conversion's log opens with (Perl's `$$self{log}`,
671 /// LaTeXML.pm:98-137, 154).
672 session_log: String,
673}
674
675impl Converter {
676 pub fn from_config(opts: Config) -> Converter {
677 // Every field named (no `..Default`): a new option fails to compile until it is wired.
678 let core = Core::new(CoreOptions {
679 model: None,
680 verbosity: Some(opts.verbosity),
681 include_comments: opts.include_comments.or(Some(false)),
682 strict: opts.strict,
683 include_styles: opts.include_styles,
684 preload: opts.preload.clone(),
685 search_paths: opts.search_paths.clone(),
686 nomathparse: opts.nomathparse,
687 source_map: opts.source_map,
688 // Perl Core.pm L60-61: seed State PERL_INPUT_ENCODING from --inputencoding
689 // (the Mouth reads it per-line to decode source bytes). `None` ⇒ utf-8.
690 input_encoding: opts.inputencoding.clone(),
691 documentid: opts.documentid.clone(),
692 graphics_paths: None,
693 });
694 Converter {
695 runtime: Runtime {
696 status: String::new(),
697 status_code: 3,
698 },
699 ready: false,
700 opts,
701 core,
702 compile_route: CompileRoute::default(),
703 session_log: String::new(),
704 }
705 }
706
707 /// Records, before a session's preloads load, whether `source` (a path or `literal:` content) is a plain TeX
708 /// document: arXiv AutoTeX's tex-vs-latex test (`compile_route`'s cues). latexml.sty's preload registers an
709 /// `\AddToHook`, which autoloads the LaTeX format; for a plain document that rebound `\end`, so the document's own
710 /// `\end` raised "`\endgroup` Attempt to close a group that switched to mode vertical" (stopped full-arXiv run 329:
711 /// 27 of 16,333 papers, 0911.4241, 1001.3079, hep-th9310069), and pstricks.tex took its LaTeX branch (repro
712 /// loader/latexml_preload_keeps_plain.tex). A LaTeX document keeps the format at preload time, pdflatex's order.
713 /// Also records a DVI driver class option. Every caller that prepares a session first tells it its source; a
714 /// streaming restart or a supplement is a converter of its own and is told again.
715 pub fn note_main_source(&mut self, source: &str) { self.compile_route = compile_route(source); }
716 /// Prepare the session, logging it (a failing `--preload`, the dump loads) into the session log, as Perl's
717 /// `initialize_session` binds the log first (LaTeXML.pm:98).
718 pub fn initialize_session(&mut self) -> Result<()> {
719 self.bind_log();
720 let result = self.initialize_session_logged();
721 let log = self.flush_log();
722 self.session_log.push_str(&log);
723 result
724 }
725
726 fn initialize_session_logged(&mut self) -> Result<()> {
727 // Per-conversion thread-local state owned by engine & package crates
728 // (the core's is `latexml_core::reset_conversion_state`, run by
729 // `initialize_singletons`): resets frontmatter/title-page/pdftex/lua/
730 // bibtex/splice/siunitx caches and the contrib closure-macro names so persistent workers never leak across papers.
731 latexml_engine::reset_conversion_state();
732 latexml_package::reset_conversion_state();
733 latexml_contrib::reset_conversion_state();
734 // The main source's kind, for the preloads below and the document's PDF mode
735 // (`core_interface::establish_pdf_output_mode`).
736 state::set_plain_tex_document(self.compile_route.plain_tex);
737 state::set_dvi_driver_option(self.compile_route.dvi);
738 state::set_pdf_driver_option(self.compile_route.pdf);
739 state::set_figure_output_cue(self.compile_route.figures);
740 // The source bundle's date, ar5iv's archival clock — reset every session, so a persistent worker thread never
741 // carries one paper's date into the next.
742 state::set_source_date_epoch(self.opts.source_date_epoch);
743 // The front ends' runaway limits, before the preloads so a latexml.sty option overrides them (OD #1080).
744 if let Some(limit) = self.opts.if_limit {
745 state::set_if_limit(limit);
746 }
747 if let Some(limit) = self.opts.absorb_limit {
748 state::set_absorb_limit(limit);
749 }
750 // Install the binding-resolution priority chain (rhai > contrib > package)
751 // — the single source of resolution policy, shared with the integration-test
752 // harness via `install_binding_dispatch`.
753 install_default_binding_chain(self.opts.extra_bindings_dispatch.clone());
754 // Prepare LaTeXML object — load mode-specific pool + user preloads.
755 // Perl: $self->initializeState($mode.".pool", @{$$self{preload} || []})
756 // For `--bibtex` (mode = BibTeX), Perl `Common/Config.pm:406`
757 // unshifts ['TeX.pool', 'LaTeX.pool', 'BibTeX.pool'] into the preload
758 // list. `BibTeX.pool` already begins with `LoadPool('LaTeX')` (and
759 // LaTeX with TeX), so we only need the BibTeX entry — the transitive
760 // chain handles the rest, and pool loads are idempotent.
761 // The format's dump must be built from the TeX tree this process reads packages from; one is
762 // built when none is (`format_dumps`), before the first format loads.
763 crate::format_dumps::ensure_format_dumps();
764 let mut preloads = match self.opts.mode {
765 Some(DigestionMode::BibTeX) => vec![s!("TeX.pool"), s!("BibTeX.pool")],
766 _ => vec![s!("TeX.pool")],
767 };
768 preloads.extend(self.core.preload.iter().cloned());
769 self.core.initialize_singletons(preloads)?;
770 // A first line `%&amstex` makes TeX start from the AMS-TeX format: the document reads as one beginning with
771 // `\input amstex` (`digest_setup`). Perl reads the line as a comment (OD #1194).
772 if self.compile_route.amstex {
773 Info!(
774 "format",
775 "amstex",
776 "The first line `%&amstex` requests the AMS-TeX format: inputting amstex"
777 );
778 }
779 state::assign_value(
780 "lx@format@amstex",
781 self.compile_route.amstex,
782 Some(state::Scope::Global),
783 );
784 // Warm libkpathsea's per-format lazy-init tables before the first file
785 // lookup, matching the CLI binaries (`latexml_oxide.rs` / `cortex_worker.rs`
786 // spawn this at startup). The library entry — tests via the trip harness,
787 // `latexml::api`, and downstream embedders — otherwise skips that prewarm,
788 // so libkpathsea's lazy `kpathsea_init_format` runs *during* the first
789 // lookups. When many conversion threads share the one process-global
790 // kpathsea handle under load (e.g. `cargo test --tests`), that mid-flight
791 // lazy init can transiently mis-resolve a support file → a spurious, flaky
792 // "1 warning". Running it inline here guarantees the tables are complete
793 // before `convert()` looks anything up, on every thread. Idempotent and a
794 // fast no-op once warm; single-process/single-thread runs (the CLI, the
795 // one-conversion-per-process cortex fleet) are unaffected. Honours the
796 // CLI's `LATEXML_NO_KPATHSEA_PREWARM` benchmarking opt-out.
797 if std::env::var_os("LATEXML_NO_KPATHSEA_PREWARM").is_none() {
798 pathname::prewarm_kpathsea();
799 }
800 // Record which file-resolution backend this process resolved, so every log
801 // carries it. A dead or degraded kpathsea is otherwise invisible — it looks
802 // exactly like a document referencing files that do not exist — and issue
803 // #304 cost days for want of this one line in the reporter's log.
804 let (backend, why) = pathname::kpathsea_backend();
805 Info!("kpathsea", "backend", s!("{} ({why})", backend.as_str()));
806 for root in pathname::trimmed_texmf_roots() {
807 let (var, given, used) = (root.var, &root.given, &root.used);
808 Info!("kpathsea", "texmf_root", s!("{var}={given} read as {used}"));
809 }
810 self.ready = true;
811 Ok(())
812 }
813
814 pub fn bind_log(&mut self) { latexml_core::util::logger::bind_log(); }
815 /// Open the bound log with the session's log (once: a persistent converter's later conversions start clean);
816 /// the cortex log mirror took it as it was logged.
817 fn take_session_log(&mut self) {
818 let log = std::mem::take(&mut self.session_log);
819 if !log.trim().is_empty() {
820 latexml_core::util::logger::append_logged_text(&format!("{}\n", log.trim_end()));
821 }
822 }
823 pub fn flush_log(&mut self) -> String { latexml_core::util::logger::flush_log() }
824
825 pub fn convert(mut self, source: String) -> ConversionResponse {
826 // This conversion's count of overflow interns starts at zero (`finish_response` reports it).
827 arena::take_overflow_interns();
828 // 1 Prepare for conversion
829 // 1.1 Initialize session if needed:
830 if !self.ready {
831 self.note_main_source(&source);
832 let _g_bootstrap = telemetry::phase(Phase::Bootstrap);
833 if let Err(e) = self.initialize_session() {
834 // We can't initialize, return error (in the log, after the session's):
835 self.bind_log();
836 self.take_session_log();
837 e.log_fatal();
838 self.session_log = self.flush_log();
839 }
840 drop(_g_bootstrap);
841 if !self.ready {
842 return ConversionResponse {
843 result: None,
844 log: std::mem::take(&mut self.session_log),
845 status: s!("Initialization failed."),
846 status_code: 3,
847 handoff_file: None,
848 };
849 }
850 }
851
852 self.bind_log();
853 self.take_session_log();
854 // 1.2 Inform of identity, increase conversion counter. Perl `bin/latexml`
855 // L83 logs `Note("$LaTeXML::IDENTITY processing $source")` UNCONDITIONALLY;
856 // our banner adds the executable name, git revision and exact start time
857 // (`identity.rs`). `Note!` itself does the log-always / stderr-gated split, so
858 // the banner reaches `.latexml.log` even under `--quiet` (issue #763) while
859 // still being muted on the console — no verbosity guard here.
860 Note!(crate::identity::identity_banner());
861 note_format_build_failure();
862 // info!( "invoked as [$0 " . join(' ', @ARGV) . "]\n" if $$opts{verbosity} >= 1;
863
864 // 1.3 Prepare for What's IN:
865 // - We use a new temporary variable to avoid confusion with daemon caching
866 // - Math needs to magically trigger math mode if needed
867 // - Fragments need to have a default pre- and postamble, if none provided
868 // Perl LaTeXML.pm:165-172 keys BOTH ambles on `whatsin`; see
869 // `resolve_amble`. (The previous inline code keyed the postamble on
870 // `whatsout`, dropping `\end{document}` / `\ensuremathpreceeds` for
871 // fragment/math inputs.)
872 let (current_preamble, current_postamble) = resolve_amble(
873 &self.opts.whatsin,
874 &self.opts.preamble,
875 &self.opts.postamble,
876 );
877 // TODO:
878 // 1.3.3 Archives need to get unpacked in a sandbox (with sufficient bookkeeping)
879 // elsif ($$opts{whatsin} =~ /^archive/) {
880 // // Sandbox the input
881 // $$opts{archive_sourcedirectory} = $$opts{sourcedirectory};
882 // my $sandbox_directory = File::Temp->newdir(TMPDIR => 1);
883 // $$opts{sourcedirectory} = $sandbox_directory;
884 // // Extract the archive in the sandbox
885 // $source = unpack_source($source, $sandbox_directory);
886 // if (!defined $source) { // Unpacking failed to find a source
887 // $$opts{sourcedirectory} = $$opts{archive_sourcedirectory};
888 // my $log = $self->flush_log;
889 // return { result => undef, log => $log, status => "Fatal:IO:Archive Can't detect a
890 // source TeX file!", status_code => 3 }; } // Destination magic: If we expect an archive
891 // on output, we need to invent the appropriate destination ourselves when not given.
892 // // Since the LaTeXML API never writes the final archive file to disk, we just use a pretend
893 // sourcename.zip: if (($$opts{whatsout} =~ /^archive/) && (!$$opts{destination})) {
894 // $$opts{placeholder_destination} = 1;
895 // $$opts{destination} = pathname_name($source) . ".zip"; } }
896
897 // 1.4's sandbox (and EPUB's OPS/) is the latexml_oxide binary's archive output (issue 807).
898 // // 1.4 Prepare for What's OUT (if we need a sandbox)
899 // if ($$opts{whatsout} =~ /^archive/) {
900 // $$opts{archive_sitedirectory} = $$opts{sitedirectory};
901 // $$opts{archive_destination} = $$opts{destination};
902 // my $destination_name = $$opts{destination} ? pathname_name($$opts{destination}) :
903 // 'document'; my $sandbox_directory = File::Temp->newdir(TMPDIR => 1);
904 // my $extension = $$opts{format};
905 // $extension =~ s/\d+$//;
906 // $extension =~ s/^epub|mobi$/xhtml/;
907 // my $sandbox_destination = "$destination_name.$extension";
908 // $$opts{sitedirectory} = $sandbox_directory;
909
910 // if ($$opts{format} eq 'epub') {
911 // $$opts{resource_directory} = File::Spec->catdir($sandbox_directory, 'OPS');
912 // $$opts{destination} = pathname_concat(File::Spec->catdir($sandbox_directory, 'OPS'),
913 // $sandbox_destination); } else {
914 // $$opts{destination} = pathname_concat($sandbox_directory, $sandbox_destination); }
915 // }
916
917 // 1.5 Prepare a daemon frame
918 // ...
919
920 // 2 Beginning Core conversion - digest the source:
921 // my ($digested, $dom, $serialized) = (undef, undef, undef);
922 // Should be this, but is overridden by withState.
923 // local $SIG{'ALRM'} = sub { LaTeXML::Common::Error::Fatal('conversion','timeout',
924 // "Conversion timed out after " . $$opts{timeout} . " seconds!\n"); };
925 // alarm($$opts{timeout});
926 // my $mode = ($$opts{type} eq 'auto') ? 'TeX' : $$opts{type};
927 // Streaming (fragmented) conversion: digest and build interleave inside
928 // `convert_streaming`, so the eager digest-then-build sequence below does
929 // not apply. TeX/Box outputs revert to eager — they serialize the DIGESTED
930 // list and never build a DOM, so there is nothing to fragment.
931 if let Some(budget) = self.opts.streaming
932 && !matches!(self.opts.format, OutputFormat::TeX | OutputFormat::Box)
933 {
934 let dom_result = {
935 let _g = telemetry::phase(Phase::Build);
936 self.core.convert_streaming(
937 source,
938 current_preamble,
939 current_postamble,
940 self.opts.mode.clone(),
941 budget,
942 )
943 };
944 let serialized = match dom_result {
945 Ok(dom) => {
946 note_rootless_document(&dom);
947 let _g = telemetry::phase(Phase::Serialize);
948 self.serialize_result(&dom)
949 },
950 Err(e) => {
951 // Same resource-fatal surfacing as the eager DOM arm below.
952 if matches!(e.category, ErrorCategory::StreamingRestart) {
953 // Not a failure: the CLI reruns this document under --streaming
954 // (the watermark crossed during the build; the digest arm above
955 // handles the common digestion crossing).
956 emit_info("streaming", "restart_watermark", &e.message);
957 } else if matches!(e.target, ErrorTarget::Timeout) {
958 e.log_fatal();
959 } else {
960 let message = s!("{:?}", e);
961 let err = || {
962 Error!("document", "convert", message);
963 Ok(())
964 };
965 err().ok();
966 }
967 (String::new(), None)
968 },
969 };
970 // The SHARED tail, not a hand-copy of parts of it: this arm used to
971 // reproduce only the verdict fold and silently skip the rest — so a
972 // streamed run emitted no MARPA_ASF_STATS line (measured: the 131 MB
973 // witness under MARPA_ASF_STATS=1 produced zero stats), and a streamed
974 // `--source-map` run emitted `data:sourcepos` tags with NO decoder
975 // table in the log. Streaming auto-activates on exactly the large
976 // documents where both matter.
977 return self.finish_response(serialized.0, serialized.1);
978 }
979
980 // Adaptive digestion (single pass): eager, until an RSS-driven yield seam
981 // says the process is over the spill watermark — then the accumulated
982 // bodies become streaming fragment 1 and digestion CONTINUES as pass 1,
983 // instead of the from-scratch `StreamingRestart` (kept as the no-seam
984 // fallback). A document that never crosses the watermark is built whole,
985 // exactly as before.
986 let digest_result = {
987 let _g = telemetry::phase(Phase::Digest);
988 self.core.digest_adaptive(
989 source,
990 current_preamble,
991 current_postamble,
992 self.opts.mode.clone(),
993 crate::streaming_restart::transition_budget(),
994 )
995 };
996 let digest_result = match digest_result {
997 Ok(crate::core_interface::AdaptiveOutcome::Streamed(dom)) => {
998 let dom = *dom;
999 note_rootless_document(&dom);
1000 // Pass 1 + pass 2 + finalize already ran; serialize like the
1001 // `--streaming` branch above.
1002 let (serialized, handoff_file) = {
1003 let _g = telemetry::phase(Phase::Serialize);
1004 self.serialize_result(&dom)
1005 };
1006 return self.finish_response(serialized, handoff_file);
1007 },
1008 Ok(crate::core_interface::AdaptiveOutcome::Eager(d)) => Ok(d),
1009 Err(e) => Err(e),
1010 };
1011 let digested = match digest_result {
1012 Err(e) if matches!(e.category, ErrorCategory::StreamingRestart) => {
1013 // Not a failure: eager digestion stopped at the streaming-restart
1014 // watermark and the CLI reruns this document under --streaming. No
1015 // salvage (that would digest on), no Fatal line, no status change.
1016 emit_info("streaming", "restart_watermark", &e.message);
1017 return self.finish_response(String::new(), None);
1018 },
1019 Err(e) => {
1020 report_mut!().status_code = 3;
1021 e.log_fatal();
1022 // Perl L251-259: If digestion failed, try finishDigestion to salvage
1023 // whatever was partially consumed. This allows partial recovery where
1024 // the beginning of the document is valid but an error occurs midway.
1025 match self.core.digest_internal() {
1026 Ok(salvaged) if !salvaged.is_empty().unwrap_or(true) => {
1027 Info!(
1028 "recovery",
1029 "digest",
1030 "Salvaged partial output after fatal error"
1031 );
1032 salvaged
1033 },
1034 _ => Digested::from(List::new(Vec::new())),
1035 }
1036 },
1037 Ok(d) => d,
1038 };
1039 // 2.1 Now, convert to DOM and output, if desired.
1040 let dom_result: Result<Document>;
1041 let mut handoff_file = None;
1042 let serialized = match self.opts.format {
1043 OutputFormat::TeX => {
1044 let untex_result = { digested.untex() };
1045 match untex_result {
1046 Ok(tex) => tex,
1047 Err(e) => {
1048 return ConversionResponse {
1049 result: None,
1050 log: self.flush_log(),
1051 status: s!("fatal:untex:{:?}", e),
1052 status_code: 3,
1053 handoff_file: None,
1054 };
1055 },
1056 }
1057 },
1058 OutputFormat::Box => {
1059 if self.opts.verbosity > 0 {
1060 digested.stringify()
1061 } else {
1062 digested.to_string()
1063 }
1064 },
1065 _ => {
1066 dom_result = {
1067 let _g = telemetry::phase(Phase::Build);
1068 self.core.convert_document(digested)
1069 };
1070 match dom_result {
1071 Ok(dom) => {
1072 note_rootless_document(&dom);
1073 let _g = telemetry::phase(Phase::Serialize);
1074 let serialized;
1075 (serialized, handoff_file) = self.serialize_result(&dom);
1076 serialized
1077 },
1078 Err(e) => {
1079 // A resource fatal (Timeout target — e.g. a cycle-guard abort
1080 // propagated out of math parsing, P1-4) must surface as the
1081 // standard `Fatal:` log line, not a generic document error;
1082 // otherwise the summary counts a fatal the log never shows.
1083 if matches!(e.category, ErrorCategory::StreamingRestart) {
1084 // Not a failure: the CLI reruns this document under --streaming.
1085 emit_info("streaming", "restart_watermark", &e.message);
1086 } else if matches!(e.target, ErrorTarget::Timeout) {
1087 e.log_fatal();
1088 } else {
1089 let message = s!("{:?}", e);
1090 let err = || {
1091 Error!("document", "convert", message);
1092 Ok(())
1093 };
1094 err().ok();
1095 }
1096 String::new()
1097 },
1098 }
1099 },
1100 };
1101
1102 self.runtime.status = get_status_message();
1103 self.runtime.status_code = get_status_code();
1104 // alarm(0)
1105
1106 // 2.2 Bookkeeping in case fatal errors occurred
1107 // ...
1108
1109 // 2.3 Clean up and exit if we only wanted the serialization of the core conversion
1110 // if ($serialized) {
1111 // // If serialized has been set, we are done with the job
1112 // // If we just processed an archive, clean up sandbox directory.
1113 // if ($$opts{whatsin} =~ /^archive/) {
1114 // rmtree($$opts{sourcedirectory});
1115 // $$opts{sourcedirectory} = $$opts{archive_sourcedirectory}; }
1116 // my $log = $self->flush_log;
1117 // return { result => $serialized, log => $log, status => $$runtime{status}, status_code =>
1118 // $$runtime{status_code} }; }
1119
1120 // 3 If desired, post-process
1121 // my $result = $dom;
1122 // if ($$opts{post} && $dom && $dom->documentElement) {
1123 // my $post_eval_return = eval {
1124 // local $SIG{'ALRM'} = sub { die "alarm\n" };
1125 // alarm($$opts{timeout});
1126 // $result = $self->convert_post($dom);
1127 // alarm(0);
1128 // 1;
1129 // };
1130 // // 3.1 Bookkeeping if a post-processing Fatal error occurred
1131 // //// $$latexml{state}->noteStatus('fatal') if $latexml && $@; // Fatal Error?
1132 // local $@ = 'Fatal:conversion:unknown Post-processing failed! (Unknown Reason)'
1133 // if ((!$post_eval_return) && (!$@));
1134 // if ($@) { //Fatal occured!
1135 // $$runtime{status_code} = 3;
1136 // $@ = 'Fatal:conversion:unknown '.$@ unless $@ =~ /^Fatal:/;
1137 // error!($@);
1138 // //Since this is postprocessing, we don't need to do anything
1139 // // just avoid crashing...
1140 // $result = undef; } }
1141
1142 // // 4 Clean-up: undo everything we sandboxed
1143 // if ($$opts{whatsin} =~ /^archive/) {
1144 // rmtree($$opts{sourcedirectory});
1145 // $$opts{sourcedirectory} = $$opts{archive_sourcedirectory}; }
1146 // if ($$opts{whatsout} =~ /^archive/) {
1147 // rmtree($$opts{sitedirectory});
1148 // $$opts{sitedirectory} = $$opts{archive_sitedirectory};
1149 // $$opts{destination} = $$opts{archive_destination};
1150 // if (delete $$opts{placeholder_destination}) {
1151 // delete $$opts{destination}; } }
1152
1153 // // 5 Output
1154 // // 5.1 Serialize the XML/HTML result (or just return the Perl object, if requested)
1155 // undef $serialized;
1156 // if ((defined $result) && ref($result) && (ref($result) =~ /^(:?LaTe)?XML/)) {
1157 // if (($$opts{format} =~ 'x(ht)?ml') || ($$opts{format} eq 'jats')) {
1158 // $serialized = $result->to_string(1); }
1159 // elsif ($$opts{format} =~ /^html/) {
1160 // if (ref($result) =~ '^LaTeXML::(Post::)?Document$') { // Special for documents
1161 // $serialized = $result->getDocument->to_stringHTML; }
1162 // else { // Regular for fragments
1163 // do {
1164 // local $XML::LibXML::setTagCompression = 1;
1165 // $serialized = $result->to_string(1);
1166 // } } }
1167 // elsif ($$opts{format} eq 'dom') {
1168 // $serialized = $result; } }
1169 // else { $serialized = $result; } // Compressed case
1170
1171 // 5.2 Finalize logging and return a response containing the document result, log and status
1172 self.finish_response(serialized, handoff_file)
1173 }
1174
1175 /// The core result as a `String`, or (with [`Config::handoff_file`]) written to that file: `("", Some(path))`.
1176 /// A failed write is reported at Info, as post's own staging failure is, and the result falls back to the
1177 /// `String`, which post then stages itself or parses from memory.
1178 fn serialize_result(&self, dom: &Document) -> (String, Option<String>) {
1179 let Some(path) = self.opts.handoff_file.as_deref() else {
1180 return (dom.serialize_to_string(), None);
1181 };
1182 // The destination's directory may not exist yet (the page writer creates it later).
1183 let written = std::path::Path::new(path)
1184 .parent()
1185 .filter(|dir| !dir.as_os_str().is_empty())
1186 .map_or(Ok(()), std::fs::create_dir_all)
1187 .and_then(|()| dom.serialize_to_file(std::path::Path::new(path)));
1188 match written {
1189 Ok(_) => (String::new(), Some(path.to_string())),
1190 Err(e) => {
1191 emit_info(
1192 "serialize",
1193 "handoff",
1194 &format!("could not serialize the core result to {path} ({e}); serializing in memory"),
1195 );
1196 (dom.serialize_to_string(), None)
1197 },
1198 }
1199 }
1200
1201 /// The SHARED conversion tail: instrumentation flush (ASF stats, the
1202 /// `--source-map` decoder table), the Perl-faithful completion `Note!`, and
1203 /// response assembly. Every arm of `convert` must end here — the streaming
1204 /// arm used to return early with a hand-copy of the verdict fold alone,
1205 /// silently skipping the rest (no `MARPA_ASF_STATS` line, and a streamed
1206 /// `--source-map` run emitted `data:sourcepos` tags with no decoder ring).
1207 ///
1208 /// Recomputes `status`/`status_code` (idempotent reads of the REPORT
1209 /// counters), so diagnostics raised during serialization itself still reach
1210 /// the reported verdict — the streaming arm always did this; the eager path
1211 /// previously froze status before serializing.
1212 fn finish_response(
1213 &mut self,
1214 serialized: String,
1215 handoff_file: Option<String>,
1216 ) -> ConversionResponse {
1217 self.runtime.status = get_status_message();
1218 self.runtime.status_code = get_status_code();
1219 // (taken at every conversion's start too, so a count never carries over; a Debug line, as every document has one)
1220 let lent_interns = arena::take_overflow_interns();
1221 if self.opts.verbosity >= 0 {
1222 Debug!("arena", "strings_allocated", arena::len());
1223 Debug!(
1224 "arena",
1225 "overflow",
1226 s!("{lent_interns} strings interned while a text was lent went to the overflow page")
1227 );
1228 // Final token-read progress: the calibration basis for `token_limit`
1229 // and `CYCLE_GUARD_ACTIVATE` (the read-checkpoint accounting changed
1230 // in PR #249 — read_x_token/read_balanced now count too — so limits
1231 // must be recalibrated against THIS metric, not historical figures).
1232 Debug!("gullet", "progress", latexml_core::gullet::token_progress());
1233 }
1234 // MARPA_ASF_STATS=1: emit ASF instrumentation counters once
1235 // per converted document. Codex instrumentation plan, see
1236 // marpa/docs/ASF_PERFORMANCE_FINDINGS.md. The thread-local
1237 // accumulator is reset after the snapshot so per-document
1238 // figures are independent.
1239 latexml_math_parser::report_and_reset_asf_stats();
1240 // --source-map (#47/#92): serialise the `tag → file` decoder table into the
1241 // `.log` — latexml-oxide's existing conversion-metadata channel — rather than
1242 // inlining it into the output. The output carries only the anonymous integer
1243 // `tag` (in each `data:sourcepos`); this is its decoder ring, Source-Map-v3
1244 // `sources`-style (the array index *is* the tag). Keeping it out of the
1245 // HTML/XML keeps that output anonymisable: a consumer without the source
1246 // files sees only opaque tags. In-process embedders (e.g. the ar5iv-editor
1247 // server) read the same table programmatically via `source_table_snapshot()`.
1248 // Gated on the switch, so a normal conversion emits nothing.
1249 if source_map_enabled() {
1250 for (tag, sym) in source_table_snapshot().iter().enumerate() {
1251 arena::with(*sym, |src| {
1252 Info!("source-map", "source", s!("[{tag}] {src}"));
1253 });
1254 }
1255 }
1256 // Perl: Note("Conversion complete: " . $$runtime{status}); (LaTeXML.pm:315)
1257 // is reached only on success — a Fatal `die`s before it, and bin/latexml:127
1258 // then prints `"Conversion " . ($code == 3 ? 'failed' : 'complete')`. Rust
1259 // recovers from a Fatal (graceful degradation) instead of dying, so it reaches
1260 // this note even when status_code == 3; fold in bin/latexml's verdict here so
1261 // a fatal run reports "failed", never the self-contradictory "complete: N fatal
1262 // error". Success cases (status_code < 3) stay byte-identical.
1263 Note!(s!("{}", conversion_verdict(self.runtime.status_code)));
1264 // The panic-log guard's trigger (`cluster_cli`): a panic with the core's log still unflushed.
1265 #[cfg(any(debug_assertions, feature = "test-utils"))]
1266 if std::env::var_os("LATEXML_INJECT_PANIC").is_some_and(|at| at == "core_end") {
1267 panic!("LATEXML_INJECT_PANIC at the core's end");
1268 }
1269 let log = self.flush_log();
1270 // self->sanitize($log) if ($$runtime{status_code} == 3);
1271
1272 ConversionResponse {
1273 result: Some(serialized),
1274 log,
1275 status: self.runtime.status.clone(),
1276 status_code: self.runtime.status_code,
1277 handoff_file,
1278 }
1279 }
1280
1281 /// Convert in-memory `content` under the source name `name`, producing the
1282 /// HTML5-format core XML (the persistent server then post-processes it).
1283 /// Unlike [`Converter::convert`] (`literal:` → anonymous source), the source
1284 /// is *named*, so `--source-map` stamps its locators. Focused on the
1285 /// `Document`/HTML5 path the server uses — no amble wrapping, no TeX/Box
1286 /// output formats.
1287 pub fn convert_content_with_provenance(
1288 mut self,
1289 name: &str,
1290 content: String,
1291 ) -> ConversionResponse {
1292 // (no count carried in from an earlier conversion on this thread: see `convert`)
1293 arena::take_overflow_interns();
1294 // Load + digest through the shared top-level loader, so the source-context
1295 // setup is not duplicated here.
1296 let digested = match self.digest_content_with_provenance(name, content) {
1297 Ok(d) => d,
1298 Err(e) => {
1299 if !self.ready {
1300 return ConversionResponse {
1301 result: None,
1302 log: self.flush_log(),
1303 status: s!("Initialization failed."),
1304 status_code: 3,
1305 handoff_file: None,
1306 };
1307 }
1308 report_mut!().status_code = 3;
1309 e.log_fatal();
1310 // Salvage whatever digested before the error (mirrors `convert`).
1311 match self.core.digest_internal() {
1312 Ok(salvaged) if !salvaged.is_empty().unwrap_or(true) => salvaged,
1313 _ => Digested::from(List::new(Vec::new())),
1314 }
1315 },
1316 };
1317
1318 let serialized = {
1319 let _g = telemetry::phase(Phase::Build);
1320 match self.core.convert_document(digested) {
1321 Ok(dom) => {
1322 // No `note_rootless_document` here: this in-process entry is also
1323 // the editor's fallback for a fragment without `\begin{document}`
1324 // (lsp_server/server.rs), a legitimate transient state.
1325 let _g = telemetry::phase(Phase::Serialize);
1326 dom.serialize_to_string()
1327 },
1328 Err(e) => {
1329 // `Error!` expands into a `Result`-returning context; wrap it the
1330 // same way `convert` does so it composes in this `-> ConversionResponse` fn.
1331 // Timeout-target resource fatals get the standard `Fatal:` line
1332 // (see the sibling handler in `convert` — P1-4).
1333 if matches!(e.category, ErrorCategory::StreamingRestart) {
1334 // Not a failure: the CLI reruns this document under --streaming
1335 // (the watermark crossed during the build; the digest arm above
1336 // handles the common digestion crossing).
1337 emit_info("streaming", "restart_watermark", &e.message);
1338 } else if matches!(e.target, ErrorTarget::Timeout) {
1339 e.log_fatal();
1340 } else {
1341 let message = s!("{:?}", e);
1342 let err = || {
1343 Error!("document", "convert", message);
1344 Ok(())
1345 };
1346 err().ok();
1347 }
1348 String::new()
1349 },
1350 }
1351 };
1352
1353 // The verdict counts what building the document raised too — its own diagnostics, and the deferred ones replayed
1354 // once every reference is built (ruling 7e) — as `finish_response` recomputes it for `convert`; read after
1355 // digestion alone, a construction-time error left the status "No obvious problems".
1356 self.runtime.status = get_status_message();
1357 self.runtime.status_code = get_status_code();
1358 let log = self.flush_log();
1359 ConversionResponse {
1360 result: Some(serialized),
1361 log,
1362 status: self.runtime.status.clone(),
1363 status_code: self.runtime.status_code,
1364 handoff_file: None,
1365 }
1366 }
1367
1368 pub fn prepare_session<'preplifetime>(
1369 &'preplifetime mut self,
1370 _opts: &'preplifetime Config,
1371 ) -> Result<()> {
1372 if !self.ready {
1373 self.initialize_session()?
1374 }
1375 Ok(())
1376 }
1377
1378 /// Digest in-memory `content` as the **main document** named `name`, leaving
1379 /// the thread-local engine state **live**. Used by the persistent server to
1380 /// warm a preamble once (then resume body digestion in a fork child over the
1381 /// inherited state) and by [`Converter::convert_content_with_provenance`] for
1382 /// the in-process path.
1383 ///
1384 /// This is the in-memory twin of [`crate::core_interface::DigestionAPI::digest_file`]:
1385 /// same top-level spine — establish the source context, open the source,
1386 /// `digest_internal` — but the content is *supplied* rather than read from
1387 /// disk. It shares `core_interface::establish_source_context` with
1388 /// `digest_file` (so `SOURCEFILE`/`SOURCEDIRECTORY`/`SEARCHPATHS`/
1389 /// `GRAPHICSPATHS`/`\jobname` can't drift), making sibling
1390 /// `\usepackage`/`\input`/`\includegraphics` of local files resolve. The
1391 /// source is opened as a *named* mouth (not the anonymous `literal:`
1392 /// protocol) so locators carry `name` — the **provenance** that
1393 /// `--source-map` needs (`stamp_source_locator` only stamps
1394 /// `.tex`/`.ltx`/`.bbl`/`.bib` user sources). Initializes the session if
1395 /// needed; does not finalize a document.
1396 pub fn digest_content_with_provenance(
1397 &mut self,
1398 name: &str,
1399 content: String,
1400 ) -> Result<Digested> {
1401 if !self.ready {
1402 self.initialize_session()?;
1403 }
1404 self.bind_log();
1405 self.take_session_log();
1406 note_format_build_failure();
1407 // Top-level document load: establish the source context (SOURCEFILE,
1408 // SOURCEDIRECTORY, SEARCHPATHS, GRAPHICSPATHS, \jobname) so sibling
1409 // \usepackage/\input/\includegraphics of local files resolve. Shared with
1410 // `digest_file` via `establish_source_context` so the two can't drift.
1411 // (A continuation/nested mouth must NOT do this — see
1412 // `open_named_in_memory_mouth`.)
1413 let path = std::path::Path::new(name);
1414 let dir = path.parent().and_then(|p| p.to_str()).unwrap_or("");
1415 let jobname = path.file_stem().and_then(|s| s.to_str()).unwrap_or(name);
1416 crate::core_interface::establish_source_context(Some(name), jobname, dir);
1417 open_named_in_memory_mouth(name, content)?;
1418 self.core.digest_internal()
1419 }
1420}
1421
1422/// Open a gullet mouth over in-memory `content` whose source is named `name`
1423/// (a real path/filename). Uses the Mouth's cached-content branch so locators
1424/// carry `name` rather than "Anonymous String".
1425///
1426/// Low-level and *position-agnostic*: it does NOT touch the document-global
1427/// `SOURCEDIRECTORY`/`SEARCHPATHS`, so it is safe for a continuation (the
1428/// forked child's body over already-inherited state) or a nested include. For
1429/// the *main* document load, go through `Converter::digest_named`, which
1430/// installs the document directory first.
1431pub fn open_named_in_memory_mouth(name: &str, content: String) -> Result<()> {
1432 use latexml_core::{
1433 gullet,
1434 mouth::{Mouth, MouthOptions},
1435 };
1436 let mouth = Mouth::create(name, MouthOptions {
1437 notes: true,
1438 content: Some(content),
1439 ..MouthOptions::default()
1440 })?;
1441 gullet::open_mouth(mouth, true);
1442 Ok(())
1443}
1444
1445/// Resolve the `(preamble, postamble)` to wrap the source in, based on
1446/// the requested input chunk size. Faithful port of Perl `LaTeXML.pm`
1447/// L165-172 — note both ambles key on **`whatsin`** (not `whatsout`):
1448///
1449/// * `math` → `\begin{document}\ensuremathfollows` … `\ensuremathpreceeds\end{document}` (magic
1450/// math-mode trigger).
1451/// * `fragment` → the caller-supplied `preamble`/`postamble`, defaulting to `standard_preamble.tex`
1452/// / `standard_postamble.tex`.
1453/// * everything else (`document`, `archive`, …) → no wrapping.
1454pub(crate) fn resolve_amble(
1455 whatsin: &DataSize,
1456 preamble: &Option<String>,
1457 postamble: &Option<String>,
1458) -> (Option<String>, Option<String>) {
1459 match whatsin {
1460 DataSize::Math => (
1461 Some(s!("literal:\\begin{{document}}\\ensuremathfollows")),
1462 Some(s!("literal:\\ensuremathpreceeds\\end{{document}}")),
1463 ),
1464 DataSize::Fragment => (
1465 Some(
1466 preamble
1467 .clone()
1468 .unwrap_or_else(|| s!("standard_preamble.tex")),
1469 ),
1470 Some(
1471 postamble
1472 .clone()
1473 .unwrap_or_else(|| s!("standard_postamble.tex")),
1474 ),
1475 ),
1476 _ => (None, None),
1477 }
1478}
1479
1480/// A built document with no root element — `\begin{document}` was never
1481/// digested, typically because an unbalanced `\ifX` (an undefined conditional
1482/// auto-`\newif`ed to `\iffalse`) skipped it through EOF — is a FATAL, not
1483/// an output. Both engines write the bare XML declaration for it (Perl too:
1484/// xwatermark-guide), but reporting it as status 2 with "output" hid a whole-
1485/// document loss behind an `Error:expected:\fi` line (skeyval-pokayoke2,
1486/// thesis-sample, xwatermark-guide in sweeps s109/s110). The messages are the
1487/// success signal, so the loss is named here — on the full-document `convert`
1488/// path (CLI, corpus harness, cortex_worker); the editor's in-process
1489/// fragment fallback is exempt. `Fatal!` logs and latches the sticky fatal at
1490/// the raise; the `Err` is not needed — serialization of the empty document
1491/// proceeds as before. Only a LaTeX document — one whose `\documentclass`
1492/// loaded a class (`document_class_filename`) — has a `\begin{document}` to
1493/// miss: a source that is all comments (arXiv's `%auto-ignore` placeholders,
1494/// 53 papers of sandbox 2605, e.g. 2605.00131; 28 of 2606) or a plain-TeX
1495/// file that typesets nothing lost no content, and stays clean as in Perl.
1496/// Guards
1497/// `perfect_kernel_batch56::document_without_a_root_is_a_fatal`,
1498/// `perfect_kernel_batch56::comment_only_source_is_not_a_fatal`.
1499fn note_rootless_document(dom: &Document) {
1500 // A Fatal already on record (TooManyErrors, a resource fuse) explains the
1501 // loss; do not add a second line for the same event.
1502 if dom.get_document().get_root_element().is_none()
1503 && get_status_code() < 3
1504 && state::has_value("document_class_filename")
1505 {
1506 let _: Result<()> = (|| {
1507 Fatal!(
1508 Document,
1509 Malformed,
1510 "The conversion built a document with no root element: \\begin{document} was never \
1511 reached (an unbalanced conditional skipped it?); the output is empty"
1512 );
1513 })();
1514 }
1515}
1516
1517#[cfg(test)]
1518mod tests {
1519 use super::*;
1520
1521 #[test]
1522 fn amble_math_wraps_both_ends() {
1523 // Perl LaTeXML.pm:166-168 — math sets BOTH preamble and postamble.
1524 let (pre, post) = resolve_amble(&DataSize::Math, &None, &None);
1525 assert_eq!(
1526 pre.as_deref(),
1527 Some("literal:\\begin{document}\\ensuremathfollows")
1528 );
1529 assert_eq!(
1530 post.as_deref(),
1531 Some("literal:\\ensuremathpreceeds\\end{document}")
1532 );
1533 }
1534
1535 #[test]
1536 fn amble_fragment_defaults_to_standard_files() {
1537 let (pre, post) = resolve_amble(&DataSize::Fragment, &None, &None);
1538 assert_eq!(pre.as_deref(), Some("standard_preamble.tex"));
1539 assert_eq!(post.as_deref(), Some("standard_postamble.tex"));
1540 }
1541
1542 #[test]
1543 fn amble_fragment_honors_explicit_files() {
1544 let (pre, post) = resolve_amble(
1545 &DataSize::Fragment,
1546 &Some("my_pre.tex".into()),
1547 &Some("my_post.tex".into()),
1548 );
1549 assert_eq!(pre.as_deref(), Some("my_pre.tex"));
1550 assert_eq!(post.as_deref(), Some("my_post.tex"));
1551 }
1552
1553 #[test]
1554 fn amble_document_and_archive_have_no_wrapping() {
1555 assert_eq!(
1556 resolve_amble(&DataSize::Document, &None, &None),
1557 (None, None)
1558 );
1559 assert_eq!(
1560 resolve_amble(&DataSize::Archive, &None, &None),
1561 (None, None)
1562 );
1563 }
1564
1565 /// A first-line format request as pdftex (TL 2025, `parse_first_line = t`) reads it: each row checked with pdftex
1566 /// on a file printing `\fmtname` (AmS-TeX or plain).
1567 #[test]
1568 fn amstex_format_request_is_read_as_pdftex_reads_it() {
1569 for (first_line, amstex) in [
1570 ("%&amstex\n", true),
1571 ("%&amstex\r\n", true),
1572 ("%&amstex\r", true),
1573 ("%&amstex \n", true),
1574 ("%& amstex\n", true),
1575 ("%&\tamstex\n", true),
1576 ("%&amstex -translate-file=cp227.tcx\n", true),
1577 ("%&AMSTeX\n", false),
1578 ("%&amstex,\n", false),
1579 ("%&amstex\ttab\n", false),
1580 ("%&-translate-file=cp227.tcx amstex\n", false),
1581 ("\u{feff}%&amstex\n", false),
1582 ("x %&amstex\n", false),
1583 ("% a comment\n%&amstex\n", false),
1584 ("%&latex\n", false),
1585 ] {
1586 let text = format!("{first_line}\\bye\n");
1587 assert_eq!(requests_amstex_format(&text), amstex, "{first_line:?}");
1588 assert_eq!(
1589 compile_route(&format!("literal:{text}")).amstex,
1590 amstex,
1591 "{first_line:?}"
1592 );
1593 }
1594 }
1595
1596 /// `compile_route`'s tex-vs-latex and DVI cues (62a, stopped full-arXiv run 329; reviewer probes): a LaTeX
1597 /// document must never read as plain, which drops the preload-time format (ar5iv's locked `\today`).
1598 #[test]
1599 fn compile_route_of_main_sources() {
1600 const PLAIN_TEX: CompileRoute = CompileRoute {
1601 plain_tex: true,
1602 dvi: false,
1603 pdf: false,
1604 figures: state::FigureOutputCue::Undecided,
1605 amstex: false,
1606 };
1607 const LATEX_PDF: CompileRoute = CompileRoute {
1608 plain_tex: false,
1609 dvi: false,
1610 pdf: false,
1611 figures: state::FigureOutputCue::Undecided,
1612 amstex: false,
1613 };
1614 const LATEX_DVI: CompileRoute = CompileRoute {
1615 plain_tex: false,
1616 dvi: true,
1617 pdf: false,
1618 figures: state::FigureOutputCue::Undecided,
1619 amstex: false,
1620 };
1621 const LATEX_PDF_OPTION: CompileRoute = CompileRoute {
1622 plain_tex: false,
1623 dvi: false,
1624 pdf: true,
1625 figures: state::FigureOutputCue::Undecided,
1626 amstex: false,
1627 };
1628 let route_of = |code: &str| compile_route(&format!("literal:{code}"));
1629 assert_eq!(route_of("Hello.\n\\bye\n"), PLAIN_TEX);
1630 assert_eq!(route_of("\\documentclass{article}\n"), LATEX_PDF);
1631 assert_eq!(route_of("\\documentstyle{article}\n"), LATEX_PDF);
1632 // `\begin{document}` in an open `\ifpdf`/`\ifCLASSINFOpdf` true branch (2105.10205, 2502.09129): PDF, over a DVI
1633 // driver option; not with the branch closed, after its `\else` (1012.0815), inside a group or a definition, after
1634 // `\newif`, past another conditional, or with a second `\begin{document}`.
1635 let ieee = "\\documentclass[journal]{IEEEtran}\n\\ifCLASSINFOpdf\n\\hyphenation{}\n\\begin{document}\nA\n";
1636 assert_eq!(route_of(ieee), LATEX_PDF_OPTION);
1637 assert_eq!(
1638 route_of("\\documentclass[dvips]{article}\\usepackage{ifpdf}\\ifpdf %\n\\begin{document}"),
1639 LATEX_PDF_OPTION
1640 );
1641 for not_open in [
1642 "\\documentclass{IEEEtran}\\ifCLASSINFOpdf\\else\\fi\\begin{document}",
1643 "\\documentclass{IEEEtran}\\ifCLASSINFOpdf\\else\n\\begin{document}",
1644 "\\documentclass{IEEEtran}\\ifCLASSINFOpdf\\ifx\\a\\b\\fi\\begin{document}",
1645 "\\documentclass{article}\\def\\x{\\ifpdf}\\begin{document}",
1646 "\\documentclass{article}{\\ifpdf}\\begin{document}",
1647 "\\documentclass{article}\\newif\\ifpdf\n\\begin{document}",
1648 "\\documentclass{article}\\ifpdfx\\begin{document}",
1649 "\\documentclass{article}% \\ifpdf\n\\begin{document}",
1650 "\\documentclass{article}\\ifpdf\\begin{document}A\\fi\\begin{document}B",
1651 ] {
1652 assert_eq!(route_of(not_open), LATEX_PDF, "{not_open}");
1653 }
1654 // CR-only (old Mac) and CRLF line ends: a comment line does not swallow the class.
1655 assert_eq!(
1656 route_of("% Mac file\r\\documentclass{article}\r"),
1657 LATEX_PDF
1658 );
1659 assert_eq!(
1660 route_of("% PC file\r\n\\documentclass{article}\r\n"),
1661 LATEX_PDF
1662 );
1663 // A commented class is no class; `\%` is a character, `\\%` a control symbol before a comment.
1664 assert_eq!(route_of("% \\documentclass{article}\nHello.\n"), PLAIN_TEX);
1665 assert_eq!(route_of("100\\% \\documentclass{article}\n"), LATEX_PDF);
1666 assert_eq!(route_of("x\\\\% \\documentclass{article}\n"), PLAIN_TEX);
1667 // A main file that `\input`s its preamble.
1668 assert_eq!(
1669 route_of("\\input pre\n\\begin{document}\nX\n\\end{document}\n"),
1670 LATEX_PDF
1671 );
1672 // A `.sty` a `filecontents` writes ends with its own `\endinput`; `\endinputs` is no `\endinput`.
1673 assert_eq!(
1674 route_of(
1675 "\\begin{filecontents*}{x.sty}\n\\def\\x{}\n\\endinput\n\\end{filecontents*}\n\\documentclass[dvips]{article}\n"
1676 ),
1677 LATEX_DVI
1678 );
1679 assert_eq!(
1680 route_of("\\def\\endinputs{}\n\\documentclass{article}\n"),
1681 LATEX_PDF
1682 );
1683 assert_eq!(route_of("\\begin {document}\nX\n"), LATEX_PDF);
1684 // TeX reads no further than `\endinput`.
1685 assert_eq!(
1686 route_of("Hello.\n\\endinput\n\\documentclass{article}\n"),
1687 PLAIN_TEX
1688 );
1689 // AMSTeX's own `\documentstyle` counts as LaTeX (plain AMSTeX measured worse; see `compile_route`).
1690 assert_eq!(
1691 route_of("\\input amstex\n\\documentstyle{amsppt}\n\\document\nX\n\\enddocument\n"),
1692 LATEX_PDF
1693 );
1694 // A DVI driver class option, unless the file sets `\pdfoutput=1` (exactly 1).
1695 assert_eq!(
1696 route_of("\\documentclass[12pt,dvips]{article}\n"),
1697 LATEX_DVI
1698 );
1699 assert_eq!(
1700 route_of("\\pdfoutput=1\n\\documentclass[dvips]{article}\n"),
1701 LATEX_PDF
1702 );
1703 assert_eq!(
1704 route_of("\\pdfoutput = 1\n\\documentclass[dvips]{article}\n"),
1705 LATEX_PDF
1706 );
1707 assert_eq!(
1708 route_of("\\pdfoutput=10\n\\documentclass[dvips]{article}\n"),
1709 LATEX_DVI
1710 );
1711 // The `pdftex` driver option: a pdflatex document (2210.04612's MDPI template, `logo-*.eps` beside PNG figures).
1712 assert_eq!(
1713 route_of("\\documentclass[journal,article,pdftex]{Definitions/mdpi}\n"),
1714 LATEX_PDF_OPTION
1715 );
1716 // A `#` name is a macro's call-time argument, no preamble: plain TeX stays plain (hep-ph9210212's
1717 // `\def\inputrefs#1{…\input #1…}`, hep-th0703274's `\input #1.aux`).
1718 assert_eq!(
1719 route_of("\\def\\inputrefs#1{\\input #1 }\n\\inputrefs{refs}\n\\bye\n"),
1720 PLAIN_TEX
1721 );
1722 // A wrapper main file naming only its preamble and body (one level of `\input`/`\include`).
1723 let dir = tempfile::tempdir().expect("tempdir");
1724 std::fs::write(
1725 dir.path().join("wpre.tex"),
1726 "\\documentclass[dvips]{article}\n",
1727 )
1728 .unwrap();
1729 std::fs::write(
1730 dir.path().join("wbody.tex"),
1731 "\\begin{document}X\\end{document}\n",
1732 )
1733 .unwrap();
1734 let main = dir.path().join("w.tex");
1735 std::fs::write(&main, "\\input{wpre}\n\\include{wbody}\n").unwrap();
1736 assert_eq!(compile_route(&main.to_string_lossy()), LATEX_DVI);
1737 std::fs::write(dir.path().join("wplain.tex"), "Hello.\n").unwrap();
1738 std::fs::write(&main, "\\input wplain\n\\bye\n").unwrap();
1739 assert_eq!(compile_route(&main.to_string_lossy()), PLAIN_TEX);
1740 // Two levels: main → setup → preamble.
1741 std::fs::write(dir.path().join("setup.tex"), "\\input wpre\n").unwrap();
1742 std::fs::write(&main, "\\input setup\n\\input wbody\n").unwrap();
1743 assert_eq!(compile_route(&main.to_string_lossy()), LATEX_DVI);
1744 // An input in `\iffalse … \fi` is not read; a dual-mode macro file's `\ifx\documentclass\undefined` is no class.
1745 std::fs::write(
1746 dir.path().join("dual.tex"),
1747 "\\ifx\\documentclass\\undefined\\def\\x{}\\fi\n",
1748 )
1749 .unwrap();
1750 std::fs::write(
1751 &main,
1752 "\\iffalse\\input{wpre}\\fi\n\\input dual\nHello.\n\\bye\n",
1753 )
1754 .unwrap();
1755 assert_eq!(compile_route(&main.to_string_lossy()), PLAIN_TEX);
1756 // An input name only TeX resolves leans LaTeX; `\iffalse … \else` keeps its `\else` branch.
1757 std::fs::write(&main, "\\def\\pre{wpre}\\input{\\pre}\nX \\today\n\\bye\n").unwrap();
1758 assert_eq!(compile_route(&main.to_string_lossy()), LATEX_PDF);
1759 std::fs::write(
1760 &main,
1761 "\\iffalse\\input{dual}\\else\\input{wpre}\\fi\n\\input wbody\n",
1762 )
1763 .unwrap();
1764 assert_eq!(compile_route(&main.to_string_lossy()), LATEX_DVI);
1765 // Commands plain TeX cannot run.
1766 assert_eq!(route_of("\\usepackage{amsmath}\nX\n"), LATEX_PDF);
1767 assert_eq!(route_of("\\include{chap}\n"), LATEX_PDF);
1768 assert_eq!(route_of("\\includegraphics{x}\n\\bye\n"), PLAIN_TEX);
1769 // The main file's `\pdfoutput=1` holds against a followed file's `[dvips]`.
1770 std::fs::write(&main, "\\pdfoutput=1\n\\input{wpre}\n\\include{wbody}\n").unwrap();
1771 assert_eq!(compile_route(&main.to_string_lossy()), LATEX_PDF);
1772 }
1773
1774 /// `figure_output_cue`: the figures a source includes, resolved in its tree, and a pstricks load (65f; 1012.0815's
1775 /// EPS figures beside an unincluded PDF, 1002.1751's pstricks).
1776 #[test]
1777 fn figure_output_cue_of_sources() {
1778 use state::FigureOutputCue::{Dvi, Pdf, Undecided};
1779 let dir = tempfile::tempdir().expect("tempdir");
1780 let write = |name: &str, content: &str| {
1781 let path = dir.path().join(name);
1782 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1783 std::fs::write(path, content).unwrap();
1784 };
1785 let cue = |code: &str| figure_output_cue(&uncommented_code(code), Some(dir.path()));
1786 write("figs/a.eps", "");
1787 write("figs/b.png", "");
1788 write("figs/c.eps", "");
1789 write("figs/c.pdf", "");
1790 write("doc/manual.pdf", "");
1791 write("img/d.EPS", "");
1792 // An EPS-only figure, by name or extension-less; one that is PNG only; one in both forms decides nothing.
1793 assert_eq!(cue("\\includegraphics[width=1cm]{figs/a.eps}"), Dvi);
1794 assert_eq!(cue("\\includegraphics{figs/a}"), Dvi);
1795 assert_eq!(
1796 cue("\\includegraphics{figs/a}\\includegraphics{figs/b}"),
1797 Pdf
1798 );
1799 assert_eq!(cue("\\includegraphics{figs/c}"), Undecided);
1800 // A missing figure, a macro argument, a commented or `\iffalse`d include: nothing.
1801 assert_eq!(cue("\\includegraphics{figs/none}"), Undecided);
1802 assert_eq!(cue("\\includegraphics{../figs/a}"), Undecided);
1803 assert_eq!(cue("\\def\\f#1{\\includegraphics{#1}}"), Undecided);
1804 assert_eq!(cue("% \\includegraphics{figs/a}\n"), Undecided);
1805 assert_eq!(cue("\\iffalse\\includegraphics{figs/a}\\fi"), Undecided);
1806 // `\graphicspath`, an upper-case extension, the epsf/psfig family, AASTeX's `\plotone`.
1807 assert_eq!(cue("\\graphicspath{{img/}}\\includegraphics{d}"), Dvi);
1808 assert_eq!(cue("\\epsfig{file=figs/a.eps,width=3cm}"), Dvi);
1809 assert_eq!(cue("\\psfig{figure=figs/b.png}"), Pdf);
1810 assert_eq!(cue("\\epsfbox{figs/a.eps}"), Dvi);
1811 assert_eq!(cue("\\plotone{figs/a.eps}"), Dvi);
1812 // pstricks; its pdflatex front ends.
1813 assert_eq!(cue("\\usepackage{pstricks,pst-node}"), Dvi);
1814 assert_eq!(cue("\\usepackage{pst-plot}"), Dvi);
1815 assert_eq!(cue("\\input pstricks"), Dvi);
1816 assert_eq!(
1817 cue("\\usepackage{pstricks}\\usepackage{auto-pst-pdf}"),
1818 Undecided
1819 );
1820 assert_eq!(cue("\\usepackage{pstricks}\\includegraphics{figs/b}"), Pdf);
1821 // Only when every included figure resolves: a missing or run-time-named one leaves the tree's files to decide.
1822 assert_eq!(
1823 cue("\\includegraphics{figs/a}\\includegraphics{figs/none}"),
1824 Undecided
1825 );
1826 assert_eq!(
1827 cue("\\includegraphics{figs/a}\\includegraphics{\\figdir/b}"),
1828 Undecided
1829 );
1830 // epstopdf's conversions beside an EPS figure, or an epstopdf load, are no PDF cue: arXiv compiled such sources
1831 // with latex+dvips (1806.00093, 1804.02991: Producer "dvips + GPL Ghostscript").
1832 write("figs/e.eps", "");
1833 write("figs/e-eps-converted-to.pdf", "");
1834 assert_eq!(cue("\\includegraphics{figs/e}"), Dvi);
1835 assert_eq!(cue("\\includegraphics{figs/e.eps}"), Dvi);
1836 assert_eq!(cue("\\usepackage{epstopdf}\\includegraphics{figs/a}"), Dvi);
1837 // A file the main file inputs.
1838 write("sec.tex", "\\includegraphics{figs/b.png}\n");
1839 assert_eq!(cue("\\input{sec}"), Pdf);
1840 // No directory: nothing resolves.
1841 assert_eq!(
1842 figure_output_cue("\\includegraphics{figs/a}", None),
1843 Undecided
1844 );
1845 }
1846}