texrs 0.6.3

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

#[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,
}

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,
    /// 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>,
    /// Pushed-back tokens (`\expandafter` and macro expansion feed these).
    pub pending: Vec<Token>,
}

impl Lexer {
    /// 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: Vec::new(),
            line_cache: std::cell::Cell::new((0, 1)),
            ahead: None,
            ahead_disabled: true,
            ahead_misses: 0,
            ahead_cooldown: Self::AHEAD_COOLDOWN,
            line_end: None,
            decoded_at: 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() {
            if 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
    }

    /// 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: Vec::new(),
            ahead: None,
            ahead_disabled: false,
            ahead_misses: 0,
            ahead_cooldown: Self::AHEAD_COOLDOWN,
            line_end: None,
            decoded_at: None,
        }
    }

    /// 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);
        }
    }

    /// 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.
    pub fn line(&self) -> u32 {
        let pos = self.pos.min(self.chars.len());
        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;
        }
        let pos = self.pos.min(self.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 = 1 + self.chars[..last].iter().filter(|c| **c == '\n').count();
        let start = self.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 = self.chars[start..]
            .iter()
            .position(|c| *c == '\n')
            .map_or(self.chars.len(), |i| start + i);
        let split = pos.min(end);
        let before: String = self.chars[start..split].iter().collect();
        let after: String = self.chars[split..end].iter().collect();
        Some(Self::context_lines(&format!("l.{line} "), &before, &after))
    }

    /// `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`.
    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.
        if std::env::var_os("TEXRS_PARALLEL").is_none() {
            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> {
        if let Some(t) = self.pending.pop() {
            return Some(t);
        }
        if let Some(t) = self.next_from_ahead(cats) {
            return Some(t);
        }
        loop {
            let c = self.peek()?;
            if self.line_end.is_none() {
                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);
                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 => {}
                _ => {
                    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.
    fn decoded_char(&mut self, cats: &CatTable) -> Option<char> {
        let c = self.peek()?;
        if let Some(decoded) = self.double_superscript(cats, c) {
            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]));
        }
        let mut name = String::from(first);
        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;
                    self.state = State::NewLine;
                    return Token::cs(&name);
                }
                break;
            }
            // 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;
            };
            if cats.get(c) != Cat::Letter {
                self.pos = save;
                break;
            }
            name.push(c);
        }
        self.state = State::SkipBlanks;
        Token::cs(&name)
    }
}