techy 0.2.0

A fast, extensible LaTeX parser for Rust
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
//! [`TokenListReader`]: a test-only [`TokenReader`] that serves a pre-built token list.
//!
//! Compiled under `cfg(test)` only, and deliberately not public API. It exists so that
//! construct parsers can be tested in isolation: a hand-written or pre-scanned
//! `Vec<Token>` drives a parser without a live scanning reader, so a test can exercise
//! exactly the token sequence it means to.
//!
//! Its most important use is the lockstep reader-agreement harness of the
//! construct-parser suites, which runs one parse against this reader and against
//! [`StdTokenReader`] and compares the two. That is what enforces "construct parsers
//! never reach around the reader into raw content": this reader rejects any token or
//! position it did not issue.
//!
//! The fidelity gap below — a fixed list cannot re-tokenize under the peek state — is
//! acceptable for a test tool, and is why this reader makes no public reader contract.
//!
//! # Fidelity contract
//!
//! The reader keeps a byte **position**, exactly like [`StdTokenReader`]:
//! [`move_to`](super::TokenReader::move_to) places it at the named edge of the token,
//! and `peek` returns the first listed token at or after the position, clipping its
//! pre-space to start no earlier than that position, so that re-peeking mid-pre-space
//! behaves like a fresh scan. Past the last token, `peek` yields the terminal
//! idempotent [`EndOfStream`](super::TokenKind::EndOfStream).
//!
//! The one inherent difference from a scanning reader is that the list is **fixed**.
//! Tokens are not re-scanned under the state passed to `peek`, and a position placed
//! *inside* a token's span — a move to [`End`](super::TokenEdge::End), rewinding before
//! swallowed post-space, as the `\verb` idiom does — yields the *following* listed
//! token, where a scanning reader would re-read the post-space bytes as fresh content.
//! Tests that need re-scanning behavior use [`StdTokenReader`] on real content.
//!
//! [`StdTokenReader`]: super::StdTokenReader

use alloc::collections::BTreeSet;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::cell::RefCell;

use crate::source::{Source, SourcePos, SourceSpan, Span};
use crate::state::{Lang, ParsingState};

use super::error::TokenResult;
use super::reader::{StdStreamPosition, TokenEdge, TokenReader};
use super::token::{StdToken, StdTokenKindData, TokenKind};
use super::tokenization::{StreamPosition, Token, Tokenization};

/// A test-only [`TokenReader`] that serves tokens from a pre-built list.
///
/// See the [module documentation](self) for what this reader is for and for the ways
/// its fixed list differs from a scanning reader.
///
/// The tokens must be in source order: ascending, non-overlapping spans, the order a
/// scan produces. A trailing [`EndOfStream`](super::TokenKind::EndOfStream) token is
/// permitted but not required, since one is synthesized past the end of the list.
///
/// # Rejecting what this reader never issued
///
/// This reader is the mechanical guard behind the lockstep harness: it **panics** when
/// handed a token or a stream position it did not issue, so that a construct parser
/// which invents either instead of asking the reader fails loudly rather than quietly
/// producing a plausible wrong span. Panicking is right here and only here — this is
/// test infrastructure, and the violation is a bug in the test suite's own code.
///
/// - A **token** is accepted when a listed token has the same span and the same kind, or
///   when it is an end-of-stream token (which this reader synthesizes rather than serves
///   from the list). Pre-space is left out of the comparison because `peek` clips it
///   to the current position.
/// - A **position** is accepted when its offset is one this reader issued. That set
///   starts with the initial position alone and grows with the five edge offsets of
///   every token the reader serves, with every position it answers
///   (`position_here`/`position_at`), and with every offset it is moved to
///   (`move_to`). A position taken from somewhere the reader never served is
///   therefore rejected.
pub struct TokenListReader<'s, L: Lang> {
    source: &'s Arc<Source<L::SourceOrigin>>,
    tokens: Vec<StdToken<L>>,
    pos: usize,
    /// Every offset this reader has issued as a stream position (see
    /// [the validation rules](TokenListReader#rejecting-what-this-reader-never-issued)).
    /// A `RefCell` because the position accessors take `&self`.
    issued: RefCell<BTreeSet<usize>>,
}

impl<'s, L> TokenListReader<'s, L>
where
    L: Lang,
    L::Tokenization: Tokenization<L, Token = StdToken<L>>,
{
    /// Creates a reader positioned before the first token.
    ///
    /// Keeping `tokens` in source order (see the type documentation) is the caller's
    /// responsibility. It is debug-asserted here, and an out-of-order list is not
    /// rejected: the parse's span bookkeeping reports the breakage as an implementation
    /// error where it surfaces.
    pub fn new(
        source: &'s Arc<Source<L::SourceOrigin>>,
        tokens: Vec<StdToken<L>>,
    ) -> TokenListReader<'s, L> {
        debug_assert!(
            tokens.windows(2).all(|w| w[0].span().end() <= w[1].span().start()),
            "tokens must be in source order with non-overlapping spans"
        );
        let pos = tokens.first().map(|t| t.pre_space().start()).unwrap_or(0);
        // Seeded with the initial position alone: every other offset becomes valid only
        // by being served or answered (see the type's validation rules).
        let issued = RefCell::new(BTreeSet::from([pos]));
        TokenListReader { source, tokens, pos, issued }
    }

    /// Record `offset` as one this reader issued.
    fn issue(&self, offset: usize) -> usize {
        self.issued.borrow_mut().insert(offset);
        offset
    }

    /// Panic unless `tok` is one this reader could have issued: a listed token with the
    /// same span and kind, or an end-of-stream token (which the reader synthesizes past
    /// the end of the list rather than serving from it). Pre-space is excluded from
    /// the comparison — `peek` clips it to the current position, so a token that came
    /// out of this very reader need not compare equal to its list entry.
    fn check_issued(&self, tok: &StdToken<L>, what: &str) {
        if matches!(tok.kind_data(), StdTokenKindData::EndOfStream) {
            return;
        }
        let known = self.tokens.iter().any(|listed| {
            listed.span() == tok.span() && listed.kind_data() == tok.kind_data()
        });
        assert!(
            known,
            "TokenListReader::{what} was handed a token it never issued: {:?}",
            tok
        );
    }

    /// Panic unless `at` is an offset this reader issued (see the type's docs).
    fn check_position(&self, at: usize, what: &str) {
        assert!(
            self.issued.borrow().contains(&at),
            "TokenListReader::{what} was handed a position it never issued: {at}"
        );
    }

    /// The first listed token at or after the current position (its span not yet begun).
    fn current(&self) -> Option<&StdToken<L>> {
        let i = self.tokens.partition_point(|t| t.span().start() < self.pos);
        self.tokens.get(i)
    }
}

/// The five edges, for seeding the issued-offset set.
const EVERY_EDGE: [TokenEdge; 5] = [
    TokenEdge::StartBeforePreSpace,
    TokenEdge::Start,
    TokenEdge::ContentStart,
    TokenEdge::End,
    TokenEdge::EndPastPostSpace,
];

impl<'s, L> TokenReader<'s, L> for TokenListReader<'s, L>
where
    L: Lang,
    L::Tokenization: Tokenization<L, Token = StdToken<L>, StreamPosition = StdStreamPosition>,
{
    fn peek(&mut self, _state: &Arc<ParsingState<L>>) -> TokenResult<L, Token<L>> {
        match self.current() {
            Some(token) => {
                // Clip the recorded pre-space to the current position: peeking from
                // within (or past) the original pre-space run reports only the remainder,
                // as a fresh scan would.
                let pre_space = token.pre_space();
                let token = token.with_pre_space(Span::new(
                    pre_space.start().max(self.pos).min(pre_space.end()),
                    pre_space.end(),
                ));
                for edge in EVERY_EDGE {
                    self.issue(token.edge_offset(edge));
                }
                Ok(token)
            }
            None => {
                self.issue(self.pos);
                Ok(StdToken::end_of_stream(Span::empty(self.pos)))
            }
        }
    }

    fn move_to(&mut self, tok: &Token<L>, edge: TokenEdge) {
        self.check_issued(tok, "move_to");
        self.pos = self.issue(tok.edge_offset(edge));
    }

    fn move_to_position(&mut self, at: &StreamPosition<L>) {
        self.check_position(at.offset(), "move_to_position");
        self.pos = at.offset();
    }

    fn token_kind<'t>(&self, tok: &'t Token<L>) -> TokenKind<'t, L>
    where
        's: 't,
    {
        self.check_issued(tok, "token_kind");
        // Interpreted exactly as `StdTokenReader` interprets it: every written spelling
        // is the run of this source's content between two of the token's edges.
        let text = |a: TokenEdge, b: TokenEdge| -> &'t str {
            self.source
                .content()
                .get(tok.edge_offset(a)..tok.edge_offset(b))
                .unwrap_or("")
        };
        match tok.kind_data() {
            StdTokenKindData::Char(c) => TokenKind::Char(*c),
            StdTokenKindData::GroupOpen { rule } => TokenKind::GroupOpen {
                delim: text(TokenEdge::Start, TokenEdge::End),
                rule,
            },
            StdTokenKindData::GroupClose => {
                TokenKind::GroupClose { delim: text(TokenEdge::Start, TokenEdge::End) }
            }
            StdTokenKindData::Command { escape_char, .. } => TokenKind::Command {
                name: text(TokenEdge::ContentStart, TokenEdge::End),
                escape_char: *escape_char,
            },
            StdTokenKindData::Specials { callable_type, spec } => TokenKind::Specials {
                callable_type: *callable_type,
                name: text(TokenEdge::Start, TokenEdge::End),
                spec,
            },
            StdTokenKindData::Comment { .. } => TokenKind::Comment {
                start_delim: text(TokenEdge::Start, TokenEdge::ContentStart),
                content: text(TokenEdge::ContentStart, TokenEdge::End),
            },
            StdTokenKindData::ParagraphBreak => TokenKind::ParagraphBreak,
            StdTokenKindData::EndOfStream => TokenKind::EndOfStream,
        }
    }

    fn source_span_between(
        &self,
        tok: &Token<L>,
        a: TokenEdge,
        b: TokenEdge,
    ) -> SourceSpan<L::SourceOrigin> {
        self.check_issued(tok, "source_span_between");
        let (a, b) = (tok.edge_offset(a), tok.edge_offset(b));
        SourceSpan::new(self.source, a.min(b)..a.max(b))
    }

    fn position_here(&self) -> StreamPosition<L> {
        StdStreamPosition::at(self.issue(self.pos))
    }

    fn position_at(&self, tok: &Token<L>, edge: TokenEdge) -> StreamPosition<L> {
        self.check_issued(tok, "position_at");
        StdStreamPosition::at(self.issue(tok.edge_offset(edge)))
    }

    fn source_position_at(&self, at: &StreamPosition<L>) -> SourcePos<L::SourceOrigin> {
        self.check_position(at.offset(), "source_position_at");
        SourcePos::new(self.source, at.offset())
    }

    fn source_span_within(
        &self,
        begin: &StreamPosition<L>,
        end: &StreamPosition<L>,
    ) -> Option<SourceSpan<L::SourceOrigin>> {
        self.check_position(begin.offset(), "source_span_within");
        self.check_position(end.offset(), "source_span_within");
        (begin.offset() <= end.offset())
            .then(|| SourceSpan::new(self.source, begin.offset()..end.offset()))
    }

    fn source_span_describing(
        &self,
        begin: &StreamPosition<L>,
        end: &StreamPosition<L>,
    ) -> SourceSpan<L::SourceOrigin> {
        self.check_position(begin.offset(), "source_span_describing");
        self.check_position(end.offset(), "source_span_describing");
        // One source, exactly like `StdTokenReader`: the ordered pair's own range, and
        // the empty span at `begin` for an inverted pair.
        match begin.offset() <= end.offset() {
            true => SourceSpan::new(self.source, begin.offset()..end.offset()),
            false => SourceSpan::new(self.source, begin.offset()..begin.offset()),
        }
    }
}

impl<L: Lang> core::fmt::Debug for TokenListReader<'_, L> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("TokenListReader")
            .field("tokens", &self.tokens.len())
            .field("pos", &self.pos)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::scopes::ScopeStack;
    use crate::source::Source;
    use crate::state::{TrivialLang, StateData};
    use crate::token::{
        CommandRule, CommandRules, CommentRule, CommentRules, ForbiddenCharsRules, GroupRule,
        GroupRules, ParagraphRules, SpecialsRules, StdTokenReader, TokenRules,
        WhitespaceRules,
    };
    use alloc::sync::Arc;
    use alloc::vec;
    use alloc::vec::Vec;

    #[derive(Debug, Clone, Copy)]
    struct TestLang;
    impl TrivialLang for TestLang {}

    fn latex_rules() -> TokenRules<TestLang> {
        TokenRules {
            whitespace: WhitespaceRules { enabled: true, chars: " \t\n\r".into() },
            paragraphs: ParagraphRules { enabled: true },
            groups: GroupRules {
                enabled: true,
                rules: vec![Arc::new(GroupRule {
                    group_type: 0,
                    open: "{".into(),
                    close: "}".into(),
                })],
                temporary: Vec::new(),
                expecting_close: None,
            },
            commands: CommandRules {
                enabled: true,
                rules: vec![Arc::new(CommandRule {
                    escape_char: '\\',
                    name_chars: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".into(),
                })],
            },
            comments: CommentRules {
                enabled: true,
                rules: vec![Arc::new(CommentRule { start: "%".into() })],
            },
            specials: SpecialsRules { enabled: true },
            forbidden_chars: ForbiddenCharsRules { chars: "".into() },
        }
    }

    fn state() -> Arc<ParsingState<TestLang>> {
        Arc::new(ParsingState::new(StateData {
            rules: latex_rules(),
            scopes: ScopeStack::new(),
            mode: (),
            ext: (),
        }))
    }

    /// The reader's view of a token — the only way to read one.
    fn kind_of<'s: 't, 't, R: TokenReader<'s, TestLang>>(
        reader: &R,
        tok: &'t StdToken<TestLang>,
    ) -> TokenKind<'t, TestLang> {
        reader.token_kind(tok)
    }

    /// Scan `source` into the full token list with `StdTokenReader` (including the
    /// terminal `EndOfStream`).
    fn scan(source: &Arc<Source>) -> Vec<StdToken<TestLang>> {
        let st = state();
        let mut tr = StdTokenReader::new(source);
        let mut tokens = Vec::new();
        loop {
            let token = TokenReader::next(&mut tr, &st).unwrap();
            let done = matches!(kind_of(&tr, &token), TokenKind::EndOfStream);
            tokens.push(token);
            if done {
                break;
            }
        }
        tokens
    }

    #[test]
    fn round_trips_a_scanned_token_sequence() {
        let source: Arc<Source> = Arc::new(Source::new("ab \\vec c % note\n {x}\n\nz  "));
        let scanned = scan(&source);
        let st = state();

        let mut lr = TokenListReader::new(&source, scanned.clone());
        for expected in &scanned {
            assert_eq!(&TokenReader::next(&mut lr, &st).unwrap(), expected);
        }
    }

    #[test]
    fn peek_is_idempotent_and_does_not_advance() {
        let source: Arc<Source> = Arc::new(Source::new(" \\vec b"));
        let mut lr = TokenListReader::new(&source, scan(&source));
        let st = state();

        let start = TokenReader::position_here(&lr);
        let first = TokenReader::peek(&mut lr, &st).unwrap();
        assert_eq!(TokenReader::peek(&mut lr, &st).unwrap(), first);
        assert_eq!(TokenReader::position_here(&lr), start);
        assert_eq!(first.pre_space(), Span::new(0, 1));
    }

    #[test]
    fn moving_to_each_edge_matches_the_std_reader() {
        // The movement matrix of the reader suite's edge test, run against both
        // readers in lockstep.
        let content = "  \\vec b";
        let st = state();
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut std_r = StdTokenReader::new(&source);
        let mut list_r = TokenListReader::new(&source, scan(&source));

        let token = TokenReader::peek(&mut std_r, &st).unwrap();
        assert_eq!(TokenReader::peek(&mut list_r, &st).unwrap(), token);

        for (edge, offset) in [
            (TokenEdge::EndPastPostSpace, 7),
            (TokenEdge::End, 6),
            (TokenEdge::ContentStart, 3),
            (TokenEdge::Start, 2),
            (TokenEdge::StartBeforePreSpace, 0),
        ] {
            let std_reader: &mut dyn TokenReader<'_, TestLang> = &mut std_r;
            std_reader.move_to(&token, edge);
            let at = std_reader.source_position_at(&std_reader.position_here());
            assert_eq!(at, SourcePos::new(&source, offset), "{edge:?}");

            let list_reader: &mut dyn TokenReader<'_, TestLang> = &mut list_r;
            list_reader.move_to(&token, edge);
            assert_eq!(
                list_reader.source_position_at(&list_reader.position_here()),
                at,
                "{edge:?}"
            );
        }

        // Reading again after the rewind yields the same token from both.
        assert_eq!(TokenReader::peek(&mut std_r, &st).unwrap(), token);
        assert_eq!(TokenReader::peek(&mut list_r, &st).unwrap(), token);
    }

    #[test]
    fn the_token_view_matches_the_std_readers_view() {
        // Both readers interpret the same tokens over the same content, so their views
        // agree kind for kind — the lockstep guarantee the construct-parser suites rest
        // on.
        let source: Arc<Source> = Arc::new(Source::new("a{\\vec  }% note\nb"));
        let st = state();
        let mut std_r = StdTokenReader::new(&source);
        let mut list_r = TokenListReader::new(&source, scan(&source));
        loop {
            let token = TokenReader::next(&mut std_r, &st).unwrap();
            let listed = TokenReader::next(&mut list_r, &st).unwrap();
            let std_reader: &dyn TokenReader<'_, TestLang> = &std_r;
            let list_reader: &dyn TokenReader<'_, TestLang> = &list_r;
            assert_eq!(list_reader.token_kind(&listed), std_reader.token_kind(&token));
            if matches!(std_reader.token_kind(&token), TokenKind::EndOfStream) {
                break;
            }
        }
    }

    #[test]
    fn the_comment_view_names_the_delimiter_and_the_text_between_it_and_the_post_space() {
        let source: Arc<Source> = Arc::new(Source::new("%% note\nx"));
        let st = state();
        let mut lr = TokenListReader::new(&source, scan(&source));
        let token = TokenReader::next(&mut lr, &st).unwrap();
        let reader: &dyn TokenReader<'_, TestLang> = &lr;
        // The rules define `%` as the only comment start, so the second `%` is content.
        assert_eq!(
            reader.token_kind(&token),
            TokenKind::Comment { start_delim: "%", content: "% note" }
        );
        // The same two spans as edge answers — what the comment node records.
        assert_eq!(
            reader
                .source_span_between(&token, TokenEdge::Start, TokenEdge::ContentStart)
                .content(),
            "%"
        );
        assert_eq!(
            reader
                .source_span_between(&token, TokenEdge::ContentStart, TokenEdge::End)
                .content(),
            "% note"
        );
    }

    #[test]
    #[should_panic(expected = "was handed a token it never issued")]
    fn the_view_of_a_foreign_token_is_rejected() {
        let source: Arc<Source> = Arc::new(Source::new("ab"));
        let other: Arc<Source> = Arc::new(Source::new("zz"));
        let lr = TokenListReader::new(&source, scan(&source));
        let foreign = scan(&other);
        let reader: &dyn TokenReader<'_, TestLang> = &lr;
        let _ = reader.token_kind(&foreign[0]);
    }

    #[test]
    fn move_to_an_earlier_token_rewinds() {
        let source: Arc<Source> = Arc::new(Source::new("a {b}"));
        let scanned = scan(&source);
        let st = state();
        let mut lr = TokenListReader::new(&source, scanned.clone());

        let first = TokenReader::next(&mut lr, &st).unwrap();
        let second = TokenReader::next(&mut lr, &st).unwrap();
        assert_eq!(second, scanned[1]);

        TokenReader::move_to(&mut lr, &first, TokenEdge::Start);
        assert_eq!(
            TokenReader::position_here(&lr),
            TokenReader::position_at(&lr, &first, TokenEdge::Start)
        );
        let again = TokenReader::peek(&mut lr, &st).unwrap();
        let reader: &dyn TokenReader<'_, TestLang> = &lr;
        assert_eq!(reader.token_kind(&again), reader.token_kind(&first));
        // pre_space was already consumed positionally: clipped to empty.
        assert_eq!(again.pre_space(), Span::empty(first.span().start()));
    }

    #[test]
    fn pre_space_clipped_when_peeking_mid_whitespace() {
        let source: Arc<Source> = Arc::new(Source::new("a   b"));
        let mut scanned = scan(&source);
        // A filler token over the first whitespace character, so that consuming it
        // leaves the reader inside `b`'s recorded pre-space run.
        scanned.insert(
            1,
            StdToken::char(' ', Span::new(1, 2), Span::empty(1)),
        );
        let mut lr = TokenListReader::new(&source, scanned);
        let st = state();

        // Land inside b's pre-space run (1..4) the only way a reader ever lands
        // anywhere: by consuming a token that ends there. The hand-built list holds
        // one covering `1..2`, so reading it leaves the stream mid-whitespace.
        let _ = TokenReader::next(&mut lr, &st).unwrap(); // `a`
        let _ = TokenReader::next(&mut lr, &st).unwrap(); // the 1..2 filler
        let token = TokenReader::peek(&mut lr, &st).unwrap();
        let reader: &dyn TokenReader<'_, TestLang> = &lr;
        assert_eq!(reader.token_kind(&token), TokenKind::Char('b'));
        assert_eq!(token.pre_space(), Span::new(2, 4));
    }

    #[test]
    fn end_of_stream_is_terminal_and_idempotent() {
        let content = "x  ";
        let st = state();
        // Same walk against both readers: EOS carries the trailing whitespace once,
        // then repeats with empty pre_space.
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut std_r = StdTokenReader::new(&source);
        let mut list_r = TokenListReader::new(&source, scan(&source));
        for _ in 0..2 {
            let a = TokenReader::next(&mut std_r, &st).unwrap();
            let b = TokenReader::next(&mut list_r, &st).unwrap();
            assert_eq!(a, b);
        }
        let a = TokenReader::next(&mut std_r, &st).unwrap();
        let b = TokenReader::next(&mut list_r, &st).unwrap();
        assert_eq!(a, b);
        assert_eq!(b, StdToken::end_of_stream(Span::empty(3)));
    }

    #[test]
    fn positions_and_spans_match_the_std_reader_in_lockstep() {
        let content = "a \\vec  b";
        let st = state();
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut std_r = StdTokenReader::new(&source);
        let mut list_r = TokenListReader::new(&source, scan(&source));
        let std_reader: &mut dyn TokenReader<'_, TestLang> = &mut std_r;
        let list_reader: &mut dyn TokenReader<'_, TestLang> = &mut list_r;

        assert_eq!(std_reader.position_here(), list_reader.position_here());

        let a = std_reader.next(&st).unwrap();
        let b = list_reader.next(&st).unwrap();
        assert_eq!(a, b);

        let token = std_reader.peek(&st).unwrap();
        assert_eq!(list_reader.peek(&st).unwrap(), token);

        for edge in [
            TokenEdge::StartBeforePreSpace,
            TokenEdge::Start,
            TokenEdge::ContentStart,
            TokenEdge::End,
            TokenEdge::EndPastPostSpace,
        ] {
            assert_eq!(
                std_reader.position_at(&token, edge),
                list_reader.position_at(&token, edge),
                "positions disagree at {edge:?}"
            );
            assert_eq!(
                std_reader.source_span_between(&token, TokenEdge::Start, edge),
                list_reader.source_span_between(&token, TokenEdge::Start, edge),
                "spans disagree at {edge:?}"
            );
            std_reader.move_to(&token, edge);
            list_reader.move_to(&token, edge);
            assert_eq!(std_reader.position_here(), list_reader.position_here());
        }

        assert_eq!(std_reader.source_span_of(&token), list_reader.source_span_of(&token));

        let begin = std_reader.position_at(&token, TokenEdge::Start);
        let end = std_reader.position_at(&token, TokenEdge::EndPastPostSpace);
        assert_eq!(
            std_reader.source_span_within(&begin, &end),
            list_reader.source_span_within(&begin, &end)
        );
        assert_eq!(
            std_reader.source_position_at(&begin),
            list_reader.source_position_at(&begin)
        );
        assert_eq!(
            std_reader.source_span_describing(&begin, &end),
            list_reader.source_span_describing(&begin, &end)
        );
    }

    #[test]
    fn a_described_span_is_the_exact_range_and_never_absent() {
        let content = "a \\vec  b";
        let st = state();
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut lr = TokenListReader::new(&source, scan(&source));
        let reader: &mut dyn TokenReader<'_, TestLang> = &mut lr;

        let begin = reader.position_here();
        let token = reader.next(&st).unwrap();
        let end = reader.position_at(&token, TokenEdge::EndPastPostSpace);

        // One source, so the ordered pair describes its own range …
        assert_eq!(
            reader.source_span_describing(&begin, &end),
            reader.source_span_within(&begin, &end).expect("an ordered pair")
        );
        // … equal positions the empty span there …
        assert_eq!(reader.source_span_describing(&end, &end).range(), 1..1);
        // … and the inverted pair — a caller bug, `None` from `source_span_within` —
        // still gets an answer: the empty span at `begin`.
        assert_eq!(reader.source_span_within(&end, &begin), None);
        assert_eq!(reader.source_span_describing(&end, &begin).range(), 1..1);
    }

    #[test]
    #[should_panic(expected = "a token it never issued")]
    fn a_token_this_reader_never_issued_is_rejected() {
        let source: Arc<Source> = Arc::new(Source::new("ab"));
        let mut lr = TokenListReader::new(&source, scan(&source));
        let reader: &mut dyn TokenReader<'_, TestLang> = &mut lr;

        // Not from this reader — and not from any scan of this content.
        let forged = StdToken::char('z', Span::new(0, 1), Span::empty(0));
        let _ = reader.source_span_between(&forged, TokenEdge::Start, TokenEdge::End);
    }

    #[test]
    #[should_panic(expected = "a position it never issued")]
    fn a_position_this_reader_never_issued_is_rejected() {
        // The list covers only the first two characters of the source, so a position
        // taken further along is one this reader never handed out.
        let source: Arc<Source> = Arc::new(Source::new("ab cd"));
        let prefix: Vec<StdToken<TestLang>> =
            scan(&source).into_iter().take(2).collect();
        let mut lr = TokenListReader::new(&source, prefix);
        let mut std_r = StdTokenReader::new(&source);
        let std_reader: &mut dyn TokenReader<'_, TestLang> = &mut std_r;
        // Read past the list's extent: the position the std reader stands at then is
        // one this list reader never handed out.
        for _ in 0..3 {
            let _ = std_reader.next(&state()).unwrap();
        }
        let elsewhere = std_reader.position_here();

        let reader: &mut dyn TokenReader<'_, TestLang> = &mut lr;
        reader.move_to_position(&elsewhere);
    }

    #[test]
    fn empty_list_yields_end_of_stream() {
        let source: Arc<Source> = Arc::new(Source::new(""));
        let mut lr: TokenListReader<'_, TestLang> = TokenListReader::new(&source, vec![]);
        let st = state();
        assert_eq!(
            TokenReader::peek(&mut lr, &st).unwrap(),
            StdToken::end_of_stream(Span::empty(0)),
        );
    }

    #[test]
    fn hand_built_lists_need_only_a_long_enough_source() {
        // The unit-test use case: a token list written by hand, spans made up — the
        // source only has to be long enough for the spans to be valid ranges in it.
        let source: Arc<Source> = Arc::new(Source::new(r"x\vec  "));
        let tokens: Vec<StdToken<TestLang>> = vec![
            StdToken::char('x', Span::new(0, 1), Span::empty(0)),
            StdToken::command('\\', Span::new(1, 6), Span::empty(1), Span::new(5, 6)),
        ];
        let st = state();
        let mut lr = TokenListReader::new(&source, tokens.clone());
        assert_eq!(TokenReader::next(&mut lr, &st).unwrap(), tokens[0]);
        assert_eq!(TokenReader::next(&mut lr, &st).unwrap(), tokens[1]);
        assert_eq!(
            TokenReader::source_position_at(&lr, &TokenReader::position_here(&lr)),
            SourcePos::new(&source, 6)
        );
        let token = TokenReader::peek(&mut lr, &st).unwrap();
        assert_eq!(kind_of(&lr, &token), TokenKind::EndOfStream);
    }
}