latexml_core/common.rs
1pub mod arena;
2pub mod color;
3#[macro_use]
4pub mod error;
5pub mod cleaners;
6pub mod def_parser;
7pub mod dimension;
8pub mod float;
9pub mod font;
10pub mod glue;
11pub mod ligature;
12pub mod local_assignments;
13pub mod locator;
14pub mod mathchar;
15pub mod model;
16pub mod mudimension;
17pub mod muglue;
18pub mod number;
19pub mod numeric_ops;
20pub mod object;
21pub mod pair;
22pub mod relaxng;
23pub mod store;
24pub mod xml;
25pub mod xml_walk;
26
27use std::rc::Rc;
28
29use crate::{common::error::*, fmt};
30
31#[derive(Clone, Debug)]
32pub enum InputFormat {
33 TeX,
34 Bib,
35}
36#[derive(Clone, Debug)]
37pub enum OutputFormat {
38 TeX,
39 Box,
40 XML,
41 HTML5,
42 XHTML,
43}
44#[derive(Clone, Debug)]
45pub enum DataSize {
46 Math,
47 Fragment,
48 Document,
49 Archive,
50}
51
52#[derive(Clone, Debug)]
53pub enum DigestionMode {
54 TeX,
55 LaTeX,
56 AmSTeX,
57 BibTeX,
58}
59impl fmt::Display for DigestionMode {
60 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
61 use self::DigestionMode::*;
62 let formatted = match *self {
63 TeX => "TeX",
64 LaTeX => "LaTeX",
65 AmSTeX => "AmSTeX",
66 BibTeX => "BibTeX",
67 };
68 write!(f, "{formatted}")
69 }
70}
71
72impl DigestionMode {
73 pub fn extension(&self) -> String {
74 match *self {
75 DigestionMode::TeX | DigestionMode::LaTeX | DigestionMode::AmSTeX => "tex",
76 DigestionMode::BibTeX => "bib",
77 }
78 .to_string()
79 }
80}
81
82/// A compiled-binding dispatcher: given a request name, either declines
83/// (`None`, so the next resolution tier is tried) or reports the load outcome
84/// (`Some(Ok(()))` / `Some(Err(_))`). It resolves *compiled-in* bindings, which
85/// have no source file, so it carries no path — the load note announces such a
86/// binding by its module-proxy name (`<name>_sty.rs`).
87pub type BindingDispatcher = Rc<dyn Fn(&str) -> Option<Result<()>>>;
88
89/// The on-disk source a binding was loaded from, when it has one: `Some(path)`
90/// for a runtime *file* binding (e.g. a `.rhai` script), `None` for a
91/// compiled-in binding. Threaded through the resolving dispatcher's result so
92/// the "(Loading …)" note can name the real path (#560) — rather than a State
93/// side-channel.
94pub type BindingSource = Option<String>;
95
96/// The **resolving** binding dispatcher installed as the single, ordered
97/// resolution chain (see `converter::install_binding_dispatch`). Unlike a bare
98/// [`BindingDispatcher`], a successful load reports the [`BindingSource`] it
99/// loaded from, so a file binding announces its real path and a compiled one
100/// its proxy name.
101pub type ResolvingBindingDispatcher = Rc<dyn Fn(&str) -> Option<Result<BindingSource>>>;
102
103/// Finds the binding file a user supplied for a request in the local search paths (a runtime `.rhai` beside the
104/// document or in a `--path` directory), which the resolving chain loads ahead of every compiled binding, as Perl's
105/// `FindFile_aux` takes the first `<file>.ltxml` of SEARCHPATHS before the installed ones (Package.pm:2127-2129).
106/// Installed with the chain (`converter::install_binding_dispatch`).
107pub type LocalBindingFinder = Rc<dyn Fn(&str) -> Option<String>>;
108
109/// Lift a **native** (compiled-in) binding dispatcher — one with no source file
110/// to name — into a [`ResolvingBindingDispatcher`]: a successful load reports
111/// `None` source, so the caller announces it by its module-proxy name. Pairs
112/// with the runtime `rhai_dispatch` tier, which reports the real `.rhai` path.
113pub fn native_dispatcher(
114 f: impl Fn(&str) -> Option<Result<()>> + 'static,
115) -> ResolvingBindingDispatcher {
116 Rc::new(move |request| f(request).map(|r| r.map(|()| None)))
117}
118
119/// Perl: LABEL_MAPPING_HOOK => sub { ($label, $ctr, $norefnum) => ($refnum, $id) }
120/// Returns (optional refnum string, optional id string)
121pub type LabelMappingHook = Rc<dyn Fn(&str, &str, bool) -> (Option<String>, Option<String>)>;
122
123#[derive(Clone)]
124pub struct Config {
125 pub verbosity: i32,
126 pub format: OutputFormat,
127 pub whatsin: DataSize,
128 pub whatsout: DataSize,
129 pub preamble: Option<String>,
130 pub postamble: Option<String>,
131 pub mode: Option<DigestionMode>,
132 pub bindings_dispatch: Option<BindingDispatcher>,
133 pub extra_bindings_dispatch: Option<BindingDispatcher>,
134 /// Packages to preload before processing (e.g. --preload=ar5iv.sty)
135 pub preload: Option<Vec<String>>,
136 /// Additional search paths for finding packages/inputs (e.g. --path=dir)
137 pub search_paths: Option<Vec<String>>,
138 /// Whether to include XML comments in output (--nocomments sets false)
139 pub include_comments: Option<bool>,
140 /// Strict error-reporting (`--strict`; State `STRICT`, Perl Core.pm L43)
141 pub strict: Option<bool>,
142 /// Raw-load `.sty` AND `.cls` sources (`--includestyles`): one flag sets State `INCLUDE_STYLES` and
143 /// `INCLUDE_CLASSES` together (Perl Core.pm L55-57). `None` keeps Perl's default (off); the CLI, the library API
144 /// and cortex's generic profile pass `Some(true)` (OXIDIZED_DESIGN_DIVERGENCES #1080).
145 pub include_styles: Option<bool>,
146 /// Perl `$LaTeXML::IF_LIMIT` / `$LaTeXML::ABSORB_LIMIT` (`latexml.sty.ltxml:100-105`), set when the session
147 /// starts, before the preloads, so a `latexml.sty` `iflimit=`/`absorblimit=` option still wins (0 = unlimited).
148 /// `None` keeps Perl's default (unlimited); the front ends pass [`RUNAWAY_IF_LIMIT`] (ten times ar5iv.sty's) and
149 /// [`RUNAWAY_ABSORB_LIMIT`] (ar5iv.sty's) (OXIDIZED_DESIGN_DIVERGENCES #1080).
150 pub if_limit: Option<i64>,
151 pub absorb_limit: Option<i64>,
152 /// Whether to skip math parsing (--nomathparse)
153 pub nomathparse: Option<bool>,
154 /// Whether to track + emit source locators (`--source-map`). Off by
155 /// default; gates both per-token start capture and per-element
156 /// `data-sourcepos` stamping. See `docs/performance/SOURCE_PROVENANCE.md`.
157 pub source_map: Option<bool>,
158 /// Input encoding for translating source bytes to LaTeXML's internal UTF-8
159 /// (`--inputencoding`; Perl Config.pm L57, Core.pm L60-61 which assigns
160 /// State `PERL_INPUT_ENCODING`, default utf-8). Consumed by the Mouth's
161 /// per-line decode; only affects byte→UTF-8 translation, never catcodes
162 /// (for those, use the inputenc package). `None` ⇒ the utf-8 default.
163 pub inputencoding: Option<String>,
164 /// Streaming (fragmented) core conversion: `Some(budget)` interleaves
165 /// digest→build in fragments of ~`budget` boxes, spilling closed subtrees
166 /// to disk so peak RSS is bounded by fragment size instead of document
167 /// size. `None` (default) = the eager path — also the Perl-parity path
168 /// (Perl is strictly digest-all→build-all; interleaving is a sanctioned
169 /// divergence, activated only by the `--streaming` flag or when the
170 /// projected need exceeds the memory cap). The budget is a box count on
171 /// the same per-box basis as the box-list guards.
172 pub streaming: Option<usize>,
173 /// The date of the source (Unix seconds, UTC): the newest modification time among the TeX source files of the
174 /// bundle the document came in — an archive's entries, a directory's or a file's mtimes
175 /// (`latexml::source_date`). `None` when there is none (stdin, literal input, an archive whose entries carry no
176 /// time). ar5iv's archival preload sets the job's clock from it, so `\today` prints the paper's date, never the
177 /// conversion's.
178 pub source_date_epoch: Option<i64>,
179 /// Serialize the core result into this file, not a `String` (the CLI's split runs, whose post reads its input
180 /// from a file anyway): the response then names the file in `handoff_file`. `None`: the `String` result.
181 pub handoff_file: Option<String>,
182 /// The document's id (`--documentid`; Perl Config.pm L159, Core.pm L48 State `DOCUMENTID`): the root's `xml:id`
183 /// and the prefix of every other id. In State before the pools load, as Base_Schema reads it to define
184 /// `\thedocument@ID`.
185 pub documentid: Option<String>,
186 /// A confined conversion's read roots (`crate::util::pathname::confine`; OXIDIZED_DESIGN_DIVERGENCES #1183): every
187 /// archive input, and `--paranoid-input`. The front end holds the guard across the core, a restart and post.
188 pub confinement: Option<crate::util::pathname::InputConfinement>,
189}
190/// The front ends' default `\if` runaway ceiling, which ar5iv.sty's `iflimit` also passes (`latexml_contrib/src/
191/// ar5iv_sty.rs`, the arXiv fleet's profile). The counter accumulates over the whole document, so a long pgf-heavy
192/// document passes the former 48M without any runaway (tkz-grapheur-doc-fr lost its last section at 48M, DG
193/// 2026-11-18: "Raise plain default 10×"; 2302.07562 converts in 128 s, DG 2026-11-23 raised ar5iv's to match); the
194/// token budget and the timeout still bound a true runaway.
195pub const RUNAWAY_IF_LIMIT: i64 = 480_000_000;
196/// ar5iv.sty's `absorblimit`, the front ends' default ceiling on absorbed boxes.
197pub const RUNAWAY_ABSORB_LIMIT: i64 = 1_299_999;
198impl Default for Config {
199 fn default() -> Self {
200 Config {
201 verbosity: 1,
202 format: OutputFormat::XML,
203 whatsin: DataSize::Document,
204 whatsout: DataSize::Document,
205 preamble: None,
206 postamble: None,
207 mode: Some(DigestionMode::LaTeX),
208 bindings_dispatch: None,
209 extra_bindings_dispatch: None,
210 preload: None,
211 search_paths: None,
212 include_comments: None,
213 strict: None,
214 include_styles: None,
215 if_limit: None,
216 absorb_limit: None,
217 nomathparse: None,
218 source_map: None,
219 inputencoding: None,
220 streaming: None,
221 source_date_epoch: None,
222 handoff_file: None,
223 documentid: None,
224 confinement: None,
225 }
226 }
227}
228
229#[cfg(test)]
230mod tests {
231 use super::*;
232
233 #[test]
234 fn digestion_mode_display() {
235 assert_eq!(format!("{}", DigestionMode::TeX), "TeX");
236 assert_eq!(format!("{}", DigestionMode::LaTeX), "LaTeX");
237 assert_eq!(format!("{}", DigestionMode::AmSTeX), "AmSTeX");
238 assert_eq!(format!("{}", DigestionMode::BibTeX), "BibTeX");
239 }
240
241 #[test]
242 fn digestion_mode_extension() {
243 assert_eq!(DigestionMode::TeX.extension(), "tex");
244 assert_eq!(DigestionMode::LaTeX.extension(), "tex");
245 assert_eq!(DigestionMode::AmSTeX.extension(), "tex");
246 assert_eq!(DigestionMode::BibTeX.extension(), "bib");
247 }
248
249 #[test]
250 fn config_default_fields() {
251 let c = Config::default();
252 assert_eq!(c.verbosity, 1);
253 assert!(matches!(c.format, OutputFormat::XML));
254 assert!(matches!(c.whatsin, DataSize::Document));
255 assert!(matches!(c.whatsout, DataSize::Document));
256 assert!(c.preamble.is_none());
257 assert!(c.postamble.is_none());
258 assert!(matches!(c.mode, Some(DigestionMode::LaTeX)));
259 assert!(c.bindings_dispatch.is_none());
260 assert!(c.extra_bindings_dispatch.is_none());
261 assert!(c.preload.is_none());
262 assert!(c.search_paths.is_none());
263 assert!(c.include_comments.is_none());
264 assert!(c.nomathparse.is_none());
265 assert!(c.source_map.is_none());
266 }
267
268 #[test]
269 fn config_clone_preserves_fields() {
270 let c = Config {
271 verbosity: 5,
272 preload: Some(vec!["ar5iv.sty".to_string()]),
273 ..Default::default()
274 };
275 let c2 = c.clone();
276 assert_eq!(c2.verbosity, 5);
277 assert_eq!(c2.preload.as_ref().unwrap(), &vec!["ar5iv.sty".to_string()]);
278 }
279
280 #[test]
281 fn input_format_variants() {
282 // Debug trait at minimum is derived; Clone too.
283 let _ = InputFormat::TeX;
284 let _ = InputFormat::Bib;
285 let cloned = InputFormat::TeX.clone();
286 assert!(matches!(cloned, InputFormat::TeX));
287 }
288
289 #[test]
290 fn output_format_variants() {
291 let _ = OutputFormat::TeX;
292 let _ = OutputFormat::Box;
293 let _ = OutputFormat::XML;
294 let _ = OutputFormat::HTML5;
295 let _ = OutputFormat::XHTML;
296 let cloned = OutputFormat::XML.clone();
297 assert!(matches!(cloned, OutputFormat::XML));
298 }
299
300 #[test]
301 fn data_size_variants() {
302 let _ = DataSize::Math;
303 let _ = DataSize::Fragment;
304 let _ = DataSize::Document;
305 let _ = DataSize::Archive;
306 let cloned = DataSize::Document.clone();
307 assert!(matches!(cloned, DataSize::Document));
308 }
309}