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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
//! 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 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, behind the `(\end
    /// occurred ...)` lines its one argument carries.
    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;
    /// Append a report the lowerer made (§82's `print_err` and its context):
    /// one argument, the text. Unlike `MSG_APPEND` it marks a message that
    /// OPENS with it as starting on a fresh line rather than after a space.
    pub const MSG_REPORT: u16 = 4017;
    /// Finish an `\immediate\write` and record it on a line of its own: glued
    /// to what came before, and the next message glued to it. No arguments.
    pub const WRITE_FLUSH: u16 = 4018;
    /// A list action (`crate::ir::list::ListOp`): its opcode, then its
    /// arguments in the order `ListOp::visit` gives them.
    pub const LIST: u16 = 4100;
    /// Append §1296's display of a box register to the message being built:
    /// one argument, the register number.
    pub const LIST_SHOWBOX: u16 = 4101;
    /// Append §218's `show_activities` to the message being built.
    pub const LIST_SHOWLISTS: u16 = 4102;
    /// `\openout`: the stream, then the file name (`crate::write`).
    ///
    /// Numbered from 4200, clear of the numbers after 4018 that other builtins
    /// take (the list actions are 4100 on): a number registered twice silently
    /// keeps the last function (see `COLOR_PUSH`).
    pub const OUT_OPEN: u16 = 4200;
    /// `\write` to an open stream: the stream, after the text is built as a
    /// message's is.
    pub const OUT_WRITE: u16 = 4201;
    /// `\closeout`: the stream.
    pub const OUT_CLOSE: u16 = 4202;
    /// Whether a stream is open: the stream; 1 or 0 back.
    pub const OUT_IS_OPEN: u16 = 4203;
    /// One step of an e-TeX expression (`crate::ir::Num::Expr`): the operands,
    /// then the operation's code and the bound, for `etex_arith::apply`.
    pub const EXPR_STEP: u16 = 4019;
    /// The end of an expression: its value or the error marker, then the
    /// report to make for the marker.
    pub const EXPR_END: u16 = 4020;
    /// Take the message being built as a string, onto the stack: the text
    /// of a `\special` the run builds (`Cmd::Special`). No arguments.
    pub const MSG_TAKE: u16 = 4021;
    /// One component of a glue `\multiply` or `\divide` (`Cmd::GlueArith`):
    /// [`ARITH_CHECKED`]'s three arguments, with an overflow noted rather
    /// than reported.
    pub const ARITH_GLUE: u16 = 4022;
    /// The value a glue component is left with: the new value, then the old;
    /// the old one back if any component overflowed.
    pub const ARITH_KEEP: u16 = 4023;
    /// Report the overflow a glue `\multiply` or `\divide` noted, once. No
    /// arguments.
    pub const ARITH_SETTLE: u16 = 4024;
}

/// 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: rustc_hash::FxHashMap<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: rustc_hash::FxHashMap::default(),
        }
    }

    /// 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 register starts as INITEX leaves it -- zero, but for the few
        // parameters `params::initial_value` names; the slots have to be
        // written before they are read or a read finds `Undef`.
        for reg in 0..TOTAL_SLOTS {
            let initial = crate::params::initial_value(i64::from(reg));
            self.b.emit(Op::LoadInt(initial), 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)
    }

    /// `body` compiled as a chunk of its own, added to this one's sub-chunks;
    /// its index. The run executes it on a VM of its own over the same slot
    /// file (`crate::stomach::run`), so it starts from the registers it is
    /// given rather than from INITEX's zeros.
    fn sub_chunk(&mut self, body: &[Cmd]) -> Result<i64, TexError> {
        let mut sub = Compiler {
            b: ChunkBuilder::new(),
            debug: false,
            line: self.line,
            strings: rustc_hash::FxHashMap::default(),
        };
        sub.b.set_builtin_argc_is_arity(true);
        sub.block(body)?;
        Ok(i64::from(self.b.add_sub_chunk(sub.b.build())))
    }

    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.
                    // A dimension or a glue component is bounded by §421's
                    // `max_dimen`, not by the 32-bit word: §1240 multiplies it
                    // with `nx_plus_y(..., 0)`, whose limit is 2^30-1.
                    Arith::Mul | Arith::Div => {
                        let scaled = (DIMEN_BASE..i64::from(TOTAL_SLOTS)).contains(reg);
                        let which = match op {
                            Arith::Mul if scaled => 2,
                            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);
            }
            // §1240 scales all three components, and only then does §1236
            // test `arith_error`: the products go on the stack, and each is
            // written back -- or the old value is -- once all three are known.
            Cmd::GlueArith(op, base, n) => {
                let which = match op {
                    Arith::Mul => 2,
                    Arith::Div => 1,
                    Arith::Add => {
                        return Err(TexError("a glue \\advance is not a GlueArith".into()))
                    }
                };
                for part in 0..3 {
                    self.b.emit(Op::GetSlot(slot(base + part)), self.line);
                    self.num(n)?;
                    self.b.emit(Op::LoadInt(which), self.line);
                    self.b.emit(Op::CallBuiltin(ops::ARITH_GLUE, 3), self.line);
                }
                for part in (0..3).rev() {
                    self.b.emit(Op::GetSlot(slot(base + part)), self.line);
                    self.b.emit(Op::CallBuiltin(ops::ARITH_KEEP, 2), self.line);
                    self.b.emit(Op::SetSlot(slot(base + part)), self.line);
                }
                self.b
                    .emit(Op::CallBuiltin(ops::ARITH_SETTLE, 0), self.line);
                self.b.emit(Op::Pop, self.line);
            }
            Cmd::List(op) => self.list_op(op)?,
            // The routine runs on a VM of its own over the same slot file
            // (`crate::stomach::run`), so it is a sub-chunk that starts from
            // the registers it is given rather than from INITEX's zeros.
            Cmd::OutputRoutine(body) => {
                let k = match body {
                    Some(body) => self.sub_chunk(body)?,
                    None => -1,
                };
                self.list_op(&crate::ir::list::ListOp::OutputRoutine(k))?;
            }
            // §1374 for the whatsit is run on a VM of its own when the page
            // holding it ships (`crate::stomach::run::out_what`), as the
            // output routine is.
            Cmd::OutWhatsit { display, body } => {
                let chunk = self.sub_chunk(body)?;
                self.list_op(&crate::ir::list::ListOp::OutWhatsit {
                    display: display.clone(),
                    chunk,
                })?;
            }
            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 { notes, glued } => {
                let k = self.str_const(&notes.concat())?;
                self.b.emit(Op::LoadConst(k), self.line);
                self.b.emit(Op::LoadInt(i64::from(*glued)), self.line);
                self.b
                    .emit(Op::CallBuiltin(ops::TRANSCRIPT_NOTICE, 2), 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);
            }
            // No flush: what is built so far waits for the next message.
            Cmd::Reports(msg) => self.msg_ops(msg)?,
            Cmd::Write(msg) => {
                self.msg_ops(msg)?;
                self.b.emit(Op::CallBuiltin(ops::WRITE_FLUSH, 0), self.line);
                self.b.emit(Op::Pop, self.line);
            }
            Cmd::OpenOut { stream, name } => {
                self.b.emit(Op::LoadInt(*stream as i64), self.line);
                let k = self.str_const(name)?;
                self.b.emit(Op::LoadConst(k), self.line);
                self.b.emit(Op::CallBuiltin(ops::OUT_OPEN, 2), self.line);
                self.b.emit(Op::Pop, self.line);
            }
            Cmd::WriteOut {
                stream,
                file,
                otherwise,
            } => {
                // Which of the two is decided by the run: see `Cmd::WriteOut`.
                self.b.emit(Op::LoadInt(*stream as i64), self.line);
                self.b.emit(Op::CallBuiltin(ops::OUT_IS_OPEN, 1), self.line);
                let to_else = self.b.emit(Op::JumpIfFalse(0), self.line);
                self.msg_ops(file)?;
                self.b.emit(Op::LoadInt(*stream as i64), self.line);
                self.b.emit(Op::CallBuiltin(ops::OUT_WRITE, 1), self.line);
                self.b.emit(Op::Pop, self.line);
                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(otherwise)?;
                let end = self.b.current_pos();
                self.b.patch_jump(over_else, end);
            }
            // The opcode, the text built and taken as the one argument, and the
            // list action `ops::LIST` then decodes as `ListOp::Whatsit`.
            Cmd::Special(parts) => {
                let code = crate::ir::list::ListOp::<Num>::Whatsit(String::new()).code();
                self.b.emit(Op::LoadInt(code), self.line);
                self.msg_ops(parts)?;
                self.b.emit(Op::CallBuiltin(ops::MSG_TAKE, 0), self.line);
                self.b.emit(Op::CallBuiltin(ops::LIST, 2), self.line);
                self.b.emit(Op::Pop, self.line);
            }
            Cmd::CloseOut(stream) => {
                self.b.emit(Op::LoadInt(*stream as i64), self.line);
                self.b.emit(Op::CallBuiltin(ops::OUT_CLOSE, 1), self.line);
                self.b.emit(Op::Pop, self.line);
            }
            Cmd::Group { saves, keeps, 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);
                }
                // A kept register's scratch slot starts at the entry value,
                // which is what the `}` restores if no `\global` runs.
                for (reg, scratch) in keeps {
                    self.b.emit(Op::GetSlot(slot(*reg)), self.line);
                    self.b.emit(Op::SetSlot(*scratch), self.line);
                }
                self.block(body)?;
                for (reg, scratch) in keeps {
                    self.b.emit(Op::GetSlot(*scratch), self.line);
                    self.b.emit(Op::SetSlot(slot(*reg)), self.line);
                }
                for reg in saves.iter().rev() {
                    self.b.emit(Op::SetSlot(slot(*reg)), self.line);
                }
            }
            Cmd::KeepGlobal { reg, into } => {
                for scratch in into {
                    self.b.emit(Op::GetSlot(slot(*reg)), self.line);
                    self.b.emit(Op::SetSlot(*scratch), 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(())
    }

    /// A list action: the opcode and its arguments, then the call.
    fn list_op(&mut self, op: &crate::ir::list::ListOp) -> Result<(), TexError> {
        use crate::ir::list::Arg;
        self.b.emit(Op::LoadInt(op.code()), self.line);
        let mut args: Vec<Arg<'_, Num>> = Vec::new();
        op.visit(&mut |a| args.push(a));
        let argc = u8::try_from(args.len() + 1)
            .map_err(|_| TexError(format!("a list action with {} arguments", args.len())))?;
        for a in args {
            match a {
                Arg::Num(n) => self.num(n)?,
                Arg::Int(v) => {
                    self.b.emit(Op::LoadInt(v), self.line);
                }
                Arg::Str(s) => {
                    let k = self.str_const(s)?;
                    self.b.emit(Op::LoadConst(k), self.line);
                }
            }
        }
        self.b.emit(Op::CallBuiltin(ops::LIST, argc), self.line);
        self.b.emit(Op::Pop, self.line);
        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::Report(t) => {
                    let k = self.str_const(t)?;
                    self.b.emit(Op::LoadConst(k), self.line);
                    self.b.emit(Op::CallBuiltin(ops::MSG_REPORT, 1), self.line);
                    self.b.emit(Op::Pop, self.line);
                }
                MsgOp::ShowBox(n) => {
                    self.b.emit(Op::LoadInt(i64::from(*n)), self.line);
                    self.b
                        .emit(Op::CallBuiltin(ops::LIST_SHOWBOX, 1), self.line);
                    self.b.emit(Op::Pop, self.line);
                }
                MsgOp::ShowLists => {
                    self.b
                        .emit(Op::CallBuiltin(ops::LIST_SHOWLISTS, 0), 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);
            }
            Num::Neg(reg) => {
                self.b.emit(Op::LoadInt(0), self.line);
                self.b.emit(Op::GetSlot(slot(*reg)), self.line);
                self.b.emit(Op::Sub, 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);
            }
            // The operands, then what to do with them: the builtin pops the two
            // trailing constants first and the operands after.
            Num::Expr { op, max, args } => {
                for a in args {
                    self.num(a)?;
                }
                self.b.emit(Op::LoadInt(op.code()), self.line);
                self.b.emit(Op::LoadInt(*max), self.line);
                let argc = u8::try_from(args.len() + 2).unwrap_or(u8::MAX);
                self.b
                    .emit(Op::CallBuiltin(ops::EXPR_STEP, argc), self.line);
            }
            Num::ExprEnd { value, report } => {
                self.num(value)?;
                let k = self.str_const(report)?;
                self.b.emit(Op::LoadConst(k), self.line);
                self.b.emit(Op::CallBuiltin(ops::EXPR_END, 2), 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 slot file.
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, 256 glues and 256 math glues at four slots each, then the
/// dimension, glue and math glue PARAMETERS (`crate::params`), then what the
/// stomach mirrors for the program to read (`crate::stomach::Mirror`), then
/// LuaTeX's parameters, then the pools registers past 255 are given slots
/// from.
pub const TOTAL_SLOTS: u16 = HIGH_END as u16;

/// Where §247's dimension parameters start: one slot each, past every register.
pub const DIMPAR_BASE: i64 = MUSKIP_BASE + 256 * SKIP_STRIDE;
/// Where §224's ordinary glue parameters start, four slots each like a `\skip`.
pub const GLUEPAR_BASE: i64 = DIMPAR_BASE + crate::params::DIMEN_NAMES.len() as i64;
/// Where §224's three math glue parameters start, four slots each like a
/// `\muskip`.
pub const MUGLUEPAR_BASE: i64 = GLUEPAR_BASE + crate::params::ORDINARY_GLUE as i64 * SKIP_STRIDE;
/// One past the last parameter slot.
const MUGLUEPAR_END: i64 = MUGLUEPAR_BASE
    + (crate::params::GLUE_NAMES.len() - crate::params::ORDINARY_GLUE) as i64 * SKIP_STRIDE;
/// Where LuaTeX's glue parameters start, four slots each.
pub const LUAGLUEPAR_BASE: i64 = LUADIMPAR_BASE + crate::params::LUATEX_DIMEN_NAMES.len() as i64;
/// One past the last of them.
const LUAGLUEPAR_END: i64 =
    LUAGLUEPAR_BASE + crate::params::LUATEX_GLUE_NAMES.len() as i64 * SKIP_STRIDE;

/// Where `\wd n`, `\ht n` and `\dp n` of the 256 box registers are
/// mirrored, three slots per register (`crate::stomach::box_dimen_slot`).
/// They are slots so that every place a dimension is read -- `\ifdim`, `\the`,
/// a factor like `.5\wd0` -- reads a box dimension the way it reads `\dimen`.
pub const BOXDIM_BASE: i64 = MUGLUEPAR_END;
/// Where what each box register holds is mirrored (`crate::stomach::KIND_VOID`
/// and its siblings), which `\ifvoid`, `\ifhbox` and `\ifvbox` test.
pub const BOXKIND_BASE: i64 = BOXDIM_BASE + 3 * 256;
/// Where §413's internal quantities the stomach computes are mirrored
/// (`crate::stomach::Internal`).
pub const INTERNAL_BASE: i64 = BOXKIND_BASE + 256;
/// One past the last stomach slot.
const STOMACH_END: i64 = INTERNAL_BASE + crate::stomach::INTERNAL_SLOTS;
/// Where LuaTeX's dimension parameters start (`crate::params::LUATEX_DIMEN_NAMES`),
/// past every slot that was there before them, so adding them moved none.
pub const LUADIMPAR_BASE: i64 = STOMACH_END;

/// The four register files that live in slots.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum RegFile {
    Count,
    Dimen,
    Skip,
    MuSkip,
}

impl RegFile {
    /// The file a register primitive names: `\count`, `\dimen`, `\skip`,
    /// `\muskip`.
    pub fn of_name(name: &str) -> Option<RegFile> {
        match name {
            "count" => Some(RegFile::Count),
            "dimen" => Some(RegFile::Dimen),
            "skip" => Some(RegFile::Skip),
            "muskip" => Some(RegFile::MuSkip),
            _ => None,
        }
    }

    /// The primitive's name, for a register's display (`\count300`).
    pub fn name(self) -> &'static str {
        match self {
            RegFile::Count => "count",
            RegFile::Dimen => "dimen",
            RegFile::Skip => "skip",
            RegFile::MuSkip => "muskip",
        }
    }

    /// How many slots one register of the file takes.
    pub fn stride(self) -> i64 {
        match self {
            RegFile::Count | RegFile::Dimen => 1,
            RegFile::Skip | RegFile::MuSkip => SKIP_STRIDE,
        }
    }

    /// Where registers 0 to 255 of the file start.
    pub fn low_base(self) -> i64 {
        match self {
            RegFile::Count => 0,
            RegFile::Dimen => DIMEN_BASE,
            RegFile::Skip => SKIP_BASE,
            RegFile::MuSkip => MUSKIP_BASE,
        }
    }

    /// The pool the file's registers past 255 are given slots from, and how
    /// many registers it holds (`crate::expand::Engine::register_address`).
    pub fn high_pool(self) -> (i64, i64) {
        match self {
            RegFile::Count => (HIGH_COUNT_BASE, HIGH_COUNTS),
            RegFile::Dimen => (HIGH_DIMEN_BASE, HIGH_DIMENS),
            RegFile::Skip => (HIGH_SKIP_BASE, HIGH_SKIPS),
            RegFile::MuSkip => (HIGH_MUSKIP_BASE, HIGH_MUSKIPS),
        }
    }
}

/// LuaTeX has 65536 registers of each kind (the LuaTeX manual, "Registers":
/// "The number of registers is 65536"); TeX82 has 256. A slot file of 65536
/// of each is more than fusevm's 16-bit slot index can address, and no
/// document uses more than a few hundred past the first 256 -- a lualatex run
/// with amsmath, hyperref, tikz, fontspec and unicode-math ends with `\count10`
/// at 347 and `\count11` at 275, measured. So a register past 255 is given a
/// slot from a pool the first time it is named, and the pools are sized well
/// past that.
pub const HIGH_COUNT_BASE: i64 = LUAGLUEPAR_END;
pub const HIGH_COUNTS: i64 = 2048;
pub const HIGH_DIMEN_BASE: i64 = HIGH_COUNT_BASE + HIGH_COUNTS;
pub const HIGH_DIMENS: i64 = 1024;
pub const HIGH_SKIP_BASE: i64 = HIGH_DIMEN_BASE + HIGH_DIMENS;
pub const HIGH_SKIPS: i64 = 512;
pub const HIGH_MUSKIP_BASE: i64 = HIGH_SKIP_BASE + HIGH_SKIPS * SKIP_STRIDE;
pub const HIGH_MUSKIPS: i64 = 128;
/// One past the last pooled slot.
const HIGH_END: i64 = HIGH_MUSKIP_BASE + HIGH_MUSKIPS * SKIP_STRIDE;

/// Whether `slot` is an integer register: one of `\count0`-`\count255`, or a
/// pooled count register past them.
pub fn is_count_slot(slot: i64) -> bool {
    (0..DIMEN_BASE).contains(&slot) || (HIGH_COUNT_BASE..HIGH_DIMEN_BASE).contains(&slot)
}

/// Whether `slot` is one the stomach writes: a box dimension or kind, or an
/// internal quantity. Such a slot is not an `eqtb` entry, so a group does not
/// save or restore it (§1247 changes a box in place; `\prevdepth` belongs to
/// the list, not to the group).
pub fn is_stomach_slot(slot: i64) -> bool {
    (BOXDIM_BASE..STOMACH_END).contains(&slot)
}

/// Whether `slot` holds (a component of) a glue: a `\skip` or `\muskip`
/// register, or a glue parameter of either kind.
pub fn is_glue_slot(slot: i64) -> bool {
    (SKIP_BASE..DIMPAR_BASE).contains(&slot)
        || (GLUEPAR_BASE..MUGLUEPAR_END).contains(&slot)
        || (LUAGLUEPAR_BASE..LUAGLUEPAR_END).contains(&slot)
        || (HIGH_SKIP_BASE..HIGH_END).contains(&slot)
}

/// Whether `slot` holds (a component of) a MATH glue: a `\muskip` register or
/// one of the three math glue parameters.
pub fn is_mu_slot(slot: i64) -> bool {
    (MUSKIP_BASE..DIMPAR_BASE).contains(&slot)
        || (MUGLUEPAR_BASE..MUGLUEPAR_END).contains(&slot)
        || (HIGH_MUSKIP_BASE..HIGH_END).contains(&slot)
}

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