Skip to main content

latexml_core/
lib.rs

1//! The core of latexml-oxide: the TeX engine that reads a document and builds its XML, the port of Perl
2//! LaTeXML's `LaTeXML::Core`, `LaTeXML::Common` and the definers of `LaTeXML::Package`.
3//!
4//! A conversion runs through the stages Perl's does: the [`mouth`] turns characters into tokens, the [`gullet`]
5//! expands macros and reads arguments, the [`stomach`] digests tokens into boxes, and the [`document`] builds the XML
6//! from them. The global [`state`] holds every definition ([`definition`]) and value, thread-local per conversion.
7//! The [`binding`] module holds the definers and loaders (`DefMacro`, `DefConstructor`, `RequirePackage`, …) that
8//! the bindings in `latexml_engine` and `latexml_package` are written with.
9//!
10//! Most users want the `latexml` crate, which drives a whole conversion. For the Perl-to-Rust map, read
11//! [ORGANIZATION.md](https://github.com/dginev/latexml-oxide/blob/main/docs/parity/ORGANIZATION.md).
12#![allow(missing_docs)]
13#![allow(clippy::invisible_characters)] // Font metrics contain real zero-width Unicode chars from TFM files
14extern crate rustc_hash;
15
16/// Auxiliary macros
17#[macro_use]
18pub mod aux_macros;
19/// The Token and its Catcode
20#[macro_use]
21pub mod token;
22/// Common abstractions that are useful at various stages of Core processing
23#[macro_use]
24pub mod common;
25pub mod cycle_guard;
26pub mod stack_guard;
27/// Grouping Tokens together
28#[macro_use]
29pub mod tokens;
30/// The programmable API foundation for creating bindings of LaTeX sty/cls libraries
31#[macro_use]
32pub mod binding;
33/// Support for TeX-like Alignments
34pub mod alignment;
35/// TeX comments as standalone objects
36pub mod comment;
37/// All possible definitions for TeX-native commands (expandable, primitive, constructor,...)
38pub mod definition;
39/// a shared interface for digested objects
40pub mod digested;
41/// An abstraction layer over the converted XML document
42pub mod document;
43/// The Gullet is responsible for reading Tokens and other data from the Mouth
44pub mod gullet;
45/// A LaTeX-like Key-Value object
46pub mod keyval;
47/// A collection of Key-Value objects, typically from a single LaTeX argument
48pub mod keyvals;
49/// Rules for combining together characters and other text rules
50pub mod ligature;
51/// A list of `Digested` objects
52pub mod list;
53/// The mouth is a thin interface over a file, responsible for reading characters and associating
54/// them with catcodes
55pub mod mouth;
56/// The abstraction layer used by the Gullet to read arguments for the various kinds of TeX object
57/// definitions
58pub mod parameter;
59/// Rules for rewriting the constructed XML document, after core processing has completed
60pub mod rewrite;
61/// A global, singleton, mutable state - hosts almost all TeX-facing runtime information for the
62/// conversion
63#[macro_use]
64pub mod state;
65/// Code generator: dump file → compiled Rust module
66pub mod dump_codegen;
67/// Reader for Rust-native kernel dump files
68pub mod dump_reader;
69/// Writer for Rust-native kernel dump files
70pub mod dump_writer;
71/// The stomach is an abstraction responsible for digesting `Tokens` and `Register`s prepared by the
72/// Gullet into Boxes
73#[macro_use]
74pub mod stomach;
75
76/// Miri soundness model for the `runtime-bindings` re-entrant trampoline (PR #248
77/// B1). Test-only; the real path is libxml2-backed and cannot be Miri-checked.
78#[cfg(test)]
79mod runtime_bindings_reentrancy_model;
80// sxml and watchdog are documented by their own `//!` alone: an outer doc here as well made stable rustdoc (1.100)
81// resolve the module docs' intra-doc links in this scope, where they fail.
82pub mod sxml;
83/// A TeX-like digested Box
84pub mod tbox;
85/// Per-job structured telemetry: phase wall times, counts, resource peaks.
86/// See `docs/performance/TELEMETRY.md` for the design contract.
87pub mod telemetry;
88/// Auxilary utilities that do not participate in the main conversion abstraction
89pub mod util;
90pub mod watchdog;
91/// A TeX-like digested Whatsit
92pub mod whatsit;
93
94use std::{borrow::Cow, fmt, rc::Rc};
95
96use libxml::tree::Node;
97/// Initialize libxml2 for thread safety. Must be called before any libxml2
98/// operations that don't go through `libxml::parser::Parser`. Delegates to
99/// the safe wrapper in rust-libxml, which uses its own `std::sync::Once` to
100/// guarantee exactly-once initialisation even across threads.
101///
102/// See: <https://dev.w3.org/XInclude-Test-Suite/libxml2-2.4.24/doc/threads.html>
103pub fn ensure_libxml_init() { libxml::init_parser(); }
104
105/// Free this thread's accumulated engine state — the three `State` singletons (`STATE`, `STD_STATE`, `STY_STATE`),
106/// the string-interner arena, the model, gullet, stomach and local assignments, and the per-conversion caches — and
107/// rebuild them empty, as a fresh thread's [`init_thread_engine`] leaves them.
108///
109/// **Why this exists.** The engine's roots are leaked per-thread statics (`thread_root!`/`thread_static!`,
110/// aux_macros.rs): they run no destructor at thread exit, so a thread that converts and exits leaks its engine
111/// (~110 MB for a typical document) unless it resets first. The test harness (a fresh libtest thread per test), the
112/// render and dump workers reset before their thread exits; the library API (`latexml::api`) resets after each call
113/// and keeps the thread for the next one, so a long-lived host holds one rebuilt engine (~36 MB) per parked worker, not
114/// one per call, and a worker about to exit runs [`shrink_thread_engine`] instead. The persistent `cortex_worker`
115/// never resets: it keeps the dump definitions across papers.
116///
117/// **Returns** whether the thread may convert again. The per-thread token and gullet symbol constants (`TOKEN_BEGIN`,
118/// …, token.rs; `DEFERRED_COMMANDS`, `COLUMN_ENDS`) are built once and hold arena symbols; they are pinned again in
119/// creation order into the new arena, and `true` means every one got its old symbol back — always so on a thread that
120/// ran [`init_thread_engine`] before anything else touched the arena. `false`: the thread must not convert again (a
121/// stale constant would alias another string, the phantom-symbol bug class of the REPORT-map fix, 7b64a48ad1).
122///
123/// **Soundness.** Resetting the interner invalidates every live `SymStr` on the thread, so call this only between
124/// fully independent conversions, once the previous conversion's output is owned data. Other symbol-holding
125/// thread-locals are reset here (`reset_conversion_state`, the arena-keyed reports and memos, `pin!` site caches) or
126/// at a conversion's start, or are scoped to a call (stacks popped by guards). Not reclaimed: kpathsea's ls-R/cnf hash
127/// tables, 8.6 MB of C heap allocated once per process.
128pub fn reset_thread_engine() -> bool {
129  common::arena::reset();
130  // The roots rebuilt in the new arena first, in `init_thread_engine`'s order (the States after it: their catcode
131  // templates hold symbols); the per-thread symbol constants, never rebuilt, checked to have their symbols back.
132  let reusable = token::repin_constants();
133  common::model::initialize_model();
134  let reusable = gullet::repin_constants() && reusable;
135  state::reset_thread_state();
136  stomach::set_stomach(Stomach::default());
137  common::local_assignments::initialize_localized();
138  // The error REPORT's `undefined`/`missing` maps are keyed by arena `SymStr`s,
139  // so they MUST be cleared together with the arena — otherwise a stale key
140  // resolves, in the renumbered arena, to a different string (phantom undefined).
141  // (`reset_arena_keyed_reports` is in scope via `pub use crate::common::error::*`.)
142  reset_arena_keyed_reports();
143  // The is_noexpand_family and fontmap-key memos are keyed by arena symbols —
144  // same stale-alias hazard as the REPORT maps; clear them with the arena.
145  token::reset_noexpand_family_memo();
146  binding::content::reset_fontmap_key_memo();
147  reset_conversion_state();
148  reusable
149}
150
151/// Empty this thread's engine roots to their smallest values, for a thread about to exit: the roots are leaked
152/// statics (no destructor at thread exit), so a thread that exits after [`reset_thread_engine`] leaves its rebuilt
153/// engine behind (~36 MB: the 2^17-slot interner, the three dump-sized States); after this, little more than the
154/// roots' boxes. The thread must not convert again. The library API's workers run it before they exit (retired,
155/// evicted, or after a panic); allocation-light, it needs no destructor and no `unsafe` (STABLE1 APIPOOL).
156pub fn shrink_thread_engine() {
157  common::local_assignments::initialize_localized();
158  stomach::set_stomach(Stomach::default());
159  gullet::shrink();
160  state::shrink_thread_state();
161  *common::model::MODEL.borrow_mut() = Model::default();
162  reset_arena_keyed_reports();
163  *REPORT.borrow_mut() = LogState::default();
164  shrink_error_notes();
165  util::logger::shrink();
166  token::reset_noexpand_family_memo();
167  binding::content::reset_fontmap_key_memo();
168  reset_conversion_state();
169  // Last: the roots above held symbols of the arena it replaces.
170  common::arena::shrink();
171}
172
173/// Build this thread's engine roots in dependency order (arena, token constants, model, gullet, catcode templates),
174/// as every conversion's `Core::new` does first. A thread that runs this before its first conversion may run more
175/// after [`reset_thread_engine`] (which returns `true` there): the constants get back the symbols they hold.
176pub fn init_thread_engine() {
177  common::arena::force_init(); // leaf
178  token::force_init(); // token constants -> arena
179  common::model::force_init(); // Model::new -> arena
180  gullet::force_init(); // DEFERRED_COMMANDS / COLUMN_ENDS / GULLET -> arena
181  state::force_init(); // STD_STATE / STY_STATE templates -> arena
182}
183
184/// Release the TeX engine's thread-local state (`STATE`, `STOMACH`, `GULLET`,
185/// `StringInterner` arena, and per-conversion caches) after `MakeBibliography`
186/// completes and before the render phases (`parallel_render`, `CrossRef`,
187/// `Graphics`, `MathML`, `XSLT`), while keeping `REPORT` (including
188/// `undefined`/`missing` macro/file tallies), `LOGGER`, `telemetry`, and
189/// watchdog/deadline limits intact.
190///
191/// On a large split book, dead core engine state can retain gigabytes in the
192/// parent process throughout post-processing, starving `parallel_render`'s
193/// worker memory budget (`RENDERFLEETBIG`).
194///
195/// **Safety / ordering contract:**
196/// 1. Call ONLY **after** `MakeBibliography` finishes — `MakeBibliography`
197///    reads virtual `.bib` files (`VFS_KEY`) and runs recursive `.bib`
198///    digestion against live `STATE` (author preamble macros and
199///    `lx@bibliography@normalfont`, OD #779).
200/// 2. Call ONLY in a one-shot process/thread that will NOT re-enter the TeX
201///    engine afterward (see the reuse contract on
202///    [`reset_thread_engine`]).
203pub fn release_core_state_for_post() {
204  let post_values = PostStateValues::capture();
205  preserve_arena_keyed_reports_across(|| {
206    common::local_assignments::initialize_localized();
207    gullet::initialize_gullet();
208    stomach::initialize_stomach();
209    state::reset_thread_state();
210    common::arena::reset();
211    token::reset_noexpand_family_memo();
212    binding::content::reset_fontmap_key_memo();
213    reset_conversion_state();
214  });
215  post_values.restore();
216}
217
218/// The STATE values the render phases still read once the engine's state is
219/// released ([`release_core_state_for_post`]) or, in a page-render worker
220/// process, never built:
221/// - `NOMINAL_FONT_SIZE`: `font::defsize()` ← `Font::math_default()`, the
222///   MathML presentation's negative-space `<mpadded>` widths on documents whose
223///   nominal font size differs from 10pt (a0poster's 25pt, 11pt/12pt classes;
224///   `latexml_post/src/mathml/presentation.rs`);
225/// - `MAX_ERRORS`: the error cap, `error::note_error_cap()` / `Error!` (tikz
226///   raises it from 100 to 1000).
227#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
228pub struct PostStateValues {
229  pub nominal_font_size: Option<f64>,
230  pub max_errors:        Option<i64>,
231}
232
233impl PostStateValues {
234  /// Read the values from this thread's STATE.
235  pub fn capture() -> Self {
236    PostStateValues {
237      nominal_font_size: state::lookup_float("NOMINAL_FONT_SIZE").map(|f| f.0),
238      max_errors:        state::try_lookup_int("MAX_ERRORS"),
239    }
240  }
241
242  /// Assign the captured values globally in this thread's STATE.
243  pub fn restore(self) {
244    if let Some(sz) = self.nominal_font_size {
245      state::assign_value(
246        "NOMINAL_FONT_SIZE",
247        common::float::Float(sz),
248        Some(state::Scope::Global),
249      );
250    }
251    if let Some(max) = self.max_errors {
252      state::assign_value("MAX_ERRORS", max, Some(state::Scope::Global));
253    }
254  }
255}
256
257/// Forgets what one conversion leaves on its thread for the next, as Perl builds a fresh State per document
258/// (LaTeXML.pm:232): a persistent `cortex_worker` converts its papers on one thread. Called at each conversion's start
259/// ([`initialize_report`]) and by [`reset_thread_engine`]. Not every per-conversion reset: the gullet's, the math
260/// parser's, the telemetry's and the rescued boxes' are in `Core::initialize_singletons`, the engine crate's (the fm
261/// reading, the title-page check, the pdfTeX random generators) in `Converter::initialize_session`; a stack a guard
262/// pops on unwinding needs none.
263pub fn reset_conversion_state() {
264  // The deferred diagnostics and the unknown KeyVals keys reported (each reported once per conversion, ST3).
265  util::logger::reset_deferred_diagnostics();
266  keyvals::reset_unknown_keys_reported();
267  // A speculative scope's log muting (`SuppressLogOutputGuard`) ends with the conversion.
268  reset_suppress_log_output();
269  // Lookups memoized per conversion: a cwd-relative kpsewhich miss, case-insensitive dir listings,
270  // an image's size, a font's metrics.
271  util::pathname::clear_kpsewhich_memo();
272  util::pathname::clear_nocase_dir_cache();
273  util::image::clear_image_size_memo();
274  common::font::tfm::reset_tfm_cache();
275  // The frontmatter fields' provenance (OXIDIZED_DESIGN #715), the files read raw and the stand-in copies'
276  // provides-modes (#731).
277  document::reset_field_provenance();
278  binding::content::reset_raw_read_paths();
279  definition::origin::reset_copy_provides();
280  // A planned `\lx@refstepcounter` step a panic unwound past (`take_pending_step` never ran) would type the next
281  // paper's first step on that counter.
282  binding::counter::dialect::reset_refstep_state();
283  // A predecessor's spent "Mouth is unexpectedly already closed" budget made the next paper's first one a Fatal.
284  gullet::reset_mouth_closed_errors();
285  binding::content::reset_subfile_package_load();
286  binding::kernel_autoload::reset_undefined_fallback();
287  binding::kernel_autoload::reset_first_use_providers();
288  // A stashed Fatal (`stomach::stash_fatal`) is the conversion's: an LSP re-warm or a post release does not inherit it.
289  stomach::set_aside_stashed_fatal();
290  #[cfg(feature = "token-locators")]
291  token::clear_token_origins();
292}
293
294pub use crate::common::error::*;
295use crate::{
296  common::{
297    arena::SymHashMap as HashMap, dimension::Dimension, font::Font, locator::Locator, model::Model,
298    numeric_ops::NumericOps, object::Object, store::Stored,
299  },
300  definition::register::RegisterValue,
301  digested::{Digested, DigestedData},
302  document::Document,
303  state::{State, StateOptions, set_state},
304  stomach::Stomach,
305  tbox::Tbox,
306  tokens::Tokens,
307};
308
309/// The empty property map of an object that has none. A `const` reference, not a `static`: a static needs `Sync`, which
310/// `Stored` (it holds `Rc`s and libxml nodes) is not; the empty map holds no `Stored`, so every thread may read it.
311pub const NO_PROPERTIES: &HashMap<Stored> = &common::arena::SymHashMap(
312  rustc_hash::FxHashMap::with_hasher(rustc_hash::FxBuildHasher),
313);
314
315/// The Core conversion runtime
316pub struct Core {
317  /// a list of library names to be preloaded before the main conversion begins
318  pub preload: Vec<String>,
319}
320
321/// Configuration for the Core processing
322#[derive(Default)]
323pub struct CoreOptions {
324  // First, state::related options:
325  /// a custom schema-induced model (default is `None`) for the final XML
326  pub model:            Option<Model>,
327  /// default is 0, sub-zero values are quiet, positive values are verbose
328  pub verbosity:        Option<i32>,
329  /// strict error-reporting (is this still used?)
330  pub strict:           Option<bool>,
331  /// toggle preserving comments in the XML on/off
332  pub include_comments: Option<bool>,
333  /// toggle loading raw .sty modules on/off
334  pub include_styles:   Option<bool>,
335  /// disable math parsing (enabled by default)
336  pub nomathparse:      Option<bool>,
337  /// enable source-locator (`--source-map`) tracking + emission (off by
338  /// default). See `docs/performance/SOURCE_PROVENANCE.md`.
339  pub source_map:       Option<bool>,
340  /// an optional, fixed id prefix for all xml:id attributes
341  pub documentid:       Option<String>,
342  /// the list of paths used for loading TeX sources and packages
343  pub search_paths:     Option<Vec<String>>,
344  /// the list of paths used for loading graphics assets
345  pub graphics_paths:   Option<Vec<String>>,
346  /// set an explicit encoding of the input text
347  pub input_encoding:   Option<String>,
348  /// a list of package names to preload before processing start
349  pub preload:          Option<Vec<String>>,
350}
351
352/// A size property as a Dimension: a Dimension itself, a Glue's natural size, and a MuGlue/MuDimension in scaled
353/// points at the current font size (TeX's `math_kern`, tex.web §717); `None` for anything else.
354pub fn stored_dimension(s: Option<&Stored>) -> Option<Dimension> {
355  match s? {
356    Stored::Number(_) => None,
357    value => value.into(),
358  }
359}
360
361impl Core {
362  /// instantiate a new Core processor
363  pub fn new(options: CoreOptions) -> Self {
364    // Eagerly initialize the engine's per-thread roots, LEAVES-FIRST,
365    // on THIS thread before any of them is touched re-entrantly. ARENA is the
366    // universal leaf (every root's initializer interns via arena::pin);
367    // the token constants, MODEL, the gullet roots and the STD/STY catcode
368    // templates all reach into ARENA (and the gullet/template roots build
369    // tokens). Forcing them in dependency order up front — before
370    // `set_stomach`/`set_state` below trigger their own initializers, and
371    // before expansion lazily touches the gullet/catcode roots mid-run —
372    // guarantees no root's init (`thread_root!`/`thread_static!`) ever runs another root's init
373    // *re-entrantly*. That cross-root-during-init pattern is
374    // benign on Linux/ELF TLS but is the documented macOS hazard
375    // (rust-lang/rust#29594) behind the macOS worker-thread memory
376    // corruption in issue #217 (varying garbage node types → panics /
377    // SIGSEGV / SIGBUS, only on macOS, only in libtest's worker threads —
378    // the single-conversion main-thread CLI was never affected). Forcing
379    // just ARENA+MODEL cut the failures 4→1; this completes the set. No
380    // behavioral change on Linux (these all initialize during any
381    // conversion anyway — this only fixes the ORDER).
382    init_thread_engine();
383    let preload = options.preload.unwrap_or_default();
384    // pass on the state::options, defaults are handled in state::new
385    let state_options = StateOptions {
386      model: options.model,
387      verbosity: options.verbosity,
388      strict: options.strict,
389      include_comments: options.include_comments,
390      documentid: options.documentid,
391      search_paths: options.search_paths,
392      graphics_paths: options.graphics_paths,
393      include_styles: options.include_styles,
394      input_encoding: options.input_encoding,
395      nomathparse: options.nomathparse,
396      source_map: options.source_map,
397      ..StateOptions::default()
398    };
399    stomach::set_stomach(Stomach::default());
400    set_state(State::new(state_options));
401    Core { preload }
402  }
403}
404/// Common operations for Box-like (digested) data
405pub trait BoxOps: Object {
406  /// If composite, unwrap into the contained digested objects (or return self)
407  fn unlist(&self) -> Vec<Digested> { Vec::new() }
408  fn unlist_ref(&self) -> Vec<Cow<'_, Digested>> { Vec::new() }
409  /// absorb the current object into the `Document` XML - returning the corresponding nodes
410  fn be_absorbed(&self, document: &mut Document) -> Result<Vec<Node>>;
411  /// be_absorbed but with allowed side-effects on the carrier (for `Alignment` only)
412  fn be_absorbed_mut(&mut self, _document: &mut Document) -> Result<Vec<Node>> {
413    self.be_absorbed(_document)
414  }
415  /// build a string representation of the underlying digested data
416  fn get_string(&self) -> Result<Cow<'_, str>>;
417  /// get the underlying tokens (preceding digestion)
418  fn get_tokens(&self) -> Option<&Tokens> { None }
419  /// deprecated: get the map of named properties. This can not be usable as long as we have any
420  /// data behind a RefCell wrapper.
421  /// Use `with_properties` instead.
422  fn get_properties(&self) -> &HashMap<Stored> { NO_PROPERTIES }
423
424  /// execute a function using this object's named properties
425  fn with_properties<R, FnR>(&self, caller: FnR) -> R
426  where FnR: FnOnce(&HashMap<Stored>) -> R;
427  /// get a mutable reference to the map of named properties
428  fn get_properties_mut(&mut self) -> &mut HashMap<Stored> {
429    panic!("get_properties_mut called on type without mutable properties");
430  }
431  /// set a named property (allows all `Stored` types for values)
432  fn set_property<T: Into<Stored>>(&mut self, key: &str, value: T) {
433    self.get_properties_mut().insert(key, value.into());
434  }
435  /// [`BoxOps::set_property`] for a memo — a value the box can compute again — which a box busy elsewhere (being
436  /// absorbed) does without, where Perl's plain hash store (Box.pm:294-296) always lands.
437  fn set_memo_property<T: Into<Stored>>(&mut self, key: &str, value: T) {
438    self.set_property(key, value);
439  }
440  /// get a single named property (with special "isSpace" check)
441  fn get_property(&self, key: &str) -> Option<Cow<'_, Stored>> {
442    self.with_properties(|props| {
443      if key == "isSpace" {
444        match props.get(key) {
445          Some(value) => Some(Cow::Owned(value.clone())),
446          None => {
447            let tex = self
448              .get_tokens()
449              .map(|tks| tks.clone().untex())
450              .unwrap_or_default(); // !
451            if !tex.is_empty() && tex.chars().all(char::is_whitespace) {
452              // Check the TeX code, not (just) the string!
453              Some(Cow::Owned(Stored::Bool(true)))
454            } else {
455              None
456            }
457          },
458        }
459      } else {
460        props.get(key).map(|v| Cow::Owned(v.clone()))
461      }
462    })
463  }
464  fn get_property_string(&self, key: &str) -> String {
465    self
466      .get_property(key)
467      .map(|v| v.to_string())
468      .unwrap_or_default()
469  }
470  /// get a mutable reference to a single named property (does NOT have the "isSpace" check)
471  fn get_property_mut(&mut self, key: &str) -> Option<&mut Stored> {
472    self.get_properties_mut().get_mut(key)
473  }
474  /// checks if a property key has been set
475  fn has_property(&self, key: &str) -> bool {
476    self.with_properties(|props| props.contains_key(key))
477  }
478  /// obtains a boolean property value (false unless `Stored::Bool`)
479  fn get_property_bool(&self, key: &str) -> bool {
480    self.with_properties(|props| matches!(props.get(key), Some(Stored::Bool(true))))
481  }
482  /// obtains the "body" of a digested object which captured it
483  fn get_body(&self) -> Result<Option<Digested>> {
484    Error!(
485      "boxops",
486      "get_body",
487      "Generic BoxOps::get_body should never be called!"
488    );
489    Ok(None)
490  }
491  /// gets the associated font, if any
492  fn get_font(&self) -> Result<Option<Rc<Font>>>;
493  /// sets an associated font
494  fn set_font(&mut self, _font: Rc<Font>) { /* no-op for types without font */
495  }
496  /// sets a "width" property, for sizing
497  fn set_width<T: Into<Stored>>(&mut self, width: T) { self.set_property("width", width); }
498
499  // For the dimensions of boxes, we'll store the (lazily) computed size as:
500  //    cached_width, cached_height, cached_depth
501  // and the explicitly requested/assigned size as
502  //    width, height, depth.
503  // Generally speaking, an XML element should only get width, height, depth
504  // attributes when they were explicitly set.
505  // However, when requesting the size of a box, you'd get either (w/ explicit size overriding)
506
507  /// gets the "width" property value, if any
508  fn get_width(&self, options: Option<HashMap<Stored>>) -> Result<Option<RegisterValue>> {
509    if !self.has_property("width") && !self.has_property("cached_width") {
510      // TODO: Restore caching?
511      // self.compute_size_store(options.unwrap_or_default())?
512      let (w, ..) = self.compute_size(options.unwrap_or_default())?;
513      return Ok(Some(RegisterValue::Dimension(w)));
514    }
515
516    // A declared width that is no dimension (a String attribute: diagbox, `\rotate[f]`) falls through; a mu width is
517    // read in pt (`\hbox{\,}` 1.66663pt).
518    let declared =
519      |key: &str| stored_dimension(self.get_property(key).as_deref()).map(RegisterValue::Dimension);
520    Ok(
521      match declared("width").or_else(|| declared("cached_width")) {
522        Some(width) => Some(width),
523        None => Some(RegisterValue::Dimension(
524          self.compute_size(options.unwrap_or_default())?.0,
525        )),
526      },
527    )
528  }
529  /// sets a "height" property value, for sizing
530  fn set_height<T: Into<Stored>>(&mut self, width: T) { self.set_property("height", width); }
531  /// gets the "height" property value, if any.
532  /// Checks "height", then "cached_height", then computes from font if needed.
533  fn get_height(&self) -> Option<RegisterValue> {
534    let declared =
535      |key: &str| stored_dimension(self.get_property(key).as_deref()).map(RegisterValue::Dimension);
536    declared("height")
537      .or_else(|| declared("cached_height"))
538      .or_else(|| match self.compute_size(HashMap::default()) {
539        Ok((_, h, _)) => Some(RegisterValue::Dimension(h)),
540        _ => Some(RegisterValue::Dimension(Dimension::default())),
541      })
542  }
543  /// sets a "depth" property value, for sizing
544  fn set_depth<T: Into<Stored>>(&mut self, width: T) { self.set_property("depth", width); }
545  /// gets the "depth" property value, if any.
546  /// Checks "depth", then "cached_depth", then computes from font if needed.
547  fn get_depth(&self) -> Option<RegisterValue> {
548    let declared =
549      |key: &str| stored_dimension(self.get_property(key).as_deref()).map(RegisterValue::Dimension);
550    declared("depth")
551      .or_else(|| declared("cached_depth"))
552      .or_else(|| match self.compute_size(HashMap::default()) {
553        Ok((_, _, d)) => Some(RegisterValue::Dimension(d)),
554        _ => Some(RegisterValue::Dimension(Dimension::default())),
555      })
556  }
557  /// gets the box size as a triple of (width, height, depth)
558  /// the generic implementation is immutable and will recompute the size on each call
559  /// see `Digested::get_size` for a variant with interior mutability which caches the box size
560  fn get_size(
561    &mut self,
562    options: Option<HashMap<Stored>>,
563  ) -> Result<(
564    Dimension,
565    Dimension,
566    Dimension,
567    Dimension,
568    Dimension,
569    Dimension,
570  )> {
571    // TODO: Reintroduce caching?
572    // The size just computed stands in for a memo the box could not keep (`set_memo_property`: busy elsewhere).
573    let computed = if !(self.has_property("cached_width")
574      && self.has_property("cached_height")
575      && self.has_property("cached_depth"))
576    {
577      Some(self.compute_size_and_cache(options.unwrap_or_default())?)
578    } else {
579      None
580    };
581    let computed_width = computed.map(|c| Stored::from(c.0));
582    let computed_height = computed.map(|c| Stored::from(c.1));
583    let computed_depth = computed.map(|c| Stored::from(c.2));
584    self.with_properties(|props| {
585      let (width, height, depth, cached_width, cached_height, cached_depth) = (
586        props.get("width"),
587        props.get("height"),
588        props.get("depth"),
589        props.get("cached_width").or(computed_width.as_ref()),
590        props.get("cached_height").or(computed_height.as_ref()),
591        props.get("cached_depth").or(computed_depth.as_ref()),
592      );
593
594      // eprintln!("SIZE of {} {}", std::any::type_name::<Self>(), self.get_string()?);
595      //     . "\n preassigned: " . _showsize($$props{width},  $$props{height},  $$props{depth})
596      //     . "\n calculated : " . _showsize($$props{cached_width}, $$props{cached_height},
597      // $$props{cached_depth})     . "\n w/options " . join(',', map { $_ . "=" .
598      // ToString($options{$_}); } sort keys %options)     . "\n =>: " .
599      // _showsize($$props{width} || $$props{cached_width}, $$props{height}
600      // || $$props{cached_height}, $$props{depth} || $$props{cached_depth})     . "\n   Of " .
601      // ToString($self)) if $LaTeXML::DEBUG{size};
602      Ok((
603        stored_dimension(width)
604          .unwrap_or_else(|| stored_dimension(cached_width).unwrap_or_default()),
605        stored_dimension(height)
606          .unwrap_or_else(|| stored_dimension(cached_height).unwrap_or_default()),
607        stored_dimension(depth)
608          .unwrap_or_else(|| stored_dimension(cached_depth).unwrap_or_default()),
609        stored_dimension(cached_width)
610          .unwrap_or_else(|| stored_dimension(width).unwrap_or_default()),
611        stored_dimension(cached_height)
612          .unwrap_or_else(|| stored_dimension(height).unwrap_or_default()),
613        stored_dimension(cached_depth)
614          .unwrap_or_else(|| stored_dimension(depth).unwrap_or_default()),
615      ))
616    })
617  }
618
619  /// computes and caches (via named properties) the size of a box-like object,
620  /// Perl's `computeSizeStore` (Box.pm:266-297). A box whose size is completely
621  /// specified keeps that size, and its contents are not measured (:275-281):
622  /// width, height and depth all given, a space's width, or a vertical space's
623  /// height or depth. A pgf picture declares its size, and sizing a box that
624  /// holds one walked every drawing box of it (pgf-spectraPreviewDataLSE, 56kq).
625  /// Perl #2798 (S5, padding slice): the size then takes any requested
626  /// `pad{top,bottom,left,right}` (display math
627  /// `\abovedisplayskip`/`\belowdisplayskip`, `\overline`/`\underline` 2pt,
628  /// items/equations). Not ported: a partly specified size keeping its given
629  /// parts over the computed ones, and `isEmpty` — a mechanical port of those
630  /// regressed (Rust boxes don't use width/height/depth uniformly as "requested
631  /// box size"; `docs/archive/UPSTREAM_SYNC_2767_to_2833_2026-06-26.md`, U2 and
632  /// slice S5); tracked with K18 in `docs/SYNC_STATUS.md`.
633  fn compute_size_and_cache(
634    &mut self,
635    mut options: HashMap<Stored>,
636  ) -> Result<(Dimension, Dimension, Dimension)> {
637    for key in [
638      "width",
639      "height",
640      "depth",
641      "vattach",
642      "layout",
643      "totalheight",
644      "padtop",
645      "padbottom",
646      "padleft",
647      "padright",
648    ] {
649      if let Some(v) = self.get_property(key) {
650        options.insert(key, v.into_owned());
651      }
652    }
653
654    let requested = |key: &str| stored_dimension(options.get(key));
655    let flag =
656      |key: &str| self.with_properties(|props| matches!(props.get(key), Some(Stored::Bool(true))));
657    let (is_space, is_vertical_space) = (flag("isSpace"), flag("isVerticalSpace"));
658    let (mut w, mut h, mut d) = match (requested("width"), requested("height"), requested("depth"))
659    {
660      (Some(w), Some(h), Some(d)) => (w, h, d),
661      (Some(w), h, d) if is_space => (w, h.unwrap_or_default(), d.unwrap_or_default()),
662      (w, h, d) if (h.is_some() || d.is_some()) && is_vertical_space => (
663        w.unwrap_or_default(),
664        h.unwrap_or_default(),
665        d.unwrap_or_default(),
666      ),
667      _ => self.compute_size(options.clone())?,
668    };
669    // Perl: add requested padding to the computed size.
670    fn pad_sp(s: Option<&Stored>) -> i64 {
671      match s {
672        Some(Stored::Dimension(d)) => d.value_of(),
673        Some(Stored::Glue(g)) => g.value_of(),
674        Some(Stored::Int(i)) => *i,
675        _ => 0,
676      }
677    }
678    let (padl, padr, padt, padb) = (
679      pad_sp(options.get("padleft")),
680      pad_sp(options.get("padright")),
681      pad_sp(options.get("padtop")),
682      pad_sp(options.get("padbottom")),
683    );
684    if padl != 0 || padr != 0 {
685      w = Dimension::new(w.value_of() + padl + padr);
686    }
687    if padt != 0 {
688      h = Dimension::new(h.value_of() + padt);
689    }
690    if padb != 0 {
691      d = Dimension::new(d.value_of() + padb);
692    }
693
694    // A memo: a box sized while it is being absorbed (an auto-closed `ltx:picture` measuring the `{picture}` whose
695    // body closed it, 1111.1991) is sized again when asked (`set_memo_property`).
696    if !self.has_property("cached_width") {
697      self.set_memo_property("cached_width", w);
698    }
699    if !self.has_property("cached_height") {
700      self.set_memo_property("cached_height", h);
701    }
702    if !self.has_property("cached_depth") {
703      self.set_memo_property("cached_depth", d);
704    }
705    Ok((w, h, d))
706  }
707
708  /// computes and returns the size of a box-like object
709  fn compute_size(&self, options: HashMap<Stored>) -> Result<(Dimension, Dimension, Dimension)>;
710}
711
712/// The current TeX processing mode
713#[derive(Debug, Clone, PartialEq, Eq)]
714pub enum TexMode {
715  /// TeX's math mode
716  Math,
717  /// TeX's text mode
718  Text,
719}
720
721#[cfg(test)]
722mod release_for_post_tests {
723  use super::*;
724  use crate::common::{
725    arena,
726    error::{LogStatus, get_status_code, get_status_message, initialize_report, note_status},
727  };
728
729  #[test]
730  fn release_core_state_for_post_shrinks_arena_and_preserves_report() {
731    initialize_report();
732    // Intern a burst of transient conversion strings.
733    let before_burst = arena::len();
734    for i in 0..2_000 {
735      let _ = arena::pin(format!("__transient_perf_test_sym_{i}__"));
736    }
737    assert!(
738      arena::len() >= before_burst + 2_000,
739      "transient strings should grow the arena"
740    );
741
742    note_status(LogStatus::Undefined, Some("\\myundefmacro"));
743    note_status(LogStatus::Undefined, Some("\\myundefmacro"));
744    note_status(LogStatus::Missing, Some("missing_pkg.sty"));
745    emit_warn("test", "sample", "a warning");
746    emit_error("test", "sample", "an error");
747    state::assign_value(
748      "NOMINAL_FONT_SIZE",
749      common::float::Float(10.95),
750      Some(state::Scope::Global),
751    );
752    state::assign_value("MAX_ERRORS", 1000i64, Some(state::Scope::Global));
753
754    let msg_before = get_status_message();
755    let code_before = get_status_code();
756    let warn_before = get_status(LogStatus::Warning);
757    let err_before = get_status(LogStatus::Error);
758
759    release_core_state_for_post();
760
761    assert!(
762      arena::len() < before_burst + 100,
763      "arena should shrink back near pinned baseline after release (len={}, before_burst={})",
764      arena::len(),
765      before_burst
766    );
767    assert_eq!(get_status_code(), code_before);
768    assert_eq!(get_status(LogStatus::Warning), warn_before);
769    assert_eq!(get_status(LogStatus::Error), err_before);
770    assert_eq!(
771      get_status_message(),
772      msg_before,
773      "status message (including undefined/missing tallies) must remain byte-identical"
774    );
775    assert!(msg_before.contains("\\myundefmacro"));
776    assert!(msg_before.contains("missing_pkg.sty"));
777    assert_eq!(
778      common::font::defsize(),
779      10.95,
780      "NOMINAL_FONT_SIZE must survive release for MathML <mpadded> sizing"
781    );
782    assert_eq!(
783      state::try_lookup_int("MAX_ERRORS"),
784      Some(1000),
785      "MAX_ERRORS must survive release for post-processing error cap"
786    );
787  }
788}