texrs 0.6.8

A TeX engine: Knuth's mouth and expander, lowered for a bytecode VM
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
//! The mlist: what a formula is, before it is a list of boxes.
//!
//! `tex.web` §680-§698. An mlist is a linear sequence of NOADS -- "no-adds",
//! to keep them apart from the nodes of an hlist -- and it is a tree because a
//! noad's nucleus, subscript and superscript can each be an mlist of their own.
//! The classification into Ord, Op, Bin, Rel, Open, Close, Punct and Inner
//! (§682) is what the spacing table of §764 is indexed by, so it is carried on
//! the noad rather than worked out again later.

use crate::node::Node;

/// A dimension in scaled points.
pub type Scaled = i64;

/// `ord_noad` … `inner_noad` (§682), and the four that are not spacing classes.
///
/// The eight spacing classes are numbered exactly as `tex.web` numbers them
/// relative to `ord_noad`, because §766 indexes `math_spacing` with
/// `r_type*8+t` -- arithmetic on the number, not a case analysis.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Class {
    Ord = 0,
    Op = 1,
    Bin = 2,
    Rel = 3,
    Open = 4,
    Close = 5,
    Punct = 6,
    Inner = 7,
}

impl Class {
    /// The class a math code's class field names (§1155): `type(p) :=
    /// ord_noad + (c div "1000)`.
    pub fn from_code(c: i64) -> Class {
        match c {
            1 => Class::Op,
            2 => Class::Bin,
            3 => Class::Rel,
            4 => Class::Open,
            5 => Class::Close,
            6 => Class::Punct,
            7 => Class::Inner,
            _ => Class::Ord,
        }
    }
}

/// `subtype(p)` of an `op_noad` (§682).
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub enum Limits {
    /// `\displaylimits`: above and below in display style, beside otherwise.
    #[default]
    Normal,
    /// `\limits`: always above and below.
    Above,
    /// `\nolimits`: always beside.
    Beside,
}

/// A `math_char` (§681): a family and a character within it.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct MathChar {
    pub fam: usize,
    pub character: u8,
}

/// A delimiter field (§683): the small and large variants, each a family and a
/// character.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub struct Delimiter {
    pub small_fam: usize,
    pub small_char: u8,
    pub large_fam: usize,
    pub large_char: u8,
}

impl Delimiter {
    /// `null_delimiter` (§685): the delimiter that is not there.
    pub fn null() -> Delimiter {
        Delimiter::default()
    }

    /// Whether this is the null delimiter, which §697 tests field by field.
    pub fn is_null(&self) -> bool {
        self.small_fam == 0 && self.small_char == 0 && self.large_fam == 0 && self.large_char == 0
    }

    /// A 24-bit `\delimiter` code's delimiter half (§1160): the low six hex
    /// digits, small variant first.
    pub fn from_code(code: i64) -> Delimiter {
        Delimiter {
            small_fam: ((code >> 20) & 0xF) as usize,
            small_char: ((code >> 12) & 0xFF) as u8,
            large_fam: ((code >> 8) & 0xF) as usize,
            large_char: (code & 0xFF) as u8,
        }
    }
}

/// One of a noad's three principal fields (§681).
#[derive(Clone, Debug, Default)]
pub enum Field {
    /// `math_type = empty`: the attribute is not present.
    #[default]
    Empty,
    /// `math_type = math_char`.
    Char(MathChar),
    /// `math_type = sub_box`: a box already built.
    ///
    /// Boxed, as `Noad::Choice` is: a box is several times the size of every
    /// other field, and held inline it made every field of every atom that
    /// size, though only the setting ever builds one.
    Box(Box<crate::node::BoxNode>),
    /// `math_type = sub_mlist`: a formula that must be converted first. An
    /// EMPTY list here is not the same as `Empty` (§681): `$P_{}$` and `$P$`
    /// differ.
    List(Vec<Noad>),
    /// A character with no Computer Modern slot: what a document writes when
    /// it puts a `€` or a `→` inside a formula.
    ///
    /// Not a `math_type` of `tex.web`'s -- TeX has no such case, because every
    /// character it can set is in a family. It exists because this engine sets
    /// a page in whatever face the document asked for and only MEASURES in
    /// Computer Modern, so a character outside the four families still has
    /// somewhere to be drawn from. It is measured as an Ord of the text
    /// family's quad, since there is no slot to ask.
    Literal(char),
}

impl Field {
    pub fn is_empty(&self) -> bool {
        matches!(self, Field::Empty)
    }
}

/// The four styles (§688), and their cramped variants.
///
/// `tex.web` numbers them 0, 2, 4, 6 with 1 added to cramp, which makes a
/// SMALLER style a LARGER number -- backwards from Appendix G, and load-bearing
/// because §744 and §758 test `cur_style < text_style` to mean "display".
pub type Style = i64;

pub const DISPLAY_STYLE: Style = 0;
pub const TEXT_STYLE: Style = 2;
pub const SCRIPT_STYLE: Style = 4;
pub const SCRIPT_SCRIPT_STYLE: Style = 6;
pub const CRAMPED: Style = 1;

/// `cramped_style(#) == 2*(# div 2)+cramped` (§702).
pub fn cramped_style(s: Style) -> Style {
    2 * (s / 2) + CRAMPED
}
/// `sub_style(#) == 2*(# div 4)+script_style+cramped` (§702).
pub fn sub_style(s: Style) -> Style {
    2 * (s / 4) + SCRIPT_STYLE + CRAMPED
}
/// `sup_style(#) == 2*(# div 4)+script_style+(# mod 2)` (§702).
pub fn sup_style(s: Style) -> Style {
    2 * (s / 4) + SCRIPT_STYLE + (s % 2)
}
/// `num_style(#) == #+2-2*(# div 6)` (§702).
pub fn num_style(s: Style) -> Style {
    s + 2 - 2 * (s / 6)
}
/// `denom_style(#) == 2*(# div 2)+cramped+2-2*(# div 6)` (§702).
pub fn denom_style(s: Style) -> Style {
    2 * (s / 2) + CRAMPED + 2 - 2 * (s / 6)
}

/// `cur_size` for a style (§703): `text_size` above `script_style`, else
/// `16*((cur_style-text_style) div 2)` -- which is 0, 1, 2 in this port's
/// renumbering.
pub fn size_of(style: Style) -> usize {
    match style < SCRIPT_STYLE {
        true => crate::math::font::TEXT_SIZE,
        false => ((style - TEXT_STYLE) / 2) as usize,
    }
}

/// One item of an mlist: a noad, or one of the nodes §730 allows among them.
#[derive(Clone, Debug)]
pub enum Noad {
    /// A noad of one of the eight spacing classes, or one of the four that
    /// build something (§687): under, over, radical, fraction.
    Atom(Atom),
    /// A `fraction_noad` (§683). It has `numerator`, `denominator` and
    /// `thickness` where a normal noad has nucleus, sub and superscript, which
    /// is why it is not an `Atom`.
    Fraction(Fraction),
    /// A `radical_noad` (§683): a nucleus under a `left_delimiter`.
    Radical(Radical),
    /// An `over_noad` (§687): the nucleus, overlined.
    Over(Atom),
    /// An `under_noad` (§687): the nucleus, underlined.
    Under(Atom),
    /// An `accent_noad` (§687): `\hat`, `\bar`, `\vec` and their siblings.
    Accent(Accent),
    /// A `vcenter_noad` (§687): a box centred on the axis.
    ///
    /// Its nucleus is always a `sub_box` holding a VLIST, which is what §736
    /// checks for and what `\vcenter{...}` leaves behind (§1167).
    VCenter(Atom),
    /// A `choice_node` (§689): `\mathchoice`'s four lists.
    ///
    /// Boxed because it is four mlists where every other variant is one, and
    /// an unboxed one would make every `Noad` in a formula that size.
    Choice(Box<Choice>),
    /// A `left_noad` (§687). It appears only as the first item of an mlist.
    Left(Delimiter),
    /// A `right_noad` (§687). It appears only as the last.
    Right(Delimiter),
    /// A `style_node` (§688): `\displaystyle` and its three siblings.
    Style(Style),
    /// A `glue_node` in an mlist (§730), already in points rather than in mu.
    Glue(Scaled),
    /// A `kern_node` in an mlist (§730).
    Kern(Scaled),
    /// A `glue_node` whose `subtype` is `mu_glue` (§732): `\mskip`, and every
    /// space §764's table asks for.
    MuGlue(MuGlue),
    /// A `kern_node` whose `subtype` is `mu_glue` (§717): `\mkern`.
    MuKern(Scaled),
    /// A box the formula carries whole -- what `\hbox{...}` and `\mathrm{...}`
    /// leave behind once their contents have been set as text.
    Node(Node),
}

/// A noad of one of the classes that has a nucleus and scripts (§681).
#[derive(Clone, Debug, Default)]
pub struct Atom {
    pub class: ClassOrOrd,
    pub nucleus: Field,
    pub supscr: Field,
    pub subscr: Field,
    /// `subtype` (§682), which only an `op_noad` reads.
    pub limits: Limits,
}

/// The class of an `Atom`, defaulting to Ord the way `new_noad` does (§686).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct ClassOrOrd(pub Class);

impl Default for ClassOrOrd {
    fn default() -> ClassOrOrd {
        ClassOrOrd(Class::Ord)
    }
}

impl Atom {
    pub fn new(class: Class, nucleus: Field) -> Atom {
        Atom {
            class: ClassOrOrd(class),
            nucleus,
            ..Atom::default()
        }
    }
    pub fn class(&self) -> Class {
        self.class.0
    }
}

/// A `fraction_noad` (§683).
#[derive(Clone, Debug)]
pub struct Fraction {
    /// `None` is §683's `default_code`: the `default_rule_thickness` of the
    /// current size, which is what `\over` and `\frac` mean.
    pub thickness: Option<Scaled>,
    pub numerator: Vec<Noad>,
    pub denominator: Vec<Noad>,
    pub left_delimiter: Delimiter,
    pub right_delimiter: Delimiter,
}

/// A `radical_noad` (§683).
#[derive(Clone, Debug)]
pub struct Radical {
    pub left_delimiter: Delimiter,
    pub nucleus: Atom,
    /// `\root n \of {x}`'s index, which is NOT part of `radical_noad`.
    ///
    /// TeX has no field for it: plain.tex:1018-1022 builds the index out of
    /// BOXES around the radical the noad makes, and `\sqrt[n]{x}` is LaTeX's
    /// spelling of the same macro. It rides here because the radical is the
    /// only thing that knows it has one.
    pub index: Option<Vec<Noad>>,
}

/// An `accent_noad` (§683, §687): a nucleus with a character over it.
///
/// `accent_chr` is a `math_char` field of its own, beside the nucleus and the
/// two scripts every noad carries.
#[derive(Clone, Debug)]
pub struct Accent {
    /// `accent_chr(q)` (§683).
    pub accent: MathChar,
    /// The noad proper: nucleus, subscript, superscript.
    pub atom: Atom,
}

/// A `choice_node` (§689): the four mlists `\mathchoice` names, of which
/// §731 keeps the one the current style asks for.
#[derive(Clone, Debug, Default)]
pub struct Choice {
    pub display: Vec<Noad>,
    pub text: Vec<Noad>,
    pub script: Vec<Noad>,
    pub script_script: Vec<Noad>,
}

/// A glue or a kern written in `mu` rather than in points (§716-§717).
///
/// `mu` is a MATH unit: one eighteenth of the `math_quad` of the size the
/// glue lands in, so `\mskip3mu` is a different number of points in a script
/// than in text. It therefore cannot be converted where it is READ -- which
/// is what `\thinmuskip` and its two siblings need, and what `\mkern` and
/// `\mskip` written by a document need too.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct MuGlue {
    pub natural: Scaled,
    pub stretch: Scaled,
    pub shrink: Scaled,
    /// `fil`, `fill` or `filll` stretch and shrink, which §716 copies
    /// without converting (0 is finite).
    pub stretch_order: i64,
    pub shrink_order: i64,
}

impl MuGlue {
    /// A rigid `mu` glue: `\mskip 5mu` with no stretch and no shrink.
    pub fn fixed(natural: Scaled) -> MuGlue {
        MuGlue {
            natural,
            ..MuGlue::default()
        }
    }

    /// The three components of one of plain.tex's math skips, as they are
    /// written there (plain.tex:373-375).
    pub fn of(spec: (i64, i64, i64)) -> MuGlue {
        MuGlue {
            natural: spec.0,
            stretch: spec.1,
            shrink: spec.2,
            ..MuGlue::default()
        }
    }

    /// `-\thinmuskip`, which is what `\!` is (plain.tex:733).
    pub fn negated(self) -> MuGlue {
        MuGlue {
            natural: -self.natural,
            stretch: -self.stretch,
            shrink: -self.shrink,
            ..self
        }
    }
}

/// The 64-digit string of §764, verbatim.
///
/// `"0"` no space, `"1"` a conditional thin space, `"2"` a thin space, `"3"` a
/// conditional medium space, `"4"` a conditional thick space, `"*"` an
/// impossible case -- and §766 reads it as `math_spacing[r_type*8 + t]`, which
/// is why the classes are numbered as they are.
///
/// "Conditional" is `\nonscript`: the space is inserted only when the current
/// style is above `script_style` (§766).
pub const MATH_SPACING: &[u8; 64] =
    b"0234000122*4000133**3**344*0400400*000000234000111*1111112341011";

/// What goes between a noad of class `left` and one of class `right`, as
/// §766's `case` reads §764's string.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Space {
    None,
    /// `\nonscript\mskip\thinmuskip`.
    ConditionalThin,
    /// `\mskip\thinmuskip`.
    Thin,
    /// `\nonscript\mskip\medmuskip`.
    ConditionalMedium,
    /// `\nonscript\mskip\thickmuskip`.
    ConditionalThick,
    /// `"*"`: a pair `mlist_to_hlist` never produces, because a Bin that would
    /// make one has already been turned into an Ord (§727-§729).
    Impossible,
}

/// §764's table, read.
pub fn spacing(left: Class, right: Class) -> Space {
    match MATH_SPACING[left as usize * 8 + right as usize] {
        b'0' => Space::None,
        b'1' => Space::ConditionalThin,
        b'2' => Space::Thin,
        b'3' => Space::ConditionalMedium,
        b'4' => Space::ConditionalThick,
        _ => Space::Impossible,
    }
}

/// The three math glues plain.tex sets (plain.tex:373-375), in `mu` scaled by
/// $2^{16}$ the way a `\mskip` holds them.
///
/// `\thinmuskip=3mu`, `\medmuskip=4mu plus 2mu minus 4mu`,
/// `\thickmuskip=5mu plus 5mu`.
pub const THIN_MU_SKIP: (i64, i64, i64) = (3 * 65536, 0, 0);
pub const MED_MU_SKIP: (i64, i64, i64) = (4 * 65536, 2 * 65536, 4 * 65536);
pub const THICK_MU_SKIP: (i64, i64, i64) = (5 * 65536, 5 * 65536, 0);

/// `\scriptspace=0.5pt` (plain.tex:347): the room reserved to the right of
/// every subscript and superscript (§757, §758).
pub const SCRIPT_SPACE: Scaled = 32768;

/// `\delimiterfactor=901` (plain.tex:327) and `\delimitershortfall=5pt`
/// (plain.tex:345), which together decide how tall a `\left(` grows (§762).
pub const DELIMITER_FACTOR: i64 = 901;
pub const DELIMITER_SHORTFALL: Scaled = 5 * 65536;

/// `\nulldelimiterspace=1.2pt` (plain.tex:346): the width `var_delimiter`
/// returns for a delimiter that is not there (§706).
pub const NULL_DELIMITER_SPACE: Scaled = 78643;

/// `\skewchar` of each family, as plain.tex sets them (plain.tex:474-475).
///
/// §742 computes how far an accent is moved to the right by looking up the
/// kern between the accented character and this character in the same font.
/// `cmmi10`'s skew character is `'177` and `cmsy10`'s is `'60`; plain.tex's
/// `\defaultskewchar` is -1 (plain.tex:324), so families 0 and 3 have none and
/// nothing set from them is skewed.
pub const SKEW_CHAR: [Option<u8>; 4] = [None, Some(0o177), Some(0o60), None];

/// `\binoppenalty=700` and `\relpenalty=500` (plain.tex:288-289): what §767
/// charges for breaking a formula after a binary operator or a relation.
pub const BIN_OP_PENALTY: i64 = 700;
pub const REL_PENALTY: i64 = 500;

/// `inf_penalty` (§157): the penalty §767 reads as "do not break here", and
/// the one every noad but a Bin and a Rel carries.
pub const INF_PENALTY: i64 = 10000;

/// The parameters `mlist_to_hlist` reads from `eqtb` besides the family
/// fonts: §764's three math skips, §757's `\scriptspace`, §762's
/// `\delimiterfactor` and `\delimitershortfall`, §706's
/// `\nulldelimiterspace` and §761's two penalties.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MathParams {
    pub thin_mu_skip: MuGlue,
    pub med_mu_skip: MuGlue,
    pub thick_mu_skip: MuGlue,
    pub script_space: Scaled,
    pub delimiter_factor: i64,
    pub delimiter_shortfall: Scaled,
    pub null_delimiter_space: Scaled,
    pub bin_op_penalty: i64,
    pub rel_penalty: i64,
}

impl MathParams {
    /// The values plain.tex sets, which the PDF path's formulas are set with.
    pub fn plain() -> MathParams {
        MathParams {
            thin_mu_skip: MuGlue::of(THIN_MU_SKIP),
            med_mu_skip: MuGlue::of(MED_MU_SKIP),
            thick_mu_skip: MuGlue::of(THICK_MU_SKIP),
            script_space: SCRIPT_SPACE,
            delimiter_factor: DELIMITER_FACTOR,
            delimiter_shortfall: DELIMITER_SHORTFALL,
            null_delimiter_space: NULL_DELIMITER_SPACE,
            bin_op_penalty: BIN_OP_PENALTY,
            rel_penalty: REL_PENALTY,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The table is the spec, so it is checked against The TeXbook's own
    /// reading of it (Chapter 18): an Ord beside a Bin takes a medium space,
    /// an Ord beside a Rel a thick one, and two Ords no space at all.
    #[test]
    fn the_spacing_table_is_the_one_in_section_764() {
        assert_eq!(MATH_SPACING.len(), 64);
        assert_eq!(spacing(Class::Ord, Class::Ord), Space::None);
        assert_eq!(spacing(Class::Ord, Class::Op), Space::Thin);
        assert_eq!(spacing(Class::Ord, Class::Bin), Space::ConditionalMedium);
        assert_eq!(spacing(Class::Ord, Class::Rel), Space::ConditionalThick);
        assert_eq!(spacing(Class::Ord, Class::Inner), Space::ConditionalThin);
        // A Bin cannot be followed by a Rel or a Close: §728 has already made
        // it an Ord by the time the second pass asks.
        assert_eq!(spacing(Class::Bin, Class::Rel), Space::Impossible);
        assert_eq!(spacing(Class::Bin, Class::Close), Space::Impossible);
        assert_eq!(spacing(Class::Open, Class::Ord), Space::None);
        assert_eq!(spacing(Class::Punct, Class::Ord), Space::ConditionalThin);
    }

    /// §702's style arithmetic, which decides the size of every subsidiary
    /// formula. The numbering runs backwards -- a smaller style is a larger
    /// number -- so these are the cases that catch a sign error.
    #[test]
    fn the_style_transitions_are_section_702s() {
        assert_eq!(sup_style(DISPLAY_STYLE), SCRIPT_STYLE);
        assert_eq!(sup_style(TEXT_STYLE), SCRIPT_STYLE);
        assert_eq!(sup_style(SCRIPT_STYLE), SCRIPT_SCRIPT_STYLE);
        assert_eq!(sup_style(SCRIPT_SCRIPT_STYLE), SCRIPT_SCRIPT_STYLE);
        // A subscript is always cramped.
        assert_eq!(sub_style(DISPLAY_STYLE), SCRIPT_STYLE + CRAMPED);
        assert_eq!(sub_style(SCRIPT_STYLE), SCRIPT_SCRIPT_STYLE + CRAMPED);
        // A numerator is one step smaller; a denominator one step smaller and
        // cramped. Neither goes below scriptscript.
        assert_eq!(num_style(DISPLAY_STYLE), TEXT_STYLE);
        assert_eq!(num_style(SCRIPT_SCRIPT_STYLE), SCRIPT_SCRIPT_STYLE);
        assert_eq!(denom_style(DISPLAY_STYLE), TEXT_STYLE + CRAMPED);
        assert_eq!(cramped_style(DISPLAY_STYLE), DISPLAY_STYLE + CRAMPED);
        assert_eq!(cramped_style(TEXT_STYLE + CRAMPED), TEXT_STYLE + CRAMPED);
    }

    /// §703: display and text are the text size, script the script size, and
    /// both cramped variants agree with their uncramped ones.
    #[test]
    fn the_size_of_a_style_is_section_703s() {
        assert_eq!(size_of(DISPLAY_STYLE), 0);
        assert_eq!(size_of(TEXT_STYLE + CRAMPED), 0);
        assert_eq!(size_of(SCRIPT_STYLE), 1);
        assert_eq!(size_of(SCRIPT_STYLE + CRAMPED), 1);
        assert_eq!(size_of(SCRIPT_SCRIPT_STYLE), 2);
        assert_eq!(size_of(SCRIPT_SCRIPT_STYLE + CRAMPED), 2);
    }
}