texrs 0.6.3

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
//! Lower the command stream to fusevm bytecode.
//!
//! This is the whole reason texrs is a fusevm frontend rather than another
//! interpreter. A count register becomes a VM SLOT, so `\advance\count0 by 5` is
//! `GetSlot / LoadInt / Add / SetSlot` — native ops the JIT can compile — rather
//! than a hash lookup and a match in a tree-walker. A conditional becomes a real
//! branch (`Lt` + `JumpIfFalse`), not a Rust `if` deciding which subtree to walk.
//!
//! There are 256 count registers and they map onto slots 0..255 directly, which
//! keeps the mapping trivial to read and means a register read is an array index.

use std::collections::HashMap;

use crate::expand::TexError;
use crate::ir::{Arith, Cmd, MsgOp, Num, Rel};
use fusevm::{Chunk, ChunkBuilder, Op, Value};

/// Builtin ids this frontend registers on the VM.
pub mod ops {
    /// Append a run of the document's own text.
    pub const TEXT: u16 = 4005;
    /// Open a colour: three components follow.
    ///
    /// 4010 and 4011, not 4006 and 4007: those are ARITH_CHECKED and MSG_CLOSE.
    /// Registering a builtin twice silently keeps the LAST one, so the colour
    /// ops were compiled, called, and quietly handled by somebody else's
    /// function -- the chunk was right and the page had no colour in it.
    pub const COLOR_PUSH: u16 = 4010;
    /// Close the innermost colour.
    pub const COLOR_POP: u16 = 4011;
    /// Append one rendered piece to the message being built.
    pub const MSG_APPEND: u16 = 4000;
    /// Finish the message being built and record it.
    pub const MSG_FLUSH: u16 = 4001;
    /// Compile and register a `\rust{ … }` block: one argument, the base64 body.
    pub const FFI_COMPILE: u16 = 4003;
    /// Call a function a block exported: the name, then its arguments.
    pub const FFI_CALL: u16 = 4004;
    /// `\multiply` / `\divide` under TeX's overflow rule: the old value, the
    /// operand, and 0 for multiply or 1 for divide.
    pub const ARITH_CHECKED: u16 = 4006;
    /// Close an `\input` file: append `)` to the message already recorded,
    /// rather than record one, because tex writes the paren hard against what
    /// came before it while the stream is joined with spaces. No arguments.
    pub const MSG_CLOSE: u16 = 4007;
    /// Append a dimension, written as TeX writes one: one argument, the value
    /// in scaled points.
    pub const MSG_DIMEN: u16 = 4008;
    /// Append a glue, written as TeX writes one: four arguments -- natural,
    /// stretch, shrink, and the packed orders.
    pub const MSG_GLUE: u16 = 4009;
    /// Append a MATH glue, written as TeX writes one: the same four arguments
    /// `MSG_GLUE` takes, with `mu` for the unit.
    pub const MSG_MUGLUE: u16 = 4014;
    /// Record where the command about to run would be reported from: one
    /// argument, `tex.web` §311's context display for that point in the source.
    pub const ERR_SITE: u16 = 4012;
    /// §1335's `(see the transcript file for additional information)`, written
    /// only if something was reported during the run. No arguments.
    pub const TRANSCRIPT_NOTICE: u16 = 4013;
    /// A statement boundary, emitted only under `--dap`. The debug adapter
    /// stops here; an ordinary run carries none of these ops.
    pub const DBG_LINE: u16 = 4002;
    /// `tex.web` §453's `<factor><internal unit>`: the register's value, the
    /// factor's integer part, and its fraction in 65536ths. A builtin rather
    /// than a run of arithmetic ops because §107's truncation and §460's clamp
    /// are the port, and one Rust function is where they stay readable.
    pub const SCALE_DIMEN: u16 = 4015;
    /// Append a number as `\romannumeral` writes it: one argument, the value.
    pub const MSG_ROMAN: u16 = 4016;
}

/// TeX has exactly 256 count registers (`tex.web` §236).
pub const COUNT_SLOTS: u16 = 256;
/// Where the dimension registers start. They are registers exactly as the
/// counts are -- assigned, read and restored by a group -- so they are slots in
/// the same file rather than a second store with its own rules.
pub const DIMEN_BASE: i64 = 256;
/// Where the glue registers start. A glue is FOUR slots -- natural, stretch,
/// shrink, and the two orders packed together -- because a register that a
/// group has to save and restore is easiest to keep as slots like every other
/// register, rather than as a fifth kind of store.
pub const SKIP_BASE: i64 = 512;
/// How many slots one glue register occupies.
pub const SKIP_STRIDE: i64 = 4;
/// Where the MATH glue registers start, past the 256 ordinary ones.
///
/// `\muskip` is `\skip` measured in mu (`tex.web` §455): the arithmetic is
/// identical -- a mu is 65536ths like a point -- and only the unit it is
/// written and read in differs. So it is four slots in the same file, at the
/// same stride, and everything a glue register already does (a group's save and
/// restore, `\advance`, `\the`) works for it with no second mechanism.
pub const MUSKIP_BASE: i64 = SKIP_BASE + 256 * SKIP_STRIDE;

pub struct Compiler {
    b: ChunkBuilder,
    /// Emit a `DBG_LINE` marker at every statement boundary. Off for an
    /// ordinary run, so nothing pays for the debugger that is not using it.
    debug: bool,
    /// The source line the commands being lowered came from, updated by
    /// [`Cmd::Line`] and stamped onto every op emitted after it.
    line: u32,
    /// Pool index of every string already added, so a repeated one costs a
    /// lookup rather than a slot.
    ///
    /// A `LoadConst` operand is a u16, so the pool holds 65,536 entries and a
    /// frontend that adds one per emission is bounded by how much text a
    /// document has -- which for a book is not a bound at all. Coalescing text
    /// runs across line directives took the books under it; a 4 MB reference
    /// still went past. Text repeats -- the same words, the same spacing -- so
    /// interning bounds the pool by what a document SAYS rather than by how
    /// often it says it.
    strings: HashMap<String, u16>,
}

impl Compiler {
    pub fn new() -> Self {
        let mut b = ChunkBuilder::new();
        // Every handler in `runtime.rs` pops exactly the `argc` its call site
        // encodes -- checked one by one, and `tests/opcodes.rs` is what keeps
        // that true. Saying so lets fusevm's AOT and native paths reason about
        // a builtin's stack effect instead of refusing to; without it a builtin
        // whose RESULT is used (rather than dropped) silently produced the
        // wrong value in an `--aot` binary while the interpreter was right.
        b.set_builtin_argc_is_arity(true);
        Self {
            b,
            debug: false,
            line: 0,
            strings: HashMap::new(),
        }
    }

    /// A compiler that also emits the `--dap` statement markers.
    pub fn new_debug() -> Self {
        Self {
            debug: true,
            ..Self::new()
        }
    }

    /// The bytecode for `cmds`, or the reason there is none.
    ///
    /// Compiling FAILS rather than panics when the chunk cannot hold the
    /// document: fusevm's own guidance for a frontend compiling input it did
    /// not write is to see the full pool and report it, and a `\message`
    /// naming the limit is a better answer than an abort inside the VM.
    pub fn compile(mut self, cmds: &[Cmd]) -> Result<Chunk, TexError> {
        // Every count register starts at zero, as INITEX leaves them; the slots
        // have to be written before they are read or a read finds `Undef`.
        for reg in 0..TOTAL_SLOTS {
            self.b.emit(Op::LoadInt(0), self.line);
            self.b.emit(Op::SetSlot(reg), self.line);
        }
        self.block(cmds)?;
        Ok(self.b.build())
    }

    /// The pool index for `s`, added once however often it is emitted.
    fn str_const(&mut self, s: &str) -> Result<u16, TexError> {
        if let Some(&k) = self.strings.get(s) {
            return Ok(k);
        }
        let Some(k) = self.b.try_add_constant(Value::Str(s.to_string().into())) else {
            return Err(TexError(format!(
                "This document has more than {} distinct strings, which is \
                 every constant a chunk can address",
                ChunkBuilder::MAX_POOL
            )));
        };
        self.strings.insert(s.to_string(), k);
        Ok(k)
    }

    fn block(&mut self, cmds: &[Cmd]) -> Result<(), TexError> {
        for c in cmds {
            self.cmd(c)?;
        }
        Ok(())
    }

    fn cmd(&mut self, c: &Cmd) -> Result<(), TexError> {
        match c {
            // A line directive: no code of its own, just the stamp every
            // following op carries -- unless this is a debug build, where it is
            // also where the debugger is allowed to stop.
            Cmd::Line(n) => {
                self.line = *n;
                if self.debug {
                    self.b.emit(Op::CallBuiltin(ops::DBG_LINE, 0), self.line);
                    self.b.emit(Op::Pop, self.line);
                }
            }
            Cmd::RustCompile(b64) => {
                let k = self.str_const(b64)?;
                self.b.emit(Op::LoadConst(k), self.line);
                self.b.emit(Op::CallBuiltin(ops::FFI_COMPILE, 1), self.line);
                self.b.emit(Op::Pop, self.line);
            }
            Cmd::SetCount(reg, n) => {
                self.num(n)?;
                self.b.emit(Op::SetSlot(slot(*reg)), self.line);
            }
            Cmd::Arith(op, reg, n) => {
                self.b.emit(Op::GetSlot(slot(*reg)), self.line);
                self.num(n)?;
                match op {
                    // `\advance` wraps. A count register is 32 bits, and TeX
                    // adds into that word without checking: 2147483647 + 1 is
                    // -2147483648 in tex, measured, with no error. Wrapping
                    // branch-free keeps the op stream JIT-eligible, which
                    // matters because `\advance` is what a TeX loop does on
                    // every turn.
                    Arith::Add => {
                        self.b.emit(Op::Add, self.line);
                        self.wrap_to_32_bits();
                    }
                    // `\multiply` and `\divide` do check (tex.web §1236), and
                    // raise `Arithmetic overflow` rather than wrapping -- so
                    // they go through a host builtin that applies TeX's rule
                    // and can raise. Neither is what a hot loop is made of.
                    Arith::Mul | Arith::Div => {
                        let which = match op {
                            Arith::Mul => 0,
                            _ => 1,
                        };
                        self.b.emit(Op::LoadInt(which), self.line);
                        self.b
                            .emit(Op::CallBuiltin(ops::ARITH_CHECKED, 3), self.line);
                    }
                }
                self.b.emit(Op::SetSlot(slot(*reg)), self.line);
            }
            Cmd::Text(t) => {
                let k = self.str_const(t)?;
                self.b.emit(Op::LoadConst(k), self.line);
                self.b.emit(Op::CallBuiltin(ops::TEXT, 1), self.line);
                self.b.emit(Op::Pop, self.line);
            }
            Cmd::FileClose => {
                self.b.emit(Op::CallBuiltin(ops::MSG_CLOSE, 0), self.line);
                self.b.emit(Op::Pop, self.line);
            }
            Cmd::ErrorSite(site) => {
                let k = self.str_const(site)?;
                self.b.emit(Op::LoadConst(k), self.line);
                self.b.emit(Op::CallBuiltin(ops::ERR_SITE, 1), self.line);
                self.b.emit(Op::Pop, self.line);
            }
            Cmd::TranscriptNotice => {
                self.b
                    .emit(Op::CallBuiltin(ops::TRANSCRIPT_NOTICE, 0), self.line);
                self.b.emit(Op::Pop, self.line);
            }
            Cmd::Color { rgb, body } => {
                let (r, g, b) = *rgb;
                for v in [r, g, b] {
                    let k = self.b.add_constant(Value::Str(format!("{v}").into()));
                    self.b.emit(Op::LoadConst(k), self.line);
                }
                self.b.emit(Op::CallBuiltin(ops::COLOR_PUSH, 3), self.line);
                self.b.emit(Op::Pop, self.line);
                self.block(body)?;
                self.b.emit(Op::CallBuiltin(ops::COLOR_POP, 0), self.line);
                self.b.emit(Op::Pop, self.line);
            }
            Cmd::Message(msg) => {
                self.msg_ops(msg)?;
                self.b.emit(Op::CallBuiltin(ops::MSG_FLUSH, 0), self.line);
                self.b.emit(Op::Pop, self.line);
            }
            Cmd::Group { saves, body } => {
                // The saved values sit on the VM stack under the group's own
                // work, which stays balanced, and are written back in reverse.
                for reg in saves {
                    self.b.emit(Op::GetSlot(slot(*reg)), self.line);
                }
                self.block(body)?;
                for reg in saves.iter().rev() {
                    self.b.emit(Op::SetSlot(slot(*reg)), self.line);
                }
            }
            Cmd::IfNum {
                left,
                rel,
                right,
                then_branch,
                else_branch,
            } => {
                self.num(left)?;
                self.num(right)?;
                self.b.emit(
                    match rel {
                        Rel::Less => Op::NumLt,
                        Rel::Equal => Op::NumEq,
                        Rel::Greater => Op::NumGt,
                    },
                    self.line,
                );
                self.branch(then_branch, else_branch)?;
            }
            Cmd::Loop {
                body,
                left,
                rel,
                right,
            } => {
                // do-while: the body runs, then the test decides whether to go
                // round again. `patch_jump` takes an absolute target, so the
                // back edge is just the position the body started at.
                let start = self.b.current_pos();
                self.block(body)?;
                self.num(left)?;
                self.num(right)?;
                self.b.emit(
                    match rel {
                        Rel::Less => Op::NumLt,
                        Rel::Equal => Op::NumEq,
                        Rel::Greater => Op::NumGt,
                    },
                    self.line,
                );
                let back = self.b.emit(Op::JumpIfTrue(0), self.line);
                self.b.patch_jump(back, start);
            }
            Cmd::IfOdd {
                value,
                then_branch,
                else_branch,
            } => {
                // `\ifodd n` is `n mod 2 = 1`, and a negative odd number is odd
                // too -- so compare against zero rather than against one.
                self.num(value)?;
                self.b.emit(Op::LoadInt(2), self.line);
                self.b.emit(Op::Mod, self.line);
                self.b.emit(Op::LoadInt(0), self.line);
                self.b.emit(Op::NumEq, self.line);
                self.b.emit(Op::LogNot, self.line);
                self.branch(then_branch, else_branch)?;
            }
        }
        Ok(())
    }

    /// Truncate the value on the stack to 32 bits, two's complement.
    ///
    /// `((v + 2^31) & 0xFFFFFFFF) - 2^31`, which is branch-free and made of ops
    /// the JIT accepts. A count register is a 32-bit word in TeX
    /// (`tex.web` §236), and a frontend holding it in an i64 silently answers
    /// differently the moment a document runs past the edge -- which real
    /// documents do, because wrapping is how TeX's own `\maxdimen` arithmetic
    /// behaves.
    fn wrap_to_32_bits(&mut self) {
        const SIGN_BIT: i64 = 1 << 31;
        const MASK: i64 = 0xFFFF_FFFF;
        self.b.emit(Op::LoadInt(SIGN_BIT), self.line);
        self.b.emit(Op::Add, self.line);
        self.b.emit(Op::LoadInt(MASK), self.line);
        self.b.emit(Op::BitAnd, self.line);
        self.b.emit(Op::LoadInt(SIGN_BIT), self.line);
        self.b.emit(Op::Sub, self.line);
    }

    /// Emit the steps that build a message, appending each piece as it goes.
    fn msg_ops(&mut self, msg: &[MsgOp]) -> Result<(), TexError> {
        for m in msg {
            match m {
                MsgOp::Text(t) => {
                    let k = self.str_const(t)?;
                    self.b.emit(Op::LoadConst(k), self.line);
                    self.b.emit(Op::CallBuiltin(ops::MSG_APPEND, 1), self.line);
                    self.b.emit(Op::Pop, self.line);
                }
                MsgOp::Discard(n) => {
                    self.num(n)?;
                    self.b.emit(Op::Pop, self.line);
                }
                MsgOp::Number(n) => {
                    self.num(n)?;
                    self.b.emit(Op::CallBuiltin(ops::MSG_APPEND, 1), self.line);
                    self.b.emit(Op::Pop, self.line);
                }
                MsgOp::Glue(parts) => {
                    for n in parts.iter() {
                        self.num(n)?;
                    }
                    self.b.emit(Op::CallBuiltin(ops::MSG_GLUE, 4), self.line);
                    self.b.emit(Op::Pop, self.line);
                }
                // The same four slots through a builtin that writes `mu` after
                // each finite component (`tex.web` §1060's `print_spec(p,"mu")`).
                MsgOp::MuGlue(parts) => {
                    for n in parts.iter() {
                        self.num(n)?;
                    }
                    self.b.emit(Op::CallBuiltin(ops::MSG_MUGLUE, 4), self.line);
                    self.b.emit(Op::Pop, self.line);
                }
                MsgOp::Dimen(n) => {
                    self.num(n)?;
                    self.b.emit(Op::CallBuiltin(ops::MSG_DIMEN, 1), self.line);
                    self.b.emit(Op::Pop, self.line);
                }
                MsgOp::Roman(n) => {
                    self.num(n)?;
                    self.b.emit(Op::CallBuiltin(ops::MSG_ROMAN, 1), self.line);
                    self.b.emit(Op::Pop, self.line);
                }
                MsgOp::If {
                    left,
                    rel,
                    right,
                    then_ops,
                    else_ops,
                } => {
                    self.num(left)?;
                    self.num(right)?;
                    self.b.emit(
                        match rel {
                            Rel::Less => Op::NumLt,
                            Rel::Equal => Op::NumEq,
                            Rel::Greater => Op::NumGt,
                        },
                        self.line,
                    );
                    self.msg_branch(then_ops, else_ops)?;
                }
                MsgOp::IfOdd {
                    value,
                    then_ops,
                    else_ops,
                } => {
                    self.num(value)?;
                    self.b.emit(Op::LoadInt(2), self.line);
                    self.b.emit(Op::Mod, self.line);
                    self.b.emit(Op::LoadInt(0), self.line);
                    self.b.emit(Op::NumEq, self.line);
                    self.b.emit(Op::LogNot, self.line);
                    self.msg_branch(then_ops, else_ops)?;
                }
            }
        }
        Ok(())
    }

    fn msg_branch(&mut self, then_ops: &[MsgOp], else_ops: &[MsgOp]) -> Result<(), TexError> {
        let to_else = self.b.emit(Op::JumpIfFalse(0), self.line);
        self.msg_ops(then_ops)?;
        let over = self.b.emit(Op::Jump(0), self.line);
        let at = self.b.current_pos();
        self.b.patch_jump(to_else, at);
        self.msg_ops(else_ops)?;
        let end = self.b.current_pos();
        self.b.patch_jump(over, end);
        Ok(())
    }

    /// The condition is on the stack; emit the two arms around it.
    fn branch(&mut self, then_branch: &[Cmd], else_branch: &[Cmd]) -> Result<(), TexError> {
        let to_else = self.b.emit(Op::JumpIfFalse(0), self.line);
        self.block(then_branch)?;
        let over_else = self.b.emit(Op::Jump(0), self.line);
        let else_at = self.b.current_pos();
        self.b.patch_jump(to_else, else_at);
        self.block(else_branch)?;
        let end = self.b.current_pos();
        self.b.patch_jump(over_else, end);
        Ok(())
    }

    fn num(&mut self, n: &Num) -> Result<(), TexError> {
        match n {
            Num::Literal(v) => {
                self.b.emit(Op::LoadInt(*v), self.line);
            }
            Num::Count(reg) => {
                self.b.emit(Op::GetSlot(slot(*reg)), self.line);
            }
            // The register first, then the two halves of the factor: the
            // builtin pops them back in that order and takes §453's product.
            Num::Scaled { int, frac, reg } => {
                self.b.emit(Op::GetSlot(slot(*reg)), self.line);
                self.b.emit(Op::LoadInt(*int), self.line);
                self.b.emit(Op::LoadInt(*frac), self.line);
                self.b.emit(Op::CallBuiltin(ops::SCALE_DIMEN, 3), self.line);
            }
            // The same builtin, with the factor's integer part read from a slot
            // instead of loaded as a constant: §453's product is `v*(n+f/2^16)`
            // and `f` is zero, because an internal integer has no fraction.
            // §453 attaches the sign to the factor, which is one multiplication
            // more and only when there was a minus.
            Num::ByCount { factor, sign, unit } => {
                self.num(unit)?;
                self.b.emit(Op::GetSlot(slot(*factor)), self.line);
                if *sign < 0 {
                    self.b.emit(Op::LoadInt(-1), self.line);
                    self.b.emit(Op::LoadInt(0), self.line);
                    self.b
                        .emit(Op::CallBuiltin(ops::ARITH_CHECKED, 3), self.line);
                }
                self.b.emit(Op::LoadInt(0), self.line);
                self.b.emit(Op::CallBuiltin(ops::SCALE_DIMEN, 3), self.line);
            }
            Num::Rust { name, args } => {
                // The name first, then the arguments: the builtin pops the
                // whole run and the name is what it dispatches on.
                let k = self.str_const(name)?;
                self.b.emit(Op::LoadConst(k), self.line);
                for a in args {
                    self.num(a)?;
                }
                let argc = u8::try_from(args.len() + 1).unwrap_or(u8::MAX);
                self.b.emit(Op::CallBuiltin(ops::FFI_CALL, argc), self.line);
            }
        }
        Ok(())
    }
}

/// A register number as a slot, clamped to the 256 TeX provides.
fn slot(reg: i64) -> u16 {
    u16::try_from(reg).unwrap_or(0).min(TOTAL_SLOTS - 1)
}

/// Every register kind that lives in the slot file, end to end: 256 counts, 256
/// dimensions, then 256 glues and 256 math glues at four slots each.
pub const TOTAL_SLOTS: u16 = 2560;

impl Default for Compiler {
    fn default() -> Self {
        Self::new()
    }
}