Skip to main content

mt_core/
ast.rs

1//! The equation tree shared by the parsers, the editor and the renderers.
2//!
3//! The model follows the shape of an equation as an author sees it rather than a TeX token
4//! stream: an equation is a [`Row`] of items, templates such as fractions or radicals own their
5//! argument slots, and every node exposes a fixed, ordered list of slots. Editing code can
6//! therefore walk and mutate any construct without knowing what the construct is, and layout can
7//! recurse over the same slot list.
8
9/// A complete equation together with the size preset it is laid out at.
10#[derive(Clone, Debug, Default, PartialEq, Eq)]
11pub struct Math {
12    pub body: Node,
13    pub style: MathStyle,
14}
15
16impl Math {
17    /// An equation wrapping `body` at full size.
18    pub fn new(body: impl Into<Node>) -> Self {
19        Self {
20            body: body.into(),
21            style: MathStyle::Full,
22        }
23    }
24
25    pub fn node_at(&self, path: &Path) -> Option<&Node> {
26        self.body.node_at(path)
27    }
28
29    pub fn node_at_mut(&mut self, path: &Path) -> Option<&mut Node> {
30        self.body.node_at_mut(path)
31    }
32}
33
34/// Size preset an equation is laid out at, matching the size classes an author picks from.
35#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
36pub enum MathStyle {
37    /// Inline text size.
38    Text,
39    /// Smaller than text, one step down in the nesting hierarchy.
40    Script,
41    /// Smallest supported size, two steps down in the nesting hierarchy.
42    ScriptScript,
43    /// Full size.
44    #[default]
45    Full,
46}
47
48impl MathStyle {
49    /// The next smaller preset, saturating at [`MathStyle::ScriptScript`].
50    pub fn smaller(self) -> Self {
51        match self {
52            MathStyle::Full => MathStyle::Script,
53            MathStyle::Text => MathStyle::Script,
54            MathStyle::Script => MathStyle::ScriptScript,
55            MathStyle::ScriptScript => MathStyle::ScriptScript,
56        }
57    }
58}
59
60/// Horizontal sequence of items.
61pub type Row = Vec<Node>;
62
63/// One item of an equation.
64///
65/// Template variants are boxed so that a `Node` stays pointer sized.
66#[derive(Clone, Debug, PartialEq, Eq)]
67pub enum Node {
68    /// Horizontal sequence of items; an empty row is an empty argument slot.
69    Row(Row),
70    /// A single character with its atom class and font.
71    Char(Char),
72    /// Literal text set upright (`\text{...}` and friends).
73    Text(Box<TextRun>),
74    /// Explicit horizontal spacing.
75    Space(Space),
76    /// Fraction, with or without a rule.
77    Frac(Box<Frac>),
78    /// Radical with an optional index.
79    Sqrt(Box<Sqrt>),
80    /// Subscript and/or superscript attached to a base.
81    Scripts(Box<Scripts>),
82    /// Over/under material that is not an accent (`\overset`, `\stackrel`, limits).
83    Limits(Box<Limits>),
84    /// Delimiters around a body.
85    Fence(Box<Fence>),
86    /// Table of cells with optional delimiters and alignment.
87    Matrix(Box<Matrix>),
88    /// Accent over or under a base.
89    Accent(Box<Accent>),
90    /// Large operator with optional limits.
91    Big(Box<BigOp>),
92    /// Style, font or class applied to a subtree.
93    Styled(Box<Styled>),
94    /// Alignment point (`&` inside aligned environments).
95    Align,
96    /// Construct kept verbatim because it could not be represented.
97    Error(String),
98}
99
100impl Node {
101    /// An empty row, i.e. an empty slot.
102    pub fn empty() -> Self {
103        Node::Row(Row::new())
104    }
105
106    pub fn row(items: impl IntoIterator<Item = Node>) -> Self {
107        Node::Row(items.into_iter().collect())
108    }
109
110    /// A character carrying `class` and `font`.
111    pub fn char_with(ch: char, class: Class, font: Font) -> Self {
112        Node::Char(Char { ch, class, font })
113    }
114
115    /// A default-class italic variable.
116    pub fn variable(ch: char) -> Self {
117        Node::Char(Char {
118            ch,
119            class: Class::Ord,
120            font: Font::Italic,
121        })
122    }
123
124    /// A default-class upright operator or symbol.
125    pub fn symbol(ch: char, class: Class) -> Self {
126        Node::Char(Char {
127            ch,
128            class,
129            font: Font::Upright,
130        })
131    }
132
133    pub fn text(text: impl Into<String>) -> Self {
134        Node::Text(Box::new(TextRun {
135            text: text.into(),
136            font: Font::Upright,
137        }))
138    }
139
140    /// True when the node is an empty row, which renderers draw as an empty slot.
141    pub fn is_empty_slot(&self) -> bool {
142        matches!(self, Node::Row(row) if row.is_empty())
143    }
144
145    /// Whether the node is a row and can therefore accept siblings.
146    pub fn is_row(&self) -> bool {
147        matches!(self, Node::Row(_))
148    }
149
150    /// Number of child slots the node exposes, in visual order.
151    pub fn slot_count(&self) -> usize {
152        match self {
153            Node::Row(row) => row.len(),
154            Node::Char(_) | Node::Text(_) | Node::Space(_) | Node::Align | Node::Error(_) => 0,
155            Node::Frac(_) => 2,
156            Node::Sqrt(sqrt) => 1 + usize::from(sqrt.index.is_some()),
157            Node::Scripts(_) => 3,
158            Node::Limits(_) => 3,
159            Node::Fence(_) => 1,
160            Node::Matrix(matrix) => matrix.rows.iter().map(Row::len).sum(),
161            Node::Accent(_) => 1,
162            Node::Big(_) => 3,
163            Node::Styled(_) => 1,
164        }
165    }
166
167    /// Read-only access to slot `index`, in the order defined by [`Node::slot_count`].
168    pub fn slot(&self, index: usize) -> Option<&Node> {
169        match self {
170            Node::Row(row) => row.get(index),
171            Node::Char(_) | Node::Text(_) | Node::Space(_) | Node::Align | Node::Error(_) => None,
172            Node::Frac(frac) => match index {
173                0 => Some(&frac.num),
174                1 => Some(&frac.den),
175                _ => None,
176            },
177            Node::Sqrt(sqrt) => match (index, &sqrt.index) {
178                (0, Some(radicand)) => Some(radicand),
179                (0, None) => Some(&sqrt.radicand),
180                (1, Some(_)) => Some(&sqrt.radicand),
181                _ => None,
182            },
183            Node::Scripts(scripts) => match index {
184                0 => Some(&scripts.base),
185                1 => scripts.sub.as_ref(),
186                2 => scripts.sup.as_ref(),
187                _ => None,
188            },
189            Node::Limits(limits) => match index {
190                0 => Some(&limits.base),
191                1 => limits.under.as_ref(),
192                2 => limits.over.as_ref(),
193                _ => None,
194            },
195            Node::Fence(fence) => (index == 0).then_some(&fence.body),
196            Node::Matrix(matrix) => matrix.cell_at(index),
197            Node::Accent(accent) => (index == 0).then_some(&accent.base),
198            Node::Big(big) => match index {
199                0 => Some(&big.base),
200                1 => big.sub.as_ref(),
201                2 => big.sup.as_ref(),
202                _ => None,
203            },
204            Node::Styled(styled) => (index == 0).then_some(&styled.body),
205        }
206    }
207
208    /// Mutable access to slot `index`, in the order defined by [`Node::slot_count`].
209    pub fn slot_mut(&mut self, index: usize) -> Option<&mut Node> {
210        match self {
211            Node::Row(row) => row.get_mut(index),
212            Node::Char(_) | Node::Text(_) | Node::Space(_) | Node::Align | Node::Error(_) => None,
213            Node::Frac(frac) => match index {
214                0 => Some(&mut frac.num),
215                1 => Some(&mut frac.den),
216                _ => None,
217            },
218            Node::Sqrt(sqrt) => match (index, &mut sqrt.index) {
219                (0, Some(radicand)) => Some(radicand),
220                (0, None) => Some(&mut sqrt.radicand),
221                (1, Some(_)) => Some(&mut sqrt.radicand),
222                _ => None,
223            },
224            Node::Scripts(scripts) => match index {
225                0 => Some(&mut scripts.base),
226                1 => scripts.sub.as_mut(),
227                2 => scripts.sup.as_mut(),
228                _ => None,
229            },
230            Node::Limits(limits) => match index {
231                0 => Some(&mut limits.base),
232                1 => limits.under.as_mut(),
233                2 => limits.over.as_mut(),
234                _ => None,
235            },
236            Node::Fence(fence) => (index == 0).then_some(&mut fence.body),
237            Node::Matrix(matrix) => matrix.cell_at_mut(index),
238            Node::Accent(accent) => (index == 0).then_some(&mut accent.base),
239            Node::Big(big) => match index {
240                0 => Some(&mut big.base),
241                1 => big.sub.as_mut(),
242                2 => big.sup.as_mut(),
243                _ => None,
244            },
245            Node::Styled(styled) => (index == 0).then_some(&mut styled.body),
246        }
247    }
248
249    /// Slots in visual order. Allocates; use [`Node::slot_count`] plus [`Node::slot`] in hot paths.
250    pub fn slots(&self) -> Vec<&Node> {
251        (0..self.slot_count())
252            .filter_map(|i| self.slot(i))
253            .collect()
254    }
255
256    /// Depth-first walk over the node and every node reachable through its slots.
257    pub fn walk<'a>(&'a self, visit: &mut impl FnMut(&'a Node)) {
258        visit(self);
259        for index in 0..self.slot_count() {
260            if let Some(slot) = self.slot(index) {
261                slot.walk(visit);
262            }
263        }
264    }
265
266    /// Node reached by following `path` from here.
267    pub fn node_at(&self, path: &Path) -> Option<&Node> {
268        let mut current = self;
269        for &index in path.as_slice() {
270            current = current.slot(index)?;
271        }
272        Some(current)
273    }
274
275    /// Mutable node reached by following `path` from here.
276    pub fn node_at_mut(&mut self, path: &Path) -> Option<&mut Node> {
277        let mut current = self;
278        for &index in path.as_slice() {
279            current = current.slot_mut(index)?;
280        }
281        Some(current)
282    }
283
284    /// Replace the node at `path`, returning the replaced node.
285    ///
286    /// The root cannot be replaced: pass a non-empty path.
287    pub fn replace_at(&mut self, path: &Path, node: Node) -> Option<Node> {
288        let (parent_path, index) = path.split_last()?;
289        let parent = self.node_at_mut(&parent_path)?;
290        match parent {
291            Node::Row(row) => {
292                let target = row.get_mut(index)?;
293                Some(std::mem::replace(target, node))
294            }
295            other => {
296                let target = other.slot_mut(index)?;
297                Some(std::mem::replace(target, node))
298            }
299        }
300    }
301
302    /// Insert `node` into the row at `path`, directly before the item at `path` or appended when
303    /// the path names a row itself.
304    pub fn insert_at(&mut self, path: &Path, node: Node) -> bool {
305        match self.node_at_mut(path) {
306            Some(Node::Row(row)) => {
307                row.push(node);
308                true
309            }
310            Some(_) => match path.split_last() {
311                Some((parent_path, index)) => match self.node_at_mut(&parent_path) {
312                    Some(parent) => parent.insert_sibling(index, node),
313                    None => false,
314                },
315                None => false,
316            },
317            None => false,
318        }
319    }
320
321    /// Insert `node` before slot `index` of a row-like parent.
322    fn insert_sibling(&mut self, index: usize, node: Node) -> bool {
323        match self {
324            Node::Row(row) => {
325                let index = index.min(row.len());
326                row.insert(index, node);
327                true
328            }
329            _ => false,
330        }
331    }
332
333    /// Remove the node at `path`, returning it. The root cannot be removed.
334    pub fn remove_at(&mut self, path: &Path) -> Option<Node> {
335        let (parent_path, index) = path.split_last()?;
336        match self.node_at_mut(&parent_path)? {
337            Node::Row(row) => (index < row.len()).then(|| row.remove(index)),
338            _ => None,
339        }
340    }
341
342    /// Flatten rows nested directly inside a row and drop empty nested rows.
343    ///
344    /// Template slots are untouched, so this only removes row nesting that carries no meaning and
345    /// keeps parse-then-serialise round trips stable.
346    pub fn normalize(&mut self) {
347        for index in 0..self.slot_count() {
348            if let Some(slot) = self.slot_mut(index) {
349                slot.normalize();
350            }
351        }
352        if let Node::Row(row) = self {
353            let mut flat = Row::with_capacity(row.len());
354            for node in row.drain(..) {
355                match node {
356                    Node::Row(inner) => flat.extend(inner),
357                    other => flat.push(other),
358                }
359            }
360            *row = flat;
361        }
362    }
363}
364
365impl From<char> for Node {
366    fn from(ch: char) -> Self {
367        Node::variable(ch)
368    }
369}
370
371impl From<&str> for Node {
372    fn from(text: &str) -> Self {
373        Node::Text(Box::new(TextRun {
374            text: text.to_owned(),
375            font: Font::Upright,
376        }))
377    }
378}
379
380impl From<String> for Node {
381    fn from(text: String) -> Self {
382        Node::Text(Box::new(TextRun {
383            text,
384            font: Font::Upright,
385        }))
386    }
387}
388
389impl From<Vec<Node>> for Node {
390    fn from(items: Vec<Node>) -> Self {
391        Node::Row(items)
392    }
393}
394
395impl Default for Node {
396    /// An empty slot.
397    fn default() -> Self {
398        Node::empty()
399    }
400}
401
402/// A character together with the atom class that drives spacing and the font it is set in.
403#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
404pub struct Char {
405    pub ch: char,
406    pub class: Class,
407    pub font: Font,
408}
409
410/// Atom class, used for operator spacing between neighbouring atoms.
411#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
412pub enum Class {
413    /// Ordinary atom: variables, numbers, most symbols.
414    #[default]
415    Ord,
416    /// Large operator or function name taking limits.
417    Op,
418    /// Binary operator.
419    Bin,
420    /// Relation.
421    Rel,
422    /// Opening delimiter.
423    Open,
424    /// Closing delimiter.
425    Close,
426    /// Punctuation.
427    Punct,
428    /// Inner atom, e.g. a fraction or matrix.
429    Inner,
430}
431
432/// Typeface a run is set in.
433#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
434pub enum Font {
435    /// Italic math variable, the default for letters.
436    #[default]
437    Italic,
438    /// Upright roman.
439    Upright,
440    Bold,
441    BoldItalic,
442    SansSerif,
443    SansSerifBold,
444    SansSerifItalic,
445    SansSerifBoldItalic,
446    Monospace,
447    Script,
448    BoldScript,
449    Fraktur,
450    BoldFraktur,
451    DoubleStruck,
452    /// Symbols drawn from the symbol font rather than the text face.
453    Symbol,
454    /// Glyphs from the extra symbol face.
455    Extra,
456}
457
458impl Font {
459    /// Whether the face is set in italics, which layout needs for metric selection.
460    pub fn is_italic(self) -> bool {
461        matches!(
462            self,
463            Font::Italic | Font::BoldItalic | Font::SansSerifItalic | Font::SansSerifBoldItalic
464        )
465    }
466
467    /// Whether the face is bold.
468    pub fn is_bold(self) -> bool {
469        matches!(
470            self,
471            Font::Bold
472                | Font::BoldItalic
473                | Font::SansSerifBold
474                | Font::SansSerifBoldItalic
475                | Font::BoldScript
476                | Font::BoldFraktur
477        )
478    }
479}
480
481/// Literal text set upright, optionally in a specific face.
482#[derive(Clone, Debug, PartialEq, Eq)]
483pub struct TextRun {
484    pub text: String,
485    pub font: Font,
486}
487
488/// Explicit horizontal space.
489#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
490pub enum Space {
491    /// 3/18 em.
492    Thin,
493    /// 4/18 em.
494    Medium,
495    /// 5/18 em.
496    Thick,
497    /// 6/18 em.
498    Sixteenth,
499    /// 1 em.
500    Quad,
501    /// 2 em.
502    DoubleQuad,
503    /// -3/18 em.
504    NegativeThin,
505    /// -4/18 em.
506    NegativeMedium,
507    /// -5/18 em.
508    NegativeThick,
509}
510
511impl Space {
512    /// Width in em units, negative for backspacing.
513    pub fn em(self) -> f64 {
514        match self {
515            Space::Thin => 3.0 / 18.0,
516            Space::Medium => 4.0 / 18.0,
517            Space::Thick => 5.0 / 18.0,
518            Space::Sixteenth => 6.0 / 18.0,
519            Space::Quad => 1.0,
520            Space::DoubleQuad => 2.0,
521            Space::NegativeThin => -3.0 / 18.0,
522            Space::NegativeMedium => -4.0 / 18.0,
523            Space::NegativeThick => -5.0 / 18.0,
524        }
525    }
526}
527
528/// Fraction, with or without a rule, drawn stacked or inline.
529#[derive(Clone, Debug, PartialEq, Eq)]
530pub struct Frac {
531    pub num: Node,
532    pub den: Node,
533    pub kind: FracKind,
534}
535
536impl Frac {
537    pub fn new(num: Node, den: Node) -> Self {
538        Self {
539            num,
540            den,
541            kind: FracKind::Bar,
542        }
543    }
544}
545
546/// How a fraction is drawn.
547#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
548pub enum FracKind {
549    /// Stacked with a horizontal rule.
550    #[default]
551    Bar,
552    /// Stacked with a slash instead of a rule.
553    Slash,
554    /// Stacked without a rule, e.g. binomial coefficients.
555    NoBar,
556    /// Written inline as `a/b`.
557    Linear,
558}
559
560/// Radical, with an optional index for higher roots.
561#[derive(Clone, Debug, PartialEq, Eq)]
562pub struct Sqrt {
563    /// Root index; `None` is a square root.
564    pub index: Option<Node>,
565    pub radicand: Node,
566}
567
568impl Sqrt {
569    pub fn square(radicand: Node) -> Self {
570        Self {
571            index: None,
572            radicand,
573        }
574    }
575
576    pub fn nth(index: Node, radicand: Node) -> Self {
577        Self {
578            index: Some(index),
579            radicand,
580        }
581    }
582}
583
584/// Subscript and superscript attached to a base.
585#[derive(Clone, Debug, PartialEq, Eq)]
586pub struct Scripts {
587    pub base: Node,
588    pub sub: Option<Node>,
589    pub sup: Option<Node>,
590}
591
592impl Scripts {
593    /// Attach `sub`/`sup` to `base`.
594    ///
595    /// Merging into an existing [`Node::Scripts`] node is up to the caller, which knows whether
596    /// the new scripts belong inside or outside the existing ones.
597    pub fn attach(base: Node, sub: Option<Node>, sup: Option<Node>) -> Self {
598        Self { base, sub, sup }
599    }
600}
601
602/// Over/under material that is not an accent.
603#[derive(Clone, Debug, PartialEq, Eq)]
604pub struct Limits {
605    pub base: Node,
606    pub under: Option<Node>,
607    pub over: Option<Node>,
608    pub align: Side,
609}
610
611/// Horizontal alignment of over/under material.
612#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
613pub enum Side {
614    #[default]
615    Center,
616    Left,
617    Right,
618}
619
620/// Delimiter shape.
621#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
622pub enum Delim {
623    Paren,
624    Bracket,
625    Brace,
626    Abs,
627    Norm,
628    Angle,
629    Floor,
630    Ceil,
631    /// No delimiter drawn.
632    None,
633    /// A specific character, drawn from a font that provides it.
634    Custom(char),
635    /// An arrow delimiter.
636    Arrow,
637    /// A double bar delimiter.
638    DoubleBar,
639}
640
641impl Delim {
642    /// The opening character, or `None` when nothing is drawn.
643    pub fn open(self) -> Option<char> {
644        Some(match self {
645            Delim::Paren => '(',
646            Delim::Bracket => '[',
647            Delim::Brace => '{',
648            Delim::Abs => '|',
649            Delim::Norm => '\u{2016}',
650            Delim::Angle => '\u{27E8}',
651            Delim::Floor => '\u{230A}',
652            Delim::Ceil => '\u{2308}',
653            Delim::None => return None,
654            Delim::Custom(ch) => ch,
655            Delim::Arrow => '\u{27E8}',
656            Delim::DoubleBar => '\u{2016}',
657        })
658    }
659
660    /// The closing character, or `None` when nothing is drawn.
661    pub fn close(self) -> Option<char> {
662        Some(match self {
663            Delim::Paren => ')',
664            Delim::Bracket => ']',
665            Delim::Brace => '}',
666            Delim::Abs => '|',
667            Delim::Norm => '\u{2016}',
668            Delim::Angle => '\u{27E9}',
669            Delim::Floor => '\u{230B}',
670            Delim::Ceil => '\u{2309}',
671            Delim::None => return None,
672            Delim::Custom(ch) => ch,
673            Delim::Arrow => '\u{27E9}',
674            Delim::DoubleBar => '\u{2016}',
675        })
676    }
677}
678
679/// Delimiters around a body.
680#[derive(Clone, Debug, PartialEq, Eq)]
681pub struct Fence {
682    pub open: Delim,
683    pub close: Delim,
684    pub body: Node,
685}
686
687/// Table of cells with optional delimiters.
688#[derive(Clone, Debug, PartialEq, Eq)]
689pub struct Matrix {
690    pub rows: Vec<Row>,
691    pub delims: Option<(Delim, Delim)>,
692    pub kind: MatrixKind,
693    /// Alignment applied to every column; per-column rules come from [`Matrix::columns`].
694    pub align: Side,
695    /// Optional per-column alignment overriding [`Matrix::align`].
696    pub columns: Vec<Side>,
697    /// Draws the horizontal and vertical cell rules of an array.
698    pub rules: bool,
699}
700
701impl Matrix {
702    /// A matrix of `rows` rows and `cols` columns, each cell an empty slot.
703    pub fn empty(rows: usize, cols: usize) -> Self {
704        Self {
705            rows: vec![vec![Node::empty(); cols]; rows],
706            delims: None,
707            kind: MatrixKind::Matrix,
708            align: Side::Center,
709            columns: Vec::new(),
710            rules: false,
711        }
712    }
713
714    /// Number of rows.
715    pub fn row_count(&self) -> usize {
716        self.rows.len()
717    }
718
719    /// Number of columns, taken from the widest row.
720    pub fn col_count(&self) -> usize {
721        self.rows.iter().map(Row::len).max().unwrap_or(0)
722    }
723
724    fn cell_position(&self, index: usize) -> Option<(usize, usize)> {
725        let mut remaining = index;
726        for (row, cells) in self.rows.iter().enumerate() {
727            if remaining < cells.len() {
728                return Some((row, remaining));
729            }
730            remaining -= cells.len();
731        }
732        None
733    }
734
735    /// Cell addressed by a flat slot index, row-major.
736    pub fn cell_at(&self, index: usize) -> Option<&Node> {
737        let (row, col) = self.cell_position(index)?;
738        self.rows[row].get(col)
739    }
740
741    /// Mutable cell addressed by a flat slot index, row-major.
742    pub fn cell_at_mut(&mut self, index: usize) -> Option<&mut Node> {
743        let (row, col) = self.cell_position(index)?;
744        self.rows[row].get_mut(col)
745    }
746}
747
748/// Kind of table, which decides delimiter defaults and column alignment.
749#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
750pub enum MatrixKind {
751    #[default]
752    Matrix,
753    /// Piecewise definitions: left brace, left aligned columns.
754    Cases,
755    /// Aligned equations on the alignment points.
756    Aligned,
757    /// Plain array.
758    Array,
759    /// Vertically stacked material.
760    Pile,
761    /// Long division layout.
762    LongDivision,
763}
764
765/// Accent drawn over or under a base.
766#[derive(Clone, Debug, PartialEq, Eq)]
767pub struct Accent {
768    pub kind: AccentKind,
769    pub base: Node,
770    /// Draws the accent under the base instead of over it.
771    pub under: bool,
772}
773
774/// Accent shapes.
775#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
776pub enum AccentKind {
777    Hat,
778    WideHat,
779    Tilde,
780    WideTilde,
781    Bar,
782    Vector,
783    Dot,
784    DoubleDot,
785    TripleDot,
786    Breve,
787    Check,
788    Acute,
789    Grave,
790    Circle,
791    OverBrace,
792    UnderBrace,
793    OverBracket,
794    UnderBracket,
795    OverParen,
796    UnderParen,
797    ArrowRight,
798    ArrowLeft,
799    Line,
800    Strike,
801}
802
803impl AccentKind {
804    /// The character used when the accent is drawn from a font rather than as a rule or path.
805    pub fn glyph(self) -> Option<char> {
806        Some(match self {
807            AccentKind::Hat => '\u{02C6}',
808            AccentKind::WideHat => '\u{0302}',
809            AccentKind::Tilde => '~',
810            AccentKind::WideTilde => '\u{0303}',
811            AccentKind::Dot => '\u{02D9}',
812            AccentKind::DoubleDot => '\u{00A8}',
813            AccentKind::TripleDot => '\u{20DB}',
814            AccentKind::Breve => '\u{02D8}',
815            AccentKind::Check => '\u{02C7}',
816            AccentKind::Acute => '\u{00B4}',
817            AccentKind::Grave => '`',
818            AccentKind::Circle => '\u{02DA}',
819            AccentKind::ArrowRight => '\u{2192}',
820            AccentKind::ArrowLeft => '\u{2190}',
821            AccentKind::Bar | AccentKind::Vector | AccentKind::Line => return None,
822            AccentKind::Strike => return None,
823            AccentKind::OverBrace => '\u{23DE}',
824            AccentKind::UnderBrace => '\u{23DF}',
825            AccentKind::OverBracket => '\u{23B4}',
826            AccentKind::UnderBracket => '\u{23B5}',
827            AccentKind::OverParen => '\u{23DC}',
828            AccentKind::UnderParen => '\u{23DD}',
829        })
830    }
831}
832
833/// Large operator with optional limits.
834#[derive(Clone, Debug, PartialEq, Eq)]
835pub struct BigOp {
836    pub base: Node,
837    pub sub: Option<Node>,
838    pub sup: Option<Node>,
839    /// Draws the limits above and below instead of beside the operator.
840    pub limits: bool,
841}
842
843/// Style, font or class override applied to a subtree.
844#[derive(Clone, Debug, PartialEq, Eq)]
845pub struct Styled {
846    pub body: Node,
847    pub style: Option<MathStyle>,
848    pub font: Option<Font>,
849    pub class: Option<Class>,
850}
851
852/// Position in the tree: the sequence of slot indices from the root.
853#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
854pub struct Path(Vec<usize>);
855
856impl Path {
857    /// The path naming the root.
858    pub fn root() -> Self {
859        Self(Vec::new())
860    }
861
862    /// Path with `index` appended.
863    pub fn child(&self, index: usize) -> Self {
864        let mut path = self.clone();
865        path.0.push(index);
866        path
867    }
868
869    /// Path with the last index removed, or `None` at the root.
870    pub fn parent(&self) -> Option<Self> {
871        let mut path = self.clone();
872        path.0.pop().map(|_| path)
873    }
874
875    /// Last index, i.e. the slot of the parent that holds this node.
876    pub fn last(&self) -> Option<usize> {
877        self.0.last().copied()
878    }
879
880    /// Split into the parent path and the final index.
881    pub fn split_last(&self) -> Option<(Self, usize)> {
882        let (index, rest) = self.0.split_last()?;
883        Some((Self(rest.to_vec()), *index))
884    }
885
886    pub fn push(&mut self, index: usize) {
887        self.0.push(index);
888    }
889
890    pub fn pop(&mut self) -> Option<usize> {
891        self.0.pop()
892    }
893
894    pub fn len(&self) -> usize {
895        self.0.len()
896    }
897
898    pub fn is_empty(&self) -> bool {
899        self.0.is_empty()
900    }
901
902    pub fn as_slice(&self) -> &[usize] {
903        &self.0
904    }
905}
906
907impl FromIterator<usize> for Path {
908    fn from_iter<T: IntoIterator<Item = usize>>(iter: T) -> Self {
909        Self(iter.into_iter().collect())
910    }
911}
912
913impl std::fmt::Display for Path {
914    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
915        if self.0.is_empty() {
916            return f.write_str(".");
917        }
918        for (position, index) in self.0.iter().enumerate() {
919            if position > 0 {
920                f.write_str(".")?;
921            }
922            write!(f, "{index}")?;
923        }
924        Ok(())
925    }
926}
927
928#[cfg(test)]
929mod tests {
930    use super::*;
931
932    fn scripts(base: Node, sub: Node, sup: Node) -> Node {
933        Node::Scripts(Box::new(Scripts {
934            base,
935            sub: Some(sub),
936            sup: Some(sup),
937        }))
938    }
939
940    #[test]
941    fn fraction_slots_are_numerator_then_denominator() {
942        let frac = Node::Frac(Box::new(Frac::new(
943            Node::variable('a'),
944            Node::variable('b'),
945        )));
946        assert_eq!(frac.slot_count(), 2);
947        assert_eq!(frac.slot(0), Some(&Node::variable('a')));
948        assert_eq!(frac.slot(1), Some(&Node::variable('b')));
949        assert_eq!(frac.slot(2), None);
950    }
951
952    #[test]
953    fn square_root_has_a_single_slot() {
954        let root = Node::Sqrt(Box::new(Sqrt::square(Node::variable('x'))));
955        assert_eq!(root.slot_count(), 1);
956        assert_eq!(root.slot(0), Some(&Node::variable('x')));
957
958        let nth = Node::Sqrt(Box::new(Sqrt::nth(
959            Node::variable('n'),
960            Node::variable('x'),
961        )));
962        assert_eq!(nth.slot_count(), 2);
963        assert_eq!(nth.slot(0), Some(&Node::variable('n')));
964        assert_eq!(nth.slot(1), Some(&Node::variable('x')));
965    }
966
967    #[test]
968    fn path_navigation_reaches_nested_slots() {
969        let math = Math::new(Node::row([
970            Node::variable('x'),
971            scripts(
972                Node::variable('a'),
973                Node::variable('i'),
974                Node::variable('2'),
975            ),
976        ]));
977        let sup = Path::root().child(1).child(2);
978        assert_eq!(math.node_at(&sup), Some(&Node::variable('2')));
979        assert_eq!(sup.to_string(), "1.2");
980        assert_eq!(
981            sup.parent().map(|path| path.to_string()),
982            Some("1".to_owned())
983        );
984        assert_eq!(math.node_at(&Path::root()), Some(&math.body));
985    }
986
987    #[test]
988    fn replace_and_insert_operate_on_nested_slots() {
989        let mut math = Math::new(Node::row([
990            Node::variable('a'),
991            Node::Sqrt(Box::new(Sqrt::square(Node::variable('x')))),
992        ]));
993        let radicand = Path::root().child(1).child(0);
994        let replaced = math
995            .node_at_mut(&radicand)
996            .map(|node| std::mem::replace(node, Node::variable('y')));
997        assert_eq!(replaced, Some(Node::variable('x')));
998        assert_eq!(math.node_at(&radicand), Some(&Node::variable('y')));
999
1000        let row = Path::root();
1001        assert!(math.body.insert_at(&row, Node::variable('z')));
1002        assert_eq!(math.body.slot_count(), 3);
1003        assert_eq!(
1004            math.node_at(&Path::root().child(2)),
1005            Some(&Node::variable('z'))
1006        );
1007        assert_eq!(
1008            math.body.remove_at(&Path::root().child(2)),
1009            Some(Node::variable('z'))
1010        );
1011        assert_eq!(math.body.slot_count(), 2);
1012    }
1013
1014    #[test]
1015    fn matrix_cells_are_addressed_row_major() {
1016        let mut matrix = Matrix::empty(2, 3);
1017        if let Some(cell) = matrix.cell_at_mut(4) {
1018            *cell = Node::variable('q');
1019        }
1020        let node = Node::Matrix(Box::new(matrix));
1021        assert_eq!(node.slot_count(), 6);
1022        assert_eq!(node.slot(4), Some(&Node::variable('q')));
1023        assert_eq!(node.slot(1), Some(&Node::empty()));
1024    }
1025
1026    #[test]
1027    fn walk_visits_every_reachable_node() {
1028        let math = Math::new(Node::row([
1029            scripts(Node::variable('a'), Node::variable('i'), Node::empty()),
1030            Node::Sqrt(Box::new(Sqrt::square(Node::variable('x')))),
1031        ]));
1032        let mut names = Vec::new();
1033        math.body.walk(&mut |node| {
1034            if let Node::Char(Char { ch, .. }) = node {
1035                names.push(*ch);
1036            }
1037        });
1038        assert_eq!(names, vec!['a', 'i', 'x']);
1039    }
1040
1041    #[test]
1042    fn normalisation_flattens_nested_rows_only() {
1043        let mut node = Node::row([
1044            Node::variable('a'),
1045            Node::row([Node::variable('b'), Node::variable('c')]),
1046        ]);
1047        node.normalize();
1048        assert_eq!(
1049            node,
1050            Node::row([
1051                Node::variable('a'),
1052                Node::variable('b'),
1053                Node::variable('c')
1054            ])
1055        );
1056
1057        let mut node = Node::row([Node::row([Node::variable('a')])]);
1058        node.normalize();
1059        assert_eq!(node, Node::row([Node::variable('a')]));
1060
1061        let mut fraction = Node::Frac(Box::new(Frac::new(
1062            Node::row([Node::row([Node::variable('1')])]),
1063            Node::variable('2'),
1064        )));
1065        fraction.normalize();
1066        assert_eq!(fraction.slot(0), Some(&Node::row([Node::variable('1')])));
1067    }
1068
1069    #[test]
1070    fn space_widths_follow_the_em_grid() {
1071        assert_eq!(Space::Thin.em(), 3.0 / 18.0);
1072        assert_eq!(Space::Quad.em(), 1.0);
1073        assert_eq!(Space::NegativeThick.em(), -5.0 / 18.0);
1074    }
1075
1076    #[test]
1077    fn delimiters_expose_matching_pairs() {
1078        assert_eq!(Delim::Paren.open(), Some('('));
1079        assert_eq!(Delim::Paren.close(), Some(')'));
1080        assert_eq!(Delim::None.open(), None);
1081        assert_eq!(Delim::Brace.close(), Some('}'));
1082    }
1083
1084    #[test]
1085    fn style_nesting_saturates() {
1086        assert_eq!(MathStyle::Full.smaller(), MathStyle::Script);
1087        assert_eq!(MathStyle::Script.smaller(), MathStyle::ScriptScript);
1088        assert_eq!(MathStyle::ScriptScript.smaller(), MathStyle::ScriptScript);
1089    }
1090}