Skip to main content

latexml_core/
tbox.rs

1use std::{borrow::Cow, fmt, rc::Rc};
2
3use libxml::tree::Node;
4
5use crate::{
6  BoxOps, Digested,
7  common::{
8    arena::{self, SymHashMap as HashMap, SymStr},
9    dimension::Dimension,
10    error::*,
11    font::Font,
12    locator::Locator,
13    object::Object,
14    store::Stored,
15  },
16  document::Document,
17  gullet, pin,
18  state::{lookup_font, with_value},
19  token::{Catcode, Token},
20  tokens::Tokens,
21};
22
23/// Box is a Rust keyword, so we use "Tbox" instead, as in "TeX Box"
24#[derive(Debug, Clone)]
25pub struct Tbox {
26  /// plain-text content
27  pub text:         SymStr,
28  /// associated font for `text`
29  pub font:         Rc<Font>,
30  /// source location where the box originated (`None` = unknown)
31  pub locator:      Option<Locator>,
32  /// misc properties, such as sizing information
33  pub properties:   HashMap<Stored>,
34  /// a Tokens list containing the TeX that created (or could have) the Tbox.
35  pub tokens:       Tokens,
36  /// `isEmpty`, lifted off the property map. The `{`/`}` group markers
37  /// (`tex_box.rs`) and the no-op primitive box carry exactly one property,
38  /// `isEmpty => true`; as a map entry it cost a heap-allocated hashbrown
39  /// table per marker — 1.24 M tables / 421 MB, 16 % of the Rust-heap peak on
40  /// pgf-spectra LSE (dhat, 2026-09-20). `Tbox::new` drains the key into this
41  /// field, so a text-mode marker's map stays empty (no allocation); the
42  /// `isEmpty` readers below consult the field first.
43  pub empty_marker: bool,
44}
45
46impl Default for Tbox {
47  fn default() -> Self {
48    Tbox {
49      text:         pin!(""),
50      font:         Rc::new(Font::text_default()),
51      locator:      None,
52      properties:   HashMap::default(),
53      tokens:       Tokens!(),
54      empty_marker: false,
55    }
56  }
57}
58
59impl PartialEq for Tbox {
60  // Should this compare fonts too?
61  fn eq(&self, other: &Self) -> bool { self.text == other.text && *self.font == *other.font }
62}
63
64//======================================================================
65// Exported constructors
66impl fmt::Display for Tbox {
67  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
68    arena::with(self.text, |text| write!(f, "{}", text))
69  }
70}
71impl Object for Tbox {
72  fn get_locator(&self) -> Option<Locator> { self.locator }
73  fn revert(&self) -> Result<Tokens> { Ok(self.tokens.clone()) }
74  fn stringify(&self) -> String { format!("{self:?}") }
75}
76impl Tbox {
77  /// creates a new Tbox.
78  /// If `font_opt` or `locator_opt` are None, they are obtained from the
79  /// currently active state? Note that `text` can
80  /// be empty, which contributes nothing to the generated document,
81  /// but does record the TeX code (in the tokens).
82  pub fn new(
83    text: SymStr,
84    font_opt: Option<Rc<Font>>,
85    locator_opt: Option<Locator>,
86    tokens_opt: Tokens,
87    mut properties: HashMap<Stored>,
88  ) -> Self {
89    // A text box always has a source position (Perl parity): use the passed
90    // locator, else the gullet's current one. Stored as `Some`.
91    let locator = Some(locator_opt.unwrap_or_else(gullet::get_locator));
92    let mut font = match font_opt {
93      Some(f) => f,
94      None => lookup_font().unwrap(),
95    };
96    let empty_sym = pin!("");
97    let tokens = if text != empty_sym && tokens_opt.is_empty() {
98      Tokens!(Token!(sym text, Catcode::OTHER))
99    } else {
100      tokens_opt
101    };
102
103    // Perl: if ((!defined $properties{isSpace}) && (defined $string) && ($string =~ /^\s*$/)) {
104    //         $properties{isSpace} = 1; }
105    // Auto-mark all-whitespace text as isSpace (matches Perl Box() behavior)
106    if !properties.contains_key("isSpace") && text != empty_sym {
107      let is_all_ws = arena::with(text, |s| {
108        !s.is_empty() && s.chars().all(|c| c.is_whitespace())
109      });
110      if is_all_ws {
111        properties.insert("isSpace", Stored::Bool(true));
112      }
113    }
114
115    if properties.contains_key("isSpace")
116      && (properties.contains_key("width")
117        || properties.contains_key("height")
118        || properties.contains_key("depth"))
119    {
120      properties
121        .entry("width")
122        .or_insert_with(|| Stored::Dimension(Dimension::default()));
123      properties
124        .entry("height")
125        .or_insert_with(|| Stored::Dimension(Dimension::default()));
126      properties
127        .entry("depth")
128        .or_insert_with(|| Stored::Dimension(Dimension::default()));
129    }
130    if crate::state::lookup_bool_sym(crate::pin!("IN_MATH")) {
131      properties.insert("mode", Stored::String(pin!("math")));
132      if text != empty_sym {
133        with_value(
134          &arena::with(text, |text_str| s!("math_token_attributes_{}", text_str)),
135          |value_opt| {
136            if let Some(Stored::HashString(attr)) = value_opt {
137              for (key, value) in attr.iter() {
138                properties
139                  .entry(key)
140                  .or_insert_with(|| Stored::String(arena::pin(value)));
141              }
142            }
143          },
144        );
145      }
146      font = Rc::new(arena::with(text, |text_str| font.specialize(text_str)));
147    }
148    // Lift `isEmpty` off the map (see the field doc); every writer keeps
149    // passing it as a property, so no call site changes.
150    let empty_marker = matches!(properties.get("isEmpty"), Some(Stored::Bool(true)));
151    if empty_marker {
152      properties.remove("isEmpty");
153    }
154    Tbox {
155      text,
156      font,
157      locator,
158      properties,
159      tokens,
160      empty_marker,
161    }
162  }
163  /// Records the font slot `code` this character box was typeset from, when its font is
164  /// measured by its TFM (`Font::measuring_tfm`): the decoded Unicode character no longer
165  /// names the slot (witness 2605.02221). A slot the TFM lacks is measured by its decoded
166  /// character as before (TeX: a missing character, 0pt).
167  pub fn with_tfm_slot(mut self, code: u32) -> Self {
168    if code <= 255 && self.font.measuring_tfm().is_some() {
169      self
170        .properties
171        .insert("tfm_code", Stored::Int(i64::from(code)));
172    }
173    self
174  }
175  /// checks if the text content is empty
176  pub fn is_empty(&self) -> bool {
177    // 1. A space-like thing
178    // 2. empty (or whitespace) text content
179    self.empty_marker
180      || self.get_property_bool("isSpace")
181      || arena::with(self.text, |text| text.trim().is_empty())
182  }
183
184  /// Whether this box is in math mode.
185  /// Perl: Box.pm::isMath (L79-81): `($mode || 'restricted_horizontal') =~ /math$/`.
186  /// Matches "math", "inline_math", "display_math".
187  pub fn is_math(&self) -> bool {
188    match self.properties.get("mode") {
189      Some(Stored::String(s)) => arena::with(*s, |m| m.ends_with("math")),
190      _ => false,
191    }
192  }
193
194  /// Batch-insert properties. Equivalent to calling `set_property` for each
195  /// entry, but avoids re-looking up the properties map per call.
196  /// Perl: Box.pm::setProperties (L171-175).
197  pub fn set_properties<I>(&mut self, entries: I)
198  where I: IntoIterator<Item = (&'static str, Stored)> {
199    for (key, value) in entries {
200      self.properties.insert(key, value);
201    }
202  }
203
204  /// height + depth of this box (the TeX "total height").
205  /// Returns Dimension::default() (0pt) when either component is absent.
206  /// Perl: Box.pm::getTotalHeight (L202-210).
207  pub fn total_height(&self) -> Dimension {
208    let h = match self.properties.get("height") {
209      Some(Stored::Dimension(d)) => d.0,
210      _ => 0,
211    };
212    let d = match self.properties.get("depth") {
213      Some(Stored::Dimension(d)) => d.0,
214      _ => 0,
215    };
216    Dimension(h + d)
217  }
218
219  /// Perl `Box::beAbsorbed`'s text: a math token in math, else text.
220  fn absorb_text(&self, text: &str, document: &mut Document) -> Result<Vec<Node>> {
221    let font = &self.font;
222    let mode = match self.properties.get("mode") {
223      Some(Stored::String(s)) => *s,
224      _ => pin!("text"),
225    };
226
227    if !text.is_empty() {
228      // Perl Box::isMath: `mode =~ /math$/` matches "math" / "inline_math" / "display_math".
229      let mode_is_math = arena::with(mode, |m| m.ends_with("math"));
230      if mode_is_math {
231        // Perl: DefMath ?#isMath — in text context, produce plain text.
232        // Check if we're inside a math element by walking up the DOM.
233        // This handles \And in author frontmatter (text) while preserving
234        // \times inside XMText within math.
235        let in_math_context = {
236          let mut node = document.node.clone();
237          let mut found = false;
238          loop {
239            let qname = crate::document::get_node_qname(&node);
240            let hit = arena::with(qname, |s| s.contains("XM") || s.contains("Math"));
241            if hit {
242              found = true;
243              break;
244            }
245            match node.get_parent() {
246              Some(parent) => node = parent,
247              None => break,
248            }
249          }
250          found
251        };
252        if in_math_context {
253          Ok(vec![document.insert_math_token(
254            text,
255            Stored::cast_to_string_hash(&self.properties),
256            Some(font),
257          )?])
258        } else {
259          // Text fallback: produce plain text (Perl's ?#isMath else branch)
260          match document.open_text(text, font)? {
261            None => Ok(Vec::new()),
262            Some(node) => Ok(vec![node]),
263          }
264        }
265      } else {
266        match document.open_text(text, font)? {
267          None => Ok(Vec::new()),
268          Some(node) => Ok(vec![node]),
269        }
270      }
271    } else {
272      Ok(Vec::new())
273    }
274  }
275}
276
277impl BoxOps for Tbox {
278  fn get_tokens(&self) -> Option<&Tokens> { Some(&self.tokens) }
279  fn get_properties(&self) -> &HashMap<Stored> { &self.properties }
280  fn get_property(&self, key: &str) -> Option<Cow<'_, Stored>> {
281    let props = &self.properties;
282    if key == "isEmpty" && self.empty_marker {
283      Some(Cow::Owned(Stored::Bool(true)))
284    } else if key == "isSpace" {
285      match props.get(key) {
286        Some(value) => Some(Cow::Owned(value.clone())),
287        None => {
288          let tex = self
289            .get_tokens()
290            .map(|tks| tks.clone().untex())
291            .unwrap_or_default(); // !
292          if !tex.is_empty() && tex.chars().all(char::is_whitespace) {
293            // Check the TeX code, not (just) the string!
294            Some(Cow::Owned(Stored::Bool(true)))
295          } else {
296            None
297          }
298        },
299      }
300    } else {
301      props.get(key).map(|v| Cow::Owned(v.clone()))
302    }
303  }
304  fn with_properties<R, FnR>(&self, caller: FnR) -> R
305  where FnR: FnOnce(&HashMap<Stored>) -> R {
306    caller(&self.properties)
307  }
308  fn get_properties_mut(&mut self) -> &mut HashMap<Stored> { &mut self.properties }
309  fn has_property(&self, key: &str) -> bool {
310    (key == "isEmpty" && self.empty_marker) || self.properties.contains_key(key)
311  }
312  fn get_property_bool(&self, key: &str) -> bool {
313    (key == "isEmpty" && self.empty_marker)
314      || matches!(self.properties.get(key), Some(Stored::Bool(true)))
315  }
316  fn get_string(&self) -> Result<Cow<'_, str>> {
317    // TODO: Should we switch these to symbols? are they used often?
318    Ok(Cow::Owned(arena::with(self.text, |text| text.to_string())))
319  }
320
321  fn be_absorbed(&self, document: &mut Document) -> Result<Vec<Node>> {
322    // The text lent from the arena, not copied into a new String per box (MEM1 L4b).
323    arena::with(self.text, |text| self.absorb_text(text, document))
324  }
325
326  fn get_font(&self) -> Result<Option<Rc<Font>>> { Ok(Some(Rc::clone(&self.font))) }
327
328  fn compute_size(&self, options: HashMap<Stored>) -> Result<(Dimension, Dimension, Dimension)> {
329    match self.get_property("body") {
330      Some(body_stored) => {
331        if let Stored::Digested(ref body) = *body_stored {
332          body.compute_size(options)
333        } else {
334          panic!("the stored 'body' property should always be a Stored::Digested enum case.");
335        }
336      },
337      _ => {
338        if let Some(Stored::Int(code)) = self.properties.get("tfm_code")
339          && let Some(tfm) = self.font.measuring_tfm()
340        {
341          let at = (self
342            .font
343            .get_size()
344            .unwrap_or_else(crate::common::font::defsize)
345            * 65536.0)
346            .round() as i64;
347          if let Some((w, h, d)) = tfm.char_dims(*code as u32, at) {
348            return Ok((Dimension(w), Dimension(h), Dimension(d)));
349          }
350        }
351        Ok(self.font.compute_string_size(&self.get_string()?, options))
352      },
353    }
354  }
355}
356
357impl From<Tbox> for Result<Vec<Digested>> {
358  fn from(tbox: Tbox) -> Result<Vec<Digested>> { Ok(vec![Digested::from(tbox)]) }
359}
360impl From<Tbox> for Option<Digested> {
361  fn from(tbox: Tbox) -> Option<Digested> { Some(Digested::from(tbox)) }
362}
363
364#[cfg(test)]
365mod tests {
366  use super::*;
367
368  #[test]
369  fn tbox_default_has_empty_text() {
370    let t = Tbox::default();
371    assert_eq!(arena::to_string(t.text), "");
372    assert_eq!(t.properties.len(), 0);
373    assert_eq!(t.tokens.len(), 0);
374  }
375
376  #[test]
377  fn tbox_display_of_default_is_empty() {
378    let t = Tbox::default();
379    assert_eq!(format!("{t}"), "");
380  }
381
382  #[test]
383  fn tbox_display_of_text_content() {
384    let t = Tbox {
385      text: arena::pin("hello"),
386      ..Default::default()
387    };
388    assert_eq!(format!("{t}"), "hello");
389  }
390
391  #[test]
392  fn tbox_partial_eq_same_text_same_font() {
393    let a = Tbox::default();
394    let b = Tbox::default();
395    assert_eq!(
396      a, b,
397      "two default Tboxes have same text '' and same text_default font"
398    );
399  }
400
401  #[test]
402  fn tbox_partial_eq_different_text() {
403    let a = Tbox::default();
404    let b = Tbox {
405      text: arena::pin("X"),
406      ..Default::default()
407    };
408    assert_ne!(a, b);
409  }
410
411  #[test]
412  fn tbox_default_font_is_text_default() {
413    let t = Tbox::default();
414    // Font::text_default is the Rc backing the default.
415    assert_eq!(*t.font, Font::text_default());
416  }
417
418  #[test]
419  fn tbox_default_locator_is_default() {
420    let t = Tbox::default();
421    // A Default locator points at the crate source file/line where
422    // Default::default was called; just verify it's not nonsense.
423    let _ = t.locator;
424  }
425}
426
427#[cfg(test)]
428mod empty_marker_tests {
429  use super::*;
430
431  /// A `{`/`}` group marker carries `isEmpty` as a field, not as a one-entry
432  /// heap map (the 421 MB class on pgf-spectra LSE), and every reader still
433  /// sees the property.
434  #[test]
435  fn is_empty_marker_lives_off_the_property_map() {
436    arena::force_init();
437    // A bare unit test has no engine: supply the font and locator the
438    // constructor would otherwise read from State/gullet.
439    let font = Some(Rc::new(Font::text_default()));
440    let here = Some(Locator::default());
441    let t = Tbox::new(
442      pin!(""),
443      font.clone(),
444      here,
445      Tokens!(),
446      stored_map!("isEmpty" => true),
447    );
448    assert!(
449      t.properties.is_empty(),
450      "no heap map for the marker: {:?}",
451      t.properties
452    );
453    assert!(t.empty_marker);
454    assert!(t.is_empty());
455    assert!(t.get_property_bool("isEmpty"));
456    assert!(t.has_property("isEmpty"));
457    assert!(matches!(
458      t.get_property("isEmpty").as_deref(),
459      Some(Stored::Bool(true))
460    ));
461    let plain = Tbox::new(pin!("x"), font, here, Tokens!(), HashMap::default());
462    assert!(!plain.empty_marker && !plain.is_empty() && !plain.has_property("isEmpty"));
463  }
464}