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
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
//! TeX's mouth: bytes to tokens.
//!
//! The mouth is a three-state machine per line (`tex.web` §303): `N` at the
//! start of a line, `M` in the middle, `S` while skipping blanks. The states are
//! not decoration — they are what makes a blank line a `\par`, what collapses a
//! run of spaces to one, and what makes a space after a control word vanish.
//! Getting them wrong changes what documents mean, so they are modelled
//! directly rather than approximated with trimming.

use crate::catcode::{Cat, CatTable};
use crate::token::{CsId, Token};
use std::rc::Rc;

#[derive(Clone, Copy, PartialEq)]
enum State {
    NewLine,
    MidLine,
    SkipBlanks,
}

/// Tokens read ahead of the expander, and the table revision they assume.
struct Ahead {
    /// Generation of the catcode table these were lexed under.
    generation: u32,
    /// Tokens with the character index each ended at, in source order.
    toks: Vec<crate::parallel::Placed>,
    /// How many have been handed out.
    at: usize,
}

/// The tokens a mouth holds to read before the file, in reverse reading order.
///
/// A `Vec` with one addition: it remembers the shallowest it has ever been.
/// A lexer holding a `\message` body keeps the body's tokens at the bottom and
/// pushes expansions above them, so that mark is how many of the body's own
/// tokens have been read -- which is where the file line an error shows is.
#[derive(Default)]
pub struct Pending {
    v: Vec<Token>,
    low: usize,
}

impl Pending {
    /// Take the next token to read, noting how deep the stack has gone.
    pub fn pop(&mut self) -> Option<Token> {
        let t = self.v.pop();
        self.low = self.low.min(self.v.len());
        t
    }
}

impl std::ops::Deref for Pending {
    type Target = Vec<Token>;
    fn deref(&self) -> &Vec<Token> {
        &self.v
    }
}

impl std::ops::DerefMut for Pending {
    fn deref_mut(&mut self) -> &mut Vec<Token> {
        &mut self.v
    }
}

/// What made a level of tex's input stack that `pending` holds.
#[derive(Clone)]
pub enum LevelKind {
    /// §325's `back_input`: `<to be read again>`, or `<recently read>` once
    /// it has been read to its end.
    BackedUp,
    /// §327's `ins_error`: `<inserted text>`.
    Inserted,
    /// A macro call (§389): the control sequence, and how many tokens each
    /// argument contributed to the substituted body, in parameter order.
    Macro { name: CsId, args: Vec<u32> },
    /// The file text a `\message` body was read from; see [`Site`].
    Site(Rc<Site>),
}

/// One level of the input stack held in `pending`.
struct Level {
    /// The depth of `pending` below the level's first token.
    base: usize,
    /// The level's tokens, in reading order.
    toks: Rc<Vec<Token>>,
    kind: LevelKind,
}

/// A level as [`Lexer::levels`] reports it.
pub struct LevelView<'a> {
    pub toks: &'a Rc<Vec<Token>>,
    /// How many of `toks` have been read.
    pub read: usize,
    pub kind: &'a LevelKind,
}

/// Where a `\message` body came from.
///
/// tex expands a message's text while it reads it from the file, so an error
/// met there is displayed with the file line the scanner had reached. This
/// engine reads the whole body first and expands it afterwards, so the
/// positions are recorded as the body is read and the display is built from
/// them: `ends[k]` is the file position after the body's k-th token.
pub struct Site {
    /// The characters of the lines the body spans, and where they start.
    text: Vec<char>,
    offset: usize,
    /// The 1-based line number of `text`'s first line.
    first_line: usize,
    /// File positions a `^^` notation was spliced in at.
    spliced: Vec<usize>,
    /// The file position after the first k tokens of the body.
    ends: Vec<usize>,
    /// How deep the reading lexer's `pending` was after the first k tokens:
    /// a body read out of a macro's expansion shows that macro's level.
    parent_lens: Vec<usize>,
    /// The reading lexer's own levels when the body was read.
    parent: Vec<(usize, Rc<Vec<Token>>, LevelKind)>,
}

impl Site {
    /// How many tokens the body had.
    pub fn body_len(&self) -> usize {
        self.ends.len().saturating_sub(1)
    }

    /// §311's two lines for the position after `k` tokens of the body.
    pub fn context(&self, k: usize) -> String {
        let k = k.min(self.ends.len().saturating_sub(1));
        let pos = self.ends.get(k).copied().unwrap_or(self.offset);
        let rel = pos.saturating_sub(self.offset).min(self.text.len());
        context_display(&self.text, self.first_line, rel, &self.spliced, self.offset)
    }

    /// The levels of the lexer the body was read from, as they stood when the
    /// first `k` tokens had been read: innermost first, with how many tokens of
    /// each had been read.
    pub fn parent_levels(&self, k: usize) -> Vec<(Rc<Vec<Token>>, usize, LevelKind)> {
        let k = k.min(self.parent_lens.len().saturating_sub(1));
        let depth = self.parent_lens.get(k).copied().unwrap_or(0);
        let mut out = Vec::new();
        let mut upper = depth;
        for (base, toks, kind) in self.parent.iter().rev() {
            let n = toks.len();
            let unread = upper.saturating_sub(*base).min(n);
            if unread > 0 || (out.is_empty() && *base >= upper && *base <= depth) {
                out.push((toks.clone(), n - unread, kind.clone()));
                upper = *base;
            }
        }
        out
    }
}

/// §317's pair of lines for the position `pos` in `chars`, whose first line is
/// numbered `first_line`: `l.N` and the text read, then the text not yet read.
fn context_display(
    chars: &[char],
    first_line: usize,
    pos: usize,
    spliced: &[usize],
    offset: usize,
) -> String {
    let pos = pos.min(chars.len());
    // tex reads a LINE at a time into `buffer` (§303) and `loc` may sit one
    // past its end, with `line` still naming the line that ended. Taking
    // the line of the last character CONSUMED rather than of the next one
    // to read is what reproduces that: `\chardef\x=256` reports on its own
    // line even though scanning the constant ate the line's end.
    let last = pos.saturating_sub(1);
    let line = first_line + chars[..last].iter().filter(|c| **c == '\n').count();
    let start = chars[..last]
        .iter()
        .rposition(|c| *c == '\n')
        .map_or(0, |i| i + 1);
    // §318 stops at `end_line_char`: a line's own terminator is not part of
    // what is shown.
    let end = chars[start..]
        .iter()
        .position(|c| *c == '\n')
        .map_or(chars.len(), |i| start + i);
    let split = pos.min(end);
    let shown = |from: usize, to: usize| -> String {
        (from..to)
            .filter(|i| spliced.binary_search(&(i + offset)).is_err())
            .map(|i| chars[i])
            .collect()
    };
    let before = shown(start, split);
    let after = shown(split, end);
    Lexer::context_lines(&format!("l.{line} "), &before, &after)
}

pub struct Lexer {
    chars: Vec<char>,
    pos: usize,
    /// The last answer [`Lexer::line`] gave, as `(position, line)`.
    ///
    /// Counting newlines from the start of the file on every call is O(n) per
    /// token and so O(n²) per document — which the scaling benchmark caught:
    /// quadrupling the input cost 27x. Counting only what has been consumed
    /// SINCE the last answer makes the whole walk amortized O(n), and a rewind
    /// (the scanner pushes tokens back) simply recounts from the start.
    line_cache: std::cell::Cell<(usize, u32)>,
    /// Tokens lexed ahead of the expander, with the generation of the catcode
    /// table they were produced under.
    ///
    /// The mouth is the largest single cost of compiling a document and it is
    /// the one stage that parallelises: its states are per-line, so line-
    /// aligned slices lex independently. Reading ahead is a GUESS that the
    /// table will not move, and `\catcode` is allowed to move it at any point,
    /// so the guess carries the generation it was made under and is dropped the
    /// moment that stops matching. Dropping it costs only the work already
    /// done, never correctness.
    ahead: Option<Ahead>,
    /// Set once read-ahead has been abandoned often enough that it is not
    /// paying: a document rewriting catcodes throughout would otherwise re-lex
    /// its tail on every change.
    ahead_disabled: bool,
    /// How many times a stale read-ahead has been thrown away.
    ahead_misses: u32,
    /// The name of the control word being read, kept between words so that
    /// reading one does not allocate: the name is interned and the buffer
    /// given back. See [`Lexer::control_sequence`].
    word: String,
    /// Tokens to scan normally before speculating again.
    ///
    /// A document opens by setting catcodes -- `\catcode`\{=1` and friends --
    /// and each one invalidates whatever was read ahead. Speculating from the
    /// first token therefore lexes the whole file once per catcode in the
    /// preamble and throws all of it away. Waiting until the table has been
    /// still for a while costs a few hundred tokens of ordinary scanning and
    /// saves re-lexing the document.
    ahead_cooldown: usize,
    state: State,
    /// The `\endlinechar` this line was read with, fixed when its first
    /// character is looked at: `tex.web` §362 appends it as the line is read,
    /// so an assignment ON a line changes the NEXT line's end, never its own.
    /// `None` between a line end and the next line's first read.
    line_end: Option<Option<char>>,
    /// Where a character `^^` notation produced was spliced into `chars`: a
    /// `^^M` written that way is the character 13, not a line end.
    decoded_at: Option<usize>,
    /// Every position a character `^^` notation produced was spliced in at,
    /// in order. It is behind the notation that wrote it, which stays where it
    /// was: §352 decodes the character without touching the line, so the line
    /// an error shows has the notation and not the character.
    spliced: Vec<usize>,
    /// Pushed-back tokens (`\expandafter` and macro expansion feed these).
    pub pending: Pending,
    /// The error context at each invalid character the mouth skipped, for the
    /// expander to report: the mouth has no error channel of its own. See
    /// [`Lexer::take_invalid`].
    invalid: std::cell::RefCell<Vec<String>>,
    /// The levels of tex's input stack that sit in `pending`, innermost last:
    /// what §325's `back_input` made and what a macro call made, each with
    /// the depth of `pending` it sits on. See [`Lexer::levels`].
    levels: Vec<Level>,
    /// The files a pseudo file (etex.ch's `pseudo_start`, for `\scantokens`)
    /// is being read on top of, innermost last: what the mouth goes back to
    /// when it has read the pseudo file to its end.
    suspended: Vec<Suspended>,
    /// What the source being read inserts at its end before it closes: e-TeX's
    /// `\everyeof` for a pseudo file, `None` once inserted and for a file that
    /// is not one.
    eof_tokens: Option<Vec<Token>>,
    /// Whether the characters are a FILE's, whose lines LuaTeX's
    /// `process_input_buffer` callback sees before they are read
    /// (`crate::input_hooks`); a token list or a pseudo file is not one.
    file_lines: bool,
    /// A FILE's `\everyeof` (etex.ch §362): the engine's current value, read
    /// when the characters run out rather than when the file opened -- a
    /// file may set it itself, as etex.src's `\patterns` does to skip to its
    /// own end -- and inserted once.
    file_eof: Option<std::rc::Rc<std::cell::RefCell<Vec<Token>>>>,
}

/// A source a pseudo file suspended, as it stood: everything that says where
/// in its characters the mouth was, and the token lists that were in front of
/// it -- those are read after the pseudo file, which is above them on tex's
/// input stack.
struct Suspended {
    chars: Vec<char>,
    pos: usize,
    line_cache: (usize, u32),
    state: State,
    line_end: Option<Option<char>>,
    decoded_at: Option<usize>,
    spliced: Vec<usize>,
    pending: Pending,
    levels: Vec<Level>,
    eof_tokens: Option<Vec<Token>>,
}

impl Lexer {
    /// Say that these characters are a file's: each line goes through LuaTeX's
    /// `process_input_buffer` callback, when there is one, as it is reached.
    pub fn mark_as_file(&mut self) {
        self.file_lines = true;
    }

    /// Insert the current `\everyeof` -- `every` is the engine's, read when the
    /// file ends -- before the file closes (etex.ch §362).
    pub fn insert_everyeof(&mut self, every: std::rc::Rc<std::cell::RefCell<Vec<Token>>>) {
        self.file_eof = Some(every);
    }

    /// `process_input_buffer` on the line that starts at `pos`, its end left
    /// off as luatex hands it over; what the callback returns takes its place.
    fn process_line(&mut self) {
        let end = (self.pos..self.chars.len())
            .find(|&i| self.terminator_at(i).is_some())
            .unwrap_or(self.chars.len());
        let line: String = self.chars[self.pos..end].iter().collect();
        if let Some(new) = crate::input_hooks::process_input_buffer(&line) {
            self.chars.splice(self.pos..end, new.chars());
        }
    }

    /// etex.ch's `pseudo_start`: read `text` as a file in front of everything
    /// else, its lines ended as a file's are (`\endlinechar` appended, trailing
    /// spaces gone), tokenised as it is read so a `\catcode` in it changes what
    /// follows. At its end `eof` is inserted (`\everyeof`) and the mouth goes
    /// back to what it was reading.
    pub fn begin_pseudo_file(&mut self, text: &str, eof: Vec<Token>) {
        self.ahead = None;
        let parent = Suspended {
            chars: std::mem::replace(&mut self.chars, text.chars().collect()),
            pos: std::mem::replace(&mut self.pos, 0),
            line_cache: self.line_cache.replace((0, 1)),
            state: std::mem::replace(&mut self.state, State::NewLine),
            line_end: self.line_end.take(),
            decoded_at: self.decoded_at.take(),
            spliced: std::mem::take(&mut self.spliced),
            pending: std::mem::take(&mut self.pending),
            levels: std::mem::take(&mut self.levels),
            eof_tokens: self.eof_tokens.replace(eof),
        };
        self.suspended.push(parent);
    }

    /// At the end of the characters: a pseudo file's `\everyeof` first, then
    /// the source it suspended. Whether there is anything more to read.
    fn end_pseudo_file(&mut self) -> bool {
        if let Some(eof) = self.eof_tokens.take() {
            if !eof.is_empty() {
                self.insert_input(&eof);
                return true;
            }
        }
        let Some(parent) = self.suspended.pop() else {
            // The file itself has ended: its `\everyeof`, once.
            if let Some(every) = self.file_eof.take() {
                let tokens = every.borrow().clone();
                if !tokens.is_empty() {
                    self.insert_input(&tokens);
                    return true;
                }
            }
            return false;
        };
        self.ahead = None;
        self.chars = parent.chars;
        self.pos = parent.pos;
        self.line_cache.set(parent.line_cache);
        self.state = parent.state;
        self.line_end = parent.line_end;
        self.decoded_at = parent.decoded_at;
        self.spliced = parent.spliced;
        self.pending = parent.pending;
        self.levels = parent.levels;
        self.eof_tokens = parent.eof_tokens;
        true
    }

    /// A mouth over an already-decoded slice of characters.
    ///
    /// The parallel pre-lexer hands each worker one line-aligned slice of the
    /// document's characters; decoding UTF-8 once for the whole file and
    /// slicing it is what keeps the split from paying for the decode N times.
    ///
    /// Read-ahead is OFF here, and that is load-bearing rather than an
    /// optimisation: this constructor is what the workers themselves run, so a
    /// worker that read ahead would fan out again, and again, each level
    /// re-chunking at different offsets. That nesting is what made the split
    /// slower than the scan it replaced AND made it disagree with the mouth --
    /// a worker's own sub-chunks split at boundaries the outer level never
    /// accounted for, so state that should have been `S` began as `N` and
    /// invented a `\par`.
    pub fn from_chars(chars: Vec<char>) -> Self {
        Self {
            chars,
            pos: 0,
            state: State::NewLine,
            pending: Pending::default(),
            line_cache: std::cell::Cell::new((0, 1)),
            ahead: None,
            ahead_disabled: true,
            ahead_misses: 0,
            word: String::new(),
            ahead_cooldown: Self::AHEAD_COOLDOWN,
            line_end: None,
            decoded_at: None,
            spliced: Vec::new(),
            invalid: std::cell::RefCell::new(Vec::new()),
            levels: Vec::new(),
            suspended: Vec::new(),
            eof_tokens: None,
            file_lines: false,
            file_eof: None,
        }
    }

    /// Read raw characters up to `marker`, consuming it, with no tokenising.
    ///
    /// A verbatim environment suspends the category codes: inside
    /// `\begin{verbatim}` a backslash is a backslash and a brace is a brace,
    /// because the point of the environment is to show TeX rather than run it.
    /// `tex.web` has no such thing -- LaTeX builds it by setting every catcode
    /// to 12 and reading a line at a time -- but the effect is a raw scan to the
    /// closing marker, which is what this is.
    ///
    /// Returns the text between here and the marker, or `None` when the marker
    /// never comes, in which case nothing is consumed and the caller can report
    /// a runaway environment rather than silently eating the rest of the file.
    pub fn read_raw_until(&mut self, marker: &str) -> Option<String> {
        let want: Vec<char> = marker.chars().collect();
        let mut i = self.pos;
        while i + want.len() <= self.chars.len() {
            // The first character alone rules out nearly every position, and is
            // one compare where the slice is a call.
            let opens = want.first().is_none_or(|w| self.chars[i] == *w);
            if opens && self.chars[i..i + want.len()] == want[..] {
                let text: String = self.chars[self.pos..i].iter().collect();
                self.pos = i + want.len();
                self.state = State::MidLine;
                return Some(text);
            }
            i += 1;
        }
        None
    }

    /// `\endinput` (`tex.web` §362's `force_eof`): the file ends with the line
    /// being read, so the rest of THAT line is still read and nothing after it
    /// is. Between two lines -- the last one's end consumed, the next one not
    /// started -- the line being read is the one already finished.
    pub fn end_file_after_line(&mut self) {
        self.ahead = None;
        let end = match self.line_end.is_none() && self.pos > 0 {
            true => self.pos,
            false => (self.pos..self.chars.len())
                .find_map(|i| self.terminator_at(i).map(|len| i + len))
                .unwrap_or(self.chars.len()),
        };
        self.chars.truncate(end);
    }

    /// How far the mouth has read, as an index into the characters.
    ///
    /// The pre-lexer records this after each token so a cached stream can be
    /// abandoned mid-way and scanning resumed at exactly the right character.
    pub fn pos(&self) -> usize {
        self.pos
    }

    /// The document's characters, for a caller that wants to slice them.
    pub fn chars(&self) -> &[char] {
        &self.chars
    }

    pub fn new(src: &str) -> Self {
        Self {
            chars: src.chars().collect(),
            pos: 0,
            line_cache: std::cell::Cell::new((0, 1)),
            state: State::NewLine,
            pending: Pending::default(),
            ahead: None,
            ahead_disabled: false,
            ahead_misses: 0,
            word: String::new(),
            ahead_cooldown: Self::AHEAD_COOLDOWN,
            line_end: None,
            decoded_at: None,
            spliced: Vec::new(),
            invalid: std::cell::RefCell::new(Vec::new()),
            levels: Vec::new(),
            suspended: Vec::new(),
            eof_tokens: None,
            file_lines: false,
            file_eof: None,
        }
    }

    /// The contexts of the invalid characters skipped since the last call,
    /// each the two-line display §346's `error` shows.
    pub fn take_invalid(&self) -> Vec<String> {
        self.invalid.take()
    }

    /// Whether any invalid character is waiting to be reported.
    #[inline]
    pub fn has_invalid(&self) -> bool {
        !self.invalid.borrow().is_empty()
    }

    /// Put a token stream back in front of the input, to be read next.
    ///
    /// Stored reversed so `next` can pop from the end — expansion pushes whole
    /// macro bodies here and they must come back out in order.
    pub fn push_back(&mut self, toks: &[Token]) {
        for t in toks.iter().rev() {
            self.pending.push(*t);
        }
    }

    /// Drop the levels whose tokens are all read and nothing sits above:
    /// §325 and §390 end a finished token list before they begin another.
    #[inline]
    fn drop_finished(&mut self) {
        let depth = self.pending.len();
        while self
            .levels
            .last()
            .is_some_and(|l| l.base >= depth && !matches!(l.kind, LevelKind::Site(_)))
        {
            self.levels.pop();
        }
    }

    /// §325's `back_input` (and §323's `back_list` for several): put tokens a
    /// scanner read too far back to be read again, as a level of their own
    /// that an error's context shows as `<to be read again>`. A token put
    /// back by [`Lexer::push_back`] -- a peek -- is not one.
    pub fn back_input(&mut self, toks: &[Token]) {
        self.begin_level(toks, LevelKind::BackedUp);
    }

    /// §327's `ins_error`: tokens tex INSERTS as a level of their own, which
    /// an error's context shows as `<inserted text>` where [`Lexer::back_input`]
    /// shows `<to be read again>`.
    pub fn insert_input(&mut self, toks: &[Token]) {
        self.begin_level(toks, LevelKind::Inserted);
    }

    /// §389's `macro_call` ending: the macro's substituted body goes in front
    /// of the input as a level that remembers which macro made it and how long
    /// each argument was, so §314's `\a #1->body` display can be rebuilt from
    /// the definition and the position.
    ///
    /// An empty body makes no level: tex pops an exhausted list before it
    /// reads on, so no error can see it.
    pub fn push_macro(&mut self, name: CsId, args: Vec<u32>, body: Vec<Token>) {
        if body.is_empty() {
            return;
        }
        self.drop_finished();
        let base = self.pending.len();
        self.push_back(&body);
        self.levels.push(Level {
            base,
            toks: Rc::new(body),
            kind: LevelKind::Macro { name, args },
        });
    }

    /// How many input levels this lexer holds: the nearest thing it has to
    /// §321's `input_ptr`, which tex bounds at `stack_size`. A level read to
    /// its end is dropped when the next one begins (§325, §390), so a tail call
    /// keeps this flat and a call that leaves tokens behind grows it by one.
    pub fn input_levels(&self) -> usize {
        self.levels.len()
    }

    fn begin_level(&mut self, toks: &[Token], kind: LevelKind) {
        // A level something has read below is gone, whatever came after it.
        self.drop_finished();
        let base = self.pending.len();
        self.push_back(toks);
        self.levels.push(Level {
            base,
            toks: Rc::new(toks.to_vec()),
            kind,
        });
    }

    /// The input-stack levels §311's `show_context` shows, innermost first:
    /// each one's tokens and how many of them have been read.
    ///
    /// A level is judged by where it sits in `pending` and by the tokens
    /// there still being the ones it holds, so a peek that takes a token and
    /// returns it leaves the level as it was, and a level something else was
    /// pushed over unread, or read to its end under another, is not shown.
    /// §314's `<recently read>` is the innermost level read to its end.
    pub fn levels(&self) -> Vec<LevelView<'_>> {
        let depth = self.pending.len();
        let mut out: Vec<LevelView<'_>> = Vec::new();
        // The top of the region of `pending` the level being judged can hold:
        // the base of the nearest level shown above it.
        let mut upper = depth;
        for level in self.levels.iter().rev() {
            if matches!(level.kind, LevelKind::Site(_)) {
                out.push(LevelView {
                    toks: &level.toks,
                    read: 0,
                    kind: &level.kind,
                });
                continue;
            }
            let n = level.toks.len();
            let cap = upper.saturating_sub(level.base).min(n);
            // The unread tokens sit at `base..`, the list's last lowest.
            let unread = (0..cap)
                .take_while(|i| self.pending[level.base + i] == level.toks[n - 1 - i])
                .count();
            // Nothing is shown above it and it is read to its end, with
            // nothing below it read yet: the one case a level with no tokens
            // left is still on tex's stack. A token read from beneath means
            // §357's get_next ended it first.
            let innermost = out.is_empty() && unread == 0 && level.base == upper;
            if unread > 0 || innermost {
                out.push(LevelView {
                    toks: &level.toks,
                    read: n - unread,
                    kind: &level.kind,
                });
                upper = level.base;
            }
        }
        out
    }

    /// Give a lexer holding a `\message` body the source the body was read
    /// from, so an error met while the body expands shows the file line the
    /// scanner had reached. Call it with the body already pushed back.
    pub fn attach_site(&mut self, site: Site) {
        self.pending.low = self.pending.len();
        self.levels.insert(
            0,
            Level {
                base: 0,
                toks: Rc::new(Vec::new()),
                kind: LevelKind::Site(Rc::new(site)),
            },
        );
    }

    /// The source around a body this lexer read, as a [`Site`]: `ends[k]` is
    /// where the mouth stood after the k-th token of the body, and
    /// `parent_lens[k]` how deep `pending` was then.
    pub fn site(&self, ends: Vec<usize>, parent_lens: Vec<usize>) -> Site {
        let top = self.chars.len();
        let lo = ends.iter().copied().min().unwrap_or(self.pos).min(top);
        let hi = ends.iter().copied().max().unwrap_or(self.pos).min(top);
        // The display names the line of the last character READ, so the first
        // line needed is the one before `lo`.
        let start = self.chars[..lo.saturating_sub(1)]
            .iter()
            .rposition(|c| *c == '\n')
            .map_or(0, |i| i + 1);
        let end = self.chars[hi..]
            .iter()
            .position(|c| *c == '\n')
            .map_or(top, |i| hi + i);
        // Counted back from the mouth's own line, which is cached: counting from
        // the top of the file for every message is quadratic in the document.
        let pos = self.pos.min(top);
        let behind = self.chars[start.min(pos)..pos]
            .iter()
            .filter(|c| **c == '\n')
            .count();
        let first_line = (self.line() as usize).saturating_sub(behind).max(1);
        Site {
            text: self.chars[start..end].to_vec(),
            offset: start,
            first_line,
            spliced: self.spliced.clone(),
            ends,
            parent_lens,
            parent: self
                .levels
                .iter()
                .filter(|l| !matches!(l.kind, LevelKind::Site(_)))
                .map(|l| (l.base, l.toks.clone(), l.kind.clone()))
                .collect(),
        }
    }

    /// How many tokens of a lexer's body have been read from the bottom, by
    /// the shallowest `pending` has ever been since [`Lexer::attach_site`].
    pub fn body_read(&self, body_len: usize) -> usize {
        body_len.saturating_sub(self.pending.low.min(body_len))
    }

    /// The 1-based line the mouth has reached, for a diagnostic that has to
    /// point somewhere. Counted from the characters already consumed rather
    /// than tracked incrementally: the scanner rewinds and pushes back, and a
    /// counter that has to be maintained through both is a counter that drifts.
    ///
    /// A line's end belongs to that line: tex reads the next line into its
    /// buffer (§362's `incr(line)`) only when it needs a character from it,
    /// so the `\par` an empty line makes, and the space at the end of a line,
    /// are read on the line they end.
    pub fn line(&self) -> u32 {
        let mut pos = self.pos.min(self.chars.len());
        if pos > 0 && self.chars[pos - 1] == '\n' {
            pos -= 1;
        }
        let (from, base) = match self.line_cache.get() {
            (cached_pos, line) if cached_pos <= pos => (cached_pos, line),
            // The scanner moved backwards: recount.
            _ => (0, 1),
        };
        let line = base + self.chars[from..pos].iter().filter(|c| **c == '\n').count() as u32;
        self.line_cache.set((pos, line));
        line
    }

    /// The two lines `tex.web` §313 and §318 print under an error message:
    /// where the mouth is, and how much of that line it had read.
    ///
    /// The first line is `l.<n> ` and the text already consumed; the second is
    /// spaces to the same width and the text not yet consumed, so the break
    /// between them points at the character the scanner had reached. The two
    /// are separated by the newline tex's `print_ln` writes there.
    ///
    /// `None` for a mouth over a token list rather than a file: tex prints
    /// `<recently read>` and the token list itself for those (§319), a display
    /// this does not have, and inventing a file position for one would put a
    /// diagnostic on a line that has nothing to do with it.
    pub fn context(&self) -> Option<String> {
        if self.chars.is_empty() {
            return None;
        }
        Some(context_display(&self.chars, 1, self.pos, &self.spliced, 0))
    }

    /// `tex.web` §317's two-line display, trimmed the way tex trims it.
    ///
    /// Line one ends where the mouth stopped, so it is the TAIL that is kept
    /// and a cut front is marked `...`; line two begins there, so it is the
    /// HEAD that is kept and a cut tail is marked `...`. The widths are tex's
    /// own `error_line` and `half_error_line`.
    pub fn context_lines(tag: &str, before: &str, after: &str) -> String {
        const ERROR_LINE: usize = 79;
        const HALF_ERROR_LINE: usize = 50;
        let l = tag.chars().count();
        let first_count = before.chars().count();
        let m = after.chars().count();
        // §317: `if l+first_count<=half_error_line then p:=0; n:=l+first_count
        // else print("..."); p:=l+first_count-half_error_line+3; n:=half_error_line`.
        let (ellipsis, drop, n) = match l + first_count <= HALF_ERROR_LINE {
            true => ("", 0, l + first_count),
            false => (
                "...",
                l + first_count + 3 - HALF_ERROR_LINE,
                HALF_ERROR_LINE,
            ),
        };
        let head: String = before.chars().skip(drop).collect();
        // `if m+n<=error_line then p:=first_count+m else p:=first_count+(error_line-n-3)`.
        let (tail, cut): (String, &str) = match m + n <= ERROR_LINE {
            true => (after.to_string(), ""),
            false => (after.chars().take(ERROR_LINE - n - 3).collect(), "..."),
        };
        format!("{tag}{ellipsis}{head}\n{:n$}{tail}{cut}", "")
    }

    fn peek(&self) -> Option<char> {
        self.chars.get(self.pos).copied()
    }

    /// `^^X` notation (`tex.web` §352): a superscript character twice, then one
    /// character, denotes a control character. `^^M` is a carriage return, which
    /// is how a line end gets written inside a macro body.
    fn double_superscript(&mut self, cats: &CatTable, c: char) -> Option<char> {
        if cats.get(c) != Cat::Superscript {
            return None;
        }
        if self.chars.get(self.pos + 1).copied() != Some(c) {
            return None;
        }
        let third = self.chars.get(self.pos + 2).copied()?;
        // Two forms, and which one applies depends on the NEXT character as
        // well: `^^` followed by two LOWERCASE hex digits is that hex code, and
        // anything else is the single character shifted by 64. Measured against
        // tex 3.141592653, which is where the lowercase part comes from --
        // `^^41` is `A` and `^^4a` is `J`, but `^^4A` is `tA`, because `A` is
        // not a lowercase hex digit and so the single-character rule applies to
        // the `4` alone. Reading only the second form left plain.tex's
        // `\catcode`\^^K=7` unreadable, which is line 16 of it.
        let is_lower_hex = |c: char| matches!(c, '0'..='9' | 'a'..='f');
        if is_lower_hex(third) {
            if let Some(fourth) = self.chars.get(self.pos + 3).copied() {
                if is_lower_hex(fourth) {
                    self.pos += 4;
                    let hi = third.to_digit(16)?;
                    let lo = fourth.to_digit(16)?;
                    return char::from_u32(hi * 16 + lo);
                }
            }
        }
        let code = u32::from(third);
        if code >= 128 {
            return None;
        }
        self.pos += 3;
        let shifted = match code < 64 {
            true => code + 64,
            false => code - 64,
        };
        char::from_u32(shifted)
    }

    /// Smallest tail worth handing to other cores.
    ///
    /// Below this the threads cost more than the scan they replace; the figure
    /// is a slice per core of a few tens of kilobytes, which is where the split
    /// starts to pay on the documents in `bench/`.
    const AHEAD_MIN_CHARS: usize = 65_536;

    /// How many times a stale read-ahead is tolerated before giving up on it.
    ///
    /// A document that rewrites catcodes throughout would otherwise re-lex its
    /// tail after every change, turning a speedup into quadratic work. Three
    /// strikes is enough to tell a preamble (which settles) from a document
    /// that keeps moving the table.
    const AHEAD_MAX_MISSES: u32 = 3;

    /// Tokens of quiet required before (re)building the read-ahead.
    const AHEAD_COOLDOWN: usize = 512;

    /// Serve the next token from the speculative read-ahead, filling it first
    /// if that is worthwhile.
    ///
    /// Returns `None` when there is nothing cached and nothing worth caching,
    /// in which case the caller scans as it always did.
    fn next_from_ahead(&mut self, cats: &CatTable) -> Option<Token> {
        if self.ahead_disabled {
            return None;
        }
        // OFF by default, and that is a measured decision rather than caution.
        //
        // Splitting the mouth across cores is correct (tests/parallel_lex.rs
        // pins it against the sequential mouth) but it LOSES: the sequential
        // mouth streams, never materialising a token list, while reading ahead
        // has to copy the characters per worker, build a token-and-position
        // vector for the whole tail, and concatenate the pieces. On a 5.6 MB
        // document that is tens of megabytes of traffic to save a scan worth
        // about 0.03s, and it measured 3x SLOWER end to end than not doing it.
        //
        // The lexer is simply not where a texrs run spends its time: it
        // compiles to bytecode, so the mouth is walked once and the VM does the
        // repeated work. Left in, off, and honest -- `TEXRS_PARALLEL=1` turns
        // it on for anyone measuring a document shaped differently.
        //
        // The variable is read once per process: every token list the
        // lowerer runs through a mouth of its own asks this on its first read,
        // and a `getenv` per list was measurable.
        static PARALLEL: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
        if !*PARALLEL.get_or_init(|| std::env::var_os("TEXRS_PARALLEL").is_some()) {
            self.ahead_disabled = true;
            return None;
        }
        // Anything cached under a superseded table is wrong from here on.
        if let Some(a) = &self.ahead {
            if a.generation != cats.generation() {
                self.ahead = None;
                crate::parallel::DROP_GEN.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                self.ahead_misses += 1;
                self.ahead_cooldown = Self::AHEAD_COOLDOWN;
                if self.ahead_misses >= Self::AHEAD_MAX_MISSES {
                    self.ahead_disabled = true;
                    return None;
                }
            }
        }
        if self.ahead.is_none() {
            if self.ahead_cooldown > 0 {
                self.ahead_cooldown -= 1;
                return None;
            }
            if self.chars.len().saturating_sub(self.pos) < Self::AHEAD_MIN_CHARS {
                return None;
            }
            let threads = crate::parallel::default_threads();
            if threads < 2 {
                return None;
            }
            let toks = crate::parallel::prelex(&self.chars, self.pos, cats, threads);
            if toks.is_empty() {
                return None;
            }
            self.ahead = Some(Ahead {
                generation: cats.generation(),
                toks,
                at: 0,
            });
        }
        let a = self.ahead.as_mut()?;
        let (tok, end) = *a.toks.get(a.at)?;
        a.at += 1;
        // Keep `pos` exact: `line()` reads it, and abandoning the cache has to
        // resume scanning at the character this token ended on.
        self.pos = end;
        if a.at == a.toks.len() {
            crate::parallel::DROP_EXHAUST.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            self.ahead = None;
        }
        Some(tok)
    }

    /// The length of the line terminator at `at` -- `\r\n`, `\n` or a lone
    /// `\r`, the three TeX Live's `input_line` ends a line on -- or `None` when
    /// `at` is not the end of a line. A `\r` that `^^M` notation produced is the
    /// character 13, not a line end.
    fn terminator_at(&self, at: usize) -> Option<usize> {
        if self.decoded_at == Some(at) {
            return None;
        }
        match self.chars.get(at).copied()? {
            '\n' => Some(1),
            '\r' if self.chars.get(at + 1).copied() == Some('\n') => Some(2),
            '\r' => Some(1),
            _ => None,
        }
    }

    /// Whether only spaces lie between here and the end of the line:
    /// `tex.web` §31 drops them before the line is read. The end of the TEXT is
    /// not a line end -- a `tex.sprint` string keeps its trailing spaces.
    fn only_spaces_to_line_end(&self) -> bool {
        let mut i = self.pos;
        while self.chars.get(i) == Some(&' ') {
            i += 1;
        }
        self.terminator_at(i).is_some()
    }

    /// Discard the rest of the line, its end included, and start the next one
    /// in state N (`loc:=limit+1` in `tex.web` §347).
    fn finish_line(&mut self) {
        while self.pos < self.chars.len() {
            if let Some(len) = self.terminator_at(self.pos) {
                self.pos += len;
                break;
            }
            self.pos += 1;
        }
        self.line_end = None;
        self.state = State::NewLine;
    }

    /// An end-of-line character in the current state (§347): a space in M, a
    /// `\par` in N, nothing in S.
    fn end_line_token(&self) -> Option<Token> {
        match self.state {
            State::MidLine => Some(Token::Char(' ', Cat::Space)),
            State::NewLine => Some(Token::cs("par")),
            State::SkipBlanks => None,
        }
    }

    /// The token the `\endlinechar` `e` appended to a line makes, read with
    /// its category code like any character of the line. It is the line's
    /// last character, so a comment has nothing to discard and an escape
    /// has no name to read (§354's null control sequence).
    fn line_end_token(&self, e: char, cats: &CatTable) -> Option<Token> {
        match cats.get(e) {
            Cat::EndLine => self.end_line_token(),
            Cat::Space => (self.state == State::MidLine).then_some(Token::Char(' ', Cat::Space)),
            Cat::Comment | Cat::Ignored => None,
            Cat::Escape => Some(Token::cs("")),
            cat => Some(Token::Char(e, cat)),
        }
    }

    /// One token, or `None` at end of input.
    pub fn next_token(&mut self, cats: &CatTable) -> Option<Token> {
        // §357: a level read to its end is ended by the NEXT read, not by
        // the one that took its last token; until then it is shown as
        // `<recently read>`.
        self.drop_finished();
        if let Some(t) = self.pending.pop() {
            return Some(t);
        }
        if let Some(t) = self.next_from_ahead(cats) {
            return Some(t);
        }
        loop {
            let Some(c) = self.peek() else {
                return match self.end_pseudo_file() {
                    true => self.next_token(cats),
                    false => None,
                };
            };
            if self.line_end.is_none() {
                // A line of a file is about to be read: LuaTeX's
                // `process_input_buffer` sees it first. Read-ahead lexed it
                // as it was, so a run with the callback reads as it goes.
                if self.file_lines
                    && self.suspended.is_empty()
                    && crate::input_hooks::has_process_input_buffer()
                {
                    self.ahead = None;
                    self.ahead_disabled = true;
                    self.process_line();
                    // The line is the callback's now; it is ended as the
                    // document's lines are, and read from its start.
                    self.line_end = Some(cats.end_line_char());
                    continue;
                }
                self.line_end = Some(cats.end_line_char());
            }
            // The end of a line in the FILE: `\endlinechar` stands in for it.
            if let Some(len) = self.terminator_at(self.pos) {
                self.pos += len;
                let end = self.line_end.take().flatten();
                let out = end.and_then(|e| self.line_end_token(e, cats));
                self.state = State::NewLine;
                match out {
                    Some(t) => return Some(t),
                    None => continue,
                }
            }
            // §31: a line's trailing spaces are gone before it is looked at.
            if c == ' ' && self.only_spaces_to_line_end() {
                while self.peek() == Some(' ') {
                    self.pos += 1;
                }
                continue;
            }
            if let Some(decoded) = self.double_superscript(cats, c) {
                // Re-read the decoded character in place of the `^^X` triple.
                self.chars.splice(self.pos..self.pos, [decoded]);
                self.decoded_at = Some(self.pos);
                self.spliced.push(self.pos);
                continue;
            }
            let cat = cats.get(c);
            self.pos += 1;
            match cat {
                Cat::Escape => return Some(self.control_sequence(cats)),
                Cat::Comment => {
                    // §347: a comment discards the rest of the line, the
                    // appended `\endlinechar` with it, and the next line starts
                    // in state N.
                    self.finish_line();
                }
                Cat::EndLine => {
                    // §347: an end-of-line character ends its line -- whatever
                    // follows it there is discarded -- and is a space in state
                    // M, a `\par` in state N (the blank-line rule), and nothing
                    // while skipping blanks.
                    let out = self.end_line_token();
                    self.finish_line();
                    if out.is_some() {
                        return out;
                    }
                }
                Cat::Space => {
                    // A run of spaces is one space, and only in state M.
                    if self.state == State::MidLine {
                        self.state = State::SkipBlanks;
                        return Some(Token::Char(' ', Cat::Space));
                    }
                }
                Cat::Ignored => {}
                // §346: an invalid character is reported and skipped, and the
                // scan restarts with the state it had.
                Cat::Invalid => {
                    let context = self.context().unwrap_or_default();
                    self.invalid.borrow_mut().push(context);
                }
                _ => {
                    self.state = State::MidLine;
                    return Some(Token::Char(c, cat));
                }
            }
        }
    }

    /// The escape character has been consumed; read the control sequence.
    ///
    /// A control WORD is a maximal run of letters and swallows the spaces after
    /// it (state S); a control SYMBOL is exactly one character and does not.
    /// That asymmetry is why `\foo bar` loses its space and `\! bar` keeps it.
    /// The next character with `^^` notation already applied.
    ///
    /// The substitution belongs to the input processor (`tex.web` §353), which
    /// runs BEFORE anything is classified -- so it applies inside a control
    /// sequence name as much as in running text. plain.tex line 16 is
    /// `\catcode`\^^K=7`, where the name of the control sequence IS the
    /// control character, and reading it raw made it `\^` followed by junk.
    ///
    /// Inside a name the notation is REDUCED: §355 writes the character over
    /// it in the line and reads the line again from there, so the line an
    /// error shows has `\A` where the file had `\^^41`.
    fn decoded_char(&mut self, cats: &CatTable) -> Option<char> {
        let c = self.peek()?;
        let at = self.pos;
        if let Some(decoded) = self.double_superscript(cats, c) {
            self.chars.splice(at..self.pos, [decoded]);
            self.pos = at + 1;
            self.decoded_at = Some(at);
            // The line count was taken over the characters as they were.
            self.line_cache.set((0, 1));
            return Some(decoded);
        }
        self.pos += 1;
        Some(c)
    }

    fn control_sequence(&mut self, cats: &CatTable) -> Token {
        // An escape last on its line names the line's appended character --
        // `\` then a line end is `\^^M` -- and with no `\endlinechar` it is
        // the null control sequence (§354: `loc>limit`). Spaces after it are
        // trailing, so `\ ` last on a line is that too (§31).
        if self.peek() == Some(' ') && self.only_spaces_to_line_end() {
            while self.peek() == Some(' ') {
                self.pos += 1;
            }
        }
        if let Some(len) = self.terminator_at(self.pos) {
            self.pos += len;
            let end = self.line_end.take().flatten();
            self.state = State::NewLine;
            return match end {
                Some(e) => Token::cs(e.encode_utf8(&mut [0u8; 4])),
                None => Token::cs(""),
            };
        }
        let Some(first) = self.decoded_char(cats) else {
            return Token::cs("");
        };
        if cats.get(first) != Cat::Letter {
            // A control space (`\ `) leaves the state mid-line, like any other
            // single-character control sequence.
            self.state = match cats.get(first) == Cat::Space {
                true => State::SkipBlanks,
                false => State::MidLine,
            };
            return Token::cs(first.encode_utf8(&mut [0u8; 4]));
        }
        // The name is built in the mouth's own buffer, taken for the length of
        // the word and given back once the name is interned.
        let mut name = std::mem::take(&mut self.word);
        name.clear();
        name.push(first);
        self.state = loop {
            // A control word cannot run past its line (§356), but the line's
            // `\endlinechar` is its last character, and may be a letter.
            if let Some(len) = self.terminator_at(self.pos) {
                let end = self.line_end.flatten();
                if let Some(e) = end.filter(|e| cats.get(*e) == Cat::Letter) {
                    name.push(e);
                    self.pos += len;
                    self.line_end = None;
                    break State::NewLine;
                }
                break State::SkipBlanks;
            }
            // The decode has to happen before the letter test, and be undone
            // when what it produced is not a letter: `\ab^^K` names `ab`.
            let save = self.pos;
            let Some(c) = self.decoded_char(cats) else {
                break State::SkipBlanks;
            };
            if cats.get(c) != Cat::Letter {
                self.pos = save;
                break State::SkipBlanks;
            }
            name.push(c);
        };
        let token = Token::cs(&name);
        self.word = name;
        token
    }
}