rubylang 0.1.18

Ruby as a fusevm frontend: lexer, parser, and compiler to fusevm::Chunk on a RubyHost heap — the first compiled standalone Ruby 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
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
//! Ruby lexer.
//!
//! Produces a flat `Vec<Token>` the parser consumes. Newlines are significant in
//! Ruby (they terminate statements) so they surface as `Token::Newline` rather
//! than being skipped; the parser treats a newline and a `;` identically. Line
//! continuation with a trailing `\`, and newlines right after a binary operator
//! or a `,`/`.`, are swallowed here so the parser never sees a spurious
//! terminator mid-expression — matching Ruby's own "expression clearly
//! continues" rule.
//!
//! Heredocs (`<<END`, `<<~SQL`, `<<-EOT`, `<<'RAW'`), regex literals, `?c`
//! character literals, and `%w[]`/`%i[]` word/symbol arrays are all lexed.
//! Double-quoted `#{…}` interpolation IS handled — the interpolating scan is
//! done in the parser from the raw string body this lexer captures.

use std::fmt;

/// A lexical token with its source line (1-based) for diagnostics and whether
/// whitespace immediately preceded it — Ruby needs the space to disambiguate
/// `foo(x)` (call) from `foo (x)` (command arg) and `h[k]` (index) from
/// `puts [x]` (command arg).
#[derive(Debug, Clone, PartialEq)]
pub struct Token {
    pub kind: Tok,
    pub line: u32,
    pub space: bool,
}

#[derive(Debug, Clone, PartialEq)]
pub enum Tok {
    Int(i64),
    Float(f64),
    /// Raw string body plus whether it was double-quoted (interpolation allowed).
    Str(String, bool),
    /// A regex literal: `/pattern/flags` — (pattern, flags).
    Regex(String, String),
    Symbol(String),
    /// A double-quoted symbol with `#{…}` interpolation: `:"pre_#{name}"`. The
    /// raw body (escapes and `#{…}` intact) is re-scanned by the parser, which
    /// builds an interpolated string and symbolizes it.
    DSymbol(String),
    Ident(String),
    Const(String), // capitalized identifier
    IVar(String),  // @foo
    CVar(String),  // @@foo
    GVar(String),  // $foo
    Keyword(String),
    Op(String),
    Newline,
    Semicolon,
    Eof,
}

impl fmt::Display for Tok {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Tok::Int(n) => write!(f, "{n}"),
            Tok::Float(x) => write!(f, "{x}"),
            Tok::Str(s, _) => write!(f, "\"{s}\""),
            Tok::Regex(s, fl) => write!(f, "/{s}/{fl}"),
            Tok::Symbol(s) | Tok::DSymbol(s) => write!(f, ":{s}"),
            Tok::Ident(s) | Tok::Const(s) | Tok::Keyword(s) => write!(f, "{s}"),
            Tok::IVar(s) => write!(f, "@{s}"),
            Tok::CVar(s) => write!(f, "@@{s}"),
            Tok::GVar(s) => write!(f, "${s}"),
            Tok::Op(s) => write!(f, "{s}"),
            Tok::Newline => write!(f, "\\n"),
            Tok::Semicolon => write!(f, ";"),
            Tok::Eof => write!(f, "<eof>"),
        }
    }
}

/// Whether byte `c` can start an identifier. MRI's `is_identchar` counts every
/// non-ASCII byte as an identifier character (`café = 1`, `:Ωmega`, `@ñ`), so a
/// UTF-8 lead or continuation byte never ends or rejects a name.
fn ident_start(c: u8) -> bool {
    c.is_ascii_alphabetic() || c == b'_' || !c.is_ascii()
}

/// Whether byte `c` can continue an identifier (see [`ident_start`]).
fn ident_byte(c: u8) -> bool {
    ident_start(c) || c.is_ascii_digit()
}

pub(crate) const KEYWORDS: &[&str] = &[
    "def", "end", "if", "elsif", "else", "unless", "while", "until", "for", "in", "do", "return",
    "break", "next", "yield", "then", "case", "when", "nil", "true", "false", "and", "or", "not",
    "class", "module", "begin", "rescue", "ensure", "self", "super", "retry", "redo", "alias",
];

/// Tokenize `src`. Returns an error string on an unterminated string or an
/// unexpected byte.
/// A heredoc marker seen mid-line whose body is collected once the line ends.
struct Heredoc {
    delim: String,
    /// `<<~` — strip the common leading indentation from the body.
    squiggly: bool,
    /// `<<-` or `<<~` — the terminator line may be indented.
    indent_term: bool,
    /// Whether the body interpolates (`<<END`/`<<"END"`/`<<~`, but not `<<'END'`).
    interp: bool,
    /// Index in the token stream of the placeholder `Str` token to fill in.
    tok_idx: usize,
}

/// Collect a heredoc body starting at byte offset `start` (the first char after
/// the marker line's newline) up to a line equal to `delim`. Returns the raw
/// body, the offset just past the terminator line, and the number of newlines
/// consumed. `indent_term` allows the terminator to have leading whitespace.
fn collect_heredoc_body(
    b: &[u8],
    start: usize,
    delim: &str,
    indent_term: bool,
) -> (String, usize, u32) {
    let mut body = String::new();
    let mut pos = start;
    let mut lines = 0u32;
    while pos < b.len() {
        let line_start = pos;
        while pos < b.len() && b[pos] != b'\n' {
            pos += 1;
        }
        let line = std::str::from_utf8(&b[line_start..pos]).unwrap_or("");
        let trimmed = if indent_term { line.trim_start() } else { line };
        // Consume the newline (if any) that ends this line.
        let had_nl = pos < b.len();
        if had_nl {
            pos += 1;
            lines += 1;
        }
        if trimmed == delim {
            return (body, pos, lines);
        }
        body.push_str(line);
        body.push('\n');
    }
    // Unterminated: treat the rest of the input as the body.
    (body, pos, lines)
}

/// `<<~` squiggly heredoc: strip the least-indented line's leading whitespace
/// from every line.
fn strip_squiggly(body: &str) -> String {
    // Indentation is measured in columns: a space is one, a tab advances to the
    // next multiple of 8 (as MRI's `dedent_string` does).
    let width_of = |l: &str| -> usize {
        let mut col = 0;
        for c in l.chars() {
            match c {
                ' ' => col += 1,
                '\t' => col = (col / 8 + 1) * 8,
                _ => break,
            }
        }
        col
    };
    let indent = body
        .lines()
        .filter(|l| !l.trim().is_empty())
        .map(width_of)
        .min()
        .unwrap_or(0);
    let mut out = String::new();
    for line in body.split_inclusive('\n') {
        let content = line.strip_suffix('\n').unwrap_or(line);
        // Remove leading whitespace until `indent` columns are gone; a tab that
        // would overshoot is kept whole.
        let mut col = 0;
        let mut cut = 0;
        for c in content.chars() {
            let next = match c {
                ' ' => col + 1,
                '\t' => (col / 8 + 1) * 8,
                _ => break,
            };
            if next > indent {
                break;
            }
            col = next;
            cut += c.len_utf8();
        }
        out.push_str(&content[cut..]);
        if line.ends_with('\n') {
            out.push('\n');
        }
    }
    out
}

/// Whether the next non-blank line (skipping whitespace, blank lines, and
/// comments) begins with a `.method` call — a leading-dot chain continuation.
/// `..`/`...` (a range) does not count.
fn next_line_leading_dot(b: &[u8], mut j: usize) -> bool {
    loop {
        while j < b.len() && matches!(b[j], b' ' | b'\t' | b'\r' | b'\n') {
            j += 1;
        }
        // Skip a comment line.
        if j < b.len() && b[j] == b'#' {
            while j < b.len() && b[j] != b'\n' {
                j += 1;
            }
            continue;
        }
        break;
    }
    b.get(j) == Some(&b'.') && b.get(j + 1) != Some(&b'.')
}

/// Whether a `<<` here begins a heredoc rather than a left-shift: true after a
/// value is NOT on the stack (start of expression, after an operator/`(`/`,`),
/// or whenever an unambiguous form (`<<~`/`<<-`/`<<"`/`<<'`) is used.
fn heredoc_here(out: &[Token], after: &[u8], space_before: bool) -> bool {
    // `<<~`/`<<-` open a heredoc only when a delimiter follows (an identifier or
    // a quote); `5<<-1` is a left shift by -1. Whether a value precedes is
    // decided by the position test below, which governs the unambiguous forms
    // too (`x<<~b` is a shift when no space separates it from a value).
    let squiggly = matches!(after.first(), Some(b'~') | Some(b'-'));
    let after_flag = if squiggly { &after[1..] } else { after };
    let quoted = matches!(after_flag.first(), Some(b'"') | Some(b'\'') | Some(b'`'));
    let bare_ok = if squiggly {
        matches!(after_flag.first(), Some(c) if c.is_ascii_alphabetic() || *c == b'_')
    } else {
        // Quoted (`<<"X"`/`<<'X'`) or bare uppercase/`_` (`<<END`) delimiters
        // are the only heredoc candidates; `<< x` is a left shift.
        matches!(after_flag.first(), Some(c) if c.is_ascii_uppercase() || *c == b'_')
    };
    if !quoted && !bare_ok {
        return false;
    }
    // Position test. A heredoc sits where a value would: at expression start
    // (nothing before, or after an operator/keyword), or as a command argument
    // (`puts <<"EOF"` — a space before the `<<` and none after). After a value
    // token with NO preceding space, `<<` is the shift/append operator, so
    // `s<<"b"` and `arr<<CONST` are shifts, not heredocs.
    match out.iter().rev().find(|t| t.kind != Tok::Newline) {
        None => true,
        Some(t) => match &t.kind {
            Tok::Op(o) if o != ")" && o != "]" && o != "}" => true,
            Tok::Keyword(_) => true,
            _ => space_before,
        },
    }
}

pub fn lex(src: &str) -> Result<Vec<Token>, String> {
    let b = src.as_bytes();
    let mut i = 0usize;
    let mut line = 1u32;
    let mut out: Vec<Token> = Vec::new();
    // Whether whitespace has been seen since the last emitted token.
    let mut sp = true;
    // Heredoc markers seen on the current line, whose bodies are collected when
    // the line's newline is reached.
    let mut pending: Vec<Heredoc> = Vec::new();

    // Whether a newline here continues the previous expression (last real token
    // is a binary op / comma / dot / open bracket / `=`).
    let continues = |out: &[Token]| -> bool {
        let mut iter = out.iter().rev().filter(|t| t.kind != Tok::Newline);
        match iter.next() {
            None => true,
            Some(t) => {
                // A block-introducing keyword (`then`/`in`/`do`/…) normally
                // continues onto the next line, EXCEPT when it is a method name —
                // `def in` / `def then` (prism/node.rb) is a no-param def whose
                // body is on the next line, so the newline must be kept.
                if matches!(&t.kind, Tok::Keyword(k)
                    if matches!(k.as_str(), "and"|"or"|"not"|"if"|"unless"|"while"|"until"|"do"|"then"|"else"|"in"))
                {
                    return !matches!(
                        iter.next().map(|p| &p.kind),
                        Some(Tok::Keyword(k)) if k == "def"
                    );
                }
                // `!` and `~` are prefix-only operators: they never end a line
                // that continues onto the next, but they *can* be a bare method
                // name (`def !`, `def ~`), so a trailing one must keep its newline.
                matches!(&t.kind,
                Tok::Op(o) if o != ")" && o != "]" && o != "}" && o != "!" && o != "~" )
            }
        }
    };

    while i < b.len() {
        let c = b[i];
        match c {
            b' ' | b'\t' | b'\r' => {
                sp = true;
                i += 1;
            }
            b'\\' if i + 1 < b.len() && b[i + 1] == b'\n' => {
                // explicit line continuation
                sp = true;
                line += 1;
                i += 2;
            }
            b'\n' => {
                // A newline is swallowed when the previous line clearly continues
                // (trailing operator) OR the next line starts with `.method` (a
                // leading-dot method chain).
                if !continues(&out) && !next_line_leading_dot(b, i + 1) {
                    out.push(Token {
                        kind: Tok::Newline,
                        line,
                        space: core::mem::take(&mut sp),
                    });
                }
                sp = true;
                line += 1;
                i += 1;
                // Collect the bodies of any heredocs opened on this line, in
                // order, from the lines that follow.
                if !pending.is_empty() {
                    for hd in pending.drain(..) {
                        let (raw, next, lines) =
                            collect_heredoc_body(b, i, &hd.delim, hd.indent_term);
                        let body = if hd.squiggly {
                            strip_squiggly(&raw)
                        } else {
                            raw
                        };
                        out[hd.tok_idx].kind = Tok::Str(body, hd.interp);
                        i = next;
                        line += lines;
                    }
                }
            }
            // `=begin` … `=end` block comment: both markers must sit at the start
            // of a line (column 0). Everything between is skipped (prism/node.rb
            // and many generated gem files open with one).
            b'=' if (i == 0 || b[i - 1] == b'\n') && src[i..].starts_with("=begin") => {
                loop {
                    // Advance to the next line.
                    while i < b.len() && b[i] != b'\n' {
                        i += 1;
                    }
                    if i >= b.len() {
                        break;
                    }
                    i += 1; // consume '\n'
                    line += 1;
                    if src[i..].starts_with("=end") {
                        // Skip the `=end` line entirely.
                        while i < b.len() && b[i] != b'\n' {
                            i += 1;
                        }
                        break;
                    }
                }
                sp = true;
            }
            b'#' => {
                while i < b.len() && b[i] != b'\n' {
                    i += 1;
                }
                sp = true;
            }
            b';' => {
                out.push(Token {
                    kind: Tok::Semicolon,
                    line,
                    space: core::mem::take(&mut sp),
                });
                i += 1;
            }
            b'0'..=b'9' => {
                // Radix-prefixed integer literals: `0b1010` (binary), `0o17` /
                // `017` (octal), `0xff` (hex), `0d99` (decimal). A leading `0`
                // followed by octal digits is octal, matching Ruby.
                if b[i] == b'0' && i + 1 < b.len() {
                    let (radix, skip) = match b[i + 1] {
                        b'b' | b'B' => (2u32, 2),
                        b'o' | b'O' => (8, 2),
                        b'x' | b'X' => (16, 2),
                        b'd' | b'D' => (10, 2),
                        c if c.is_ascii_digit() => (8, 1),
                        _ => (0, 0),
                    };
                    if radix != 0 {
                        let dstart = i + skip;
                        let mut j = dstart;
                        while j < b.len() {
                            let c = b[j] as char;
                            if c == '_' || c.is_digit(radix) {
                                j += 1;
                            } else {
                                break;
                            }
                        }
                        let digits: String = src[dstart..j].chars().filter(|c| *c != '_').collect();
                        let this_sp = core::mem::take(&mut sp);
                        match i64::from_str_radix(&digits, radix) {
                            Ok(n) => out.push(Token {
                                kind: Tok::Int(n),
                                line,
                                space: this_sp,
                            }),
                            // Overflows i64 — emit `"<digits>".to_i(<radix>)` so it
                            // parses as a BigInt at runtime (Ruby Integers auto-
                            // promote past the i64 range; `0x8000000000000000`).
                            Err(_) => {
                                let toks = [
                                    Tok::Str(digits.clone(), false),
                                    Tok::Op(".".into()),
                                    Tok::Ident("to_i".into()),
                                    Tok::Op("(".into()),
                                    Tok::Int(radix as i64),
                                    Tok::Op(")".into()),
                                ];
                                for (k, kind) in toks.into_iter().enumerate() {
                                    out.push(Token {
                                        kind,
                                        line,
                                        space: k == 0 && this_sp,
                                    });
                                }
                            }
                        }
                        i = j;
                        continue;
                    }
                }
                let start = i;
                while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'_') {
                    i += 1;
                }
                let mut is_float = false;
                if i + 1 < b.len() && b[i] == b'.' && b[i + 1].is_ascii_digit() {
                    is_float = true;
                    i += 1;
                    while i < b.len() && (b[i].is_ascii_digit() || b[i] == b'_') {
                        i += 1;
                    }
                }
                if i < b.len() && (b[i] == b'e' || b[i] == b'E') {
                    is_float = true;
                    i += 1;
                    if i < b.len() && (b[i] == b'+' || b[i] == b'-') {
                        i += 1;
                    }
                    while i < b.len() && b[i].is_ascii_digit() {
                        i += 1;
                    }
                }
                let raw: String = src[start..i].chars().filter(|c| *c != '_').collect();
                // A `r` / `i` / `ri` suffix on a NUMBER (not the start of an
                // identifier). `4r` is `Rational(4)`, `3i` is `Complex(0, 3)`,
                // and `2ri` is both. On a decimal the rational is EXACT — MRI's
                // `0.1r` is `(1/10)`, not the nearest double — so it is built
                // from the digits rather than through an f64.
                let num_suffix = |at: usize| -> Option<(&'static str, usize)> {
                    let two = b.get(at) == Some(&b'r') && b.get(at + 1) == Some(&b'i');
                    let (tag, len): (&'static str, usize) = if two {
                        ("ri", 2)
                    } else if b.get(at) == Some(&b'r') {
                        ("r", 1)
                    } else if b.get(at) == Some(&b'i') {
                        ("i", 1)
                    } else {
                        return None;
                    };
                    if b.get(at + len)
                        .is_some_and(|c| c.is_ascii_alphanumeric() || *c == b'_')
                    {
                        return None;
                    }
                    Some((tag, len))
                };
                if is_float {
                    // An exponent form takes no suffix (`1e2r` is a SyntaxError
                    // in MRI), so only a plain decimal converts exactly.
                    let plain = !raw.contains(['e', 'E']);
                    if let Some((tag, len)) = num_suffix(i).filter(|_| plain) {
                        {
                            let (int_part, frac) = raw.split_once('.').unwrap_or((&raw, ""));
                            let den = 10i64.pow(frac.len() as u32);
                            let digits = format!("{int_part}{frac}");
                            let num: i64 = digits
                                .parse()
                                .map_err(|_| format!("bad rational literal: {raw}"))?;
                            i += len;
                            let this_sp = core::mem::take(&mut sp);
                            let mut synth = vec![
                                Tok::Ident("Rational".into()),
                                Tok::Op("(".into()),
                                Tok::Int(num),
                                Tok::Op(",".into()),
                                Tok::Int(den),
                                Tok::Op(")".into()),
                            ];
                            if tag != "r" {
                                // `0.5i` is `Complex(0, 0.5)`; `0.5ri` is
                                // `Complex(0, Rational(1, 2))`.
                                if tag == "i" {
                                    synth = vec![Tok::Float(
                                        raw.parse().map_err(|_| format!("bad float: {raw}"))?,
                                    )];
                                }
                                let mut wrapped = vec![
                                    Tok::Ident("Complex".into()),
                                    Tok::Op("(".into()),
                                    Tok::Int(0),
                                    Tok::Op(",".into()),
                                ];
                                wrapped.extend(synth);
                                wrapped.push(Tok::Op(")".into()));
                                synth = wrapped;
                            }
                            for (k, kind) in synth.into_iter().enumerate() {
                                out.push(Token {
                                    kind,
                                    line,
                                    space: if k == 0 { this_sp } else { false },
                                });
                            }
                            continue;
                        }
                    }
                    let x: f64 = raw.parse().map_err(|_| format!("bad float: {raw}"))?;
                    out.push(Token {
                        kind: Tok::Float(x),
                        line,
                        space: core::mem::take(&mut sp),
                    });
                } else {
                    let n_res = raw.parse::<i64>();
                    // A trailing `r`/`i` (not part of an identifier) makes a
                    // Rational (`4r` → `Rational(4)`) or imaginary Complex
                    // (`3i` → `Complex(0, 3)`) literal, desugared into a call.
                    let suffix = num_suffix(i);
                    let this_sp = core::mem::take(&mut sp);
                    let synth: Vec<Tok> = match (suffix.map(|(t, _)| t), n_res) {
                        (Some("r"), Ok(n)) => vec![
                            Tok::Ident("Rational".into()),
                            Tok::Op("(".into()),
                            Tok::Int(n),
                            Tok::Op(")".into()),
                        ],
                        (Some("i"), Ok(n)) => vec![
                            Tok::Ident("Complex".into()),
                            Tok::Op("(".into()),
                            Tok::Int(0),
                            Tok::Op(",".into()),
                            Tok::Int(n),
                            Tok::Op(")".into()),
                        ],
                        // `2ri` — an imaginary part that is itself a Rational.
                        (Some("ri"), Ok(n)) => vec![
                            Tok::Ident("Complex".into()),
                            Tok::Op("(".into()),
                            Tok::Int(0),
                            Tok::Op(",".into()),
                            Tok::Ident("Rational".into()),
                            Tok::Op("(".into()),
                            Tok::Int(n),
                            Tok::Op(")".into()),
                            Tok::Op(")".into()),
                        ],
                        (_, Ok(n)) => vec![Tok::Int(n)],
                        // Overflows i64 — emit `"<digits>".to_i(10)` so it parses
                        // as a BigInt at runtime (large decimal literals).
                        (_, Err(_)) => vec![
                            Tok::Str(raw.clone(), false),
                            Tok::Op(".".into()),
                            Tok::Ident("to_i".into()),
                            Tok::Op("(".into()),
                            Tok::Int(10),
                            Tok::Op(")".into()),
                        ],
                    };
                    if let Some((_, len)) = suffix {
                        i += len;
                    }
                    for (k, kind) in synth.into_iter().enumerate() {
                        out.push(Token {
                            kind,
                            line,
                            space: if k == 0 { this_sp } else { false },
                        });
                    }
                }
            }
            // A backtick is a command string unless it names the `` ` `` method
            // (`def `(c)`, `obj.`(c)`).
            b'"' | b'\'' | b'`' if c != b'`' || !method_name_pos(&out) => {
                let quote = c;
                let dq = quote != b'\'';
                i += 1;
                let mut s = String::new();
                loop {
                    if i >= b.len() {
                        return Err(format!("unterminated string at line {line}"));
                    }
                    let ch = b[i];
                    if ch == quote {
                        i += 1;
                        break;
                    }
                    if ch == b'\\' && i + 1 < b.len() {
                        // Keep escapes raw for double-quoted (the parser's interp
                        // scan decodes them); decode the essentials for single.
                        let n = b[i + 1];
                        // The escaped character is copied whole: it may be a
                        // multi-byte one (`"\é"`).
                        let cl = utf8_len(n);
                        match n {
                            b'\'' if !dq => s.push('\''),
                            b'\\' if !dq => s.push('\\'),
                            _ => {
                                s.push('\\');
                                s.push_str(&src[i + 1..i + 1 + cl]);
                            }
                        }
                        i += 1 + cl;
                        continue;
                    }
                    // A `#{ … }` interpolation in a double-quoted string is copied
                    // verbatim (the parser re-scans it), balancing braces and any
                    // nested string literals so an inner `"` doesn't end us.
                    if dq && ch == b'#' && i + 1 < b.len() && b[i + 1] == b'{' {
                        s.push('#');
                        s.push('{');
                        i += 2;
                        let mut depth = 1u32;
                        // Track the previous significant byte so a `/` can be
                        // classified as a regex start vs. a division operator.
                        // `#{` opens an expression context, so a leading `/` is a
                        // regex. Regex-start context = expression start or after an
                        // operator/opening bracket.
                        let mut last: u8 = b'{';
                        while i < b.len() && depth > 0 {
                            let d = b[i];
                            match d {
                                b'{' => depth += 1,
                                b'}' => depth -= 1,
                                b'"' | b'\'' => {
                                    // skip a nested string literal wholesale
                                    let q = d;
                                    s.push(q as char);
                                    i += 1;
                                    while i < b.len() && b[i] != q {
                                        if b[i] == b'\\' && i + 1 < b.len() {
                                            s.push('\\');
                                            let cl = utf8_len(b[i + 1]);
                                            s.push_str(&src[i + 1..i + 1 + cl]);
                                            i += 1 + cl;
                                            continue;
                                        }
                                        if b[i] == b'\n' {
                                            line += 1;
                                        }
                                        let cl = utf8_len(b[i]);
                                        s.push_str(&src[i..i + cl]);
                                        i += cl;
                                    }
                                    if i < b.len() {
                                        s.push(q as char);
                                        i += 1;
                                    }
                                    last = q;
                                    continue;
                                }
                                b'/' if matches!(
                                    last,
                                    b'{' | b'('
                                        | b'['
                                        | b','
                                        | b';'
                                        | b':'
                                        | b'='
                                        | b'<'
                                        | b'>'
                                        | b'!'
                                        | b'&'
                                        | b'|'
                                        | b'^'
                                        | b'~'
                                        | b'+'
                                        | b'-'
                                        | b'*'
                                        | b'/'
                                        | b'%'
                                        | b'?'
                                ) =>
                                {
                                    // Skip a regex literal wholesale: quotes inside
                                    // it are literal, not string delimiters. A `/`
                                    // inside a `[...]` character class is literal too.
                                    s.push('/');
                                    i += 1;
                                    let mut in_class = false;
                                    while i < b.len() {
                                        let c = b[i];
                                        if c == b'\\' && i + 1 < b.len() {
                                            s.push('\\');
                                            let cl = utf8_len(b[i + 1]);
                                            s.push_str(&src[i + 1..i + 1 + cl]);
                                            i += 1 + cl;
                                            continue;
                                        }
                                        if c == b'[' {
                                            in_class = true;
                                        } else if c == b']' {
                                            in_class = false;
                                        } else if c == b'/' && !in_class {
                                            break;
                                        }
                                        if c == b'\n' {
                                            line += 1;
                                        }
                                        let cl = utf8_len(c);
                                        s.push_str(&src[i..i + cl]);
                                        i += cl;
                                    }
                                    if i < b.len() {
                                        s.push('/');
                                        i += 1;
                                    }
                                    // Regex flags (imxounse…).
                                    while i < b.len() && b[i].is_ascii_alphabetic() {
                                        s.push(b[i] as char);
                                        i += 1;
                                    }
                                    last = b'/';
                                    continue;
                                }
                                b'\n' => line += 1,
                                _ => {}
                            }
                            if depth == 0 {
                                s.push('}');
                                i += 1;
                                break;
                            }
                            if !d.is_ascii_whitespace() {
                                last = d;
                            }
                            let cl = utf8_len(d);
                            s.push_str(&src[i..i + cl]);
                            i += cl;
                        }
                        continue;
                    }
                    if ch == b'\n' {
                        line += 1;
                    }
                    // advance one UTF-8 char
                    let clen = utf8_len(ch);
                    s.push_str(&src[i..i + clen]);
                    i += clen;
                }
                if quote == b'`' {
                    push_xstring(&mut out, Tok::Str(s, true), line, core::mem::take(&mut sp));
                    continue;
                }
                out.push(Token {
                    kind: Tok::Str(s, dq),
                    line,
                    space: core::mem::take(&mut sp),
                });
            }
            b'@' => {
                i += 1;
                // `@@name` is a class variable; `@name` an instance variable.
                let class_var = i < b.len() && b[i] == b'@';
                if class_var {
                    i += 1;
                }
                let start = i;
                while i < b.len() && ident_byte(b[i]) {
                    i += 1;
                }
                let name = src[start..i].to_string();
                out.push(Token {
                    kind: if class_var {
                        Tok::CVar(name)
                    } else {
                        Tok::IVar(name)
                    },
                    line,
                    space: core::mem::take(&mut sp),
                });
            }
            b'$' => {
                i += 1;
                let start = i;
                // Special single-punctuation globals: `$~` (last MatchData),
                // `$&` (whole match), `` $` `` (pre-match), `$'` (post-match),
                // `$+` (last group), `$,` (output field separator), `$\` (output
                // record separator), `$;` (input field separator), `$/` (input
                // record separator), `$!` (last error), `$:` (load path, alias of
                // `$LOAD_PATH`), `$"` (loaded features, alias of
                // `$LOADED_FEATURES`). Otherwise an alphanumeric/underscore name.
                // Option globals `$-w` (warnings), `$-v`, `$-d`, `$-i`, `$-a`,
                // `$-l`, `$-p`, `$-F`, `$-0`, `$-W` — `$-` plus one more char.
                if i + 1 < b.len() && b[i] == b'-' {
                    i += 2;
                } else if i < b.len()
                    && matches!(
                        b[i],
                        // match/output/input-related punctuation globals …
                        b'~' | b'&' | b'`' | b'\'' | b'+' | b',' | b'\\' | b';' | b'/' | b'!'
                            | b':' | b'"'
                        // … plus `$?` (last process status), `$$` (pid), `$*`
                        // (ARGV), `$@` (last backtrace), `$<` (ARGF), `$>` (stdout).
                            | b'?' | b'$' | b'*' | b'@' | b'<' | b'>'
                    )
                {
                    i += 1;
                } else {
                    while i < b.len() && ident_byte(b[i]) {
                        i += 1;
                    }
                }
                out.push(Token {
                    kind: Tok::GVar(src[start..i].to_string()),
                    line,
                    space: core::mem::take(&mut sp),
                });
            }
            // `%q(…)` / `%Q(…)` / `%r{…}flags` / `%s(…)` percent literals. The
            // explicit type letter is unambiguous (never the modulo operator);
            // the delimiter is any following punctuation, with `()`/`{}`/`[]`/
            // `<>` nesting. `%q` is single-quoted (no interpolation), `%Q` is
            // double-quoted, `%r` is a Regexp, `%s` is a Symbol.
            b'%' if i + 2 < b.len()
                && matches!(b[i + 1], b'q' | b'Q' | b'r' | b's' | b'x')
                && !b[i + 2].is_ascii_alphanumeric()
                && !matches!(b[i + 2], b' ' | b'\t' | b'\n' | b'=')
                && !method_name_pos(&out) =>
            {
                let letter = b[i + 1];
                let open = b[i + 2];
                let close = match open {
                    b'[' => b']',
                    b'(' => b')',
                    b'{' => b'}',
                    b'<' => b'>',
                    other => other,
                };
                i += 3;
                let start = i;
                let mut depth = 1u32;
                while i < b.len() {
                    if b[i] == b'\\' && i + 1 < b.len() {
                        i += 2; // an escaped char is never a delimiter
                        continue;
                    }
                    if b[i] == b'\n' {
                        line += 1;
                    }
                    if b[i] == open && open != close {
                        depth += 1;
                    } else if b[i] == close {
                        depth -= 1;
                        if depth == 0 {
                            break;
                        }
                    }
                    i += 1;
                }
                let body = src[start..i.min(b.len())].to_string();
                i += 1; // consume the closing delimiter
                let kind = match letter {
                    b'q' => Tok::Str(body, false),
                    b'Q' => Tok::Str(body, true),
                    b's' => Tok::Symbol(body),
                    b'x' => {
                        push_xstring(
                            &mut out,
                            Tok::Str(body, true),
                            line,
                            core::mem::take(&mut sp),
                        );
                        continue;
                    }
                    _ => {
                        // `%r{…}` — collect trailing regex flags.
                        let fstart = i;
                        while i < b.len() && matches!(b[i], b'i' | b'm' | b'x' | b'o' | b'u' | b'n')
                        {
                            i += 1;
                        }
                        Tok::Regex(body, src[fstart..i].to_string())
                    }
                };
                out.push(Token {
                    kind,
                    line,
                    space: core::mem::take(&mut sp),
                });
            }
            // `%w[…]` / `%i[…]` word/symbol arrays → synthetic `[ … ]` tokens so
            // the parser handles them as ordinary array literals.
            b'%' if i + 2 < b.len()
                && matches!(b[i + 1], b'w' | b'i' | b'W' | b'I')
                && matches!(b[i + 2], b'[' | b'(' | b'{' | b'<' | b'|')
                && !method_name_pos(&out) =>
            {
                let symbols = matches!(b[i + 1], b'i' | b'I');
                // The uppercase forms (`%W`/`%I`) interpolate like a
                // double-quoted string; the lowercase ones are literal.
                let interp = matches!(b[i + 1], b'W' | b'I');
                let open = b[i + 2];
                let close = match open {
                    b'[' => b']',
                    b'(' => b')',
                    b'{' => b'}',
                    b'<' => b'>',
                    other => other,
                };
                i += 3;
                let start = i;
                let mut depth = 1u32;
                while i < b.len() {
                    if b[i] == b'\\' && i + 1 < b.len() {
                        // An escaped character never delimits or nests.
                        if b[i + 1] == b'\n' {
                            line += 1;
                        }
                        i += 2;
                        continue;
                    }
                    if b[i] == b'\n' {
                        line += 1;
                    }
                    if b[i] == open && open != close {
                        depth += 1;
                    } else if b[i] == close {
                        depth -= 1;
                        if depth == 0 {
                            break;
                        }
                    }
                    i += 1;
                }
                let body = &src[start..i.min(b.len())];
                i += 1; // consume the closing delimiter
                let words = percent_words(body, interp, open, close);
                out.push(Token {
                    kind: Tok::Op("[".into()),
                    line,
                    space: core::mem::take(&mut sp),
                });
                for (idx, w) in words.iter().enumerate() {
                    if idx > 0 {
                        out.push(Token {
                            kind: Tok::Op(",".into()),
                            line,
                            space: false,
                        });
                    }
                    let kind = match (symbols, interp) {
                        (true, false) => Tok::Symbol(w.clone()),
                        (true, true) => Tok::DSymbol(w.clone()),
                        (false, i) => Tok::Str(w.clone(), i),
                    };
                    out.push(Token {
                        kind,
                        line,
                        space: false,
                    });
                }
                out.push(Token {
                    kind: Tok::Op("]".into()),
                    line,
                    space: false,
                });
            }
            // Bare `%(…)` / `%{…}` / `%[…]` / `%<…>` — a double-quoted string
            // (same as `%Q`). Only in value / command-argument position (see
            // `percent_string_start`), so the binary modulo operator (`a % b`,
            // `10 %(3)`, `v % 3`) is left to the operator arm. Requires the
            // delimiter immediately after `%` (a space means modulo).
            b'%' if i + 1 < b.len()
                && matches!(b[i + 1], b'(' | b'{' | b'[' | b'<')
                && percent_string_start(&out, sp)
                && !method_name_pos(&out) =>
            {
                let open = b[i + 1];
                let close = match open {
                    b'[' => b']',
                    b'(' => b')',
                    b'{' => b'}',
                    _ => b'>',
                };
                i += 2;
                let start = i;
                let mut depth = 1u32;
                while i < b.len() {
                    if b[i] == b'\\' && i + 1 < b.len() {
                        i += 2; // an escaped char is never a delimiter
                        continue;
                    }
                    if b[i] == b'\n' {
                        line += 1;
                    }
                    if b[i] == open && open != close {
                        depth += 1;
                    } else if b[i] == close {
                        depth -= 1;
                        if depth == 0 {
                            break;
                        }
                    }
                    i += 1;
                }
                let body = src[start..i.min(b.len())].to_string();
                i += 1; // consume the closing delimiter
                out.push(Token {
                    kind: Tok::Str(body, true),
                    line,
                    space: core::mem::take(&mut sp),
                });
            }
            // `?c` character literal → a one-char string. Only when `?` is at an
            // expression start (leading space) and directly followed by an escape
            // (`?\n`) or a lone alnum char (not `?ab`, and not the `? :` ternary).
            // A char literal is only possible where a `?` ternary can't be: at an
            // expression start (leading space, or right after a non-value token such
            // as `(`, `,`, an operator, or another `?`). `include?(??)` glues `??`
            // straight after `(`, so a whitespace-only guard would miss it.
            b'?' if (sp || !prev_is_value(&out))
                && i + 1 < b.len()
                && (b[i + 1] == b'\\'
                    || (b[i + 1].is_ascii_alphanumeric()
                        && (i + 2 >= b.len()
                            || !(b[i + 2].is_ascii_alphanumeric() || b[i + 2] == b'_')))
                    // A punctuation char literal (`?/`, `?.`, `?!`): `?` glued to a
                    // printable non-alphanumeric char (a space after `?` stays a
                    // ternary).
                    || (b[i + 1].is_ascii_graphic() && !b[i + 1].is_ascii_alphanumeric())) =>
            {
                i += 1;
                let ch = if b[i] == b'\\' && i + 1 < b.len() {
                    i += 1;
                    let e = b[i];
                    i += 1;
                    match e {
                        b'n' => '\n',
                        b't' => '\t',
                        b'r' => '\r',
                        b's' => ' ',
                        b'0' => '\0',
                        b'e' => '\x1b',
                        other => other as char,
                    }
                } else {
                    let c = b[i] as char;
                    i += 1;
                    c
                };
                out.push(Token {
                    kind: Tok::Str(ch.to_string(), false),
                    line,
                    space: core::mem::take(&mut sp),
                });
            }
            // Operator symbols: `:+`, `:<=>`, `:[]`, … only in value position (so
            // `a ? b : c` ternary and `key: v` hash keys are untouched).
            // An operator symbol (`:+`, `:<<`, `:[]`) — recognized when it can't be
            // a ternary colon: either at the start of an expression, or as a
            // spaced command argument (`foo :<<`). Ternary's `:` is followed by a
            // space, so `op_symbol_at` never matches there.
            // `:"name"` / `:'name'` — a quoted symbol literal (`:"\0foo"`, a name
            // with characters an ordinary symbol can't hold). Interpolation is
            // not evaluated; double-quoted escapes cover `\0 \n \t \e \\ \"`.
            b':' if i + 1 < b.len()
                && (b[i + 1] == b'"' || b[i + 1] == b'\'')
                && (!prev_is_value(&out) || sp)
                && !glued_keyword_label(&out, sp) =>
            {
                let quote = b[i + 1];
                i += 2;
                let mut bytes: Vec<u8> = Vec::new();
                let mut has_interp = false;
                while i < b.len() && b[i] != quote {
                    // A `#{ … }` in a double-quoted symbol is interpolation: copy it
                    // verbatim (braces balanced, nested string literals skipped so an
                    // inner quote doesn't end us) for the parser to re-scan.
                    if quote == b'"' && b[i] == b'#' && i + 1 < b.len() && b[i + 1] == b'{' {
                        has_interp = true;
                        bytes.push(b'#');
                        bytes.push(b'{');
                        i += 2;
                        let mut depth = 1u32;
                        while i < b.len() && depth > 0 {
                            match b[i] {
                                b'{' => depth += 1,
                                b'}' => depth -= 1,
                                q @ (b'"' | b'\'') => {
                                    bytes.push(q);
                                    i += 1;
                                    while i < b.len() && b[i] != q {
                                        if b[i] == b'\\' && i + 1 < b.len() {
                                            bytes.push(b[i]);
                                            bytes.push(b[i + 1]);
                                            i += 2;
                                            continue;
                                        }
                                        bytes.push(b[i]);
                                        i += 1;
                                    }
                                    if i < b.len() {
                                        bytes.push(q);
                                        i += 1;
                                    }
                                    continue;
                                }
                                _ => {}
                            }
                            bytes.push(b[i]);
                            i += 1;
                        }
                        continue;
                    }
                    if quote == b'"' && b[i] == b'\\' && i + 1 < b.len() {
                        // With interpolation the parser's scan decodes escapes, so
                        // keep them raw; otherwise decode the essentials here.
                        bytes.push(b'\\');
                        bytes.push(b[i + 1]);
                        i += 2;
                    } else {
                        bytes.push(b[i]);
                        i += 1;
                    }
                }
                i += 1; // closing quote
                let body = String::from_utf8_lossy(&bytes).into_owned();
                // `:"a #$g"` interpolates through the sigil shorthand too, with
                // no `#{` for the loop above to have spotted.
                let has_interp =
                    has_interp || (quote == b'"' && crate::parser::has_sigil_interp(&body));
                let kind = if has_interp {
                    Tok::DSymbol(body)
                } else if quote == b'"' {
                    // No interpolation: decode the double-quote escapes now.
                    match decode_dquote_escapes(&body) {
                        Some(name) => Tok::Symbol(name),
                        None => return Err(format!("invalid symbol at line {line}")),
                    }
                } else {
                    Tok::Symbol(body)
                };
                out.push(Token {
                    kind,
                    line,
                    space: core::mem::take(&mut sp),
                });
            }
            b':' if i + 1 < b.len()
                && op_symbol_at(&src[i + 1..]).is_some()
                && (!prev_is_value(&out) || sp)
                && !glued_keyword_label(&out, sp) =>
            {
                let op = op_symbol_at(&src[i + 1..]).unwrap();
                i += 1 + op.len();
                out.push(Token {
                    kind: Tok::Symbol(op.to_string()),
                    line,
                    space: core::mem::take(&mut sp),
                });
            }
            b':' if i + 1 < b.len()
                && (ident_start(b[i + 1])
                    || b[i + 1] == b'@'
                    || b[i + 1] == b'$')
                // A `:` glued to the right of a value (`x:true`, `key:String`) is a
                // label colon, not a symbol start — the same disambiguation the
                // operator-symbol case above uses. `foo :bar` (spaced) and
                // expression-start `:bar` still lex as symbols.
                && (!prev_is_value(&out) || sp)
                && !glued_keyword_label(&out, sp) =>
            {
                i += 1;
                let start = i;
                // Instance/class/global-variable symbols keep their sigil:
                // `:@x`, `:@@x`, `:$x`.
                while i < b.len() && b[i] == b'@' {
                    i += 1;
                }
                if i < b.len() && b[i] == b'$' {
                    i += 1;
                }
                while i < b.len() && ident_byte(b[i]) {
                    i += 1;
                }
                // allow trailing ? / ! on symbol/method names, or a single `=` for
                // a setter symbol (`:x=`) — but not `==`/`=~`/`=>` which are ops.
                //
                // `?` and `!` carry the same guard as an ordinary identifier: a
                // following `=` means the operator, not the suffix, so `:b!=:a`
                // is `:b != :a` and not the symbol `:b!` being assigned to.
                if i < b.len()
                    && (((b[i] == b'?' || b[i] == b'!') && b.get(i + 1) != Some(&b'='))
                        || (b[i] == b'='
                            && !matches!(b.get(i + 1), Some(b'=') | Some(b'~') | Some(b'>'))))
                {
                    i += 1;
                }
                out.push(Token {
                    kind: Tok::Symbol(src[start..i].to_string()),
                    line,
                    space: core::mem::take(&mut sp),
                });
            }
            // `__END__` alone on a line ends the program; everything after it is
            // the DATA section (out of scope), so lexing stops here. Must sit at
            // column 0 (start of file or right after a newline) and be the whole
            // line (followed by EOF, `\n`, or `\r\n`).
            b'_' if (i == 0 || b[i - 1] == b'\n')
                && src[i..].starts_with("__END__")
                && matches!(b.get(i + 7), None | Some(b'\n') | Some(b'\r')) =>
            {
                break;
            }
            _ if ident_start(c) => {
                let start = i;
                while i < b.len() && ident_byte(b[i]) {
                    i += 1;
                }
                // Method-name suffixes `?` and `!`, with MRI's one condition on
                // them (parse.y `parse_ident`): the suffix is taken only when
                // the NEXT character is not `=`.
                //
                //     if ((c == '!' || c == '?') && !peek(p, '=')) tokadd(p, c);
                //
                // Without that guard `b!=a` reads as the bang-method name `b!`
                // followed by `=`, so the whole comparison silently became an
                // ASSIGNMENT — `p b!=a` printed 1 (the assigned value) instead
                // of true, and `arr.size!=1` raised NoMethodError for a method
                // named `size!=`. Spaces hid it (`b != a` was always right),
                // which is why it survived: only the unspaced form is affected,
                // and that is the form most Ruby is written in.
                if i < b.len() && (b[i] == b'?' || b[i] == b'!') && b.get(i + 1) != Some(&b'=') {
                    i += 1;
                }
                let word = &src[start..i];
                let kind = if KEYWORDS.contains(&word) {
                    Tok::Keyword(word.to_string())
                } else if word.chars().next().is_some_and(char::is_uppercase) {
                    Tok::Const(word.to_string())
                } else {
                    Tok::Ident(word.to_string())
                };
                out.push(Token {
                    kind,
                    line,
                    space: core::mem::take(&mut sp),
                });
            }
            // `/pattern/flags` regex literal — when `/` is at an expression start
            // (not a division / `/=`). Body respects `\/` escapes and `[…]`
            // char-classes; trailing `imx` are flags.
            b'/' if regex_start(&out, sp, b.get(i + 1).copied()) => {
                i += 1;
                let mut pat = String::new();
                let mut in_class = false;
                while i < b.len() {
                    let ch = b[i];
                    if ch == b'\\' && i + 1 < b.len() {
                        pat.push('\\');
                        let cl = utf8_len(b[i + 1]);
                        pat.push_str(&src[i + 1..i + 1 + cl]);
                        i += 1 + cl;
                        continue;
                    }
                    // `#{ … }` interpolation — copy the whole expression through
                    // (balanced braces) so a `/`, `[`, etc. inside it does not end
                    // the regex or toggle a char class. The compiler evaluates it.
                    if ch == b'#' && i + 1 < b.len() && b[i + 1] == b'{' {
                        pat.push_str("#{");
                        i += 2;
                        let mut depth = 1;
                        while i < b.len() && depth > 0 {
                            match b[i] {
                                b'{' => depth += 1,
                                b'}' => depth -= 1,
                                b'\n' => line += 1,
                                _ => {}
                            }
                            let cl = utf8_len(b[i]);
                            pat.push_str(&src[i..i + cl]);
                            i += cl;
                        }
                        continue;
                    }
                    match ch {
                        b'[' => in_class = true,
                        b']' => in_class = false,
                        b'/' if !in_class => break,
                        b'\n' => line += 1,
                        _ => {}
                    }
                    let cl = utf8_len(ch);
                    pat.push_str(&src[i..i + cl]);
                    i += cl;
                }
                // Consume the closing `/` only if the loop actually reached one
                // (an unterminated regex leaves `i` at end-of-input — never index
                // past it).
                if i < b.len() {
                    i += 1;
                }
                let fstart = i;
                while i < b.len() && matches!(b[i], b'i' | b'm' | b'x' | b'o' | b'u' | b'n') {
                    i += 1;
                }
                let flags = src[fstart..i].to_string();
                out.push(Token {
                    kind: Tok::Regex(pat, flags),
                    line,
                    space: core::mem::take(&mut sp),
                });
            }
            b'<' if i + 2 < b.len() && b[i + 1] == b'<' && heredoc_here(&out, &b[i + 2..], sp) => {
                // A heredoc marker: `<<DELIM`, `<<~DELIM`, `<<-DELIM`, or a quoted
                // delimiter. Consume the marker; the body is filled in when the
                // line's newline is reached.
                let mut j = i + 2;
                let squiggly = b[j] == b'~';
                let dash = b[j] == b'-';
                if squiggly || dash {
                    j += 1;
                }
                let (quote, interp) = match b.get(j) {
                    Some(b'\'') => (Some(b'\''), false),
                    Some(b'"') => (Some(b'"'), true),
                    Some(b'`') => (Some(b'`'), true),
                    _ => (None, true),
                };
                if quote.is_some() {
                    j += 1;
                }
                let delim_start = j;
                while j < b.len() && (b[j].is_ascii_alphanumeric() || b[j] == b'_') {
                    j += 1;
                }
                let delim = src[delim_start..j].to_string();
                if let Some(q) = quote {
                    if b.get(j) == Some(&q) {
                        j += 1;
                    }
                }
                // Emit a placeholder Str token (filled at end of line) and record
                // the pending heredoc. A `` <<`CMD` `` heredoc is a command string.
                if quote == Some(b'`') {
                    push_xstring(
                        &mut out,
                        Tok::Str(String::new(), true),
                        line,
                        core::mem::take(&mut sp),
                    );
                    // `tok_idx` below must name the Str, not the closing `)`.
                    let close = out.pop().expect("push_xstring pushed `)`");
                    pending.push(Heredoc {
                        delim,
                        squiggly,
                        indent_term: squiggly || dash,
                        interp,
                        tok_idx: out.len() - 1,
                    });
                    out.push(close);
                    i = j;
                    continue;
                }
                out.push(Token {
                    kind: Tok::Str(String::new(), interp),
                    line,
                    space: core::mem::take(&mut sp),
                });
                pending.push(Heredoc {
                    delim,
                    squiggly,
                    indent_term: squiggly || dash,
                    interp,
                    tok_idx: out.len() - 1,
                });
                i = j;
            }
            _ => {
                // operators / punctuation, longest match first. Guard the string
                // slices on char boundaries: a multibyte char elsewhere on the
                // line means `i + n` can land inside a codepoint, and slicing a
                // `str` off a boundary panics.
                let three = if i + 3 <= b.len() && src.is_char_boundary(i + 3) {
                    &src[i..i + 3]
                } else {
                    ""
                };
                let two = if i + 2 <= b.len() && src.is_char_boundary(i + 2) {
                    &src[i..i + 2]
                } else {
                    ""
                };
                let op: &str = if matches!(
                    three,
                    "**=" | "<=>" | "===" | "..." | "&&=" | "||=" | "<<=" | ">>="
                ) {
                    three
                } else if matches!(
                    two,
                    "**" | "=="
                        | "!="
                        | "<="
                        | ">="
                        | "&&"
                        | "||"
                        | "+="
                        | "-="
                        | "*="
                        | "/="
                        | "%="
                        | "<<"
                        | ">>"
                        | ".."
                        | "::"
                        | "=>"
                        | "|="
                        | "&="
                        | "^="
                        | "->"
                        | "=~"
                        | "!~"
                        | "&."
                ) {
                    two
                } else {
                    match c {
                        b'+' | b'-' | b'*' | b'/' | b'%' | b'=' | b'<' | b'>' | b'!' | b'&'
                        | b'|' | b'^' | b'~' | b'(' | b')' | b'[' | b']' | b'{' | b'}' | b','
                        | b'.' | b':' | b'?' | b'`' => &src[i..i + 1],
                        other => {
                            return Err(format!(
                                "unexpected character '{}' at line {line}",
                                other as char
                            ))
                        }
                    }
                };
                out.push(Token {
                    kind: Tok::Op(op.to_string()),
                    line,
                    space: core::mem::take(&mut sp),
                });
                i += op.len();
            }
        }
    }
    out.push(Token {
        kind: Tok::Eof,
        line,
        space: core::mem::take(&mut sp),
    });
    Ok(out)
}

/// Byte length of the UTF-8 sequence whose lead byte is `b`.
/// Whether a `/` here begins a regex literal rather than division. It does when
/// the previous real token is not a value (so `/` sits at an expression start),
/// or — after a value — when there's a space before `/` but not after (the
/// command-argument form `scan /re/`, versus `a / b` division).
/// True in a method-name position — right after `def`, or after a `.`/`::`/`&.`
/// call dot — where an operator char (`/`, `%`, …) is a method name, not the
/// start of a regex / percent-literal (`def /(o)`, `def %(o)`, `x./(y)`).
/// A command string (`` `cmd` ``, `%x(cmd)`, `` <<`CMD` ``) is a call of the
/// `` ` `` method on self with the interpolated string (parse.y `NODE_XSTR`), so
/// it is lexed as exactly that call, `` `(str) ``, and a user `` def ` ``
/// overrides it as in MRI.
fn push_xstring(out: &mut Vec<Token>, body: Tok, line: u32, space: bool) {
    let tok = |kind, space| Token { kind, line, space };
    out.push(tok(Tok::Ident("`".to_string()), space));
    out.push(tok(Tok::Op("(".to_string()), false));
    out.push(tok(body, false));
    out.push(tok(Tok::Op(")".to_string()), false));
}

fn method_name_pos(out: &[Token]) -> bool {
    match out
        .iter()
        .rev()
        .find(|t| t.kind != Tok::Newline)
        .map(|t| &t.kind)
    {
        Some(Tok::Keyword(k)) if k == "def" => true,
        Some(Tok::Op(o)) => o == "." || o == "::" || o == "&.",
        _ => false,
    }
}

fn regex_start(out: &[Token], sp: bool, next: Option<u8>) -> bool {
    if method_name_pos(out) {
        return false;
    }
    let prev = out.iter().rev().find(|t| t.kind != Tok::Newline);
    let prev_is_value = match prev.map(|t| &t.kind) {
        None => false,
        Some(Tok::Int(_))
        | Some(Tok::Float(_))
        | Some(Tok::Str(_, _))
        | Some(Tok::Regex(_, _))
        | Some(Tok::Ident(_))
        | Some(Tok::Const(_))
        | Some(Tok::IVar(_))
        | Some(Tok::GVar(_))
        | Some(Tok::Symbol(_)) => true,
        Some(Tok::Op(o)) => o == ")" || o == "]" || o == "}",
        Some(Tok::Keyword(k)) => matches!(k.as_str(), "self" | "end" | "true" | "false" | "nil"),
        _ => false,
    };
    if !prev_is_value {
        // A regex position (`=~ /=/`, `(/=/)`): even `/=…` is a regex, not the
        // divide-assign operator.
        return true;
    }
    // After a value, `/=` is the divide-assign operator (`x /= 2`), never a regex.
    if next == Some(b'=') {
        return false;
    }
    // Otherwise a command-argument regex needs a leading space and no space
    // immediately after the `/` (so `foo /re/` is a regex, `a / b` is division).
    sp && !matches!(next, Some(b' ') | Some(b'\t') | None)
}

/// Operator method-name symbols, longest-first so `starts_with` picks the
/// longest (`[]=` before `[]`, `<=>` before `<=` before `<`).
// Longest / most-specific first: `op_symbol_at` takes the first `starts_with`
// match, so `-@`/`+@`/`!~` must precede `-`/`+`/`!` (`:-@` vs `:-`).
const OP_SYMBOLS: &[&str] = &[
    "<=>", "===", "[]=", "**", "==", "!=", "!~", "<=", ">=", "<<", ">>", "=~", "[]", "-@", "+@",
    "+", "-", "*", "/", "%", "<", ">", "&", "|", "^", "~", "!", "`",
];

/// The operator symbol beginning `s` (text right after `:`), or `None`.
fn op_symbol_at(s: &str) -> Option<&'static str> {
    OP_SYMBOLS.iter().find(|op| s.starts_with(**op)).copied()
}

/// Decode a non-interpolating `:"…"` symbol body with the same escapes as a
/// double-quoted string.
fn decode_dquote_escapes(body: &str) -> Option<String> {
    crate::parser::decode_dquote_body(body)
}

/// Whether a `%` here begins a `%(…)`-style double-quoted string rather than
/// the modulo operator. True at an expression start (prev token is not a value),
/// and — like a command-argument regex — after a bare method name (`p %(x)`,
/// `puts %(x)`) with a leading space. After a literal value (number, string,
/// `)`, `]`, ivar/gvar) it stays modulo. MRI additionally treats a bare *local
/// variable* (`foo %(3)` where `foo` is assigned) as modulo via its
/// local-variable table; this lexer has none, so a spaced identifier is always
/// read as a command call (see BUGS.md for the edge cost).
fn percent_string_start(out: &[Token], sp: bool) -> bool {
    // A statement boundary (newline/`;`) immediately before `%` is an expression
    // start, so `%(…)` is a string — `prev_is_value` skips newlines and would
    // otherwise see a `)` from the preceding line's `def foo(x)` and read modulo.
    if matches!(
        out.last().map(|t| &t.kind),
        None | Some(Tok::Newline) | Some(Tok::Semicolon)
    ) {
        return true;
    }
    let prev = out.iter().rev().find(|t| t.kind != Tok::Newline);
    match prev.map(|t| &t.kind) {
        // Bare method name in command position: `p %(x)`.
        Some(Tok::Ident(_)) | Some(Tok::Const(_)) => sp,
        // Otherwise: string at an expression start, modulo after a value.
        _ => !prev_is_value(out),
    }
}

/// Whether the last significant token is a value (so a following `:op` is a
/// ternary colon / hash key, not an operator symbol).
/// A keyword glued directly to a `:` (no preceding space) is a label name, not
/// the start of a symbol: `class:"x"`, `if: 1`, `def f(in: 5)`, `return:5`. MRI
/// lexes every glued `keyword:` as a hash/kwarg label (verified against 4.0.6:
/// `{class:"x"}`→`{class: "x"}`, `{return: 5}`). Distinguishes from `:sym` (the
/// colon precedes the name) and `foo ? a : b` (the ternary colon carries a
/// leading space). A preceding KEYWORD counts as non-value in `prev_is_value`,
/// so without this the symbol branches would swallow `keyword:"…"` / `keyword:x`
/// as a symbol.
fn glued_keyword_label(out: &[Token], sp: bool) -> bool {
    !sp && matches!(out.last().map(|t| &t.kind), Some(Tok::Keyword(_)))
}

fn prev_is_value(out: &[Token]) -> bool {
    let prev = out.iter().rev().find(|t| t.kind != Tok::Newline);
    match prev.map(|t| &t.kind) {
        Some(Tok::Int(_))
        | Some(Tok::Float(_))
        | Some(Tok::Str(_, _))
        | Some(Tok::Regex(_, _))
        | Some(Tok::Ident(_))
        | Some(Tok::Const(_))
        | Some(Tok::IVar(_))
        | Some(Tok::GVar(_))
        | Some(Tok::Symbol(_)) => true,
        Some(Tok::Op(o)) => o == ")" || o == "]" || o == "}",
        Some(Tok::Keyword(k)) => matches!(k.as_str(), "self" | "end" | "true" | "false" | "nil"),
        _ => false,
    }
}

fn utf8_len(b: u8) -> usize {
    match b {
        0x00..=0x7F => 1,
        0xC0..=0xDF => 2,
        0xE0..=0xEF => 3,
        _ => 4,
    }
}

/// Split a `%w`/`%i` (or, with `interp`, `%W`/`%I`) body into its words, as
/// MRI's QWORDS string scanner does. Unescaped whitespace separates words;
/// `\` before whitespace makes it part of the word. In the literal forms `\\`
/// is one backslash; in every form `\` before a delimiter is that delimiter.
/// Any other `\x` stays as written, which the interpolating forms then run
/// through double-quoted escape processing.
fn percent_words(body: &str, interp: bool, open: u8, close: u8) -> Vec<String> {
    let mut words = Vec::new();
    let mut cur = String::new();
    let mut in_word = false;
    let mut chars = body.chars();
    while let Some(c) = chars.next() {
        if c == '\\' {
            in_word = true;
            match chars.next() {
                Some(n) if n.is_whitespace() => cur.push(n),
                Some(n) if n == open as char || n == close as char || (!interp && n == '\\') => {
                    cur.push(n)
                }
                Some(n) => {
                    cur.push('\\');
                    cur.push(n);
                }
                None => cur.push('\\'),
            }
        } else if c.is_whitespace() {
            if in_word {
                words.push(std::mem::take(&mut cur));
                in_word = false;
            }
        } else {
            in_word = true;
            cur.push(c);
        }
    }
    if in_word {
        words.push(cur);
    }
    words
}