pythonrs 0.1.14

Python as a fusevm frontend: lexer, parser, and compiler to fusevm::Chunk on a PyHost heap — the first compiled standalone Python runtime
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
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
//! Python tokenizer.
//!
//! Turns source into a flat token stream with the significant-indentation
//! contract CPython uses: logical lines end in `Newline`, and a change in
//! leading indentation emits `Indent`/`Dedent` (skipped inside brackets and on
//! blank/comment-only lines). Bracket depth (`()[]{}`) and backslash-newline
//! suppress newlines for implicit/explicit line continuation. f-strings are
//! emitted as a single `FString` token carrying the raw inner text; the parser
//! expands the `{...}` fields with the expression grammar.

/// A lexical token.
#[derive(Debug, Clone, PartialEq)]
pub enum Tok {
    Name(String),
    /// A non-ASCII identifier whose NFKC form spells a keyword or soft keyword
    /// (`if`, `match`). CPython recognizes keywords by the token's raw
    /// spelling and normalizes only afterwards, so this is always a plain name
    /// (`if = 1` binds `if`) and never starts a statement or a pattern.
    Ident(String),
    Int(i64),
    /// Integer literal too wide for `i64`, kept as decimal text.
    BigInt(String),
    Float(f64),
    /// Imaginary literal (`3j`) — the real magnitude; host builds the complex.
    Complex(f64),
    Str(String),
    Bytes(Vec<u8>),
    /// `(raw_inner_text, is_raw)` for an f-string; fields parsed by the parser.
    FString(String, bool),
    /// PEP 750 template string (`t"..."`); same body syntax as an f-string.
    TString(String, bool),
    /// An operator or delimiter, e.g. `+`, `==`, `**`, `(`, `:`, `,`, `->`.
    Op(String),
    Newline,
    Indent,
    Dedent,
    Eof,
}

/// A token plus its 1-based source line and 0-based character columns (start
/// inclusive, end exclusive) within that line. Columns feed traceback carets;
/// they are only meaningful for on-line tokens (structural Newline/Indent/Dedent/
/// Eof carry stale columns that no consumer reads).
#[derive(Debug, Clone, PartialEq)]
pub struct Token {
    pub tok: Tok,
    pub line: u32,
    pub col: u32,
    pub end_col: u32,
}

/// A tokenized module: the stream, plus an indentation error the parser is to
/// report only if it consumes that far. See [`Lexed::deferred`].
pub struct Lexed {
    pub toks: Vec<Token>,
    /// An `unindent does not match any outer indentation level` found while
    /// tokenizing, held back rather than raised.
    ///
    /// CPython's tokenizer is pulled lazily by the parser, so a syntax error on
    /// an EARLIER line wins over a bad dedent on a later one:
    ///
    /// ```text
    /// match -3:
    ///         print('bad')     <- line 2: not a `case`, SyntaxError
    ///     case _:              <- line 3: dedent matches nothing
    /// ```
    ///
    /// CPython reports `SyntaxError: invalid syntax` at line 2. pythonrs
    /// tokenizes the whole module up front, so the line-3 tokenizer error used
    /// to pre-empt it with `IndentationError`. Tokenizing now STOPS at the bad
    /// dedent and parks the message here: an earlier parse error surfaces
    /// first, and if the truncated stream parses cleanly the parser raises this
    /// instead — which restores the original error for the case where the
    /// dedent really is the only problem.
    pub deferred: Option<String>,
    /// A bracket still open at end of input: `'(' was never closed`, pointing
    /// at the bracket. The parser reports it when it runs out of input there,
    /// and its own error otherwise.
    pub unclosed: Option<String>,
}

struct Lexer {
    src: Vec<char>,
    pos: usize,
    line: u32,
    depth: i32,
    indents: Vec<usize>,
    out: Vec<Token>,
    /// See [`Lexed::deferred`]. Set by `handle_indent`; stops `run`.
    deferred: Option<String>,
    /// Char index where the current line begins — subtracted from a token's
    /// start/end char index to get its 0-based character column (for carets).
    line_start: usize,
    /// Char index where the token currently being scanned begins.
    tok_start: usize,
    /// The brackets currently open: the character, its line, and its 0-based
    /// column — what `'(' was never closed` and a mismatched closer name.
    open: Vec<(char, u32, u32)>,
}

/// CPython's `MAXLEVEL` (`Parser/lexer/state.h`): the tokenizer tracks at most
/// 200 simultaneously-open brackets, counting `(`, `[` and `{` together.
const MAX_PAREN_DEPTH: i32 = 200;

/// Multi-char operators, longest first so the scanner is greedy.
const OPS3: &[&str] = &["**=", "//=", ">>=", "<<=", "...", "!=="];
const OPS2: &[&str] = &[
    "**", "//", ">>", "<<", "<=", ">=", "==", "!=", "->", ":=", "+=", "-=", "*=", "/=", "%=", "&=",
    "|=", "^=", "@=",
];

/// Tokenize `src` into a token stream ending in `Eof`.
pub fn lex(src: &str) -> Result<Lexed, String> {
    let mut lx = Lexer {
        src: src.chars().collect(),
        pos: 0,
        line: 1,
        depth: 0,
        indents: vec![0],
        out: Vec::new(),
        deferred: None,
        line_start: 0,
        tok_start: 0,
        open: Vec::new(),
    };
    lx.run()?;
    let unclosed = lx.open.first().map(|&(c, line, col)| {
        // The line the bracket is on, newline-terminated only when nothing but
        // blank lines follows it — as CPython's tokenizer leaves its buffer.
        let rest_blank = src
            .split_inclusive('\n')
            .skip(line as usize)
            .all(|l| l.trim().is_empty());
        let mut text = lx.line_text(line);
        if rest_blank {
            text.push('\n');
        }
        crate::parser::with_text(
            crate::parser::at_pos(
                &format!("SyntaxError: '{c}' was never closed"),
                line,
                col as i64 + 1,
                line,
                0,
            ),
            &text,
        )
    });
    Ok(Lexed {
        toks: lx.out,
        deferred: lx.deferred,
        unclosed,
    })
}

impl Lexer {
    fn peek(&self) -> Option<char> {
        self.src.get(self.pos).copied()
    }
    fn peek2(&self) -> Option<char> {
        self.src.get(self.pos + 1).copied()
    }
    fn bump(&mut self) -> Option<char> {
        let c = self.src.get(self.pos).copied();
        if let Some(ch) = c {
            self.pos += 1;
            if ch == '\n' {
                self.line += 1;
                self.line_start = self.pos;
            }
        }
        c
    }
    /// Source line `line` (1-based), without its newline.
    fn line_text(&self, line: u32) -> String {
        let mut cur = 1;
        let mut out = String::new();
        for &c in &self.src {
            if c == '\n' {
                if cur == line {
                    break;
                }
                cur += 1;
                continue;
            }
            if cur == line {
                out.push(c);
            }
        }
        out
    }

    /// An error decoding the string literal just scanned, positioned over the
    /// whole literal as CPython positions the errors its string parser raises
    /// (`_PyPegen_decode_string`'s caller reports the token): from its first
    /// character on its first line to just past its closing quote. The text is
    /// that first line, newline-terminated only when the literal ends on it
    /// (measured against CPython 3.14's `SyntaxError.text`).
    fn literal_err(&self, err: String) -> String {
        let before = &self.src[..self.tok_start];
        let line = 1 + before.iter().filter(|&&c| c == '\n').count() as u32;
        let line_start = before.iter().rposition(|&c| c == '\n').map_or(0, |i| i + 1);
        let col = (self.tok_start - line_start) as i64;
        let text = self.line_text(line);
        // pegen converts every offset against the FIRST line's text, which
        // clamps an end on a later line to one past that line's length.
        let mut end_offset = (self.pos - self.line_start) as i64 + 1;
        if line != self.line {
            end_offset = end_offset.min(text.chars().count() as i64 + 1);
        }
        let err = crate::parser::at_pos(&err, line, col + 1, self.line, end_offset);
        let newline = if line == self.line { "\n" } else { "" };
        crate::parser::with_text(err, &format!("{text}{newline}"))
    }

    /// A tokenizer error at `line`/`col` (0-based column), carrying the line's
    /// text without its newline, as CPython's tokenizer reports it.
    fn tok_err(&self, msg: &str, line: u32, col: usize, end_col: i64) -> String {
        crate::parser::with_text(
            crate::parser::at_pos(msg, line, col as i64 + 1, line, end_col),
            &self.line_text(line),
        )
    }

    fn push(&mut self, tok: Tok) {
        self.out.push(Token {
            tok,
            line: self.line,
            col: (self.tok_start.saturating_sub(self.line_start)) as u32,
            end_col: (self.pos.saturating_sub(self.line_start)) as u32,
        });
    }

    /// A `\` outside a literal. It must end its line, or it is the
    /// tokenizer's "unexpected character after line continuation character"
    /// (positioned on the character after it, end 0); and a line must follow
    /// it, or the input ran out — exec input always ends in a newline, so a
    /// `\` at the very end continues onto nothing — which pegen reports as
    /// "unexpected EOF while parsing" just past the `\`, end -1. Inside an
    /// open bracket running out is that bracket's error instead.
    fn line_continuation(&mut self) -> Result<(), String> {
        let (line, col) = (self.line, (self.pos - self.line_start) as i64);
        let text = format!("{}\n", self.line_text(line).trim_end_matches('\r'));
        self.bump(); // `\`
        match self.peek() {
            Some('\n') => {
                self.bump();
            }
            Some('\r') => {
                self.bump();
                if self.peek() == Some('\n') {
                    self.bump();
                }
            }
            None => {}
            Some(_) => {
                let msg = "SyntaxError: unexpected character after line continuation character";
                return Err(crate::parser::with_text(crate::parser::at_pos(msg, line, col + 2, line, 0), &text));
            }
        }
        if self.peek().is_none() && self.depth == 0 {
            let msg = "SyntaxError: unexpected EOF while parsing";
            return Err(crate::parser::with_text(crate::parser::at_pos(msg, line, col + 2, line, -1), &text));
        }
        Ok(())
    }

    fn run(&mut self) -> Result<(), String> {
        let mut at_line_start = true;
        loop {
            if at_line_start && self.depth == 0 {
                let blank = self.handle_indent()?;
                if self.deferred.is_some() {
                    // Bad dedent: stop here so the parser sees only the lines
                    // before it. See `Lexed::deferred`.
                    break;
                }
                if blank {
                    // Blank/comment-only line consumed; stay at line start.
                    continue;
                }
                at_line_start = false;
            }
            match self.peek() {
                None => break,
                Some('\n') => {
                    // A Newline token sits where the line break is, so an error
                    // reported against it names this line, not the next.
                    let (line, col) = (self.line, (self.pos - self.line_start) as u32);
                    self.bump();
                    if self.depth == 0 {
                        // Collapse runs of blank physical lines to one Newline.
                        if !matches!(self.out.last().map(|t| &t.tok), Some(Tok::Newline) | None) {
                            self.out.push(Token {
                                tok: Tok::Newline,
                                line,
                                col,
                                end_col: col + 1,
                            });
                        }
                        at_line_start = true;
                    }
                }
                Some(c) if c == ' ' || c == '\t' || c == '\r' => {
                    self.bump();
                }
                Some('#') => {
                    while let Some(c) = self.peek() {
                        if c == '\n' {
                            break;
                        }
                        self.bump();
                    }
                }
                Some('\\') => self.line_continuation()?,
                Some(_) => self.scan_token()?,
            }
        }
        // Terminate a trailing logical line. A stream cut short by a bad dedent
        // already ends in the Newline of the last complete line followed by the
        // Dedents that line closed, so appending another Newline there would put
        // one AFTER the Dedents and derail the parser.
        if self.deferred.is_none()
            && !matches!(self.out.last().map(|t| &t.tok), Some(Tok::Newline) | None)
        {
            self.tok_start = self.pos;
            self.push(Tok::Newline);
        }
        while self.indents.len() > 1 {
            self.indents.pop();
            self.push(Tok::Dedent);
        }
        self.push(Tok::Eof);
        Ok(())
    }

    /// Measure a fresh logical line's indentation and emit Indent/Dedent.
    /// Returns true if the line was blank or comment-only (skip it entirely).
    fn handle_indent(&mut self) -> Result<bool, String> {
        let mut col = 0usize;
        let start = self.pos;
        loop {
            match self.peek() {
                Some(' ') => {
                    col += 1;
                    self.pos += 1;
                }
                Some('\t') => {
                    col += 8 - (col % 8);
                    self.pos += 1;
                }
                Some('\r') => {
                    self.pos += 1;
                }
                _ => break,
            }
        }
        match self.peek() {
            None => return Ok(false),
            Some('\n') => {
                self.bump();
                return Ok(true);
            }
            Some('#') => {
                while let Some(c) = self.peek() {
                    if c == '\n' {
                        break;
                    }
                    self.pos += 1;
                }
                return Ok(true);
            }
            _ => {}
        }
        let top = *self.indents.last().unwrap();
        if col > top {
            self.indents.push(col);
            self.push(Tok::Indent);
        } else if col < top {
            while col < *self.indents.last().unwrap() {
                self.indents.pop();
                self.push(Tok::Dedent);
            }
            if col != *self.indents.last().unwrap() {
                // CPython positions it just past the end of the offending line
                // (offset = its length + 1, no end offset).
                let len = self.src[start..]
                    .iter()
                    .take_while(|c| !matches!(c, '\n' | '\r'))
                    .count();
                self.deferred = Some(crate::parser::at_pos(
                    "IndentationError: unindent does not match any outer indentation level",
                    self.line,
                    len as i64 + 1,
                    self.line,
                    -1,
                ));
                return Ok(false);
            }
        }
        Ok(false)
    }

    fn scan_token(&mut self) -> Result<(), String> {
        // Record where this token begins so `push` can derive its column. The
        // scan_* helpers each emit exactly one token, so this start holds until
        // the corresponding `push`.
        self.tok_start = self.pos;
        let c = self.peek().unwrap();
        // String / prefixed string / f-string / bytes.
        if c == '"' || c == '\'' {
            return self.scan_string(String::new());
        }
        if c.is_ascii_alphabetic() || c == '_' {
            // Distinguish a string prefix (r, b, f, u and combos) from an ident.
            if let Some(consumed) = self.try_string_prefix()? {
                return self.scan_string(consumed);
            }
            return self.scan_name();
        }
        // PEP 3131: an identifier may start with any Unicode letter (`é`, `π`,
        // `变量`). Only ASCII was accepted, so every non-ASCII name was a bare
        // `SyntaxError: invalid syntax`.
        if c.is_alphabetic() {
            return self.scan_name();
        }
        if c.is_ascii_digit()
            || (c == '.' && self.peek2().map(|d| d.is_ascii_digit()).unwrap_or(false))
        {
            return self.scan_number();
        }
        self.scan_op()
    }

    /// If the identifier at `pos` is a string prefix immediately followed by a
    /// quote, consume it and return the lowercased prefix; else return None.
    fn try_string_prefix(&mut self) -> Result<Option<String>, String> {
        let save = self.pos;
        let mut pre = String::new();
        while let Some(c) = self.peek() {
            if c.is_ascii_alphabetic() && pre.len() < 2 {
                pre.push(c.to_ascii_lowercase());
                self.pos += 1;
            } else {
                break;
            }
        }
        let is_prefix = matches!(
            pre.as_str(),
            "r" | "b" | "f" | "u" | "t" | "rb" | "br" | "rf" | "fr" | "bf" | "fb" | "rt" | "tr"
        );
        if is_prefix && matches!(self.peek(), Some('"') | Some('\'')) {
            Ok(Some(pre))
        } else {
            self.pos = save;
            Ok(None)
        }
    }

    fn scan_name(&mut self) -> Result<(), String> {
        let mut s = String::new();
        while let Some(c) = self.peek() {
            if c.is_alphanumeric() || c == '_' || crate::builtins::is_other_id_continue(c) {
                s.push(c);
                self.pos += 1;
            } else {
                break;
            }
        }
        // PEP 3131: a non-ASCII identifier is NFKC-normalized once tokenized
        // (CPython's `_PyPegen_new_identifier`), so `fi` and `fi` are one name.
        // Keyword recognition has already used the raw spelling; see `Ident`.
        if s.is_ascii() {
            self.push(Tok::Name(s));
        } else {
            use unicode_normalization::UnicodeNormalization;
            let norm: String = s.nfkc().collect();
            // CPython's AST validator refuses an identifier spelling a constant
            // (`None`), whatever position it is in.
            if matches!(norm.as_str(), "None" | "True" | "False") {
                return Err(format!(
                    "ValueError: identifier field can't represent '{norm}' constant"
                ));
            }
            if crate::parser::is_keyword(&norm) || crate::parser::is_soft_keyword(&norm) {
                self.push(Tok::Ident(norm));
            } else {
                self.push(Tok::Name(norm));
            }
        }
        Ok(())
    }

    fn scan_string(&mut self, prefix: String) -> Result<(), String> {
        let is_raw = prefix.contains('r');
        let is_bytes = prefix.contains('b');
        let is_t = prefix.contains('t');
        // A t-string body scans exactly like an f-string body: same replacement
        // fields, same PEP 701 nesting, same `{{`/`}}` escapes. Only what the
        // parser BUILDS from it differs.
        let is_f = prefix.contains('f') || is_t;
        // Where the literal starts — prefix included — which is what an
        // unterminated one is reported against.
        let (start_line, start_col) = (self.line, self.tok_start - self.line_start);
        let quote = self.bump().unwrap();
        let triple = self.peek() == Some(quote) && self.peek2() == Some(quote);
        if triple {
            self.bump();
            self.bump();
        }
        // `_PyTokenizer_syntaxerror`'s wording, naming the kind of literal and
        // the line the tokenizer had reached.
        let unterminated = |lx: &Self| {
            let kind = match (triple, is_t, is_f) {
                (true, true, _) => "triple-quoted t-string",
                (true, false, true) => "triple-quoted f-string",
                (true, false, false) => "triple-quoted string",
                (false, true, _) => "t-string",
                (false, false, true) => "f-string",
                (false, false, false) => "string",
            };
            // A final newline ends the last line rather than starting another,
            // so input that runs out there was detected on the line before.
            let detected = if lx.pos >= lx.src.len() && lx.src.last() == Some(&'\n') {
                lx.line - 1
            } else {
                lx.line
            };
            lx.tok_err(
                &format!("SyntaxError: unterminated {kind} literal (detected at line {detected})"),
                start_line,
                start_col,
                start_col as i64 + 1,
            )
        };
        let mut raw = String::new();
        // For an f-string, a quote inside a `{…}` replacement field does not end
        // the literal (PEP 701 nested strings), so track replacement-field depth.
        let mut brace_depth: i32 = 0;
        loop {
            // Inside an f-string replacement field, a quote opens a NESTED string
            // literal (same or different quotes); scan it whole so its content —
            // including the outer quote char — never terminates the outer f-string.
            if is_f && brace_depth > 0 {
                if let Some(q) = self.peek() {
                    if q == '\'' || q == '"' {
                        raw.push(q);
                        self.bump();
                        let nested_triple = self.peek() == Some(q) && self.peek2() == Some(q);
                        if nested_triple {
                            raw.push(q);
                            raw.push(q);
                            self.bump();
                            self.bump();
                        }
                        loop {
                            match self.peek() {
                                None => {
                                    return Err(format!(
                                        "SyntaxError: unterminated string (line {})",
                                        self.line
                                    ))
                                }
                                Some('\\') => {
                                    raw.push('\\');
                                    self.bump();
                                    if let Some(n) = self.peek() {
                                        raw.push(n);
                                        self.bump();
                                    }
                                }
                                Some(c) if c == q => {
                                    if nested_triple {
                                        if self.peek2() == Some(q)
                                            && self.src.get(self.pos + 2).copied() == Some(q)
                                        {
                                            raw.push(q);
                                            raw.push(q);
                                            raw.push(q);
                                            self.bump();
                                            self.bump();
                                            self.bump();
                                            break;
                                        }
                                        raw.push(c);
                                        self.bump();
                                    } else {
                                        raw.push(q);
                                        self.bump();
                                        break;
                                    }
                                }
                                Some(c) => {
                                    // `bump` counts the line a newline ends.
                                    raw.push(c);
                                    self.bump();
                                }
                            }
                        }
                        continue;
                    }
                }
            }
            match self.peek() {
                None => return Err(unterminated(self)),
                Some(c) if c == quote => {
                    if triple {
                        if self.peek2() == Some(quote)
                            && self.src.get(self.pos + 2).copied() == Some(quote)
                        {
                            self.bump();
                            self.bump();
                            self.bump();
                            break;
                        } else {
                            raw.push(c);
                            self.bump();
                        }
                    } else {
                        self.bump();
                        break;
                    }
                }
                Some('\\') => {
                    // Keep escapes verbatim; decode below (raw keeps them literal).
                    raw.push('\\');
                    self.bump();
                    if let Some(n) = self.peek() {
                        raw.push(n);
                        self.bump();
                    }
                }
                // f-string replacement-field braces. `{{`/`}}` are literal braces
                // ONLY in the literal text between fields (depth 0). Inside a
                // field they are two structural braces: `f"{x:{w}}"` closes the
                // nested width field and then the outer one, and reading that
                // `}}` as an escape left the outer field open — the scan ran past
                // the closing quote and reported an unterminated string.
                Some('{') if is_f => {
                    raw.push('{');
                    self.bump();
                    if brace_depth == 0 && self.peek() == Some('{') {
                        raw.push('{');
                        self.bump();
                    } else {
                        brace_depth += 1;
                    }
                }
                Some('}') if is_f => {
                    raw.push('}');
                    self.bump();
                    if brace_depth == 0 && self.peek() == Some('}') {
                        raw.push('}');
                        self.bump();
                    } else if brace_depth > 0 {
                        brace_depth -= 1;
                    }
                }
                Some('\n') if !triple => return Err(unterminated(self)),
                Some(c) => {
                    raw.push(c);
                    self.bump();
                }
            }
        }
        if is_t {
            self.push(Tok::TString(raw, is_raw));
        } else if is_f {
            self.push(Tok::FString(raw, is_raw));
        } else if is_bytes {
            let decoded = decode_bytes_escapes(&raw, is_raw).map_err(|e| self.literal_err(e))?;
            // Each decoded code point is one byte (latin-1): `\xff` -> 0xFF, not
            // its two-byte UTF-8 encoding.
            let bytes: Vec<u8> = decoded.chars().map(|c| c as u32 as u8).collect();
            self.push(Tok::Bytes(bytes));
        } else {
            let decoded = decode_escapes(&raw, is_raw).map_err(|e| self.literal_err(e))?;
            self.push(Tok::Str(decoded));
        }
        Ok(())
    }

    fn scan_number(&mut self) -> Result<(), String> {
        let mut s = String::new();
        let mut is_float = false;
        let mut is_complex = false;
        // Radix prefixes.
        if self.peek() == Some('0') {
            if let Some(r) = self.peek2() {
                if matches!(r, 'x' | 'X' | 'o' | 'O' | 'b' | 'B') {
                    self.bump();
                    self.bump();
                    let radix = match r.to_ascii_lowercase() {
                        'x' => 16,
                        'o' => 8,
                        _ => 2,
                    };
                    let kind = match radix {
                        16 => "hexadecimal",
                        8 => "octal",
                        _ => "binary",
                    };
                    // Reported at the character at `at` (a char index), as the
                    // tokenizer's `verify_end_of_number` does.
                    let bad = |lx: &Self, at: usize| {
                        let col = at - lx.line_start;
                        lx.tok_err(
                            &format!("SyntaxError: invalid {kind} literal"),
                            lx.line,
                            col,
                            col as i64 + 1,
                        )
                    };
                    let mut digits = String::new();
                    while let Some(c) = self.peek() {
                        if c == '_' {
                            // A separator sits between two digits, or right after
                            // the prefix (`0x_f`): never last, never doubled.
                            match self.src.get(self.pos + 1) {
                                Some(n) if n.is_digit(radix) => self.pos += 1,
                                _ => return Err(bad(self, self.pos)),
                            }
                        } else if c.is_digit(radix) {
                            digits.push(c);
                            self.pos += 1;
                        } else if c.is_ascii_digit() {
                            // `0b2`, `0o8`: a decimal digit the radix lacks.
                            let col = self.pos - self.line_start;
                            return Err(self.tok_err(
                                &format!("SyntaxError: invalid digit '{c}' in {kind} literal"),
                                self.line,
                                col,
                                col as i64 + 1,
                            ));
                        } else {
                            break;
                        }
                    }
                    if digits.is_empty() {
                        return Err(bad(self, self.pos - 1));
                    }
                    match i64::from_str_radix(&digits, radix) {
                        Ok(n) => self.push(Tok::Int(n)),
                        // Overflows i64 (`0xFFFFFFFFFFFFFFFF`, a wide `0o…`/`0b…`):
                        // promote to a bignum, storing its decimal form so it takes
                        // the same `Tok::BigInt` path as an oversized decimal.
                        Err(_) => {
                            let big = num_bigint::BigInt::parse_bytes(digits.as_bytes(), radix)
                                .ok_or_else(|| {
                                    format!("SyntaxError: bad int literal (line {})", self.line)
                                })?;
                            self.push(Tok::BigInt(big.to_string()));
                        }
                    }
                    return Ok(());
                }
            }
        }
        while let Some(c) = self.peek() {
            match c {
                '0'..='9' => {
                    s.push(c);
                    self.pos += 1;
                }
                // A separator sits between two decimal digits — not after the
                // point or the exponent marker, not last, not doubled.
                '_' => {
                    let after_digit = s.ends_with(|p: char| p.is_ascii_digit());
                    let before_digit =
                        matches!(self.src.get(self.pos + 1), Some(n) if n.is_ascii_digit());
                    if !(after_digit && before_digit) {
                        let col = self.pos - self.line_start;
                        return Err(self.tok_err(
                            "SyntaxError: invalid decimal literal",
                            self.line,
                            col,
                            col as i64 + 1,
                        ));
                    }
                    self.pos += 1;
                }
                '.' => {
                    // A second `.` after the number is already a float (a
                    // decimal point or an exponent was seen) is attribute
                    // access, not part of the literal: `0.1.is_integer()` lexes
                    // as `0.1` then `.is_integer`, matching CPython.
                    if is_float {
                        break;
                    }
                    is_float = true;
                    s.push(c);
                    self.pos += 1;
                }
                'e' | 'E' => {
                    is_float = true;
                    s.push('e');
                    self.pos += 1;
                    if matches!(self.peek(), Some('+') | Some('-')) {
                        s.push(self.peek().unwrap());
                        self.pos += 1;
                    }
                }
                'j' | 'J' => {
                    is_complex = true;
                    self.pos += 1;
                    break;
                }
                _ => break,
            }
        }
        if is_complex {
            let v: f64 = s
                .parse()
                .map_err(|_| format!("SyntaxError: bad complex (line {})", self.line))?;
            self.push(Tok::Complex(v));
        } else if is_float {
            let v: f64 = s
                .parse()
                .map_err(|_| format!("SyntaxError: bad float (line {})", self.line))?;
            self.push(Tok::Float(v));
        } else {
            // `0777`: a decimal integer may not have leading zeros unless it is
            // all zeros. Underlined from the literal's start through the zeros.
            if s.len() > 1 && s.starts_with('0') && !s.trim_start_matches('0').is_empty() {
                let start = self.tok_start - self.line_start;
                let zeros = s.len() - s.trim_start_matches('0').len();
                return Err(self.tok_err(
                    "SyntaxError: leading zeros in decimal integer literals are not permitted; \
                     use an 0o prefix for octal integers",
                    self.line,
                    start,
                    (start + zeros) as i64 + 1,
                ));
            }
            // A decimal literal is converted like `int(str)` and is bounded by
            // the same `sys.get_int_max_str_digits()` (hex/octal/binary are not).
            let limit = crate::host::int_max_str_digits();
            if limit > 0 && s.len() > limit {
                let msg = crate::host::int_max_str_digits_error(limit, Some(s.len()));
                return Err(format!(
                    "SyntaxError{} - Consider hexadecimal for huge integer literals to avoid \
                     decimal conversion limits. (line {})",
                    msg.trim_start_matches("ValueError"),
                    self.line
                ));
            }
            match s.parse::<i64>() {
                Ok(n) => self.push(Tok::Int(n)),
                Err(_) => self.push(Tok::BigInt(s)),
            }
        }
        Ok(())
    }

    fn scan_op(&mut self) -> Result<(), String> {
        let rest: String = self.src[self.pos..(self.pos + 3).min(self.src.len())]
            .iter()
            .collect();
        for op in OPS3 {
            if rest.starts_with(op) {
                self.pos += 3;
                self.push(Tok::Op((*op).to_string()));
                return Ok(());
            }
        }
        let two: String = self.src[self.pos..(self.pos + 2).min(self.src.len())]
            .iter()
            .collect();
        for op in OPS2 {
            if two.starts_with(op) {
                self.pos += 2;
                self.push(Tok::Op((*op).to_string()));
                return Ok(());
            }
        }
        let c = self.bump().unwrap();
        match c {
            '(' | '[' | '{' => {
                self.depth += 1;
                self.open
                    .push((c, self.line, (self.pos - 1 - self.line_start) as u32));
                // CPython's tokenizer holds the open brackets in a fixed
                // `tok->parenstack[MAXLEVEL]` with `MAXLEVEL == 200`
                // (`Parser/lexer/state.h`), and `tok_get_normal_mode` refuses the
                // 201st open with `too many nested parentheses` — one counter
                // shared by `(`, `[` and `{`, so `([{` * 67 trips it too.
                // Without the cap a deep literal recursed the parser, the
                // compiler and the AST's own `Drop` until the interpreter
                // thread's stack ran out: `exec('('*10000)` aborted the process
                // (SIGABRT, exit 134) where CPython raises a catchable
                // `SyntaxError`.
                if self.depth > MAX_PAREN_DEPTH {
                    return Err("SyntaxError: too many nested parentheses".to_string());
                }
            }
            ')' | ']' | '}' => {
                let col = self.pos - 1 - self.line_start;
                let opener = match c {
                    ')' => '(',
                    ']' => '[',
                    _ => '{',
                };
                match self.open.pop() {
                    None => {
                        return Err(self.tok_err(
                            &format!("SyntaxError: unmatched '{c}'"),
                            self.line,
                            col,
                            col as i64 + 1,
                        ))
                    }
                    Some((o, line, _)) if o != opener => {
                        let at = if line == self.line {
                            String::new()
                        } else {
                            format!(" on line {line}")
                        };
                        return Err(self.tok_err(
                            &format!(
                                "SyntaxError: closing parenthesis '{c}' does not match \
                                 opening parenthesis '{o}'{at}"
                            ),
                            self.line,
                            col,
                            col as i64 + 1,
                        ));
                    }
                    Some(_) => {}
                }
                self.depth = (self.depth - 1).max(0)
            }
            _ => {}
        }
        if "+-*/%@&|^~<>=(){}[]:,.;".contains(c) {
            self.push(Tok::Op(c.to_string()));
            Ok(())
        } else {
            // A stray character is rejected the way CPython's tokenizer
            // reports it, positioned at that character: an ASCII one (`!`
            // outside `!=`, `$`, `?`, backtick, …) is `invalid syntax`, any
            // other is `invalid character '€' (U+20AC)`.
            let col = self.pos - 1 - self.line_start;
            let msg = if c.is_ascii() {
                "SyntaxError: invalid syntax".to_string()
            } else {
                format!("SyntaxError: invalid character '{c}' (U+{:04X})", c as u32)
            };
            Err(self.tok_err(&msg, self.line, col, col as i64 + 1))
        }
    }
}

/// Decode Python string escapes. Raw strings keep backslashes literal.
pub fn decode_escapes(raw: &str, is_raw: bool) -> Result<String, String> {
    decode_escapes_mode(raw, is_raw, false)
}

/// Escape decoding for a BYTES literal. Differs from the text form in exactly
/// the two ways CPython's `PyBytes_DecodeEscape` does: `\u`/`\U`/`\N` are not
/// escapes at all (the backslash and letter stay literal), and a short `\x`
/// reports `(value error) invalid \x escape at position N` rather than the
/// `unicodeescape` wording.
pub fn decode_bytes_escapes(raw: &str, is_raw: bool) -> Result<String, String> {
    decode_escapes_mode(raw, is_raw, true)
}

fn decode_escapes_mode(raw: &str, is_raw: bool, bytes_mode: bool) -> Result<String, String> {
    if is_raw {
        return Ok(raw.to_string());
    }
    let mut out = String::new();
    let chars: Vec<char> = raw.chars().collect();
    let mut i = 0;
    while i < chars.len() {
        if chars[i] == '\\' && i + 1 < chars.len() {
            i += 1;
            let e = chars[i];
            match e {
                'n' => out.push('\n'),
                't' => out.push('\t'),
                'r' => out.push('\r'),
                '\\' => out.push('\\'),
                '\'' => out.push('\''),
                '"' => out.push('"'),
                // Octal escape `\ooo` (1-3 octal digits).
                '0'..='7' => {
                    let mut oct = String::new();
                    oct.push(e);
                    while oct.len() < 3 && matches!(chars.get(i + 1), Some('0'..='7')) {
                        i += 1;
                        oct.push(chars[i]);
                    }
                    if let Ok(n) = u32::from_str_radix(&oct, 8) {
                        if let Some(ch) = char::from_u32(n) {
                            out.push(ch);
                        }
                    }
                }
                'a' => out.push('\u{07}'),
                'b' => out.push('\u{08}'),
                'f' => out.push('\u{0C}'),
                'v' => out.push('\u{0B}'),
                '\n' => {} // line continuation inside string
                // `\xXX`, `\uXXXX`, `\UXXXXXXXX` — a FIXED digit count. Fewer hex
                // digits than the escape demands is a `SyntaxError` in CPython,
                // not a shorter escape: pythonrs read as many as were there and
                // silently produced a different string, so `'\x2'` evaluated to
                // `'\x02'`, `'\u12'` to `'\x12'` and `'\xzz'` to `'zz'`.
                // `\u`, `\U` and `\N` are TEXT escapes only; inside a bytes
                // literal CPython leaves them as the two literal characters.
                // pythonrs decoded them anyway, so `b'ሴ'` — six bytes in
                // CPython — came out as the single byte `b'4'`.
                'u' | 'U' | 'N' if bytes_mode => {
                    out.push('\\');
                    out.push(e);
                }
                'x' | 'u' | 'U' => {
                    let want = match e {
                        'x' => 2,
                        'u' => 4,
                        _ => 8,
                    };
                    let start = byte_offset(&chars, i - 1);
                    // A bytes literal reports the same defect as a `value error`
                    // out of `PyBytes_DecodeEscape`, with a different wording and
                    // only the start position.
                    if bytes_mode {
                        let digits = chars[i + 1..]
                            .iter()
                            .take(want)
                            .take_while(|c| c.is_ascii_hexdigit())
                            .count();
                        if digits < want {
                            return Err(format!(
                                "SyntaxError: (value error) invalid \\x escape at position {start}"
                            ));
                        }
                    }
                    let digits: String = chars[i + 1..]
                        .iter()
                        .take(want)
                        .take_while(|c| c.is_ascii_hexdigit())
                        .collect();
                    if digits.len() < want {
                        // CPython's span covers the backslash, the escape letter,
                        // and however many hex digits it did manage to read.
                        return Err(unicode_escape_err(
                            start,
                            start + 1 + digits.len(),
                            EscErr::Truncated(e),
                        ));
                    }
                    let n = u32::from_str_radix(&digits, 16).unwrap_or(u32::MAX);
                    match char::from_u32(n) {
                        Some(ch) => out.push(ch),
                        // Past U+10FFFF (only reachable through `\U`).
                        None => {
                            return Err(unicode_escape_err(
                                start,
                                start + 1 + want,
                                EscErr::IllegalChar,
                            ))
                        }
                    }
                    i += want;
                }
                // Named Unicode escape `\N{NAME}` (e.g. `\N{LATIN SMALL LETTER E WITH ACUTE}`).
                'N' => {
                    // Byte offset of the `\` (positions in CPython's error are byte-based).
                    let start = byte_offset(&chars, i - 1);
                    if chars.get(i + 1) != Some(&'{') {
                        // `\N` not followed by `{` → malformed (covers just `\N`).
                        return Err(unicode_escape_err(start, start + 1, EscErr::MalformedName));
                    }
                    let name_start = i + 2;
                    let mut j = name_start;
                    while j < chars.len() && chars[j] != '}' {
                        j += 1;
                    }
                    if j >= chars.len() {
                        // No closing `}` → malformed (covers to end of the literal).
                        let end = raw.len().saturating_sub(1);
                        return Err(unicode_escape_err(start, end, EscErr::MalformedName));
                    }
                    if j == name_start {
                        // Empty `\N{}` → malformed (covers `\N{`).
                        let end = byte_offset(&chars, i + 1);
                        return Err(unicode_escape_err(start, end, EscErr::MalformedName));
                    }
                    let name: String = chars[name_start..j].iter().collect();
                    match lookup_char_name(&name) {
                        Some(ch) => {
                            out.push(ch);
                            i = j; // land on `}`; the `i += 1` below steps past it.
                        }
                        None => {
                            // Unknown name → covers `\N{NAME}` through the closing `}`.
                            let end = byte_offset(&chars, j);
                            return Err(unicode_escape_err(start, end, EscErr::UnknownName));
                        }
                    }
                }
                other => {
                    out.push('\\');
                    out.push(other);
                }
            }
            i += 1;
        } else {
            out.push(chars[i]);
            i += 1;
        }
    }
    Ok(out)
}

/// The character a `\N{name}` escape names, as CPython resolves it: the name
/// matched case-insensitively but NOT loosely — leading/trailing whitespace
/// or `_`/`-` swaps must fail. `unicode_names2` does UAX#44 loose matching,
/// so the lookup round-trips through the canonical name and requires it to
/// equal the uppercased input exactly. Shared with `re`'s `\N{...}`.
pub fn lookup_char_name(name: &str) -> Option<char> {
    let upper = name.to_ascii_uppercase();
    unicode_names2::character(&upper)
        .filter(|&ch| unicode_names2::name(ch).is_some_and(|n| n.to_string() == upper))
}

/// True if `lit` ends with an active `\N` escape lead — a trailing `N` preceded by
/// an odd run of backslashes. Used by the f-string parser so `\N{NAME}`'s braces are
/// treated as part of the named-Unicode escape rather than a replacement field.
/// Always false for raw strings (backslashes are literal there).
pub fn ends_with_named_escape_lead(lit: &str, is_raw: bool) -> bool {
    if is_raw {
        return false;
    }
    let chars: Vec<char> = lit.chars().collect();
    if chars.last() != Some(&'N') {
        return false;
    }
    let mut backslashes = 0;
    let mut idx = chars.len() - 1;
    while idx > 0 && chars[idx - 1] == '\\' {
        backslashes += 1;
        idx -= 1;
    }
    backslashes % 2 == 1
}

/// Byte offset of the char at `idx` within a `char` slice.
fn byte_offset(chars: &[char], idx: usize) -> usize {
    chars[..idx].iter().map(|c| c.len_utf8()).sum()
}

/// Which `unicodeescape` failure to report. The four spellings are CPython's own
/// (`Objects/unicodeobject.c`, `unicode_decode_call_errorhandler_writer`
/// callers), reproduced verbatim.
pub(crate) enum EscErr {
    /// `\N{...}` that is not a well-formed named escape.
    MalformedName,
    /// `\N{...}` whose name is not in the Unicode database.
    UnknownName,
    /// `\x`/`\u`/`\U` with fewer hex digits than it requires; carries the escape
    /// letter so the message names the right form.
    Truncated(char),
    /// A `\U` code point past U+10FFFF.
    IllegalChar,
}

/// Format CPython's `unicodeescape` error. `start`/`end` are the inclusive byte
/// positions CPython reports.
fn unicode_escape_err(start: usize, end: usize, kind: EscErr) -> String {
    let truncated;
    let reason: &str = match kind {
        EscErr::UnknownName => "unknown Unicode character name",
        EscErr::MalformedName => "malformed \\N character escape",
        EscErr::IllegalChar => "illegal Unicode character",
        EscErr::Truncated(e) => {
            let form = match e {
                'x' => "\\xXX",
                'u' => "\\uXXXX",
                _ => "\\UXXXXXXXX",
            };
            truncated = format!("truncated {form} escape");
            &truncated
        }
    };
    // CPython raises this as a `SyntaxError` whose `str()` is the parenthesised
    // `(unicode error) …` text, so the reported line reads
    // `SyntaxError: (unicode error) …`. The prefix was missing here, and the
    // escape-decoding errors were the only lexer diagnostics printed without an
    // exception name in front of them.
    format!(
        "SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position {}-{}: {}",
        start, end, reason
    )
}