Skip to main content

latexml_core/
definition.rs

1#[macro_use]
2pub mod expandable;
3pub mod argument;
4pub mod conditional;
5pub mod constructor;
6pub mod math_primitive;
7pub mod origin;
8pub mod primitive;
9pub mod register;
10
11use std::{borrow::Cow, fmt, rc::Rc};
12
13use libxml::tree::Node;
14
15use self::{
16  argument::ArgWrap,
17  register::{RegisterType, RegisterValue},
18};
19use crate::{
20  Digested,
21  common::{
22    arena::{self, SymHashMap, SymStr},
23    dimension::Dimension,
24    error::{emit_warn, *},
25    font::Font,
26    object::Object,
27    store::Stored,
28  },
29  definition::conditional::ConditionalType,
30  document::Document,
31  gullet::Gullet,
32  mouth,
33  parameter::Parameters,
34  state::{Scope, expire_state_unlocked, local_state_unlocked},
35  token::Token,
36  tokens::{NO_TOKENS, TeXString, Tokens},
37  whatsit::Whatsit,
38};
39
40pub type ExpansionClosure = Rc<dyn Fn(Vec<ArgWrap>) -> Result<Tokens>>;
41pub type ConditionalClosure = Rc<dyn Fn(Vec<ArgWrap>) -> Result<bool>>;
42pub type PrimitiveFn = dyn Fn(Vec<ArgWrap>) -> Result<Vec<Digested>>;
43pub type PrimitiveClosure = Rc<PrimitiveFn>;
44pub type BeforeDigestClosure = Rc<dyn Fn() -> Result<Vec<Digested>>>;
45pub type PropertiesClosure = Rc<dyn Fn(&Vec<Option<Digested>>) -> Result<SymHashMap<Stored>>>;
46pub type DigestionClosure = Rc<dyn Fn(&mut Whatsit) -> Result<Vec<Digested>>>;
47pub type ReplacementClosure =
48  Rc<dyn Fn(&mut Document, &Vec<Option<Digested>>, &SymHashMap<Stored>) -> Result<()>>;
49pub type ConstructionClosure = Rc<dyn Fn(&mut Document, &Whatsit) -> Result<()>>;
50pub type DigestedReversionClosure = Rc<dyn Fn(&Whatsit, &Vec<Option<Digested>>) -> Result<Tokens>>;
51pub type SizingClosure = Rc<dyn Fn(&Whatsit) -> Result<(Dimension, Dimension, Dimension)>>;
52pub type FontClosure = Rc<dyn Fn(Option<&Whatsit>) -> Result<Font>>;
53
54#[derive(Clone)]
55pub enum ExpansionBody {
56  Closure(ExpansionClosure),
57  Tokens(Tokens),
58}
59
60impl ExpansionBody {
61  /// A convenience method that pushes a token into the internal tokens of
62  /// an existing `ExpansionBody::Tokens`, re-wrapping the outer structs
63  pub fn push(&mut self, t: Token) {
64    match self {
65      ExpansionBody::Tokens(tks) => tks.unlist_mut().push(t),
66      ExpansionBody::Closure(_) => {
67        // Can't push a token into a closure-based expansion — silently ignore
68      },
69    }
70  }
71}
72
73/// What a body coded in the host language prints where Perl prints `CODE(0x…)`: no address, so the same on every run
74/// (QA89), and still `CODE(`.
75pub const CLOSURE_BODY_TEXT: &str = "CODE(native)";
76
77/// `\meaning`'s text for a closure body of `cs`: its name, letters only, keeps two natives' meanings apart as Perl's
78/// addresses did (`\value` vs `\arabic`); any other name prints [`CLOSURE_BODY_TEXT`].
79pub fn closure_body_meaning(cs: &str) -> String {
80  let name = cs.strip_prefix('\\').unwrap_or(cs);
81  if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphabetic() || c == '@') {
82    format!("CODE({name})")
83  } else {
84    CLOSURE_BODY_TEXT.to_string()
85  }
86}
87
88impl fmt::Debug for ExpansionBody {
89  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90    match self {
91      ExpansionBody::Closure(_) => f.write_str(CLOSURE_BODY_TEXT),
92      ExpansionBody::Tokens(ts) => write!(f, "{ts:?}"),
93    }
94  }
95}
96
97impl Default for ExpansionBody {
98  fn default() -> Self { ExpansionBody::Tokens(NO_TOKENS) }
99}
100
101impl PartialEq for ExpansionBody {
102  fn eq(&self, other: &ExpansionBody) -> bool {
103    // A closure body is never `\ifx`-equal to a token body — OXIDIZED_DESIGN
104    // #183. Perl `Common/Object.pm:80-95` `Equals` (and this port, until 2026-09)
105    // matched the closure's `CODE(0x…)` `\meaning` text against a token body so
106    // a `\meaning`→`\scantokens`→`\ifx` round-trip "reconstructed" native
107    // macros; biditools' patchcmd clone (`\bidi@ifscanable`, biditools.sty:792)
108    // then believed it could patch the native `\begin`/`\end` and replaced
109    // them with a body whose tail was the literal text `CODE(…)` — every later
110    // environment lost its `\begingroup` ("Attempt to close a group that
111    // switched to mode horizontal", crbox-doc, ghab-doc; Perl errs the same
112    // way, KNOWN_PERL_ERRORS #147). Guard:
113    // `perfect_kernel_batch54::biditools_env_patch_leaves_begin_end_intact`.
114    match (self, other) {
115      (ExpansionBody::Closure(a), ExpansionBody::Closure(b)) => Rc::ptr_eq(a, b),
116      (ExpansionBody::Tokens(a), ExpansionBody::Tokens(b)) => a == b,
117      _ => false,
118    }
119  }
120}
121
122#[derive(Clone)]
123pub enum PrimitiveBody {
124  Closure(PrimitiveClosure),
125  String(SymStr),
126}
127impl From<char> for PrimitiveBody {
128  fn from(c: char) -> Self { PrimitiveBody::String(arena::pin_char(c)) }
129}
130
131#[derive(Clone)]
132pub enum Reversion {
133  Closure(DigestedReversionClosure),
134  Tokens(Tokens),
135}
136
137impl PartialEq for Reversion {
138  fn eq(&self, other: &Reversion) -> bool {
139    match self {
140      Reversion::Tokens(t) => match other {
141        Reversion::Tokens(t2) => t == t2,
142        _ => false,
143      },
144      // never compare pointers - i.e. never equal
145      _ => false,
146    }
147  }
148}
149
150/// NOTE (`TeXString` guard): this and `From<&str> for ExpansionBody` below are
151/// the residual back doors into the tokenizer — a `String` reaches them as
152/// `s.as_str()` without ever naming its intent. They stay on plain `&str`
153/// because narrowing them to `&'static str` would reject the many legitimate
154/// runtime-built bodies. Anything that flattens `Tokens` must still go through
155/// [`Tokens::untex_string`](crate::tokens::Tokens::untex_string) before it gets
156/// here.
157impl From<&str> for Reversion {
158  fn from(t: &str) -> Reversion {
159    Reversion::Tokens(
160      mouth::tokenize_internal(TeXString::assembled(t.to_string()))
161        .pack_parameters()
162        .unwrap(),
163    )
164  }
165}
166impl From<Tokens> for Reversion {
167  fn from(ts: Tokens) -> Reversion { Reversion::Tokens(ts) }
168}
169
170impl From<Token> for ExpansionBody {
171  fn from(t: Token) -> ExpansionBody { ExpansionBody::Tokens(Tokens!(t)) }
172}
173
174impl From<Token> for Option<ExpansionBody> {
175  fn from(t: Token) -> Option<ExpansionBody> { Some(ExpansionBody::Tokens(Tokens!(t))) }
176}
177
178impl From<Tokens> for ExpansionBody {
179  fn from(t: Tokens) -> ExpansionBody { ExpansionBody::Tokens(t) }
180}
181
182impl From<Tokens> for Option<ExpansionBody> {
183  fn from(t: Tokens) -> Option<ExpansionBody> { if t.is_empty() { None } else { Some(t.into()) } }
184}
185
186impl From<&str> for ExpansionBody {
187  fn from(s: &str) -> ExpansionBody {
188    mouth::tokenize_internal(TeXString::assembled(s.to_string())).into()
189  }
190}
191
192impl From<String> for ExpansionBody {
193  fn from(s: String) -> ExpansionBody { s.as_str().into() }
194}
195
196impl From<ArgWrap> for ExpansionBody {
197  fn from(t: ArgWrap) -> ExpansionBody {
198    ExpansionBody::Tokens(t.owned_tokens().unwrap_or_default())
199  }
200}
201impl From<ArgWrap> for Option<ExpansionBody> {
202  fn from(t: ArgWrap) -> Option<ExpansionBody> {
203    match t.owned_tokens() {
204      Some(tks) if !tks.is_empty() => Some(ExpansionBody::Tokens(tks)),
205      _ => None,
206    }
207  }
208}
209
210#[derive(Clone)]
211pub enum FontDirective {
212  Closure(FontClosure),
213  Asset(Rc<Font>),
214}
215
216impl From<Font> for FontDirective {
217  fn from(f: Font) -> Self { FontDirective::Asset(Rc::new(f)) }
218}
219impl From<FontClosure> for FontDirective {
220  fn from(fc: FontClosure) -> Self { FontDirective::Closure(fc) }
221}
222impl FontDirective {
223  pub fn get_font(&self, whatsit: Option<&Whatsit>) -> Result<Rc<Font>> {
224    match self {
225      FontDirective::Closure(fc) => Ok(Rc::new((fc)(whatsit)?)),
226      FontDirective::Asset(font) => Ok(Rc::clone(font)),
227    }
228  }
229  pub fn get_asset(&self) -> Option<Rc<Font>> {
230    if let FontDirective::Asset(font) = self {
231      Some(Rc::clone(font))
232    } else {
233      None
234    }
235  }
236}
237impl fmt::Debug for FontDirective {
238  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
239    match self {
240      FontDirective::Closure(_) => write!(f, "<FontClosure>"),
241      FontDirective::Asset(font) => write!(f, "{:?}", *font),
242    }
243  }
244}
245impl PartialEq for FontDirective {
246  fn eq(&self, other: &FontDirective) -> bool {
247    match self {
248      FontDirective::Closure(_) => false, // we can't compare them for now?
249      FontDirective::Asset(asset1) => match other {
250        FontDirective::Closure(_) => false,
251        FontDirective::Asset(asset2) => *asset1 == *asset2,
252      },
253    }
254  }
255}
256
257/// The mode transitions a binding's options compile to for a primitive or constructor (its
258/// `mode`, `enter_horizontal`, `leave_horizontal`, `bounded`, `require_math` and `forbid_math`
259/// options), kept beside the digestion closures so that an audit can compare them with the
260/// prologue of the real macro the binding replaces (KERNEL_CAPABILITIES K13). The definers
261/// build those closures from this record, so the two cannot drift apart.
262///
263/// It holds what the options compile to, not their spelling: an environment that names no
264/// mode records `restricted_horizontal` (Perl's `DefEnvironmentI`, Package.pm:1902), and
265/// `bounded` is dropped when a mode is given. It covers the opening side only (`\begin{env}`
266/// and the bare `\env`; the closers undo it), and only the options: a prologue a binding's
267/// closure performs by hand (`enter_horizontal()` in its body) is not in it. A robust
268/// command's record is on its `\cs␣` body, not on the `\protect` wrapper.
269///
270/// The prologue runs in the fixed order of Perl's `DefPrimitiveI`/`DefConstructorI`
271/// (Package.pm:1303-1309, 1465-1471): `require_math`, `forbid_math`, `enter_horizontal`,
272/// `leave_horizontal`, then the mode (or the group when `bounded`). No definition declares both
273/// horizontal transitions, in Perl's pools or here; one that did would start a paragraph and
274/// then end it.
275#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
276pub struct DeclaredMode {
277  /// The mode the definition begins, after `text` is lowered to `restricted_horizontal`.
278  pub mode:             Option<SymStr>,
279  /// Starts a paragraph first: declared, or implied by a primitive's or constructor's
280  /// `mode => "text"` (Package.pm:1297-1299, 1459-1461; not an environment's).
281  pub enter_horizontal: bool,
282  /// Ends the paragraph, after `enter_horizontal` when both are declared.
283  pub leave_horizontal: bool,
284  /// Opens a group: `bounded` with no mode, or a math constructor without `nogroup`.
285  pub bounded:          bool,
286  pub require_math:     bool,
287  pub forbid_math:      bool,
288  /// Declared `mode => "restricted_horizontal"` itself (not `text`, not an environment's default): the constructor
289  /// builds a TeX box (`\hbox`, `\mbox`, `\fcolorbox`, `\scalebox`), the first element it opens outside math marked
290  /// for a frontmatter field's print (core `document::FIELD_BOX_PROPERTY`, OXIDIZED_DESIGN #715).
291  pub restricted_box:   bool,
292}
293
294pub trait Definition: Object {
295  fn invoke(&self, once_only: bool) -> Result<Tokens>;
296  /// Expand onto the input: [`Self::invoke`]'s result pushed back with [`crate::gullet::unread_expansion`], as
297  /// the gullet's macro expansion does. An expandable with a token-list body substitutes its arguments straight
298  /// onto the input instead (tex.web §390 `macro_call`).
299  fn invoke_onto_input(&self, once_only: bool) -> Result<()> {
300    crate::gullet::unread_expansion(self.invoke(once_only)?);
301    Ok(())
302  }
303  /// [`expandable::SpecialCall::Native`], for a call the gullet expands in full: only there, so a one-step
304  /// `\expandafter` and every other reader of the expansion get the macro's own body.
305  fn native_expansion(&self) -> Result<Option<Tokens>> { Ok(None) }
306  fn invoke_primitive(&self) -> Result<Vec<Digested>>;
307
308  /// We can almost always return the CS by reference, except in a Register's RefCell, where we are
309  /// forced to clone
310  fn get_cs(&self) -> Cow<'_, Token>;
311  fn get_cs_name(&self) -> Cow<'_, str>;
312  fn get_cs_or_alias(&self) -> Cow<'_, Token> {
313    match self.get_alias() {
314      Some(alias) => Cow::Owned(T_CS!(alias)),
315      None => self.get_cs(),
316    }
317  }
318  fn get_sizer(&self) -> Option<SizingClosure> { None }
319  /// The mode transitions the binding declared ([`DeclaredMode`]); `None` for definitions
320  /// not made by a definer that takes mode options (macros, registers, raw-TeX definitions,
321  /// a primitive built by hand). The audit reads `None` on a primitive or constructor as
322  /// declaring nothing.
323  fn declared_mode(&self) -> Option<DeclaredMode> { None }
324  /// The font a primitive or constructor was declared with (its `font => {…}` option), which its
325  /// digestion merges into the current font; `None` for every other definition. latex.ltx's
326  /// `\@fontswitch` reads a math alphabet as a switch to the group's end (`\mathrm\relax` with
327  /// `\math@bgroup` let to `\relax`, latex.ltx:14312-14321): the binding's switch merges this font
328  /// (`\lx@math@alphabet@switch`, latex_constructs/sect13.rs).
329  fn declared_font(&self) -> Option<&FontDirective> { None }
330  /// The literal XML template that is a constructor's whole construction: its replacement's source (`DefConstructor!`
331  /// with a string replacement), when no construction hook (`before_construct`, `after_construct`) adds to it. `None`
332  /// for a closure replacement, a constructor made at run time and every other definition: what it builds cannot be
333  /// read off it (the frontmatter's no-ink test, latexml_engine util_text.rs `first_ink`, counts such a whatsit as ink).
334  fn replacement_template(&self) -> Option<&'static str> { None }
335  fn get_alias(&self) -> Option<&String>;
336  fn is_protected(&self) -> bool { false }
337  /// Whether this macro peeks at the next token the way latex.ltx's
338  /// `\@ifnextchar` does (1756-1760): by `\futurelet`, behind an unexpandable
339  /// `\let`. A number scan (tex.web §445) ends at such a macro instead of
340  /// expanding it (see `gullet::expands_now`). A binding closure that makes an
341  /// assignment as it expands carries it too when its TeX original reaches an
342  /// unexpandable token (`\begingroup`, `\let`, `\relax`) before it acts:
343  /// etoolbox's `\newrobustcmd` and `\patchcmd`, amsthm's `\pushQED`.
344  fn peeks_by_futurelet(&self) -> bool { false }
345  fn is_register(&self) -> bool { false }
346  fn is_prefix(&self) -> bool { false }
347  fn is_readonly(&self) -> bool { false }
348  fn get_test(&self) -> Option<&ConditionalClosure> { None }
349  fn get_conditional_type(&self) -> Option<ConditionalType> { None }
350
351  fn read_arguments(&self) -> Result<Vec<ArgWrap>>
352  where Self: Sized {
353    match self.get_parameters() {
354      None => Ok(Vec::new()),
355      Some(params) => params.read_arguments(Some(self)),
356    }
357  }
358  fn get_parameters(&self) -> Option<&Parameters>;
359
360  // ======================================================================
361  // Return the Tokens that would invoke the given definition with arguments.
362  fn invocation(&mut self, args: Vec<Option<Tokens>>, _gullet: &mut Gullet) -> Result<Tokens> {
363    let mut invocation_result: Vec<Token> = vec![self.get_cs().into_owned()];
364
365    match self.get_parameters() {
366      None => {},
367      Some(params) => {
368        for result_token in params.revert_arguments(args)? {
369          invocation_result.push(result_token);
370        }
371      },
372    }
373    Ok(Tokens::new(invocation_result))
374  }
375
376  fn get_num_args(&self) -> usize { 0 }
377
378  fn do_absorption(&self, _document: &mut Document, _whatsit: &Whatsit) -> Result<Vec<Node>>;
379  fn before_digest(&self) -> Option<&Vec<BeforeDigestClosure>> { None }
380  fn after_digest(&self) -> Option<&Vec<DigestionClosure>> { None }
381  fn after_digest_body(&self) -> Option<&Vec<DigestionClosure>> { None }
382  fn capture_body(&self) -> bool { false }
383
384  fn execute_before_digest(&self) -> Result<Vec<Digested>> {
385    local_state_unlocked(true);
386    // Perl #2798 (S2): executeBeforeDigest pushes each hook's result DIRECTLY
387    // onto the active @LaTeXML::LIST as it runs, rather than collecting them to
388    // be prepended later. This lets a *later* before_digest side-effect see the
389    // earlier hooks' boxes in the current list — e.g. `\AtBeginEnvironment{
390    // equation}{…}` digests its text into the paragraph BEFORE the equation's
391    // own `before_equation` does `begin_mode("display_math")` → leave_horizontal,
392    // so the hook text stays in the (outside) paragraph instead of splitting off.
393    // The final box order is unchanged (these boxes still precede the whatsit,
394    // which the caller appends and the digestion loop pushes afterwards); only
395    // the *timing* moves earlier. Returns nothing.
396    if let Some(pre_list) = self.before_digest() {
397      for pre in pre_list.iter() {
398        for bx in pre()? {
399          crate::stomach::push_box_list(bx);
400        }
401      }
402    }
403    expire_state_unlocked();
404    Ok(Vec::new())
405  }
406  fn execute_after_digest(&self, whatsit: &mut Whatsit) -> Result<Vec<Digested>> {
407    local_state_unlocked(true);
408    let mut after_digested = Vec::new();
409    if let Some(post_list) = self.after_digest() {
410      for post in post_list.iter() {
411        after_digested.extend(post(whatsit)?);
412      }
413    }
414    expire_state_unlocked();
415    Ok(after_digested)
416  }
417
418  fn execute_after_digest_body(&self, whatsit: &mut Whatsit) -> Result<Vec<Digested>> {
419    local_state_unlocked(true);
420    let mut after_body_digested = Vec::new();
421    if let Some(post_list) = self.after_digest_body() {
422      // info!("Found {:?} after_digest_body closures, capture_body was: {:?}", post_list.len(),
423      // self.capture_body());
424      for post in post_list {
425        let after_body_digest_result = post(whatsit)?;
426        after_body_digested.extend(after_body_digest_result);
427      }
428    }
429    expire_state_unlocked();
430    Ok(after_body_digested)
431  }
432
433  fn value_of(&self, _args: Vec<ArgWrap>) -> Option<RegisterValue> { None }
434  /// runs the setter to assign the value for a register
435  fn set_value(
436    &self,
437    _value: RegisterValue,
438    _scope: Option<Scope>,
439    _args: Vec<ArgWrap>,
440  ) -> Result<()> {
441    emit_warn(
442      "internal",
443      "register",
444      "set_value called on non-register definition",
445    );
446    Ok(())
447  }
448  fn register_type(&self) -> Option<RegisterType> { None }
449  fn get_reversion_spec(&self) -> Option<Reversion> { None }
450  fn get_expansion(&self) -> Option<&ExpansionBody> { None }
451
452  fn stringify_type(&self, deftype: &str) -> String {
453    let name = match self.get_alias() {
454      Some(alias) => alias.clone(),
455      None => self.get_cs().with_cs_name(ToString::to_string),
456    };
457    if let Some(parameters) = self.get_parameters() {
458      s!("{}[{} {}]", deftype, name, parameters.stringify())
459    } else {
460      s!("{}[{}]", deftype, name)
461    }
462  }
463}
464
465// We need to compare definitions for the internal TeX logic to make sense, but we don't have Perl's
466// level of meta-programming, since cloning an `Rc<Definition>` for storage makes it impossible to
467// compare with the old `Rc<Definition>`. Hence, we need our own meta-programming "hack", via the
468// `stringify` method that is different for each `definition` implementation
469// (`Primitive`/`Constructor`/etc) and each control sequence
470//
471// This could evolve if Rust comes up with a best practice for implementing `PartialEq` on trait
472// objects.
473impl PartialEq for dyn Definition {
474  fn eq(&self, other: &dyn Definition) -> bool { self.stringify() == other.stringify() }
475}
476
477impl fmt::Display for dyn Definition {
478  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
479    if let Some(params) = self.get_parameters() {
480      write!(f, "{} {}", self.get_cs_name(), params)
481    } else {
482      write!(f, "{}", self.get_cs_name())
483    }
484  }
485}
486
487impl fmt::Display for ExpansionBody {
488  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
489    match self {
490      ExpansionBody::Tokens(t) => write!(f, "{t}"),
491      ExpansionBody::Closure(_) => f.write_str(CLOSURE_BODY_TEXT),
492    }
493  }
494}