1#![allow(dead_code)] #![allow(clippy::collapsible_match, clippy::collapsible_if)]
3#![allow(clippy::if_same_then_else)] #![allow(clippy::cloned_ref_to_slice_refs)] #[macro_use]
43pub mod diag;
44
45pub mod document;
47pub mod math_processor;
48pub mod object_db;
49pub mod processor;
50pub mod radix;
51
52pub mod collector;
54pub mod crossref;
55pub mod extract;
56pub mod graphics;
57pub mod graphics_cache; pub 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#[cfg(test)]
85mod build_rerun;
86
87#[cfg(test)]
90mod test_env;
91
92use std::sync::LazyLock;
93
94use document::PostDocument;
95use processor::{PostError, Processor};
96
97static POST_AUDIT: LazyLock<bool> = LazyLock::new(|| std::env::var("LATEXML_POST_AUDIT").is_ok());
99
100pub struct Post {
105 pub status: PostStatus,
107}
108
109#[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 pub fn new() -> Self { Post { status: PostStatus::default() } }
121
122 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 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 latexml_core::telemetry::Phase::MathImages
157 } else {
158 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 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 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 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 #[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 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 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 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 #[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<b<c<d'>\
369 <XMath><XMApp><XMTok meaning='multirelation'/>\
370 <XMTok role='ID'>a</XMTok><XMTok meaning='less-than' role='RELOP'><</XMTok>\
371 <XMTok role='ID'>b</XMTok><XMTok meaning='less-than' role='RELOP'><</XMTok>\
372 <XMTok role='ID'>c</XMTok><XMTok meaning='less-than' role='RELOP'><</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}