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
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
//! A recursive-descent parser with precedence-climbing for expressions.
//!
//! Grammar: a compilation unit is one or more `class`/`interface` declarations;
//! javars locates `public static void main(String[] args) { <body> }` as the
//! entry and parses every other member (fields, constructors, static and
//! instance methods) into the AST. Statements cover local decls, assignments,
//! `if`/`while`/`do`/`for` (C-style and enhanced)/`switch`, labeled
//! `break`/`continue`, `return`, `try`/`catch`/`finally`, `throw`,
//! `System.out.print[ln]`, and post-inc/dec.

use crate::ast::*;
use crate::lexer::{Tok, Token};

/// Parse Java `src` into a [`Program`].
pub fn parse(src: &str) -> Result<Program, String> {
    let tokens = crate::lexer::lex(src)?;
    let mut p = Parser {
        toks: tokens,
        pos: 0,
        uses_exceptions: false,
        uses_functional: false,
        switch_expr_depth: 0,
    };
    p.program()
}

/// One entry of a try-with-resources header. `decl` is the declared type and
/// initializer (`Type r = expr`); a bare `try (r)` naming an already-declared
/// variable carries `None` and only contributes the `close()` call.
struct Resource {
    decl: Option<(String, Expr)>,
    name: String,
    line: u32,
}

/// The located entry point: the class declaring `main`, its body, and the name
/// it gives its `String[]` parameter (if it declares one).
struct Entry {
    class_name: String,
    body: Vec<Stmt>,
    param: Option<String>,
}

struct Parser {
    toks: Vec<Token>,
    pos: usize,
    /// Set when a `try`, a `throw`, or a `new` of a modeled `java.lang`
    /// throwable is parsed — the signal that this unit needs the exception
    /// prelude and the compiler's exception lowering (see
    /// [`crate::ast::Program::uses_exceptions`]).
    uses_exceptions: bool,
    /// Set when a lambda, a method reference, or a declared
    /// `java.util.function` type is parsed — the signal that this unit needs the
    /// functional-interface prelude (see
    /// [`crate::ast::Program::uses_functional`]).
    uses_functional: bool,
    /// How many arrow-`switch` arm bodies enclose the cursor. `yield` is a
    /// keyword only inside one; everywhere else it is an ordinary identifier,
    /// which is Java's contextual rule (a variable or method named `yield`
    /// predates the keyword and must keep working).
    switch_expr_depth: usize,
}

impl Parser {
    fn peek(&self) -> &Tok {
        &self.toks[self.pos].kind
    }

    fn line(&self) -> u32 {
        self.toks[self.pos].line
    }

    fn advance(&mut self) -> Tok {
        let t = self.toks[self.pos].kind.clone();
        if self.pos < self.toks.len() - 1 {
            self.pos += 1;
        }
        t
    }

    fn eat(&mut self, want: &Tok) -> Result<(), String> {
        if std::mem::discriminant(self.peek()) == std::mem::discriminant(want) {
            self.advance();
            Ok(())
        } else {
            Err(format!(
                "javars: expected {want} but found {} on line {}",
                self.peek(),
                self.line()
            ))
        }
    }

    fn is(&self, t: &Tok) -> bool {
        std::mem::discriminant(self.peek()) == std::mem::discriminant(t)
    }

    /// A compilation unit: one or more top-level classes. Locates the class
    /// declaring `public static void main(String[] args)` (the entry) and
    /// flattens every class (top-level siblings and nested `static` classes)
    /// into [`Program::classes`]. Leading `import`/`package` lines are tolerated.
    fn program(&mut self) -> Result<Program, String> {
        // Skip package/import prologue lines.
        loop {
            match self.peek() {
                Tok::Ident(w) if w == "package" || w == "import" => {
                    while !self.is(&Tok::Semi) && !self.is(&Tok::Eof) {
                        self.advance();
                    }
                    self.eat(&Tok::Semi)?;
                }
                _ => break,
            }
        }
        let mut entry: Option<Entry> = None;
        let mut methods = Vec::new();
        let mut classes = Vec::new();
        // Top-level type declarations, in sequence.
        while !self.is(&Tok::Eof) {
            self.parse_class(None, &mut entry, &mut methods, &mut classes)?;
        }
        match entry {
            Some(entry) => Ok(Program {
                class_name: entry.class_name,
                main: entry.body,
                main_param: entry.param,
                methods,
                classes,
                uses_exceptions: self.uses_exceptions,
                uses_functional: self.uses_functional,
            }),
            None => Err(
                "javars: no class declares `public static void main(String[] args)`".to_string(),
            ),
        }
    }

    /// Parse one `[modifiers] class Name [extends Super] { members }`. The entry
    /// `main` body (when present) is written to `entry`; `static` methods go to
    /// the flat `methods` pool; the class itself (with its fields, constructors,
    /// and instance methods) is pushed to `classes`. Nested classes recurse into
    /// the same three sinks (flattened namespace).
    fn parse_class(
        &mut self,
        enclosing: Option<&str>,
        entry: &mut Option<Entry>,
        methods: &mut Vec<Method>,
        classes: &mut Vec<Class>,
    ) -> Result<(), String> {
        // modifiers (`public`, `static`, and the ident-form ones — see
        // [`class_modifier_len`], which also spells `non-sealed`)
        loop {
            let n = class_modifier_len(&self.toks, self.pos);
            if n == 0 {
                break;
            }
            self.pos += n;
        }
        let line = self.line();
        // `class Name`, `interface Name`, or `enum Name`. Neither `interface`
        // nor `enum` is a reserved token in this lexer, so both are matched by
        // name here.
        let is_interface = matches!(self.peek(), Tok::Ident(w) if w == "interface");
        let is_enum = matches!(self.peek(), Tok::Ident(w) if w == "enum");
        let is_record = self.at_record();
        if is_interface || is_enum || is_record {
            self.advance();
        } else {
            self.eat(&Tok::Class)?;
        }
        let name = self.ident()?;
        // Java's binary name nests with `$`; the enclosing declaration passes
        // down its own binary name, so a doubly-nested type is `A$B$C`.
        let binary = match enclosing {
            Some(outer) => format!("{outer}${name}"),
            None => name.clone(),
        };
        // Optional generic type-parameter declaration `<T>`, `<T extends X>`,
        // `<K, V>` — erased (parsed and discarded).
        self.skip_generics();
        // A record's header carries its components: `record Point(int x, int y)`.
        let components = if is_record {
            self.eat(&Tok::LParen)?;
            let ps = self.params()?;
            self.eat(&Tok::RParen)?;
            ps
        } else {
            Vec::new()
        };
        // `extends`: a class has a single superclass; an interface may extend
        // several interfaces (collected as `interfaces`).
        let mut superclass = None;
        let mut interfaces = Vec::new();
        if matches!(self.peek(), Tok::Ident(w) if w == "extends") {
            self.advance();
            loop {
                let sup = self.type_name()?;
                // `class MyEx extends RuntimeException { … }` needs the modeled
                // throwable hierarchy just as much as a `throw` does — the
                // superclass is where `detailMessage`, `getMessage()` and
                // `toString()` come from. Without this, the prelude was skipped
                // for a program that only *subclasses* an exception, the
                // `extends` dangled, and `e.getMessage()` was "class `MyEx` has
                // no method `getMessage`" while `println(e)` rendered the
                // `Object` default `T$MyEx@1` instead of `T$MyEx: b`.
                if crate::prelude::is_throwable(&sup) {
                    self.uses_exceptions = true;
                }
                if is_interface {
                    interfaces.push(sup);
                } else {
                    superclass = Some(sup);
                }
                if self.is(&Tok::Comma) {
                    self.advance();
                } else {
                    break;
                }
            }
        }
        // `implements I, J` (classes only).
        if matches!(self.peek(), Tok::Ident(w) if w == "implements") {
            self.advance();
            loop {
                interfaces.push(self.type_name()?);
                if self.is(&Tok::Comma) {
                    self.advance();
                } else {
                    break;
                }
            }
        }
        // `permits A, B` — a `sealed` type's list of allowed subtypes. It is a
        // *compile-time* restriction: `javac` has already rejected every
        // implementation outside the list, and a permitted subtype declares its
        // own `implements`/`extends` edge, so the list adds nothing the
        // supertype graph does not already carry. Parsed and discarded, like the
        // generic parameters above.
        if matches!(self.peek(), Tok::Ident(w) if w == "permits") {
            self.advance();
            loop {
                self.type_name()?;
                if self.is(&Tok::Comma) {
                    self.advance();
                } else {
                    break;
                }
            }
        }
        self.eat(&Tok::LBrace)?;

        let mut fields = Vec::new();
        let mut static_fields = Vec::new();
        let mut static_init = Vec::new();
        let mut inst_init = Vec::new();
        let mut ctors = Vec::new();
        let mut inst_methods = Vec::new();
        // An `enum` body opens with its constant list; the ordinary members (if
        // any) follow the `;` that terminates it.
        let enum_constants = if is_enum {
            self.enum_constants(&name, classes)?
        } else {
            Vec::new()
        };
        while !self.is(&Tok::RBrace) && !self.is(&Tok::Eof) {
            if let Some(body) = self.try_static_block()? {
                static_init.extend(body);
            } else if let Some(found) = self.try_main()? {
                *entry = Some(Entry {
                    class_name: name.clone(),
                    ..found
                });
            } else if self.at_nested_class() {
                self.parse_class(Some(&binary), entry, methods, classes)?;
            } else if let Some(c) = self.try_compact_ctor(&name, is_record, &components)? {
                ctors.push(c);
            } else if let Some(c) = self.try_ctor(&name)? {
                ctors.push(c);
            } else if let Some((m, is_static)) = self.try_any_method(&name)? {
                if is_static {
                    methods.push(m);
                } else {
                    inst_methods.push(m);
                }
            } else if let Some((fs, is_static)) = self.try_fields()? {
                if is_static {
                    static_declaration(line, fs, &mut static_fields, &mut static_init);
                } else {
                    instance_declaration(line, fs, &mut fields, &mut inst_init);
                }
            } else if self.is(&Tok::LBrace) {
                // A bare `{ … }` at member position is an instance initializer
                // (JLS 8.6). It runs on every new instance in textual order with
                // the field initializers; `skip_member` used to drop it, which
                // silently lost everything it did.
                self.advance();
                inst_init.extend(self.block()?);
            } else {
                self.skip_member()?;
            }
        }
        self.eat(&Tok::RBrace)?;
        if is_enum {
            enum_members(line, &name, &mut fields, &mut inst_methods);
        }
        if is_record {
            record_members(
                line,
                &name,
                &components,
                &mut fields,
                &mut ctors,
                &mut inst_methods,
            );
        }
        classes.push(Class {
            name,
            binary,
            superclass,
            interfaces,
            is_interface,
            is_enum,
            is_record,
            enum_constants,
            fields,
            static_fields,
            static_init,
            inst_init,
            ctors,
            methods: inst_methods,
            line,
        });
        Ok(())
    }

    /// Parse a `static { … }` initializer block, returning its statements. The
    /// cursor is restored and `None` returned when the member is something else.
    fn try_static_block(&mut self) -> Result<Option<Vec<Stmt>>, String> {
        if !(matches!(self.peek(), Tok::Static)
            && matches!(self.toks[self.pos + 1].kind, Tok::LBrace))
        {
            return Ok(None);
        }
        self.advance(); // static
        self.advance(); // {
        Ok(Some(self.block()?))
    }

    /// Parse an `enum` body's constant list (the cursor just past `{`), and give
    /// the type the state and accessors every enum has.
    ///
    /// javars models an enum as an ordinary class with two synthesized fields —
    /// `#name` and `#ordinal`, whose `#` is not a legal Java identifier char, so
    /// they cannot collide with a user field — plus the `name()`, `ordinal()`,
    /// and `toString()` bodies that read them. The compiler builds one instance
    /// per constant before `main` runs (see `Compiler::emit_enum_prologue`), so
    /// everything else (virtual dispatch, `instanceof`, reference `==`, arrays)
    /// applies unchanged.
    ///
    /// A constant may carry constructor arguments (`EARTH(5.97e24)`), a class
    /// body (`PLUS { int apply(…) { … } }`), or both. Java specifies a constant
    /// with a body as an anonymous *subclass* of the enum, so the body is
    /// parsed into a real synthetic class pushed onto `classes`; its overrides
    /// are then reached by the same virtual dispatch every other subclass uses.
    fn enum_constants(
        &mut self,
        name: &str,
        classes: &mut Vec<Class>,
    ) -> Result<Vec<EnumConstant>, String> {
        let mut constants = Vec::new();
        while matches!(self.peek(), Tok::Ident(_)) {
            let line = self.line();
            let c = self.ident()?;
            let args = if self.is(&Tok::LParen) {
                self.call_args()?
            } else {
                Vec::new()
            };
            let body_class = if self.is(&Tok::LBrace) {
                self.advance();
                let cl = self.enum_constant_body(name, &c, line)?;
                let cname = cl.name.clone();
                classes.push(cl);
                Some(cname)
            } else {
                None
            };
            constants.push(EnumConstant {
                name: c,
                line,
                args,
                body_class,
            });
            if self.is(&Tok::Comma) {
                self.advance();
            } else {
                break;
            }
        }
        // The `;` is optional when the body holds nothing but constants.
        if self.is(&Tok::Semi) {
            self.advance();
        }
        Ok(constants)
    }

    /// Parse an enum constant's `{ … }` body (the cursor just past the `{`) into
    /// the synthetic subclass that models it. A constant body may declare fields
    /// and methods but no constructor — the enum's own constructor runs against
    /// the arguments the constant supplied.
    fn enum_constant_body(
        &mut self,
        enum_name: &str,
        constant: &str,
        line: u32,
    ) -> Result<Class, String> {
        let name = enum_body_class(enum_name, constant);
        let mut fields = Vec::new();
        let mut static_fields = Vec::new();
        let mut static_init = Vec::new();
        let mut inst_init = Vec::new();
        let mut methods = Vec::new();
        while !self.is(&Tok::RBrace) && !self.is(&Tok::Eof) {
            if let Some((m, _)) = self.try_any_method(&name)? {
                methods.push(m);
            } else if let Some((fs, is_static)) = self.try_fields()? {
                if is_static {
                    static_declaration(line, fs, &mut static_fields, &mut static_init);
                } else {
                    instance_declaration(line, fs, &mut fields, &mut inst_init);
                }
            } else {
                return Err(format!(
                    "javars: unsupported member in the body of enum constant `{enum_name}.{constant}` (line {})",
                    self.line()
                ));
            }
        }
        self.eat(&Tok::RBrace)?;
        Ok(Class {
            // An enum constant body is a synthetic subclass javars mints; Java
            // names its own `Outer$Enum$1`, which is a counter this frontend does
            // not model, so the synthetic name stands in.
            binary: name.clone(),
            name,
            superclass: Some(enum_name.to_string()),
            interfaces: Vec::new(),
            is_interface: false,
            is_enum: false,
            // The body of an enum constant is an anonymous subclass of the enum,
            // never a record of its own.
            is_record: false,
            enum_constants: Vec::new(),
            fields,
            static_fields,
            static_init,
            inst_init,
            ctors: Vec::new(),
            methods,
            line,
        })
    }
}

/// True when `toks[j]` starts a `record Name(` header.
/// How many tokens the class-declaration modifier at `j` spans, or 0 when there
/// is none.
///
/// Most modifiers are one token. `non-sealed` is three — the lexer has no
/// hyphenated identifier, so it arrives as `non`, `-`, `sealed` — which is the
/// reason this answers a length rather than a bool.
///
/// `sealed` and `non-sealed` are contextual keywords: a variable named `sealed`
/// is still legal Java, so only the *declaration* position reads them as
/// modifiers, which is exactly where this is asked.
fn class_modifier_len(toks: &[Token], j: usize) -> usize {
    if matches!(toks[j].kind, Tok::Public | Tok::Static) {
        return 1;
    }
    let word = match &toks[j].kind {
        Tok::Ident(w) => w.as_str(),
        _ => return 0,
    };
    if word == "non"
        && matches!(toks.get(j + 1).map(|t| &t.kind), Some(Tok::Minus))
        && matches!(toks.get(j + 2).map(|t| &t.kind), Some(Tok::Ident(w)) if w == "sealed")
    {
        return 3;
    }
    usize::from(matches!(word, "final" | "abstract" | "sealed"))
}

fn record_at(toks: &[Token], j: usize) -> bool {
    matches!(&toks[j].kind, Tok::Ident(w) if w == "record")
        && matches!(toks.get(j + 1).map(|t| &t.kind), Some(Tok::Ident(_)))
        && matches!(
            toks.get(j + 2).map(|t| &t.kind),
            Some(Tok::LParen | Tok::Lt)
        )
}

/// Give a `record` the members Java derives from its component list: one final
/// field per component, the canonical constructor, the component accessors, and
/// `toString`/`equals`. Anything the body declares itself wins — a record that
/// writes its own `toString()` keeps it.
///
/// Called once per record declaration, after its own members are parsed.
/// How a `record`'s derived `equals` compares one component, which is not `==`
/// for two of the three kinds.
///
/// JLS 8.10.3: the derived `equals` compares a `float` component with
/// `Float.compare(…) == 0`, a `double` with `Double.compare(…) == 0`, any other
/// primitive with `==`, and a reference with `Objects.equals`. The two special
/// cases are not pedantry — `Double.compare` is a *total* order, so
/// `new D(Double.NaN).equals(new D(Double.NaN))` is `true` and
/// `new D(0.0).equals(new D(-0.0))` is `false`, both the opposite of what `==`
/// answers. `Objects.equals` reaches a component class's own `equals`, where
/// `==` would compare handles; for a `String` component the two agree already
/// (javars's `==` on strings is by value) and for an array component they agree
/// too (arrays inherit identity `equals`), but routing every reference through
/// one rule is the rule Java states.
fn component_eq(ty: &str, mine: Expr, theirs: Expr, line: u32) -> Expr {
    match ty {
        "float" | "double" => {
            let owner = if ty == "float" { "Float" } else { "Double" };
            Expr::Binary {
                op: BinOp::Eq,
                lhs: Box::new(Expr::MethodCall {
                    recv: Box::new(Expr::Var(owner.to_string())),
                    method: "compare".to_string(),
                    args: vec![mine, theirs],
                    line,
                }),
                rhs: Box::new(Expr::Int(0)),
            }
        }
        "int" | "long" | "short" | "byte" | "char" | "boolean" => Expr::Binary {
            op: BinOp::Eq,
            lhs: Box::new(mine),
            rhs: Box::new(theirs),
        },
        _ => Expr::MethodCall {
            recv: Box::new(Expr::Var("Objects".to_string())),
            method: "equals".to_string(),
            args: vec![mine, theirs],
            line,
        },
    }
}

/// How a `record`'s derived `hashCode` hashes one component.
///
/// Each primitive goes through its own wrapper's `hashCode(x)` static, because
/// the widths disagree: `Float.hashCode(1.5f)` and `Double.hashCode(1.5)` are
/// different numbers, and `Long.hashCode` folds its two halves where
/// `Integer.hashCode` is the value. A reference component contributes its own
/// `hashCode()`, or 0 when it is `null` — which is what makes
/// `new S(null).hashCode()` 0 rather than a `NullPointerException`.
fn component_hash(ty: &str, value: Expr, line: u32) -> Expr {
    let wrapper = match ty {
        "int" | "short" | "byte" => "Integer",
        "long" => "Long",
        "float" => "Float",
        "double" => "Double",
        "boolean" => "Boolean",
        "char" => "Character",
        _ => {
            return Expr::Ternary {
                cond: Box::new(Expr::Binary {
                    op: BinOp::Eq,
                    lhs: Box::new(value.clone()),
                    rhs: Box::new(Expr::Var("null".to_string())),
                }),
                then: Box::new(Expr::Int(0)),
                els: Box::new(Expr::MethodCall {
                    recv: Box::new(value),
                    method: "hashCode".to_string(),
                    args: Vec::new(),
                    line,
                }),
            }
        }
    };
    Expr::MethodCall {
        recv: Box::new(Expr::Var(wrapper.to_string())),
        method: "hashCode".to_string(),
        args: vec![value],
        line,
    }
}

fn record_members(
    line: u32,
    name: &str,
    components: &[Param],
    fields: &mut Vec<FieldDecl>,
    ctors: &mut Vec<Ctor>,
    methods: &mut Vec<Method>,
) {
    for c in components {
        fields.push(FieldDecl {
            ty: c.ty.clone(),
            name: c.name.clone(),
            init: None,
            // A record's component field IS final in Java, but it holds a
            // constructor argument rather than a constant expression, so it is
            // never a *constant variable* and folding must not reach it.
            is_final: false,
            line,
        });
    }
    // The canonical constructor assigns each component to its field. A compact
    // constructor already contributed its validation body under the same
    // parameter list, so the assignments are appended to it — Java's order.
    let assigns: Vec<Stmt> = components
        .iter()
        .map(|c| {
            Stmt::new(
                line,
                StmtKind::FieldAssign {
                    recv: Expr::This,
                    name: c.name.clone(),
                    op: AssignOp::Assign,
                    value: Expr::Var(c.name.clone()),
                },
            )
        })
        .collect();
    let param_tys: Vec<&str> = components.iter().map(|c| c.ty.as_str()).collect();
    match ctors.iter_mut().find(|c| {
        c.params
            .iter()
            .map(|p| p.ty.as_str())
            .eq(param_tys.iter().copied())
    }) {
        Some(canonical) => canonical.body.extend(assigns),
        None => ctors.push(Ctor {
            params: components.to_vec(),
            body: assigns,
            line,
        }),
    }
    // One accessor per component.
    for c in components {
        if methods
            .iter()
            .any(|m| m.name == c.name && m.params.is_empty())
        {
            continue;
        }
        methods.push(Method {
            name: c.name.clone(),
            owner: name.to_string(),
            params: Vec::new(),
            ret: c.ty.clone(),
            body: vec![Stmt::new(
                line,
                StmtKind::Return(Some(Expr::Field {
                    recv: Box::new(Expr::This),
                    name: c.name.clone(),
                })),
            )],
            is_abstract: false,
            line,
        });
    }
    // `toString()` → `Point[x=1, y=2]`.
    if !methods
        .iter()
        .any(|m| m.name == "toString" && m.params.is_empty())
    {
        let mut text = Expr::Str(format!("{name}["));
        for (i, c) in components.iter().enumerate() {
            let sep = if i == 0 { "" } else { ", " };
            text = concat(text, Expr::Str(format!("{sep}{}=", c.name)));
            text = concat(
                text,
                Expr::Field {
                    recv: Box::new(Expr::This),
                    name: c.name.clone(),
                },
            );
        }
        text = concat(text, Expr::Str("]".to_string()));
        methods.push(Method {
            name: "toString".to_string(),
            owner: name.to_string(),
            params: Vec::new(),
            ret: "String".to_string(),
            body: vec![Stmt::new(line, StmtKind::Return(Some(text)))],
            is_abstract: false,
            line,
        });
    }
    // `hashCode()` — the `31 * h + componentHash` fold, seeded at 0.
    //
    // The JLS leaves a record's hash *unspecified* beyond "derived from the
    // components", so this reproduces what openjdk 26.0.2's `ObjectMethods`
    // bootstrap computes rather than inventing one: a program that prints a
    // record's hash, or that depends on two records landing in the same
    // `HashMap` bucket, would otherwise disagree with the reference for no
    // reason a user could see.
    if !methods
        .iter()
        .any(|m| m.name == "hashCode" && m.params.is_empty())
    {
        let acc = "#h";
        let mut body = vec![Stmt::new(
            line,
            StmtKind::Local {
                ty: "int".to_string(),
                name: acc.to_string(),
                init: Some(Expr::Int(0)),
            },
        )];
        for c in components {
            let mine = Expr::Field {
                recv: Box::new(Expr::This),
                name: c.name.clone(),
            };
            body.push(Stmt::new(
                line,
                StmtKind::Assign {
                    name: acc.to_string(),
                    op: AssignOp::Assign,
                    value: Expr::Binary {
                        op: BinOp::Add,
                        lhs: Box::new(Expr::Binary {
                            op: BinOp::Mul,
                            lhs: Box::new(Expr::Int(31)),
                            rhs: Box::new(Expr::Var(acc.to_string())),
                        }),
                        rhs: Box::new(component_hash(&c.ty, mine, line)),
                    },
                },
            ));
        }
        body.push(Stmt::new(
            line,
            StmtKind::Return(Some(Expr::Var(acc.to_string()))),
        ));
        methods.push(Method {
            name: "hashCode".to_string(),
            owner: name.to_string(),
            params: Vec::new(),
            ret: "int".to_string(),
            body,
            is_abstract: false,
            line,
        });
    }
    // `equals(Object)` — component-wise, guarded by the type test.
    if !methods
        .iter()
        .any(|m| m.name == "equals" && m.params.len() == 1)
    {
        let other = "#other";
        let mut cond = Expr::Bool(true);
        for c in components {
            let mine = Expr::Field {
                recv: Box::new(Expr::This),
                name: c.name.clone(),
            };
            let theirs = Expr::Field {
                recv: Box::new(Expr::Var(other.to_string())),
                name: c.name.clone(),
            };
            cond = Expr::Binary {
                op: BinOp::And,
                lhs: Box::new(cond),
                rhs: Box::new(component_eq(&c.ty, mine, theirs, line)),
            };
        }
        methods.push(Method {
            name: "equals".to_string(),
            owner: name.to_string(),
            params: vec![Param {
                ty: "Object".to_string(),
                name: other.to_string(),
                varargs: false,
            }],
            ret: "boolean".to_string(),
            body: vec![
                Stmt::new(
                    line,
                    StmtKind::If {
                        cond: Expr::Unary {
                            op: UnOp::Not,
                            rhs: Box::new(Expr::InstanceOf {
                                expr: Box::new(Expr::Var(other.to_string())),
                                class: name.to_string(),
                                binding: None,
                                components: Vec::new(),
                            }),
                        },
                        then: vec![Stmt::new(line, StmtKind::Return(Some(Expr::Bool(false))))],
                        els: Vec::new(),
                    },
                ),
                Stmt::new(line, StmtKind::Return(Some(cond))),
            ],
            is_abstract: false,
            line,
        });
    }
}

/// `lhs + rhs` — the string-concatenation node the synthesized `toString`
/// bodies are built from.
fn concat(lhs: Expr, rhs: Expr) -> Expr {
    Expr::Binary {
        op: BinOp::Add,
        lhs: Box::new(lhs),
        rhs: Box::new(rhs),
    }
}

/// Split a `static` field declaration into its storage (one cell per field,
/// seeded with the type's default) and its initialization (an assignment run at
/// class-init time, in textual order with the `static { … }` blocks).
fn static_declaration(
    line: u32,
    decls: Vec<FieldDecl>,
    fields: &mut Vec<FieldDecl>,
    init: &mut Vec<Stmt>,
) {
    for f in decls {
        if let Some(value) = f.init.clone() {
            init.push(Stmt::new(
                line,
                StmtKind::Assign {
                    name: f.name.clone(),
                    op: AssignOp::Assign,
                    value,
                },
            ));
        }
        fields.push(FieldDecl { init: None, ..f });
    }
}

/// Split an instance field declaration into its storage (the field, seeded with
/// the type's default) and its initialization (a `this.f = …` assignment run in
/// textual order with the bare `{ … }` instance-initializer blocks). The mirror
/// of [`static_declaration`], one level down: an instance initializer needs a
/// bound `this`, which only the per-instance initialization subroutine has.
fn instance_declaration(
    line: u32,
    decls: Vec<FieldDecl>,
    fields: &mut Vec<FieldDecl>,
    init: &mut Vec<Stmt>,
) {
    for f in decls {
        if let Some(value) = f.init.clone() {
            init.push(Stmt::new(
                line,
                StmtKind::FieldAssign {
                    recv: Expr::This,
                    name: f.name.clone(),
                    op: AssignOp::Assign,
                    value,
                },
            ));
        }
        fields.push(FieldDecl { init: None, ..f });
    }
}

/// Give an `enum` its synthesized state and accessors, after its own members
/// have been parsed so a user-declared `toString()`/`name()`/`ordinal()` is left
/// alone. Called once per enum declaration.
fn enum_members(line: u32, owner: &str, fields: &mut Vec<FieldDecl>, methods: &mut Vec<Method>) {
    fields.push(FieldDecl {
        ty: "String".to_string(),
        name: ENUM_NAME.to_string(),
        init: None,
        is_final: false,
        line,
    });
    fields.push(FieldDecl {
        ty: "int".to_string(),
        name: ENUM_ORDINAL.to_string(),
        init: None,
        is_final: false,
        line,
    });
    let reader = |method: &str, field: &str, ret: &str| Method {
        name: method.to_string(),
        owner: owner.to_string(),
        params: Vec::new(),
        ret: ret.to_string(),
        body: vec![Stmt::new(
            line,
            StmtKind::Return(Some(Expr::Field {
                recv: Box::new(Expr::This),
                name: field.to_string(),
            })),
        )],
        is_abstract: false,
        line,
    };
    // `Enum.toString()` returns `name()`. A body that declares any of these
    // itself keeps its own version — the synthesized one is only a default.
    for (method, field, ret) in [
        ("name", ENUM_NAME, "String"),
        ("ordinal", ENUM_ORDINAL, "int"),
        ("toString", ENUM_NAME, "String"),
    ] {
        if !methods
            .iter()
            .any(|m| m.name == method && m.params.is_empty())
        {
            methods.push(reader(method, field, ret));
        }
    }
    // `Enum.compareTo` is the difference of the two ordinals — declaration
    // order — and is `final` in Java, so an enum never supplies its own. That
    // makes every enum a `Comparable`, which is what lets `Collections.sort` of
    // an enum list and a bare `a.compareTo(b)` between constants both work.
    if !methods
        .iter()
        .any(|m| m.name == "compareTo" && m.params.len() == 1)
    {
        methods.push(Method {
            name: "compareTo".to_string(),
            owner: owner.to_string(),
            params: vec![Param {
                ty: owner.to_string(),
                name: "other".to_string(),
                varargs: false,
            }],
            ret: "int".to_string(),
            body: vec![Stmt::new(
                line,
                StmtKind::Return(Some(Expr::Binary {
                    op: BinOp::Sub,
                    lhs: Box::new(Expr::Field {
                        recv: Box::new(Expr::This),
                        name: ENUM_ORDINAL.to_string(),
                    }),
                    rhs: Box::new(Expr::Field {
                        recv: Box::new(Expr::Var("other".to_string())),
                        name: ENUM_ORDINAL.to_string(),
                    }),
                })),
            )],
            is_abstract: false,
            line,
        });
    }
    // `Enum.equals` is identity — constants are singletons, so `==` is exactly
    // it, and `final` in Java (never overridden).
    if !methods
        .iter()
        .any(|m| m.name == "equals" && m.params.len() == 1)
    {
        methods.push(Method {
            name: "equals".to_string(),
            owner: owner.to_string(),
            params: vec![Param {
                ty: "Object".to_string(),
                name: "other".to_string(),
                varargs: false,
            }],
            ret: "boolean".to_string(),
            body: vec![Stmt::new(
                line,
                StmtKind::Return(Some(Expr::Binary {
                    op: BinOp::Eq,
                    lhs: Box::new(Expr::This),
                    rhs: Box::new(Expr::Var("other".to_string())),
                })),
            )],
            is_abstract: false,
            line,
        });
    }
}

impl Parser {
    /// Skip a generic type-parameter/argument group `< ... >` when the cursor is
    /// on `<`, matching nested `<`/`>` (Java erases these at runtime, so javars
    /// parses and discards them). A no-op when the cursor is not on `<`.
    fn skip_generics(&mut self) {
        if !self.is(&Tok::Lt) {
            return;
        }
        let mut depth = 0;
        loop {
            match self.peek() {
                Tok::Lt => depth += 1,
                // A nested type argument closes with `>>`/`>>>`, which the lexer
                // takes as one shift token — so a closer is worth however many
                // `>` it spells.
                t if t.generic_closers() > 0 => {
                    depth -= t.generic_closers();
                    if depth <= 0 {
                        self.advance();
                        return;
                    }
                }
                Tok::Eof => return,
                _ => {}
            }
            self.advance();
        }
    }

    /// True when the member at the cursor is a (possibly modifier-prefixed)
    /// nested `class`, `interface`, `enum`, or `record` declaration.
    ///
    /// The modifier scan is [`class_modifier_len`]'s, so a `sealed` nested type
    /// is recognised here exactly as at the top level.
    fn at_nested_class(&self) -> bool {
        let mut j = self.pos;
        loop {
            let n = class_modifier_len(&self.toks, j);
            if n == 0 {
                break;
            }
            j += n;
        }
        matches!(self.toks[j].kind, Tok::Class)
            || matches!(&self.toks[j].kind, Tok::Ident(w) if w == "interface" || w == "enum")
            || record_at(&self.toks, j)
    }

    /// True when the cursor is on a `record Name(` header. `record` is a
    /// contextual keyword in Java, so the shape — not the word alone — is what
    /// makes it one; a variable or method named `record` still parses.
    fn at_record(&self) -> bool {
        record_at(&self.toks, self.pos)
    }

    /// A record's *compact* constructor — `Point { … }`, no parameter list. Its
    /// body validates/normalizes the components; the field assignments Java
    /// appends afterwards are supplied by [`record_members`], so the canonical
    /// constructor synthesized here already carries the component parameters.
    fn try_compact_ctor(
        &mut self,
        class_name: &str,
        is_record: bool,
        components: &[Param],
    ) -> Result<Option<Ctor>, String> {
        if !is_record
            || !(matches!(self.peek(), Tok::Ident(n) if n == class_name)
                && matches!(self.toks[self.pos + 1].kind, Tok::LBrace))
        {
            return Ok(None);
        }
        let line = self.line();
        self.advance(); // class name
        self.advance(); // {
        let body = self.block()?;
        Ok(Some(Ctor {
            params: components.to_vec(),
            body,
            line,
        }))
    }

    /// If the cursor is at a constructor (`[public] Name(<params>) { ... }` where
    /// `Name` is the enclosing class), parse it; otherwise restore and return
    /// `None`. A constructor has no return type — the class name sits directly
    /// before the `(`.
    fn try_ctor(&mut self, class_name: &str) -> Result<Option<Ctor>, String> {
        let save = self.pos;
        while matches!(self.peek(), Tok::Public | Tok::Static)
            || matches!(self.peek(), Tok::Ident(w) if w == "final" || w == "abstract" || w == "private" || w == "protected")
        {
            self.advance();
        }
        let line = self.line();
        let is_ctor = matches!(self.peek(), Tok::Ident(n) if n == class_name)
            && matches!(&self.toks[self.pos + 1].kind, Tok::LParen);
        if !is_ctor {
            self.pos = save;
            return Ok(None);
        }
        self.advance(); // class name
        self.eat(&Tok::LParen)?;
        let params = self.params()?;
        self.eat(&Tok::RParen)?;
        self.skip_throws()?;
        self.eat(&Tok::LBrace)?;
        let body = self.block()?;
        Ok(Some(Ctor { params, body, line }))
    }

    /// Parse one or more field declarations sharing a type (`int x, y = 3;`).
    /// Restores and returns `None` if the member is not a field (e.g. a method
    /// the earlier probes already rejected — a `type name (` shape). The `bool`
    /// of the result reports whether the declaration carried `static`: a
    /// `static` field is one shared cell per class and an instance field is one
    /// per object, so the caller routes them to different sinks.
    fn try_fields(&mut self) -> Result<Option<(Vec<FieldDecl>, bool)>, String> {
        let save = self.pos;
        let mut saw_static = false;
        let mut saw_final = false;
        while matches!(self.peek(), Tok::Public | Tok::Static)
            || matches!(self.peek(), Tok::Ident(w) if w == "final" || w == "private" || w == "protected" || w == "volatile" || w == "transient")
        {
            if matches!(self.peek(), Tok::Static) {
                saw_static = true;
            }
            if matches!(self.peek(), Tok::Ident(w) if w == "final") {
                saw_final = true;
            }
            self.advance();
        }
        if !self.at_type() {
            self.pos = save;
            return Ok(None);
        }
        let base_ty = self.type_name()?;
        // A field is `type name` where name is not followed by `(` (that would be
        // a method the method-probe should have taken).
        let first_is_field = matches!(self.peek(), Tok::Ident(_))
            && !matches!(&self.toks[self.pos + 1].kind, Tok::LParen);
        if !first_is_field {
            self.pos = save;
            return Ok(None);
        }
        let mut out = Vec::new();
        loop {
            // Each declarator in `int a = 1, b = 2;` reports its own line, so a
            // duplicate is pointed at where it was written.
            let line = self.line();
            let (name, ty) = self.declarator(&base_ty)?;
            let init = if self.is(&Tok::Assign) {
                self.advance();
                Some(self.var_init()?)
            } else {
                None
            };
            out.push(FieldDecl {
                ty,
                name,
                init,
                is_final: saw_final,
                line,
            });
            if self.is(&Tok::Comma) {
                self.advance();
            } else {
                break;
            }
        }
        self.eat(&Tok::Semi)?;
        Ok(Some((out, saw_static)))
    }

    /// If the cursor is at a method (`[modifiers] <ret> name(<params>) { ... }`),
    /// parse it and report whether it was `static`. Otherwise restore the cursor
    /// and return `None` (fields and constructors are handled by their own
    /// probes). `main` is matched earlier by [`Parser::try_main`], so it never
    /// reaches here.
    fn try_any_method(&mut self, owner: &str) -> Result<Option<(Method, bool)>, String> {
        let save = self.pos;
        let mut saw_static = false;
        // Modifiers, including interface method modifiers (`default`, `abstract`)
        // and access/other qualifiers, in any order.
        while matches!(self.peek(), Tok::Public | Tok::Static | Tok::Default)
            || matches!(self.peek(), Tok::Ident(w) if w == "final" || w == "abstract" || w == "private" || w == "protected" || w == "synchronized" || w == "native")
        {
            if matches!(self.peek(), Tok::Static) {
                saw_static = true;
            }
            self.advance();
        }
        // Optional generic method type parameters `<T> T id(T x)` — erased.
        self.skip_generics();
        // A return type is required, so peeking a non-type here means this is not
        // a method (it is a field or constructor).
        if !self.at_type() {
            self.pos = save;
            return Ok(None);
        }
        let line = self.line();
        let ret = self.type_name()?;
        // `<ret> name (` — anything else (e.g. `int COUNT =`) is a field.
        let name = match self.peek().clone() {
            Tok::Ident(n) if matches!(&self.toks[self.pos + 1].kind, Tok::LParen) => {
                self.advance();
                n
            }
            _ => {
                self.pos = save;
                return Ok(None);
            }
        };
        self.eat(&Tok::LParen)?;
        let params = self.params()?;
        self.eat(&Tok::RParen)?;
        self.skip_throws()?;
        // An interface abstract method (or `abstract` class method) ends in `;`
        // with no body; a concrete/`default` method has a `{ ... }` block.
        let (body, is_abstract) = if self.is(&Tok::Semi) {
            self.advance();
            (Vec::new(), true)
        } else {
            self.eat(&Tok::LBrace)?;
            (self.block()?, false)
        };
        Ok(Some((
            Method {
                name,
                owner: owner.to_string(),
                params,
                ret,
                body,
                is_abstract,
                line,
            },
            saw_static,
        )))
    }

    /// Skip a `throws A, B` clause following a method/constructor parameter
    /// list. javars has no checked-exception analysis — an exception either
    /// reaches a handler or terminates the program — so the declared list is
    /// parsed and discarded, exactly as its runtime effect is nil.
    fn skip_throws(&mut self) -> Result<(), String> {
        if !matches!(self.peek(), Tok::Ident(w) if w == "throws") {
            return Ok(());
        }
        self.advance();
        loop {
            self.type_name()?;
            if self.is(&Tok::Comma) {
                self.advance();
            } else {
                return Ok(());
            }
        }
    }

    /// Parse a comma-separated formal parameter list `<type> <name>, ...`, the
    /// cursor sitting just past the opening `(`. Stops at the closing `)`.
    fn params(&mut self) -> Result<Vec<Param>, String> {
        let mut out = Vec::new();
        if self.is(&Tok::RParen) {
            return Ok(out);
        }
        loop {
            let mut ty = self.type_name()?;
            // A varargs parameter (`String... args`) *is* an array parameter —
            // inside the body it is a `String[]`. The dots additionally admit
            // Java's third resolution phase, so the flag rides along on the
            // parameter for the compiler's call-site packing.
            let mut varargs = false;
            if self.is(&Tok::Dot) && matches!(self.toks[self.pos + 1].kind, Tok::Dot) {
                self.advance();
                self.advance();
                self.eat(&Tok::Dot)?;
                ty.push_str("[]");
                varargs = true;
            }
            let (name, ty) = self.declarator(&ty)?;
            out.push(Param { ty, name, varargs });
            if self.is(&Tok::Comma) {
                self.advance();
            } else {
                break;
            }
        }
        Ok(out)
    }

    /// True when the cursor sits on a type name (`void` or an identifier,
    /// possibly followed by `[]`).
    fn at_type(&self) -> bool {
        matches!(self.peek(), Tok::Void | Tok::Ident(_))
    }

    /// Read a type's name, dropping any package qualifier
    /// (`java.util.List` → `List`). javars keys every type on its simple name —
    /// there is no JDK to import from and no package graph — so the prefix
    /// carries no meaning, exactly as it does not for the qualified *static*
    /// call `java.util.Arrays.sort(x)`.
    ///
    /// A segment counts as a package only when it starts with a lowercase letter
    /// *and* is followed by another name. That is what keeps `Map.Entry` (a
    /// nested type, not a package) and the expression `obj.field` out of the
    /// loop, and what leaves `int... xs` alone (the dot is not followed by a
    /// name).
    fn simple_type_name(&mut self) -> Result<String, String> {
        let mut ty = self.ident()?;
        while ty.starts_with(|c: char| c.is_lowercase())
            && self.is(&Tok::Dot)
            && matches!(&self.toks[self.pos + 1].kind, Tok::Ident(_))
        {
            self.advance();
            ty = self.ident()?;
        }
        Ok(ty)
    }

    /// Parse one declarator — its name plus any C-style array suffix — and
    /// return `(name, type)`. Java lets the brackets sit after the *name*
    /// (`int a[]`) as well as after the type (`int[] a`), and the two spellings
    /// declare the same thing; the difference only shows in a multi-declarator
    /// statement, where a suffix binds to its own declarator alone, so
    /// `int a[], b;` declares an `int[]` and an `int`.
    fn declarator(&mut self, base_ty: &str) -> Result<(String, String), String> {
        let name = self.ident()?;
        let mut ty = base_ty.to_string();
        while self.is(&Tok::LBracket) && matches!(self.toks[self.pos + 1].kind, Tok::RBracket) {
            self.advance();
            self.advance();
            ty.push_str("[]");
        }
        Ok((name, ty))
    }

    /// Parse a declaration-position type: `void`, `int`, `String`, `int[]`, ….
    /// Trailing `[]` pairs are folded into the returned name (e.g. `int[]`).
    fn type_name(&mut self) -> Result<String, String> {
        let mut ty = self.simple_type_name()?;
        // Naming a functional interface pulls in the prelude that declares it,
        // even when the program never writes a lambda literal (a method
        // parameter of type `Runnable` is enough).
        if crate::prelude::is_functional(&ty) {
            self.uses_functional = true;
        }
        // Generic type arguments (`List<String>`, `Map<K, V>`) are erased — the
        // erased type is just the raw name.
        self.skip_generics();
        while self.is(&Tok::LBracket) {
            self.advance();
            self.eat(&Tok::RBracket)?;
            ty.push_str("[]");
        }
        Ok(ty)
    }

    /// If the cursor is at `public static void main(String[] args)`, parse its
    /// body and the name it gives its parameter. Otherwise leave the cursor
    /// untouched and return None. The enclosing class name is the caller's, so
    /// the returned [`Entry`] carries an empty one for it to fill in.
    fn try_main(&mut self) -> Result<Option<Entry>, String> {
        let save = self.pos;
        // modifiers in any order
        let mut saw_static = false;
        while matches!(self.peek(), Tok::Public | Tok::Static) {
            if matches!(self.peek(), Tok::Static) {
                saw_static = true;
            }
            self.advance();
        }
        let is_void = self.is(&Tok::Void);
        let named_main = matches!(self.peek(), Tok::Void)
            && matches!(&self.toks[self.pos + 1].kind, Tok::Ident(n) if n == "main");
        if !(saw_static && is_void && named_main) {
            self.pos = save;
            return Ok(None);
        }
        self.eat(&Tok::Void)?; // void
        self.ident()?; // main
        self.eat(&Tok::LParen)?;
        // `main` takes `String[] args` (or `String... args`, or nothing). The
        // name is what the compiler binds the real program arguments to.
        let params = self.params()?;
        self.eat(&Tok::RParen)?;
        let param = params.into_iter().next().map(|p| p.name);
        self.skip_throws()?;
        self.eat(&Tok::LBrace)?;
        let body = self.block()?;
        Ok(Some(Entry {
            class_name: String::new(),
            body,
            param,
        }))
    }

    /// Skip a non-`main` member by matching its braces (or a field `;`).
    fn skip_member(&mut self) -> Result<(), String> {
        while !self.is(&Tok::Eof) {
            match self.peek() {
                Tok::LBrace => {
                    let mut depth = 0;
                    loop {
                        match self.advance() {
                            Tok::LBrace => depth += 1,
                            Tok::RBrace => {
                                depth -= 1;
                                if depth == 0 {
                                    return Ok(());
                                }
                            }
                            Tok::Eof => return Ok(()),
                            _ => {}
                        }
                    }
                }
                Tok::Semi => {
                    self.advance();
                    return Ok(());
                }
                Tok::RBrace => return Ok(()),
                _ => {
                    self.advance();
                }
            }
        }
        Ok(())
    }

    /// Parse a `{ ... }` body already past the opening brace; consumes the `}`.
    fn block(&mut self) -> Result<Vec<Stmt>, String> {
        let mut out = Vec::new();
        while !self.is(&Tok::RBrace) && !self.is(&Tok::Eof) {
            out.push(self.statement()?);
        }
        self.eat(&Tok::RBrace)?;
        Ok(out)
    }

    /// Parse a `{ ... }` or a single statement into a statement list.
    fn braced_or_single(&mut self) -> Result<Vec<Stmt>, String> {
        if self.is(&Tok::LBrace) {
            self.advance();
            self.block()
        } else {
            Ok(vec![self.statement()?])
        }
    }

    /// Parse one statement, tagging it with the source line it starts on.
    fn statement(&mut self) -> Result<Stmt, String> {
        let line = self.line();
        Ok(Stmt::new(line, self.statement_kind()?))
    }

    fn statement_kind(&mut self) -> Result<StmtKind, String> {
        // A labeled statement `label: <stmt>` — an identifier immediately
        // followed by `:`. (A ternary is never a valid statement expression, so
        // a leading `Ident :` is unambiguously a label.)
        if let Tok::Ident(label) = self.peek().clone() {
            if matches!(self.toks[self.pos + 1].kind, Tok::Colon) {
                self.advance(); // label
                self.advance(); // :
                let body = self.statement()?;
                return Ok(StmtKind::Labeled {
                    label,
                    body: Box::new(body),
                });
            }
        }
        // `try` and `throw` are not reserved tokens in this lexer (they lex as
        // identifiers, like `instanceof` and `interface`), so they are matched
        // here by name before the general statement forms.
        if let Tok::Ident(w) = self.peek() {
            match w.as_str() {
                "try" => return self.try_stmt(),
                // `yield <expr>;` is a keyword only inside an arrow-`switch`
                // arm body — Java's contextual rule, which keeps a variable or
                // method named `yield` working everywhere else.
                "yield" if self.switch_expr_depth > 0 => {
                    self.advance();
                    let e = self.expression()?;
                    self.eat(&Tok::Semi)?;
                    return Ok(StmtKind::Yield(e));
                }
                "throw" => {
                    self.uses_exceptions = true;
                    self.advance();
                    let e = self.expression()?;
                    self.eat(&Tok::Semi)?;
                    return Ok(StmtKind::Throw(e));
                }
                // `synchronized (m) { … }` — a statement here, but also a method
                // modifier, so the `(` is what tells the two apart.
                "synchronized" if matches!(self.toks[self.pos + 1].kind, Tok::LParen) => {
                    return self.synchronized_stmt()
                }
                _ => {}
            }
        }
        match self.peek() {
            Tok::If => self.if_stmt(),
            Tok::While => self.while_stmt(),
            Tok::Do => self.do_stmt(),
            Tok::For => self.for_stmt(),
            Tok::Switch => self.switch_stmt(),
            Tok::Return => {
                // `return;` or `return <expr>;`. The compiler resolves the
                // context: a value return is valid in a method but rejected in
                // `void main`.
                self.advance();
                if self.is(&Tok::Semi) {
                    self.advance();
                    Ok(StmtKind::Return(None))
                } else {
                    let e = self.expression()?;
                    self.eat(&Tok::Semi)?;
                    Ok(StmtKind::Return(Some(e)))
                }
            }
            Tok::Break => {
                self.advance();
                let label = self.optional_label();
                self.eat(&Tok::Semi)?;
                Ok(StmtKind::Break(label))
            }
            Tok::Continue => {
                self.advance();
                let label = self.optional_label();
                self.eat(&Tok::Semi)?;
                Ok(StmtKind::Continue(label))
            }
            Tok::LBrace => {
                self.advance();
                // a bare block: flatten into a single synthetic if-true. Slice 1
                // has no lexical scopes, so inlining is behavior-preserving.
                let body = self.block()?;
                Ok(StmtKind::If {
                    cond: Expr::Bool(true),
                    then: body,
                    els: vec![],
                })
            }
            _ => self.simple_statement(true),
        }
    }

    /// Local decl, assignment, or expression statement. `expect_semi` consumes
    /// the trailing `;` (false for the `for` init/update clauses).
    fn simple_statement(&mut self, expect_semi: bool) -> Result<StmtKind, String> {
        // A local declaration starts with a type keyword/ident followed by an
        // identifier: `int x`, `String s`, `var v`, `int[] a`, `Point p`.
        if self.looks_like_decl() {
            if matches!(self.peek(), Tok::Ident(w) if w == "final") {
                self.advance();
            }
            let base_ty = self.type_name()?;
            // Every declarator of the statement, in source order: `int a = 1,
            // b = 2;` is two, and `int a[], b;` gives them different types.
            let mut decls = Vec::new();
            loop {
                let line = self.line();
                let (name, ty) = self.declarator(&base_ty)?;
                let init = if self.is(&Tok::Assign) {
                    self.advance();
                    Some(self.var_init()?)
                } else {
                    None
                };
                decls.push(Stmt::new(line, StmtKind::Local { ty, name, init }));
                if !self.is(&Tok::Comma) {
                    break;
                }
                self.advance();
            }
            // `var a = 1, b = 2;` is not Java: each `var` declarator would need
            // its own inferred type, so the language forbids the compound form.
            if base_ty == "var" && decls.len() > 1 {
                return Err(format!(
                    "javars: 'var' is not allowed in a compound declaration on line {}",
                    self.line()
                ));
            }
            if expect_semi {
                self.eat(&Tok::Semi)?;
            }
            // A one-declarator statement stays the plain `Local` node, so the
            // overwhelmingly common shape emits exactly the bytecode it did.
            return Ok(if decls.len() == 1 {
                decls.pop().expect("length checked").kind
            } else {
                StmtKind::Locals(decls)
            });
        }

        // Bare-variable fast paths: `x <op>= e` and `x++`/`x--`. Handled before
        // the general expression parse because `primary` rejects a bare `x++` in
        // value position (post-inc/dec is a statement, not an expression here).
        if let Tok::Ident(name) = self.peek().clone() {
            let next = &self.toks[self.pos + 1].kind;
            if let Some(op) = assign_op(next) {
                self.advance(); // name
                self.advance(); // op
                let value = self.expression()?;
                if expect_semi {
                    self.eat(&Tok::Semi)?;
                }
                return Ok(StmtKind::Assign { name, op, value });
            }
            if matches!(next, Tok::PlusPlus | Tok::MinusMinus) {
                let inc = matches!(next, Tok::PlusPlus);
                self.advance(); // name
                self.advance(); // ++/--
                if expect_semi {
                    self.eat(&Tok::Semi)?;
                }
                return Ok(StmtKind::Expr(Expr::PostIncDec { name, inc }));
            }
        }

        // Otherwise parse an lvalue/expression, then decide by what follows: an
        // `a[i] = …` / `obj.f = …` assignment, an `a[i]++` post-inc, or a plain
        // expression statement (`System.out.println(...)`, a call, `new C(...)`).
        let lhs = self.expression()?;
        if let Some(op) = assign_op(self.peek()) {
            self.advance();
            let value = self.expression()?;
            if expect_semi {
                self.eat(&Tok::Semi)?;
            }
            return self.make_assign(lhs, op, value);
        }
        if matches!(self.peek(), Tok::PlusPlus | Tok::MinusMinus) {
            let inc = matches!(self.peek(), Tok::PlusPlus);
            self.advance();
            if expect_semi {
                self.eat(&Tok::Semi)?;
            }
            // The discarded statement result makes `a[i]++` == `a[i] += 1`.
            let op = if inc { AssignOp::Add } else { AssignOp::Sub };
            return self.make_assign(lhs, op, Expr::Int(1));
        }
        if expect_semi {
            self.eat(&Tok::Semi)?;
        }
        Ok(StmtKind::Expr(lhs))
    }

    /// Build an assignment statement from a parsed lvalue expression, rejecting
    /// non-assignable left-hand sides.
    fn make_assign(&self, lhs: Expr, op: AssignOp, value: Expr) -> Result<StmtKind, String> {
        match lhs {
            Expr::Var(name) => Ok(StmtKind::Assign { name, op, value }),
            Expr::Index { array, index } => Ok(StmtKind::IndexAssign {
                array: *array,
                index: *index,
                op,
                value,
            }),
            Expr::Field { recv, name } => Ok(StmtKind::FieldAssign {
                recv: *recv,
                name,
                op,
                value,
            }),
            other => Err(format!(
                "javars: `{other:?}` is not an assignable target on line {}",
                self.line()
            )),
        }
    }

    /// Parse a variable/field initializer: an array literal `{...}` when the
    /// cursor is on `{`, otherwise an ordinary expression.
    fn var_init(&mut self) -> Result<Expr, String> {
        if self.is(&Tok::LBrace) {
            self.advance();
            let elems = self.array_lit_elems()?;
            Ok(Expr::ArrayLit {
                elems,
                elem_ty: None,
            })
        } else {
            self.expression()
        }
    }

    /// Heuristic: two identifiers in a row (`Type name`) with the type not being
    /// a value keyword — a local declaration. Array types (`int[] a`) are
    /// handled by skipping the `[]` before the name.
    fn looks_like_decl(&self) -> bool {
        // `final` is a legal modifier on a local declaration (and the classic
        // spelling of a lambda-capturable local). It constrains reassignment,
        // which `javac` has already checked, so javars parses and drops it.
        let mut start = self.pos;
        if matches!(&self.toks[start].kind, Tok::Ident(w) if w == "final")
            && matches!(self.toks[start + 1].kind, Tok::Ident(_))
        {
            start += 1;
        }
        let t0 = &self.toks[start].kind;
        let is_type = matches!(t0, Tok::Ident(_));
        if !is_type {
            return false;
        }
        let mut j = start + 1;
        // Step over a package qualifier (`java.util.List xs`), on the same
        // lowercase-segment rule [`Parser::simple_type_name`] uses. An
        // expression like `obj.field = 1` walks the same path and then fails the
        // trailing-identifier test below, so it is still not a declaration.
        while matches!(&self.toks[j - 1].kind, Tok::Ident(w) if w.starts_with(|c: char| c.is_lowercase()))
            && matches!(self.toks[j].kind, Tok::Dot)
            && matches!(self.toks.get(j + 1).map(|t| &t.kind), Some(Tok::Ident(_)))
        {
            j += 2;
        }
        // optional generic type arguments on the type (`List<String> xs`)
        if matches!(self.toks[j].kind, Tok::Lt) {
            let mut depth = 0;
            while j < self.toks.len() {
                match &self.toks[j].kind {
                    Tok::Lt => depth += 1,
                    t if t.generic_closers() > 0 => {
                        depth -= t.generic_closers();
                        if depth <= 0 {
                            j += 1;
                            break;
                        }
                    }
                    Tok::Eof => return false,
                    _ => {}
                }
                j += 1;
            }
        }
        // optional array brackets on the type
        while matches!(self.toks[j].kind, Tok::LBracket)
            && matches!(self.toks.get(j + 1).map(|t| &t.kind), Some(Tok::RBracket))
        {
            j += 2;
        }
        matches!(self.toks[j].kind, Tok::Ident(_))
    }

    fn if_stmt(&mut self) -> Result<StmtKind, String> {
        self.eat(&Tok::If)?;
        self.eat(&Tok::LParen)?;
        let cond = self.expression()?;
        self.eat(&Tok::RParen)?;
        let then = self.braced_or_single()?;
        let els = if self.is(&Tok::Else) {
            self.advance();
            self.braced_or_single()?
        } else {
            vec![]
        };
        Ok(StmtKind::If { cond, then, els })
    }

    fn while_stmt(&mut self) -> Result<StmtKind, String> {
        self.eat(&Tok::While)?;
        self.eat(&Tok::LParen)?;
        let cond = self.expression()?;
        self.eat(&Tok::RParen)?;
        let body = self.braced_or_single()?;
        Ok(StmtKind::While { cond, body })
    }

    /// Both `for` forms: the enhanced `for (T x : arr)` and the C-style
    /// `for (init; cond; update)`. The two are told apart by a probe for the
    /// `<type> <name> :` header — a C-style init clause always has `=` or `;`
    /// where the enhanced form has `:`, so the probe is unambiguous.
    fn for_stmt(&mut self) -> Result<StmtKind, String> {
        self.eat(&Tok::For)?;
        self.eat(&Tok::LParen)?;
        if let Some((ty, name)) = self.try_foreach_header()? {
            let iter = self.expression()?;
            self.eat(&Tok::RParen)?;
            let body = self.braced_or_single()?;
            return Ok(StmtKind::ForEach {
                ty,
                name,
                iter,
                body,
            });
        }
        let init = self.for_clause(&Tok::Semi)?;
        self.eat(&Tok::Semi)?;
        let cond = if self.is(&Tok::Semi) {
            None
        } else {
            Some(self.expression()?)
        };
        self.eat(&Tok::Semi)?;
        let update = self.for_clause(&Tok::RParen)?;
        self.eat(&Tok::RParen)?;
        let body = self.braced_or_single()?;
        Ok(StmtKind::For {
            init,
            cond,
            update,
            body,
        })
    }

    /// Parse a `for` header's init or update clause — a comma-separated list of
    /// simple statements, terminated by `end` (`;` for init, `)` for update).
    ///
    /// Java lets the init clause declare several variables of one type
    /// (`for (int i = 0, j = n; …)`), where only the first declarator names the
    /// type; the rest reuse it, so the type is carried across the commas.
    fn for_clause(&mut self, end: &Tok) -> Result<Vec<Stmt>, String> {
        let mut out = Vec::new();
        if self.is(end) {
            return Ok(out);
        }
        let line = self.line();
        out.push(Stmt::new(line, self.simple_statement(false)?));
        // A declaration clause has already swallowed its own comma-separated
        // declarators (`for (int i = 0, n = 3; …)` is one `Locals` statement),
        // so a comma left here separates statement *expressions*: `i++, j--`.
        while self.is(&Tok::Comma) {
            self.advance();
            let line = self.line();
            out.push(Stmt::new(line, self.simple_statement(false)?));
        }
        Ok(out)
    }

    /// Parse `synchronized (monitor) { body }`.
    ///
    /// javars runs one thread, so holding the monitor is unobservable and the
    /// lock itself is not modeled. What *is* observable is the rest of the
    /// statement's semantics, and those are kept: the monitor expression is
    /// evaluated exactly once (so `synchronized (next())` still calls `next`),
    /// and a `null` monitor throws `NullPointerException` before the body runs.
    /// Both fall out of desugaring to `if (m != null) { body } else { throw }` —
    /// the same shape try-with-resources uses, so no new node reaches the
    /// compiler.
    ///
    /// Java's own message names where the null came from
    /// (`… because the return value of "C.give()" is null`), which is the
    /// bytecode-slot provenance javars cannot reproduce; it keeps the operation
    /// half, exactly as every other javars NPE message does.
    fn synchronized_stmt(&mut self) -> Result<StmtKind, String> {
        self.uses_exceptions = true;
        let line = self.line();
        self.advance(); // `synchronized`
        self.eat(&Tok::LParen)?;
        let monitor = self.expression()?;
        self.eat(&Tok::RParen)?;
        self.eat(&Tok::LBrace)?;
        let body = self.block()?;
        let npe = Stmt::new(
            line,
            StmtKind::Throw(Expr::NewObject {
                class: "NullPointerException".to_string(),
                args: vec![Expr::Str(
                    "Cannot enter synchronized block because the monitor is null".to_string(),
                )],
                line,
            }),
        );
        Ok(StmtKind::If {
            cond: Expr::Binary {
                op: BinOp::Ne,
                lhs: Box::new(monitor),
                rhs: Box::new(Expr::Var("null".to_string())),
            },
            then: body,
            els: vec![npe],
        })
    }

    /// Parse `try [(resources)] { .. } catch (Type name) { .. }* [finally { .. }]`.
    ///
    /// Try-with-resources is desugared here (see [`Parser::with_resources`]) so
    /// the compiler only ever sees the plain `try`/`catch`/`finally` node.
    /// Multi-catch (`catch (A | B e)`) does not reach this point: the lexer has
    /// no single `|` token, so it fails earlier with a lexical error.
    fn try_stmt(&mut self) -> Result<StmtKind, String> {
        self.uses_exceptions = true;
        self.advance(); // `try`
        let resources = if self.is(&Tok::LParen) {
            self.resource_spec()?
        } else {
            Vec::new()
        };
        self.eat(&Tok::LBrace)?;
        let body = self.block()?;
        let mut catches = Vec::new();
        while matches!(self.peek(), Tok::Ident(w) if w == "catch") {
            self.advance();
            self.eat(&Tok::LParen)?;
            // `final` is legal on a catch parameter and carries no meaning here.
            if matches!(self.peek(), Tok::Ident(w) if w == "final") {
                self.advance();
            }
            // `catch (A | B e)` — a multi-catch lists alternative types before
            // the one bound variable.
            let mut types = vec![self.type_name()?];
            while self.is(&Tok::Pipe) {
                self.advance();
                types.push(self.type_name()?);
            }
            let name = self.ident()?;
            self.eat(&Tok::RParen)?;
            self.eat(&Tok::LBrace)?;
            let arm_body = self.block()?;
            catches.push(CatchArm {
                types,
                name,
                body: arm_body,
            });
        }
        let finally_body = if matches!(self.peek(), Tok::Ident(w) if w == "finally") {
            self.advance();
            self.eat(&Tok::LBrace)?;
            self.block()?
        } else {
            Vec::new()
        };
        if catches.is_empty() && finally_body.is_empty() && resources.is_empty() {
            return Err(format!(
                "javars: `try` needs a `catch` or a `finally` (line {})",
                self.line()
            ));
        }
        if resources.is_empty() {
            return Ok(StmtKind::Try {
                body,
                catches,
                finally_body,
            });
        }
        Ok(Parser::with_resources(
            resources,
            body,
            catches,
            finally_body,
        ))
    }

    /// Parse a try-with-resources header `( <resource> ; … [;] )`, the cursor on
    /// the `(`. A resource is `Type name = expr`, `var name = expr`, or (Java 9)
    /// a bare name already holding an effectively-final reference.
    fn resource_spec(&mut self) -> Result<Vec<Resource>, String> {
        self.eat(&Tok::LParen)?;
        let mut out = Vec::new();
        loop {
            if self.is(&Tok::RParen) {
                self.advance();
                break;
            }
            // `final` on a resource declaration carries no meaning here.
            if matches!(self.peek(), Tok::Ident(w) if w == "final") {
                self.advance();
            }
            let line = self.line();
            // `try (existing)` — a bare name, no declaration.
            if matches!(self.peek(), Tok::Ident(_))
                && matches!(self.toks[self.pos + 1].kind, Tok::RParen | Tok::Semi)
            {
                let name = self.ident()?;
                out.push(Resource {
                    decl: None,
                    name,
                    line,
                });
            } else {
                let ty = self.type_name()?;
                let name = self.ident()?;
                self.eat(&Tok::Assign)?;
                let init = self.expression()?;
                out.push(Resource {
                    decl: Some((ty, init)),
                    name,
                    line,
                });
            }
            if self.is(&Tok::Semi) {
                self.advance();
            }
        }
        if out.is_empty() {
            return Err(format!(
                "javars: try-with-resources needs at least one resource (line {})",
                self.line()
            ));
        }
        Ok(out)
    }

    /// Desugar try-with-resources into the plain `try` nodes Java itself
    /// specifies it as: each resource declaration is followed by a
    /// `try { … } finally { if (r != null) r.close(); }` wrapping everything
    /// inside it, so resources close in reverse declaration order and close
    /// before any `catch`/`finally` of the outer statement runs.
    ///
    /// Java additionally records a close-thrown exception as *suppressed* on the
    /// body's exception; javars has no `addSuppressed`, so a throwing `close`
    /// replaces it (documented in BUGS.md).
    fn with_resources(
        resources: Vec<Resource>,
        body: Vec<Stmt>,
        catches: Vec<CatchArm>,
        finally_body: Vec<Stmt>,
    ) -> StmtKind {
        let mut inner = body;
        for r in resources.into_iter().rev() {
            let close = Stmt::new(
                r.line,
                StmtKind::If {
                    cond: Expr::Binary {
                        op: BinOp::Ne,
                        lhs: Box::new(Expr::Var(r.name.clone())),
                        rhs: Box::new(Expr::Var("null".to_string())),
                    },
                    then: vec![Stmt::new(
                        r.line,
                        StmtKind::Expr(Expr::MethodCall {
                            recv: Box::new(Expr::Var(r.name.clone())),
                            method: "close".to_string(),
                            args: Vec::new(),
                            line: r.line,
                        }),
                    )],
                    els: Vec::new(),
                },
            );
            let guarded = Stmt::new(
                r.line,
                StmtKind::Try {
                    body: inner,
                    catches: Vec::new(),
                    finally_body: vec![close],
                },
            );
            inner = match r.decl {
                Some((ty, init)) => vec![
                    Stmt::new(
                        r.line,
                        StmtKind::Local {
                            ty,
                            name: r.name,
                            init: Some(init),
                        },
                    ),
                    guarded,
                ],
                None => vec![guarded],
            };
        }
        if catches.is_empty() && finally_body.is_empty() {
            // No outer handler: the declarations + guarded body are just a
            // block, which this parser models as an always-taken `if`.
            return StmtKind::If {
                cond: Expr::Bool(true),
                then: inner,
                els: Vec::new(),
            };
        }
        StmtKind::Try {
            body: inner,
            catches,
            finally_body,
        }
    }

    /// Probe for an enhanced-`for` header `<type> <name> :`, the cursor sitting
    /// just past the `(`. On a match the cursor is left on the iterable
    /// expression and the declared type + variable name are returned; otherwise
    /// the cursor is restored untouched so the C-style clauses can parse.
    fn try_foreach_header(&mut self) -> Result<Option<(String, String)>, String> {
        if !self.looks_like_decl() {
            return Ok(None);
        }
        let save = self.pos;
        // `for (final String s : xs)` — the modifier is parsed and dropped.
        if matches!(self.peek(), Tok::Ident(w) if w == "final") {
            self.advance();
        }
        let ty = self.type_name()?;
        let name = self.ident()?;
        if self.is(&Tok::Colon) {
            self.advance();
            return Ok(Some((ty, name)));
        }
        self.pos = save;
        Ok(None)
    }

    /// Consume an optional label identifier following `break`/`continue`
    /// (`break outer;`). Returns `None` when the next token is the `;`.
    fn optional_label(&mut self) -> Option<String> {
        if let Tok::Ident(name) = self.peek().clone() {
            self.advance();
            Some(name)
        } else {
            None
        }
    }

    fn do_stmt(&mut self) -> Result<StmtKind, String> {
        self.eat(&Tok::Do)?;
        let body = self.braced_or_single()?;
        self.eat(&Tok::While)?;
        self.eat(&Tok::LParen)?;
        let cond = self.expression()?;
        self.eat(&Tok::RParen)?;
        self.eat(&Tok::Semi)?;
        Ok(StmtKind::DoWhile { body, cond })
    }

    /// Parse `switch (disc) { (case E:|default:)+ stmts ... }`. Consecutive
    /// `case`/`default` labels with no statements between them share the body
    /// that follows (`case 1: case 2: body`), forming one [`SwitchGroup`].
    fn switch_stmt(&mut self) -> Result<StmtKind, String> {
        // An arrow `switch` used as a *statement* is the expression form with
        // its value discarded, and that is exactly how it is lowered: one shared
        // parser, one shared lowering, no fall-through logic to keep in step.
        if self.at_arrow_switch() {
            return Ok(StmtKind::Expr(self.switch_expr()?));
        }
        self.eat(&Tok::Switch)?;
        self.eat(&Tok::LParen)?;
        let disc = self.expression()?;
        self.eat(&Tok::RParen)?;
        self.eat(&Tok::LBrace)?;
        let mut groups = Vec::new();
        while !self.is(&Tok::RBrace) && !self.is(&Tok::Eof) {
            // Collect the run of labels that introduce this group.
            let mut labels = Vec::new();
            let mut is_default = false;
            let mut guard = None;
            loop {
                if self.is(&Tok::Case) {
                    self.advance();
                    loop {
                        labels.push(self.case_label()?);
                        if self.is(&Tok::Comma) {
                            self.advance();
                        } else {
                            break;
                        }
                    }
                    guard = self.case_guard()?;
                    self.eat(&Tok::Colon)?;
                } else if self.is(&Tok::Default) {
                    self.advance();
                    self.eat(&Tok::Colon)?;
                    is_default = true;
                } else {
                    break;
                }
            }
            if labels.is_empty() && !is_default {
                return Err(format!(
                    "javars: expected `case` or `default` in switch body (line {})",
                    self.line()
                ));
            }
            // Statements up to the next label or the closing brace.
            let mut body = Vec::new();
            while !self.is(&Tok::Case)
                && !self.is(&Tok::Default)
                && !self.is(&Tok::RBrace)
                && !self.is(&Tok::Eof)
            {
                body.push(self.statement()?);
            }
            groups.push(SwitchGroup {
                labels,
                is_default,
                guard,
                body,
            });
        }
        self.eat(&Tok::RBrace)?;
        Ok(StmtKind::Switch { disc, groups })
    }

    /// True when the `switch` at the cursor uses the arrow form. The two forms
    /// differ only at the first label's terminator (`->` vs `:`), so the decision
    /// needs a scan past the discriminant's parentheses to that token.
    fn at_arrow_switch(&self) -> bool {
        if !self.is(&Tok::Switch) {
            return false;
        }
        let mut j = self.pos + 1;
        let mut depth = 0usize;
        // Skip `( disc )`.
        loop {
            match self.toks.get(j).map(|t| &t.kind) {
                Some(Tok::LParen) => depth += 1,
                Some(Tok::RParen) => {
                    depth -= 1;
                    if depth == 0 {
                        j += 1;
                        break;
                    }
                }
                Some(Tok::Eof) | None => return false,
                _ => {}
            }
            j += 1;
        }
        // `{ case <labels> ->` / `{ default ->`.
        if !matches!(self.toks.get(j).map(|t| &t.kind), Some(Tok::LBrace)) {
            return false;
        }
        j += 1;
        let mut depth = 0usize;
        loop {
            match self.toks.get(j).map(|t| &t.kind) {
                Some(Tok::Arrow) if depth == 0 => return true,
                Some(Tok::Colon) if depth == 0 => return false,
                // A label may itself contain parentheses; only a top-level
                // terminator decides the form.
                Some(Tok::LParen) => depth += 1,
                Some(Tok::RParen) => depth = depth.saturating_sub(1),
                Some(Tok::RBrace) | Some(Tok::Eof) | None => return false,
                _ => {}
            }
            j += 1;
        }
    }

    /// Parse an arrow `switch` expression, the cursor on `switch`.
    fn switch_expr(&mut self) -> Result<Expr, String> {
        let line = self.line();
        self.eat(&Tok::Switch)?;
        self.eat(&Tok::LParen)?;
        let disc = self.expression()?;
        self.eat(&Tok::RParen)?;
        self.eat(&Tok::LBrace)?;
        let mut arms = Vec::new();
        // Labels of colon-form arms with an empty body, waiting to be folded
        // into the next arm that has one (`case 1: case 2: yield x;`).
        let mut grouped: Vec<Expr> = Vec::new();
        while !self.is(&Tok::RBrace) && !self.is(&Tok::Eof) {
            let mut labels = Vec::new();
            let mut is_default = false;
            if self.is(&Tok::Default) {
                self.advance();
                is_default = true;
            } else {
                self.eat(&Tok::Case)?;
                loop {
                    labels.push(self.case_label()?);
                    if self.is(&Tok::Comma) {
                        self.advance();
                    } else {
                        break;
                    }
                }
            }
            let guard = self.case_guard()?;
            // Java allows both arm forms in a switch *expression*: `case X ->`
            // and the classic `case X:`. In the colon form every arm must
            // complete with `yield` or `throw`, so there is no fall-through
            // value to model — only an empty arm falls through, and that just
            // groups its labels onto the next one.
            if self.is(&Tok::Colon) {
                self.advance();
                self.switch_expr_depth += 1;
                let mut stmts = Vec::new();
                while !self.is(&Tok::Case)
                    && !self.is(&Tok::Default)
                    && !self.is(&Tok::RBrace)
                    && !self.is(&Tok::Eof)
                {
                    stmts.push(self.statement()?);
                }
                self.switch_expr_depth -= 1;
                if stmts.is_empty() && !is_default {
                    grouped.extend(labels);
                    continue;
                }
                labels.splice(0..0, grouped.drain(..));
                arms.push(SwitchArm {
                    labels,
                    is_default,
                    guard,
                    body: SwitchArmBody::Block(stmts),
                });
                continue;
            }
            self.eat(&Tok::Arrow)?;
            // Inside an arm body `yield` is a keyword; outside it stays an
            // ordinary identifier, which is what Java's contextual rule says.
            self.switch_expr_depth += 1;
            let body = if self.is(&Tok::LBrace) {
                self.advance();
                SwitchArmBody::Block(self.block()?)
            } else if matches!(self.peek(), Tok::Ident(w) if w == "throw") {
                // `case X -> throw new Foo();` — the one statement form an
                // unbraced arm may take. It never produces a value.
                SwitchArmBody::Block(vec![self.statement()?])
            } else {
                let e = self.expression()?;
                self.eat(&Tok::Semi)?;
                SwitchArmBody::Expr(Box::new(e))
            };
            self.switch_expr_depth -= 1;
            arms.push(SwitchArm {
                labels,
                is_default,
                guard,
                body,
            });
        }
        self.eat(&Tok::RBrace)?;
        Ok(Expr::SwitchExpr {
            disc: Box::new(disc),
            arms,
            line,
        })
    }

    /// One `case` label: a *type pattern* (`case Circle c`) or a constant
    /// expression (`case 1`, `case RED`, `case "x"`, `case null`).
    ///
    /// The two are told apart by shape rather than by looking up the name: a
    /// type pattern is an identifier, optional type arguments, then a *second*
    /// identifier, and no constant label has that shape — an enum constant, a
    /// `static final` name and a literal are each one token where the label
    /// ends. The binding is optional so `case Circle` (a type pattern with no
    /// variable, legal in a `switch` over a sealed type) is one too, but only
    /// when the discriminant is not an enum; that ambiguity is resolved in the
    /// compiler, which knows the discriminant's type, by treating a bare
    /// identifier as a constant.
    fn case_label(&mut self) -> Result<Expr, String> {
        if let Tok::Ident(class) = self.peek().clone() {
            let mut j = self.pos + 1;
            if matches!(self.toks[j].kind, Tok::Lt) {
                let mut depth = 0;
                while j < self.toks.len() {
                    match &self.toks[j].kind {
                        Tok::Lt => depth += 1,
                        t if t.generic_closers() > 0 => {
                            depth -= t.generic_closers();
                            if depth <= 0 {
                                j += 1;
                                break;
                            }
                        }
                        Tok::Eof => break,
                        _ => {}
                    }
                    j += 1;
                }
            }
            // `case Pt(int x, int y)` — a record pattern, told apart by the
            // `(` that no constant label can have here.
            if matches!(self.toks[j].kind, Tok::LParen) {
                self.pos = j;
                let (binding, components) = self.pattern_tail()?;
                return Ok(Expr::TypePattern {
                    class,
                    binding,
                    components,
                });
            }
            if let Tok::Ident(binding) = &self.toks[j].kind {
                // `when` is a contextual keyword: `case Foo when …` is a guarded
                // *constant* label, not a pattern binding named `when`.
                if binding != "when" {
                    let binding = binding.clone();
                    self.pos = j + 1;
                    return Ok(Expr::TypePattern {
                        class,
                        binding: Some(binding),
                        components: Vec::new(),
                    });
                }
            }
        }
        // Below the ternary, so the label's terminator (`:` or `->`) is not
        // swallowed.
        self.binary(0)
    }

    /// What follows a pattern's type: a binding name, a record pattern's
    /// component list, or neither.
    ///
    /// `(` opens a **record pattern**, whose components are themselves patterns
    /// — `Pt(int x, int y)`, and nested — so this recurses. Java 21 dropped the
    /// named record pattern, so a component list is never followed by a
    /// binding. An identifier is a plain type pattern's binding, and anything
    /// else is a bare type test with neither.
    fn pattern_tail(&mut self) -> Result<(Option<String>, Vec<Expr>), String> {
        if self.is(&Tok::LParen) {
            self.advance();
            let mut components = Vec::new();
            if !self.is(&Tok::RParen) {
                loop {
                    components.push(self.component_pattern()?);
                    if self.is(&Tok::Comma) {
                        self.advance();
                    } else {
                        break;
                    }
                }
            }
            self.eat(&Tok::RParen)?;
            return Ok((None, components));
        }
        let binding = match self.peek() {
            Tok::Ident(_) => Some(self.ident()?),
            _ => None,
        };
        Ok((binding, Vec::new()))
    }

    /// One component of a record pattern: `int x`, `var v`, `String s`, or a
    /// nested `Pt(int a, int b)`.
    ///
    /// A component's type is always written out (there is no bare binding), so
    /// this reads the type and then defers to [`Parser::pattern_tail`] for the
    /// rest — which is what makes the nesting fall out rather than needing its
    /// own case.
    fn component_pattern(&mut self) -> Result<Expr, String> {
        let class = self.type_name()?;
        let (binding, components) = self.pattern_tail()?;
        Ok(Expr::TypePattern {
            class,
            binding,
            components,
        })
    }

    /// A `when <expr>` guard following a `case` label list, if there is one.
    fn case_guard(&mut self) -> Result<Option<Expr>, String> {
        if !matches!(self.peek(), Tok::Ident(w) if w == "when") {
            return Ok(None);
        }
        self.advance();
        Ok(Some(self.binary(0)?))
    }

    // ── expressions (precedence climbing) ─────────────────────────────────

    /// A full expression: a binary/precedence-climbed operand optionally
    /// followed by the ternary `? then : els`. The ternary binds looser than
    /// every binary operator and is right-associative — `a ? b : c ? d : e`
    /// parses as `a ? b : (c ? d : e)` because the `els` branch recurses through
    /// `expression`.
    fn expression(&mut self) -> Result<Expr, String> {
        // A lambda is recognised before any operator parsing, because its
        // parameter list is not an expression: `(a, b) -> …` would otherwise be
        // parsed as a parenthesized `a` followed by a stray comma.
        if let Some(lambda) = self.try_lambda()? {
            return Ok(lambda);
        }
        let cond = self.binary(0)?;
        if self.is(&Tok::Question) {
            self.advance();
            let then = self.expression()?;
            self.eat(&Tok::Colon)?;
            let els = self.expression()?;
            return Ok(Expr::Ternary {
                cond: Box::new(cond),
                then: Box::new(then),
                els: Box::new(els),
            });
        }
        Ok(cond)
    }

    fn binary(&mut self, min_bp: u8) -> Result<Expr, String> {
        let mut lhs = self.unary()?;
        loop {
            // `instanceof` is a relational operator (binding power 4) whose
            // right-hand side is a type name, not an expression.
            if matches!(self.peek(), Tok::Ident(w) if w == "instanceof") && BP_RELATIONAL >= min_bp
            {
                self.advance();
                let class = self.ident()?;
                // `o instanceof List<?>` — the type argument is erased, so it is
                // parsed and discarded exactly as every other type position's is.
                self.skip_generics();
                // A *type pattern* names a variable after the type
                // (`o instanceof String s`), which Java binds to the tested
                // value wherever the pattern definitely matched. An identifier
                // is the only thing that can follow the type here — every
                // operator, delimiter and keyword the grammar allows after a
                // relational operand is a different token — so the lookahead
                // needs no further disambiguation.
                let (binding, components) = self.pattern_tail()?;
                lhs = Expr::InstanceOf {
                    expr: Box::new(lhs),
                    class,
                    binding,
                    components,
                };
                continue;
            }
            let Some((op, bp)) = binop(self.peek()) else {
                break;
            };
            if bp < min_bp {
                break;
            }
            self.advance();
            let rhs = self.binary(bp + 1)?;
            lhs = Expr::Binary {
                op,
                lhs: Box::new(lhs),
                rhs: Box::new(rhs),
            };
        }
        Ok(lhs)
    }

    /// Parse a lambda if the cursor is at one, else leave the cursor untouched.
    ///
    /// Two spellings start a lambda: a bare `x ->`, and a parenthesized
    /// parameter list `(…) ->`. Only the arrow distinguishes the second from a
    /// parenthesized expression, so the decision needs a scan to the matching
    /// `)` before any token is consumed.
    fn try_lambda(&mut self) -> Result<Option<Expr>, String> {
        let line = self.line();
        // `x -> …`
        if matches!(self.peek(), Tok::Ident(_)) && self.toks[self.pos + 1].kind == Tok::Arrow {
            let name = self.ident()?;
            self.eat(&Tok::Arrow)?;
            let body = self.lambda_body()?;
            self.uses_functional = true;
            return Ok(Some(Expr::Lambda {
                params: vec![name],
                body,
                line,
            }));
        }
        if !self.is(&Tok::LParen) {
            return Ok(None);
        }
        // `(…) -> …` — scan to the matching `)` and require an arrow after it.
        let mut depth = 0usize;
        let mut j = self.pos;
        loop {
            match &self.toks[j].kind {
                Tok::LParen => depth += 1,
                Tok::RParen => {
                    depth -= 1;
                    if depth == 0 {
                        break;
                    }
                }
                Tok::Eof => return Ok(None),
                _ => {}
            }
            j += 1;
        }
        if self.toks[j + 1].kind != Tok::Arrow {
            return Ok(None);
        }
        self.eat(&Tok::LParen)?;
        let mut params = Vec::new();
        while !self.is(&Tok::RParen) {
            // `final` is a legal modifier on an explicitly-typed parameter.
            if matches!(self.peek(), Tok::Ident(w) if w == "final") {
                self.advance();
            }
            // An explicitly-typed parameter (`(int a, String b) -> …`) is two
            // identifiers; an inferred one (`(a, b) -> …`) is one. The declared
            // type is erased, as every other javars declared type is.
            if matches!(self.peek(), Tok::Ident(_) | Tok::Void)
                && matches!(
                    self.toks[self.pos + 1].kind,
                    Tok::Ident(_) | Tok::Lt | Tok::LBracket
                )
            {
                self.type_name()?;
            }
            params.push(self.ident()?);
            if self.is(&Tok::Comma) {
                self.advance();
            } else {
                break;
            }
        }
        self.eat(&Tok::RParen)?;
        self.eat(&Tok::Arrow)?;
        let body = self.lambda_body()?;
        self.uses_functional = true;
        Ok(Some(Expr::Lambda { params, body, line }))
    }

    /// A lambda's body: `{ statements }` or a single expression.
    fn lambda_body(&mut self) -> Result<LambdaBody, String> {
        if self.is(&Tok::LBrace) {
            self.advance();
            return Ok(LambdaBody::Block(self.block()?));
        }
        Ok(LambdaBody::Expr(Box::new(self.expression()?)))
    }

    fn unary(&mut self) -> Result<Expr, String> {
        // A cast shares its opening `(` with a parenthesized expression, so it
        // is probed (without consuming anything on a miss) before the prefix
        // operators — `(int) -x` is a cast of a negation, not a negation.
        if let Some(cast) = self.try_cast()? {
            return Ok(cast);
        }
        match self.peek() {
            Tok::Minus => {
                self.advance();
                Ok(Expr::Unary {
                    op: UnOp::Neg,
                    rhs: Box::new(self.unary()?),
                })
            }
            // Java's unary `+` leaves the value alone, but it is not a no-op:
            // JLS 5.6.1 promotes a `byte`/`short`/`char` operand to `int`, and
            // for `char` that is visible in the result's rendering. Dropping the
            // node here made `+c` a `char` again, so `"" + +c` printed the
            // letter where Java prints its code point.
            Tok::Plus => {
                self.advance();
                Ok(Expr::Unary {
                    op: UnOp::Plus,
                    rhs: Box::new(self.unary()?),
                })
            }
            Tok::Not => {
                self.advance();
                Ok(Expr::Unary {
                    op: UnOp::Not,
                    rhs: Box::new(self.unary()?),
                })
            }
            Tok::Tilde => {
                self.advance();
                Ok(Expr::Unary {
                    op: UnOp::BitNot,
                    rhs: Box::new(self.unary()?),
                })
            }
            // `++i` / `--i`: update first, and the expression's value is the
            // *new* one. The operand is a whole lvalue, not just an identifier:
            // `++a[i]` and `++p.n` are as valid as `++i`, and parsing only an
            // identifier rejected them outright.
            Tok::PlusPlus | Tok::MinusMinus => {
                let inc = self.is(&Tok::PlusPlus);
                let line = self.line();
                self.advance();
                match self.postfix()? {
                    Expr::Var(name) => Ok(Expr::PreIncDec { name, inc }),
                    target => Ok(Expr::IncDec {
                        target: Box::new(target),
                        inc,
                        post: false,
                        line,
                    }),
                }
            }
            _ => self.postfix(),
        }
    }

    /// Parse `(Type) operand` if the cursor is at one, else leave the cursor
    /// untouched and return `None`.
    ///
    /// `(x)` opens both a cast and a parenthesized expression, and only what
    /// follows the `)` tells them apart. Java's rule, reproduced here: a
    /// *primitive* type name is always a cast (`(int) -x`), while a reference
    /// type name is a cast only when the next token can start an operand —
    /// `(a) - b` is a subtraction, `(a) b` and `(Integer) o` are casts.
    fn try_cast(&mut self) -> Result<Option<Expr>, String> {
        if !self.is(&Tok::LParen) {
            return Ok(None);
        }
        let at = |j: usize| self.toks.get(j).map(|t| &t.kind).unwrap_or(&Tok::Eof);
        let mut j = self.pos + 1;
        let Tok::Ident(head) = at(j) else {
            return Ok(None);
        };
        // A qualified name (`java.util.List`) keys on its simple name, which is
        // what every other javars type lookup uses.
        let mut name = head.clone();
        j += 1;
        while matches!(at(j), Tok::Dot) {
            let Tok::Ident(seg) = at(j + 1) else {
                return Ok(None);
            };
            name = seg.clone();
            j += 2;
        }
        // Type arguments are erased, so they only have to be stepped over.
        if matches!(at(j), Tok::Lt) {
            let mut depth = 0;
            loop {
                match at(j) {
                    Tok::Lt => depth += 1,
                    Tok::Eof => return Ok(None),
                    t if t.generic_closers() > 0 => {
                        depth -= t.generic_closers();
                        if depth <= 0 {
                            j += 1;
                            break;
                        }
                    }
                    _ => {}
                }
                j += 1;
            }
        }
        while matches!(at(j), Tok::LBracket) && matches!(at(j + 1), Tok::RBracket) {
            name.push_str("[]");
            j += 2;
        }
        if !matches!(at(j), Tok::RParen) {
            return Ok(None);
        }
        let primitive = matches!(
            name.as_str(),
            "int" | "long" | "short" | "byte" | "char" | "float" | "double" | "boolean"
        );
        // `instanceof` reads as an identifier but continues the *enclosing*
        // expression, so it must not be mistaken for a cast operand.
        let starts_operand = match at(j + 1) {
            Tok::Ident(w) => w != "instanceof",
            Tok::Str(_)
            | Tok::Char(_)
            | Tok::Int(_)
            | Tok::Long(_)
            | Tok::Float(_)
            | Tok::Float32(_)
            | Tok::True
            | Tok::False
            | Tok::LParen
            | Tok::Not
            | Tok::Tilde
            | Tok::New => true,
            _ => false,
        };
        if !primitive && !starts_operand {
            return Ok(None);
        }
        let line = self.toks[j].line;
        self.pos = j + 1;
        let expr = self.unary()?;
        Ok(Some(Expr::Cast {
            ty: name,
            expr: Box::new(expr),
            line,
        }))
    }

    /// Parse a primary followed by any postfix chain: `.method(args)` instance
    /// method calls, `.field` field access (an array's `.length` or an instance
    /// field), and `[index]` array indexing. Chains compose left-to-right
    /// (`grid[i][j]`, `s.substring(1).length()`, `p.next.value`).
    fn postfix(&mut self) -> Result<Expr, String> {
        let mut e = self.primary()?;
        loop {
            if self.is(&Tok::Dot) {
                let line = self.line();
                self.advance();
                // `outer.new Inner(…)` — a *qualified* class instance creation.
                // javars flattens nested types into one namespace, so `Inner`
                // names the same class a bare `new Inner(…)` does and the
                // qualifier is dropped. An inner class that reads the outer
                // *instance*'s fields is unmodeled either way (see BUGS.md); the
                // qualifier only ever said which instance, and there is none to
                // say. A side-effecting qualifier is evaluated by Java and not
                // here, which is the observable part of dropping it.
                if self.is(&Tok::New) {
                    e = self.new_expr()?;
                    continue;
                }
                // An *explicit* generic method type argument
                // (`Optional.<String>empty()`, `Collections.<Integer>emptyList()`)
                // sits between the dot and the method name. Java erases it, and
                // it is the only thing that can appear there, so it is skipped
                // like every other type-argument group.
                self.skip_generics();
                let member = self.ident()?;
                if self.is(&Tok::LParen) {
                    let args = self.call_args()?;
                    e = Expr::MethodCall {
                        recv: Box::new(e),
                        method: member,
                        args,
                        line,
                    };
                } else {
                    e = Expr::Field {
                        recv: Box::new(e),
                        name: member,
                    };
                }
            } else if self.is(&Tok::ColonColon) {
                let line = self.line();
                self.advance();
                // `Type::new` is a constructor reference; everything else names
                // a method.
                let method = if self.is(&Tok::New) {
                    self.advance();
                    "new".to_string()
                } else {
                    self.ident()?
                };
                self.uses_functional = true;
                e = Expr::MethodRef {
                    recv: Box::new(e),
                    method,
                    line,
                };
            } else if self.is(&Tok::LBracket) {
                self.advance();
                let index = self.expression()?;
                self.eat(&Tok::RBracket)?;
                e = Expr::Index {
                    array: Box::new(e),
                    index: Box::new(index),
                };
            } else {
                break;
            }
        }
        // `a[i]++` / `p.n++`: a suffix update of the chain just parsed. A bare
        // `i++` never reaches here — `primary` consumes it — so only the array
        // and field forms are built, and they must keep the target expression so
        // the index or receiver is evaluated once.
        if matches!(e, Expr::Index { .. } | Expr::Field { .. })
            && matches!(self.peek(), Tok::PlusPlus | Tok::MinusMinus)
        {
            let inc = self.is(&Tok::PlusPlus);
            let line = self.line();
            self.advance();
            e = Expr::IncDec {
                target: Box::new(e),
                inc,
                post: true,
                line,
            };
        }
        Ok(e)
    }

    fn primary(&mut self) -> Result<Expr, String> {
        match self.peek().clone() {
            Tok::Int(n) => {
                self.advance();
                Ok(Expr::Int(n))
            }
            Tok::Long(n) => {
                self.advance();
                Ok(Expr::Long(n))
            }
            Tok::Float(f) => {
                self.advance();
                Ok(Expr::Float(f))
            }
            Tok::Float32(f) => {
                self.advance();
                Ok(Expr::Float32(f))
            }
            Tok::Str(s) => {
                self.advance();
                Ok(Expr::Str(s))
            }
            Tok::Char(c) => {
                self.advance();
                Ok(Expr::Char(c))
            }
            Tok::True => {
                self.advance();
                Ok(Expr::Bool(true))
            }
            Tok::False => {
                self.advance();
                Ok(Expr::Bool(false))
            }
            Tok::LParen => {
                self.advance();
                let e = self.expression()?;
                self.eat(&Tok::RParen)?;
                Ok(e)
            }
            Tok::New => self.new_expr(),
            // A `switch` *expression* — only the arrow form has one.
            Tok::Switch => self.switch_expr(),
            Tok::Ident(name) if name == "this" => {
                let line = self.line();
                self.advance();
                // `this(args)` is an explicit constructor invocation (JLS 8.8.7.1)
                // — a call, not a read of `this`. It is spelled as a `Call` named
                // `this`, the same shape `super(args)` already uses.
                if self.is(&Tok::LParen) {
                    let args = self.call_args()?;
                    return Ok(Expr::Call {
                        name: "this".to_string(),
                        args,
                        line,
                    });
                }
                Ok(Expr::This)
            }
            Tok::Ident(name) => {
                // `System.out.println(...)` / `.print(...)`, or a var read,
                // a bare-identifier call `name(args)`, or unsupported field
                // access.
                // `java.lang.System.out.println(...)` names the same stream its
                // simple form does. The package prefix is stepped over here
                // rather than in [`Parser::simple_type_name`] because
                // `System.out` is parsed as a dedicated node, not as a type.
                if name == "java"
                    && matches!(&self.toks[self.pos + 2].kind, Tok::Ident(w) if w == "lang")
                    && matches!(&self.toks[self.pos + 4].kind, Tok::Ident(w) if w == "System")
                {
                    self.advance(); // java
                    self.eat(&Tok::Dot)?;
                    self.advance(); // lang
                    self.eat(&Tok::Dot)?;
                    return self.system_out();
                }
                if name == "System" {
                    // `System.out::println` is a method *reference*, not a call:
                    // hand the stream back as a field access and let the postfix
                    // layer take the `::`.
                    if self.toks[self.pos + 3].kind == Tok::ColonColon {
                        self.advance(); // System
                        self.eat(&Tok::Dot)?;
                        let stream = self.ident()?;
                        return Ok(Expr::Field {
                            recv: Box::new(Expr::Var("System".to_string())),
                            name: stream,
                        });
                    }
                    return self.system_out();
                }
                let line = self.line();
                self.advance();
                // `i++` / `i--` in value position: the expression's value is the
                // variable's *old* value, with the update applied after (the
                // compiler's `Expr::PostIncDec` arm emits exactly that order).
                if matches!(self.peek(), Tok::PlusPlus | Tok::MinusMinus) {
                    let inc = self.is(&Tok::PlusPlus);
                    self.advance();
                    return Ok(Expr::PostIncDec { name, inc });
                }
                // `name(args...)` — a call. The compiler resolves it: the FFI
                // desugar target `__rust_compile(...)` and `rust { ... }`-exported
                // barewords lower to `fusevm::ffi`; any other name with no FFI
                // block present is an unresolved reference.
                if self.is(&Tok::LParen) {
                    let args = self.call_args()?;
                    return Ok(Expr::Call { name, args, line });
                }
                // Naming a functional interface pulls in the prelude that
                // declares it — and it can be named in an *expression* as well
                // as in a type position: `Comparator.naturalOrder()` writes it
                // as a static-call receiver and nowhere else, which is why
                // `Comparator` was ``cannot find symbol`` for a program that
                // used nothing but its statics.
                if crate::prelude::is_functional(&name) {
                    self.uses_functional = true;
                }
                // A trailing `.` (method/field access) is consumed by the
                // postfix layer above; a bare identifier is a variable read.
                Ok(Expr::Var(name))
            }
            other => Err(format!(
                "javars: unexpected token {other} in expression on line {}",
                self.line()
            )),
        }
    }

    /// Parse a `new` expression, the cursor sitting just past `new`:
    /// `new Type[size]` (default-valued array), `new Type[]{elems}` /
    /// `new Type[]{}` (array literal), or `new Class(args)` (object).
    fn new_expr(&mut self) -> Result<Expr, String> {
        let line = self.line();
        self.eat(&Tok::New)?;
        let mut ty = self.simple_type_name()?;
        // `new Outer.Nested()` — javars flattens nested types into one namespace
        // keyed by the *simple* name, so the qualifier names the same class the
        // bare `new Nested()` does and is dropped. A lowercase qualifier is a
        // package (`new java.util.ArrayList<>()`), which `simple_type_name` has
        // already consumed.
        while self.is(&Tok::Dot) && matches!(&self.toks[self.pos + 1].kind, Tok::Ident(_)) {
            self.advance();
            ty = self.ident()?;
        }
        // Diamond / explicit type arguments (`new Box<>()`, `new Box<Integer>()`)
        // — erased.
        self.skip_generics();
        if self.is(&Tok::LBracket) {
            self.advance();
            if self.is(&Tok::RBracket) {
                // `new T[]{…}` / `new T[][]{{…},{…}}` — an array literal with an
                // explicit element type. Each extra `[]` pair deepens the
                // element type by one dimension (`new int[][]` has `int[]`
                // elements), which is what a `var` binding needs to infer from.
                self.advance();
                let mut elem_ty = ty;
                while self.is(&Tok::LBracket) {
                    self.advance();
                    self.eat(&Tok::RBracket)?;
                    elem_ty.push_str("[]");
                }
                self.eat(&Tok::LBrace)?;
                let elems = self.array_lit_elems()?;
                return Ok(Expr::ArrayLit {
                    elems,
                    elem_ty: Some(elem_ty),
                });
            }
            // `new T[s0][s1]…[sK][]…` — collect the sized dimensions, then any
            // trailing unsized `[]` (whose elements default to null).
            let mut sizes = vec![self.expression()?];
            self.eat(&Tok::RBracket)?;
            let mut extra_dims = 0;
            while self.is(&Tok::LBracket) {
                self.advance();
                if self.is(&Tok::RBracket) {
                    self.advance();
                    extra_dims += 1;
                } else {
                    if extra_dims > 0 {
                        return Err(format!(
                            "javars: a sized array dimension cannot follow an empty one (line {line})"
                        ));
                    }
                    sizes.push(self.expression()?);
                    self.eat(&Tok::RBracket)?;
                }
            }
            return Ok(Expr::NewArray {
                elem_ty: ty,
                sizes,
                extra_dims,
            });
        }
        // `new Class(args)` — object construction. Constructing a modeled
        // `java.lang` throwable pulls in the exception prelude even when the
        // program never throws it (`Exception e = new Exception("x");`).
        if crate::prelude::is_throwable(&ty) {
            self.uses_exceptions = true;
        }
        let args = self.call_args()?;
        // `new I() { … }` — an anonymous class. When its body declares exactly
        // one method it *is* a lambda: the interface has one abstract method,
        // the body supplies it, and the enclosing locals it reads are captured
        // the same way. Desugaring to one reuses that whole path — including the
        // capture machinery, which is the part an anonymous class most needs.
        if self.is(&Tok::LBrace) {
            return self.anonymous_class(&ty, line);
        }
        Ok(Expr::NewObject {
            class: ty,
            args,
            line,
        })
    }

    /// Desugar an anonymous class body into the lambda it abbreviates.
    ///
    /// Only the single-method form is modeled, which is the form an anonymous
    /// class is written in: the interface it implements has one abstract method
    /// and the body supplies it. A body that declares a field, a constructor, or
    /// a second method is a real class with state, and is refused by name rather
    /// than silently losing the members javars would not carry.
    fn anonymous_class(&mut self, ty: &str, line: u32) -> Result<Expr, String> {
        self.eat(&Tok::LBrace)?;
        let mut methods = Vec::new();
        while !self.is(&Tok::RBrace) && !self.is(&Tok::Eof) {
            match self.try_any_method(ty)? {
                Some((m, _)) => methods.push(m),
                None => {
                    return Err(format!(
                        "javars: an anonymous `{ty}` may declare only methods (line {line})"
                    ))
                }
            }
        }
        self.eat(&Tok::RBrace)?;
        let [m] = <[Method; 1]>::try_from(methods).map_err(|ms| {
            format!(
                "javars: an anonymous `{ty}` is modeled only when its body declares exactly one                  method; this one declares {} (line {line})",
                ms.len()
            )
        })?;
        self.uses_functional = true;
        Ok(Expr::Lambda {
            params: m.params.iter().map(|p| p.name.clone()).collect(),
            body: LambdaBody::Block(m.body),
            line,
        })
    }

    /// Parse the elements of an array literal `{e, e, ...}` (a trailing comma is
    /// allowed), the cursor sitting just past the opening `{`; consumes the `}`.
    fn array_lit_elems(&mut self) -> Result<Vec<Expr>, String> {
        let mut elems = Vec::new();
        while !self.is(&Tok::RBrace) && !self.is(&Tok::Eof) {
            // A nested `{…}` element is a sub-array literal (`{{1,2},{3,4}}`).
            if self.is(&Tok::LBrace) {
                self.advance();
                let inner = self.array_lit_elems()?;
                elems.push(Expr::ArrayLit {
                    elems: inner,
                    elem_ty: None,
                });
            } else {
                elems.push(self.expression()?);
            }
            if self.is(&Tok::Comma) {
                self.advance();
            } else {
                break;
            }
        }
        self.eat(&Tok::RBrace)?;
        Ok(elems)
    }

    /// Parse a parenthesized, comma-separated argument list `( e, e, ... )`,
    /// the cursor sitting on the opening `(`.
    fn call_args(&mut self) -> Result<Vec<Expr>, String> {
        self.eat(&Tok::LParen)?;
        let mut args = Vec::new();
        if !self.is(&Tok::RParen) {
            loop {
                args.push(self.expression()?);
                if self.is(&Tok::Comma) {
                    self.advance();
                } else {
                    break;
                }
            }
        }
        self.eat(&Tok::RParen)?;
        Ok(args)
    }

    /// Parse `System.out.println(arg)` / `System.out.print(arg)` and the
    /// `System.err` variants (which print to stderr).
    fn system_out(&mut self) -> Result<Expr, String> {
        self.ident()?; // System
        self.eat(&Tok::Dot)?;
        let stream = self.ident()?;
        let err = match stream.as_str() {
            "out" => false,
            "err" => true,
            _ => {
                return Err(format!(
                    "javars: only `System.out`/`System.err` are supported, not `System.{stream}` (line {})",
                    self.line()
                ))
            }
        };
        self.eat(&Tok::Dot)?;
        let line = self.line();
        let method = self.ident()?;
        // `printf(fmt, args…)` is `print(String.format(fmt, args…))` — the same
        // formatter, no trailing newline. Desugaring here keeps one formatting
        // implementation instead of two.
        if method == "printf" || method == "format" {
            let args = self.call_args()?;
            return Ok(Expr::Println {
                newline: false,
                err,
                arg: Some(Box::new(Expr::MethodCall {
                    recv: Box::new(Expr::Var("String".to_string())),
                    method: "format".to_string(),
                    args,
                    line,
                })),
            });
        }
        let newline = match method.as_str() {
            "println" => true,
            "print" => false,
            _ => {
                return Err(format!(
                "javars: only `System.{stream}.println`/`print`/`printf` are supported, not `{method}` (line {})",
                self.line()
            ))
            }
        };
        self.eat(&Tok::LParen)?;
        let arg = if self.is(&Tok::RParen) {
            None
        } else {
            Some(Box::new(self.expression()?))
        };
        self.eat(&Tok::RParen)?;
        Ok(Expr::Println { newline, err, arg })
    }

    fn ident(&mut self) -> Result<String, String> {
        match self.advance() {
            Tok::Ident(s) => Ok(s),
            // type keywords double as idents in declaration position
            Tok::Void => Ok("void".into()),
            other => Err(format!(
                "javars: expected an identifier but found {other} on line {}",
                self.line()
            )),
        }
    }
}

/// Map a token to a compound-assignment operator, if it is one.
fn assign_op(t: &Tok) -> Option<AssignOp> {
    Some(match t {
        Tok::Assign => AssignOp::Assign,
        Tok::PlusAssign => AssignOp::Add,
        Tok::MinusAssign => AssignOp::Sub,
        Tok::StarAssign => AssignOp::Mul,
        Tok::SlashAssign => AssignOp::Div,
        Tok::PercentAssign => AssignOp::Mod,
        Tok::AmpAssign => AssignOp::BitAnd,
        Tok::PipeAssign => AssignOp::BitOr,
        Tok::CaretAssign => AssignOp::BitXor,
        Tok::ShlAssign => AssignOp::Shl,
        Tok::ShrAssign => AssignOp::Shr,
        Tok::UshrAssign => AssignOp::Ushr,
        _ => return None,
    })
}

/// Binding power of `instanceof`, which [`Parser::binary`] handles inline
/// because its right-hand side is a type name rather than an expression. Java
/// puts it at the relational level, alongside `<` and `>`.
const BP_RELATIONAL: u8 = 7;

/// Binary operator + its binding power (higher binds tighter).
///
/// The ladder is Java's, loosest first: `||`, `&&`, `|`, `^`, `&`, equality,
/// relational (+ `instanceof`), shift, additive, multiplicative.
fn binop(t: &Tok) -> Option<(BinOp, u8)> {
    Some(match t {
        Tok::OrOr => (BinOp::Or, 1),
        Tok::AndAnd => (BinOp::And, 2),
        Tok::Pipe => (BinOp::BitOr, 3),
        Tok::Caret => (BinOp::BitXor, 4),
        Tok::Amp => (BinOp::BitAnd, 5),
        Tok::EqEq => (BinOp::Eq, 6),
        Tok::NotEq => (BinOp::Ne, 6),
        Tok::Lt => (BinOp::Lt, BP_RELATIONAL),
        Tok::Gt => (BinOp::Gt, BP_RELATIONAL),
        Tok::Le => (BinOp::Le, BP_RELATIONAL),
        Tok::Ge => (BinOp::Ge, BP_RELATIONAL),
        Tok::Shl => (BinOp::Shl, 8),
        Tok::Shr => (BinOp::Shr, 8),
        Tok::Ushr => (BinOp::Ushr, 8),
        Tok::Plus => (BinOp::Add, 9),
        Tok::Minus => (BinOp::Sub, 9),
        Tok::Star => (BinOp::Mul, 10),
        Tok::Slash => (BinOp::Div, 10),
        Tok::Percent => (BinOp::Mod, 10),
        _ => return None,
    })
}