Skip to main content

latexml_core/
list.rs

1use std::{borrow::Cow, fmt, rc::Rc};
2
3use libxml::tree::Node;
4
5use crate::{
6  BoxOps, Digested, TexMode,
7  common::{
8    arena::SymHashMap as HashMap, dimension::Dimension, error::*, font::Font, locator::Locator,
9    object::Object, store::Stored,
10  },
11  document::Document,
12  pin,
13  tokens::Tokens,
14};
15
16/// Lists can contain any Digested items, such as boxes, whatsits or other lists
17#[derive(Clone, Default)]
18pub struct List {
19  pub boxes:      Vec<Digested>,
20  pub mode:       Option<TexMode>,
21  /// The list's font. `Rc`-shared (like [`crate::tbox::Tbox::font`]): fonts
22  /// repeat massively across a document, and storing the 328-byte [`struct@Font`]
23  /// by value in every list box dominated the digested-box footprint (issue #361
24  /// memory pass). Set once at construction; never mutated in place.
25  pub font:       Option<Rc<Font>>,
26  pub locator:    Option<Locator>,
27  pub properties: HashMap<Stored>,
28}
29
30impl fmt::Debug for List {
31  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
32    write!(
33      f,
34      "{}",
35      self
36        .boxes
37        .iter()
38        .map(|d| d.stringify())
39        .collect::<Vec<_>>()
40        .join(", ")
41    )
42  }
43}
44
45impl fmt::Display for List {
46  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
47    for inner in self.boxes.iter() {
48      write!(f, "{inner}")?;
49    }
50    Ok(())
51  }
52}
53
54impl PartialEq for List {
55  fn eq(&self, other: &Self) -> bool {
56    self.boxes.len() == other.boxes.len()
57      && self
58        .boxes
59        .iter()
60        .zip(other.boxes.iter())
61        .all(|(box1, box2)| box1 == box2)
62  }
63}
64
65impl Object for List {
66  fn stringify(&self) -> String { format!("List[{self:?}]") }
67  fn get_locator(&self) -> Option<Locator> { self.locator }
68
69  fn revert(&self) -> Result<Tokens> {
70    // Seed with one-token-per-box (a lower bound) so the per-box `extend` loop
71    // starts past the first few doubling reallocations (a `grow_one` site).
72    let mut reverted = Vec::with_capacity(self.boxes.len());
73    for tbox in self.boxes.iter() {
74      reverted.extend(tbox.revert()?.unlist());
75    }
76    Ok(Tokens::new(reverted))
77  }
78}
79impl BoxOps for List {
80  fn unlist(&self) -> Vec<Digested> { self.boxes.clone() }
81  fn unlist_ref(&self) -> Vec<Cow<'_, Digested>> { self.boxes.iter().map(Cow::Borrowed).collect() }
82  fn get_properties(&self) -> &HashMap<Stored> { &self.properties }
83  fn get_property(&self, key: &str) -> Option<Cow<'_, Stored>> {
84    self.properties.get(key).map(Cow::Borrowed)
85  }
86  fn with_properties<R, FnR>(&self, caller: FnR) -> R
87  where FnR: FnOnce(&HashMap<Stored>) -> R {
88    caller(&self.properties)
89  }
90  fn get_properties_mut(&mut self) -> &mut HashMap<Stored> { &mut self.properties }
91  fn set_property<T: Into<Stored>>(&mut self, key: &str, value: T) {
92    self.properties.insert(key, value.into());
93  }
94  fn get_string(&self) -> Result<Cow<'_, str>> { Ok(Cow::Owned(self.to_string())) }
95  /// NOTE: No longer used; Document->absorb bypasses this for stack efficiency.
96  /// If called directly, absorb each box individually.
97  fn be_absorbed(&self, document: &mut Document) -> Result<Vec<Node>> {
98    for box_item in &self.boxes {
99      document.absorb(box_item, None)?;
100    }
101    Ok(Vec::new())
102  }
103
104  fn get_font(&self) -> Result<Option<Rc<Font>>> { Ok(self.font.clone()) }
105  fn compute_size(
106    &self,
107    mut options: HashMap<Stored>,
108  ) -> Result<(Dimension, Dimension, Dimension)> {
109    let font = self
110      .font
111      .clone()
112      .unwrap_or_else(|| Rc::new(Font::text_default()));
113    // Perl: pass mode, vattach, and width from List properties through options
114    // so that compute_boxes_size can determine layout mode
115    //
116    // In Perl, List stores mode as a property string ("horizontal", "restricted_horizontal",
117    // "internal_vertical"). In Rust, we have: list.mode = TexMode::Text for horizontal modes.
118    // The actual mode string may be stored as a property, OR we infer from context:
119    //  - If "width" property is set, this is a horizontal-mode List (paragraph layout)
120    //  - Otherwise, default to "restricted_horizontal"
121    if let Some(mode_str) = self.properties.get("mode") {
122      if let Stored::String(s) = mode_str {
123        options.insert("mode", Stored::String(*s));
124      }
125    } else if self.properties.get("width").is_some() && matches!(self.mode, Some(TexMode::Text)) {
126      // Lists with width property set are from horizontal mode (paragraph layout)
127      options.insert("mode", Stored::String(pin!("horizontal")));
128    }
129    if let Some(Stored::String(s)) = self.properties.get("vattach") {
130      options.insert("vattach", Stored::String(*s));
131    }
132    // A horizontal list is a paragraph only at its OWN width (Perl
133    // computeBoxesSize, Font.pm:661, 683: `$boxes->getProperty('width')`,
134    // never `$options{width}`). A width passed in the options is the enclosing
135    // box's requested size (`compute_size_and_cache`), which must not break the
136    // contents' lines: `\makebox[1em]{aaa bbb ccc ddd}` measured 4.3pt high and
137    // 36pt deep, set as a 1em paragraph (TeX and Perl: 6.94pt, 0pt). Witness:
138    // the bxcalc manual's measured boxes (sample-bxcalc, batch 56kf).
139    match self.properties.get("width") {
140      Some(width) => {
141        options.insert("width", width.clone());
142      },
143      None => {
144        options.remove("width");
145      },
146    }
147    // Perl #2798 (S6): pass the List's recorded \baselineskip (set by S4 in
148    // repack_horizontal) so compute_boxes_size can stack lines with the right
149    // inter-line spacing.
150    if let Some(baseline) = self.properties.get("baseline")
151      && options.get("baseline").is_none()
152    {
153      options.insert("baseline", baseline.clone());
154    }
155    // A vertical box's `\lineskip` and `\lineskiplimit` (base_utilities.rs `predigest_box_contents_in_mode`).
156    for key in ["lineskip", "lineskiplimit"] {
157      if let Some(value) = self.properties.get(key) {
158        options.insert(key, value.clone());
159      }
160    }
161    // Not vertical: horizontal and math lists (`hpack`, tex.web §649, §720);
162    // `compute_boxes_size`'s own default for a list with no mode.
163    let horizontal = match options.get("mode") {
164      Some(Stored::String(mode)) => {
165        crate::common::arena::with(*mode, |mode| !mode.ends_with("vertical"))
166      },
167      _ => true,
168    };
169    let (width, height, depth) = font.compute_boxes_size(&self.boxes, options)?;
170    // An hbox's height and depth start at 0 (tex.web §649 `hpack`), which a
171    // one-item list, measured through `compute_boxes_size`'s bare-box shortcut,
172    // did not do: `\hbox{\rotatebox[origin=l,y=1.2em]{90}{Qg}}` was 12pt deep
173    // below 0 (arXiv 2605.19974). Perl's `List()` returns the lone box itself
174    // (List.pm:41-44), so Perl measures it unfloored too (DIVERGENCES #331).
175    // A vbox keeps a negative depth (tex.web §670).
176    if horizontal {
177      Ok((width, Dimension(height.0.max(0)), Dimension(depth.0.max(0))))
178    } else {
179      Ok((width, height, depth))
180    }
181  }
182}
183
184impl List {
185  pub fn new(boxes: Vec<Digested>) -> Self {
186    // Perl: `$locator = $bx->getLocator unless defined $locator` — the first
187    // box (walking back-to-front) that has a locator. Now that locators are
188    // `Option<Locator>`, this is a clean `find_map` (no default-sentinel hack).
189    //
190    // Under the `token-locators` precision build we instead want the run's full
191    // *extent* — the span from the first contributing box's start to the last
192    // box's end — so a text run carries its true `(from..to)` range
193    // (docs/performance/SOURCE_PROVENANCE.md §3.1.1, Tbox consumer). Boxes are in source
194    // order, so folding `new_range` keeps the first `from` and extends to the
195    // latest `to`. Gated at *compile time* (not the runtime `source_map`
196    // switch): `List::new` runs deep in digestion where `State` is already
197    // mutably borrowed, so a `state!()` read here double-borrows the RefCell.
198    // Off the feature this stays the byte-identical Perl representative-locator
199    // behavior and never touches `State`.
200    #[cfg(feature = "token-locators")]
201    let locator: Option<Locator> = boxes.iter().fold(None, |acc, bx| match bx.get_locator() {
202      Some(l) if l.from_line != 0 => match acc {
203        None => Some(l),
204        Some(a) => Locator::new_range(a, l).or(Some(a)),
205      },
206      _ => acc,
207    });
208    #[cfg(not(feature = "token-locators"))]
209    let locator: Option<Locator> = boxes.iter().rev().find_map(|bx| bx.get_locator());
210    // Maybe the most representative font for a List is the font of the LAST box (that _has_ a
211    // font!) ???
212    // Walk boxes back-to-front for the most representative font.
213    // A single box whose font resolution errors (e.g. FontDirective::Closure
214    // returning Err) shouldn't crash the whole List; treat it as "no font"
215    // and keep walking.
216    // The handle is SHARED, not deep-copied. This is the hottest caller of
217    // `get_font` in the whole conversion: `Document::append_node_box` builds a
218    // fresh `List` for EVERY box absorbed into a node, so while `get_font`
219    // returned an owned `Font` this line paid a struct clone plus an `Rc::new`
220    // per box. Measured with `--features dhat-heap` on 100k words of plain
221    // prose: 392 MB of an 840 MB peak (47 %), 1,196,000 allocations of 344 B,
222    // all attributed here.
223    let mut font: Option<Rc<Font>> = None;
224    for bx in boxes.iter().rev() {
225      if let Ok(Some(bx_font)) = bx.get_font() {
226        font = Some(bx_font);
227        break;
228      }
229    }
230    List {
231      boxes,
232      font,
233      mode: None,
234      locator,
235      properties: HashMap::default(),
236    }
237  }
238
239  /// Append `boxes`, keeping the font and locator [`List::new`] would give
240  /// the longer list: the last box's that has one (or, under
241  /// `token-locators`, the extent to the last box's end). For a list only its
242  /// owner holds — `Document::append_node_box` growing a node's own box.
243  pub fn push_boxes(&mut self, boxes: impl IntoIterator<Item = Digested>) {
244    for bx in boxes {
245      if let Ok(Some(bx_font)) = bx.get_font() {
246        self.font = Some(bx_font);
247      }
248      #[cfg(feature = "token-locators")]
249      if let Some(l) = bx.get_locator().filter(|l| l.from_line != 0) {
250        self.locator = match self.locator.take() {
251          None => Some(l),
252          Some(a) => Locator::new_range(a, l).or(Some(a)),
253        };
254      }
255      #[cfg(not(feature = "token-locators"))]
256      if let Some(l) = bx.get_locator() {
257        self.locator = Some(l);
258      }
259      self.boxes.push(bx);
260    }
261  }
262
263  pub fn is_empty(&self) -> bool {
264    // 1. A space-like thing
265    // 2. empty contents
266    self.get_property_bool("isEmpty")
267      || self.get_property_bool("isSpace")
268      || self
269        .boxes
270        .iter()
271        .all(|item| item.is_empty().unwrap_or(false))
272  }
273}
274
275impl From<List> for Result<Vec<Digested>> {
276  fn from(list: List) -> Result<Vec<Digested>> {
277    let tmp: Digested = list.into();
278    tmp.into()
279  }
280}
281
282impl From<List> for Result<Digested> {
283  fn from(value: List) -> Result<Digested> {
284    let tmp: Digested = value.into();
285    tmp.into()
286  }
287}
288
289#[cfg(test)]
290mod tests {
291  use super::*;
292
293  #[test]
294  fn list_default_is_empty() {
295    let l = List::default();
296    assert!(l.is_empty());
297    assert_eq!(l.boxes.len(), 0);
298    assert_eq!(l.mode, None);
299    assert_eq!(l.font, None);
300  }
301
302  #[test]
303  fn list_new_from_empty_vec() {
304    let l = List::new(vec![]);
305    assert!(l.is_empty());
306    assert_eq!(l.boxes.len(), 0);
307  }
308
309  #[test]
310  fn list_display_empty_is_empty_string() {
311    let l = List::default();
312    assert_eq!(format!("{l}"), "");
313  }
314
315  #[test]
316  fn list_equality_same_empty() {
317    let a = List::default();
318    let b = List::default();
319    assert_eq!(a, b);
320  }
321
322  #[test]
323  fn list_stringify_wraps_in_brackets() {
324    let l = List::default();
325    let s = l.stringify();
326    assert!(s.starts_with("List["), "got {s:?}");
327    assert!(s.ends_with(']'));
328  }
329
330  #[test]
331  fn list_get_properties_empty_by_default() {
332    let l = List::default();
333    assert_eq!(l.get_properties().len(), 0);
334  }
335
336  #[test]
337  fn list_set_property_persists() {
338    let mut l = List::default();
339    l.set_property("testkey", Stored::Bool(true));
340    assert!(l.get_properties().contains_key("testkey"));
341  }
342
343  #[test]
344  fn list_revert_empty_is_empty_tokens() {
345    let l = List::default();
346    let t = l.revert().expect("empty list reverts cleanly");
347    assert_eq!(t.len(), 0);
348  }
349
350  #[test]
351  fn list_unlist_ref_returns_borrowed_boxes() {
352    let l = List::default();
353    let refs = l.unlist_ref();
354    assert_eq!(refs.len(), 0);
355  }
356
357  #[test]
358  fn list_get_font_default_none() {
359    let l = List::default();
360    let f = l.get_font().unwrap();
361    assert!(f.is_none());
362  }
363}