Skip to main content

latexml_core/common/
store.rs

1use std::{borrow::Cow, cell::RefCell, collections::VecDeque, fmt, rc::Rc};
2
3use libxml::tree::Node;
4use rustc_hash::FxHashMap as HashMap;
5
6use crate::definition::math_primitive::MathPrimitive; //MathPrimitiveOptions
7use crate::{
8  alignment::Alignment,
9  common::{
10    arena::{self, SymStr, data::SymHashMap},
11    dimension::Dimension,
12    error::*,
13    float::Float,
14    font::Font,
15    glue::Glue,
16    locator::Locator,
17    mudimension::MuDimension,
18    muglue::MuGlue,
19    number::Number,
20    numeric_ops::NumericOps,
21  },
22  definition::{
23    Definition, FontDirective, Reversion,
24    argument::ArgWrap,
25    conditional::{Conditional, IfFrame},
26    constructor::Constructor,
27    expandable::Expandable,
28    primitive::Primitive,
29    register::{Register, RegisterValue},
30  },
31  document::tag::{RawFrontmatter, TagList},
32  keyval::KeyVal,
33  keyvals::KeyVals,
34  ligature::Ligature,
35  list::List,
36  mouth,
37  mouth::Mouth,
38  parameter::Parameter,
39  rewrite::Rewrite,
40  state::StashTable,
41  token::{Catcode, Token},
42  tokens::{TeXString, Tokens},
43};
44
45const STORED_TRUE: Stored = Stored::Bool(true);
46const STORED_FALSE: Stored = Stored::Bool(false);
47
48// Basic principles:
49// 1. If the type is `Copy`, store directly
50// 2. If the type is intended as state-exclusive, store in a Box (or directly if any already Boxed
51//    datatype such as Vec, VecDeque, HashMap)
52// 3. If the struct is intended for reuse in digestion components, store it in an Rc, e.g. Rc<Font>
53// 4. In the very unfortunate cases where we have to mutate items while they are stored, we may
54//    consider a RefCell<> wrapper for interior mutability. BUT it is often possible to take the
55//    value out to mutate, and re-insert. state::checkout_value(key) + mutate +
56//    state::checkin_value(key,val) The only cases where this isn't straightforward is for deep
57//    recursive callchains, as in the ones where we rely on Stomach or a Mouth being in state.
58/// The original global state (in Perl) allowed arbitrary values. To stay consistent, we create an
59/// extremely permissive struct that affords all essential kinds of values that appear essential.
60#[derive(Default, Clone)]
61pub enum Stored {
62  /// if we want to keep a key but make it 'undef', set it to None
63  #[default]
64  None,
65  // Primitives (Copy types, or cheap Clone)
66  /// atomic data (Copy)
67  Bool(bool),
68  /// atomic data (Clone)
69  String(SymStr),
70  /// atomic data (Copy)
71  Charcode(u16),
72  /// atomic data (Copy)
73  /// note that we currently work with 64-bit integers
74  Int(i64),
75  /// atomic data (Clone)
76  Node(Node),
77  // Collections (boxed)
78  /// boxed [char]
79  Chars(Box<[char]>),
80  /// boxed `[Option<char>]`
81  Fontmap(Rc<[Option<char>]>),
82  /// A font's parameters, `\fontdimen1`.. in sp (TeX's `param` array; Perl's
83  /// `$$fontinfo{data}`, TeX_Fonts.pool.ltxml:131-146): one array per font,
84  /// written in place, since a `\fontdimen` assignment is always global
85  /// (tex.web §1253). expl3 keeps its intarrays here.
86  FontDimens(Rc<RefCell<Vec<i64>>>),
87  /// boxed collection
88  Strings(Rc<[SymStr]>),
89  /// boxed collection (latexml)
90  VecDigested(Vec<crate::Digested>),
91  /// the heart of state - a stored Stash table
92  Stash(StashTable),
93  /// boxed map
94  HashString(HashMap<String, String>),
95  /// boxed collection - Stored
96  VecDequeStored(VecDeque<Stored>),
97  /// boxed map - Stored
98  HashStored(SymHashMap<Stored>),
99  /// boxed map (latexml)
100  HashTagData(HashMap<String, TagList>),
101  /// queued-but-undigested frontmatter commands (Perl: `frontmatter_raw`)
102  FrontmatterRaw(Vec<RawFrontmatter>),
103  // LaTeXML primitives (Copy types)
104  /// latexml object
105  Catcode(Catcode),
106  /// latexml object
107  Token(Token),
108  /// latexml object
109  Tokens(Tokens),
110  /// latexml object
111  Number(Number),
112  /// latexml object
113  Float(Float),
114  /// latexml object
115  Glue(Glue),
116  /// latexml object
117  MuGlue(MuGlue),
118  /// latexml object
119  Dimension(Dimension),
120  /// latexml object
121  MuDimension(MuDimension),
122  /// metadata object
123  Locator(Box<Locator>),
124  /// latexml object
125  Rewrite(Box<Rewrite>),
126  /// latexml object
127  Ligature(Box<Ligature>),
128  /// latexml object
129  Reversion(Reversion),
130  // LaTeXML objects (Rc-wrapped)
131  /// latexml object (Rc-wrapped)
132  Register(Rc<Register>),
133  /// latexml object (Rc-wrapped)
134  Expandable(Rc<Expandable>),
135  /// latexml object (Rc-wrapped)
136  Conditional(Rc<Conditional>),
137  /// latexml object (Rc-wrapped)
138  Primitive(Rc<Primitive>),
139  /// latexml object (Rc-wrapped)
140  MathPrimitive(Rc<MathPrimitive>),
141  //  MathPrimitiveOptions(MathPrimitiveOptions), // Maybe later
142  /// latexml object (Rc-wrapped)
143  Constructor(Rc<Constructor>),
144  /// latexml object (Rc-wrapped from within)
145  Digested(crate::Digested),
146  /// latexml object (Rc-wrapped)
147  Parameter(Rc<Parameter>),
148  /// latexml object (Rc-wrapped)
149  Font(Rc<Font>),
150  /// a stored FontDirective (Font or closure building a Font)
151  FontDirective(FontDirective),
152  /// WALL OF SHAME (interior mutability) -- can we dispense with these?
153  Mouth(Rc<RefCell<Mouth>>),
154  /// WALL OF SHAME (interior mutability) -- can we dispense with these?
155  IfFrame(Rc<RefCell<IfFrame>>),
156  /// latexml keyval definition
157  KeyVal(KeyVal),
158  /// latexml keyvals collection
159  KeyVals(Rc<KeyVals>),
160  /// alignment template (for storing between macros, e.g. deluxetable)
161  Template(Rc<crate::alignment::template::Template>),
162  /// A binding-private payload carried on a whatsit's properties (Perl's
163  /// `%props` held any scalar or reference): a parsed tree, a parser context.
164  /// Cheap to clone (`Rc`), compared by identity, never serialized to a dump,
165  /// downcast at the reading site (`Rc::downcast`/`Any::downcast_ref`). This
166  /// is what lets a constructor's `properties` hand its own `before_digest`
167  /// result to its replacement without a thread-local side table.
168  Opaque(Rc<dyn std::any::Any>),
169}
170
171impl fmt::Debug for Stored {
172  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
173    use crate::Stored::*;
174    match *self {
175      None => write!(f, "None"),
176      String(ref s) => arena::with(*s, |str| write!(f, "{str}")),
177      Int(ref num) => write!(f, "Stored::Int[{num:?}]"),
178      Node(ref n) => write!(f, "Stored::Node[{n:?}]"),
179      Chars(ref vs) => write!(f, "Stored::Chars[{vs:?}]"),
180      Fontmap(ref vs) => write!(f, "Stored::Fontmap[{vs:?}]"),
181      FontDimens(ref params) => write!(f, "Stored::FontDimens[{} params]", params.borrow().len()),
182      Stash(ref vs) => write!(f, "Stored::Stash[{vs:?}]"),
183      Strings(ref vs) => write!(f, "Stored::Strings[{vs:?}]"),
184      Bool(ref b) => write!(f, "Stored::Bool[{b:?}]"),
185      Token(ref t) => write!(f, "Stored::Token[{t:?}]"),
186      Tokens(ref t) => write!(f, "Stored::Tokens[{t:?}]"),
187      Locator(ref t) => write!(f, "Stored::Locator[{t:?}]"),
188      Reversion(ref _t) => write!(f, "Stored::Reversion[TODO]"),
189      Catcode(ref cc) => write!(f, "Stored::Catcode[{cc:?}]"),
190      Charcode(ref cc) => write!(f, "Stored::Charcode[{cc:?}]"),
191      IfFrame(ref fr) => write!(f, "Stored::IfFrame[{fr:?}]"),
192      Expandable(ref expandable) => write!(f, "Stored::Expandable[{expandable:?}]"),
193      Conditional(ref _conditional) => write!(f, "Stored::Conditional[TODO]"),
194      Primitive(ref _primitive) => write!(f, "Stored::Primitive[TODO]"),
195      MathPrimitive(ref _primitive) => write!(f, "Stored::MathPrimitive[TODO]"),
196      // MathPrimitiveOptions(ref _primitive) => write!(f, "<math primitive options>"),
197      Constructor(ref _constructor) => write!(f, "Stored::Constructor[TODO]"),
198      Digested(ref digested) => write!(f, "Stored::Digested[{digested:?}]"),
199      Parameter(ref parameter) => write!(f, "Stored::Parameter[{parameter:?}]"),
200      Register(ref register) => write!(f, "Stored::Register[{:?}]", register.cs),
201      Rewrite(ref rewrite) => write!(f, "Stored::Rewrite[{rewrite:?}]"),
202      Mouth(ref mouth) => write!(f, "Stored::Mouth[{:?}]", mouth.borrow().get_source()),
203      Font(ref font) => write!(f, "Stored::Font[{font:?}]"),
204      FontDirective(ref font) => write!(f, "Stored::FontDirective[{font:?}]"),
205      Number(ref number) => write!(f, "Stored::Number[{number:?}]"),
206      Float(ref float) => write!(f, "Stored::Float[{float:?}]"),
207      Glue(ref glue) => write!(f, "Stored::Glue[{glue:?}]"),
208      MuGlue(ref glue) => write!(f, "Stored::MuGlue[{glue:?}]"),
209      Dimension(ref dimension) => write!(f, "Stored::Dimension[{dimension:?}]"),
210      MuDimension(ref dimension) => write!(f, "Stored::MuDimension[{dimension:?}]"),
211      VecDigested(ref digested_vec) => write!(f, "VecDigested{digested_vec:?}"),
212      VecDequeStored(ref vec) => write!(f, "VecDequeStored{vec:?}"),
213      HashStored(ref hos) => write!(f, "HashStored{hos:?}"),
214      HashTagData(ref htd) => write!(f, "HashTagData[{htd:?}]"),
215      FrontmatterRaw(ref raw) => write!(f, "FrontmatterRaw[{raw:?}]"),
216      HashString(ref hstr) => write!(f, "HashStr[{hstr:?}]"),
217      Ligature(ref lig) => write!(f, "Ligature[{lig:?}]"),
218      KeyVal(ref kv) => write!(f, "KeyVal[{kv:?}]"),
219      KeyVals(ref kvs) => write!(f, "KeyVals[{kvs:?}]"),
220      Template(ref t) => write!(f, "Template[{t}]"),
221      Opaque(_) => write!(f, "Stored::Opaque"),
222    }
223  }
224}
225impl fmt::Display for Stored {
226  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
227    use crate::Stored::*;
228    match *self {
229      Digested(ref digested) => write!(f, "{digested}"),
230      Dimension(ref v) => write!(f, "{v}"),
231      Number(ref v) => write!(f, "{v}"),
232      Float(ref v) => write!(f, "{v}"),
233      Glue(ref v) => write!(f, "{v}"),
234      MuGlue(ref v) => write!(f, "{v}"),
235      MuDimension(ref v) => write!(f, "{v}"),
236      Font(ref font) => write!(f, "{font}"),
237      FontDirective(ref font) => write!(f, "{font:?}"),
238      String(ref s) => arena::with(*s, |str| write!(f, "{str}")),
239      Int(ref s) => write!(f, "{s}"),
240      Bool(ref s) => write!(f, "{s}"),
241      Tokens(ref s) => write!(f, "{s}"),
242      Token(ref s) => write!(f, "{s}"),
243      Conditional(ref s) => write!(f, "{s}"),
244      Constructor(ref c) => write!(f, "Constructor[{}]", c.get_cs_name()),
245      Strings(ref vs) => write!(f, "{}", arena::join(vs, ",")),
246      KeyVals(ref kvs) => write!(f, "{kvs}"),
247      Template(ref t) => write!(f, "{t}"),
248      None => write!(f, "Stored[None]"),
249      _ => write!(f, "Stored[??]"),
250    }
251  }
252}
253
254/// Note: PartialEq on Stored is *structural*. See WISDOM.md for RegisterType trap.
255impl PartialEq for Stored {
256  fn eq(&self, other: &Stored) -> bool {
257    use crate::Stored::*;
258    match *self {
259      None => matches!(other, None),
260      String(ref s) => {
261        if let String(s2) = other {
262          *s == *s2
263        } else {
264          false
265        }
266      },
267      Int(ref num) => {
268        if let Int(num2) = other {
269          *num == *num2
270        } else {
271          false
272        }
273      },
274      Node(ref n) => {
275        if let Node(n2) = other {
276          *n == *n2
277        } else {
278          false
279        }
280      },
281      Chars(ref vs) => {
282        if let Chars(vs2) = other {
283          **vs == **vs2
284        } else {
285          false
286        }
287      },
288      Fontmap(ref vs) => {
289        if let Fontmap(vs2) = other {
290          *vs == *vs2
291        } else {
292          false
293        }
294      },
295      FontDimens(ref params) => {
296        if let FontDimens(params2) = other {
297          *params.borrow() == *params2.borrow()
298        } else {
299          false
300        }
301      },
302      Strings(ref vs) => {
303        if let Strings(vs2) = other {
304          *vs == *vs2
305        } else {
306          false
307        }
308      },
309      Bool(ref b) => {
310        if let Bool(b2) = other {
311          *b == *b2
312        } else {
313          false
314        }
315      },
316      Token(ref t) => {
317        if let Token(t2) = other {
318          *t == *t2
319        } else {
320          false
321        }
322      },
323      Tokens(ref t) => {
324        if let Tokens(t2) = other {
325          *t == *t2
326        } else {
327          false
328        }
329      },
330      Locator(ref t) => {
331        if let Locator(t2) = other {
332          *t == *t2
333        } else {
334          false
335        }
336      },
337      Reversion(ref t) => {
338        if let Reversion(t2) = other {
339          *t == *t2
340        } else {
341          false
342        }
343      },
344      Catcode(ref cc) => {
345        if let Catcode(cc2) = other {
346          *cc == *cc2
347        } else {
348          false
349        }
350      },
351      Charcode(ref cc) => {
352        if let Charcode(cc2) = other {
353          *cc == *cc2
354        } else {
355          false
356        }
357      },
358      IfFrame(ref fr) => {
359        if let IfFrame(fr2) = other {
360          *fr.borrow() == *fr2.borrow()
361        } else {
362          false
363        }
364      },
365      Expandable(ref e) => {
366        if let Expandable(e2) = other {
367          **e == **e2
368        } else {
369          false
370        }
371      },
372      Conditional(ref c) => {
373        if let Conditional(c2) = other {
374          **c == **c2
375        } else {
376          false
377        }
378      },
379      Primitive(ref p) => {
380        if let Primitive(p2) = other {
381          **p == **p2
382        } else {
383          false
384        }
385      },
386      MathPrimitive(ref p) => {
387        if let MathPrimitive(p2) = other {
388          **p == **p2
389        } else {
390          false
391        }
392      },
393      // MathPrimitiveOptions(ref _primitive) =>
394      Constructor(ref c) => {
395        if let Constructor(c2) = other {
396          **c == **c2
397        } else {
398          false
399        }
400      },
401      Digested(ref d) => {
402        if let Digested(d2) = other {
403          *d == *d2
404        } else {
405          false
406        }
407      },
408      Parameter(ref p) => {
409        if let Parameter(p2) = other {
410          **p == **p2
411        } else {
412          false
413        }
414      },
415      Register(ref r) => {
416        if let Register(r2) = other {
417          **r == **r2
418        } else {
419          false
420        }
421      },
422      Rewrite(ref r) => {
423        if let Rewrite(r2) = other {
424          *r == *r2
425        } else {
426          false
427        }
428      },
429      Mouth(ref m) => {
430        if let Mouth(m2) = other {
431          *m.borrow() == *m2.borrow()
432        } else {
433          false
434        }
435      },
436      Font(ref f) => {
437        if let Font(f2) = other {
438          **f == **f2
439        } else {
440          false
441        }
442      },
443      FontDirective(ref fd) => {
444        if let FontDirective(fd2) = other {
445          fd == fd2
446        } else {
447          false
448        }
449      },
450      Number(ref n) => {
451        if let Number(n2) = other {
452          *n == *n2
453        } else {
454          false
455        }
456      },
457      Float(ref n) => {
458        if let Float(n2) = other {
459          *n == *n2
460        } else {
461          false
462        }
463      },
464      Glue(ref g) => {
465        if let Glue(g2) = other {
466          *g == *g2
467        } else {
468          false
469        }
470      },
471      MuGlue(ref mg) => {
472        if let MuGlue(mg2) = other {
473          *mg == *mg2
474        } else {
475          false
476        }
477      },
478      Dimension(ref d) => {
479        if let Dimension(d2) = other {
480          *d == *d2
481        } else {
482          false
483        }
484      },
485      MuDimension(ref md) => {
486        if let MuDimension(md2) = other {
487          *md == *md2
488        } else {
489          false
490        }
491      },
492      VecDigested(ref vd) => {
493        if let VecDigested(vd2) = other {
494          *vd == *vd2
495        } else {
496          false
497        }
498      },
499      VecDequeStored(ref v) => {
500        if let VecDequeStored(v2) = other {
501          v.len() == v2.len() && v.iter().zip(v2.iter()).all(|(item1, item2)| item1 == item2)
502        } else {
503          false
504        }
505      },
506      Stash(ref v) => {
507        if let Stash(v2) = other {
508          v.len() == v2.len() // TODO: Do we need accuracy on stash comparisons?
509        } else {
510          false
511        }
512      },
513      HashStored(ref hs) => {
514        if let HashStored(hs2) = other {
515          hs.len() == hs2.len()
516            && hs.iter().all(|(key, value)| {
517              if let Some(item2) = hs2.get_sym(*key) {
518                value == item2
519              } else {
520                false
521              }
522            })
523        } else {
524          false
525        }
526      },
527      HashTagData(ref htd) => {
528        if let HashTagData(htd2) = other {
529          *htd == *htd2
530        } else {
531          false
532        }
533      },
534      FrontmatterRaw(ref raw) => {
535        if let FrontmatterRaw(raw2) = other {
536          *raw == *raw2
537        } else {
538          false
539        }
540      },
541      HashString(ref hstr) => {
542        if let HashString(hstr2) = other {
543          *hstr == *hstr2
544        } else {
545          false
546        }
547      },
548      Ligature(ref lig) => {
549        if let Ligature(lig2) = other {
550          *lig == *lig2
551        } else {
552          false
553        }
554      },
555      KeyVal(ref kv) => {
556        if let KeyVal(kv2) = other {
557          *kv == *kv2
558        } else {
559          false
560        }
561      },
562      KeyVals(ref kvs) => {
563        if let KeyVals(kvs2) = other {
564          Rc::ptr_eq(kvs, kvs2)
565        } else {
566          false
567        }
568      },
569      Template(ref t) => {
570        if let Template(t2) = other {
571          Rc::ptr_eq(t, t2)
572        } else {
573          false
574        }
575      },
576      Opaque(ref a) => {
577        if let Opaque(b) = other {
578          Rc::ptr_eq(a, b)
579        } else {
580          false
581        }
582      },
583    }
584  }
585}
586
587impl Stored {
588  /// Zero-alloc equivalent of `self.to_string() == target` for the two
589  /// string-carrying variants (`String`, `Tokens`). Falls back to
590  /// `to_string()` for everything else, where the Display impl allocates
591  /// anyway.
592  pub fn eq_text(&self, target: &str) -> bool {
593    match self {
594      Stored::String(s) => arena::with(*s, |v| v == target),
595      Stored::Tokens(t) => t.eq_text(target),
596      Stored::Token(t) => t.with_str(|v| v == target),
597      other => other.to_string() == target,
598    }
599  }
600
601  /// A list-shaped value: exposed to the Rhai `LookupValue` binding as an array
602  /// (mirroring Perl's `LookupValue` returning an arrayref), and having no
603  /// scalar string form — so `lookup_string` returns "" for it rather than
604  /// leaking the internal Debug repr (#315). The two variants a `push_value` /
605  /// list `AssignValue` can produce: `VecDequeStored` (a pushed queue, e.g.
606  /// `class_options`) and `Strings` (an immutable string array).
607  pub fn is_list(&self) -> bool { matches!(self, Stored::VecDequeStored(_) | Stored::Strings(_)) }
608
609  /// The items of a list value as strings, for structural access. `None` for a
610  /// non-list value.
611  pub fn list_items(&self) -> Option<Vec<String>> {
612    match self {
613      Stored::Strings(ss) => Some(ss.iter().map(|s| arena::to_string(*s)).collect()),
614      Stored::VecDequeStored(v) => Some(v.iter().map(String::from).collect()),
615      _ => None,
616    }
617  }
618
619  /// Zero-alloc `self.to_string().starts_with(prefix)` for the
620  /// string-carrying variants; falls back to `to_string()` for others.
621  pub fn starts_with_text(&self, prefix: &str) -> bool {
622    match self {
623      Stored::String(s) => arena::with(*s, |v| v.starts_with(prefix)),
624      Stored::Tokens(t) => t.starts_with_text(prefix),
625      Stored::Token(t) => t.with_str(|v| v.starts_with(prefix)),
626      other => other.to_string().starts_with(prefix),
627    }
628  }
629
630  /// Zero-alloc `self.to_string().ends_with(suffix)` for the String /
631  /// Token variants (where the entire Display output equals the
632  /// interned text). For Tokens, we still walk into a small owned
633  /// String — ends_with requires anchoring at the tail and rolling
634  /// backward, which needs random access. Others fall back to
635  /// `to_string()` (cost paid anyway via the Display impl).
636  pub fn ends_with_text(&self, suffix: &str) -> bool {
637    match self {
638      Stored::String(s) => arena::with(*s, |v| v.ends_with(suffix)),
639      Stored::Token(t) => t.with_str(|v| v.ends_with(suffix)),
640      other => other.to_string().ends_with(suffix),
641    }
642  }
643
644  /// helper method that uses `ToString::to_string` to flatten a map with Stored values
645  // TODO: Obviously a performance issue, find a way to unify the interfaces where string allocation
646  // is completely avoided until serialization in the XML.
647  // libxml can accept &str, so as long as we can stay within the interner arena paradigm,
648  // we should be allocation free. [end TODO]
649  pub fn cast_to_string_hash(in_map: &SymHashMap<Stored>) -> HashMap<String, String> {
650    let mut out_map: HashMap<String, String> = HashMap::default();
651    for (key, val) in in_map {
652      // Use to_attribute() so MuGlue/MuDimension widths are converted to pt
653      // (e.g. `3.0mu` → `1.66663pt`) before becoming XML attribute strings.
654      // Mirror Perl `attributeformat` which uses `ptValue` for mu-typed
655      // lengths in attribute context.
656      out_map.insert(arena::to_string(*key), val.to_attribute());
657    }
658    out_map
659  }
660  /// Dynamic dispatch for Definition's `read_arguments`,
661  /// to circumvent the limitations of using trait objects with `Rc<Definition>`
662  pub fn read_arguments(&self) -> Result<Vec<ArgWrap>> {
663    match self {
664      Stored::Conditional(entry) => entry.read_arguments(),
665      Stored::Constructor(entry) => entry.read_arguments(),
666      Stored::Expandable(entry) => entry.read_arguments(),
667      Stored::MathPrimitive(entry) => entry.read_arguments(),
668      Stored::Primitive(entry) => entry.read_arguments(),
669      Stored::Register(entry) => entry.read_arguments(),
670      e => Err(s!(".read_arguments not defined for stored variant {:?}", e).into()),
671    }
672  }
673  /// Uses `NumericOps::to_attribute` for Stored values supporting it, otherwise
674  /// `ToString::to_string`
675  pub fn to_attribute(&self) -> String {
676    match self {
677      Stored::Dimension(v) => v.to_attribute(),
678      Stored::Number(v) => v.to_attribute(),
679      Stored::MuDimension(v) => v.to_attribute(),
680      Stored::Glue(v) => v.to_attribute(),
681      Stored::MuGlue(v) => v.to_attribute(),
682      other => other.to_string(),
683    }
684  }
685  pub fn to_definition(&self) -> Option<Rc<dyn Definition>> {
686    match self {
687      Stored::Primitive(defn) => Some(defn.clone()),
688      Stored::MathPrimitive(defn) => Some(defn.clone()),
689      Stored::Conditional(defn) => Some(defn.clone()),
690      Stored::Register(defn) => Some(defn.clone()),
691      Stored::Expandable(defn) => Some(defn.clone()),
692      Stored::Constructor(defn) => Some(defn.clone()),
693      _ => None,
694    }
695  }
696}
697
698impl From<bool> for Stored {
699  fn from(value: bool) -> Self { Stored::Bool(value) }
700}
701
702impl From<bool> for &Stored {
703  fn from(value: bool) -> Self { if value { &STORED_TRUE } else { &STORED_FALSE } }
704}
705
706impl From<Cow<'_, str>> for Stored {
707  fn from(value: Cow<'_, str>) -> Self { Stored::String(arena::pin(value)) }
708}
709impl From<String> for Stored {
710  fn from(value: String) -> Self { Stored::String(arena::pin(value)) }
711}
712impl From<SymStr> for Stored {
713  fn from(value: SymStr) -> Self { Stored::String(value) }
714}
715
716impl From<char> for Stored {
717  fn from(value: char) -> Self { Stored::String(arena::pin_char(value)) }
718}
719
720impl<'a> From<&'a String> for Stored {
721  fn from(value: &'a String) -> Self { Stored::String(arena::pin(value)) }
722}
723
724impl From<&'static str> for Stored {
725  fn from(value: &'static str) -> Self { Stored::String(arena::pin_static(value)) }
726}
727
728impl From<usize> for Stored {
729  fn from(value: usize) -> Self { Stored::Int(value as i64) }
730}
731
732// TODO: Should we add a lot more numeric nuance to the Store ?
733impl From<u8> for Stored {
734  fn from(value: u8) -> Self { Stored::Int(value as i64) }
735}
736
737impl From<i32> for Stored {
738  fn from(value: i32) -> Self { Stored::Int(value as i64) }
739}
740impl From<i64> for Stored {
741  fn from(value: i64) -> Self { Stored::Int(value) }
742}
743
744impl From<f64> for Stored {
745  fn from(value: f64) -> Self { Stored::Number(Number::new(value.floor() as i64)) }
746}
747
748impl From<Catcode> for Stored {
749  fn from(value: Catcode) -> Self { Stored::Catcode(value) }
750}
751
752impl From<Token> for Stored {
753  fn from(value: Token) -> Self { Stored::Token(value) }
754}
755
756// Storing all definitions is expected - Rc<Expandable> case
757
758impl From<Tokens> for Stored {
759  fn from(value: Tokens) -> Self { Stored::Tokens(value) }
760}
761
762impl From<Locator> for Stored {
763  fn from(value: Locator) -> Self { Stored::Locator(Box::new(value)) }
764}
765
766impl From<Mouth> for Stored {
767  fn from(value: Mouth) -> Self { Stored::Mouth(Rc::new(RefCell::new(value))) }
768}
769
770impl From<Rc<Expandable>> for Stored {
771  fn from(definition: Rc<Expandable>) -> Self { Stored::Expandable(definition) }
772}
773/// Storing all definitions is expected - Expandable case
774impl From<Expandable> for Stored {
775  fn from(definition: Expandable) -> Self { Rc::new(definition).into() }
776}
777
778impl From<Rc<Conditional>> for Stored {
779  fn from(definition: Rc<Conditional>) -> Self { Stored::Conditional(definition) }
780}
781impl From<Conditional> for Stored {
782  fn from(value: Conditional) -> Self { Rc::new(value).into() }
783}
784
785impl From<Rc<Primitive>> for Stored {
786  fn from(definition: Rc<Primitive>) -> Self { Stored::Primitive(definition) }
787}
788impl From<Primitive> for Stored {
789  fn from(value: Primitive) -> Self { Rc::new(value).into() }
790}
791
792impl From<Rc<MathPrimitive>> for Stored {
793  fn from(definition: Rc<MathPrimitive>) -> Self { Stored::MathPrimitive(definition) }
794}
795impl From<MathPrimitive> for Stored {
796  fn from(value: MathPrimitive) -> Self { Rc::new(value).into() }
797}
798
799impl From<Rc<Constructor>> for Stored {
800  fn from(definition: Rc<Constructor>) -> Self { Stored::Constructor(definition) }
801}
802impl From<Constructor> for Stored {
803  fn from(value: Constructor) -> Self { Rc::new(value).into() }
804}
805
806impl From<List> for Stored {
807  fn from(value: List) -> Self { crate::Digested::from(value).into() }
808}
809
810impl From<Node> for Stored {
811  fn from(value: Node) -> Self { Stored::Node(value) }
812}
813
814impl From<crate::Digested> for Stored {
815  fn from(value: crate::Digested) -> Self { Stored::Digested(value) }
816}
817
818impl From<&crate::Digested> for Stored {
819  fn from(value: &crate::Digested) -> Self { Stored::Digested(value.clone()) }
820}
821
822impl<T> From<Option<T>> for Stored
823where T: Into<Stored> + Sized
824{
825  fn from(value_opt: Option<T>) -> Self {
826    match value_opt {
827      None => Stored::None,
828      Some(v) => v.into(),
829    }
830  }
831}
832
833impl<'a> From<Cow<'a, crate::Digested>> for Stored {
834  fn from(value: Cow<'a, crate::Digested>) -> Self { Stored::Digested(value.into_owned()) }
835}
836
837impl From<Box<crate::Digested>> for Stored {
838  fn from(value: Box<crate::Digested>) -> Self { Stored::Digested(*value) }
839}
840
841impl From<Parameter> for Stored {
842  fn from(value: Parameter) -> Self { Stored::Parameter(Rc::new(value)) }
843}
844
845impl From<Rc<Font>> for Stored {
846  fn from(font: Rc<Font>) -> Self { Stored::Font(font) }
847}
848
849impl From<Rc<Register>> for Stored {
850  fn from(register: Rc<Register>) -> Self { Stored::Register(register) }
851}
852impl From<Register> for Stored {
853  fn from(register: Register) -> Self { Rc::new(register).into() }
854}
855
856impl From<Rewrite> for Stored {
857  fn from(value: Rewrite) -> Self { Stored::Rewrite(Box::new(value)) }
858}
859
860impl From<Font> for Stored {
861  fn from(value: Font) -> Self { Rc::new(value).into() }
862}
863
864impl From<Cow<'_, Font>> for Stored {
865  fn from(value: Cow<Font>) -> Self { Rc::new((*value).clone()).into() }
866}
867
868impl From<Number> for Stored {
869  fn from(value: Number) -> Self { Stored::Number(value) }
870}
871// A distinct slot from `From<f64>` above, which FLOORS to an integer `Number`
872// (TeX registers are integral). A `Float` value keeps its fraction — the only
873// path that stores `Stored::Float`, so an `AssignFloat` binding must build a
874// `Float`, not lean on `f64 -> Stored`.
875impl From<Float> for Stored {
876  fn from(value: Float) -> Self { Stored::Float(value) }
877}
878impl From<Dimension> for Stored {
879  fn from(value: Dimension) -> Self { Stored::Dimension(value) }
880}
881impl From<MuDimension> for Stored {
882  fn from(value: MuDimension) -> Self { Stored::MuDimension(value) }
883}
884impl From<Glue> for Stored {
885  fn from(value: Glue) -> Self { Stored::Glue(value) }
886}
887impl From<MuGlue> for Stored {
888  fn from(value: MuGlue) -> Self { Stored::MuGlue(value) }
889}
890
891impl<'a> From<&'a Token> for Stored {
892  fn from(value: &'a Token) -> Self { Stored::Token(*value) }
893}
894
895impl From<Alignment> for Stored {
896  fn from(a: Alignment) -> Self { Stored::Digested(crate::Digested::from(a)) }
897}
898
899impl From<Box<[char]>> for Stored {
900  fn from(value: Box<[char]>) -> Self { Stored::Chars(value) }
901}
902impl From<Rc<[Option<char>]>> for Stored {
903  fn from(value: Rc<[Option<char>]>) -> Self { Stored::Fontmap(value) }
904}
905
906impl From<Rc<[SymStr]>> for Stored {
907  fn from(value: Rc<[SymStr]>) -> Self { Stored::Strings(value) }
908}
909
910impl From<Vec<String>> for Stored {
911  fn from(value: Vec<String>) -> Self { Stored::Strings(value.iter().map(arena::pin).collect()) }
912}
913
914impl<'a> From<Vec<&'a str>> for Stored {
915  fn from(value: Vec<&'a str>) -> Self { Stored::Strings(value.iter().map(arena::pin).collect()) }
916}
917
918impl From<Vec<Token>> for Stored {
919  fn from(value: Vec<Token>) -> Self { Stored::Tokens(Tokens::new(value)) }
920}
921
922impl From<Vec<crate::Digested>> for Stored {
923  fn from(value: Vec<crate::Digested>) -> Self { Stored::VecDigested(value) }
924}
925
926impl From<HashMap<String, String>> for Stored {
927  fn from(value: HashMap<String, String>) -> Self { Stored::HashString(value) }
928}
929
930impl From<VecDeque<Stored>> for Stored {
931  fn from(value: VecDeque<Stored>) -> Self { Stored::VecDequeStored(value) }
932}
933
934impl From<HashMap<SymStr, Stored>> for Stored {
935  fn from(value: HashMap<SymStr, Stored>) -> Self { Stored::HashStored(SymHashMap(value)) }
936}
937impl From<SymHashMap<Stored>> for Stored {
938  fn from(value: SymHashMap<Stored>) -> Self { Stored::HashStored(value) }
939}
940
941// TODO: What is the right interface here? Should we really commit to SymStr?
942// Or is it too distracting from a developer perspective and String should be allowed more widely?
943impl From<HashMap<String, Stored>> for Stored {
944  fn from(str_hash: HashMap<String, Stored>) -> Self {
945    let mut arena_value = HashMap::default();
946    for (key, value) in str_hash {
947      arena_value.insert(arena::pin(key), value);
948    }
949    Stored::HashStored(SymHashMap(arena_value))
950  }
951}
952
953impl From<HashMap<String, TagList>> for Stored {
954  fn from(value: HashMap<String, TagList>) -> Self { Stored::HashTagData(value) }
955}
956
957impl From<RegisterValue> for Stored {
958  fn from(rv: RegisterValue) -> Self {
959    match rv {
960      RegisterValue::Number(v) => Stored::Number(v),
961      RegisterValue::Dimension(v) => Stored::Dimension(v),
962      RegisterValue::MuDimension(v) => Stored::MuDimension(v),
963      RegisterValue::Glue(v) => Stored::Glue(v),
964      RegisterValue::MuGlue(v) => Stored::MuGlue(v),
965      RegisterValue::Token(v) => Stored::Token(v),
966      RegisterValue::Tokens(v) => Stored::Tokens(v),
967      RegisterValue::Pair(_) => Stored::None, // TODO: add Stored::Pair
968    }
969  }
970}
971
972impl From<Rc<RefCell<IfFrame>>> for Stored {
973  fn from(frame: Rc<RefCell<IfFrame>>) -> Stored { Stored::IfFrame(frame) }
974}
975
976impl From<Ligature> for Stored {
977  fn from(lig: Ligature) -> Stored { Stored::Ligature(Box::new(lig)) }
978}
979
980impl From<Reversion> for Stored {
981  fn from(rev: Reversion) -> Stored { Stored::Reversion(rev) }
982}
983
984impl From<KeyVal> for Stored {
985  fn from(kv: KeyVal) -> Stored { Stored::KeyVal(kv) }
986}
987
988impl From<KeyVals> for Stored {
989  fn from(kvs: KeyVals) -> Stored { Stored::KeyVals(Rc::new(kvs)) }
990}
991
992impl From<crate::alignment::template::Template> for Stored {
993  fn from(t: crate::alignment::template::Template) -> Stored { Stored::Template(Rc::new(t)) }
994}
995
996impl From<Option<&Stored>> for Stored {
997  fn from(stored_opt: Option<&Stored>) -> Stored {
998    match stored_opt {
999      Some(val) => val.clone(),
1000      None => Stored::Bool(false),
1001    }
1002  }
1003}
1004
1005// Reverse direction -- cast Stored back into concrete types, with meaningfull fallbacks where
1006// impossible
1007
1008impl From<&Stored> for bool {
1009  fn from(value: &Stored) -> bool {
1010    // Mirror Perl's `if ($val)` truthiness: defined-and-nonzero is true,
1011    // numeric-zero is false. Without the numeric-zero check, registers
1012    // initialized to 0 (e.g. `\globaldefs` default, `\count255` unset)
1013    // would read as "set" via `lookup_bool`, breaking flag-style probes.
1014    match value {
1015      Stored::Bool(b) => *b,
1016      Stored::Int(0) => false,
1017      Stored::Number(n) if n.0 == 0 => false,
1018      _ => true,
1019    }
1020  }
1021}
1022
1023impl From<&Stored> for String {
1024  fn from(value: &Stored) -> String {
1025    match value {
1026      Stored::String(v) => arena::to_string(*v),
1027      // A token list reads as its text (Perl's `ToString`), not its Debug form (repro rhai-bindings/lookupstring_of_tokens).
1028      Stored::Tokens(t) => t.to_string(),
1029      Stored::Token(t) => t.to_string(),
1030      v => s!("{v:?}"),
1031    }
1032  }
1033}
1034
1035impl<'a> From<&'a Stored> for Option<&'a VecDeque<Stored>> {
1036  fn from(value: &'a Stored) -> Option<&'a VecDeque<Stored>> {
1037    match value {
1038      Stored::VecDequeStored(v) => Some(v),
1039      _ => None,
1040    }
1041  }
1042}
1043
1044impl<'a> From<&'a Stored> for Option<Rc<Font>> {
1045  fn from(value: &'a Stored) -> Option<Rc<Font>> {
1046    match value {
1047      Stored::Font(f) => Some(Rc::clone(f)),
1048      _ => None,
1049    }
1050  }
1051}
1052
1053impl<'a> From<&'a Stored> for Option<Number> {
1054  fn from(value: &'a Stored) -> Option<Number> {
1055    match value {
1056      Stored::Number(n) => Some(*n),
1057      // A plain integer (a runtime binding's `AssignValue(k, 7)`) is a Number, as Perl's scalar.
1058      Stored::Int(i) => Some(Number::new(*i)),
1059      // A `Float` narrows to an integer `Number` through `Float::value_of`
1060      // (truncation toward zero, the crate's canonical Float->i64), the same
1061      // `value_of` narrowing the dimension family uses just below. NB this is
1062      // *not* the `floor` that `From<f64> for Stored` applies — they agree for
1063      // non-negative values (the only ones stored here in practice).
1064      Stored::Float(f) => Some(Number::new(f.value_of())),
1065      Stored::Dimension(n) => Some(Number::new(n.value_of())),
1066      Stored::Glue(n) => Some(Number::new(n.value_of())),
1067      Stored::MuDimension(n) => Some(Number::new(n.value_of())),
1068      Stored::MuGlue(n) => Some(Number::new(n.value_of())),
1069      other => {
1070        // No Number projection for this Stored variant — surface it through the
1071        // logger (counts in REPORT, respects the log floor + `--quiet` stderr gate)
1072        // rather than a raw `eprintln!` that bypassed both; callers degrade on the
1073        // None. Mirrors the `Warn!("stored", "cast", …)` fallback for the CS cast.
1074        Warn!(
1075          "stored",
1076          "cast",
1077          s!("no auto-cast of Stored to Number for {other:?}")
1078        );
1079        None
1080      },
1081    }
1082  }
1083}
1084
1085// The counterpart of the `Option<Number>` narrowing above, kept lenient in the
1086// same spirit: a stored `Float` reads as itself, and the integral numerics
1087// widen to `Float` (`Number`/`Int`), so `lookup_float` sees a value assigned
1088// either way. Non-numeric variants are `None` (no eprintln — an optional typed
1089// read, not a coercion error).
1090impl<'a> From<&'a Stored> for Option<Float> {
1091  fn from(value: &'a Stored) -> Option<Float> {
1092    match value {
1093      Stored::Float(f) => Some(*f),
1094      Stored::Number(n) => Some(Float::new(n.value_of())),
1095      Stored::Int(i) => Some(Float(*i as f64)),
1096      _ => None,
1097    }
1098  }
1099}
1100
1101// MuGlue/MuDimension store raw mu in fixpoint units (1mu = 1/18 em).
1102// Convert to scaled-pt by mirroring Perl `MuGlue::spValue` →
1103// `fixpoint(mu/UNITY, MUWidth)` where `MUWidth = int(size * emwidth /
1104// 18)`. The two-step integer truncation in Perl is load-bearing: a
1105// single-step `(mu * size / 18)` gives a slightly larger value (109226
1106// vs 109219 for 3mu at 10pt), and Knuth's `print_scaled` then formats
1107// "1.66666pt" instead of the expected "1.66663pt". See
1108// LaTeXML/lib/LaTeXML/Common/Font.pm:580 (getMUWidth) and
1109// Core/MuGlue.pm spValue.
1110fn mu_to_pt_value(mu_val: i64) -> i64 {
1111  let fs = crate::state::lookup_font()
1112    .and_then(|f| f.get_size())
1113    .unwrap_or(10.0);
1114  let unity = crate::common::numeric_ops::UNITY_F64;
1115  // MUWidth = int(font_size * emwidth(=1.0*UNITY) / 18)
1116  let muwidth = (fs * unity / 18.0) as i64;
1117  // fixpoint(mu/UNITY, MUWidth) ≈ (mu_val * muwidth / UNITY).trunc()
1118  ((mu_val as f64 * muwidth as f64 / unity).trunc()) as i64
1119}
1120
1121impl<'a> From<&'a Stored> for Option<Dimension> {
1122  fn from(value: &'a Stored) -> Option<Dimension> {
1123    match value {
1124      Stored::Dimension(n) => Some(*n),
1125      Stored::Number(n) => Some(Dimension::new(n.value_of())),
1126      Stored::Glue(n) => Some(Dimension::new(n.value_of())),
1127      Stored::MuDimension(n) => Some(Dimension::new(mu_to_pt_value(n.value_of()))),
1128      Stored::MuGlue(n) => Some(Dimension::new(mu_to_pt_value(n.value_of()))),
1129      _ => None,
1130    }
1131  }
1132}
1133
1134impl<'a> From<&'a Stored> for Option<Glue> {
1135  fn from(value: &'a Stored) -> Option<Glue> {
1136    match value {
1137      Stored::Dimension(n) => Some(Glue::new(n.value_of())),
1138      Stored::Number(n) => Some(Glue::new(n.value_of())),
1139      Stored::MuDimension(n) => Some(Glue::new(mu_to_pt_value(n.value_of()))),
1140      Stored::MuGlue(n) => Some(Glue::new(mu_to_pt_value(n.value_of()))),
1141      Stored::Glue(n) => Some(*n),
1142      _ => None,
1143    }
1144  }
1145}
1146
1147impl From<Stored> for Option<Tokens> {
1148  fn from(value: Stored) -> Option<Tokens> {
1149    match value {
1150      Stored::String(sym) => Some(mouth::tokenize_internal(TeXString::assembled(
1151        arena::to_string(sym),
1152      ))),
1153      Stored::Token(ts) => Some(Tokens::new(vec![ts])),
1154      Stored::Tokens(ts) => Some(ts),
1155      // Digested: revert to tokens (needed for \AtBeginDocument hooks that
1156      // store Digested arguments via push_value)
1157      Stored::Digested(d) => {
1158        use crate::common::object::Object;
1159        d.revert().ok()
1160      },
1161      Stored::VecDequeStored(vdq) => {
1162        // Each item in the queue can be unlisted into a Vec<Token>
1163        // and then the result can be re-cast as a single Tokens
1164        let mut collected: Vec<Token> = Vec::new();
1165        for item in vdq {
1166          let item_tokens_opt: Option<Tokens> = item.into();
1167          if let Some(item_tokens) = item_tokens_opt {
1168            collected.extend(item_tokens.unlist());
1169          }
1170        }
1171        if collected.is_empty() {
1172          None
1173        } else {
1174          Some(Tokens::new(collected))
1175        }
1176      },
1177      _ => None,
1178    }
1179  }
1180}
1181
1182impl<'a> From<&'a Stored> for Option<Rc<Register>> {
1183  fn from(value: &'a Stored) -> Option<Rc<Register>> {
1184    match value {
1185      Stored::Register(reg) => Some(Rc::clone(reg)),
1186      _ => None,
1187    }
1188  }
1189}
1190
1191impl<'a> From<&'a Stored> for Option<Catcode> {
1192  fn from(value: &'a Stored) -> Option<Catcode> {
1193    match value {
1194      Stored::Catcode(cc) => Some(*cc),
1195      _ => None,
1196    }
1197  }
1198}
1199
1200impl<'a> From<&'a Stored> for Option<&'a [char]> {
1201  fn from(value: &'a Stored) -> Option<&'a [char]> {
1202    match value {
1203      Stored::Chars(cc) => Some(cc),
1204      _ => None,
1205    }
1206  }
1207}
1208
1209impl From<&Stored> for Option<Rc<[Option<char>]>> {
1210  fn from(value: &Stored) -> Option<Rc<[Option<char>]>> {
1211    match value {
1212      Stored::Fontmap(cc) => Some(Rc::clone(cc)),
1213      _ => None,
1214    }
1215  }
1216}
1217impl From<Stored> for Option<Rc<[Option<char>]>> {
1218  fn from(value: Stored) -> Option<Rc<[Option<char>]>> { (&value).into() }
1219}
1220
1221impl<'a> From<&'a Stored> for Option<RegisterValue> {
1222  fn from(value: &'a Stored) -> Option<RegisterValue> {
1223    match value {
1224      Stored::Number(v) => Some(RegisterValue::Number(*v)),
1225      Stored::Dimension(v) => Some(RegisterValue::Dimension(*v)),
1226      Stored::Glue(v) => Some(RegisterValue::Glue(*v)),
1227      Stored::MuGlue(v) => Some(RegisterValue::MuGlue(*v)),
1228      Stored::Token(v) => Some(RegisterValue::Token(*v)),
1229      Stored::Tokens(v) => Some(RegisterValue::Tokens(v.clone())),
1230      _ => None,
1231    }
1232  }
1233}
1234
1235impl From<Stored> for Option<crate::Digested> {
1236  fn from(value: Stored) -> Option<crate::Digested> {
1237    match value {
1238      Stored::Digested(digested) => Some(digested),
1239      Stored::String(text) => Some(text.into()),
1240      Stored::Int(text) => Some(text.to_string().into()),
1241      _ => None,
1242    }
1243  }
1244}
1245
1246impl<'a> From<&'a Stored> for Option<crate::Digested> {
1247  fn from(value: &'a Stored) -> Option<crate::Digested> {
1248    match value {
1249      Stored::Digested(digested) => Some((*digested).clone()),
1250      Stored::String(text) => Some((*text).into()),
1251      Stored::Int(text) => Some(text.to_string().into()),
1252      _ => None,
1253    }
1254  }
1255}
1256
1257impl<'a, 'b> From<&'a &'b Stored> for Option<crate::Digested> {
1258  fn from(value: &'a &'b Stored) -> Option<crate::Digested> { (*value).into() }
1259}
1260
1261impl<'a> From<&'a Stored> for Token {
1262  fn from(value: &'a Stored) -> Token {
1263    match value {
1264      Stored::Tokens(ts) => ts.into(),
1265      Stored::Token(t) => *t,
1266      Stored::String(text) => Token!(sym * text, Catcode::CS),
1267      t => {
1268        let message = s!("dangerous cast to CS for {:?}", t);
1269        Warn!("stored", "cast", message);
1270        T_CS!(t.to_string())
1271      }, /* TODO, is this the right place to default to CS? Do we need a
1272          * custom method instead? */
1273    }
1274  }
1275}