Skip to main content

latexml_core/definition/
math_primitive.rs

1use std::borrow::Cow;
2
3use libxml::tree::Node;
4
5use super::SizingClosure;
6use crate::{
7  Digested,
8  common::{
9    arena::SymHashMap as HashMap, error::*, font::LettersClass, object::Object, store::Stored,
10  },
11  definition::{
12    BeforeDigestClosure, ConstructionClosure, Definition, DigestionClosure, FontDirective,
13    PrimitiveClosure, Reversion,
14  },
15  document::Document,
16  parameter::Parameters,
17  state::Scope,
18  token::*,
19  tokens::Tokens,
20  whatsit::Whatsit,
21};
22
23// DefMath Define a Mathematical symbol or function.
24// There are two sets of cases:
25//  (1) If the presentation appears to be TeX code, we create an XMDual,
26// since the presentation may end up with structure, etc.
27//  (2) But if the presentation is a simple string, or unicode,
28// it is just the content of the symbol; even if the function takes arguments.
29// ALSO
30//  arrange that the operator token gets cs="$cs"
31// ALSO
32//  Possibly some trick with SUMOP/INTOP affecting limits ?
33//  Well, not exactly, but....
34// HMM.... Still fishy.
35// When to make a dual ?
36// If the $presentation seems to be TeX (ie. it involves #1... but not ONLY!)
37
38#[derive(Clone, Default)]
39pub struct MathPrimitiveOptions {
40  pub bounded:          bool,
41  pub mode:             Option<String>,
42  pub before_digest:    Vec<BeforeDigestClosure>,
43  pub after_digest:     Vec<DigestionClosure>,
44  pub before_construct: Vec<ConstructionClosure>,
45  pub after_construct:  Vec<ConstructionClosure>,
46  pub is_prefix:        bool,
47  pub scope:            Option<Scope>,
48  pub font:             Option<FontDirective>,
49  pub require_math:     bool,
50  pub forbid_math:      bool,
51  pub locked:           bool,
52  pub alias:            Option<String>,
53  pub decl_id:          Option<String>,
54  pub replace:          Option<String>,
55  pub protected:        bool,
56  pub robust:           bool,
57
58  // Math specific
59  pub name:                   Option<String>,
60  pub meaning:                Option<String>,
61  pub omcd:                   Option<String>,
62  pub reversion:              Option<Reversion>,
63  pub sizer:                  Option<SizingClosure>,
64  pub role:                   Option<String>,
65  pub operator_role:          Option<String>,
66  pub reorder:                bool,
67  pub dual:                   bool,
68  pub mathstyle:              Option<String>,
69  /// A variable-size operator: Perl's `mathstyle => \&doVariablesizeOp`
70  /// (TeX_Math.pool.ltxml:353) — the `mathstyle` is computed at construction
71  /// from the current style (`display` in display style, else `text`) instead
72  /// of being a fixed value (`\int`, `\sum`, amsmath's `\iint` family).
73  pub variablesize_op:        bool,
74  pub scriptpos:              Option<String>,
75  /// Dynamic scriptpos: compute "mid"/"post" based on current font mathstyle at invocation time
76  /// Perl: scriptpos => \&doScriptpos
77  pub dynamic_scriptpos:      bool,
78  pub operator_scriptpos:     Option<usize>,
79  pub stretchy:               Option<bool>,
80  pub operator_stretchy:      Option<bool>,
81  pub nogroup:                bool,
82  pub hide_content_reversion: bool,
83  pub revert_as:              Option<Cow<'static, str>>,
84  pub lpadding:               Option<usize>,
85  pub rpadding:               Option<usize>,
86  /// A glyph `\DeclareMathSymbol`'d from the math italic symbol font (`letters`), with its math class: the token's
87  /// font is specialized by `Font::specialize_letters` (a capital Greek letter italic as the class says).
88  pub letters_class:          Option<LettersClass>,
89  /// A Warning that belongs to the symbol's print, not its digestion: carried as the box's
90  /// [`ABSORB_WARNING_PROPERTY`](crate::document::ABSORB_WARNING_PROPERTY) (on the simple primitive's box and on a
91  /// constructor's whatsit alike) and raised once per key when the document absorbs it
92  /// ([`absorb_warning`](crate::document::absorb_warning)) — an undecodable glyph's once-per-font Warning
93  /// (`\DeclareMathSymbol`, OXIDIZED_DESIGN_DIVERGENCES #27). A property, so a simple symbol stays on the primitive
94  /// path with a simple symbol's box and sizing.
95  pub absorb_warning:         Option<Stored>,
96}
97impl PartialEq for MathPrimitiveOptions {
98  fn eq(&self, other: &MathPrimitiveOptions) -> bool {
99    self.name == other.name && self.meaning == other.meaning && self.role == other.role
100  }
101}
102
103impl MathPrimitiveOptions {
104  pub fn to_hash_stored(&self) -> HashMap<Stored> {
105    let mut h = HashMap::default();
106    if let Some(ref meaning) = self.meaning {
107      h.insert("meaning", meaning.into());
108    }
109    if let Some(ref name) = self.name {
110      h.insert("name", name.into());
111    }
112    if let Some(ref omcd) = self.omcd {
113      h.insert("omcd", omcd.into());
114    }
115    if let Some(ref role) = self.role {
116      h.insert("role", role.into());
117    }
118    if let Some(ref decl_id) = self.decl_id {
119      h.insert("decl_id", decl_id.into());
120    }
121    if let Some(ref warning) = self.absorb_warning {
122      h.insert(crate::document::ABSORB_WARNING_PROPERTY, warning.clone());
123    }
124    if let Some(ref operator_role) = self.operator_role {
125      h.insert("operator_role", operator_role.into());
126    }
127    if let Some(ref mathstyle) = self.mathstyle {
128      h.insert("mathstyle", mathstyle.into());
129    }
130    if let Some(ref scriptpos) = self.scriptpos {
131      h.insert("scriptpos", scriptpos.into());
132    }
133    if let Some(ref operator_scriptpos) = self.operator_scriptpos {
134      h.insert(
135        "operator_scriptpos",
136        Stored::Int(*operator_scriptpos as i64),
137      );
138    }
139    if let Some(ref stretchy) = self.stretchy {
140      h.insert("stretchy", (*stretchy).into());
141    }
142    if let Some(ref stretchy) = self.operator_stretchy {
143      h.insert("operator_stretchy", (*stretchy).into());
144    }
145    if let Some(ref mode) = self.mode {
146      h.insert("mode", mode.into());
147    }
148    // TODO: Do we want to run the font closures here? Maybe?
149    if let Some(ref font_directive) = self.font {
150      h.insert("font", Stored::FontDirective(font_directive.clone()));
151    }
152    if let Some(ref lpadding) = self.lpadding {
153      h.insert("lpadding", (*lpadding).into());
154    }
155    if let Some(ref rpadding) = self.rpadding {
156      h.insert("rpadding", (*rpadding).into());
157    }
158
159    h
160  }
161
162  /// Like `to_hash_stored` but applies per-invocation overrides without
163  /// cloning the whole options. Used in DefMath closures (hot path —
164  /// one call per math token invocation).
165  pub fn to_hash_stored_with_overrides(
166    &self,
167    mode_override: Option<&'static str>,
168    mathstyle_override: Option<&'static str>,
169    scriptpos_override: Option<&'static str>,
170  ) -> HashMap<Stored> {
171    let mut h = self.to_hash_stored();
172    if let Some(m) = mode_override {
173      h.insert("mode", Stored::String(crate::common::arena::pin_static(m)));
174    }
175    if let Some(ms) = mathstyle_override {
176      h.insert(
177        "mathstyle",
178        Stored::String(crate::common::arena::pin_static(ms)),
179      );
180    }
181    if let Some(sp) = scriptpos_override {
182      h.insert(
183        "scriptpos",
184        Stored::String(crate::common::arena::pin_static(sp)),
185      );
186    }
187    h
188  }
189
190  /// Whether an option outside Perl's `$simpletoken_options` is present (Package.pm:1603-1607:
191  /// name, meaning, omcd, role, mathstyle, stretchy, protected, robust, alias, lpadding,
192  /// rpadding, font, scriptpos, scope, locked), which makes a parameterless DefMath a constructor
193  /// rather than a box (Package.pm:1665). `alias` and `stretchy` are simple: counted complex, the
194  /// eighteen stretchy delimiters (`\langle`, `\{`, `\lceil`, amsmath's `\lvert`, …) became
195  /// constructors whose font is read at construction, so `\big\langle` lost its size and
196  /// `\boldmath` its bold. `variablesize_op` and `dynamic_scriptpos` are Perl's code-valued
197  /// `mathstyle` and `scriptpos`; the construct hooks are complex, as in Perl.
198  pub fn has_complex_option(&self) -> bool {
199    // Perl's simple-token options (Package.pm:1602-1606) do not include `nogroup`.
200    self.bounded
201      || self.nogroup
202      || self.mode.is_some()
203      || !self.before_digest.is_empty()
204      || !self.after_digest.is_empty()
205      || self.is_prefix
206      || self.require_math
207      || self.forbid_math
208      || self.decl_id.is_some()
209      || self.replace.is_some()
210      || self.reversion.is_some()
211      || self.sizer.is_some()
212      || self.operator_role.is_some()
213      || self.reorder
214      || self.dual
215      || self.operator_scriptpos.is_some()
216      || self.operator_stretchy.is_some()
217      || self.hide_content_reversion
218      || self.revert_as.is_some()
219      || !self.before_construct.is_empty()
220      || !self.after_construct.is_empty()
221  }
222}
223
224#[derive(Clone)]
225pub struct MathPrimitive {
226  pub cs:          Token,
227  pub paramlist:   Option<Parameters>,
228  pub nargs:       Option<usize>,
229  pub replacement: Option<PrimitiveClosure>,
230  pub options:     MathPrimitiveOptions,
231  pub alias:       Option<String>,
232  pub origin:      crate::definition::origin::DefinitionOrigin,
233}
234impl Default for MathPrimitive {
235  fn default() -> Self {
236    MathPrimitive {
237      cs:          T_CS!("MathPrimitive"),
238      paramlist:   None,
239      nargs:       None,
240      replacement: None,
241      options:     MathPrimitiveOptions::default(),
242      alias:       None,
243      origin:      crate::definition::origin::current_origin(),
244    }
245  }
246}
247impl PartialEq for MathPrimitive {
248  fn eq(&self, other: &MathPrimitive) -> bool { self.cs == other.cs }
249}
250
251// impl fmt::Display for MathPrimitive {
252//   fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
253//     todo!();
254//   }
255// }
256impl Object for MathPrimitive {
257  fn stringify(&self) -> String { <Self as Definition>::stringify_type(self, "MathPrimitive") }
258}
259impl Definition for MathPrimitive {
260  fn before_digest(&self) -> Option<&Vec<BeforeDigestClosure>> { Some(&self.options.before_digest) }
261  fn after_digest(&self) -> Option<&Vec<DigestionClosure>> { Some(&self.options.after_digest) }
262  fn invoke(&self, _once_only: bool) -> Result<Tokens> { Ok(Tokens!()) }
263  fn invoke_primitive(&self) -> Result<Vec<Digested>> {
264    // Info!("MathPrimitive", "invoke", stomach, "invoke for {:?}", self.cs);
265    // my $profiled = $state->lookupValue('PROFILING') && ($LaTeXML::CURRENT_TOKEN || $$self{cs});
266    // my $tracing = $state->lookupValue('tracingcommands');
267    // LaTeXML::Core::Definition::startProfiling($profiled, 'digest') if $profiled;
268    // print STDERR '{' . $self->tracingCSName . "}\n" if $tracing;
269    let mut result: Vec<Digested> = self.execute_before_digest()?;
270    let args = self.read_arguments()?;
271    // print STDERR $self->tracingArgs(@args) . "\n" if $tracing && @args;
272    let replacement_result = match self.replacement {
273      None => Vec::new(),
274      Some(ref closure) => closure(args)?,
275    };
276    result.extend(replacement_result);
277    let mut w = Whatsit::default();
278    let after_result = self.execute_after_digest(&mut w)?;
279    result.extend(after_result);
280
281    // LaTeXML::Core::Definition::stopProfiling($profiled, 'digest') if $profiled;
282    Ok(result)
283  }
284
285  fn do_absorption(&self, _document: &mut Document, _whatsit: &Whatsit) -> Result<Vec<Node>> {
286    fatal!(
287      Definition,
288      Unexpected,
289      "do_absorption on MathPrimitive should never be called!"
290    );
291  }
292
293  fn get_cs(&self) -> Cow<'_, Token> { Cow::Borrowed(&self.cs) }
294  fn get_cs_name(&self) -> Cow<'_, str> { Cow::Owned(self.cs.with_cs_name(ToString::to_string)) }
295  fn get_alias(&self) -> Option<&String> { self.alias.as_ref() }
296  fn get_parameters(&self) -> Option<&Parameters> { self.paramlist.as_ref() }
297  fn get_num_args(&self) -> usize {
298    match self.nargs {
299      Some(n) => n,
300      None => match self.paramlist {
301        Some(ref params) => params.get_num_args(),
302        None => 0,
303      },
304    }
305    // TODO: Rethink the memoize in this immutable setting
306    // self.nargs = Some(nargs);
307  }
308}
309
310#[cfg(test)]
311mod tests {
312  use super::*;
313
314  #[test]
315  fn math_primitive_options_default_fields() {
316    let o = MathPrimitiveOptions::default();
317    // Spot-check representative fields from the ~30-field struct.
318    assert!(!o.bounded);
319    assert!(!o.is_prefix);
320    assert!(!o.require_math);
321    assert!(!o.forbid_math);
322    assert!(!o.locked);
323    assert!(!o.robust);
324    assert!(!o.protected);
325    assert!(!o.reorder);
326    assert!(!o.dual);
327    assert!(!o.variablesize_op);
328    assert!(!o.dynamic_scriptpos);
329    assert!(
330      !o.nogroup,
331      "a DefMath constructor digests in its own group unless nogroup (Package.pm:1707)"
332    );
333    assert!(!o.hide_content_reversion);
334    assert!(o.name.is_none());
335    assert!(o.meaning.is_none());
336    assert!(o.role.is_none());
337    assert!(o.operator_role.is_none());
338    assert!(o.mathstyle.is_none());
339    assert!(o.scriptpos.is_none());
340    assert!(o.operator_scriptpos.is_none());
341    assert!(o.stretchy.is_none());
342    assert!(o.operator_stretchy.is_none());
343    assert!(o.revert_as.is_none());
344    assert!(o.lpadding.is_none());
345    assert!(o.rpadding.is_none());
346    assert!(o.before_digest.is_empty());
347    assert!(o.after_digest.is_empty());
348  }
349
350  #[test]
351  fn math_primitive_options_partial_eq_by_subset() {
352    // PartialEq compares name + meaning + role only — defaults of
353    // other fields don't affect equality.
354    let mut a = MathPrimitiveOptions::default();
355    let mut b = MathPrimitiveOptions::default();
356    a.name = Some("plus".into());
357    b.name = Some("plus".into());
358    assert!(a == b, "same name equal");
359    // Changing a non-compared field still keeps them equal.
360    a.locked = true;
361    assert!(a == b);
362    // Changing a compared field breaks equality.
363    b.name = Some("times".into());
364    assert!(!(a == b));
365  }
366
367  #[test]
368  fn math_primitive_options_to_hash_stored_empty_default() {
369    // Default options with no string fields set produces an empty
370    // HashMap.
371    let o = MathPrimitiveOptions::default();
372    let h = o.to_hash_stored();
373    assert_eq!(h.len(), 0);
374  }
375
376  #[test]
377  fn math_primitive_options_to_hash_stored_with_fields() {
378    let o = MathPrimitiveOptions {
379      meaning: Some("plus".into()),
380      name: Some("+".into()),
381      ..Default::default()
382    };
383    let h = o.to_hash_stored();
384    assert!(h.contains_key("meaning"));
385    assert!(h.contains_key("name"));
386    assert!(
387      !h.contains_key("role"),
388      "role=None shouldn't populate the hash"
389    );
390  }
391
392  #[test]
393  fn math_primitive_default_fields() {
394    let m = MathPrimitive::default();
395    assert!(m.paramlist.is_none());
396    assert!(m.replacement.is_none());
397    assert!(m.alias.is_none());
398    assert!(m.nargs.is_none());
399    // options and flags live in m.options, not directly on the struct.
400    assert!(m.options.reversion.is_none());
401    assert!(!m.options.is_prefix);
402  }
403
404  #[test]
405  fn math_primitive_partial_eq_by_cs() {
406    let a = MathPrimitive::default();
407    let b = MathPrimitive::default();
408    // Both defaults have the same cs → equal.
409    assert!(a == b);
410  }
411}