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
//! The Java AST javars parses and lowers to fusevm bytecode.
//!
//! Slice 1 is a single-class, single-`main` subset: the parser accepts a
//! `public class Name { ... static void main(String[] args) { ... } }` shell
//! and models the statements and expressions inside `main`. User-defined
//! methods, fields, and multiple classes are parsed no further than the entry
//! point today (see `BUGS.md`); the AST is shaped to grow into them.

/// A parsed compilation unit: the entry class name, the body of its `main`, and
/// any user-defined static helper methods.
#[derive(Debug, Clone, PartialEq)]
pub struct Program {
    /// The name of the class that declares `main` (informational; used by the
    /// `--dump-ast` output and error messages).
    pub class_name: String,
    /// The statements of `public static void main(String[] args)`.
    pub main: Vec<Stmt>,
    /// The name `main` gives its `String[]` parameter (`args`), when it declares
    /// one. Bound to the real program arguments by the compiler's prologue;
    /// `None` for the (legal) `main()` that declares no parameter.
    pub main_param: Option<String>,
    /// User-defined `static` methods declared in any class, in one pool keyed by
    /// name. Each entry carries its declaring class in [`Method::owner`], which
    /// is what a *qualified* `C.m(...)` call resolves against (`C`'s own
    /// declarations, then its superclass chain); an *unqualified* `m(...)`
    /// prefers the enclosing class's chain and falls back to the whole pool.
    /// `main` is excluded (it is the entry [`Program::main`]).
    pub methods: Vec<Method>,
    /// Every user-defined class in the compilation unit (top-level siblings and
    /// nested `static` classes, flattened into one namespace). The entry class
    /// (whichever declares `main`) is also present here so `new EntryClass()` and
    /// its instance members resolve.
    pub classes: Vec<Class>,
    /// True when the unit mentions exceptions at all — a `try`, a `throw`, or a
    /// `new` of a modeled `java.lang` throwable. Set by the parser and read by
    /// [`crate::prelude::inject`] (which supplies the throwable classes) and by
    /// the compiler (which only emits the post-call exception checks when this is
    /// set, so an exception-free program's bytecode is unchanged).
    pub uses_exceptions: bool,
    /// True when the unit mentions a lambda, a method reference, or one of the
    /// `java.util.function` interface names. Set by the parser and read by
    /// [`crate::prelude::inject`], which supplies the functional interfaces —
    /// a program with no lambda carries none of them.
    pub uses_functional: bool,
}

/// Field holding an enum constant's `name()`. `#` is not a legal Java identifier
/// character, so a synthesized field can never collide with a user-declared one.
pub const ENUM_NAME: &str = "#name";
/// Field holding an enum constant's `ordinal()`.
pub const ENUM_ORDINAL: &str = "#ordinal";

/// The global holding the singleton instance of `class.constant` — the storage
/// `Color.RED` reads. Minted by the compiler's enum prologue.
pub fn enum_global(class: &str, constant: &str) -> String {
    format!("#enum#{class}#{constant}")
}

/// The global holding `class.field`, a `static` field's one shared cell.
///
/// fusevm's `GetVar`/`SetVar` address a flat global table while frame slots are
/// per-call, so a `static` field — which every frame sees, and which outlives
/// any one call — is stored as a global rather than a slot. `#` is not a legal
/// Java identifier character, so the minted name can never collide with a
/// user-declared variable.
pub fn static_global(class: &str, field: &str) -> String {
    format!("#static#{class}#{field}")
}

/// The instance-map key of a field declared in `class` that hides a
/// same-named field an ancestor declares (JLS 8.3.1): each declaration has its
/// own cell, so the hiding one is stored apart from the bare name the topmost
/// declaration keeps. A name no subclass re-declares keeps its bare key, so a
/// program without hiding stores exactly as before.
pub fn hidden_field_key(class: &str, field: &str) -> String {
    format!("#hide#{class}#{field}")
}

/// The Java name of the field a storage key holds — the bare name back from a
/// [`hidden_field_key`], for the messages that name the field.
pub fn field_key_name(key: &str) -> &str {
    match key.strip_prefix("#hide#") {
        Some(rest) => rest.rsplit('#').next().unwrap_or(rest),
        None => key,
    }
}

/// The field and trailing constructor parameter through which an inner
/// (non-`static`) member class holds its enclosing instance — javac's own
/// synthetic name for it.
pub const OUTER_THIS: &str = "this$0";

/// A user-defined class: its instance fields, constructors, and instance
/// methods. `static` methods are hoisted into [`Program::methods`]; only the
/// non-static members live here. Modeled as heap objects ([`crate::host`]
/// `HostObj::Instance`) at runtime.
#[derive(Debug, Clone, PartialEq)]
pub struct Class {
    /// The names of the type parameters the declaration binds (`class Box<T>`
    /// binds `T`), in order — what a use's type arguments substitute into the
    /// members' `#T`-marked types.
    pub type_params: Vec<String>,
    /// The type arguments of the `extends` clause (`extends Box<Float>`), in
    /// the declaration's own type variables — what binds the superclass's.
    pub super_targs: Vec<String>,
    /// The type arguments of each `implements` (or, for an interface,
    /// `extends`) entry, parallel to [`Class::interfaces`].
    pub interface_targs: Vec<Vec<String>>,
    /// True for a `sealed` class or interface.
    pub is_sealed: bool,
    /// True for an `abstract` class (an interface is abstract by nature).
    pub is_abstract: bool,
    /// Its `permits` list, empty when it names none (the permitted subtypes
    /// are then the ones the compilation unit declares).
    pub permits: Vec<String>,
    pub name: String,
    /// Java's *binary* name for this type: `Outer$Nested` for a nested
    /// declaration, the simple name for a top-level one. javars flattens nesting
    /// into one namespace, so `name` is the simple name everything resolves by;
    /// this is what `getClass().getName()` and the default `toString()` report,
    /// which are the two places Java shows the nesting.
    pub binary: String,
    /// The direct superclass name (`class C extends B`), if any. For an
    /// `interface` this is always `None` (extended interfaces go in
    /// [`Class::interfaces`]).
    pub superclass: Option<String>,
    /// Directly implemented interfaces (`class C implements I, J`). For an
    /// `interface`, the interfaces it `extends` (`interface I extends A, B`).
    pub interfaces: Vec<String>,
    /// True when this declaration is an `interface` rather than a `class`. An
    /// interface is not instantiable; its abstract methods are dispatch-only and
    /// its `default` methods supply an inherited body to implementors.
    pub is_interface: bool,
    /// True when this declaration is an `enum`. Distinct from a non-empty
    /// [`Class::enum_constants`] because `enum Empty { }` is legal Java.
    pub is_enum: bool,
    /// True when this declaration is a `record`. The parser lowers a record to
    /// an ordinary class (fields, canonical constructor, accessors), so this is
    /// the only thing left that says it was one — and `r instanceof Record` is
    /// the observable that needs it, since Java makes every record a subclass of
    /// `java.lang.Record`.
    pub is_record: bool,
    /// The constants of an `enum`, in declaration order — the index is the
    /// value of `ordinal()`. Empty for a `class`/`interface`. An enum is
    /// otherwise an ordinary class: the parser gives it the `#name`/`#ordinal`
    /// fields and the `name()`/`ordinal()`/`toString()` bodies that read them,
    /// and the compiler builds one instance per constant before `main` runs.
    pub enum_constants: Vec<EnumConstant>,
    /// Instance fields in declaration order (name, type, optional initializer).
    pub fields: Vec<FieldDecl>,
    /// `static` fields in declaration order. Their storage is one global per
    /// field ([`static_global`]), seeded with the type's default value before
    /// any user code runs.
    pub static_fields: Vec<FieldDecl>,
    /// The class's static initialization, in textual order: each `static` field
    /// initializer lowered to an assignment, interleaved with the bodies of the
    /// `static { … }` blocks. Run once, before `main`.
    pub static_init: Vec<Stmt>,
    /// The class's *instance* initialization, in textual order: each instance
    /// field initializer lowered to a `this.f = …` assignment, interleaved with
    /// the bodies of the bare `{ … }` instance-initializer blocks. Run on every
    /// new instance before its constructor body — which is why the statements
    /// live here rather than in [`FieldDecl::init`]: a block needs a bound
    /// `this`, and so does a field initializer that reads an earlier field.
    pub inst_init: Vec<Stmt>,
    /// Declared constructors. Empty means the implicit no-arg default ctor.
    pub ctors: Vec<Ctor>,
    /// Instance (non-static) methods.
    pub methods: Vec<Method>,
    /// The enclosing locals a *local* class captures (JLS 8.1.3), in the
    /// order they trail every constructor's parameter list. Each is also a
    /// field of the class (unless a capturing local superclass already holds
    /// it). Empty for every other type.
    pub captures: Vec<Param>,
    /// 1-based source line the class starts on (diagnostics).
    pub line: u32,
}

/// One constant of an `enum`: `RED`, `EARTH(5.97e24)`, or `PLUS { … }`.
#[derive(Debug, Clone, PartialEq)]
pub struct EnumConstant {
    pub name: String,
    /// 1-based source line the constant sits on (diagnostics).
    pub line: u32,
    /// The constructor arguments the constant supplies (`EARTH(5.97e24)`), run
    /// against the enum's own constructor when its singleton is built.
    pub args: Vec<Expr>,
    /// The synthetic subclass a constant *body* (`PLUS { int apply(…) { … } }`)
    /// is compiled to — Java specifies such a constant as an anonymous subclass
    /// of the enum, and modeling it as a real class is what makes its overrides
    /// reachable through ordinary virtual dispatch. `None` for a bare constant.
    pub body_class: Option<String>,
}

/// The synthetic subclass name for an `enum` constant that declares a body.
/// `#` is not a legal Java identifier character, so it cannot collide with a
/// user-declared class.
pub fn enum_body_class(enum_name: &str, constant: &str) -> String {
    format!("{enum_name}#{constant}")
}

/// An instance field declaration: `int x;` or `String name = "?";`.
#[derive(Debug, Clone, PartialEq)]
pub struct FieldDecl {
    pub ty: String,
    /// The declared type's type arguments (`Map<String, Integer>` → `String`,
    /// `Integer`), see [`StmtKind::Local::targs`].
    pub targs: Vec<String>,
    /// See [`StmtKind::Local::super_slots`].
    pub super_slots: Vec<usize>,
    /// See [`StmtKind::Local::wildcard`].
    pub wildcard: bool,
    pub name: String,
    /// True when the declaration carried `final`.
    ///
    /// A `static final String` initialized with a constant expression is a
    /// *constant variable* (JLS 4.12.4): Java folds its uses at compile time, so
    /// `CONST + ""` is the interned literal `"ab"` rather than a string built at
    /// run time — which `==` can tell apart.
    pub is_final: bool,
    /// Field initializer expression, run (with default values first) before the
    /// constructor body — Java's instance-initialization order.
    pub init: Option<Expr>,
    /// 1-based source line the declaration sits on, so a duplicate can be
    /// reported where it was written rather than at the head of its class. A
    /// parser-synthesized field (a record component, an `enum`'s `#name`) has
    /// its declaration's line.
    pub line: u32,
    /// True when the declaration wrote an initializer (`int x = 1;`), which
    /// the parser moves into the class's `static_init`/`inst_init`.
    pub has_init: bool,
    /// Where the declaration sits among those initialization statements:
    /// how many of them precede it. With `has_init`, its own initializer is
    /// the statement at this index. This is the textual order a forward
    /// reference (JLS 8.3.3) is judged by.
    pub init_pos: usize,
}

/// A constructor: `ClassName(<params>) { <body> }`.
#[derive(Debug, Clone, PartialEq)]
pub struct Ctor {
    pub params: Vec<Param>,
    pub body: Vec<Stmt>,
    pub line: u32,
    /// The line of the body's closing brace, where `javac` reports a blank
    /// `final` field the constructor leaves unassigned.
    pub end_line: u32,
    /// True for a constructor the source does not declare: the default one
    /// `javac` synthesizes (here also for a class given captures), whose
    /// unassigned blank `final` is reported at the field instead.
    pub implicit: bool,
}

/// A user-defined `static` method: `static <ret> name(<params>) { <body> }`.
/// Lowered to a fusevm call-frame subroutine (`Op::Call`); parameters and locals
/// live in frame slots so recursion is well-behaved.
#[derive(Debug, Clone, PartialEq)]
pub struct Method {
    pub name: String,
    /// The class that declares this method. For a `static` method it is both the
    /// class whose `static` fields an unqualified name inside the body resolves
    /// against, and the scope a qualified `C.m(...)` call must match — statics
    /// share one by-name pool, so the owner has to travel with the method or two
    /// classes spelling the same method name become indistinguishable.
    pub owner: String,
    /// Formal parameters in declaration order (bound to slots `0..n`).
    pub params: Vec<Param>,
    /// The declared return type (retained for diagnostics and numeric-division
    /// typing; not otherwise checked).
    pub ret: String,
    /// The declared return type's type arguments, see
    /// [`StmtKind::Local::targs`].
    pub ret_targs: Vec<String>,
    /// See [`StmtKind::Local::super_slots`], for the return type.
    pub ret_super_slots: Vec<usize>,
    /// See [`StmtKind::Local::wildcard`], for the return type.
    pub ret_wildcard: bool,
    pub body: Vec<Stmt>,
    /// True for a bodyless method — an interface abstract method (`void m();`)
    /// or an `abstract` class method. No subroutine is emitted; the method is a
    /// virtual-dispatch target resolved to a concrete override at runtime.
    pub is_abstract: bool,
    /// The access modifier the declaration wrote (`Package` when it wrote
    /// none — which in an interface means `public`).
    pub access: Access,
    /// 1-based source line the method starts on (for the debug line marker and
    /// prologue ops).
    pub line: u32,
}

/// A member's access modifier, most open first (JLS 6.6).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Access {
    Public,
    Protected,
    Package,
    Private,
}

/// A method formal parameter: its declared type and name.
#[derive(Debug, Clone, PartialEq)]
pub struct Param {
    pub ty: String,
    /// The declared type's type arguments, see [`StmtKind::Local::targs`].
    pub targs: Vec<String>,
    /// See [`StmtKind::Local::super_slots`].
    pub super_slots: Vec<usize>,
    /// See [`StmtKind::Local::wildcard`].
    pub wildcard: bool,
    pub name: String,
    /// True for the variable-arity parameter (`int... xs`). `ty` is already the
    /// array type (`int[]`) — inside the body the parameter *is* that array —
    /// so this flag only says the declaration also admits Java's third
    /// (variable-arity) resolution phase, where a call passing loose trailing
    /// arguments is packed into the array at the call site. Only the last
    /// parameter may carry it.
    pub varargs: bool,
    /// Whether the parameter was declared `final`.
    pub is_final: bool,
}

/// A Java statement with its 1-based source line (threaded through the parser so
/// the debug-compile path can emit a per-statement line marker for `--dap`).
#[derive(Debug, Clone, PartialEq)]
pub struct Stmt {
    pub line: u32,
    pub kind: StmtKind,
}

impl Stmt {
    /// Build a statement carrying its source line.
    pub fn new(line: u32, kind: StmtKind) -> Self {
        Stmt { line, kind }
    }
}

/// The kind of a Java statement (the payload of [`Stmt`]).
#[derive(Debug, Clone, PartialEq)]
pub enum StmtKind {
    /// A local variable declaration: `int x = expr;`, `var s = expr;`. The
    /// declared type is retained for diagnostics; the runtime is dynamically
    /// typed on the fusevm value model, so it does not gate execution yet.
    Local {
        ty: String,
        /// The type arguments of the declared type, outermost level, each in
        /// [`generic_parts`] form: `Map<String, List<Integer>>` holds `String`
        /// and `List<Integer>`. `ty` itself stays erased (`Map`); these are
        /// what types a `get` or a lambda parameter the way `javac` does.
        /// Empty for a raw or non-generic type, a type variable erases to
        /// `Object`, and a wildcard reads as its upper bound.
        targs: Vec<String>,
        /// Whether one of those top-level arguments was written as a wildcard
        /// (`Comparable<? extends Number>`), which `targs` alone cannot tell
        /// from the exact `Comparable<Number>`.
        wildcard: bool,
        /// The positions of the arguments written as a lower-bounded wildcard
        /// (`? super Integer`), which `targs` reads as `Object`: an element
        /// read through one is a capture type (`crate::flow` checks it).
        super_slots: Vec<usize>,
        name: String,
        init: Option<Expr>,
        /// Whether the declaration carried `final`, which the definite-
        /// assignment pass (`crate::flow`) needs: a `final` local may be
        /// assigned only while definitely unassigned (JLS 16).
        is_final: bool,
    },
    /// One declaration statement that declares more than one variable:
    /// `int a = 1, b = 2;`. Each element is a [`StmtKind::Local`], in source
    /// order, so every declarator keeps its own type (a C-style declarator
    /// suffix binds to the *name*, so `int a[], b;` declares an `int[]` and an
    /// `int`) and its own initializer. Java evaluates them left to right, and a
    /// later declarator may read an earlier one (`int a = 1, b = a + 1;`).
    Locals(Vec<Stmt>),
    /// An assignment to an existing variable: `x = expr;`, `x += expr;`.
    Assign {
        name: String,
        op: AssignOp,
        value: Expr,
    },
    /// An assignment to an array element: `a[i] = expr;`, `a[i] += expr;`.
    IndexAssign {
        array: Expr,
        index: Expr,
        op: AssignOp,
        value: Expr,
    },
    /// An assignment to an instance field: `obj.f = expr;`, `this.f += expr;`.
    FieldAssign {
        recv: Expr,
        name: String,
        op: AssignOp,
        value: Expr,
    },
    /// An expression evaluated for its side effects: `System.out.println(x);`.
    Expr(Expr),
    /// `if (cond) { .. } else { .. }`.
    If {
        cond: Expr,
        then: Vec<Stmt>,
        els: Vec<Stmt>,
    },
    /// `while (cond) { .. }`.
    While { cond: Expr, body: Vec<Stmt> },
    /// `do { .. } while (cond);` — the body runs once before the condition is
    /// first tested.
    DoWhile { body: Vec<Stmt>, cond: Expr },
    /// `for (init; cond; update) { .. }` — the C-style loop.
    For {
        /// The init clause, which Java lets be a comma-separated list — either
        /// several declarators of one type (`int i = 0, j = n`) or several
        /// expression statements. Empty when the clause is.
        init: Vec<Stmt>,
        cond: Option<Expr>,
        /// The update clause, likewise a comma-separated list (`i++, j--`).
        update: Vec<Stmt>,
        body: Vec<Stmt>,
    },
    /// `for (T x : arr) { .. }` — the enhanced (`for-each`) loop. Java defines
    /// it over arrays and `Iterable`; javars has no collections, so the source
    /// of elements is always an array. Kept as its own node rather than
    /// desugared in the parser because the index cursor and the array temp must
    /// be compiler-minted internal names (`#t0`), which are not expressible in
    /// the `Stmt` surface the parser produces.
    ForEach {
        /// The declared element type (`String`, `int`, `var`, …) — recorded for
        /// `/`-truncation typing and class-typed dispatch of the loop variable.
        ty: String,
        /// The element type's type arguments, see [`StmtKind::Local::targs`].
        targs: Vec<String>,
        /// See [`StmtKind::Local::super_slots`].
        super_slots: Vec<usize>,
        name: String,
        /// Whether the loop variable was declared `final`.
        is_final: bool,
        /// The array expression, evaluated exactly once before the loop.
        iter: Expr,
        body: Vec<Stmt>,
    },
    /// `switch (disc) { case L: .. break; default: .. }` — the classic
    /// statement form with fall-through between groups.
    Switch {
        disc: Expr,
        groups: Vec<SwitchGroup>,
    },
    /// A labeled statement `label: <stmt>`. The label names the enclosing loop
    /// or switch so `break label;`/`continue label;` can target it.
    Labeled { label: String, body: Box<Stmt> },
    /// `try { .. } catch (E e) { .. } … finally { .. }`. `catches` may be empty
    /// (a `try`/`finally`), and `finally_body` may be empty (a `try`/`catch`).
    Try {
        body: Vec<Stmt>,
        catches: Vec<CatchArm>,
        finally_body: Vec<Stmt>,
    },
    /// `throw <expr>;` — raise the (already-constructed) throwable.
    Throw(Expr),
    /// The declaration of a local class (JLS 14.3), by its binary name. The
    /// class itself is hoisted to the program's type list, so this lowers to
    /// no code; it marks where definite assignment judges the enclosing
    /// locals the class body names (javac's `visitClassDef` of a local class).
    LocalClass(String),
    /// `assert cond;` / `assert cond : detail;` (JLS 14.10). The launcher runs
    /// with assertions disabled unless `-ea` is given, and a disabled assertion
    /// evaluates neither expression, so it lowers to no code — but it is kept
    /// for definite assignment (JLS 16.2.15), which reads both expressions.
    Assert { cond: Expr, detail: Option<Expr> },
    /// `yield <expr>;` — supply the value of the enclosing arrow-`switch`
    /// *expression* from inside a block arm. Parsed as a keyword only inside
    /// such a block, because `yield` is a contextual keyword everywhere else.
    Yield(Expr),
    /// `break;` or `break label;`.
    Break(Option<String>),
    /// `continue;` or `continue label;`.
    Continue(Option<String>),
    /// `return;` or `return <expr>;`. In `main` (which is `void`) a bare return
    /// ends the program and a value return is rejected; in a method it lowers to
    /// `Op::ReturnValue`.
    Return(Option<Expr>),
}

/// One group of a `switch`: its `case` label expressions (and/or `default`),
/// followed by the statements that run when a label matches. Fall-through is
/// modeled by laying the groups' bodies out consecutively — control drops into
/// the next group's body unless a `break` intervenes. `case 1: case 2: body`
/// is a single group with two labels.
#[derive(Debug, Clone, PartialEq)]
pub struct SwitchGroup {
    /// The `case` label constant expressions selecting this group. A
    /// [`Expr::TypePattern`] here is a *pattern* label rather than a constant.
    pub labels: Vec<Expr>,
    /// True when this group carries the `default:` label.
    pub is_default: bool,
    /// A `when` guard: the group matches only when its label matched *and* this
    /// is true. `None` for an unguarded group.
    pub guard: Option<Expr>,
    /// The statements of this group.
    pub body: Vec<Stmt>,
}

/// One `catch (Type name) { body }` clause. Arms are tested in source order and
/// the first whose type the thrown object `instanceof`-matches wins — Java's
/// rule, and the reason a `catch (Exception e)` written before a
/// `catch (RuntimeException e)` shadows it.
#[derive(Debug, Clone, PartialEq)]
pub struct CatchArm {
    /// The caught type names (`RuntimeException`, a user class, …). A
    /// multi-catch (`catch (A | B e)`) lists more than one; the arm runs when
    /// the throwable matches any of them.
    pub types: Vec<String>,
    /// The bound exception variable.
    pub name: String,
    /// Whether the parameter was declared `final` (a multi-catch parameter
    /// is implicitly final whatever this says).
    pub is_final: bool,
    pub body: Vec<Stmt>,
}

/// Compound-assignment operator. `Assign` is a plain `=`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AssignOp {
    Assign,
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    /// `&=`
    BitAnd,
    /// `|=`
    BitOr,
    /// `^=`
    BitXor,
    /// `<<=`
    Shl,
    /// `>>=`
    Shr,
    /// `>>>=`
    Ushr,
}

/// A Java expression.
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
    /// `T.class` / `int.class` — a class literal.
    ///
    /// Held as the type NAME as written. javars has no `Class` object: a class
    /// is its binary name, over which `getName`/`getSimpleName` answer, which is
    /// what `x.getClass()` already evaluates to. So the literal resolves to the
    /// same string, and the two spellings agree by construction.
    ClassLit(String),
    Int(i64),
    /// An `L`-suffixed integer literal. Runs on the same 64-bit value as
    /// [`Expr::Int`]; the distinct node exists only so the static type is
    /// `long`, which keeps the operation out of the 32-bit `int` wrap.
    Long(i64),
    Float(f64),
    /// An `f`-suffixed floating literal. Java types it `float`, a *32-bit*
    /// value: every operation on one rounds to `f32`, and its string form is the
    /// shortest decimal that round-trips through `f32` — `1.0f / 3.0f` is
    /// `0.33333334`, not the `double` `0.3333333333333333`.
    Float32(f64),
    Str(String),
    /// A `char` literal. Runs as its code point (an integer), because Java's
    /// `char` is an integral type that participates in numeric promotion; the
    /// distinct node exists so the static type is `char`, which is what turns
    /// the value back into a one-character String at a string conversion.
    Char(char),
    Bool(bool),
    /// A bare identifier — a local variable read.
    Var(String),
    /// A unary operator applied to one operand (`-x`, `!b`).
    Unary {
        op: UnOp,
        rhs: Box<Expr>,
    },
    /// A binary operator applied to two operands.
    Binary {
        op: BinOp,
        lhs: Box<Expr>,
        rhs: Box<Expr>,
    },
    /// `cond ? then : els` — the conditional (ternary) operator. Right-
    /// associative; the result takes the value of the selected branch.
    Ternary {
        cond: Box<Expr>,
        then: Box<Expr>,
        els: Box<Expr>,
    },
    /// `System.out.println(arg)` / `System.out.print(arg)`, or the `System.err`
    /// variants when `err` is set. Modeled directly (rather than as a general
    /// method call) because `System.out`/`err` are streams, not values.
    Println {
        newline: bool,
        err: bool,
        arg: Option<Box<Expr>>,
    },
    /// Post-increment / post-decrement of a variable (`i++`, `i--`). As an
    /// expression it yields the value the variable held *before* the update; the
    /// bool is `true` for `++`.
    PostIncDec {
        name: String,
        inc: bool,
    },
    /// Pre-increment / pre-decrement of a variable (`++i`, `--i`) — updates
    /// first and yields the *new* value. The bool is `true` for `++`.
    PreIncDec {
        name: String,
        inc: bool,
    },
    /// `++`/`--` on an lvalue that is not a plain named variable — an array
    /// element (`a[i]++`) or a field (`p.n++`, `C.total++`). A bare variable
    /// keeps [`Expr::PostIncDec`]/[`Expr::PreIncDec`], which name it directly;
    /// this form has to hold the whole target expression so its receiver or
    /// index is evaluated exactly once. `inc` is `true` for `++`, `post` is
    /// `true` for the suffix form (which yields the value held before).
    IncDec {
        target: Box<Expr>,
        inc: bool,
        post: bool,
        line: u32,
    },
    /// An assignment in *value* position: `(n = next()) != -1`, `a = b = 0`,
    /// `if ((x += 2) > 5)`. Java's assignment is an expression whose value is
    /// the variable's value after the store (JLS 15.26), so the result is read
    /// back from the target rather than taken from the right-hand side — which
    /// is what makes `byte b; (b += 200)` yield the narrowed value. `target` is
    /// a [`Expr::Var`], [`Expr::Index`], or [`Expr::Field`]; its array, index,
    /// or receiver is evaluated exactly once. An assignment in *statement*
    /// position still parses to [`StmtKind::Assign`] and its siblings.
    Assign {
        target: Box<Expr>,
        op: AssignOp,
        value: Box<Expr>,
        line: u32,
    },
    /// A cast, `(ty) expr`. Java's narrowing primitive conversions are real
    /// value changes (`(int) 3.9` is 3, `(byte) 200` is -56), so the target type
    /// is kept rather than erased; a reference cast is a no-op at runtime here,
    /// because the host heap already carries each object's class.
    Cast {
        ty: String,
        /// The type arguments written on the cast type (`(List<Float>) o`), see
        /// [`StmtKind::Local::targs`].
        targs: Vec<String>,
        expr: Box<Expr>,
        line: u32,
    },
    /// A bare-identifier function call `name(args...)`. Slice 1 declares no
    /// user methods, so the only calls that reach the compiler are the inline
    /// Rust FFI desugar target `__rust_compile("<base64>", line)` and the
    /// barewords a `rust { ... }` block exports (routed to `fusevm::ffi` by
    /// name — see [`crate::rust_ffi`] and [`crate::host`]). A call name that is
    /// neither, with no FFI block present, is an unresolved reference.
    Call {
        name: String,
        args: Vec<Expr>,
        line: u32,
    },
    /// An instance method call `recv.method(args...)`. Dispatches on the
    /// receiver's static type: a `String` receiver runs the [`crate::host`]
    /// string builtins (`length`, `substring`, …); a user-class receiver calls
    /// the class's mangled instance-method subroutine (static-type dispatch —
    /// exact when there is no overriding). `System.out.print[ln]` keeps its
    /// dedicated [`Expr::Println`] form.
    MethodCall {
        recv: Box<Expr>,
        method: String,
        args: Vec<Expr>,
        line: u32,
    },
    /// `new int[n]` / `new int[m][n]` — a fresh (possibly multi-dimensional)
    /// array of default-valued elements. The element type sets the leaf default
    /// (`int`→0, `double`→0.0, `boolean`→false, a class/`String`→`null`).
    /// `sizes` holds the explicitly-sized dimensions (outer first); `extra_dims`
    /// counts trailing unsized `[]` dimensions (`new int[2][]` → `sizes=[2]`,
    /// `extra_dims=1`), whose innermost elements default to `null`. Lives on the
    /// host heap as `Obj` handles, so aliasing is by reference.
    NewArray {
        elem_ty: String,
        sizes: Vec<Expr>,
        extra_dims: usize,
    },
    /// An array literal `{a, b, c}` (from `int[] a = {1,2,3}` or
    /// `new int[]{1,2,3}`). Builds a heap array from the element values.
    ArrayLit {
        elems: Vec<Expr>,
        /// The element type when the literal named one (`new int[]{…}`), so
        /// `var a = new int[]{1, 2};` still infers `int[]` and its elements
        /// still truncate their division. `None` for the bare `{…}` form, whose
        /// type comes from the declaration it initializes.
        elem_ty: Option<String>,
    },
    /// `array[index]` — element read. Bounds-checked at runtime.
    Index {
        array: Box<Expr>,
        index: Box<Expr>,
    },
    /// `recv.field` field access with no call parens: an array's `.length` or an
    /// instance field. (String's `.length()` keeps its method-call form.)
    Field {
        recv: Box<Expr>,
        name: String,
    },
    /// `new ClassName(args...)` — construct a class instance on the host heap.
    NewObject {
        class: String,
        args: Vec<Expr>,
        /// The type arguments written on the class (`new Box<Float>(…)`), in
        /// [`generic_parts`] form: `None` for a raw `new Box(…)`, empty for the
        /// diamond `new Box<>(…)`, whose arguments are inferred.
        targs: Option<Vec<String>>,
        /// The explicit enclosing instance of `outer.new Inner(…)`; `None` for
        /// a bare `new`, whose enclosing instance (for an inner class) is the
        /// innermost `this` of the right type.
        outer: Option<Box<Expr>>,
        line: u32,
    },
    /// `this` — the receiver of the enclosing instance method or constructor
    /// (frame slot 0).
    This,
    /// A `switch` *pattern* label — `case Circle c ->`. It appears only in a
    /// [`SwitchArm`]'s or [`SwitchGroup`]'s `labels`, never as a value: the
    /// subject it tests is the `switch`'s own discriminant, which the label has
    /// no way to name, so the compiler supplies it.
    ///
    /// This is deliberately a separate node from [`Expr::InstanceOf`] rather
    /// than one carrying a placeholder subject — a label that *looks* like an
    /// expression but silently means something else is the kind of thing that
    /// goes wrong at the next call site that treats labels uniformly.
    TypePattern {
        class: String,
        binding: Option<String>,
        /// A *record* pattern's component sub-patterns, in component order
        /// (`case Pt(int x, int y)`). Empty for a plain type pattern. Each
        /// element is itself a `TypePattern`, so the form nests.
        components: Vec<Expr>,
    },
    /// `expr instanceof ClassName` — true when `expr` is a non-null instance of
    /// `ClassName` or a subclass.
    ///
    /// `binding` is the name of a *type pattern*'s variable
    /// (`o instanceof String s`), which Java brings into scope wherever the
    /// pattern definitely matched. It is `None` for the plain form.
    InstanceOf {
        expr: Box<Expr>,
        class: String,
        binding: Option<String>,
        /// A record pattern's component sub-patterns — the same shape
        /// [`Expr::TypePattern`] carries, for `o instanceof Pt(int x, int y)`.
        components: Vec<Expr>,
    },
    /// A lambda expression: `() -> e`, `x -> e`, `(a, b) -> { … }`. Compiled to
    /// a heap closure that captures the enclosing scope **by value**, because a
    /// lambda outlives the fusevm call frame whose slots hold those locals.
    /// Java only lets a lambda capture effectively-final locals, so a by-value
    /// snapshot is observationally exact.
    Lambda {
        /// Formal parameter names, in order. Declared types (`(int a) -> …`) are
        /// erased by the parser, exactly as they are for every other javars
        /// declaration.
        params: Vec<String>,
        /// Which of `params` were declared `final`, parallel to it; empty when
        /// none was (a synthesized lambda never has one). Only definite
        /// assignment reads it: assigning one is `final parameter x may not be
        /// assigned` (JLS 4.12.4).
        finals: Vec<bool>,
        body: LambdaBody,
        line: u32,
    },
    /// A method reference: `String::length`, `Integer::parseInt`, `obj::run`,
    /// `Point::new`. Desugared by the compiler into the equivalent
    /// [`Expr::Lambda`] once the referenced member's arity is known.
    MethodRef {
        /// The receiver expression — a value (`obj::run`, captured by the
        /// synthesized lambda) or a bare type name (`String::length`, which
        /// takes the receiver as its first parameter instead).
        recv: Box<Expr>,
        /// The referenced member, or `new` for a constructor reference.
        method: String,
        line: u32,
    },
    /// A `switch` *expression* in the arrow form:
    /// `int r = switch (x) { case 1, 2 -> 10; default -> 0; };`. Arms do not
    /// fall through, exactly one runs, and its value is the expression's value.
    SwitchExpr {
        disc: Box<Expr>,
        arms: Vec<SwitchArm>,
        line: u32,
    },
}

/// One arm of an arrow `switch`: `case A, B -> body` or `default -> body`.
#[derive(Debug, Clone, PartialEq)]
pub struct SwitchArm {
    /// The `case` label constant expressions selecting this arm. A
    /// [`Expr::TypePattern`] here is a *pattern* label rather than a constant.
    pub labels: Vec<Expr>,
    /// True when this arm carries `default`.
    pub is_default: bool,
    /// A `when` guard: the arm matches only when its label matched *and* this is
    /// true. `None` for an unguarded arm.
    pub guard: Option<Expr>,
    pub body: SwitchArmBody,
}

/// An arrow arm's right-hand side.
#[derive(Debug, Clone, PartialEq)]
pub enum SwitchArmBody {
    /// `case 1 -> expr;` — the expression is the arm's value.
    Expr(Box<Expr>),
    /// `case 1 -> { … yield v; }` — a block whose `yield` supplies the value.
    Block(Vec<Stmt>),
}

/// A lambda's body: a single expression (whose value is the result) or a block.
#[derive(Debug, Clone, PartialEq)]
pub enum LambdaBody {
    /// `x -> x + 1` — the expression is the returned value.
    Expr(Box<Expr>),
    /// `x -> { … }` — statements; a `return e;` inside supplies the value and a
    /// fall-off returns `null` (which is what a `void` functional interface
    /// wants).
    Block(Vec<Stmt>),
}

/// Unary operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnOp {
    Neg,
    Not,
    /// `~x` — bitwise complement of an integral operand.
    BitNot,
    /// `+x` — leaves the value alone but still applies unary numeric promotion
    /// (JLS 5.6.1), so `+aChar` is an `int`. That is observable: `"" + +'A'`
    /// is `"65"`, not `"A"`.
    Plus,
}

/// Binary operators.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinOp {
    Add,
    Sub,
    Mul,
    Div,
    Mod,
    Eq,
    Ne,
    Lt,
    Gt,
    Le,
    Ge,
    And,
    Or,
    /// `&` — bitwise AND on integers, non-short-circuit AND on booleans.
    BitAnd,
    /// `|` — bitwise OR on integers, non-short-circuit OR on booleans.
    BitOr,
    /// `^` — bitwise XOR on integers, "not equal" on booleans.
    BitXor,
    /// `<<` — left shift.
    Shl,
    /// `>>` — arithmetic (sign-propagating) right shift.
    Shr,
    /// `>>>` — logical (zero-fill) right shift.
    Ushr,
}

/// Split a type in the form [`StmtKind::Local::targs`] records into its erased
/// name and its top-level type arguments: `Map<String,List<Integer>>` is `Map`
/// with `String` and `List<Integer>`; `Integer` is `Integer` with none.
///
/// A trailing array suffix belongs to the whole type, so `List<Integer>[]`
/// splits as `List[]` with no arguments — an array's own methods never see its
/// element's type arguments.
pub fn generic_parts(ty: &str) -> (String, Vec<String>) {
    let Some(open) = ty.find('<') else {
        return (ty.to_string(), Vec::new());
    };
    let close = ty.rfind('>').unwrap_or(ty.len() - 1);
    let suffix = &ty[close + 1..];
    let name = format!("{}{suffix}", &ty[..open]);
    if !suffix.is_empty() {
        return (name, Vec::new());
    }
    (name, split_top_level(&ty[open + 1..close]))
}

/// The comma-separated items of a type-argument list, splitting only at depth
/// zero so `String,List<Integer>` is two items.
fn split_top_level(s: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut depth = 0i32;
    let mut cur = String::new();
    for ch in s.chars() {
        match ch {
            '<' => depth += 1,
            '>' => depth -= 1,
            ',' if depth == 0 => {
                out.push(std::mem::take(&mut cur));
                continue;
            }
            _ => {}
        }
        cur.push(ch);
    }
    if !cur.is_empty() {
        out.push(cur);
    }
    out
}

/// Normalize the source text of one type argument (`? extends Number`,
/// `java.util.List<Integer>`, `int[]`) into [`generic_parts`] form: a wildcard
/// reads as its upper bound — `Object` when it has none or a lower one — and a
/// package or enclosing-type qualifier is dropped, as every other type position
/// drops it.
pub fn normalize_type_arg(raw: &str) -> String {
    let s = raw.trim();
    if let Some(rest) = s.strip_prefix('?') {
        let rest = rest.trim_start();
        return match rest.strip_prefix("extends") {
            Some(bound) if bound.starts_with(char::is_whitespace) => {
                // `? extends A & B` cannot occur (only a type parameter takes
                // an intersection bound), so the bound is one type.
                normalize_type_arg(bound)
            }
            _ => "Object".to_string(),
        };
    }
    let (head, tail) = match s.find(['<', '[']) {
        Some(i) => s.split_at(i),
        None => (s, ""),
    };
    let simple = head.rsplit('.').next().unwrap_or(head).trim();
    let Some(inner) = tail.strip_prefix('<') else {
        return format!("{simple}{}", tail.replace(' ', ""));
    };
    let mut depth = 1i32;
    let mut end = inner.len();
    for (i, ch) in inner.char_indices() {
        match ch {
            '<' => depth += 1,
            '>' => {
                depth -= 1;
                if depth == 0 {
                    end = i;
                    break;
                }
            }
            _ => {}
        }
    }
    let args: Vec<String> = split_top_level(&inner[..end])
        .iter()
        .map(|a| normalize_type_arg(a))
        .collect();
    let rest = inner.get(end + 1..).unwrap_or("").replace(' ', "");
    format!("{simple}<{}>{rest}", args.join(","))
}