javars 0.1.14

Java as a fusevm frontend: lexer, parser, and compiler to fusevm::Chunk, run on the shared three-tier Cranelift JIT — no bespoke VM or JVM
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
//! A hand-written Java lexer.
//!
//! Produces the token stream the parser consumes. Covers the slice-1 surface:
//! identifiers/keywords, integer/floating/string/char literals, and the
//! operators and punctuation used by declarations, expressions, and the
//! C-style control statements. Line/block/`//`-doc comments are skipped.

use std::borrow::Cow;
use std::fmt;

/// A lexical token with its 1-based source line (for error reporting).
#[derive(Debug, Clone, PartialEq)]
pub struct Token {
    pub kind: Tok,
    pub line: u32,
}

/// Token kinds.
#[derive(Debug, Clone, PartialEq)]
pub enum Tok {
    // literals & names
    Int(i64),
    /// An `L`-suffixed integer literal (`3000000000L`). Java types it `long`,
    /// which is what keeps it out of the 32-bit `int` wrap — so the suffix has
    /// to survive lexing rather than being dropped with the other ones.
    Long(i64),
    Float(f64),
    /// An `f`/`F`-suffixed floating literal (`1.5f`). Java types it `float`,
    /// which is a *32-bit* value — a distinct token because the width is what
    /// makes `1.0f / 3.0f` print `0.33333334` rather than the `double` answer.
    Float32(f64),
    Str(String),
    /// A `char` literal (`'a'`, `'\n'`). Java's `char` is a 16-bit *integral*
    /// type, so this is distinct from [`Tok::Str`]: `'a' + 1` is 98, not `"a1"`.
    Char(char),
    Ident(String),
    // keywords
    Class,
    Public,
    Static,
    Void,
    If,
    Else,
    While,
    For,
    Do,
    Switch,
    Case,
    Default,
    Return,
    Break,
    Continue,
    True,
    False,
    New,
    // punctuation
    LBrace,
    RBrace,
    LParen,
    RParen,
    LBracket,
    RBracket,
    Semi,
    Comma,
    Dot,
    Question,
    Colon,
    /// `->` — the lambda arrow (and the arrow form of `switch`).
    Arrow,
    /// `::` — the method-reference separator (`String::length`).
    ColonColon,
    /// `@` — the start of an annotation, which `strip_annotations` removes
    /// before the parser sees it.
    At,
    // operators
    Assign,
    PlusAssign,
    MinusAssign,
    StarAssign,
    SlashAssign,
    PercentAssign,
    Plus,
    Minus,
    Star,
    Slash,
    Percent,
    PlusPlus,
    MinusMinus,
    EqEq,
    NotEq,
    Lt,
    Gt,
    Le,
    Ge,
    AndAnd,
    OrOr,
    Not,
    /// `&` — bitwise AND on integers, non-short-circuit AND on booleans.
    Amp,
    /// `|` — bitwise OR on integers, non-short-circuit OR on booleans. Also the
    /// separator of a multi-catch (`catch (A | B e)`).
    Pipe,
    /// `^` — bitwise XOR on integers, logical XOR on booleans.
    Caret,
    /// `~` — bitwise complement.
    Tilde,
    /// `<<` — left shift.
    Shl,
    /// `>>` — arithmetic (sign-propagating) right shift.
    Shr,
    /// `>>>` — logical (zero-fill) right shift.
    Ushr,
    AmpAssign,
    PipeAssign,
    CaretAssign,
    ShlAssign,
    ShrAssign,
    UshrAssign,
    Eof,
}

impl Tok {
    /// How many closing `>` of a generic type-argument list this token spells.
    ///
    /// The lexer takes the longest match, so `Map<String, List<String>>` ends in
    /// one [`Tok::Shr`] rather than two [`Tok::Gt`]. Every generic-skipping
    /// depth counter asks this instead of matching `Gt` alone, so a nested type
    /// argument closes correctly.
    pub fn generic_closers(&self) -> i32 {
        match self {
            Tok::Gt => 1,
            Tok::Shr => 2,
            Tok::Ushr => 3,
            _ => 0,
        }
    }
}

impl fmt::Display for Tok {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{self:?}")
    }
}

/// Lex `src` into a token vector terminated by `Tok::Eof`.
pub fn lex(src: &str) -> Result<Vec<Token>, String> {
    // javars stores an unpaired surrogate as a code point from
    // `U+10F800..=U+10FFFF` (see `src/jstr.rs`), so source text holding one of
    // those characters itself cannot be represented and is refused.
    if let Some((n, c)) = src.lines().enumerate().find_map(|(n, l)| {
        l.chars()
            .find(|c| crate::jstr::is_reserved(*c as u32))
            .map(|c| (n, c))
    }) {
        return Err(format!(
            "{} (line {})",
            crate::jstr::reserved_message(c as u32),
            n + 1
        ));
    }
    lex_translated(&translate_unicode_escapes(src)?)
}

/// JLS 3.3: replace every eligible `\uXXXX` in the source with the character it
/// names, **before** the source is tokenized.
///
/// This is a translation of the whole file, not an escape the string lexer
/// handles, and Java specifies it that way — `A` is the letter `A`
/// wherever it appears, including in an identifier or a comment. javars did not
/// perform it at all, so `System.out.println("AB")` printed
/// `u0041u0042` (the string lexer dropped the unrecognised backslash) and
/// `'é'` was an `unterminated char literal`. The first is the dangerous
/// one: it is a silent wrong answer, not a refusal.
///
/// Two details of the rule are load-bearing and both are tested:
///
///   * A backslash starts an escape only when an **even** number of backslashes
///     precedes it. `"\\u0041"` is therefore a literal backslash followed by
///     `u0041`, not the letter `A` — which is how a Java program writes a
///     regex like `\\u` without it being translated away.
///   * `\uuuu0041` is legal: any run of `u`s after the backslash is part of the
///     escape. (The convention exists so a translator can mark text it has
///     already processed.)
///
/// A surrogate escape (`\ud83d`) is one UTF-16 unit, exactly as in Java: a high
/// one followed by a low one is the character they encode (`"\ud83d\ude00"`
/// is one astral character), and an unpaired one becomes its stand-in (see
/// `src/jstr.rs`), so `"\ud83d".length()` is 1 as in Java.
///
/// A source with no `\u` in it at all is the overwhelmingly common case, and it
/// borrows: returning an owned `String` here copied the whole file on every
/// `lex`, which `parse` and `compile` each pay for again.
fn translate_unicode_escapes(src: &str) -> Result<Cow<'_, str>, String> {
    if !src.contains("\\u") {
        return Ok(Cow::Borrowed(src));
    }
    let cs: Vec<char> = src.chars().collect();
    let mut out = String::with_capacity(src.len());
    let mut i = 0usize;
    let mut line = 1u32;
    while i < cs.len() {
        if cs[i] != '\\' {
            if cs[i] == '\n' {
                line += 1;
            }
            out.push(cs[i]);
            i += 1;
            continue;
        }
        // A run of backslashes: the k-th is preceded by k of them, so the only
        // one that can open an escape is the last, and only when the run has
        // odd length.
        let start = i;
        while i < cs.len() && cs[i] == '\\' {
            i += 1;
        }
        let run = i - start;
        if run % 2 == 0 || i >= cs.len() || cs[i] != 'u' {
            out.extend(cs[start..i].iter());
            continue;
        }
        // Keep every backslash but the one that opens the escape.
        out.extend(std::iter::repeat_n('\\', run - 1));
        while i < cs.len() && cs[i] == 'u' {
            i += 1;
        }
        let hex: String = cs.get(i..i + 4).unwrap_or_default().iter().collect();
        let value = (hex.len() == 4)
            .then(|| u32::from_str_radix(&hex, 16).ok())
            .flatten()
            .ok_or_else(|| format!("javars: illegal unicode escape on line {line}"))?;
        if value == u32::from('\n') {
            line += 1;
        }
        crate::jstr::push_unit(&mut out, value as u16);
        i += 4;
    }
    Ok(Cow::Owned(out))
}

fn lex_translated(src: &str) -> Result<Vec<Token>, String> {
    let bytes = src.as_bytes();
    let mut i = 0usize;
    let mut line = 1u32;
    // Java averages a little over four source bytes per token, so this is one
    // allocation for the whole file rather than the ~20 doublings (each a
    // `memmove` of everything lexed so far) a `Vec::new()` takes to get there.
    let mut out = Vec::with_capacity(src.len() / 4 + 16);

    while i < bytes.len() {
        let c = bytes[i] as char;

        // whitespace
        if c == '\n' {
            line += 1;
            i += 1;
            continue;
        }
        if c.is_whitespace() {
            i += 1;
            continue;
        }

        // comments
        if c == '/' && i + 1 < bytes.len() {
            match bytes[i + 1] as char {
                '/' => {
                    i += 2;
                    while i < bytes.len() && bytes[i] != b'\n' {
                        i += 1;
                    }
                    continue;
                }
                '*' => {
                    i += 2;
                    while i + 1 < bytes.len() && !(bytes[i] == b'*' && bytes[i + 1] == b'/') {
                        if bytes[i] == b'\n' {
                            line += 1;
                        }
                        i += 1;
                    }
                    i += 2; // consume closing */
                    continue;
                }
                _ => {}
            }
        }

        // identifiers & keywords
        if c.is_ascii_alphabetic() || c == '_' || c == '$' {
            let start = i;
            while i < bytes.len() {
                let ch = bytes[i] as char;
                if ch.is_ascii_alphanumeric() || ch == '_' || ch == '$' {
                    i += 1;
                } else {
                    break;
                }
            }
            let word = &src[start..i];
            out.push(Token {
                kind: keyword_or_ident(word),
                line,
            });
            continue;
        }

        // `0x…` / `0X…` hex and `0b…` / `0B…` binary integer literals. Neither
        // takes a fractional part or an exponent, so they are lexed ahead of the
        // decimal path rather than inside it. Java reads them as a *bit
        // pattern*: `0xFFFFFFFF` is the `int` -1 and `0xFFFFFFFFFFFFFFFFL` is the
        // `long` -1, so the digits are parsed unsigned and then reinterpreted at
        // the literal's width.
        if c == '0'
            && i + 1 < bytes.len()
            && matches!(bytes[i + 1], b'x' | b'X' | b'b' | b'B')
            && i + 2 < bytes.len()
            && ((bytes[i + 2] as char).is_ascii_alphanumeric()
                || (matches!(bytes[i + 1], b'x' | b'X') && bytes[i + 2] == b'.'))
        {
            let radix = if matches!(bytes[i + 1], b'x' | b'X') {
                16
            } else {
                2
            };
            i += 2;
            let start = i;
            // A hexadecimal *floating-point* literal (`0x1.8p1`, `0x.8P0`,
            // `0x1p-2f`): hex digits with an optional point, then the binary
            // exponent JLS 3.10.2 makes mandatory, then an optional `f`/`d`.
            if radix == 16 {
                let mut j = i;
                while j < bytes.len() && (bytes[j].is_ascii_hexdigit() || bytes[j] == b'_') {
                    j += 1;
                }
                if j < bytes.len() && bytes[j] == b'.' {
                    j += 1;
                    while j < bytes.len() && (bytes[j].is_ascii_hexdigit() || bytes[j] == b'_') {
                        j += 1;
                    }
                }
                if j < bytes.len() && matches!(bytes[j], b'p' | b'P') {
                    j += 1;
                    if j < bytes.len() && matches!(bytes[j], b'+' | b'-') {
                        j += 1;
                    }
                    while j < bytes.len() && (bytes[j].is_ascii_digit() || bytes[j] == b'_') {
                        j += 1;
                    }
                    let text = src[start..j].replace('_', "");
                    let single = j < bytes.len() && matches!(bytes[j], b'f' | b'F');
                    if j < bytes.len() && matches!(bytes[j], b'f' | b'F' | b'd' | b'D') {
                        j += 1;
                    }
                    let v = hex_float(&text, single).ok_or_else(|| {
                        format!("javars: bad floating-point literal `0x{text}` on line {line}")
                    })?;
                    i = j;
                    out.push(Token {
                        kind: if single {
                            Tok::Float32(v)
                        } else {
                            Tok::Float(v)
                        },
                        line,
                    });
                    continue;
                }
            }
            while i < bytes.len()
                && ((bytes[i] as char).is_ascii_alphanumeric() || bytes[i] == b'_')
            {
                i += 1;
            }
            let mut digits = src[start..i].replace('_', "");
            // Only `L`/`l` is a suffix here — `d`/`f` are hex *digits*, and Java
            // has no `d`/`f`-suffixed hex integer literal.
            let is_long = digits.ends_with(['L', 'l']);
            if is_long {
                digits.pop();
            }
            let bits = u64::from_str_radix(&digits, radix)
                .map_err(|_| format!("javars: bad integer literal `{digits}` on line {line}"))?;
            let v = if is_long {
                bits as i64
            } else {
                bits as u32 as i32 as i64
            };
            out.push(Token {
                kind: if is_long { Tok::Long(v) } else { Tok::Int(v) },
                line,
            });
            continue;
        }

        // numbers (int or float); a leading point (`.5`) starts one too
        let dot_number = c == '.' && bytes.get(i + 1).is_some_and(u8::is_ascii_digit);
        if c.is_ascii_digit() || dot_number {
            let start = i;
            let mut is_float = false;
            while i < bytes.len() && ((bytes[i] as char).is_ascii_digit() || bytes[i] == b'_') {
                i += 1;
            }
            if i < bytes.len()
                && bytes[i] == b'.'
                && i + 1 < bytes.len()
                && (bytes[i + 1] as char).is_ascii_digit()
            {
                is_float = true;
                i += 1;
                while i < bytes.len() && ((bytes[i] as char).is_ascii_digit() || bytes[i] == b'_') {
                    i += 1;
                }
            }
            // A point with no fraction digits (`5.`, `5.e1`, `5.f`) is still a
            // floating literal, unless it is a member access or a range-like `..`.
            if !is_float && i < bytes.len() && bytes[i] == b'.' {
                let after = bytes.get(i + 1).copied().unwrap_or(b' ');
                let after2 = bytes.get(i + 2).copied().unwrap_or(b' ');
                let ident = |b: u8| b.is_ascii_alphanumeric() || b == b'_' || b == b'$';
                let exp = matches!(after, b'e' | b'E')
                    && (after2.is_ascii_digit()
                        || (matches!(after2, b'+' | b'-')
                            && bytes.get(i + 3).is_some_and(u8::is_ascii_digit)));
                let suffix = matches!(after, b'f' | b'F' | b'd' | b'D') && !ident(after2);
                if exp || suffix || (!ident(after) && after != b'.') {
                    is_float = true;
                    i += 1;
                }
            }
            // Exponent part: `1e3`, `1.5e-3`, `2E+2`. Java allows an exponent with
            // or without a fractional part, and it makes the literal floating
            // point either way. Only consume the `e` when a valid exponent
            // actually follows, so `1.foo` and an identifier starting with `e`
            // are left alone.
            if i < bytes.len() && matches!(bytes[i], b'e' | b'E') {
                let mut j = i + 1;
                if j < bytes.len() && matches!(bytes[j], b'+' | b'-') {
                    j += 1;
                }
                if j < bytes.len() && (bytes[j] as char).is_ascii_digit() {
                    is_float = true;
                    i = j;
                    while i < bytes.len() && (bytes[i] as char).is_ascii_digit() {
                        i += 1;
                    }
                }
            }
            // Float/double suffixes only make the literal floating; the `L`
            // suffix is kept, because it is what makes the literal a `long` and
            // therefore exempt from Java's 32-bit `int` wrap. The slice ends
            // here rather than being alpha-trimmed, because trimming trailing
            // letters would also eat the `e` of an exponent.
            let num_end = i;
            let mut is_long = false;
            let mut is_f32 = false;
            if i < bytes.len() && matches!(bytes[i], b'L' | b'l' | b'f' | b'F' | b'd' | b'D') {
                match bytes[i] {
                    b'f' | b'F' => {
                        is_float = true;
                        is_f32 = true;
                    }
                    b'd' | b'D' => is_float = true,
                    _ => is_long = true,
                }
                i += 1;
            }
            // Java lets `_` separate digits anywhere inside a literal
            // (`1_000_000`, `3.141_592`); it carries no value, so it is dropped
            // before parsing.
            let text = src[start..num_end].replace('_', "");
            let text = text.as_str();
            if is_float {
                // A `float` literal is rounded once, straight from the decimal
                // text to 32 bits; going through `f64` first rounds twice and
                // can land one ulp off (`1.00000017881393432617187499f`).
                let parsed = if is_f32 {
                    text.parse::<f32>().map(f64::from)
                } else {
                    text.parse::<f64>()
                };
                let v: f64 = parsed
                    .map_err(|_| format!("javars: bad float literal `{text}` on line {line}"))?;
                out.push(Token {
                    kind: if is_f32 {
                        Tok::Float32(v)
                    } else {
                        Tok::Float(v)
                    },
                    line,
                });
            } else {
                // A leading `0` on a multi-digit integer is Java's octal form:
                // `017` is 15. `0` itself stays decimal zero.
                let v: i64 = if text.len() > 1 && text.starts_with('0') {
                    i64::from_str_radix(&text[1..], 8)
                        .map_err(|_| format!("javars: bad octal literal `{text}` on line {line}"))?
                } else {
                    text.parse().map_err(|_| {
                        format!("javars: bad integer literal `{text}` on line {line}")
                    })?
                };
                out.push(Token {
                    kind: if is_long { Tok::Long(v) } else { Tok::Int(v) },
                    line,
                });
            }
            continue;
        }

        // text blocks (JLS 3.10.6) — `"""` opens one, and it is checked before
        // the ordinary string literal because `"""` also starts with a `"`.
        if c == '"' && src[i..].starts_with("\"\"\"") {
            let (block, consumed, lines) = text_block(src, i, line)?;
            i += consumed;
            out.push(Token {
                kind: Tok::Str(block),
                line,
            });
            line += lines;
            continue;
        }

        // string literals
        if c == '"' {
            i += 1;
            let mut s = String::new();
            while i < bytes.len() && bytes[i] != b'"' {
                if bytes[i] == b'\\' && i + 1 < bytes.len() {
                    i += 1;
                    let (ch, used) = escape_at(bytes, i);
                    s.push(ch);
                    i += used;
                } else {
                    // Decode a full UTF-8 char so multibyte literals survive.
                    let ch = src[i..].chars().next().unwrap();
                    if ch == '\n' {
                        line += 1;
                    }
                    s.push(ch);
                    i += ch.len_utf8();
                }
            }
            if i >= bytes.len() {
                return Err(format!(
                    "javars: unterminated string literal on line {line}"
                ));
            }
            i += 1; // closing quote
            out.push(Token {
                kind: Tok::Str(s),
                line,
            });
            continue;
        }

        // char literals — a 16-bit integral value (its code point), which is
        // what makes `'a' + 1` arithmetic rather than concatenation.
        if c == '\'' {
            i += 1;
            let ch = if bytes[i] == b'\\' {
                i += 1;
                let (c, used) = escape_at(bytes, i);
                i += used;
                c
            } else {
                let c = src[i..].chars().next().unwrap();
                i += c.len_utf8();
                c
            };
            // A `char` is one UTF-16 unit. javac (openjdk 21.0.13) accepts a
            // character above the BMP between the quotes — written raw or as
            // its two `\u` escapes — and the literal's value is its high
            // surrogate, which is kept here as that unit's stand-in.
            let cp = crate::jstr::char_value(ch);
            let ch = if cp > 0xFFFF {
                crate::jstr::char_of(0xD800 + ((cp - 0x10000) >> 10)).unwrap_or(ch)
            } else {
                ch
            };
            if i >= bytes.len() || bytes[i] != b'\'' {
                return Err(format!("javars: unterminated char literal on line {line}"));
            }
            i += 1;
            out.push(Token {
                kind: Tok::Char(ch),
                line,
            });
            continue;
        }

        // operators & punctuation (longest match first)
        //
        // Every three- and four-character form is a shift or a shift-assignment,
        // so all four of them start with `<` or `>`. Gating on that first byte
        // keeps two `str::get` slice-boundary checks and four string compares
        // off every *other* token, which is nearly all of them.
        let (kind, adv) = if c == '<' || c == '>' {
            match src.get(i..i + 4).unwrap_or("") {
                ">>>=" => (Tok::UshrAssign, 4),
                _ => match src.get(i..i + 3).unwrap_or("") {
                    ">>>" => (Tok::Ushr, 3),
                    ">>=" => (Tok::ShrAssign, 3),
                    "<<=" => (Tok::ShlAssign, 3),
                    _ => lex_short(c, bytes.get(i + 1).copied(), line)?,
                },
            }
        } else {
            lex_short(c, bytes.get(i + 1).copied(), line)?
        };
        out.push(Token { kind, line });
        i += adv;
    }

    out.push(Token {
        kind: Tok::Eof,
        line,
    });
    strip_annotations(out)
}

/// Drop every annotation (`@Override`, `@SuppressWarnings("unchecked")`,
/// `@java.lang.Deprecated(since = "9")`) from the token stream.
///
/// javars has no reflection, so an annotation has nothing to be read by: the
/// ones a program uses are compile-time checks (`@Override`,
/// `@FunctionalInterface`) or warnings control, and none changes what the
/// program prints. An annotation *type* declaration (`@interface`) is refused
/// rather than dropped, since its body is a declaration javars would lose.
fn strip_annotations(toks: Vec<Token>) -> Result<Vec<Token>, String> {
    if !toks.iter().any(|t| t.kind == Tok::At) {
        return Ok(toks);
    }
    let mut out = Vec::with_capacity(toks.len());
    let mut i = 0;
    while i < toks.len() {
        if toks[i].kind != Tok::At {
            out.push(toks[i].clone());
            i += 1;
            continue;
        }
        let line = toks[i].line;
        match toks.get(i + 1).map(|t| &t.kind) {
            Some(Tok::Ident(w)) if w == "interface" => {
                return Err(format!(
                "javars: annotation type declarations (`@interface`) are not modeled (line {line})"
            ))
            }
            Some(Tok::Ident(_)) => i += 2,
            _ => {
                return Err(format!(
                    "javars: `@` must start an annotation (line {line})"
                ))
            }
        }
        // A qualified name: `@java.lang.Override`.
        while matches!(toks.get(i).map(|t| &t.kind), Some(Tok::Dot))
            && matches!(toks.get(i + 1).map(|t| &t.kind), Some(Tok::Ident(_)))
        {
            i += 2;
        }
        // The element values, `(…)`, skipped to the matching parenthesis.
        if matches!(toks.get(i).map(|t| &t.kind), Some(Tok::LParen)) {
            let mut depth = 0usize;
            while i < toks.len() {
                match toks[i].kind {
                    Tok::LParen => depth += 1,
                    Tok::RParen => {
                        depth -= 1;
                        if depth == 0 {
                            i += 1;
                            break;
                        }
                    }
                    Tok::Eof => {
                        return Err(format!("javars: unterminated annotation (line {line})"))
                    }
                    _ => {}
                }
                i += 1;
            }
        }
    }
    Ok(out)
}

/// Match the one- and two-character operators and punctuation.
///
/// Split out of [`lex`] so the three- and four-character shift-assignment forms
/// can be tried first without nesting the whole table another level deep.
///
/// The two-character forms are matched as a **byte pair**, not as a
/// two-character `&str`. A `match` over string literals lowers (in an
/// unoptimised build, which is the one that runs) to a linear chain of
/// `memcmp` calls, and punctuation is a large fraction of every Java file — so
/// each `;`, `)` or `.` used to walk all 21 two-character forms before reaching
/// the one-character table below. `platform_memcmp` was the second-hottest
/// symbol in the process under `sample` because of it. An integer-pair match
/// switches on the bytes instead.
///
/// Taking the bytes also removes a latent panic: the old caller sliced
/// `&src[i..i + 2]`, which is a panic rather than an error when the next byte
/// is not a UTF-8 boundary — i.e. on a stray non-ASCII character in operator
/// position, exactly the input that should reach the diagnostic below.
fn lex_short(c: char, next: Option<u8>, line: u32) -> Result<(Tok, usize), String> {
    Ok(match next.map(|n| (c as u8, n)) {
        Some((b'+', b'=')) => (Tok::PlusAssign, 2),
        Some((b'-', b'=')) => (Tok::MinusAssign, 2),
        Some((b'*', b'=')) => (Tok::StarAssign, 2),
        Some((b'/', b'=')) => (Tok::SlashAssign, 2),
        Some((b'%', b'=')) => (Tok::PercentAssign, 2),
        Some((b'+', b'+')) => (Tok::PlusPlus, 2),
        Some((b'-', b'-')) => (Tok::MinusMinus, 2),
        Some((b'=', b'=')) => (Tok::EqEq, 2),
        Some((b'!', b'=')) => (Tok::NotEq, 2),
        Some((b'<', b'=')) => (Tok::Le, 2),
        Some((b'>', b'=')) => (Tok::Ge, 2),
        Some((b'&', b'&')) => (Tok::AndAnd, 2),
        Some((b'|', b'|')) => (Tok::OrOr, 2),
        Some((b'&', b'=')) => (Tok::AmpAssign, 2),
        Some((b'|', b'=')) => (Tok::PipeAssign, 2),
        Some((b'^', b'=')) => (Tok::CaretAssign, 2),
        Some((b'<', b'<')) => (Tok::Shl, 2),
        // `>>` is lexed here rather than being left as two `Gt`s, so the
        // shift is a single token; the generic-argument skippers ask
        // [`Tok::generic_closers`] instead of matching `Gt`, which is what
        // keeps `List<List<String>>` parsing.
        Some((b'>', b'>')) => (Tok::Shr, 2),
        // `->` cannot collide with `-` followed by `>`: Java has no prefix
        // `>`, so a `-`/`>` adjacency is only ever the arrow. `::` likewise
        // cannot collide with the ternary/label `:`.
        Some((b'-', b'>')) => (Tok::Arrow, 2),
        Some((b':', b':')) => (Tok::ColonColon, 2),
        _ => match c {
            '{' => (Tok::LBrace, 1),
            '}' => (Tok::RBrace, 1),
            '(' => (Tok::LParen, 1),
            ')' => (Tok::RParen, 1),
            '[' => (Tok::LBracket, 1),
            ']' => (Tok::RBracket, 1),
            ';' => (Tok::Semi, 1),
            ',' => (Tok::Comma, 1),
            '.' => (Tok::Dot, 1),
            '?' => (Tok::Question, 1),
            ':' => (Tok::Colon, 1),
            '=' => (Tok::Assign, 1),
            '+' => (Tok::Plus, 1),
            '-' => (Tok::Minus, 1),
            '*' => (Tok::Star, 1),
            '/' => (Tok::Slash, 1),
            '%' => (Tok::Percent, 1),
            '<' => (Tok::Lt, 1),
            '>' => (Tok::Gt, 1),
            '!' => (Tok::Not, 1),
            '&' => (Tok::Amp, 1),
            '|' => (Tok::Pipe, 1),
            '^' => (Tok::Caret, 1),
            '~' => (Tok::Tilde, 1),
            '@' => (Tok::At, 1),
            other => {
                return Err(format!(
                    "javars: unexpected character `{other}` on line {line}"
                ))
            }
        },
    })
}

/// Classify an identifier-shaped word: a reserved word becomes its own token,
/// anything else becomes [`Tok::Ident`].
///
/// The keyword set is dispatched on **length** first. Written as one flat
/// `match word { "class" => …, … }`, rustc's unoptimised build lowers it to a
/// linear chain of `str` equality tests, so every identifier in the file — and
/// identifiers are most of the tokens — paid up to 18 `memcmp` calls before
/// falling through to the `Ident` arm. Under `sample`, `core::str::PartialEq::eq`
/// plus `memcmp` were the two hottest symbols in the whole lexer for exactly
/// this reason. Splitting on length first means a word of a length no keyword
/// has (the common case: 1, or 9 and up) does zero comparisons, and no word
/// does more than four.
fn keyword_or_ident(word: &str) -> Tok {
    let kw = match word.len() {
        2 => match word {
            "if" => Some(Tok::If),
            "do" => Some(Tok::Do),
            _ => None,
        },
        3 => match word {
            "for" => Some(Tok::For),
            "new" => Some(Tok::New),
            _ => None,
        },
        4 => match word {
            "void" => Some(Tok::Void),
            "else" => Some(Tok::Else),
            "case" => Some(Tok::Case),
            "true" => Some(Tok::True),
            _ => None,
        },
        5 => match word {
            "class" => Some(Tok::Class),
            "while" => Some(Tok::While),
            "break" => Some(Tok::Break),
            "false" => Some(Tok::False),
            _ => None,
        },
        6 => match word {
            "public" => Some(Tok::Public),
            "static" => Some(Tok::Static),
            "switch" => Some(Tok::Switch),
            "return" => Some(Tok::Return),
            _ => None,
        },
        7 => match word {
            "default" => Some(Tok::Default),
            _ => None,
        },
        8 => match word {
            "continue" => Some(Tok::Continue),
            _ => None,
        },
        _ => None,
    };
    kw.unwrap_or_else(|| Tok::Ident(word.to_string()))
}

/// Decode the escape whose backslash precedes `bytes[at]`, returning the
/// character and how many bytes of `bytes` it consumed (JLS 3.10.7). An octal
/// escape takes up to three digits when the first is `0`-`3`, else up to two.
fn escape_at(bytes: &[u8], at: usize) -> (char, usize) {
    let first = bytes[at];
    if !(b'0'..=b'7').contains(&first) {
        return (unescape(first as char), 1);
    }
    let max = if first <= b'3' { 3 } else { 2 };
    let mut value = 0u32;
    let mut n = 0;
    while n < max && bytes.get(at + n).is_some_and(|b| (b'0'..=b'7').contains(b)) {
        value = value * 8 + u32::from(bytes[at + n] - b'0');
        n += 1;
    }
    (char::from_u32(value).unwrap_or('\0'), n)
}

fn unescape(c: char) -> char {
    match c {
        'n' => '\n',
        't' => '\t',
        'r' => '\r',
        'b' => '\u{8}',
        'f' => '\u{c}',
        's' => ' ',
        '0' => '\0',
        '\\' => '\\',
        '"' => '"',
        '\'' => '\'',
        other => other,
    }
}

/// Lex a **text block** (JLS 3.10.6) starting at `start`, where `src[start..]`
/// begins with `"""`.
///
/// Returns the block's value, how many bytes it consumed, and how many newlines
/// it spanned (so the caller's line counter stays right).
///
/// The value is built in the order the specification gives, and the order
/// matters:
///
///   1. The opening delimiter must be followed by optional whitespace and then
///      a line terminator, which is *not* part of the content.
///   2. **Incidental** leading whitespace is stripped: the minimum indentation
///      over every non-blank line, and over the closing delimiter's line when
///      that delimiter sits on a line of its own. That last part is what lets a
///      block be indented to match its surrounding code and still start at
///      column 0 — and what makes a closing `"""` on the content's last line
///      contribute nothing.
///   3. Trailing whitespace is stripped from every line.
///   4. Escapes are processed **last**, so a `\n` written in the source is a
///      newline in the value but is not a line for steps 2 and 3 to see.
fn text_block(src: &str, start: usize, line: u32) -> Result<(String, usize, u32), String> {
    let after_open = start + 3;
    let rest = &src[after_open..];
    // Step 1: whitespace, then the line terminator that opens the content.
    let header = rest
        .find('\n')
        .ok_or_else(|| format!("javars: unterminated text block on line {line}"))?;
    if rest[..header].trim().is_empty() {
        // ok — only whitespace (and a possible `\r`) before the terminator
    } else {
        return Err(format!(
            "javars: a text block's opening `\"\"\"` must be followed by a line terminator (line {line})"
        ));
    }
    let body_start = after_open + header + 1;
    // The first `"""` that is not escaped closes it: `\"""` puts three quotes
    // in the content, so a backslash skips the character after it.
    let bytes = src.as_bytes();
    let mut k = body_start;
    let body_end = loop {
        match bytes.get(k) {
            None => return Err(format!("javars: unterminated text block on line {line}")),
            Some(b'\\') => k += 2,
            Some(b'"') if src[k..].starts_with("\"\"\"") => break k,
            Some(_) => k += 1,
        }
    };
    let body = &src[body_start..body_end];
    let newlines = body.matches('\n').count() as u32 + 1;

    let mut lines: Vec<&str> = body.split('\n').map(|l| l.trim_end_matches('\r')).collect();
    // The closing delimiter's own line is the last element when it sits alone;
    // it is blank in that case, and it *does* count toward the indentation.
    let closer_alone = lines
        .last()
        .is_some_and(|l| l.chars().all(|c| c == ' ' || c == '\t'));
    let indent_of = |l: &str| l.len() - l.trim_start_matches([' ', '\t']).len();
    let mut indent = usize::MAX;
    for (n, l) in lines.iter().enumerate() {
        let last = n + 1 == lines.len();
        if l.trim().is_empty() && !(last && closer_alone) {
            continue;
        }
        indent = indent.min(indent_of(l));
    }
    if indent == usize::MAX {
        indent = 0;
    }
    if closer_alone {
        // Its line contributes indentation and nothing else; the content ends
        // with the newline that precedes it.
        lines.pop();
    }
    // A block whose closing delimiter sits on the line right after the opening
    // one has no content *lines* at all, so it is the empty string rather than a
    // lone newline.
    let trailing_newline = closer_alone && !lines.is_empty();
    let mut value = String::new();
    for (n, l) in lines.iter().enumerate() {
        if n > 0 {
            value.push('\n');
        }
        let stripped = if l.len() >= indent { &l[indent..] } else { "" };
        value.push_str(stripped.trim_end_matches([' ', '\t']));
    }
    if trailing_newline {
        value.push('\n');
    }
    Ok((unescape_block(&value), body_end + 3 - start, newlines))
}

/// Process the escapes in a text block's already-stripped value.
///
/// Two exist only here: `\<line-terminator>` joins the line to the next with no
/// newline, and `\s` is a space that survives the trailing-whitespace stripping
/// (which has already happened by the time this runs, which is the point).
fn unescape_block(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let bytes = s.as_bytes();
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] != b'\\' {
            let ch = s[i..].chars().next().unwrap_or('\0');
            out.push(ch);
            i += ch.len_utf8();
            continue;
        }
        i += 1;
        match bytes.get(i) {
            Some(b'\n') => i += 1,
            Some(_) => {
                let (ch, used) = escape_at(bytes, i);
                out.push(ch);
                i += used;
            }
            None => out.push('\\'),
        }
    }
    out
}

/// The value of a hexadecimal floating-point literal (JLS 3.10.2) — the text
/// after the `0x`/`0X` prefix, with the sign, any `_` separators and the
/// `f`/`d` suffix already removed: `1.8p1`, `.8P0`, `1p-2`. `single` rounds to
/// `float` precision. `None` when the text is not `HexDigits [.] [HexDigits]`
/// followed by a binary exponent `p [+-] Digits`, which is mandatory.
///
/// The significand is exact binary, so the one rounding is the final one —
/// correctly rounded, half to even, to 53 (or 24) bits, gradually underflowing
/// below the normal range as `Double.valueOf("0x…")` does. Rounding through
/// `f64` first and then to `f32` would round twice.
pub fn hex_float(text: &str, single: bool) -> Option<f64> {
    let (sig, exp) = text.split_once(['p', 'P'])?;
    let exp_digits = exp.strip_prefix(['+', '-']).unwrap_or(exp);
    if exp_digits.is_empty() || !exp_digits.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    // A huge exponent saturates; it can only mean zero or infinity.
    let mut exp2: i64 = exp_digits
        .parse()
        .unwrap_or(i64::from(i32::MAX))
        .min(i64::from(i32::MAX));
    if exp.starts_with('-') {
        exp2 = -exp2;
    }
    let (int_part, frac_part) = sig.split_once('.').unwrap_or((sig, ""));
    if int_part.is_empty() && frac_part.is_empty() {
        return None;
    }
    // Up to 15 significant hex digits (60 bits) are kept exactly; any nonzero
    // digit past them only matters as a sticky bit for the rounding.
    let (mut m, mut kept, mut sticky) = (0u64, 0u32, false);
    for (i, ch) in int_part.chars().chain(frac_part.chars()).enumerate() {
        let d = u64::from(ch.to_digit(16)?);
        let fractional = i >= int_part.len();
        if m == 0 && d == 0 {
            if fractional {
                exp2 -= 4;
            }
            continue;
        }
        if kept < 15 {
            m = (m << 4) | d;
            kept += 1;
            if fractional {
                exp2 -= 4;
            }
        } else {
            sticky |= d != 0;
            if !fractional {
                exp2 += 4;
            }
        }
    }
    let zero = 0.0;
    if m == 0 {
        return Some(zero);
    }
    let (precision, emin, emax) = if single {
        (24i64, -126i64, 127i64)
    } else {
        (53, -1022, 1023)
    };
    let width = 64 - i64::from(m.leading_zeros());
    // The value is `m * 2^exp2`, whose leading bit is `2^top`.
    let top = exp2 + width - 1;
    if top > emax {
        return Some(f64::INFINITY);
    }
    // Below the normal range the significand loses a bit per binade.
    let keep = if top < emin {
        precision - (emin - top)
    } else {
        precision
    };
    let shift = width - keep;
    let (mut r, mut e) = (m, exp2);
    if shift > 0 {
        if shift > 64 {
            return Some(zero);
        }
        let (dropped, half) = if shift == 64 {
            (m, 1u64 << 63)
        } else {
            (m & ((1u64 << shift) - 1), 1u64 << (shift - 1))
        };
        r = if shift == 64 { 0 } else { m >> shift };
        e += shift;
        let round_up = dropped > half || (dropped == half && (sticky || r & 1 == 1));
        if round_up {
            r += 1;
        }
        if r == 0 {
            return Some(zero);
        }
    } else if shift < 0 {
        r = m << -shift;
        e += shift;
    }
    // Rounding up may have carried into a new binade past the largest finite.
    if e + 64 - i64::from(r.leading_zeros()) - 1 > emax {
        return Some(f64::INFINITY);
    }
    Some(scale2(r as f64, e))
}

/// `x * 2^k`, exact whenever the result is representable — applied in steps
/// that keep every intermediate in the normal range.
fn scale2(mut x: f64, mut k: i64) -> f64 {
    while k > 1000 {
        x *= 2f64.powi(1000);
        k -= 1000;
    }
    while k < -1000 {
        x *= 2f64.powi(-1000);
        k += 1000;
    }
    x * 2f64.powi(k as i32)
}