Skip to main content

latexml_post/
lib.rs

1#![allow(dead_code)] // Library in progress — many APIs not yet consumed externally
2#![allow(clippy::collapsible_match, clippy::collapsible_if)]
3#![allow(clippy::if_same_then_else)] // Intentional per-type branches for FMT_SPEC clarity
4#![allow(clippy::cloned_ref_to_slice_refs)] // Node::clone() is Rc clone (cheap), needed for &[Node] APIs
5//! Post-processing pipeline for latexml_oxide.
6//!
7//! Rust port of `LaTeXML::Post` — the driver that orchestrates
8//! post-processors (Scan, CrossRef, MathML conversion, XSLT, Writer, etc.)
9//! on a converted LaTeXML XML document.
10//!
11//! # Architecture
12//!
13//! The processing pipeline follows the Perl original:
14//!
15//! 1. **Input**: An XML document produced by the core LaTeXML conversion
16//! 2. **ProcessChain**: Each `Processor` in sequence gets:
17//!    - `to_process(doc)` → nodes relevant to this processor
18//!    - `process(doc, nodes)` → the (possibly split) result document(s)
19//! 3. **Output**: One or more processed XML documents
20//!
21//! # Modules
22//!
23//! - Infrastructure: [`document`] (`PostDocument`: the XML, ids, XPath), [`processor`] (the `Processor` trait),
24//!   [`math_processor`], [`object_db`] (cross-page data), [`radix`] (id suffixes), [`diag`] (diagnostics).
25//! - Structure: [`scan`], [`split`], [`stream_split`] (the split of a core result on disk), [`crossref`],
26//!   [`make_bibliography`], [`make_index`], [`collector`].
27//! - Math: [`mathml`] (Presentation and Content MathML), [`unicode_math`], [`open_math`], [`tex_math`], [`xmath`],
28//!   [`lex_math`], [`unicode`].
29//! - Images: [`graphics`] and [`graphics_cache`], [`latex_images`], [`math_images`], [`picture_images`], [`svg`].
30//! - Output: [`xslt`], [`writer`], [`manifest`] (the EPUB package), [`pack`] (zip and EPUB bundles), [`extract`]
31//!   (`--whatsout=fragment` and `math`), [`resource_cache`] and [`sqlite_store`] (the `LaTeXML-oxide.cache` names),
32//!   [`schema_docs`].
33//!
34//! The `latexml` crate's `post` module drives this pipeline for a conversion.
35
36// Crate-wide diagnostic emission macros
37// (`Error!`, `Warn!`, `Info!`,
38// `Fatal!`). Loaded first via #[macro_use] so every
39// post-processor module can use them without explicit imports —
40// matching how `latexml_engine`'s prelude makes the engine-level
41// `Error!`/`Warn!` macros visible.
42#[macro_use]
43pub mod diag;
44
45// Core infrastructure
46pub mod document;
47pub mod math_processor;
48pub mod object_db;
49pub mod processor;
50pub mod radix;
51
52// Concrete post-processors (alphabetical)
53pub mod collector;
54pub mod crossref;
55pub mod extract;
56pub mod graphics;
57pub mod graphics_cache; // Content-addressed cache for graphics phase subprocs.
58pub mod latex_images;
59pub mod lex_math;
60pub mod make_bibliography;
61pub mod make_index;
62pub mod manifest;
63pub mod math_images;
64pub mod mathml;
65pub mod open_math;
66pub mod pack;
67pub mod picture_images;
68mod postscript_fonts;
69pub mod resource_cache;
70pub mod scan;
71pub mod schema_docs;
72pub mod split;
73pub mod sqlite_store;
74pub mod stream_split;
75pub mod svg;
76pub mod tex_math;
77pub mod unicode;
78pub mod unicode_math;
79pub mod writer;
80pub mod xmath;
81pub mod xslt;
82
83// `build.rs` pulls this in with `#[path] mod`; declared here under cfg(test) only, for its unit tests.
84#[cfg(test)]
85mod build_rerun;
86
87/// Shared helpers for the process-global state (`env`, `/tmp`) that this
88/// crate's multi-threaded unit tests contend over.
89#[cfg(test)]
90mod test_env;
91
92use std::sync::LazyLock;
93
94use document::PostDocument;
95use processor::{PostError, Processor};
96
97// Process-once cached env var (see WISDOM #56 — getenv hot-path race).
98static POST_AUDIT: LazyLock<bool> = LazyLock::new(|| std::env::var("LATEXML_POST_AUDIT").is_ok());
99
100/// The post-processing pipeline driver.
101///
102/// Port of `LaTeXML::Post`.
103/// Manages a chain of processors and orchestrates their execution.
104pub struct Post {
105  /// Status tracking.
106  pub status: PostStatus,
107}
108
109/// Status of post-processing.
110#[derive(Debug, Default)]
111pub struct PostStatus {
112  pub warning_count: u32,
113  pub error_count:   u32,
114  pub fatal_count:   u32,
115  pub info_count:    u32,
116}
117
118impl Post {
119  /// Create a new post-processing driver.
120  pub fn new() -> Self { Post { status: PostStatus::default() } }
121
122  /// Run the processing chain on a document.
123  ///
124  /// Each processor in order gets the current document(s),
125  /// finds nodes to process via `to_process()`, and transforms them
126  /// via `process()`. Documents may be split (producing multiple outputs).
127  ///
128  /// Port of `Post::ProcessChain` + `ProcessChain_internal`.
129  pub fn process_chain(
130    &mut self,
131    docs: Vec<PostDocument>,
132    processors: &mut [Box<dyn Processor>],
133  ) -> Result<Vec<PostDocument>, PostError> {
134    let mut docs = docs;
135
136    Note!("post-processing");
137    let audit = *POST_AUDIT;
138
139    for processor in processors.iter_mut() {
140      // Map processor names to telemetry phases. See docs/performance/TELEMETRY.md.
141      // Names come from each Processor's get_name() — same bracket-
142      // classifier shape as XSLT (`XSLT[using ...]`): MathML uses
143      // `MathML[Presentation]` / `MathML[Content]`. Anything
144      // unrecognised attributes to Xslt as a coarse fallback.
145      let pname = processor.get_name();
146      let phase = if pname.starts_with("MathML[Presentation]") {
147        latexml_core::telemetry::Phase::MathmlPres
148      } else if pname.starts_with("MathML[Content]") {
149        latexml_core::telemetry::Phase::MathmlCont
150      } else if pname.starts_with("XSLT") {
151        latexml_core::telemetry::Phase::Xslt
152      } else if pname.contains("Image") || pname.contains("image") {
153        // math_images / picture_images / latex_images all share the
154        // external-tool-rendering semantics of Graphics; classify them
155        // as MathImages when they are wired up to process_chain.
156        latexml_core::telemetry::Phase::MathImages
157      } else {
158        // Unknown processor — fall through to Xslt (least surprising
159        // catch-all for the post-XSLT-ish region).
160        latexml_core::telemetry::Phase::Xslt
161      };
162      let _gp = latexml_core::telemetry::phase(phase);
163      let mut new_docs = Vec::new();
164      for doc in docs {
165        let nodes = processor.to_process(&doc);
166        if !nodes.is_empty() {
167          let n = nodes.len();
168          let msg = format!(
169            "{} {} {}",
170            processor.get_name(),
171            doc.site_relative_destination().unwrap_or_default(),
172            if n > 1 {
173              format!("{} to process", n)
174            } else {
175              "processing".to_string()
176            }
177          );
178          Note!(msg);
179          let t0 = if audit {
180            Some(std::time::Instant::now())
181          } else {
182            None
183          };
184          let result_docs = processor.process(doc, nodes)?;
185          if let Some(t0) = t0 {
186            let ms = t0.elapsed().as_millis();
187            Note!(format!(
188              "POST_AUDIT stage {} took {}ms ({} nodes)",
189              processor.get_name(),
190              ms,
191              n
192            ));
193          }
194          new_docs.extend(result_docs);
195        } else {
196          new_docs.push(doc);
197        }
198      }
199      docs = new_docs;
200    }
201
202    // Drain any XMath subtrees that the math-format processors queued
203    // for deferred unlink. The defer-then-drain split is what lets the
204    // CorTeX pmml+cmml chain share one XMath subtree across both
205    // formats; eager unlink in the first processor was the root cause
206    // of the dominant `Error:expected:id` cluster (~63% of CONVERR
207    // papers on second-500K stages) — the second processor's
208    // `mark_xm_node_visibility` walked stale XMRefs into a freed
209    // subtree. See `PostDocument::defer_xmath_unlink`.
210    for doc in docs.iter_mut() {
211      doc.drain_pending_xmath_unlinks();
212    }
213
214    Note!("post-processing complete");
215    Ok(docs)
216  }
217}
218
219impl Default for Post {
220  fn default() -> Self { Self::new() }
221}
222
223#[cfg(test)]
224mod tests {
225  use super::*;
226  use crate::{
227    document::PostDocumentOptions,
228    writer::{OutputFormat, Writer},
229  };
230
231  #[test]
232  fn test_empty_pipeline() {
233    let mut post = Post::new();
234    let doc = PostDocument::new_from_string(
235      "<document xmlns='http://dlmf.nist.gov/LaTeXML'/>",
236      PostDocumentOptions::default(),
237    )
238    .unwrap();
239
240    let mut processors: Vec<Box<dyn Processor>> = vec![];
241    let result = post.process_chain(vec![doc], &mut processors);
242    assert!(result.is_ok());
243    assert_eq!(result.unwrap().len(), 1);
244  }
245
246  #[test]
247  fn test_writer_pipeline() {
248    let mut post = Post::new();
249    let doc = PostDocument::new_from_string(
250      "<document xmlns='http://dlmf.nist.gov/LaTeXML'><title>Test</title></document>",
251      PostDocumentOptions::default(),
252    )
253    .unwrap();
254
255    // Writer without destination prints to stdout (we just test it doesn't crash)
256    let writer = Writer::new(Some(OutputFormat::Xml), false, false);
257    let mut processors: Vec<Box<dyn Processor>> = vec![Box::new(writer)];
258    let result = post.process_chain(vec![doc], &mut processors);
259    assert!(result.is_ok());
260  }
261
262  #[test]
263  fn test_pmml_pipeline() {
264    let mut post = Post::new();
265    let doc = PostDocument::new_from_string(
266      "<document xmlns='http://dlmf.nist.gov/LaTeXML'>\
267         <para xml:id='p1'><p>Inline <Math mode='inline' tex='a+b' text='a + b' xml:id='p1.m1'>\
268           <XMath><XMApp>\
269             <XMTok meaning='plus' role='ADDOP'>+</XMTok>\
270             <XMTok font='italic' role='ID'>a</XMTok>\
271             <XMTok font='italic' role='ID'>b</XMTok>\
272           </XMApp></XMath></Math></p></para>\
273       </document>",
274      PostDocumentOptions::default(),
275    )
276    .unwrap();
277
278    let pmml = mathml::MathML::new_presentation().with_keep_xmath(true);
279    let mut processors: Vec<Box<dyn Processor>> = vec![Box::new(pmml)];
280    let result = post.process_chain(vec![doc], &mut processors);
281    assert!(result.is_ok());
282    let docs = result.unwrap();
283    let output = docs[0].to_xml_string();
284    eprintln!("PMML output:\n{}", output);
285    // Should contain both XMath and m:math
286    assert!(
287      output.contains("<XMath>") || output.contains("<XMath "),
288      "XMath should be preserved"
289    );
290    assert!(
291      output.contains("m:math"),
292      "m:math element should be present"
293    );
294    assert!(output.contains("m:mi"), "m:mi element should be present");
295    assert!(output.contains("m:mo"), "m:mo element should be present");
296  }
297
298  /// Parallel Presentation+Content markup must merge into ONE `<m:semantics>`
299  /// with the content tree wrapped in `<m:annotation-xml encoding="MathML-Content">`
300  /// — never left as an orphan `<m:apply>` sibling of `<m:semantics>` (which
301  /// browsers render as stray text after the formula). Exercises
302  /// `MathProcessor::combine_parallel` via the primary→secondary chain that
303  /// `latexml_oxide::post` builds when both `pmml` and `cmml` are requested.
304  /// Regression guard for the cortex-preview "broken MathML" bug.
305  #[test]
306  fn test_parallel_pmml_cmml_combine_parallel() {
307    let mut post = Post::new();
308    let doc = PostDocument::new_from_string(
309      "<document xmlns='http://dlmf.nist.gov/LaTeXML'>\
310         <para xml:id='p1'><p>Inline <Math mode='inline' tex='a+b' text='a + b' xml:id='p1.m1'>\
311           <XMath><XMApp>\
312             <XMTok meaning='plus' role='ADDOP'>+</XMTok>\
313             <XMTok font='italic' role='ID'>a</XMTok>\
314             <XMTok font='italic' role='ID'>b</XMTok>\
315           </XMApp></XMath></Math></p></para>\
316       </document>",
317      PostDocumentOptions::default(),
318    )
319    .unwrap();
320
321    // Presentation primary holding a Content secondary — the same parallel-markup
322    // shape `latexml_oxide::post` builds for `pmml && cmml`.
323    let content = mathml::MathML::new_content().secondary();
324    let pmml = mathml::MathML::new_presentation()
325      .with_mathtex(true)
326      .with_secondaries(vec![Box::new(content)]);
327    let mut processors: Vec<Box<dyn Processor>> = vec![Box::new(pmml)];
328    let result = post.process_chain(vec![doc], &mut processors);
329    assert!(result.is_ok());
330    let docs = result.unwrap();
331    let output = docs[0].to_xml_string();
332    eprintln!("parallel P+C output:\n{output}");
333
334    // Single semantics holding presentation + content + tex source.
335    assert!(
336      output.contains("m:semantics"),
337      "m:semantics wrapper missing"
338    );
339    assert!(
340      output.contains("m:apply"),
341      "content m:apply should be generated"
342    );
343    assert!(
344      output.contains(r#"m:annotation-xml encoding="MathML-Content""#),
345      "content must be folded into <m:annotation-xml encoding=\"MathML-Content\">"
346    );
347    assert!(
348      output.contains(r#"encoding="application/x-tex""#),
349      "x-tex source annotation should be present in the parallel semantics"
350    );
351    // THE regression assertion: no content markup may appear AFTER the
352    // semantics closes (i.e. as an orphan sibling under <m:math>).
353    let after_semantics = output.rsplit("</m:semantics>").next().unwrap_or("");
354    assert!(
355      !after_semantics.contains("m:apply") && !after_semantics.contains("m:ci"),
356      "orphan Content MathML found after </m:semantics> — combine_parallel not applied:\n{output}"
357    );
358  }
359
360  /// Content MathML's share ids on a formula with no ancestor xml:id (a chained relation shares its middle operand,
361  /// `cmml_shared`) count per document, as Perl's `generateNodeID` probes the document's idcache (Post.pm:1475): the
362  /// same document converted twice on one thread (a persistent worker) gets the same ids, `sh1` to `sh3`, which the
363  /// kept XMath carries (`--keepXMath`).
364  #[test]
365  fn content_share_ids_restart_per_document() {
366    let convert = || {
367      let doc = PostDocument::new_from_string(
368        "<document xmlns='http://dlmf.nist.gov/LaTeXML'><para><p><Math mode='inline' tex='a&lt;b&lt;c&lt;d'>\
369           <XMath><XMApp><XMTok meaning='multirelation'/>\
370             <XMTok role='ID'>a</XMTok><XMTok meaning='less-than' role='RELOP'>&lt;</XMTok>\
371             <XMTok role='ID'>b</XMTok><XMTok meaning='less-than' role='RELOP'>&lt;</XMTok>\
372             <XMTok role='ID'>c</XMTok><XMTok meaning='less-than' role='RELOP'>&lt;</XMTok>\
373             <XMTok role='ID'>d</XMTok>\
374           </XMApp></XMath></Math></p></para></document>",
375        PostDocumentOptions::default(),
376      )
377      .unwrap();
378      let mut processors: Vec<Box<dyn Processor>> = vec![Box::new(
379        mathml::MathML::new_content().with_keep_xmath(true),
380      )];
381      let docs = Post::new()
382        .process_chain(vec![doc], &mut processors)
383        .expect("content MathML");
384      docs[0].to_xml_string()
385    };
386    let first = convert();
387    assert!(
388      first.contains("xml:id=\"sh1\"") && first.contains("xml:id=\"sh3\""),
389      "{first}"
390    );
391    assert!(!first.contains("\"sh4\""), "{first}");
392    assert_eq!(convert(), first);
393  }
394
395  #[test]
396  fn test_scan_pipeline() {
397    let mut post = Post::new();
398    let doc = PostDocument::new_from_string(
399      "<document xmlns='http://dlmf.nist.gov/LaTeXML' xml:id='doc'>\
400         <section xml:id='s1'><title>First</title></section>\
401         <section xml:id='s2'><title>Second</title></section>\
402       </document>",
403      PostDocumentOptions::default(),
404    )
405    .unwrap();
406
407    let db = object_db::ObjectDB::new();
408    let scanner = scan::Scan::new(db);
409    let mut processors: Vec<Box<dyn Processor>> = vec![Box::new(scanner)];
410    let result = post.process_chain(vec![doc], &mut processors);
411    assert!(result.is_ok());
412  }
413}