javars 0.1.14

Java as a fusevm frontend: lexer, parser, and compiler to fusevm::Chunk, run on the shared three-tier Cranelift JIT — no bespoke VM or JVM
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
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
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
//! A recursive-descent arser 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,
        type_params: Vec::new(),
        enclosing: Vec::new(),
        local_binary: None,
        local_counts: std::collections::HashMap::new(),
        local_methods: Vec::new(),
        local_classes: Vec::new(),
        scope: Vec::new(),
        local_captures: std::collections::HashMap::new(),
        inner_of: None,
        enclosing_names: Vec::new(),
        in_static: false,
        enclosing_enum: None,
        anon_supers: Vec::new(),
        class_names: std::collections::HashSet::new(),
        last_targs: Vec::new(),
        last_targs_wildcard: false,
        last_super_slots: Vec::new(),
    };
    // The names declared as classes (not interfaces) anywhere in the unit, so
    // an anonymous class can tell a superclass from an interface even when the
    // type is declared after the `new` that names it.
    for w in p.toks.windows(2) {
        if let (Tok::Class, Tok::Ident(n)) = (&w[0].kind, &w[1].kind) {
            p.class_names.insert(n.clone());
        }
        if let (Tok::Ident(kw), Tok::Ident(n)) = (&w[0].kind, &w[1].kind) {
            if kw == "enum" || kw == "record" {
                p.class_names.insert(n.clone());
            }
        }
    }
    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,
    /// The type-parameter names in scope at the cursor — a `class Box<T>`'s and
    /// the enclosing method's, pushed at the declaration and popped after its
    /// body.
    ///
    /// Java erases these, and javars erases them too, but erasing by *dropping
    /// the name* leaves the raw text behind — so in a program where a type
    /// variable and a class share a name, `T get()` was read as returning the
    /// class. The parity harness writes exactly that shape (`public class T`
    /// holding `interface Gen<T> { T get(); }`), and it made `g.get().length()`
    /// the hard error ``class `T` has no method `length` ``. A name in this set
    /// erases to `Object` instead, which is what Java's own erasure produces
    /// for an unbounded parameter and which leaves the call to dispatch on the
    /// receiver at run time.
    type_params: Vec<String>,
    /// The type arguments of the type [`Parser::type_name`] read last, in
    /// [`crate::ast::generic_parts`] form — what a declaration site copies into
    /// its `targs`.
    last_targs: Vec<String>,
    /// Whether a top-level argument of [`Parser::last_targs`] was a wildcard.
    last_targs_wildcard: bool,
    /// The positions of its lower-bounded wildcard arguments (`? super X`).
    last_super_slots: Vec<usize>,
    /// The binary names of the type declarations enclosing the cursor,
    /// innermost last — what a local type declared in a method body is named
    /// after.
    enclosing: Vec<String>,
    /// The binary name the next [`Parser::parse_class`] takes instead of
    /// deriving one, set for a local type (`T$1Point`).
    local_binary: Option<String>,
    /// How many local types of each simple name the outermost class holds so
    /// far, which is the number `javac` puts in the binary name.
    local_counts: std::collections::HashMap<(String, String), usize>,
    /// Local types, and the `static` methods they declare, hoisted out of the
    /// method bodies that declared them and added to the program at the end.
    local_methods: Vec<Method>,
    local_classes: Vec<Class>,
    /// The locals and parameters in scope at the cursor, innermost last, as
    /// `(name, declared type)` — what a local class declared here can capture.
    scope: Vec<(String, String)>,
    /// The captured locals of each local class parsed so far, by binary name,
    /// so a local class extending another captures what its superclass does.
    local_captures: std::collections::HashMap<String, Vec<Param>>,
    /// The enclosing class's name, set just before an inner member class is
    /// parsed and taken by [`Parser::parse_class`].
    inner_of: Option<String>,
    /// The simple names of the classes enclosing the cursor, innermost last
    /// (the names [`Parser::enclosing`] holds the binary names of).
    enclosing_names: Vec<String>,
    /// True while the cursor is in a `static` method body (or `main`), where a
    /// local class has no enclosing instance.
    in_static: bool,
    /// The innermost enum whose body (constant bodies included) the cursor
    /// is in.
    enclosing_enum: Option<String>,
    /// The anonymous classes lifted to real classes, as `(binary name, the type
    /// after `new`)`. Whether that type is a class to extend or an interface to
    /// implement is only known once every declaration is parsed — a top-level
    /// interface may be declared after the `main` that instantiates it — so
    /// [`Parser::program`] settles it at the end.
    anon_supers: Vec<(String, String)>,
    /// Every type the unit declares as a `class`, `enum`, or `record`.
    class_names: std::collections::HashSet<String>,
}

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)?;
        }
        methods.append(&mut self.local_methods);
        classes.append(&mut self.local_classes);
        // An anonymous class's synthesized constructor forwards its arguments
        // to `super(…)`, and javac types its parameters as the superclass
        // constructor it selected. With every class now parsed, the superclass
        // constructor of the same arity supplies them; when there is none, or
        // more than one, the erased `Object` stands.
        for (anon, sup) in std::mem::take(&mut self.anon_supers) {
            let Some(sup_cl) = classes.iter().find(|c| c.name == sup) else {
                continue;
            };
            let own = sup_cl.captures.len();
            let Some(anon_cl) = classes.iter().find(|c| c.name == anon) else {
                continue;
            };
            let nargs = anon_cl.ctors[0].params.len() - anon_cl.captures.len();
            let mut fits = sup_cl
                .ctors
                .iter()
                .filter(|c| c.params.len() - own == nargs);
            let (Some(fit), None) = (fits.next(), fits.next()) else {
                continue;
            };
            let tys: Vec<String> = fit.params[..nargs].iter().map(|p| p.ty.clone()).collect();
            if let Some(anon_cl) = classes.iter_mut().find(|c| c.name == anon) {
                for (p, ty) in anon_cl.ctors[0].params.iter_mut().zip(tys) {
                    p.ty = ty;
                }
            }
        }
        // javac names an enum constant's body `Enum$1`, `Enum$2`, … in
        // declaration order. The synthetic subclass is minted under another name
        // while parsing, so its binary name is assigned once the enum's own is
        // known.
        let numbered: Vec<(String, String)> = classes
            .iter()
            .flat_map(|c| {
                c.enum_constants
                    .iter()
                    .filter_map(|k| k.body_class.as_ref())
                    .enumerate()
                    .map(|(i, body)| (body.clone(), format!("{}${}", c.binary, i + 1)))
            })
            .collect();
        for (body, binary) in numbered {
            if let Some(cl) = classes.iter_mut().find(|c| c.name == body) {
                cl.binary = binary;
            }
        }
        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> {
        // Set by the enclosing class when this is an inner member class.
        let inner_of = self.inner_of.take();
        // modifiers (`public`, `static`, and the ident-form ones — see
        // [`class_modifier_len`], which also spells `non-sealed`)
        let mut is_sealed = false;
        let mut is_abstract = false;
        loop {
            let n = class_modifier_len(&self.toks, self.pos);
            if n == 0 {
                break;
            }
            is_sealed |=
                n == 1 && matches!(&self.toks[self.pos].kind, Tok::Ident(w) if w == "sealed");
            is_abstract |=
                n == 1 && matches!(&self.toks[self.pos].kind, Tok::Ident(w) if w == "abstract");
            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 (self.local_binary.take(), enclosing) {
            (Some(local), _) => local,
            (None, Some(outer)) => format!("{outer}${name}"),
            (None, None) => name.clone(),
        };
        self.enclosing.push(binary.clone());
        self.enclosing_names.push(name.clone());
        let saved_enum = self.enclosing_enum.clone();
        if is_enum {
            self.enclosing_enum = Some(name.clone());
        }
        // Optional generic type-parameter declaration `<T>`, `<T extends X>`,
        // `<K, V>` — erased, but the names stay in scope for the body so a
        // parameter that shadows a class name is not read as that class.
        let class_generics = self.declare_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();
        let mut super_targs = Vec::new();
        let mut interface_targs: Vec<Vec<String>> = 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);
                    interface_targs.push(self.last_targs.clone());
                } else {
                    super_targs = self.last_targs.clone();
                    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()?);
                interface_targs.push(self.last_targs.clone());
                if self.is(&Tok::Comma) {
                    self.advance();
                } else {
                    break;
                }
            }
        }
        // `permits A, B` — a `sealed` type's list of allowed subtypes, which a
        // `switch` over the type reads to decide whether it is exhaustive.
        let mut permits = Vec::new();
        if matches!(self.peek(), Tok::Ident(w) if w == "permits") {
            self.advance();
            loop {
                permits.push(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() {
                // A member `class` without `static`, in a class, enum, or
                // record body, is *inner*: it holds its enclosing instance.
                // Interface members, and nested records, enums, and
                // interfaces, are implicitly `static` (JLS 8.1.3, 9.5).
                if !is_interface && self.at_inner_class() {
                    self.inner_of = Some(name.clone());
                }
                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()? {
                // Every field of an interface is implicitly `public static
                // final` (JLS 9.3): `interface G { String P = "x"; }` declares a
                // constant, read as `G.P`, as a bare `P` in the interface's own
                // methods, and as a bare `P` in every implementing class.
                if is_static || is_interface {
                    static_declaration(fs, &mut static_fields, &mut static_init);
                } else {
                    instance_declaration(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.enclosing.pop();
        self.enclosing_names.pop();
        self.enclosing_enum = saved_enum;
        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,
            );
        }
        let type_params = self.type_params[self.type_params.len() - class_generics..].to_vec();
        self.undeclare_generics(class_generics);
        classes.push(Class {
            type_params,
            super_targs,
            interface_targs,
            is_sealed,
            is_abstract,
            permits,
            name,
            binary,
            superclass,
            interfaces,
            is_interface,
            is_enum,
            is_record,
            enum_constants,
            fields,
            static_fields,
            static_init,
            inst_init,
            ctors,
            methods: inst_methods,
            captures: Vec::new(),
            line,
        });
        if let (Some(outer), Some(cl)) = (inner_of, classes.last_mut()) {
            let this0 = Param {
                targs: Vec::new(),
                super_slots: Vec::new(),
                wildcard: false,
                ty: outer,
                name: OUTER_THIS.to_string(),
                varargs: false,
                is_final: false,
            };
            attach_captures(cl, vec![this0], 0);
        }
        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(fs, &mut static_fields, &mut static_init);
                } else {
                    instance_declaration(fs, &mut fields, &mut inst_init);
                }
            } else if self.is(&Tok::LBrace) {
                // An instance initializer: the body is an anonymous class, so
                // it runs after the enum's constructor with the field
                // initializers, in textual order (JLS 8.9.1, 15.9.5.1).
                self.advance();
                inst_init.extend(self.block()?);
            } 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 {
            type_params: Vec::new(),
            super_targs: Vec::new(),
            interface_targs: Vec::new(),
            is_sealed: false,
            is_abstract: false,
            permits: Vec::new(),
            // 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,
            captures: Vec::new(),
            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.
/// Give `cl` its captured values: a `final` field for each capture from
/// `own_from` on (the earlier ones are fields of a capturing superclass
/// already), and every capture as a trailing parameter of every constructor —
/// synthesizing the no-argument one a class that declares none would have.
/// A local class captures enclosing locals (`Parser::capture_locals`); an
/// inner member class captures its enclosing instance as [`OUTER_THIS`].
fn attach_captures(cl: &mut Class, captures: Vec<Param>, own_from: usize) {
    for c in &captures[own_from..] {
        cl.fields.push(FieldDecl {
            targs: Vec::new(),
            super_slots: Vec::new(),
            wildcard: false,
            ty: c.ty.clone(),
            name: c.name.clone(),
            is_final: true,
            init: None,
            line: cl.line,
            has_init: false,
            init_pos: 0,
        });
    }
    if cl.ctors.is_empty() {
        cl.ctors.push(Ctor {
            params: Vec::new(),
            body: Vec::new(),
            line: cl.line,
            end_line: cl.line,
            implicit: true,
        });
    }
    for ctor in &mut cl.ctors {
        ctor.params.extend(captures.iter().cloned());
    }
    cl.captures.extend(captures);
}

/// The index one past the last token of the block enclosing `from`: the
/// first `}` that closes a brace opened before `from`, or the end of input.
/// `e`, an anonymous class javars lowered to something else (a closure, or
/// the collection a double-brace initializer fills), marked with the binary
/// name `javac` gives the class: the compiler lowers `e` and records the name
/// for `getClass()` ([`crate::host::JCLASS_NAME`]).
fn anonymous_named(e: Expr, binary: String, line: u32) -> Expr {
    Expr::Call {
        name: ANON_CLASS_CALL.to_string(),
        args: vec![e, Expr::Str(binary)],
        line,
    }
}

/// The internal call `anonymous_named` builds; `#` keeps it out of reach of
/// a Java identifier.
pub const ANON_CLASS_CALL: &str = "#anon_class";

fn block_end(toks: &[Token], from: usize) -> usize {
    let mut depth = 0usize;
    for (k, t) in toks.iter().enumerate().skip(from) {
        match t.kind {
            Tok::LBrace => depth += 1,
            Tok::RBrace if depth == 0 => return k,
            Tok::RBrace => depth -= 1,
            _ => {}
        }
    }
    toks.len()
}

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" | "private" | "protected" | "strictfp"
    ))
}

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 {
            targs: c.targs.clone(),
            super_slots: c.super_slots.clone(),
            wildcard: c.wildcard,
            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,
            has_init: false,
            init_pos: 0,
        });
    }
    // 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,
            end_line: line,
            implicit: true,
        }),
    }
    // 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 {
            ret_targs: c.targs.clone(),
            ret_super_slots: c.super_slots.clone(),
            ret_wildcard: c.wildcard,
            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,
            access: Access::Public,
            line,
        });
    }
    // `toString()` → `Point[x=1, y=2]`.
    if !methods
        .iter()
        .any(|m| m.name == "toString" && m.params.is_empty())
    {
        // Java renders the *simple* name; a local record is declared under its
        // binary name (`T$1Point`), so the prefix and ordinal are dropped.
        let simple = name.rsplit('$').next().unwrap_or(name);
        let simple = simple.trim_start_matches(|c: char| c.is_ascii_digit());
        let mut text = Expr::Str(format!("{simple}["));
        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 {
            ret_targs: Vec::new(),
            ret_super_slots: Vec::new(),
            ret_wildcard: false,
            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,
            access: Access::Public,
            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 {
                targs: Vec::new(),
                wildcard: false,
                super_slots: Vec::new(),
                ty: "int".to_string(),
                name: acc.to_string(),
                init: Some(Expr::Int(0)),
                is_final: false,
            },
        )];
        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 {
            ret_targs: Vec::new(),
            ret_super_slots: Vec::new(),
            ret_wildcard: false,
            name: "hashCode".to_string(),
            owner: name.to_string(),
            params: Vec::new(),
            ret: "int".to_string(),
            body,
            is_abstract: false,
            access: Access::Public,
            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 {
            ret_targs: Vec::new(),
            ret_super_slots: Vec::new(),
            ret_wildcard: false,
            name: "equals".to_string(),
            owner: name.to_string(),
            params: vec![Param {
                targs: Vec::new(),
                super_slots: Vec::new(),
                wildcard: false,
                ty: "Object".to_string(),
                name: other.to_string(),
                varargs: false,
                is_final: 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,
            access: Access::Public,
            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(decls: Vec<FieldDecl>, fields: &mut Vec<FieldDecl>, init: &mut Vec<Stmt>) {
    for f in decls {
        let init_pos = init.len();
        if let Some(value) = f.init.clone() {
            init.push(Stmt::new(
                f.line,
                StmtKind::Assign {
                    name: f.name.clone(),
                    op: AssignOp::Assign,
                    value,
                },
            ));
        }
        fields.push(FieldDecl {
            init: None,
            init_pos,
            ..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(decls: Vec<FieldDecl>, fields: &mut Vec<FieldDecl>, init: &mut Vec<Stmt>) {
    for f in decls {
        let init_pos = init.len();
        if let Some(value) = f.init.clone() {
            init.push(Stmt::new(
                f.line,
                StmtKind::FieldAssign {
                    recv: Expr::This,
                    name: f.name.clone(),
                    op: AssignOp::Assign,
                    value,
                },
            ));
        }
        fields.push(FieldDecl {
            init: None,
            init_pos,
            ..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 {
        targs: Vec::new(),
        super_slots: Vec::new(),
        wildcard: false,
        ty: "String".to_string(),
        name: ENUM_NAME.to_string(),
        init: None,
        is_final: false,
        line,
        has_init: false,
        init_pos: 0,
    });
    fields.push(FieldDecl {
        targs: Vec::new(),
        super_slots: Vec::new(),
        wildcard: false,
        ty: "int".to_string(),
        name: ENUM_ORDINAL.to_string(),
        init: None,
        is_final: false,
        line,
        has_init: false,
        init_pos: 0,
    });
    let reader = |method: &str, field: &str, ret: &str| Method {
        ret_targs: Vec::new(),
        ret_super_slots: Vec::new(),
        ret_wildcard: false,
        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,
        access: Access::Public,
        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.getDeclaringClass()` is the enum's own class even for a constant
    // with a body, whose runtime class is the anonymous subclass.
    if !methods
        .iter()
        .any(|m| m.name == "getDeclaringClass" && m.params.is_empty())
    {
        methods.push(Method {
            ret_targs: Vec::new(),
            ret_super_slots: Vec::new(),
            ret_wildcard: false,
            name: "getDeclaringClass".to_string(),
            owner: owner.to_string(),
            params: Vec::new(),
            ret: "Class".to_string(),
            body: vec![Stmt::new(
                line,
                StmtKind::Return(Some(Expr::ClassLit(owner.to_string()))),
            )],
            is_abstract: false,
            access: Access::Public,
            line,
        });
    }
    // `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 {
            ret_targs: Vec::new(),
            ret_super_slots: Vec::new(),
            ret_wildcard: false,
            name: "compareTo".to_string(),
            owner: owner.to_string(),
            params: vec![Param {
                targs: Vec::new(),
                super_slots: Vec::new(),
                wildcard: false,
                ty: owner.to_string(),
                name: "other".to_string(),
                varargs: false,
                is_final: 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,
            access: Access::Public,
            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 {
            ret_targs: Vec::new(),
            ret_super_slots: Vec::new(),
            ret_wildcard: false,
            name: "equals".to_string(),
            owner: owner.to_string(),
            params: vec![Param {
                targs: Vec::new(),
                super_slots: Vec::new(),
                wildcard: false,
                ty: "Object".to_string(),
                name: "other".to_string(),
                varargs: false,
                is_final: 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,
            access: Access::Public,
            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 `<`.
    /// Parse a *declaration's* `<…>` and record the parameter names it binds,
    /// where [`Parser::skip_generics`] parses a *use's* type arguments and keeps
    /// nothing. Returns how many names were pushed, for the caller to pop once
    /// the declaration's body is parsed.
    ///
    /// The names are the identifiers at nesting depth 1 that open the list or
    /// follow a top-level comma — `<T>`, `<K, V>`, `<T extends Comparable<T>>`.
    fn declare_generics(&mut self) -> usize {
        if !self.is(&Tok::Lt) {
            return 0;
        }
        let start = self.pos;
        self.skip_generics();
        let mut names = Vec::new();
        let mut depth = 0i32;
        let mut expect_name = false;
        for t in &self.toks[start..self.pos] {
            match &t.kind {
                Tok::Lt => {
                    depth += 1;
                    expect_name = depth == 1;
                }
                k if k.generic_closers() > 0 => {
                    depth -= k.generic_closers();
                    expect_name = false;
                }
                Tok::Comma if depth == 1 => expect_name = true,
                Tok::Ident(w) if expect_name && depth == 1 => {
                    names.push(w.clone());
                    expect_name = false;
                }
                _ => expect_name = false,
            }
        }
        let n = names.len();
        self.type_params.extend(names);
        n
    }

    /// Drop the `n` most recently declared type-parameter names.
    fn undeclare_generics(&mut self, n: usize) {
        self.type_params.truncate(self.type_params.len() - n);
    }

    /// Parse a *use's* type-argument group `<…>` (as [`Parser::skip_generics`]
    /// does) and answer its top-level arguments in
    /// [`crate::ast::generic_parts`] form. A name bound as a type parameter
    /// erases to `Object`, the erasure `javac` gives it; an annotation on an
    /// argument is dropped. Empty when the cursor is not on `<`.
    fn type_args(&mut self) -> Vec<String> {
        if !self.is(&Tok::Lt) {
            self.last_targs_wildcard = false;
            self.last_super_slots.clear();
            return Vec::new();
        }
        let start = self.pos;
        self.skip_generics();
        let mut text = String::new();
        let mut toks = self.toks[start..self.pos].iter().peekable();
        while let Some(t) = toks.next() {
            match &t.kind {
                Tok::At => {
                    toks.next();
                }
                Tok::Ident(w) => {
                    if text.ends_with(|c: char| c.is_alphanumeric() || c == '_' || c == '?') {
                        text.push(' ');
                    }
                    // A type variable is kept as `#T`, which a use site
                    // substitutes from its receiver's type arguments and
                    // otherwise reads as its erasure, `Object`.
                    if self.type_params.contains(w) && !text.ends_with('.') {
                        text.push('#');
                    }
                    text.push_str(w);
                }
                Tok::Lt => text.push('<'),
                Tok::Comma => text.push(','),
                Tok::Question => text.push('?'),
                Tok::Dot => text.push('.'),
                Tok::LBracket => text.push('['),
                Tok::RBracket => text.push(']'),
                k => {
                    for _ in 0..k.generic_closers() {
                        text.push('>');
                    }
                }
            }
        }
        let (_, args) = crate::ast::generic_parts(&format!("T{text}"));
        self.last_targs_wildcard = args.iter().any(|a| a.trim_start().starts_with('?'));
        self.last_super_slots = (0..args.len())
            .filter(|&i| {
                args[i]
                    .trim_start()
                    .strip_prefix('?')
                    .is_some_and(|r| r.trim_start().starts_with("super"))
            })
            .collect();
        args.iter()
            .map(|a| crate::ast::normalize_type_arg(a))
            .collect()
    }

    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 `class` declaration whose modifiers do not
    /// include `static`.
    fn at_inner_class(&self) -> bool {
        let mut j = self.pos;
        loop {
            let n = class_modifier_len(&self.toks, j);
            if n == 0 {
                break;
            }
            if matches!(self.toks[j].kind, Tok::Static) {
                return false;
            }
            j += n;
        }
        matches!(self.toks[j].kind, Tok::Class)
    }

    /// Parse a local type declaration and hoist it (see `statement_kind`).
    fn local_type_decl(&mut self) -> Result<String, String> {
        let mut j = self.pos;
        loop {
            let n = class_modifier_len(&self.toks, j);
            if n == 0 {
                break;
            }
            // JLS 14.3: a local class or interface takes no access modifier and
            // no `static` (a local record, enum or interface is implicitly
            // static), and JLS 8.1.1.2 forbids `sealed`/`non-sealed` on one.
            let word = match &self.toks[j].kind {
                Tok::Public => Some("public"),
                Tok::Static => Some("static"),
                Tok::Ident(w) if n == 3 => (w == "non").then_some("non-sealed"),
                Tok::Ident(w) => ["private", "protected", "sealed"]
                    .into_iter()
                    .find(|m| m == w),
                _ => None,
            };
            if let Some(m) = word {
                return Err(format!(
                    "javars: modifier `{m}` not allowed on a local class or interface (line {})",
                    self.toks[j].line
                ));
            }
            j += n;
        }
        let name = match &self.toks[j + 1].kind {
            Tok::Ident(n) => n.clone(),
            other => return Err(format!("javars: expected a type name but found {other}")),
        };
        let outer = self.enclosing.last().cloned().unwrap_or_default();
        let top = outer.split('$').next().unwrap_or_default().to_string();
        let n = self.local_counts.entry((top, name.clone())).or_insert(0);
        *n += 1;
        let binary = format!("{outer}${n}{name}");
        // javars resolves types in one flat namespace, so the local type is
        // declared under its binary name and every mention of the simple name
        // from the declaration to the end of the enclosing block -- its scope,
        // JLS 6.3 -- is renamed to match. Two methods may then each declare a
        // local `P` (`T$1P`, `T$2P`), and a local type may shadow a member or
        // top-level type of the same name. A name after `.` is a member
        // selection, never the local type, so it is left alone.
        let end = block_end(&self.toks, self.pos);
        for k in self.pos..end {
            let after_dot = k > 0 && matches!(self.toks[k - 1].kind, Tok::Dot);
            if !after_dot && matches!(&self.toks[k].kind, Tok::Ident(w) if *w == name) {
                self.toks[k].kind = Tok::Ident(binary.clone());
            }
        }
        self.local_binary = Some(binary);
        let (mut entry, mut methods, mut classes) = (None, Vec::new(), Vec::new());
        let start = self.pos;
        // A local class in an instance context is inner (JLS 8.1.3): it holds
        // the instance of the class whose method declares it.
        if !self.in_static && self.at_inner_class() {
            self.inner_of = self.enclosing_names.last().cloned();
        }
        self.parse_class(None, &mut entry, &mut methods, &mut classes)?;
        // `parse_class` pushes the declaration itself after any member types.
        if let Some(cl) = classes.last_mut() {
            self.capture_locals(cl, start);
        }
        let declared = classes.last().map(|cl| cl.name.clone()).unwrap_or_default();
        self.local_methods.append(&mut methods);
        self.local_classes.append(&mut classes);
        Ok(declared)
    }

    /// Give a local class the enclosing locals its body reads (JLS 8.1.3).
    ///
    /// javac's lowering, which javars follows: each captured local becomes a
    /// field of the class and a trailing parameter of every constructor, and
    /// every `new`, `this(…)`, and `super(…)` naming the class passes the
    /// value along (`Compiler::with_captures`). The name the body reads then
    /// resolves to that field. Java requires a captured local to be
    /// effectively final, so the copy taken at construction is the value.
    ///
    /// A local is captured when its name appears in the class's tokens other
    /// than as a member selection (`x.name`) or a call (`name(…)`), and the
    /// class declares no field of that name — a field shadows the local. A
    /// superclass that is itself a capturing local class passes its captures
    /// down. Records, enums, and interfaces are implicitly `static` and never
    /// capture.
    fn capture_locals(&mut self, cl: &mut Class, start: usize) {
        if cl.is_record || cl.is_enum || cl.is_interface {
            return;
        }
        let mut read = std::collections::HashSet::new();
        for k in start..self.pos {
            if let Tok::Ident(w) = &self.toks[k].kind {
                let after_dot = matches!(self.toks[k - 1].kind, Tok::Dot);
                let called = matches!(self.toks[k + 1].kind, Tok::LParen);
                if !after_dot && !called {
                    read.insert(w.as_str());
                }
            }
        }
        // An inner local class already holds its enclosing instance.
        let held = |caps: &[Param], name: &str| caps.iter().any(|c| c.name == name);
        let inherited: Vec<Param> = cl
            .superclass
            .as_ref()
            .and_then(|s| self.local_captures.get(s))
            .into_iter()
            .flatten()
            .filter(|c| !held(&cl.captures, &c.name))
            .cloned()
            .collect();
        let mut captures = inherited.clone();
        for (i, (name, ty)) in self.scope.iter().enumerate() {
            let shadowed = self.scope[i + 1..].iter().any(|(n, _)| n == name);
            if shadowed
                || !read.contains(name.as_str())
                || cl.fields.iter().any(|f| f.name == *name)
                || held(&captures, name)
                || held(&cl.captures, name)
            {
                continue;
            }
            captures.push(Param {
                targs: Vec::new(),
                super_slots: Vec::new(),
                wildcard: false,
                ty: ty.clone(),
                name: name.clone(),
                varargs: false,
                is_final: false,
            });
        }
        if !captures.is_empty() {
            attach_captures(cl, captures, inherited.len());
        }
        if !cl.captures.is_empty() {
            self.local_captures
                .insert(cl.name.clone(), cl.captures.clone());
        }
    }

    /// 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,
            end_line: self.toks[self.pos - 1].line,
            implicit: false,
        }))
    }

    /// 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();
        }
        // A generic constructor (`<T> Main(T t)`, JLS 8.8.4) binds its own
        // type parameters for the signature and body.
        let generics = self.declare_generics();
        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;
            self.undeclare_generics(generics);
            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.body_with_params(&params, false)?;
        self.undeclare_generics(generics);
        Ok(Some(Ctor {
            params,
            body,
            line,
            end_line: self.toks[self.pos - 1].line,
            implicit: false,
        }))
    }

    /// 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()?;
        let targs = self.last_targs.clone();
        let super_slots = self.last_super_slots.clone();
        let wildcard = self.last_targs_wildcard;
        // 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,
                targs: targs.clone(),
                super_slots: super_slots.clone(),
                wildcard,
                name,
                has_init: init.is_some(),
                init,
                is_final: saw_final,
                line,
                init_pos: 0,
            });
            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;
        let mut access = Access::Package;
        // 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")
        {
            match self.peek() {
                Tok::Static => saw_static = true,
                Tok::Public => access = Access::Public,
                Tok::Ident(w) if w == "private" => access = Access::Private,
                Tok::Ident(w) if w == "protected" => access = Access::Protected,
                _ => {}
            }
            self.advance();
        }
        // Optional generic method type parameters `<T> T id(T x)` — erased, with
        // the names kept in scope for the signature and body.
        let method_generics = self.declare_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;
            self.undeclare_generics(method_generics);
            return Ok(None);
        }
        let line = self.line();
        let ret = self.type_name()?;
        let ret_targs = self.last_targs.clone();
        let ret_super_slots = self.last_super_slots.clone();
        let ret_wildcard = self.last_targs_wildcard;
        // `<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;
                self.undeclare_generics(method_generics);
                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.body_with_params(&params, saw_static)?, false)
        };
        self.undeclare_generics(method_generics);
        Ok(Some((
            Method {
                name,
                owner: owner.to_string(),
                params,
                ret,
                ret_targs,
                ret_super_slots,
                ret_wildcard,
                body,
                is_abstract,
                access,
                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 {
            // `final` on a formal parameter only forbids assigning it.
            let is_final = matches!(self.peek(), Tok::Ident(w) if w == "final");
            if is_final {
                self.advance();
            }
            let mut ty = self.type_name()?;
            let targs = self.last_targs.clone();
            let super_slots = self.last_super_slots.clone();
            let wildcard = self.last_targs_wildcard;
            // 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)?;
            // A varargs parameter is an array, whose members see no type
            // arguments.
            let targs = if varargs { Vec::new() } else { targs };
            out.push(Param {
                ty,
                targs,
                super_slots: if varargs { Vec::new() } else { super_slots },
                wildcard: wildcard && !varargs,
                name,
                varargs,
                is_final,
            });
            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()?;
        // Two kinds of qualifier lead to a type name, and they are told apart by
        // which segment is capitalised:
        //
        //   `java.util.List xs`  — a *package* qualifier, lowercase segments
        //   `T.Point p`          — an *enclosing class*, so the next segment is
        //                          itself a type name and starts uppercase
        //
        // Only the last segment is kept either way: javars flattens a nested
        // class to its simple name, which is the name `new Point(…)` already
        // uses inside the same file. Requiring the *next* segment to be
        // capitalised is what keeps `System.out.println(x)` an expression —
        // `out` is a field, not a nested type.
        while self.is(&Tok::Dot)
            && matches!(&self.toks[self.pos + 1].kind,
                Tok::Ident(n) if ty.starts_with(|c: char| c.is_lowercase())
                    || n.starts_with(|c: char| c.is_uppercase()))
        {
            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()?;
        // A name bound as a type parameter erases to `Object`, not to itself —
        // see [`Parser::type_params`]. Its one "type argument" is the variable
        // itself, `#T`, which is how a declaration records that its type is
        // one (see [`crate::ast::StmtKind::Local::targs`]).
        let tvar = self.type_params.contains(&ty).then(|| format!("#{ty}"));
        if tvar.is_some() {
            ty = "Object".to_string();
        }
        // 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 from
        // the type itself, but kept beside it for a declaration to record. An
        // array of a generic type keeps none: its own members never see them.
        self.last_targs = self.type_args();
        if let Some(t) = tvar {
            self.last_targs = vec![t];
        }
        while self.is(&Tok::LBracket) {
            self.advance();
            self.eat(&Tok::RBracket)?;
            ty.push_str("[]");
            self.last_targs.clear();
        }
        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)?;
        self.skip_throws()?;
        self.eat(&Tok::LBrace)?;
        let body = self.body_with_params(&params, true)?;
        let param = params.into_iter().next().map(|p| p.name);
        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 mark = self.scope.len();
        let mut out = Vec::new();
        while !self.is(&Tok::RBrace) && !self.is(&Tok::Eof) {
            out.push(self.statement()?);
        }
        self.scope.truncate(mark);
        self.eat(&Tok::RBrace)?;
        Ok(out)
    }

    /// Parse a method or constructor body (the cursor just past its `{`) with
    /// the formal parameters in [`Parser::scope`] for its duration.
    fn body_with_params(&mut self, params: &[Param], is_static: bool) -> Result<Vec<Stmt>, String> {
        let mark = self.scope.len();
        let outer_static = std::mem::replace(&mut self.in_static, is_static);
        self.scope
            .extend(params.iter().map(|p| (p.name.clone(), p.ty.clone())));
        let body = self.block();
        self.scope.truncate(mark);
        self.in_static = outer_static;
        body
    }

    /// 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();
        // A declaration adds its names to the enclosing block; every other
        // statement's own declarations (a `for` init, a caught exception) end
        // with it.
        let mark = self.scope.len();
        let kind = self.statement_kind()?;
        if !matches!(kind, StmtKind::Local { .. } | StmtKind::Locals(_)) {
            self.scope.truncate(mark);
        }
        Ok(Stmt::new(line, kind))
    }

    fn statement_kind(&mut self) -> Result<StmtKind, String> {
        // A local `class`, `record`, `enum`, or `interface` (JLS 14.3). Records,
        // enums, and interfaces declared in a body are implicitly `static`, so
        // hoisting one to the program's type list changes nothing it can see;
        // a local class that reads an enclosing local is refused where that
        // name fails to resolve rather than capturing it. The type keeps
        // `javac`'s binary name, `Outer$1Name`.
        if self.at_nested_class() {
            let class = self.local_type_decl()?;
            return Ok(StmtKind::LocalClass(class));
        }
        // 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));
                }
                // `assert cond;` / `assert cond : detail;` (JLS 14.10). The
                // reference launcher runs with assertions disabled unless `-ea`
                // is given, and a disabled assertion evaluates *neither*
                // expression, so the statement compiles to nothing; the flow
                // pass still reads it (see [`StmtKind::Assert`]).
                "assert" => {
                    self.advance();
                    let cond = self.expression()?;
                    let detail = if self.is(&Tok::Colon) {
                        self.advance();
                        Some(self.expression()?)
                    } else {
                        None
                    };
                    self.eat(&Tok::Semi)?;
                    return Ok(StmtKind::Assert { cond, detail });
                }
                "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() {
            let is_final = matches!(self.peek(), Tok::Ident(w) if w == "final");
            if is_final {
                self.advance();
            }
            let base_ty = self.type_name()?;
            let targs = self.last_targs.clone();
            let wildcard = self.last_targs_wildcard;
            let super_slots = self.last_super_slots.clone();
            // 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
                };
                self.scope.push((name.clone(), ty.clone()));
                decls.push(Stmt::new(
                    line,
                    StmtKind::Local {
                        ty,
                        targs: targs.clone(),
                        wildcard,
                        super_slots: super_slots.clone(),
                        name,
                        init,
                        is_final,
                    },
                ));
                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()?;
        // A top-level assignment is a statement, and keeps the statement
        // lowering (which leaves nothing on the stack) rather than the value
        // form's read-back.
        if let Expr::Assign {
            target, op, value, ..
        } = lhs
        {
            if expect_semi {
                self.eat(&Tok::Semi)?;
            }
            return self.make_assign(*target, op, *value);
        }
        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`) or an enclosing
        // class (`T.Point p`), on the same rule [`Parser::simple_type_name`]
        // uses: a lowercase segment is a package and continues, and a segment
        // whose *successor* is capitalised names an enclosing type. An
        // expression like `obj.field = 1` or `Color.RED;` walks the same path
        // and then fails the trailing-identifier test below, so neither is a
        // declaration.
        while matches!(self.toks[j].kind, Tok::Dot)
            && matches!(
                (&self.toks[j - 1].kind, self.toks.get(j + 1).map(|t| &t.kind)),
                (Tok::Ident(w), Some(Tok::Ident(n)))
                    if w.starts_with(|c: char| c.is_lowercase())
                        || n.starts_with(|c: char| c.is_uppercase())
            )
        {
            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, is_final)) = self.try_foreach_header()? {
            let targs = self.last_targs.clone();
            let super_slots = self.last_super_slots.clone();
            let iter = self.expression()?;
            self.eat(&Tok::RParen)?;
            self.scope.push((name.clone(), ty.clone()));
            let body = self.braced_or_single()?;
            return Ok(StmtKind::ForEach {
                ty,
                targs,
                super_slots,
                name,
                is_final,
                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 {
                targs: None,
                class: "NullPointerException".to_string(),
                args: vec![Expr::Str(
                    "Cannot enter synchronized block because the monitor is null".to_string(),
                )],
                outer: None,
                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` on a catch parameter forbids assigning it.
            let is_final = matches!(self.peek(), Tok::Ident(w) if w == "final");
            if is_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 mark = self.scope.len();
            let caught = if types.len() == 1 {
                types[0].clone()
            } else {
                "Exception".to_string()
            };
            self.scope.push((name.clone(), caught));
            let arm_body = self.block()?;
            self.scope.truncate(mark);
            catches.push(CatchArm {
                types,
                name,
                is_final,
                body: arm_body,
            });
        }
        // JLS 14.20: a `finally` clause is what is required, not a non-empty
        // one, so `try { … } finally { }` is a valid statement.
        let has_finally = matches!(self.peek(), Tok::Ident(w) if w == "finally");
        let finally_body = if has_finally {
            self.advance();
            self.eat(&Tok::LBrace)?;
            self.block()?
        } else {
            Vec::new()
        };
        if catches.is_empty() && !has_finally && 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 JLS 14.20.3.1
    /// specifies it as, one level per resource, innermost last declared:
    ///
    /// ```text
    /// final R r = init;
    /// Throwable #primary = null;
    /// try { <inner> }
    /// catch (Throwable #t) { #primary = #t; throw #t; }
    /// finally {
    ///     if (r != null) {
    ///         if (#primary != null) {
    ///             try { r.close(); } catch (Throwable #s) { #primary.addSuppressed(#s); }
    ///         } else {
    ///             r.close();
    ///         }
    ///     }
    /// }
    /// ```
    ///
    /// So resources close in reverse declaration order, before any
    /// `catch`/`finally` of the outer statement runs, and an exception a
    /// `close` throws while another is already propagating is recorded on that
    /// one rather than replacing it. The synthetic names contain `#`, which no
    /// identifier javars lexes from source can.
    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 line = r.line;
            let primary = format!("#twr_primary#{}", r.name);
            let thrown = format!("#twr_thrown#{}", r.name);
            let suppressed = format!("#twr_suppressed#{}", r.name);
            let var = |n: &str| Expr::Var(n.to_string());
            let not_null = |n: &str| Expr::Binary {
                op: BinOp::Ne,
                lhs: Box::new(var(n)),
                rhs: Box::new(var("null")),
            };
            let close = || {
                Stmt::new(
                    line,
                    StmtKind::Expr(Expr::MethodCall {
                        recv: Box::new(var(&r.name)),
                        method: "close".to_string(),
                        args: Vec::new(),
                        line,
                    }),
                )
            };
            let close_suppressing = Stmt::new(
                line,
                StmtKind::Try {
                    body: vec![close()],
                    catches: vec![CatchArm {
                        types: vec!["Throwable".to_string()],
                        name: suppressed.clone(),
                        is_final: false,
                        body: vec![Stmt::new(
                            line,
                            StmtKind::Expr(Expr::MethodCall {
                                recv: Box::new(var(&primary)),
                                method: "addSuppressed".to_string(),
                                args: vec![var(&suppressed)],
                                line,
                            }),
                        )],
                    }],
                    finally_body: Vec::new(),
                },
            );
            let finally_close = Stmt::new(
                line,
                StmtKind::If {
                    cond: not_null(&r.name),
                    then: vec![Stmt::new(
                        line,
                        StmtKind::If {
                            cond: not_null(&primary),
                            then: vec![close_suppressing],
                            els: vec![close()],
                        },
                    )],
                    els: Vec::new(),
                },
            );
            let record_primary = CatchArm {
                types: vec!["Throwable".to_string()],
                name: thrown.clone(),
                is_final: false,
                body: vec![
                    Stmt::new(
                        line,
                        StmtKind::Assign {
                            name: primary.clone(),
                            op: AssignOp::Assign,
                            value: var(&thrown),
                        },
                    ),
                    Stmt::new(line, StmtKind::Throw(var(&thrown))),
                ],
            };
            let primary_decl = Stmt::new(
                line,
                StmtKind::Local {
                    targs: Vec::new(),
                    wildcard: false,
                    super_slots: Vec::new(),
                    ty: "Throwable".to_string(),
                    name: primary.clone(),
                    init: Some(var("null")),
                    is_final: false,
                },
            );
            let guarded = Stmt::new(
                line,
                StmtKind::Try {
                    body: inner,
                    catches: vec![record_primary],
                    finally_body: vec![finally_close],
                },
            );
            inner = match r.decl {
                Some((ty, init)) => vec![
                    Stmt::new(
                        line,
                        StmtKind::Local {
                            targs: Vec::new(),
                            wildcard: false,
                            super_slots: Vec::new(),
                            ty,
                            name: r.name,
                            init: Some(init),
                            // A resource is implicitly `final` (JLS 14.20.3).
                            is_final: true,
                        },
                    ),
                    primary_decl,
                    guarded,
                ],
                None => vec![primary_decl, 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, bool)>, String> {
        if !self.looks_like_decl() {
            return Ok(None);
        }
        let save = self.pos;
        // `for (final String s : xs)` — the modifier is kept for the
        // definite-assignment pass.
        let is_final = matches!(self.peek(), Tok::Ident(w) if w == "final");
        if is_final {
            self.advance();
        }
        let ty = self.type_name()?;
        let name = self.ident()?;
        if self.is(&Tok::Colon) {
            self.advance();
            return Ok(Some((ty, name, is_final)));
        }
        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 int[] ia` — an array type pattern.
            let mut class = class;
            while matches!(self.toks[j].kind, Tok::LBracket)
                && matches!(self.toks.get(j + 1).map(|t| &t.kind), Some(Tok::RBracket))
            {
                class.push_str("[]");
                j += 2;
            }
            // `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),
            });
        }
        // Assignment binds loosest of all and is right-associative, so
        // `a = b = 0` is `a = (b = 0)`. Only an lvalue takes it; anything else
        // leaves the operator for the caller to reject.
        if let Some(op) = assign_op(self.peek()) {
            if matches!(cond, Expr::Var(_) | Expr::Index { .. } | Expr::Field { .. }) {
                let line = self.line();
                self.advance();
                let value = self.expression()?;
                return Ok(Expr::Assign {
                    target: Box::new(cond),
                    op,
                    value: Box::new(value),
                    line,
                });
            }
        }
        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();
                // The type is read the way every other type position reads one,
                // so a qualified name works here too: `o instanceof Map.Entry`
                // flattens to `Entry` and `o instanceof java.util.List` to
                // `List`. `ident()` alone stopped at the first segment and left
                // the `.` for the expression parser, which then reported a
                // missing `)`.
                let mut class = self.simple_type_name()?;
                // `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();
                // `o instanceof int[]` — an array type, answered from the type
                // the array's creation recorded.
                while self.is(&Tok::LBracket)
                    && matches!(self.toks[self.pos + 1].kind, Tok::RBracket)
                {
                    self.advance();
                    self.advance();
                    class.push_str("[]");
                }
                // 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],
                finals: Vec::new(),
                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, mut finals) = (Vec::new(), Vec::new());
        while !self.is(&Tok::RParen) {
            // `final` is a legal modifier on an explicitly-typed parameter.
            let is_final = matches!(self.peek(), Tok::Ident(w) if w == "final");
            if is_final {
                self.advance();
            }
            finals.push(is_final);
            // 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,
            finals,
            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 from the cast's class, so they are stepped
        // over here and read for static typing once this is known to be a cast.
        let lt_at = matches!(at(j), Tok::Lt).then_some(j);
        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;
        let targs = match lt_at {
            Some(p) if !name.ends_with("[]") => {
                self.pos = p;
                self.type_args()
            }
            _ => Vec::new(),
        };
        self.pos = j + 1;
        // JLS 15.16: a reference cast may also apply to a lambda, which gives
        // the lambda its target type (`(Runnable) () -> go()`, `(UnaryOperator<T>)
        // x -> x`). A lambda is not a unary operand, so it is tried first.
        let lambda = if primitive { None } else { self.try_lambda()? };
        let expr = match lambda {
            Some(l) => l,
            None => self.unary()?,
        };
        Ok(Some(Expr::Cast {
            ty: name,
            targs,
            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:
                // `outer` is the enclosing instance the inner class holds.
                if self.is(&Tok::New) {
                    e = match self.new_expr()? {
                        Expr::NewObject {
                            class,
                            args,
                            targs,
                            line,
                            ..
                        } => Expr::NewObject {
                            class,
                            args,
                            targs,
                            outer: Some(Box::new(e)),
                            line,
                        },
                        _ => {
                            return Err(format!(
                                "javars: a qualified `new` of an array or an anonymous class is not modeled (line {line})"
                            ))
                        }
                    };
                    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.
                // `T.class` — the class literal. `class` is a keyword, so it
                // never reaches `ident()`; without this arm the selector
                // reported "expected an identifier but found Class".
                if self.is(&Tok::Class) {
                    self.advance();
                    let name = class_lit_name(&e).ok_or_else(|| {
                        format!("javars: `.class` needs a type name on line {line}")
                    })?;
                    e = Expr::ClassLit(name);
                    continue;
                }
                self.skip_generics();
                let member = self.ident()?;
                if strict_math_alias(&e, &member) {
                    e = Expr::Var("Math".to_string());
                }
                // A package-qualified functional interface or `Collections`
                // (`java.util.Comparator.naturalOrder()`) needs the prelude
                // exactly as its simple name does in the bare-identifier arm.
                if package_rooted(&e)
                    && (crate::prelude::is_functional(&member) || member == "Collections")
                {
                    self.uses_functional = true;
                }
                if self.is(&Tok::LParen) {
                    let args = self.call_args()?;
                    // `Map.Entry.comparingByKey()` / `comparingByValue()`, and
                    // the one-comparator forms: `Map.Entry`'s statics are
                    // comparators, declared with `Comparator`'s in the prelude,
                    // so the receiver becomes `Comparator`.
                    let entry_owner = match &e {
                        Expr::Field { recv, name } => {
                            name == "Entry" && matches!(&**recv, Expr::Var(m) if m == "Map")
                        }
                        Expr::Var(v) => v == "Entry",
                        _ => false,
                    };
                    if entry_owner
                        && matches!(member.as_str(), "comparingByKey" | "comparingByValue")
                    {
                        self.uses_functional = true;
                        e = Expr::Var("Comparator".to_string());
                    }
                    e = Expr::MethodCall {
                        recv: Box::new(e),
                        method: member,
                        args,
                        line,
                    };
                } else if member == "CASE_INSENSITIVE_ORDER"
                    && matches!(&e, Expr::Var(c) if c == "String")
                {
                    // `String.CASE_INSENSITIVE_ORDER` is the comparator whose
                    // `compare` is `compareToIgnoreCase` — the JDK documents
                    // the method as "the same as" this comparator — so it is
                    // that lambda. `#` keeps the parameters out of the user's
                    // namespace.
                    self.uses_functional = true;
                    let (a, b) = ("#ci0".to_string(), "#ci1".to_string());
                    // Cast to its interface, so a member call straight on it
                    // (`String.CASE_INSENSITIVE_ORDER.reversed()`) has the
                    // static type a field read would.
                    let lambda = Expr::Lambda {
                        params: vec![a.clone(), b.clone()],
                        finals: Vec::new(),
                        body: LambdaBody::Expr(Box::new(Expr::MethodCall {
                            recv: Box::new(Expr::Var(a)),
                            method: "compareToIgnoreCase".to_string(),
                            args: vec![Expr::Var(b)],
                            line,
                        })),
                        line,
                    };
                    e = Expr::Cast {
                        ty: "Comparator".to_string(),
                        targs: Vec::new(),
                        expr: Box::new(lambda),
                        line,
                    };
                } else if package_rooted(&e)
                    && member.starts_with(|c: char| c.is_ascii_uppercase())
                    && !(self.is(&Tok::Dot) && matches!(self.toks[self.pos + 1].kind, Tok::Class))
                {
                    // A package-qualified type (`java.util.Comparator`) is its
                    // simple name, which every type is keyed on — so a static
                    // call or constant through it (`java.util.Comparator
                    // .comparing(…)`, `java.lang.Integer.MAX_VALUE`) is typed
                    // and lowered exactly as the unqualified spelling. A class
                    // literal keeps the qualified spelling it names.
                    e = Expr::Var(member);
                } 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;
                // A package-qualified type (`java.util.TreeMap::new`) keys on
                // its simple name, as it does in every other position.
                if let Expr::Field { recv, name } = &e {
                    if package_rooted(recv) {
                        e = Expr::Var(name.clone());
                    }
                }
                if strict_math_alias(&e, &method) {
                    e = Expr::Var("Math".to_string());
                }
                e = Expr::MethodRef {
                    recv: Box::new(e),
                    method,
                    line,
                };
            } else if self.is(&Tok::LBracket)
                && matches!(e, Expr::Var(_))
                && matches!(self.toks[self.pos + 1].kind, Tok::RBracket)
            {
                // `String[]::new` / `int[][]::new` — an array constructor
                // reference. `T[]` is never an expression on its own, so an
                // empty bracket pair after a name can only be this.
                let line = self.line();
                let Expr::Var(base) = &e else { unreachable!() };
                let mut ty = base.clone();
                while self.is(&Tok::LBracket)
                    && matches!(self.toks[self.pos + 1].kind, Tok::RBracket)
                {
                    self.advance();
                    self.advance();
                    ty.push_str("[]");
                }
                // `int[].class` — the array class literal.
                if self.is(&Tok::Dot) && self.toks[self.pos + 1].kind == Tok::Class {
                    self.advance();
                    self.advance();
                    e = Expr::ClassLit(ty);
                    continue;
                }
                self.eat(&Tok::ColonColon)?;
                if !self.is(&Tok::New) {
                    return Err(format!(
                        "javars: expected `new` after `{ty}::` on line {line}"
                    ));
                }
                self.advance();
                self.uses_functional = true;
                e = Expr::MethodRef {
                    recv: Box::new(Expr::Var(ty)),
                    method: "new".to_string(),
                    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()?;
                    // Inside an enum body the two statics every enum has are
                    // callable unqualified; they are the enum's own.
                    if let Some(en) = self.enclosing_enum.clone() {
                        if (name == "values" && args.is_empty())
                            || (name == "valueOf" && args.len() == 1)
                        {
                            return Ok(Expr::MethodCall {
                                recv: Box::new(Expr::Var(en)),
                                method: name,
                                args,
                                line,
                            });
                        }
                    }
                    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;
                }
                // `Collections.reverseOrder` is lowered to `Comparator`'s own, so it
                // needs the prelude that declares `Comparator` too.
                if name == "Collections"
                    && self.is(&Tok::Dot)
                    && matches!(&self.toks[self.pos + 1].kind, Tok::Ident(m) if m == "reverseOrder")
                {
                    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 from the class, kept beside it for static typing.
        let targs = self.is(&Tok::Lt).then(|| self.type_args());
        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, args, line);
        }
        Ok(Expr::NewObject {
            class: ty,
            args,
            targs,
            outer: None,
            line,
        })
    }

    /// Model an anonymous class body `new G(args) { … }`.
    ///
    /// The single-method form of an *interface* desugars to the lambda it
    /// abbreviates: the interface has one abstract method, the body supplies it,
    /// and the enclosing locals it reads are captured the same way. Keeping that
    /// form a lambda is what lets an anonymous `Comparator` or `Runnable` go
    /// everywhere a lambda already goes.
    ///
    /// Every other body is a real class with state — fields, an instance
    /// initializer, two or more methods, an override of an inherited
    /// `toString`/`equals`/`hashCode`, or a *class* supertype — and is lifted to
    /// one by [`Parser::lift_anonymous_class`].
    fn anonymous_class(&mut self, ty: &str, args: Vec<Expr>, line: u32) -> Result<Expr, String> {
        if let Some(e) = self.double_brace(ty, &args, line)? {
            return Ok(e);
        }
        let open = self.pos;
        let class_super = ty == "Object" || !args.is_empty() || self.is_class_name(ty);
        if !class_super {
            // Try the lambda form, restoring every piece of parser state the
            // attempt touched when the body turns out to be a class: a local type
            // declared inside the body renames its tokens and hoists itself.
            let toks = self.toks.clone();
            let (n_classes, n_methods) = (self.local_classes.len(), self.local_methods.len());
            let (counts, captures) = (self.local_counts.clone(), self.local_captures.clone());
            if let Some(lambda) = self.anonymous_lambda(ty, line)? {
                // javac still compiles it to a class, which takes the next
                // `Encloser$N`, and that is what its `getClass()` names.
                let binary = self.next_anonymous_name();
                return Ok(anonymous_named(lambda, binary, line));
            }
            self.toks = toks;
            self.local_classes.truncate(n_classes);
            self.local_methods.truncate(n_methods);
            self.local_counts = counts;
            self.local_captures = captures;
            self.pos = open;
        }
        self.lift_anonymous_class(ty, args, class_super, line)
    }

    /// `new ArrayList<>() {{ add(1); add(2); }}` — the "double brace"
    /// initialization of a JDK collection: an anonymous subclass whose only
    /// member is an instance initializer. javars models a collection as a host
    /// value rather than a class it could subclass, so this is lowered to what
    /// it computes — the collection, built and then filled by the block, in
    /// which a bare call to one of the collection's methods (and `this.m(…)`)
    /// is a call on it, as the inherited member shadows any outer one (JLS
    /// 6.4.1). `None` for any other anonymous body, which keeps the ordinary
    /// path (and its refusal).
    fn double_brace(&mut self, ty: &str, args: &[Expr], line: u32) -> Result<Option<Expr>, String> {
        let members: &[&str] = match ty {
            "ArrayList" | "LinkedList" | "Vector" | "Stack" | "ArrayDeque" | "PriorityQueue" => &[
                "add",
                "addAll",
                "remove",
                "removeAll",
                "retainAll",
                "clear",
                "contains",
                "containsAll",
                "size",
                "isEmpty",
                "get",
                "set",
                "indexOf",
                "lastIndexOf",
                "sort",
                "removeIf",
                "replaceAll",
                "forEach",
                "iterator",
                "stream",
                "toArray",
                "subList",
                "offer",
                "poll",
                "peek",
                "push",
                "pop",
                "addFirst",
                "addLast",
                "removeFirst",
                "removeLast",
                "getFirst",
                "getLast",
                "element",
                "toString",
                "hashCode",
                "equals",
            ],
            "HashSet" | "LinkedHashSet" | "TreeSet" => &[
                "add",
                "addAll",
                "remove",
                "removeAll",
                "retainAll",
                "clear",
                "contains",
                "containsAll",
                "size",
                "isEmpty",
                "removeIf",
                "forEach",
                "iterator",
                "stream",
                "toArray",
                "first",
                "last",
                "toString",
                "hashCode",
                "equals",
            ],
            "HashMap" | "LinkedHashMap" | "TreeMap" => &[
                "put",
                "putAll",
                "putIfAbsent",
                "remove",
                "clear",
                "get",
                "getOrDefault",
                "containsKey",
                "containsValue",
                "size",
                "isEmpty",
                "keySet",
                "values",
                "entrySet",
                "merge",
                "compute",
                "computeIfAbsent",
                "computeIfPresent",
                "replace",
                "replaceAll",
                "forEach",
                "firstKey",
                "lastKey",
                "toString",
                "hashCode",
                "equals",
            ],
            _ => return Ok(None),
        };
        if self.is_class_name(ty) {
            return Ok(None);
        }
        // Exactly `{ { … } }`: one initializer block and nothing else.
        let open = self.pos;
        if !matches!(self.toks.get(open + 1).map(|t| &t.kind), Some(Tok::LBrace)) {
            return Ok(None);
        }
        let inner_end = block_end(&self.toks, open + 2);
        if !matches!(
            self.toks.get(inner_end + 1).map(|t| &t.kind),
            Some(Tok::RBrace)
        ) {
            return Ok(None);
        }
        const SELF: &str = "#dbl";
        self.double_brace_rewrite(open, members, SELF);
        // javac compiles the initializer to an anonymous class `Encloser$N`,
        // which is what the result's `getClass()` names.
        let binary = self.next_anonymous_name();
        Ok(self
            .double_brace_parse(ty, args, line, SELF)?
            .map(|e| anonymous_named(e, binary, line)))
    }

    /// The binary name the next anonymous class in the innermost enclosing
    /// declaration takes — `Encloser$N`, numbered in source order as `javac`
    /// numbers them.
    fn next_anonymous_name(&mut self) -> String {
        let outer = self.enclosing.last().cloned().unwrap_or_default();
        let n = self
            .local_counts
            .entry((outer.clone(), String::new()))
            .or_insert(0);
        *n += 1;
        format!("{outer}${n}")
    }

    /// Retarget the initializer block's bare calls to the collection's own
    /// methods, and its `this.`, at `self_name`. An insertion moves every later
    /// token, so each pass rescans; a rewritten call follows a `.` and is not
    /// matched again.
    fn double_brace_rewrite(&mut self, open: usize, members: &[&str], self_name: &str) {
        loop {
            let inner_end = block_end(&self.toks, open + 2);
            let next = (open + 2..inner_end).find(|&k| {
                let after_dot = k > 0 && matches!(self.toks[k - 1].kind, Tok::Dot);
                let call = matches!(self.toks.get(k + 1).map(|t| &t.kind), Some(Tok::LParen));
                match &self.toks[k].kind {
                    Tok::Ident(w) if w == "this" => {
                        matches!(self.toks.get(k + 1).map(|t| &t.kind), Some(Tok::Dot))
                    }
                    Tok::Ident(w) => !after_dot && call && members.contains(&w.as_str()),
                    _ => false,
                }
            });
            let Some(k) = next else {
                return;
            };
            if matches!(&self.toks[k].kind, Tok::Ident(w) if w == "this") {
                self.toks[k].kind = Tok::Ident(self_name.to_string());
            } else {
                let mut dot = self.toks[k].clone();
                dot.kind = Tok::Dot;
                let mut recv = self.toks[k].clone();
                recv.kind = Tok::Ident(self_name.to_string());
                self.toks.splice(k..k, [recv, dot]);
            }
        }
    }

    /// Parse the rewritten `{ { … } }` into `((Supplier) () -> { var #dbl =
    /// new T<>(args); …; return #dbl; }).get()`.
    fn double_brace_parse(
        &mut self,
        ty: &str,
        args: &[Expr],
        line: u32,
        self_name: &str,
    ) -> Result<Option<Expr>, String> {
        self.eat(&Tok::LBrace)?;
        self.eat(&Tok::LBrace)?;
        self.scope.push((self_name.to_string(), ty.to_string()));
        let mut body = vec![Stmt::new(
            line,
            StmtKind::Local {
                ty: ty.to_string(),
                targs: Vec::new(),
                wildcard: false,
                super_slots: Vec::new(),
                name: self_name.to_string(),
                init: Some(Expr::NewObject {
                    class: ty.to_string(),
                    args: args.to_vec(),
                    targs: Some(Vec::new()),
                    outer: None,
                    line,
                }),
                is_final: false,
            },
        )];
        body.extend(self.block()?);
        self.eat(&Tok::RBrace)?;
        body.push(Stmt::new(
            line,
            StmtKind::Return(Some(Expr::Var(self_name.to_string()))),
        ));
        self.uses_functional = true;
        Ok(Some(Expr::MethodCall {
            recv: Box::new(Expr::Cast {
                ty: "Supplier".to_string(),
                targs: Vec::new(),
                expr: Box::new(Expr::Lambda {
                    params: Vec::new(),
                    finals: Vec::new(),
                    body: LambdaBody::Block(body),
                    line,
                }),
                line,
            }),
            method: "get".to_string(),
            args: Vec::new(),
            line,
        }))
    }

    /// The lambda an anonymous class body abbreviates, or `None` when the body
    /// is not exactly one method supplying an abstract one.
    fn anonymous_lambda(&mut self, ty: &str, line: u32) -> Result<Option<Expr>, String> {
        self.eat(&Tok::LBrace)?;
        let body_start = self.pos;
        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 Ok(None),
            }
        }
        self.eat(&Tok::RBrace)?;
        let Ok([m]) = <[Method; 1]>::try_from(methods) else {
            return Ok(None);
        };
        // `toString`/`equals`/`hashCode` are never the abstract method: what
        // such a body overrides is an *inherited* implementation, so the object
        // is a class. Desugaring one to a lambda made `println(o)` print
        // `<lambda>@e` where Java prints what the override returns.
        if matches!(m.name.as_str(), "toString" | "equals" | "hashCode") {
            return Ok(None);
        }
        // A lambda's `this` is the *enclosing* instance and its name resolves
        // outward, so a body that names its own object — `this`, `super`, or a
        // bare call to the method it is defining (the recursion idiom) — means
        // something else as an anonymous class and has to stay one.
        let body = &self.toks[body_start..self.pos];
        // The method's own declaration (`Type name(`) is in the range too, and
        // is told from a call by the type that precedes it.
        let names_itself = body.iter().enumerate().any(|(i, t)| match &t.kind {
            Tok::Ident(w) if w == "this" || w == "super" => true,
            Tok::Ident(w) => {
                let prev = i.checked_sub(1).map(|p| &body[p].kind);
                *w == m.name
                    && body.get(i + 1).is_some_and(|n| n.kind == Tok::LParen)
                    && !matches!(
                        prev,
                        Some(Tok::Dot | Tok::ColonColon | Tok::Ident(_) | Tok::Gt)
                    )
            }
            _ => false,
        });
        if names_itself {
            return Ok(None);
        }
        self.uses_functional = true;
        Ok(Some(Expr::Lambda {
            params: m.params.iter().map(|p| p.name.clone()).collect(),
            finals: m.params.iter().map(|p| p.is_final).collect(),
            body: LambdaBody::Block(m.body),
            line,
        }))
    }

    /// True when `name` is a class (not an interface) this program can extend:
    /// a declared `class`, `enum`, or `record`, a local class already parsed, or
    /// a modeled throwable.
    fn is_class_name(&self, name: &str) -> bool {
        self.class_names.contains(name)
            || self
                .local_classes
                .iter()
                .any(|c| c.name == name && !c.is_interface)
            || crate::prelude::is_throwable(name)
    }

    /// Lift an anonymous class body to the class javac compiles it to.
    ///
    /// javac's lowering, which javars follows: the class is named
    /// `Encloser$N`, the smallest `N` not yet taken under that encloser
    /// (`T$1`, `T$2`, `T$Inner$1`); it extends the named class or implements
    /// the named interface; its constructor takes the arguments the `new`
    /// supplied and passes them to `super(…)`; and, like a local class, it
    /// captures the enclosing locals its body reads and — in an instance
    /// context — the enclosing instance. The expression is then an ordinary
    /// `new` of that class.
    fn lift_anonymous_class(
        &mut self,
        ty: &str,
        args: Vec<Expr>,
        class_super: bool,
        line: u32,
    ) -> Result<Expr, String> {
        let binary = self.next_anonymous_name();
        let start = self.pos;
        self.eat(&Tok::LBrace)?;
        self.enclosing.push(binary.clone());
        self.enclosing_names.push(binary.clone());
        let outer_static = std::mem::replace(&mut self.in_static, false);
        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();
        let body = (|| {
            while !self.is(&Tok::RBrace) && !self.is(&Tok::Eof) {
                if let Some((m, is_static)) = self.try_any_method(&binary)? {
                    if is_static {
                        return Err(format!(
                            "javars: a `static` method in an anonymous class is not modeled (line {})",
                            m.line
                        ));
                    }
                    methods.push(m);
                } else if let Some((fs, is_static)) = self.try_fields()? {
                    if is_static {
                        static_declaration(fs, &mut static_fields, &mut static_init);
                    } else {
                        instance_declaration(fs, &mut fields, &mut inst_init);
                    }
                } else if self.is(&Tok::LBrace) {
                    // An instance initializer: an anonymous class cannot declare
                    // a constructor, so this is where its setup code goes.
                    self.advance();
                    inst_init.extend(self.block()?);
                } else {
                    return Err(format!(
                        "javars: unsupported member in an anonymous `{ty}` (line {})",
                        self.line()
                    ));
                }
            }
            self.eat(&Tok::RBrace)
        })();
        self.in_static = outer_static;
        self.enclosing.pop();
        self.enclosing_names.pop();
        body?;
        // The constructor javac synthesizes: one parameter per argument, passed
        // straight to `super(…)`. Its parameter types are the superclass
        // constructor's, which `program` copies in once every class is parsed.
        let ctors = if args.is_empty() {
            Vec::new()
        } else {
            let params: Vec<Param> = (0..args.len())
                .map(|i| Param {
                    targs: Vec::new(),
                    super_slots: Vec::new(),
                    wildcard: false,
                    ty: "Object".to_string(),
                    name: format!("x{i}"),
                    varargs: false,
                    is_final: false,
                })
                .collect();
            let call = Expr::Call {
                name: "super".to_string(),
                args: params.iter().map(|p| Expr::Var(p.name.clone())).collect(),
                line,
            };
            vec![Ctor {
                params,
                body: vec![Stmt::new(line, StmtKind::Expr(call))],
                line,
                end_line: line,
                implicit: true,
            }]
        };
        let (superclass, interfaces) = match ty {
            "Object" => (None, Vec::new()),
            _ if class_super => (Some(ty.to_string()), Vec::new()),
            _ => (None, vec![ty.to_string()]),
        };
        let mut cl = Class {
            type_params: Vec::new(),
            super_targs: Vec::new(),
            interface_targs: Vec::new(),
            is_sealed: false,
            is_abstract: false,
            permits: Vec::new(),
            name: binary.clone(),
            binary: binary.clone(),
            superclass,
            interfaces,
            is_interface: false,
            is_enum: false,
            is_record: false,
            enum_constants: Vec::new(),
            fields,
            static_fields,
            static_init,
            inst_init,
            ctors,
            methods,
            captures: Vec::new(),
            line,
        };
        if !self.in_static {
            if let Some(outer) = self.enclosing_names.last().cloned() {
                let this0 = Param {
                    targs: Vec::new(),
                    super_slots: Vec::new(),
                    wildcard: false,
                    ty: outer,
                    name: OUTER_THIS.to_string(),
                    varargs: false,
                    is_final: false,
                };
                attach_captures(&mut cl, vec![this0], 0);
            }
        }
        self.capture_locals(&mut cl, start);
        if !args.is_empty() {
            self.anon_supers.push((binary.clone(), ty.to_string()));
        }
        self.local_classes.push(cl);
        Ok(Expr::NewObject {
            class: binary,
            args,
            targs: None,
            outer: None,
            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 line = self.line();
        let stream = self.ident()?;
        let system_call = |method: &str, args: Vec<Expr>| Expr::MethodCall {
            recv: Box::new(Expr::Var("System".to_string())),
            method: method.to_string(),
            args,
            line,
        };
        let err = match stream.as_str() {
            "out" => false,
            "err" => true,
            // `System.in` is the console input stream a `Scanner` or an
            // `InputStreamReader` wraps. `#` keeps the host's name for it out
            // of the user's namespace.
            "in" => return Ok(system_call("#in", Vec::new())),
            // The other `System` members javars models — `exit`, `arraycopy`,
            // `currentTimeMillis`, `nanoTime`, `lineSeparator` — are statics.
            _ if self.is(&Tok::LParen) => {
                let args = self.call_args()?;
                return Ok(system_call(&stream, args));
            }
            _ => {
                return Err(format!(
                    "javars: `System.{stream}` is not a member javars models (line {})",
                    self.line()
                ))
            }
        };
        // `System.out` as a value — `PrintStream o = System.out;`,
        // `new PrintWriter(System.out)` — rather than as a `print` receiver.
        let stream_value = system_call(if err { "#err" } else { "#out" }, Vec::new());
        if !self.is(&Tok::Dot) {
            return Ok(stream_value);
        }
        self.eat(&Tok::Dot)?;
        let line = self.line();
        let method = self.ident()?;
        // Every other `PrintStream` member (`write`, `append`, `checkError`,
        // `close`) is an ordinary call on the stream value.
        if !matches!(
            method.as_str(),
            "flush" | "printf" | "format" | "println" | "print"
        ) {
            let args = self.call_args()?;
            return Ok(Expr::MethodCall {
                recv: Box::new(stream_value),
                method,
                args,
                line,
            });
        }
        // `flush()` writes out whatever the stream holds; the host's streams
        // hold nothing a later write would not also flush, but a prompt read
        // back by another process must not wait for the program to end.
        if method == "flush" {
            self.eat(&Tok::LParen)?;
            self.eat(&Tok::RParen)?;
            return Ok(system_call(
                if err { "#flushErr" } else { "#flushOut" },
                Vec::new(),
            ));
        }
        // `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,
    })
}

/// The type name a `.class` literal was written on, rebuilt from the expression
/// the selector loop had already parsed.
///
/// `T.class` parses `T` as an identifier and `java.util.List.class` as a chain
/// of field accesses, because nothing before the `class` token says a type is
/// coming — so the name is recovered here rather than predicted.
fn class_lit_name(e: &Expr) -> Option<String> {
    match e {
        Expr::Var(n) => Some(n.clone()),
        Expr::Field { recv, name } => Some(format!("{}.{}", class_lit_name(recv)?, name)),
        _ => None,
    }
}

/// `StrictMath.m` read as `Math.m`, for every member but `sin` and `cos`.
///
/// The JDK's `Math` delegates to `StrictMath` for everything javars models
/// except where HotSpot has an intrinsic, and the intrinsics javars answers
/// from agree with `StrictMath` bit for bit (see `host::static_method`). The
/// two exceptions are `sin` and `cos`, whose `Math` intrinsic is not fdlibm:
/// those keep their own `StrictMath` receiver and are answered by the fdlibm
/// port. Everything else — constants, overload typing, the `Exact` family,
/// method references — then needs no second table.
fn strict_math_alias(e: &Expr, member: &str) -> bool {
    matches!(e, Expr::Var(c) if c == "StrictMath") && !matches!(member, "sin" | "cos")
}

/// Whether `e` is a package qualifier — a field chain rooted at `java` or
/// `javax` (`java.util`) — so a member selected on it names a JDK type.
fn package_rooted(e: &Expr) -> bool {
    match e {
        Expr::Var(v) => v == "java" || v == "javax",
        Expr::Field { recv, .. } => package_rooted(recv),
        _ => false,
    }
}