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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
//! TeX82's primitive control sequences, as `\meaning` and `\show` name them.
//!
//! `tex.web` enters every primitive into the hash table with a `primitive`
//! call (§226 through §1344), so before a document redefines one its meaning
//! is the primitive itself and §296's `print_meaning` prints it through §298's
//! `print_cmd_chr` -- almost always as the escaped name. texrs dispatches only
//! some of them, but which of them it can EXECUTE is a separate fact from what
//! each one MEANS: `\meaning\hsize` is `\hsize` in every TeX, whether or not
//! the engine in front of it lays out a page with it.
//!
//! The list is §226's `primitive` calls in TeX82 (no e-TeX or pdfTeX
//! extensions), measured against tex 3.141592653 one name at a time.

/// Every TeX82 primitive that is not a §236 integer parameter (those are
/// `crate::intpar::NAMES`). The control symbols `\ `, `\/` and `\-` are the
/// one-character names `" "`, `"/"` and `"-"`.
const NAMES: &[&str] = &[
    // §226: the glue parameters.
    "lineskip",
    "baselineskip",
    "parskip",
    "abovedisplayskip",
    "belowdisplayskip",
    "abovedisplayshortskip",
    "belowdisplayshortskip",
    "leftskip",
    "rightskip",
    "topskip",
    "splittopskip",
    "tabskip",
    "spaceskip",
    "xspaceskip",
    "parfillskip",
    "thinmuskip",
    "medmuskip",
    "thickmuskip",
    // §230: the token-list parameters.
    "output",
    "everypar",
    "everymath",
    "everydisplay",
    "everyhbox",
    "everyvbox",
    "everyjob",
    "everycr",
    "errhelp",
    // §248: the dimension parameters.
    "parindent",
    "mathsurround",
    "lineskiplimit",
    "hsize",
    "vsize",
    "maxdepth",
    "splitmaxdepth",
    "boxmaxdepth",
    "hfuzz",
    "vfuzz",
    "delimitershortfall",
    "nulldelimiterspace",
    "scriptspace",
    "predisplaysize",
    "displaywidth",
    "displayindent",
    "overfullrule",
    "hangindent",
    "hoffset",
    "voffset",
    "emergencystretch",
    // §265: the rest of the commands the hash table starts with.
    " ",
    "/",
    "accent",
    "advance",
    "afterassignment",
    "aftergroup",
    "begingroup",
    "char",
    "csname",
    "delimiter",
    "divide",
    "endcsname",
    "endgroup",
    "expandafter",
    "font",
    "fontdimen",
    "halign",
    "hrule",
    "ignorespaces",
    "insert",
    "mark",
    "mathaccent",
    "mathchar",
    "mathchoice",
    "multiply",
    "noalign",
    "noboundary",
    "noexpand",
    "nonscript",
    "omit",
    "parshape",
    "penalty",
    "prevgraf",
    "radical",
    "read",
    "relax",
    "setbox",
    "the",
    "toks",
    "vadjust",
    "valign",
    "vcenter",
    "vrule",
    // §334, §376, §384: \par, \input and \endinput, the five marks.
    "par",
    "input",
    "endinput",
    "topmark",
    "firstmark",
    "botmark",
    "splitfirstmark",
    "splitbotmark",
    // §411, §416: registers and the internal quantities.
    "count",
    "dimen",
    "skip",
    "muskip",
    "spacefactor",
    "prevdepth",
    "deadcycles",
    "insertpenalties",
    "wd",
    "ht",
    "dp",
    "lastpenalty",
    "lastkern",
    "lastskip",
    "inputlineno",
    "badness",
    // §468, §487, §491: conversions and conditionals.
    "number",
    "romannumeral",
    "string",
    "meaning",
    "fontname",
    "jobname",
    "if",
    "ifcat",
    "ifnum",
    "ifdim",
    "ifodd",
    "ifvmode",
    "ifhmode",
    "ifmmode",
    "ifinner",
    "ifvoid",
    "ifhbox",
    "ifvbox",
    "ifx",
    "ifeof",
    "iftrue",
    "iffalse",
    "ifcase",
    "fi",
    "or",
    "else",
    // §553, §780: the null font and the alignment delimiters.
    "nullfont",
    "span",
    "cr",
    "crcr",
    // §983, §1052 onward: the page builder and the chief executive.
    "pagegoal",
    "pagetotal",
    "pagestretch",
    "pagefilstretch",
    "pagefillstretch",
    "pagefilllstretch",
    "pageshrink",
    "pagedepth",
    "end",
    "dump",
    "hskip",
    "hfil",
    "hfill",
    "hss",
    "hfilneg",
    "vskip",
    "vfil",
    "vfill",
    "vss",
    "vfilneg",
    "mskip",
    "kern",
    "mkern",
    "moveleft",
    "moveright",
    "raise",
    "lower",
    "box",
    "copy",
    "lastbox",
    "vsplit",
    "vtop",
    "vbox",
    "hbox",
    "shipout",
    "leaders",
    "cleaders",
    "xleaders",
    "indent",
    "noindent",
    "unpenalty",
    "unkern",
    "unskip",
    "unhbox",
    "unhcopy",
    "unvbox",
    "unvcopy",
    "-",
    "discretionary",
    "eqno",
    "leqno",
    "mathord",
    "mathop",
    "mathbin",
    "mathrel",
    "mathopen",
    "mathclose",
    "mathpunct",
    "mathinner",
    "underline",
    "overline",
    "displaylimits",
    "limits",
    "nolimits",
    "displaystyle",
    "textstyle",
    "scriptstyle",
    "scriptscriptstyle",
    "above",
    "over",
    "atop",
    "abovewithdelims",
    "overwithdelims",
    "atopwithdelims",
    "left",
    "right",
    "long",
    "outer",
    "global",
    "def",
    "gdef",
    "edef",
    "xdef",
    "let",
    "futurelet",
    "chardef",
    "mathchardef",
    "countdef",
    "dimendef",
    "skipdef",
    "muskipdef",
    "toksdef",
    "catcode",
    "mathcode",
    "lccode",
    "uccode",
    "sfcode",
    "delcode",
    "textfont",
    "scriptfont",
    "scriptscriptfont",
    "hyphenation",
    "patterns",
    "hyphenchar",
    "skewchar",
    "batchmode",
    "nonstopmode",
    "scrollmode",
    "errorstopmode",
    "openin",
    "closein",
    "message",
    "errmessage",
    "lowercase",
    "uppercase",
    "show",
    "showbox",
    "showthe",
    "showlists",
    // §1344: the extensions.
    "openout",
    "write",
    "closeout",
    "special",
    "immediate",
    "setlanguage",
];

/// Whether `name` is a TeX82 primitive outside §236's integer parameters.
pub fn is_primitive(name: &str) -> bool {
    NAMES.contains(&name)
}

/// §413's internal quantities that are not parameters: the primitives whose
/// commands lie from §209's `min_internal` to `max_internal` -- `last_item`,
/// `toks_register`, `assign_font_dimen`, `assign_font_int`, `set_aux`,
/// `set_prev_graf`, `set_page_dimen`, `set_page_int`, `set_box_dimen`,
/// `set_shape`, `def_code`, `def_family`, `set_font`, `def_font` and
/// `register`. A `\chardef`, `\mathchardef` or register name is one too, by
/// its meaning rather than by a name here.
const INTERNAL: &[&str] = &[
    "lastpenalty",
    "lastkern",
    "lastskip",
    "inputlineno",
    "badness",
    "toks",
    "fontdimen",
    "hyphenchar",
    "skewchar",
    "spacefactor",
    "prevdepth",
    "prevgraf",
    "pagegoal",
    "pagetotal",
    "pagestretch",
    "pagefilstretch",
    "pagefillstretch",
    "pagefilllstretch",
    "pageshrink",
    "pagedepth",
    "deadcycles",
    "insertpenalties",
    "wd",
    "ht",
    "dp",
    "parshape",
    "catcode",
    "mathcode",
    "lccode",
    "uccode",
    "sfcode",
    "delcode",
    "textfont",
    "scriptfont",
    "scriptscriptfont",
    "nullfont",
    "font",
    "count",
    "dimen",
    "skip",
    "muskip",
];

/// Whether the primitive `name` is an internal quantity (§413), which §440's
/// `scan_int` reads through `scan_something_internal` rather than as the
/// missing number it would otherwise be: one of `INTERNAL`, or a glue,
/// token-list, dimension (§226, §230, §248) or integer (§236) parameter.
pub fn is_internal_quantity(name: &str) -> bool {
    // The parameter sections open `NAMES` and §265's commands follow them,
    // the first of those being the control space.
    let parameters = NAMES.iter().position(|n| *n == " ").unwrap_or(0);
    INTERNAL.contains(&name)
        || NAMES[..parameters].contains(&name)
        || crate::intpar::index(name).is_some()
}

/// The primitives §1211's `prefixed_command` accepts that are neither a
/// parameter nor one of `expand::ASSIGNMENTS`: every command code above
/// `max_non_prefixed_command` (§209) that takes a `\global`.
const PREFIXED_ASSIGNMENTS: &[&str] = &[
    "fontdimen",
    "hyphenchar",
    "skewchar",
    "spacefactor",
    "prevdepth",
    "prevgraf",
    "pagegoal",
    "pagetotal",
    "pagestretch",
    "pagefilstretch",
    "pagefillstretch",
    "pagefilllstretch",
    "pageshrink",
    "pagedepth",
    "deadcycles",
    "insertpenalties",
    "wd",
    "ht",
    "dp",
    "parshape",
    "textfont",
    "scriptfont",
    "scriptscriptfont",
    "nullfont",
    "font",
    "setbox",
    "read",
    "hyphenation",
    "patterns",
    "batchmode",
    "nonstopmode",
    "scrollmode",
    "errorstopmode",
];

/// LuaTeX's commands above `max_non_prefixed_command` (commands.h, from
/// `toks_register_cmd` to `set_font_id_cmd`), spelt as `token.create` names
/// them in `crate::luatex_primitives`: every one a prefix may stand in front of.
const PREFIXED_LUATEX_COMMANDS: &[&str] = &[
    "toks_register",
    "assign_toks",
    "assign_int",
    "assign_attr",
    "assign_dimen",
    "assign_glue",
    "assign_mu_glue",
    "assign_font_dimen",
    "assign_font_int",
    "assign_hang_indent",
    "set_aux",
    "set_prev_graf",
    "set_page_dimen",
    "set_page_int",
    "set_box_dimen",
    "set_tex_shape",
    "set_etex_shape",
    "def_char_code",
    "def_del_code",
    "extdef_math_code",
    "extdef_del_code",
    "def_family",
    "set_math_param",
    "set_font",
    "def_font",
    "register",
    "assign_box_direction",
    "assign_box_dir",
    "assign_direction",
    "assign_dir",
    "combinetoks",
    "advance",
    "multiply",
    "divide",
    "prefix",
    "let",
    "shorthand_def",
    "def_lua_call",
    "read_to_cs",
    "def",
    "set_box",
    "hyph_data",
    "set_interaction",
    "letterspace_font",
    "expand_font",
    "copy_font",
    "set_font_id",
];

/// Whether the primitive `name` is a command a prefix may stand in front of
/// (§1211): a parameter, one of `PREFIXED_ASSIGNMENTS`, or one of LuaTeX's
/// assignments (`PREFIXED_LUATEX_COMMANDS`).
pub fn is_prefixed_assignment(name: &str) -> bool {
    let parameters = NAMES.iter().position(|n| *n == " ").unwrap_or(0);
    PREFIXED_ASSIGNMENTS.contains(&name)
        || NAMES[..parameters].contains(&name)
        || crate::intpar::index(name).is_some()
        || luatex_command(name).is_some_and(|cmd| PREFIXED_LUATEX_COMMANDS.contains(&cmd))
}

/// The primitives other than the conditionals that expand (§366): the
/// `expand_after`, `no_expand`, `cs_name`, `convert`, `the`, `top_bot_mark`,
/// `input` and `fi_or_else` commands, and e-TeX's additions to them.
const EXPANDABLE: &[&str] = &[
    "expandafter",
    "unless",
    "noexpand",
    "csname",
    "number",
    "romannumeral",
    "string",
    "meaning",
    "fontname",
    "jobname",
    "csstring",
    "the",
    "detokenize",
    "unexpanded",
    "topmark",
    "firstmark",
    "botmark",
    "splitfirstmark",
    "splitbotmark",
    "input",
    "endinput",
    "scantokens",
    "scantextokens",
    "expanded",
    "begincsname",
    "lastnamedcs",
    "fi",
    "or",
    "else",
];

/// Whether the primitive `name` expands, the conditionals aside (those are
/// `crate::expand`'s `CONDITIONALS`).
pub fn expands(name: &str) -> bool {
    EXPANDABLE.contains(&name)
}

/// What §296's `print_meaning` prints for the primitive `name` while it still
/// means itself, `esc` being the `\escapechar` character (if any).
///
/// Two kinds print something other than the escaped name. §577's
/// `print_cmd_chr` for `set_font` is `select font` and the font's name, and
/// the only font a primitive names is `\nullfont`. And §296 follows a mark
/// command with `:`, a line end and the mark's text -- empty, because texrs
/// has no page builder to fill one. The line end is NOT written: the message
/// printer has no way to say "end the line" other than the `\newlinechar`
/// character, and a raw line feed would print as `^^J` under INITEX's
/// `\newlinechar=-1`. `BUGS.md` records it.
pub fn meaning(name: &str, esc: &str) -> String {
    match name {
        "nullfont" => "select font nullfont".to_string(),
        "topmark" | "firstmark" | "botmark" | "splitfirstmark" | "splitbotmark" => {
            format!("{esc}{name}:")
        }
        _ => format!("{esc}{name}"),
    }
}

/// luatex's command code for the primitive `name` (`crate::luatex_primitives`,
/// written from luatex's own table), if luatex has a primitive of that name.
///
/// This is what the expander knows about a primitive it has no arm for: that
/// it IS one, of which command, and whether that command expands -- so
/// `\meaning` and `\ifdefined` answer as luatex does, whatever texrs executes.
pub fn luatex_command(name: &str) -> Option<&'static str> {
    use crate::luatex_primitives::TABLE;
    TABLE
        .binary_search_by(|(n, ..)| (*n).cmp(name))
        .ok()
        .map(|i| TABLE[i].1)
}

/// Whether `name` is something tex starts out knowing: a TeX82 primitive, a §236
/// parameter, a primitive of luatex's, or a command this engine documents.
/// Anything else is undefined until a document defines it.
///
/// A set rather than a scan of the lists: the expander asks for every control
/// sequence it expands.
pub fn is_known_name(name: &str) -> bool {
    use once_cell::sync::Lazy;
    static KNOWN: Lazy<std::collections::HashSet<&'static str>> = Lazy::new(|| {
        let mut set: std::collections::HashSet<&'static str> = NAMES.iter().copied().collect();
        set.extend(crate::intpar::NAMES.iter().copied());
        set.extend(crate::luatex_primitives::TABLE.iter().map(|(n, ..)| *n));
        set.extend(crate::corpus::names().filter_map(|n| n.strip_prefix('\\')));
        set
    });
    KNOWN.contains(name)
}

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

    #[test]
    fn no_name_is_listed_twice_or_also_an_integer_parameter() {
        for (i, n) in NAMES.iter().enumerate() {
            assert!(!NAMES[..i].contains(n), "{n} listed twice");
            assert!(crate::intpar::index(n).is_none(), "{n} is a §236 parameter");
        }
    }
}