javars 0.1.2

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
//! 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::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,
    // 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> {
    let bytes = src.as_bytes();
    let mut i = 0usize;
    let mut line = 1u32;
    let mut out = Vec::new();

    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()
        {
            let radix = if matches!(bytes[i + 1], b'x' | b'X') {
                16
            } else {
                2
            };
            i += 2;
            let start = i;
            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)
        if c.is_ascii_digit() {
            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;
                }
            }
            // 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 {
                let v: f64 = text
                    .parse()
                    .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;
                    s.push(unescape(bytes[i] as char));
                    i += 1;
                } 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 = unescape(bytes[i] as char);
                i += 1;
                c
            } else {
                let c = src[i..].chars().next().unwrap();
                i += c.len_utf8();
                c
            };
            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)
        let two = if i + 1 < bytes.len() {
            &src[i..i + 2]
        } else {
            ""
        };
        let three = src.get(i..i + 3).unwrap_or("");
        let four = src.get(i..i + 4).unwrap_or("");
        let (kind, adv) = match four {
            ">>>=" => (Tok::UshrAssign, 4),
            _ => match three {
                ">>>" => (Tok::Ushr, 3),
                ">>=" => (Tok::ShrAssign, 3),
                "<<=" => (Tok::ShlAssign, 3),
                _ => lex_short(two, c, line)?,
            },
        };
        out.push(Token { kind, line });
        i += adv;
    }

    out.push(Token {
        kind: Tok::Eof,
        line,
    });
    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.
fn lex_short(two: &str, c: char, line: u32) -> Result<(Tok, usize), String> {
    Ok(match two {
        "+=" => (Tok::PlusAssign, 2),
        "-=" => (Tok::MinusAssign, 2),
        "*=" => (Tok::StarAssign, 2),
        "/=" => (Tok::SlashAssign, 2),
        "%=" => (Tok::PercentAssign, 2),
        "++" => (Tok::PlusPlus, 2),
        "--" => (Tok::MinusMinus, 2),
        "==" => (Tok::EqEq, 2),
        "!=" => (Tok::NotEq, 2),
        "<=" => (Tok::Le, 2),
        ">=" => (Tok::Ge, 2),
        "&&" => (Tok::AndAnd, 2),
        "||" => (Tok::OrOr, 2),
        "&=" => (Tok::AmpAssign, 2),
        "|=" => (Tok::PipeAssign, 2),
        "^=" => (Tok::CaretAssign, 2),
        "<<" => (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.
        ">>" => (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 `:`.
        "->" => (Tok::Arrow, 2),
        "::" => (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),
            other => {
                return Err(format!(
                    "javars: unexpected character `{other}` on line {line}"
                ))
            }
        },
    })
}

fn keyword_or_ident(word: &str) -> Tok {
    match word {
        "class" => Tok::Class,
        "public" => Tok::Public,
        "static" => Tok::Static,
        "void" => Tok::Void,
        "if" => Tok::If,
        "else" => Tok::Else,
        "while" => Tok::While,
        "for" => Tok::For,
        "do" => Tok::Do,
        "switch" => Tok::Switch,
        "case" => Tok::Case,
        "default" => Tok::Default,
        "return" => Tok::Return,
        "break" => Tok::Break,
        "continue" => Tok::Continue,
        "true" => Tok::True,
        "false" => Tok::False,
        "new" => Tok::New,
        _ => Tok::Ident(word.to_string()),
    }
}

fn unescape(c: char) -> char {
    match c {
        'n' => '\n',
        't' => '\t',
        'r' => '\r',
        '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;
    let body_end = src[body_start..]
        .find("\"\"\"")
        .map(|k| body_start + k)
        .ok_or_else(|| format!("javars: unterminated text block on line {line}"))?;
    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 mut chars = s.chars();
    while let Some(c) = chars.next() {
        if c != '\\' {
            out.push(c);
            continue;
        }
        match chars.next() {
            Some('\n') => {}
            Some('s') => out.push(' '),
            Some(e) => out.push(unescape(e)),
            None => out.push('\\'),
        }
    }
    out
}