Skip to main content

latexml_core/definition/
constructor.rs

1use std::{borrow::Cow, fmt, rc::Rc};
2
3use libxml::tree::Node;
4
5use crate::{
6  BoxOps, Digested,
7  common::{arena::SymHashMap, error::*, font::Font, locator::Locator, object::Object},
8  definition::{
9    BeforeDigestClosure, ConstructionClosure, Definition, DigestionClosure, FontDirective,
10    PropertiesClosure, ReplacementClosure, Reversion, SizingClosure,
11  },
12  document::Document,
13  parameter::Parameters,
14  state::*,
15  stomach::digest_next_body,
16  token::*,
17  tokens::Tokens,
18  whatsit::Whatsit,
19};
20
21/// A `--source-map` construct's source extent: the union (first `from` → last
22/// `to`) of its children's spans, or `None` if none carries a position (the
23/// caller then falls back to the gullet locator). docs/performance/SOURCE_PROVENANCE.md §3.1.
24fn assemble_locator(args: &[Option<Digested>]) -> Option<Locator> {
25  args
26    .iter()
27    .flatten()
28    .filter_map(child_span)
29    .reduce(|a, b| Locator::new_range(a, b).unwrap_or(a))
30}
31
32/// A child's located span: its own `get_locator()` if set, else — under
33/// `token-locators` — recovered from the per-token origin handles still riding
34/// its reverted tokens. (Origins survive revert/re-digest; `get_locator` merely
35/// fails to aggregate undigested/composite content — §3.1.3.) Off the feature,
36/// only `get_locator` is consulted (byte-identical behavior).
37///
38/// `pub` so out-of-band construction paths that open an element *around*
39/// already-digested content — e.g. `insert_frontmatter` building `<ltx:title>`
40/// from the stored, deferred `\title{…}` boxes — can recover the same span and
41/// feed it to `Document::set_current_box_locator`.
42pub fn child_span(d: &Digested) -> Option<Locator> {
43  if let Some(l) = d.get_locator().filter(|l| l.from_line != 0) {
44    return Some(l);
45  }
46  #[cfg(feature = "token-locators")]
47  {
48    let reverted = d.revert().ok()?;
49    let origins: Vec<crate::token::TokenStart> = reverted
50      .unlist_ref()
51      .iter()
52      .filter_map(|t| crate::token::get_token_origin(t.loc))
53      .collect();
54    // Prefer genuine (read-from-source) origins: a macro's structural body
55    // literals carry an *inherited* origin (its call site) and must not widen
56    // the content-exact span of its real arguments. Fall back to the inherited
57    // origins only when nothing genuine was recovered — that is the
58    // origin-less expansion case (`\today`), where the invocation point is the
59    // only source position there is. See docs/performance/SOURCE_PROVENANCE.md §3.1.3.
60    let span = |it: &mut dyn Iterator<Item = &crate::token::TokenStart>| {
61      it.map(|o| {
62        crate::common::arena::with(o.source, |s| Locator::new(s, o.line, o.col, o.line, o.col))
63      })
64      .reduce(|a, b| Locator::new_range(a, b).unwrap_or(a))
65    };
66    span(&mut origins.iter().filter(|o| !o.inherited))
67      .or_else(|| span(&mut origins.iter().filter(|o| o.inherited)))
68  }
69  #[cfg(not(feature = "token-locators"))]
70  {
71    None
72  }
73}
74
75/// The TeX group an environment's begin code leaves open for its end code, in tex.web's group codes (§269):
76/// none (`\trivlist`, `\list`: the bare `\X` opens no group at all), a `semi_simple_group` (`\begingroup`, or a
77/// nested `\begin`: setspace's `spacing`, lscape's `landscape`, `multicols`, beamer's blocks), or a box group (a
78/// `\vbox\bgroup`/`\hbox\bgroup`/`\color@hbox`: a float's `\@xfloat`, latex.ltx:17421-17479; `\minipage`, :16310).
79/// §1063 `end_group` against a `semi_simple_group` just unsaves; against a box group it is `off_save`'s "Missing }
80/// inserted" (§1064). `}` against a `semi_simple_group` is §1069 `extra_right_brace` ("Extra }, or forgotten
81/// \endgroup"); against a box group §1068 packages the box, with no error there, and TeX reports the mismatch later.
82#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
83pub enum TexGroup {
84  /// no group of its own
85  #[default]
86  None,
87  /// a `\begingroup` (`semi_simple_group`)
88  SemiSimple,
89  /// a box or colour group
90  Box,
91}
92
93impl TexGroup {
94  /// The name stored on the environment's frame (`lx@env@tex@group`) and in a binding's run-time override.
95  pub fn as_str(self) -> &'static str {
96    match self {
97      TexGroup::None => "none",
98      TexGroup::SemiSimple => "semi_simple",
99      TexGroup::Box => "box",
100    }
101  }
102
103  /// The kind named by [`TexGroup::as_str`]; `None` for anything else.
104  pub fn from_name(name: &str) -> Option<TexGroup> {
105    match name {
106      "none" => Some(TexGroup::None),
107      "semi_simple" => Some(TexGroup::SemiSimple),
108      "box" => Some(TexGroup::Box),
109      _ => None,
110    }
111  }
112}
113
114/// configuration for creating a new Constructor
115#[derive(Clone)]
116pub struct ConstructorOptions {
117  /// number of arguments (if any)
118  pub nargs:            Option<usize>,
119  /// bouded mode (default: false)
120  pub bounded:          bool,
121  /// begin a named mode
122  pub mode:             Option<String>,
123  /// a `SizingClosure` to estimate the size of the digested box
124  pub sizer:            Option<SizingClosure>,
125  /// custom code to run immediately before the digestion phase
126  pub before_digest:    Vec<BeforeDigestClosure>,
127  /// custom code to run immediately after the digestion phase
128  pub after_digest:     Vec<DigestionClosure>,
129  /// custom code to run immediately before the construction phase
130  pub before_construct: Vec<ConstructionClosure>,
131  /// custom code to run immediately after the construction phase
132  pub after_construct:  Vec<ConstructionClosure>,
133
134  /// switch to horizontal mode before digesting (Perl: enterHorizontal => 1)
135  pub enter_horizontal: bool,
136  /// switch to vertical mode before digesting (Perl: leaveHorizontal => 1)
137  pub leave_horizontal: bool,
138
139  // environment-specific
140  /// requires to be used in math mode
141  pub require_math:       bool,
142  /// forbids use in math mode
143  pub forbid_math:        bool,
144  /// custom directives for computing box properties
145  pub properties:         PropertiesClosure,
146  /// should it capture the body as `#body` (default: false)
147  pub capture_body:       bool,
148  /// environment-specific: the TeX group the LaTeX source's begin code leaves open for its end code
149  /// ([`TexGroup`]), which decides whether a plain closer of an enclosing group meeting the environment is a TeX
150  /// error (stomach.rs `close_environment_frame`)
151  pub tex_group:          TexGroup,
152  /// specify a font to use, or instructions how to compute which font to use
153  pub font:               Option<FontDirective>,
154  /// custom code to run as digestion begins
155  pub after_digest_begin: Vec<DigestionClosure>,
156  /// custom code to run just before digestion ends
157  pub before_digest_end:  Vec<BeforeDigestClosure>,
158  /// custom code to run after `#body` has been digested
159  pub after_digest_body:  Vec<DigestionClosure>,
160  /// provide tokens to revert to, or custom code for computing them
161  pub reversion:          Option<Reversion>,
162  /// Local/Global scope of installing this definition (default: Local)
163  pub scope:              Option<Scope>,
164  /// is this a robust command sequence (default: false)
165  pub robust:             bool,
166  /// lock the definition for raw TeX overrides (default: false)
167  pub locked:             bool,
168  /// alternative (command sequence) name, used for reversion
169  pub alias:              Option<String>,
170  /// The constructor is TeX's `\halign` primitive or a binding's stand-in for it ([`Constructor::halign_primitive`]).
171  pub halign_primitive:   bool,
172  /// The XML template its replacement was compiled from, when it is a literal one ([`Constructor::template`]).
173  pub template:           Option<&'static str>,
174  /// The half of a pair its opener began that its close ends, run when a digestion Fatal closes it instead
175  /// ([`Constructor::salvage_close`]).
176  pub salvage_close:      Vec<DigestionClosure>,
177}
178impl Default for ConstructorOptions {
179  fn default() -> Self {
180    ConstructorOptions {
181      nargs:              None,
182      bounded:            false,
183      before_digest:      vec![],
184      after_digest:       vec![],
185      before_construct:   vec![],
186      after_construct:    vec![],
187      mode:               None,
188      enter_horizontal:   false,
189      leave_horizontal:   false,
190      // environment-specific
191      require_math:       false,
192      forbid_math:        false,
193      properties:         Rc::new(|_whatsit| Ok(SymHashMap::default())),
194      capture_body:       false,
195      tex_group:          TexGroup::None,
196      font:               None,
197      after_digest_begin: vec![],
198      before_digest_end:  vec![],
199      after_digest_body:  vec![],
200      scope:              None,
201      robust:             false,
202      locked:             false,
203      alias:              None,
204      reversion:          None,
205      sizer:              None,
206      halign_primitive:   false,
207      template:           None,
208      salvage_close:      vec![],
209    }
210  }
211}
212impl fmt::Debug for ConstructorOptions {
213  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
214    write!(
215      f,
216      "\nConstructorOptions {{nargs:{:?}, bounded:{:?}, mode:{:?}, \n\tbefore_digest:{:?}, \
217       after_digest_begin:{:?}, before_digest_end:{:?},\n\tafter_digest:{:?}, \
218       after_digest_body:{:?}, before_construct:{:?}, after_construct:{:?},\n\trequire_math:{:?}, \
219       forbid_math:{:?}, capture_body:{:?}, scope:{:?},\n\tlocked:{:?}, alias:{:?} }}\n",
220      self.nargs,
221      self.bounded,
222      self.mode,
223      self.before_digest.len(),
224      self.after_digest_begin.len(),
225      self.before_digest_end.len(),
226      self.after_digest.len(),
227      self.after_digest_body.len(),
228      self.before_construct.len(),
229      self.after_construct.len(),
230      self.require_math,
231      self.forbid_math,
232      self.capture_body,
233      self.scope,
234      self.locked,
235      self.alias
236    )
237  }
238}
239
240#[derive(Clone)]
241pub struct Constructor {
242  pub cs:                Token,
243  pub nargs:             Option<usize>,
244  pub paramlist:         Option<Parameters>,
245  pub replacement:       Option<ReplacementClosure>,
246  pub sizer:             Option<SizingClosure>,
247  pub before_digest:     Vec<BeforeDigestClosure>,
248  pub after_digest:      Vec<DigestionClosure>,
249  pub before_construct:  Vec<ConstructionClosure>,
250  pub after_construct:   Vec<ConstructionClosure>,
251  pub properties:        PropertiesClosure,
252  pub capture_body:      bool,
253  // environment-specific
254  pub after_digest_body: Vec<DigestionClosure>,
255  pub reversion:         Option<Reversion>,
256  pub alias:             Option<String>,
257  pub origin:            crate::definition::origin::DefinitionOrigin,
258  /// The mode options `def_constructor` compiled into `before_digest` (K13).
259  pub declared_mode:     Option<crate::definition::DeclaredMode>,
260  /// The `font` option `def_constructor` compiled into `before_digest` ([`Definition::declared_font`]).
261  pub font:              Option<FontDirective>,
262  /// TeX's `\halign` primitive (tex_tables.rs) or a binding's stand-in that takes its place (pgfsys-latexml's SVG
263  /// matrix `\lxSVG@halign`): what a document's `\halign` macro ends with when it is run before an alignment the
264  /// bindings build (latexml_engine tex_tables.rs `run_halign_redefinition_prelude`), under whatever name it was saved.
265  pub halign_primitive:  bool,
266  /// The XML template its replacement was compiled from, when it is a literal one (`DefConstructor!` with a string
267  /// replacement); none for a closure replacement or a constructor made at run time. Read by
268  /// [`Definition::replacement_template`].
269  pub template:          Option<&'static str>,
270  /// An environment's opener (`\begin{X}`, the bare `\X`): its end's token (`\end{X}`, `\endX`) and the
271  /// `after_digest` hooks its binding gave that end, without the end's mode or group closer. A digestion Fatal in its
272  /// body closes the body with that end's trailer, run through these hooks, then ends its mode as `end_mode` would (OD
273  /// #251, #1237; `def_environment`).
274  pub salvage_end:       Option<(Token, Vec<DigestionClosure>)>,
275  /// Run on its whatsit when a digestion Fatal ends its body or last argument (OD #251), where its close would run
276  /// them: the end of a pair its opener began (`end_caption_box` for `begin_caption_box`), never its other close code.
277  pub salvage_close:     Vec<DigestionClosure>,
278}
279impl Default for Constructor {
280  fn default() -> Self {
281    Constructor {
282      origin:            crate::definition::origin::current_origin(),
283      cs:                T_CS!("Constructor"),
284      nargs:             None,
285      paramlist:         None,
286      replacement:       None,
287      before_digest:     vec![],
288      after_digest:      vec![],
289      before_construct:  vec![],
290      after_construct:   vec![],
291      properties:        Rc::new(|_whatsit| Ok(SymHashMap::default())),
292      capture_body:      false,
293      after_digest_body: vec![],
294      reversion:         None,
295      alias:             None,
296      sizer:             None,
297      declared_mode:     None,
298      font:              None,
299      halign_primitive:  false,
300      template:          None,
301      salvage_end:       None,
302      salvage_close:     vec![],
303    }
304  }
305}
306impl fmt::Debug for Constructor {
307  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
308    write!(
309      f,
310      "\nConstructor {{
311        cs:{:?}
312        nargs:{:?}
313        paramlist:{:?}
314        replacement:{:?}
315        before_digest:{:?}
316        after_digest:{:?}
317        before_construct:{:?}
318        after_construct:{:?}
319        capture_body:{:?}
320        after_digest_body:{:?}
321        reversion:{:?}
322        alias:{:?}
323        sizer:{:?} }}\n",
324      self.cs,
325      self.nargs,
326      self.paramlist,
327      self.replacement.is_some(),
328      self.before_digest.len(),
329      self.after_digest.len(),
330      self.before_construct.len(),
331      self.after_construct.len(),
332      self.capture_body,
333      self.after_digest_body.len(),
334      self.reversion.is_some(),
335      self.alias,
336      self.sizer.is_some(),
337    )
338  }
339}
340
341impl PartialEq for Constructor {
342  fn eq(&self, other: &Constructor) -> bool { self.cs == other.cs }
343}
344
345impl fmt::Display for Constructor {
346  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
347    write!(
348      f,
349      "{}",
350      <Self as Definition>::stringify_type(self, "Constructor")
351    )
352  }
353}
354impl Object for Constructor {
355  fn stringify(&self) -> String { <Self as Definition>::stringify_type(self, "Constructor") }
356}
357impl Constructor {
358  /// Digest through the `Rc<Constructor>` the state table already holds, instead
359  /// of deep-cloning the definition for every invocation.
360  ///
361  /// Every Whatsit keeps a back-reference to the definition that built it
362  /// ([`Whatsit::definition`]), and [`Definition::invoke_primitive`] fills that
363  /// slot with `Rc::new(self.clone())` — a **fresh deep clone per invocation**,
364  /// carrying the `Parameters` and all three `Vec<Rc<dyn Fn…>>` hook lists with
365  /// it. Those clones are not transient: a Whatsit lives in the digested tree
366  /// for the whole Build, so a document retains one private copy of the
367  /// constructor per construct it uses. Measured with dhat (2026-07-29, debug
368  /// profile, math-dense fixture): the `Rc<Constructor>` itself was 1,215 blocks
369  /// / 349,920 B — an exact 1:1 with the 1,215 constructor invocations — plus
370  /// 3,638 blocks / 314,816 B inside `<Constructor as Clone>::clone` for the
371  /// parameters and hook vectors.
372  ///
373  /// The state table's entry is `Stored::Constructor(Rc<Constructor>)`
374  /// (`common/store.rs`), so the invoker is already holding a shareable handle;
375  /// passing it through turns that whole per-invocation cost into a refcount
376  /// bump. Sharing is sound because the definition is immutable once installed —
377  /// nothing calls `Rc::get_mut` on it, and `PartialEq for Whatsit` compares
378  /// definitions **by value** (`*self.definition == *other.definition`), so a
379  /// shared handle compares exactly as a private clone did.
380  pub fn invoke_primitive_shared(me: &Rc<Constructor>) -> Result<Vec<Digested>> {
381    me.digest_to_whatsit(Rc::clone(me) as Rc<dyn Definition>)
382  }
383
384  /// The body of constructor digestion, parameterized by the handle to install
385  /// as the Whatsit's [`Whatsit::definition`] back-reference.
386  fn digest_to_whatsit(&self, definition: Rc<dyn Definition>) -> Result<Vec<Digested>> {
387    Debug!("invoke_primitive for {:?}", self.get_cs());
388    // Call any `Before' code.
389    // TODO: profiling / tracing
390    // let profiled = state!().lookup_value("PROFILING") && ($LaTeXML::CURRENT_TOKEN || $$self{cs});
391    // let tracing = state!().lookup_value("tracingcommands");
392    // LaTeXML::Definition::startProfiling($profiled, "digest") if $profiled;
393
394    // Where a declared `enter_horizontal` leaves TeX: in a paragraph (unrestricted horizontal
395    // mode) when met in vertical mode, which begins one (tex.web §1091 `new_graf`), or inside a
396    // paragraph already; in a restricted box or math it is a no-op (arXiv 2605.20645's
397    // `\rotatebox{90}{\parbox…}`). A box that is paragraph material may need to open that
398    // paragraph in the document (`insert_block_in_paragraph`, latexml_engine).
399    let in_paragraph = self.declared_mode.is_some_and(|mode| mode.enter_horizontal) && {
400      let mode = lookup_mode();
401      mode == crate::pin!("horizontal")
402        || crate::common::arena::with(mode, |mode| mode.ends_with("vertical"))
403    };
404    // (where the box lists of its arguments and body open: a Fatal inside one closes it as this whatsit, OD #251)
405    let mark = crate::stomach::pending_list_mark();
406    // (the frame depth it starts at, where its `after_digest_body` runs, and the one its begin code leaves, where its
407    // `after_digest` runs: `salvage_close`)
408    let outer_depth = get_frame_depth();
409    let mut result = self
410      .execute_before_digest()
411      .inspect_err(|_| crate::stomach::clear_pending_list_closers(mark))?;
412    let begun_depth = get_frame_depth();
413    // After the `before` code: `\lx@finalize@document`'s is what ends the document (1611.05714: an
414    // itemize left open by a `\description` used as a command).
415    let ends_before = crate::stomach::ends_inside_groups();
416
417    // info!("{" + $self->tracingCSName . "}\n" if $tracing;
418    // Get some info before we process arguments...
419    let state_font = lookup_font();
420    let ismath = lookup_bool_sym(crate::pin!("IN_MATH"));
421    // info!(target: "constructor", "invoke for {:?} ({:?})", self.get_cs(), ismath);
422    // Parse AND digest the arguments to the Constructor
423    // (and the tokens its length arguments state, where they are kept: `parameter::KEEP_STATED_LENGTHS`)
424    let mut stated: Vec<(usize, Tokens)> = Vec::new();
425    let mut withheld = false;
426    let mut args: Vec<Option<Digested>> = Vec::new();
427    let nargs = self.get_num_args();
428    if let Some(params) = self.get_parameters()
429      && let Err(e) = params.read_arguments_and_digest(self, &mut stated, &mut withheld, &mut args)
430    {
431      // In its last argument: the whatsit takes what that argument digested (an earlier one leaves later ones unread,
432      // and its text joins as it is).
433      if args.len() + 1 == nargs {
434        let properties = Rc::clone(&self.properties);
435        let restricted_box = self.declared_mode.is_some_and(|mode| mode.restricted_box);
436        let close = self.salvage_close.clone();
437        crate::stomach::close_pending_list_as(mark, ismath, move |mut boxes| {
438          // (a math argument keeps its leading math, the rest joins the enclosing list: `stomach::split_off_after_leading_math`)
439          let rest = if ismath {
440            crate::stomach::split_off_after_leading_math(&mut boxes)
441          } else {
442            Vec::new()
443          };
444          // (marked, so a properties closure can tell a salvaged argument: `\@@toccaption` makes its caption from it)
445          let mut list = crate::list::List::new(boxes);
446          list.set_property(crate::stomach::SALVAGED, true);
447          let partial: Digested = list.into();
448          let mut args = args;
449          args.push(Some(partial.clone()));
450          let parts = WhatsitParts {
451            definition,
452            args,
453            state_font,
454            ismath,
455            in_paragraph,
456            stated,
457            withheld,
458          };
459          // (its properties failed: the argument's boxes stay, in the enclosing list)
460          let mut closed = Vec::new();
461          result.push(match parts.assemble(&properties, restricted_box) {
462            Ok(mut whatsit) => {
463              closed = run_salvage_close(&close, begun_depth, &mut whatsit);
464              salvaged(whatsit, Some("argument")).into()
465            },
466            Err(_) => partial,
467          });
468          result.extend(closed);
469          result.extend(rest);
470          result
471        });
472      } else {
473        crate::stomach::clear_pending_list_closers(mark);
474      }
475      return Err(e);
476    }
477    // info!($self->tracingArgs(@args) . "\n" if $tracing && @args;
478    args.truncate(nargs);
479
480    let parts = WhatsitParts {
481      definition,
482      args,
483      state_font,
484      ismath,
485      in_paragraph,
486      stated,
487      withheld,
488    };
489    // (a Fatal in its properties, which may digest, an `\item`'s label, closes no whatsit: its text joins as it is)
490    let mut whatsit = parts
491      .assemble(
492        &self.properties,
493        self.declared_mode.is_some_and(|mode| mode.restricted_box),
494      )
495      .inspect_err(|_| crate::stomach::clear_pending_list_closers(mark))?;
496
497    // Call any 'After' code.
498    let mut post = match self.execute_after_digest(&mut whatsit) {
499      Ok(post) => post,
500      Err(e) => {
501        crate::stomach::close_pending_list_as(mark, ismath, move |boxes| {
502          result.push(salvaged(whatsit, None).into());
503          result.extend(boxes);
504          result
505        });
506        return Err(e);
507      },
508    };
509
510    if self.capture_body {
511      // tex.web §679 `append_to_vlist`: a vertical body's interline glue follows the `\baselineskip`, `\lineskip`
512      // and `\lineskiplimit` in force inside it. The body is measured after its group closed, where an enclosing
513      // `\@array`'s zero values reign (a minipage's stacked lines lost their `\lineskip` in a table cell, arXiv
514      // 2605.19065), so they are read here, when the body opens, after its begin code (`\@parboxrestore` for a
515      // minipage). Unlike the box reader, which reads them at the box's end (base_utilities.rs
516      // `predigest_list_in_mode`), a change inside the body (`\small`, `\offinterlineskip`) is not seen: RED
517      // kernel-alignment/captured_body_interline_changed_inside. DIVERGENCES #421. Repro
518      // kernel-alignment/minipage_in_a_cell_keeps_its_lineskip.
519      use crate::common::numeric_ops::NumericOps;
520      // the body's own mode, in force now (the whatsit's `mode` property is the mode it was invoked in)
521      let interline: Vec<(&str, crate::Dimension)> = if mode_ends_with("vertical") {
522        [
523          ("baseline", "\\baselineskip"),
524          ("lineskip", "\\lineskip"),
525          ("lineskiplimit", "\\lineskiplimit"),
526        ]
527        .into_iter()
528        .filter_map(|(key, register)| {
529          lookup_register_quiet(register)
530            .map(|value| (key, crate::Dimension::new(value.value_of())))
531        })
532        .collect()
533      } else {
534        Vec::new()
535      };
536      let body_in_math = lookup_bool_sym(crate::pin!("IN_MATH"));
537      // (the frames its body opens in: its own, on top, as its end finds them)
538      let body_depth = get_frame_depth();
539      let captured = match digest_next_body(None) {
540        Ok(captured) => captured,
541        Err(e) => {
542          // (its body so far is its body: a list's items, a formula's atoms; no `\end` came, its trailer is the one
543          // `salvaged_trailer` makes; a math body keeps its leading math, the rest joins the enclosing list:
544          // `stomach::split_off_after_leading_math`)
545          let end = self.salvage_end.clone();
546          let close = self.salvage_close.clone();
547          let after_body = self.after_digest_body.clone();
548          crate::stomach::close_pending_list_as(mark, ismath || body_in_math, move |mut boxes| {
549            let rest = if body_in_math {
550              crate::stomach::split_off_after_leading_math(&mut boxes)
551            } else {
552              Vec::new()
553            };
554            post.extend(boxes);
555            let trailer = salvaged_trailer(end, body_depth, &mut post);
556            post.push(trailer);
557            whatsit.set_body(post);
558            let mut closed = run_salvage_close(&close, outer_depth, &mut whatsit);
559            // (and its `after_digest_body`, which reads the body it closed: a `{sidewaystable}`'s angle and width)
560            closed.extend(run_salvage_close(&after_body, outer_depth, &mut whatsit));
561            result.push(salvaged(whatsit, Some("body")).into());
562            result.extend(closed);
563            result.extend(rest);
564            result
565          });
566          return Err(e);
567        },
568      };
569      // info!(target:"constructor:digest_next_body", "\n{:?}\n----\n",captured);
570      post.extend(captured);
571
572      // token-locators: capture_body constructs (e.g. `\lx@begin@inline@math`)
573      // carry their content as #body, not positional args, so the earlier
574      // assemble_locator (over args) missed it and fell back to the gullet point.
575      // Derive the span from the digested body and union it with any positional-
576      // arg span, so the wrapper (e.g. `ltx:Math`) spans its content. §3.1.3.
577      #[cfg(feature = "token-locators")]
578      if crate::state::source_map_enabled() {
579        if let Some(body_span) = post
580          .iter()
581          .filter_map(child_span)
582          .reduce(|a, b| Locator::new_range(a, b).unwrap_or(a))
583        {
584          whatsit.locator = Some(match whatsit.locator {
585            Some(prev) if prev.from_line != 0 => {
586              Locator::new_range(prev, body_span).unwrap_or(body_span)
587            },
588            _ => body_span,
589          });
590        }
591      }
592      whatsit.set_body(std::mem::take(&mut post));
593      if let Some(Stored::Digested(body)) = whatsit.properties.get_mut("body") {
594        for (key, value) in interline {
595          body.set_property(key, Stored::Dimension(value));
596        }
597      }
598      //info!(target: "constructor:capture", "whatsit: {:?}", whatsit);
599      // info!(target: "constructor:capture", "constructor: {:?}", self.get_cs_name());
600    }
601    // The document ended inside this construct's arguments or body (`stomach::UNENDED`, OXIDIZED_DESIGN
602    // #542; 1611.05714).
603    if crate::stomach::ends_inside_groups() != ends_before {
604      whatsit
605        .properties
606        .insert(crate::stomach::UNENDED, Stored::Bool(true));
607    }
608    let post_post = self
609      .execute_after_digest_body(&mut whatsit)
610      .inspect_err(|_| crate::stomach::clear_pending_list_closers(mark))?;
611    // LaTeXML::Core::Definition::stopProfiling($profiled, 'digest') if $profiled;
612
613    // Package the result boxes
614    result.push(whatsit.into());
615    result.extend(post);
616    result.extend(post_post);
617    Ok(result)
618  }
619}
620
621/// The `\end{X}` trailer of a body a digestion Fatal ended, run through its end's `after_digest` hooks in the
622/// environment's own frame with the body as the live list, then its mode ended as `end_mode` ends it; an empty list
623/// where the end has no hooks (OD #251, #1237).
624fn salvaged_trailer(
625  end: Option<(Token, Vec<DigestionClosure>)>,
626  body_depth: usize,
627  body: &mut Vec<Digested>,
628) -> Digested {
629  let Some((end, hooks)) = end else {
630    return crate::list::List::new(Vec::new()).into();
631  };
632  crate::stomach::with_box_list_mut_vec(|list| std::mem::swap(list, body));
633  // (a sub-float's `\@captype` and `\hsize` are its own: its enclosing float's are read in that float's frame; each
634  // group the Fatal left open does its element-closing work first, `\centering`'s `\@add@centering`, as its pop would)
635  while get_frame_depth() > body_depth {
636    let _ = crate::stomach::execute_before_after_group();
637    if pop_frame().is_err() {
638      break;
639    }
640  }
641  let mut trailer = (!hooks.is_empty())
642    .then(|| salvaged_end_whatsit(&end))
643    .flatten();
644  let mut digested = Vec::new();
645  {
646    let _unlocked = local_state_unlocked_guard(true);
647    if let Some(trailer) = trailer.as_mut() {
648      for hook in &hooks {
649        match hook(trailer) {
650          Ok(boxes) => digested.extend(boxes),
651          Err(_) => break,
652        }
653      }
654    }
655    // (then its mode ends as `end_mode` ends it after these hooks: the open paragraph repacked, which a
656    // `{sidewaystable}` measures, and the group's own closing work, a float's `\centering`)
657    crate::stomach::leave_horizontal_internal();
658    let _ = crate::stomach::execute_before_after_group();
659  }
660  crate::stomach::with_box_list_mut_vec(|list| std::mem::swap(list, body));
661  // (what a hook digested stays in the body, before its trailer)
662  body.extend(digested);
663  match trailer {
664    Some(trailer) => trailer.into(),
665    None => crate::list::List::new(Vec::new()).into(),
666  }
667}
668
669/// The whatsit of an environment's end `end` with no arguments, for its hooks to run on ([`salvaged_trailer`]).
670fn salvaged_end_whatsit(end: &Token) -> Option<Whatsit> {
671  let definition = lookup_definition(end).ok().flatten()?;
672  let parts = WhatsitParts {
673    definition,
674    args: Vec::new(),
675    state_font: lookup_font(),
676    ismath: lookup_bool_sym(crate::pin!("IN_MATH")),
677    in_paragraph: false,
678    stated: Vec::new(),
679    withheld: false,
680  };
681  let no_properties: PropertiesClosure = Rc::new(|_args| Ok(SymHashMap::default()));
682  parts.assemble(&no_properties, false).ok()
683}
684
685/// A math construct the salvage kept closed and handed out of its formula, as a formula of its own: the kernel's inline
686/// formula (`\lx@begin@inline@math`) around it, with an empty trailer, as `$…$` builds one (OD #251). Itself, if that
687/// constructor is not defined.
688pub(crate) fn salvaged_formula(item: Digested) -> Digested {
689  let Ok(Some(definition)) = lookup_definition(&T_CS!("\\lx@begin@inline@math")) else {
690    return item;
691  };
692  let parts = WhatsitParts {
693    definition,
694    args: Vec::new(),
695    state_font: lookup_font(),
696    ismath: false,
697    in_paragraph: false,
698    stated: Vec::new(),
699    withheld: false,
700  };
701  let math_mode: PropertiesClosure = Rc::new(|_args| Ok(stored_map!("mode" => "math")));
702  let Ok(mut formula) = parts.assemble(&math_mode, false) else {
703    return item;
704  };
705  formula.set_body(vec![item, crate::list::List::new(Vec::new()).into()]);
706  formula.into()
707}
708
709/// A salvaged whatsit's [`Constructor::salvage_close`] hooks, or its `after_digest_body`, run at `depth`, where its close
710/// runs them (OD #251): a minipage's captioned panel claims its own caption, and its float gets its own back.
711fn run_salvage_close(
712  hooks: &[DigestionClosure],
713  depth: usize,
714  whatsit: &mut Whatsit,
715) -> Vec<Digested> {
716  let mut digested = Vec::new();
717  if hooks.is_empty() {
718    return digested;
719  }
720  while get_frame_depth() > depth && pop_frame().is_ok() {}
721  let _unlocked = local_state_unlocked_guard(true);
722  for hook in hooks {
723    match hook(whatsit) {
724      Ok(boxes) => digested.extend(boxes),
725      Err(_) => break,
726    }
727  }
728  digested
729}
730
731/// What a constructor's whatsit is made of once its arguments are read ([`Constructor::digest_to_whatsit`]; on a Fatal
732/// in its last argument, at the salvage, OD #251).
733struct WhatsitParts {
734  definition:   Rc<dyn Definition>,
735  args:         Vec<Option<Digested>>,
736  state_font:   Option<Rc<Font>>,
737  ismath:       bool,
738  in_paragraph: bool,
739  stated:       Vec<(usize, Tokens)>,
740  withheld:     bool,
741}
742
743impl WhatsitParts {
744  fn assemble(self, properties: &PropertiesClosure, restricted_box: bool) -> Result<Whatsit> {
745    let WhatsitParts {
746      definition,
747      args,
748      state_font,
749      ismath,
750      in_paragraph,
751      stated,
752      withheld,
753    } = self;
754    // Compute any extra Whatsit properties (many end up as element attributes)
755
756    let mut properties = properties(&args)?;
757    // for (key, value) in properties.iter() {
758    //   if (ref $value eq 'CODE') {
759    //     $properties{$key} = &$value($stomach, @args); } }
760
761    properties
762      .entry("font")
763      .or_insert_with(|| match state_font {
764        Some(f) => Stored::Font(Rc::clone(&f)),
765        None => Stored::Font(Rc::new(Font::text_default())), // should never happen?
766      });
767    // $properties{locator} = $stomach->getGullet->getMouth->getLocator unless defined
768    // $properties{locator};
769    properties
770      .entry("isMath")
771      .or_insert_with(|| Stored::Bool(ismath));
772    // Perl: $mode = $properties{mode} || $state->lookupValue('MODE') || 'restricted_horizontal';
773    // Set mode on whatsit so repackHorizontal can distinguish vertical vs horizontal items.
774    properties.entry("mode").or_insert_with(|| {
775      let mode = lookup_mode();
776      Stored::String(if mode == crate::pin!("") {
777        crate::pin!("restricted_horizontal")
778      } else {
779        mode
780      })
781    });
782    if in_paragraph {
783      properties.insert("in_paragraph", Stored::Bool(true));
784    }
785    if !stated.is_empty() {
786      let mut lengths: std::collections::VecDeque<Stored> = std::iter::repeat_with(|| Stored::None)
787        .take(args.len())
788        .collect();
789      for (index, tokens) in stated {
790        if let Some(slot) = lengths.get_mut(index) {
791          *slot = Stored::Tokens(tokens);
792        }
793      }
794      properties.insert(
795        crate::parameter::STATED_LENGTHS,
796        Stored::VecDequeStored(lengths),
797      );
798    }
799    if withheld {
800      properties.insert(
801        crate::parameter::STATED_LENGTHS_WITHHELD,
802        Stored::Bool(true),
803      );
804    }
805    // A TeX box's constructor outside math (a declared `restricted_horizontal`): the element it opens is marked for a
806    // frontmatter field's print (core `document::FIELD_BOX_PROPERTY`, OXIDIZED_DESIGN #715).
807    if restricted_box && !ismath && crate::document::field_box_marks_live() {
808      properties.insert(crate::document::FIELD_BOX_PROPERTY, Stored::Bool(true));
809    }
810    // $properties{level}   = $stomach->getBoxingLevel;
811
812    // Now create the Whatsit, itself.
813    // Every field is named rather than `..Whatsit::default()`: the default
814    // builds a placeholder `Rc::new(Expandable::default())` for `definition`
815    // that this literal immediately overwrites, so the functional-update form
816    // allocated and dropped one `Rc<Expandable>` per constructor invocation
817    // (dhat 2026-07-29: 1,215 blocks / 145,800 B, again 1:1 with invocations).
818    let mut whatsit = Whatsit {
819      definition,
820      args,
821      properties,
822      reversion: None,
823      dual_reversion: None,
824      locator: None,
825    };
826    // Perl `Core/Definition/Constructor.pm` L106:
827    //   `$props{locator} = $stomach->getGullet->getLocator`
828    // — capture the construct's source position at digest time. Gated on
829    // `--source-map`: the whatsit locator is consumed only by source-map
830    // stamping + (untested) error messages, so the corpus/parity path skips
831    // the per-construct `get_locator`/`arena::pin` cost and stays
832    // byte-identical (the switch gates *all* locator tracking). Without this,
833    // constructor-built elements carry `Locator::default()` (source =
834    // `locator.rs`) and the source-map user-source filter drops them
835    // (~53/265 → 128/… `article.tex` elements stamped once captured).
836    if source_map_enabled() {
837      // --source-map: the construct's source extent is the union of its
838      // children's spans (fixes the post-expansion eating-disorder, Experiment 2),
839      // falling back to the gullet locator when no child carries a position.
840      whatsit.locator =
841        assemble_locator(&whatsit.args).or_else(|| Some(crate::gullet::get_locator()));
842    }
843    Ok(whatsit)
844  }
845}
846
847/// A whatsit a Fatal left unfinished, made by the salvage ([`crate::stomach::SALVAGED`]), with the part its closer filled
848/// ([`crate::stomach::SALVAGED_PART`]). (Not `UNENDED`, OD #542: no input follows a Fatal, so its element closes through
849/// its own pattern, its note's `\par` inside it.)
850fn salvaged(mut whatsit: Whatsit, part: Option<&str>) -> Whatsit {
851  whatsit
852    .properties
853    .insert(crate::stomach::SALVAGED, Stored::Bool(true));
854  if let Some(part) = part {
855    whatsit.properties.insert(
856      crate::stomach::SALVAGED_PART,
857      Stored::String(crate::common::arena::pin(part)),
858    );
859  }
860  whatsit
861}
862
863impl Definition for Constructor {
864  fn declared_mode(&self) -> Option<crate::definition::DeclaredMode> { self.declared_mode }
865  fn declared_font(&self) -> Option<&FontDirective> { self.font.as_ref() }
866  fn replacement_template(&self) -> Option<&'static str> {
867    self
868      .template
869      .filter(|_| self.before_construct.is_empty() && self.after_construct.is_empty())
870  }
871  fn before_digest(&self) -> Option<&Vec<BeforeDigestClosure>> { Some(&self.before_digest) }
872  fn after_digest(&self) -> Option<&Vec<DigestionClosure>> { Some(&self.after_digest) }
873  fn after_digest_body(&self) -> Option<&Vec<DigestionClosure>> { Some(&self.after_digest_body) }
874  fn capture_body(&self) -> bool { self.capture_body }
875  fn get_sizer(&self) -> Option<SizingClosure> { self.sizer.clone() }
876  fn invoke(&self, _once_only: bool) -> Result<Tokens> { Ok(Tokens!()) }
877  /// Digest the constructor; This should occur in the Stomach to create a Whatsit.
878  /// The whatsit which will be further processed to create the document.
879  ///
880  /// Allocates a fresh `Rc` for the Whatsit's back-reference. Callers that
881  /// already hold the state table's `Rc<Constructor>` should use
882  /// [`Constructor::invoke_primitive_shared`] instead, which reuses it — see
883  /// there for why that matters.
884  fn invoke_primitive(&self) -> Result<Vec<Digested>> {
885    self.digest_to_whatsit(Rc::new(self.clone()))
886  }
887
888  fn get_cs(&self) -> Cow<'_, Token> { Cow::Borrowed(&self.cs) }
889  fn get_cs_name(&self) -> Cow<'_, str> { Cow::Owned(self.cs.with_cs_name(ToString::to_string)) }
890  fn get_alias(&self) -> Option<&String> { self.alias.as_ref() }
891  fn get_parameters(&self) -> Option<&Parameters> { self.paramlist.as_ref() }
892  fn get_num_args(&self) -> usize {
893    match self.nargs {
894      Some(n) => n,
895      None => match self.paramlist {
896        Some(ref params) => params.get_num_args(),
897        None => 0,
898      },
899    }
900    // self.nargs = Some(nargs);
901  }
902
903  fn do_absorption(&self, document: &mut Document, whatsit: &Whatsit) -> Result<Vec<Node>> {
904    for pre_closure in &self.before_construct {
905      pre_closure(document, whatsit)?;
906    }
907
908    match self.replacement {
909      None => {
910        // info!(target:"constructor:replacement", "no replacement for {:?}", self.get_cs_name());
911      },
912      Some(ref main_closure) => {
913        main_closure(document, whatsit.get_args(), whatsit.get_properties())?
914      },
915    };
916
917    for post_closure in &self.after_construct {
918      post_closure(document, whatsit)?;
919    }
920    Ok(Vec::new())
921  }
922  fn get_reversion_spec(&self) -> Option<Reversion> { self.reversion.clone() }
923}
924
925#[cfg(test)]
926mod tests {
927  use super::*;
928
929  #[test]
930  fn constructor_options_default_all_false_none_empty() {
931    let o = ConstructorOptions::default();
932    assert!(o.nargs.is_none());
933    assert!(!o.bounded);
934    assert!(o.mode.is_none());
935    assert!(!o.enter_horizontal);
936    assert!(!o.leave_horizontal);
937    assert!(!o.require_math);
938    assert!(!o.forbid_math);
939    assert!(!o.capture_body);
940    assert!(o.font.is_none());
941    assert!(o.scope.is_none());
942    assert!(!o.robust);
943    assert!(!o.locked);
944    assert!(o.alias.is_none());
945    assert!(o.reversion.is_none());
946    assert!(o.sizer.is_none());
947    assert!(o.before_digest.is_empty());
948    assert!(o.after_digest.is_empty());
949    assert!(o.before_construct.is_empty());
950    assert!(o.after_construct.is_empty());
951    assert!(o.after_digest_begin.is_empty());
952    assert!(o.before_digest_end.is_empty());
953    assert!(o.after_digest_body.is_empty());
954  }
955
956  #[test]
957  fn constructor_default_fields() {
958    let c = Constructor::default();
959    assert!(c.nargs.is_none());
960    assert!(c.paramlist.is_none());
961    assert!(c.replacement.is_none());
962    assert!(c.sizer.is_none());
963    assert!(!c.capture_body);
964    assert!(c.alias.is_none());
965    assert!(c.reversion.is_none());
966    assert!(c.before_digest.is_empty());
967    assert!(c.after_digest.is_empty());
968    assert!(c.before_construct.is_empty());
969    assert!(c.after_construct.is_empty());
970    assert!(c.after_digest_body.is_empty());
971  }
972
973  #[test]
974  fn constructor_options_debug_includes_fields() {
975    // The hand-written Debug impl formats the struct; just verify it
976    // doesn't panic and produces a non-empty string that contains
977    // key field names.
978    let o = ConstructorOptions::default();
979    let s = format!("{o:?}");
980    assert!(s.contains("nargs"), "got {s:?}");
981    assert!(s.contains("bounded"), "got {s:?}");
982    assert!(s.contains("capture_body"), "got {s:?}");
983  }
984}