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
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
//! Lower the Java AST to a `fusevm::Chunk`.
//!
//! There is no bespoke VM or JVM here: statements and expressions emit fusevm
//! ops (`LoadInt`, `Add`, `GetVar`, `JumpIfFalse`, `PrintLn`, …) into a
//! `ChunkBuilder`, and fusevm runs the chunk on its three-tier Cranelift JIT.
//! Java values ride the fusevm value model; the strict numeric hook in
//! `crate::host` supplies string `+` concatenation for the mixed operands the
//! VM's native arithmetic does not compute.
//!
//! `main`'s locals are addressed by name through `GetVar`/`SetVar` (one frame,
//! no lexical scopes); a method body's locals live in call-frame slots. Both
//! stay a direct, readable lowering. `break`/`continue` are backpatched through
//! a loop-context stack, and `throw`/`catch` through a try-context stack plus a
//! pending-exception check after every call (see the exception section below).
use crate::ast::*;
use fusevm::{Chunk, ChunkBuilder, Op, Value};
use std::borrow::Cow;
/// The tables in this file are keyed on identifiers out of the program being
/// compiled — class names, method names, variable names — and on nothing an
/// adversary chooses. So they are hashed with FNV-1a rather than with the
/// standard library's SipHash-1-3, which is built for the case where an
/// attacker picks the keys.
///
/// The difference is not small. Sampling a compile of the 261-program corpus at
/// 3f56addff0 put 29.9% of the phase's self time in SipHash's rounds and
/// another 12.7% in the probing those hashes drive. FNV-1a is a multiply and an
/// xor per byte with no setup, and it spreads short ASCII names well enough
/// that the probe counts do not move.
type HashMap<K, V> = std::collections::HashMap<K, V, NameHash>;
type HashSet<T> = std::collections::HashSet<T, NameHash>;
/// FNV-1a over whatever bytes a key offers. See [`HashMap`].
#[derive(Clone, Copy)]
struct NameHasher(u64);
impl std::hash::Hasher for NameHasher {
fn finish(&self) -> u64 {
self.0
}
fn write(&mut self, bytes: &[u8]) {
let mut h = self.0;
for b in bytes {
h ^= u64::from(*b);
h = h.wrapping_mul(0x0000_0100_0000_01b3);
}
self.0 = h;
}
}
#[derive(Clone, Copy, Default)]
struct NameHash;
impl std::hash::BuildHasher for NameHash {
type Hasher = NameHasher;
fn build_hasher(&self) -> NameHasher {
NameHasher(0xcbf2_9ce4_8422_2325)
}
}
/// The desugar target an inline `rust { ... }` FFI block lowers to (see
/// [`crate::rust_ffi`]).
const RUST_COMPILE: &str = "__rust_compile";
/// `super` reaches the parser as an ordinary identifier, so both of its
/// expression forms — `super.field` and `super.method(args)` — arrive as an
/// [`Expr::Var`] receiver. It is a Java reserved word, so no user declaration
/// can ever produce this name and no shadowing check is needed. (`super(args)`
/// constructor chaining is a separate [`Expr::Call`] shape.)
const SUPER: &str = "super";
/// Java's `null` literal reaches the compiler as a bare name (the lexer has no
/// null token), and reading the never-assigned cell is exactly `Value::Undef` —
/// so it is a name that legitimately resolves to nothing.
const NULL_LITERAL: &str = "null";
/// Member name of the per-class instance-initialization subroutine. Spelled the
/// way the JVM spells the analogous static one so it cannot collide with a Java
/// method name (`<` is not an identifier character).
const INST_INIT: &str = "<instinit>";
/// Where the receiver of a synthesized constructor step comes from. Inside a
/// constructor it is `this`; at a `new` site the freshly allocated instance is
/// still only in a compiler temp, because no frame binds it yet.
#[derive(Clone, Copy)]
enum Recv<'a> {
This,
Temp(&'a str),
}
/// What an update of an lvalue leaves on the stack.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Yield {
/// Nothing — statement position, where the result is discarded.
Nothing,
/// The value the lvalue held before the update (`x++`).
Old,
/// The value it takes (`++x`).
New,
}
/// What a constructor body's first statement is, which decides where its
/// superclass call and its instance initializers go (JLS 8.8.7, 12.5).
#[derive(Clone, Copy, PartialEq, Eq)]
enum CtorChain {
/// Opens with `super(…)`.
Super,
/// Opens with `this(…)` — the delegate runs the chain and the initializers.
This,
/// Opens with neither, so an implicit `super()` is synthesized.
Implicit,
}
/// The static numeric category of an expression, used to reproduce Java's
/// binary numeric promotion. Java's `/` truncates when both operands are
/// integral and divides as floating point when either is `float`/`double`; the
/// fusevm runtime is untyped, so the compiler tracks this statically and emits
/// a truncating division only for `Int` ÷ `Int`.
#[derive(Clone, Copy, PartialEq, Eq)]
enum NumType {
/// An integral type (`int`, `long`, `short`, `byte`, `char`).
Int,
/// A floating-point type (`float`, `double`).
Float,
/// A non-numeric or statically-unknown type (`String`, `boolean`, an
/// untyped `var`, an unresolved variable). Never truncates.
Other,
}
/// Map a declaration-position type name to its numeric category. Returns `None`
/// for `var` and unknown types, whose category is inferred from an initializer.
fn numtype_of_ty(ty: &str) -> Option<NumType> {
match ty {
// The wrappers answer as the primitives they box, because every
// arithmetic operator unboxes them first: `Integer a = f(); a / 2` is
// integral division in Java however opaque `f` is.
"int" | "long" | "short" | "byte" | "char" | "Character" | "Integer" | "Long" | "Short"
| "Byte" => Some(NumType::Int),
"float" | "double" | "Float" | "Double" => Some(NumType::Float),
"boolean" | "String" | "Boolean" => Some(NumType::Other),
_ => None,
}
}
/// Static signature of one user-defined static-method overload: its declared
/// parameter types (for overload resolution + mangling) and the numeric category
/// of its return type (so a call participates in division typing). The raw
/// return-type name is kept for static typing of a call result.
struct MethodSig {
/// The class that declares this overload. Two classes may declare a static
/// of the same name and signature, so the owner is part of both the
/// resolution key (a qualified `C.m()` may only reach `C`'s chain) and the
/// mangled subroutine name (or the two bodies would collide).
owner: String,
param_tys: Vec<String>,
ret: NumType,
ret_name: String,
/// True when the last parameter was declared `T...` — the overload is
/// eligible for Java's variable-arity resolution phase.
varargs: bool,
}
/// A resolved static-method call: the mangled target subroutine name and its
/// return type (numeric category + raw name).
struct StaticResolved {
mangled: String,
/// The class declaring the method, whose initialization its call triggers.
owner: String,
ret: NumType,
ret_name: String,
/// The chosen overload's declared parameter types — the lambda target type
/// for each argument.
param_tys: Vec<String>,
/// `Some(k)` when the call was resolved in the variable-arity phase: the
/// arguments from index `k` on are packed into one array at the call site
/// (see [`Compiler::effective_args`]). `None` is a fixed-arity call, whose
/// arguments pass through untouched.
vararg_from: Option<usize>,
}
/// A resolved instance-method call: the chosen overload's declared parameter
/// types (the virtual-dispatch key and the per-argument lambda target type),
/// its return type, and the variable-arity packing point.
struct InstanceResolved {
param_tys: Vec<String>,
ret_name: String,
ret: NumType,
vararg_from: Option<usize>,
}
/// Compile-time metadata for one user-defined class, resolved with inheritance
/// (fields and methods include those from ancestors). Drives object layout,
/// field-type lookup, and static-type method dispatch.
struct ClassInfo {
/// Direct superclass name (for `super(...)` constructor chaining), if any.
superclass: Option<String>,
/// Direct supertypes (superclass + implemented/extended interfaces), for
/// `instanceof` and virtual-dispatch subtype tests.
supertypes: Vec<String>,
/// Java's *binary* name for this class (`Outer$Nested`), for the two
/// messages that name a type the way the JDK spells it.
binary: String,
/// True when this is an `interface` (not instantiable; a dispatch-only type).
is_interface: bool,
/// True when this is an `enum` — the flag that makes a bare `Color` a type
/// reference rather than a variable, even for `enum Empty { }`.
is_enum: bool,
/// True when this is a `record`. A record pattern reads its components
/// through their accessors, which only a record has, so the lowering asks
/// here before deriving the component list from the fields.
is_record: bool,
/// An `enum`'s constant names in declaration order. Index is the constant's
/// `ordinal()`.
enum_constants: Vec<String>,
/// Every instance field this class has (ancestors first, then own), in
/// initialization order — the sequence the constructor prologue emits.
fields: Vec<FieldInit>,
/// Declared type of every field (own + inherited), for static typing.
field_types: HashMap<String, String>,
/// The storage key of every instance field visible from this class (own +
/// inherited), by name — see [`field_storage_key`]. A name only one class
/// in the chain declares keys by the bare name; a re-declaration that
/// *hides* an ancestor's field keys its own cell, so the two coexist in
/// one instance and the receiver's static type picks between them.
field_keys: HashMap<String, String>,
/// The declared type, with its type arguments, of every field of this
/// class that carries any (own, inherited and `static` alike) — see
/// [`with_targs`].
field_generic: HashMap<String, (String, String)>,
/// The fields among those whose declared type arguments include a
/// wildcard (`List<? extends Number> f`), which a bounds check reads as
/// bounds rather than exact types.
field_wildcard: HashSet<String>,
/// The type variables the declaration binds, see [`crate::ast::Class::type_params`].
type_params: Vec<String>,
/// See [`crate::ast::Class::super_targs`].
super_targs: Vec<String>,
/// See [`crate::ast::Class::is_sealed`]; with `is_abstract` and `permits`,
/// what a `switch` over the type reads to decide exhaustiveness.
is_sealed: bool,
/// An `abstract` class or an interface: it has no instances of its own.
is_abstract: bool,
permits: Vec<String>,
/// The direct interfaces with their type arguments (see
/// [`crate::ast::Class::interface_targs`]).
interfaces: Vec<(String, Vec<String>)>,
/// Declared type of every `static` field visible on this class — its own
/// plus every ancestor's, because Java inherits statics by name. Maps the
/// field name to `(declaring class, declared type)`; the declaring class is
/// what mints the global, so `Sub.count` and `Base.count` name one cell.
static_fields: HashMap<String, (String, String)>,
/// Every method this class can dispatch, keyed by `(name, param_types)` so
/// same-name overloads differing only in parameter type coexist. Interface
/// abstract/`default` methods are folded in first, then the class chain
/// (most-derived wins). An entry whose defining type is an interface abstract
/// method has no subroutine; it is only reached through virtual dispatch to a
/// concrete implementor.
methods: Vec<MethodMeta>,
/// Constructor signatures this class declares (empty ⇒ implicit default
/// ctor). Enables constructor overload resolution by type.
ctors: Vec<CtorSig>,
/// True when this class declares any instance initialization of its own — a
/// field initializer or a bare `{ … }` block. Gates the call to its
/// `<instinit>` subroutine when an instance is built.
has_inst_init: bool,
/// The enclosing locals a local class captures, as `(name, type)`: the
/// trailing constructor arguments every construction of it passes
/// ([`Compiler::with_captures`]).
captures: Vec<(String, String)>,
}
/// One declared constructor's compile-time signature.
#[derive(Clone)]
struct CtorSig {
param_tys: Vec<String>,
/// True when the last parameter was declared `T...` (see [`MethodSig`]).
varargs: bool,
}
/// True when a parameter list ends in a variable-arity parameter (`T... xs`).
/// Java allows it only in last position, so only the last one is consulted.
fn is_varargs(params: &[Param]) -> bool {
params.last().is_some_and(|p| p.varargs)
}
/// The `i`-th parameter type of a variable-arity signature *expanded* to as
/// many positions as asked for: the fixed parameters as declared, then the
/// trailing array's component type repeated. `(String, int[]…)` expands to
/// `String, int, int, …`.
fn expanded_param(ptys: &[String], i: usize) -> &str {
let last = ptys.len().saturating_sub(1);
let p = &ptys[i.min(last)];
if i >= last {
p.strip_suffix("[]").unwrap_or(p)
} else {
p
}
}
/// Why a fixed-arity resolution phase selected nothing.
///
/// The distinction decides whether Java's *third* (variable-arity) phase runs:
/// it is reached only when the first two find nothing **applicable**. An
/// ambiguity among applicable fixed-arity candidates is a compile error in
/// Java, not a reason to widen the search — so it must not fall through, or
/// `f(int,int)`/`f(long,long)` against `f(1,2)` could silently land on a
/// `f(int...)` that Java never considers.
#[derive(Clone, Copy, PartialEq, Eq)]
enum NoPick {
/// No candidate's parameters accept the arguments.
Inapplicable,
/// Several candidates are equally specific.
Ambiguous,
}
/// One dispatchable method's compile-time signature: its name, declared
/// parameter types (for overload resolution and mangling), the class that
/// defines the body (`this` binding), and its declared return type.
#[derive(Clone)]
struct MethodMeta {
name: String,
param_tys: Vec<String>,
defining: String,
ret: String,
/// True for a bodyless interface/abstract method — it has no subroutine and
/// is never itself a concrete virtual-dispatch target.
is_abstract: bool,
/// True when the last parameter was declared `T...` (see [`MethodSig`]).
varargs: bool,
}
/// A field with its declared type and optional initializer, in the order it is
/// initialized (used to seed a fresh instance before the constructor runs).
struct FieldInit {
name: String,
/// The instance-map key this declaration's cell lives under.
key: String,
ty: String,
init: Option<Expr>,
}
/// The lowering scope for a user-defined method body. Locals and parameters
/// live in fusevm call-frame slots (`GetSlot`/`SetSlot`) rather than the shared
/// globals `main` uses, so recursion does not clobber a caller's variables.
struct MethodScope {
/// Local/parameter name → frame slot index (allocated on first mention).
slots: HashMap<String, u16>,
/// Next free slot index. Starts at 1 for an instance method/constructor
/// (slot 0 is reserved for `this`).
next_slot: u16,
/// Declared numeric types of this method's locals/parameters.
types: HashMap<String, NumType>,
/// Declared type name of each local/parameter (raw, e.g. `Point`, `int[]`).
decl_types: HashMap<String, String>,
/// The declared type of each local/parameter *with* its type arguments
/// (`List<Float>`), for the ones that carry any — see [`with_targs`].
decl_generic: HashMap<String, String>,
/// The locals and parameters among those whose type arguments include a
/// wildcard.
decl_wildcard: HashSet<String>,
/// Names actually declared as a local or parameter here — distinguishes a
/// true local from an implicit-`this` field reference.
declared: HashSet<String>,
/// The slot holding `this`, when this frame has one. Slot 0 for an instance
/// method or constructor; a lambda body binds `this` as its last captured
/// upvalue instead, so the slot is not fixed.
this_slot: Option<u16>,
}
impl MethodScope {
/// A static-method scope: slots start at 0, no `this`.
fn new() -> Self {
MethodScope::with_first_slot(0)
}
/// An instance-method/constructor scope: slot 0 is `this`, params start at 1.
fn for_instance() -> Self {
let mut s = MethodScope::with_first_slot(1);
s.this_slot = Some(0);
s
}
fn with_first_slot(first: u16) -> Self {
MethodScope {
slots: HashMap::default(),
next_slot: first,
types: HashMap::default(),
decl_types: HashMap::default(),
decl_generic: HashMap::default(),
decl_wildcard: HashSet::default(),
declared: HashSet::default(),
this_slot: None,
}
}
/// Slot index for `name`, allocating a fresh one on first mention.
fn slot(&mut self, name: &str) -> u16 {
if let Some(&s) = self.slots.get(name) {
return s;
}
let s = self.next_slot;
self.next_slot += 1;
self.slots.insert(name.to_string(), s);
s
}
}
/// What kind of construct a [`BreakScope`] wraps. A `break` may target either a
/// loop or a `switch`; a `continue` targets only a loop.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ScopeKind {
Loop,
Switch,
}
/// One enclosing breakable construct's backpatch targets. Loops and `switch`
/// bodies both catch `break`; only loops catch `continue`. An optional `label`
/// lets `break label;`/`continue label;` target a specific enclosing construct.
struct BreakScope {
kind: ScopeKind,
/// The source label naming this construct (`outer: for …`), if any.
label: Option<String>,
/// `continue` jump op indices, patched to the loop's continue target (the
/// step/condition entry) once it is known. Backpatched — not read eagerly —
/// because a `for` loop's continue target (the update clause) is only known
/// after its body is lowered. Always empty for a `switch` scope.
continue_ops: Vec<usize>,
/// `break` jump op indices, patched to the construct's exit once known.
break_ops: Vec<usize>,
}
impl BreakScope {
fn loop_scope(label: Option<String>) -> Self {
BreakScope {
kind: ScopeKind::Loop,
label,
continue_ops: Vec::new(),
break_ops: Vec::new(),
}
}
fn switch_scope(label: Option<String>) -> Self {
BreakScope {
kind: ScopeKind::Switch,
label,
continue_ops: Vec::new(),
break_ops: Vec::new(),
}
}
}
/// One enclosing `try` block's pending unwind jumps. A `throw` (or a post-call
/// check that finds an exception in flight) lowered *inside* the try body emits
/// a `Jump` and parks its index here; the jumps are patched to the handler once
/// the try body has been laid out. Popped before the `catch` bodies are lowered,
/// so a throw from a handler targets the *enclosing* try — Java's rule.
struct TryScope {
unwind_ops: Vec<usize>,
}
/// One enclosing `finally` block of the *current frame*, innermost last.
///
/// A `return`/`break`/`continue` that leaves the guarded region has to run every
/// `finally` it jumps out of, innermost first, before taking the jump. javars
/// duplicates the block at each exit (as `javac` does since `jsr`/`ret` were
/// dropped), so the exit sites need the source back — hence the body is kept
/// here rather than a code address.
struct FinallyScope {
body: Vec<Stmt>,
/// `Compiler::scopes.len()` when the `try` was entered. A `break`/`continue`
/// targeting scope index `i` must run exactly the finallys entered *inside*
/// that construct — the ones whose depth is greater than `i`.
scope_depth: usize,
/// `Compiler::tries.len()` when the `try` was entered: the handlers this
/// `finally` is *not* covered by. A copy emitted at a jump runs outside its
/// own `try`, so an exception it raises must reach the handler enclosing
/// the whole statement, never the statement's own `catch` arms.
tries_depth: usize,
}
struct Compiler {
b: ChunkBuilder,
/// Every `static final String` whose initializer is a constant expression,
/// by field name — Java's *constant variables* (JLS 4.12.4).
///
/// Java folds a use of one at compile time, so `CONST + ""` is the interned
/// literal `"ab"` rather than a string built at run time. Keyed by the bare
/// name because that is how a constant is written inside its own class,
/// which is where nearly every use of one is.
string_constants: HashMap<String, String>,
/// Every Java `String` literal already in the constant pool, by text.
///
/// Java *interns* string literals: two occurrences of `"ab"` in a program
/// denote one object, which is why `"ab" == "ab"` is `true`. javars gives a
/// `String` its identity through its `Arc`, and `Op::LoadConst` hands back a
/// clone of the pooled value — so one pool entry per distinct text is
/// exactly one interned object per distinct text, and the interning falls
/// out of the pooling rather than needing a runtime table.
literals: HashMap<String, u16>,
/// The stack of enclosing breakable constructs (loops and `switch`es),
/// innermost last. `break`/`continue` backpatch through it.
scopes: Vec<BreakScope>,
/// A pending source label consumed by the next loop/`switch` it prefixes
/// (`outer: for …`). Set by [`StmtKind::Labeled`], taken when the construct
/// pushes its [`BreakScope`].
pending_label: Option<String>,
/// Counter minting unique internal names for `switch` discriminant temps.
switch_counter: u32,
/// A top-level `break`/`return;` (no enclosing loop) jumps to program end.
exit_ops: Vec<usize>,
/// When true, emit a per-statement `CallBuiltin(DBG_LINE)` line marker so the
/// `--dap` debugger can stop on statement lines. Normal runs leave this off
/// and carry zero extra ops.
debug: bool,
/// True when the program contains an inline `rust { ... }` FFI block (a
/// `__rust_compile` call). Only then does an unresolved call name lower to a
/// runtime FFI dispatch instead of a compile error — so non-FFI programs keep
/// their exact "unresolved reference" compile-time diagnostic.
has_ffi: bool,
/// True when any user class supplies a `toString()` body. Only then does a
/// concatenation operand the compiler could not type route through the
/// VM-holding rendering builtin instead of fusevm's `Op::Add` — see
/// [`Compiler::emit_host_stringified`].
has_user_tostring: bool,
/// The classes whose `static` initialization is observable, so it runs on
/// first use (JLS 12.4.1) rather than before `main` — see
/// [`lazy_initialized_classes`].
lazy_init: HashSet<String>,
/// The `static final` fields that are constant variables, as their cells'
/// global names: seeded before `main`, and read without initializing the
/// class that declares them.
const_statics: HashSet<String>,
/// Declared numeric types of `main`'s locals (the global/`main` scope,
/// keyed by name). Method locals live in [`Compiler::scope`] instead.
global_types: HashMap<String, NumType>,
/// The active method scope while lowering a method body; `None` while
/// lowering `main`. Selects slot-based vs. global variable access.
scope: Option<MethodScope>,
/// User-defined static-method overloads, keyed by name — populated before
/// any body is lowered so calls (including forward and recursive ones)
/// resolve. Multiple entries per name are overloads resolved by argument
/// type at the call site.
methods: HashMap<String, Vec<MethodSig>>,
/// Declared type name of each `main`-scope local (parallel to
/// [`Compiler::global_types`] but the raw type string, for class typing).
global_decl_types: HashMap<String, String>,
/// [`MethodScope::decl_generic`] for the `main`-scope locals.
global_decl_generic: HashMap<String, String>,
/// [`MethodScope::decl_wildcard`] for the `main`-scope locals.
global_decl_wildcard: HashSet<String>,
/// Resolved metadata (fields/methods/ctors, inheritance-flattened) for every
/// user class. Keyed by class name; populated before any body is lowered.
classes: HashMap<String, ClassInfo>,
/// The class of `this` while lowering an instance method or constructor;
/// `None` in `main` and in `static` methods.
this_class: Option<String>,
/// The class textually enclosing the code being lowered — the one an
/// unqualified `static` field name resolves against. Unlike
/// [`Compiler::this_class`] it is also set inside a `static` method (to the
/// method's declaring class) and inside `main` (to the entry class).
current_class: Option<String>,
/// Counter minting unique internal temp names (`new`/compound-assign temps).
temp_counter: u32,
/// True when the program uses exceptions ([`Program::uses_exceptions`]).
/// Only then does a call site carry the pending-exception check, so an
/// exception-free program emits byte-identical bytecode to before.
has_exceptions: bool,
/// Enclosing `try` blocks of the *current frame*, innermost last. Empty in a
/// frame with no active try, which makes an unwind a plain "return out of
/// this frame and let the caller's check see it".
tries: Vec<TryScope>,
/// Enclosing `finally` blocks of the current frame, innermost last. A jump
/// that leaves them (`return`/`break`/`continue`) emits their bodies first.
finallys: Vec<FinallyScope>,
/// Lambda bodies queued for emission as subroutines. A lambda literal emits
/// only the closure construction at its site; the body is laid out with the
/// other subroutines, after `main`, so control never falls into it. The queue
/// grows while it drains (a lambda may contain a lambda).
pending_lambdas: Vec<PendingLambda>,
/// Counter minting unique lambda subroutine names (`#lambda#0`).
lambda_counter: u32,
/// The functional-interface type the expression being lowered is assigned
/// to, when one is known — a local's declared type, a parameter's type, a
/// method's return type. A lambda literal consumes it to type its own
/// parameters from the interface's single abstract method, which is how
/// `Calc c = x -> 100 / x;` gets Java's integral division inside the body.
lambda_target: Option<String>,
/// The return type a lambda literal takes when its context names no
/// functional interface but the JDK method it is passed to fixes the
/// single abstract method's result as a *reference* (`Stream.map`,
/// `IntStream.mapToObj`, …). Only the return is known there, so the
/// parameters stay untyped; what the hint buys is the boxing conversion on
/// the result, which is what turns a `char` body into a `Character`.
lambda_ret_hint: Option<String>,
/// The generic type a lambda literal is being assigned to, when the
/// declaration names its type arguments (`Function<Integer, Integer>`) —
/// what substitutes the `java.util.function` interface's erased `Object`
/// parameters and result (see [`functional_type_arg_slots`]).
lambda_generic: Option<String>,
/// The generic target (`Comparable<String>`) of the expression about to be
/// lowered by [`Compiler::expr_targeted`], which takes it: only that one
/// expression's bounds check reads it.
pending_target_generic: Option<String>,
/// Every user method by declaring class: name, parameter types and access
/// — what [`Compiler::check_private_access`] reads.
method_access: HashMap<String, Vec<(String, Vec<String>, Access)>>,
/// The `static` methods of user interfaces, as `(interface, name)`.
interface_statics: HashSet<(String, String)>,
/// Whether [`Compiler::pending_target_generic`] was written with a
/// wildcard argument, so its arguments are bounds rather than exact.
target_wildcard: Option<bool>,
/// The parameter types, with type arguments, of a lambda literal passed to
/// a JDK generic method whose receiver's type arguments are known —
/// `li.replaceAll(x -> x * 2)` on a `List<Integer>` takes an `Integer`.
/// See [`Compiler::lambda_param_generics`].
lambda_param_hint: Option<Vec<String>>,
/// True while an arrow-form `switch` written as a statement is lowered,
/// so its labels are checked as a statement's rather than an
/// expression's (see [`Compiler::check_switch_labels`]).
switch_is_statement: bool,
/// The parameter count a method reference argument's functional interface
/// takes, when the JDK method it is passed to fixes one — what picks the
/// overload of an arity-overloaded reference (`flatMapToInt(Arrays::stream)`
/// is `Arrays.stream(int[])`, not `(int[], int, int)`).
ref_arity_hint: Option<usize>,
/// The parameters of a lambda whose body is being *typed* (not lowered)
/// to infer its result, innermost last — see
/// [`Compiler::lambda_result_type`].
lambda_param_types: std::cell::RefCell<Vec<(String, String)>>,
/// See [`Compiler::expr_generic`]: node address → (node, answer), alive
/// only while an outermost query is in progress.
generic_memo: TypeMemo,
/// The same for [`Compiler::expr_java_type`].
java_type_memo: TypeMemo,
/// How many typing queries are in progress; the memos are dropped when it
/// returns to zero.
query_depth: std::cell::Cell<u32>,
/// Each user method's and constructor's parameter types with their type
/// arguments, keyed by its mangled name — only the ones declaring any.
param_generics: HashMap<String, Vec<Option<String>>>,
/// Each user method's return type with its type arguments, keyed by its
/// mangled name — only the ones declaring any.
ret_generics: HashMap<String, String>,
/// The enclosing method's [`Compiler::ret_generics`] entry while its body
/// is lowered, so a `return x -> …` reads the declared type's arguments.
current_ret_generic: Option<String>,
/// Whether the current method's return type was written with a
/// wildcard argument.
current_ret_wildcard: bool,
/// The parameters (per method, see [`Compiler::param_generics`]) and the
/// method returns whose declared type arguments include a wildcard.
param_wildcards: HashMap<String, Vec<bool>>,
ret_wildcards: HashSet<String>,
/// The declared return type of the method being lowered, so a `return
/// <lambda>;` knows its target type.
current_ret: Option<String>,
/// `yield` jumps of the arrow-`switch` arm body being lowered, patched to
/// the arm's exit once it is laid out.
yield_ops: Vec<usize>,
/// `finallys.len()` when the current arm body was entered — a `yield` runs
/// exactly the cleanup blocks opened inside the arm, and no more.
yield_finally_depth: usize,
/// The type a `yield` in the current arm body is assigned to: the switch
/// expression's target, or its own standalone type (see
/// [`Compiler::switch_arm_target`]).
yield_target: Option<String>,
}
/// A lambda body waiting to be emitted as a subroutine.
struct PendingLambda {
/// Chunk name index of the body's subroutine — the value the closure stores
/// and [`crate::host::JCLOSURE_CALL`] looks the entry address up by.
name_idx: u16,
/// The lambda's formal parameter names, bound to slots `0..n`.
params: Vec<String>,
/// The declared parameter types the target interface's single abstract
/// method gives them, when the literal's context named a target type. Empty
/// when it did not, in which case the parameters are statically untyped and
/// arithmetic on them falls back to the runtime's own rules.
param_tys: Vec<String>,
/// The parameters' types with their type arguments, where known (a
/// `Function<List<Integer>, …>` parameter is a `List<Integer>`), parallel
/// to `params`.
param_generic: Vec<Option<String>>,
/// The target interface's declared *return* type, when the literal's context
/// named a target. It drives the assignment conversion on the body's result
/// — a `double`-returning single abstract method widens an integral body.
ret_ty: Option<String>,
/// The enclosing locals captured by value, in push order, each with the
/// declared type and numeric category it had in the enclosing scope (so
/// `/`-truncation and class-typed dispatch keep working inside the body).
/// Bound to the slots after the parameters.
captures: Vec<Capture>,
/// True when the enclosing frame had a `this` — captured as the last
/// upvalue, so `this`, implicit field reads, and instance calls work inside
/// a lambda written in an instance method or constructor.
captures_this: bool,
body: LambdaBody,
/// The `this`/enclosing class the body lowers under (restored around the
/// body, because it is emitted long after its literal site).
this_class: Option<String>,
current_class: Option<String>,
line: u32,
}
/// One captured upvalue: the name it keeps inside the body, plus the static
/// typing it had outside.
struct Capture {
name: String,
decl_ty: Option<String>,
/// The captured local's [`MethodScope::decl_generic`] entry.
generic: Option<String>,
num_ty: NumType,
}
/// Compile a parsed [`Program`]'s `main` body to a runnable fusevm chunk.
pub fn compile(prog: &Program) -> Result<Chunk, String> {
compile_with(prog, false)
}
/// Compile with per-statement `DBG_LINE` line markers for the `--dap` debugger.
/// Identical to [`compile`] except each statement is preceded by a marker
/// carrying its source line (see [`crate::host::DBG_LINE`]).
pub fn compile_debug(prog: &Program) -> Result<Chunk, String> {
compile_with(prog, true)
}
fn compile_with(prog: &Program, debug: bool) -> Result<Chunk, String> {
let has_ffi = body_has_ffi(&prog.main);
// Register every static-method signature up front so calls resolve
// regardless of source order (forward references, recursion, mutual
// recursion).
let mut methods: HashMap<String, Vec<MethodSig>> = HashMap::default();
for m in &prog.methods {
methods.entry(m.name.clone()).or_default().push(MethodSig {
owner: m.owner.clone(),
param_tys: m.params.iter().map(|p| p.ty.clone()).collect(),
ret: numtype_of_ty(&m.ret).unwrap_or(NumType::Other),
ret_name: m.ret.clone(),
varargs: is_varargs(&m.params),
});
}
let (param_generics, ret_generics, param_wildcards, ret_wildcards) = signature_generics(prog);
let classes = resolve_classes(prog)?;
// One whole-program question, asked once: does any class supply a
// `toString()` body? It gates the concatenation rerouting in
// [`Compiler::emit_host_stringified`], so a program with none emits exactly
// the bytecode it did before that path existed.
let has_user_tostring = classes.values().any(|ci| {
ci.methods
.iter()
.any(|m| m.name == "toString" && m.param_tys.is_empty() && !m.is_abstract)
});
// Java's *constant variables*: a `static final String` whose initializer is
// a constant expression. Collected before any body is lowered, because a use
// can precede the declaration and folding has to see it either way.
let mut string_constants: HashMap<String, String> = HashMap::default();
for cl in &prog.classes {
for f in &cl.static_fields {
if !(f.is_final && f.ty == "String") {
continue;
}
// The parser moves a `static` field's initializer into the class's
// static-init sequence, so the literal is found there rather than on
// the declaration — as the assignment that seeds the cell.
let text = cl.static_init.iter().find_map(|st| match &st.kind {
StmtKind::Assign {
name,
op: AssignOp::Assign,
value: Expr::Str(text),
} if *name == f.name => Some(text.clone()),
_ => None,
});
if let Some(text) = text {
string_constants.insert(f.name.clone(), text);
}
}
}
let mut c = Compiler {
b: ChunkBuilder::new(),
literals: HashMap::default(),
string_constants,
scopes: Vec::new(),
pending_label: None,
switch_counter: 0,
exit_ops: Vec::new(),
debug,
has_ffi,
has_user_tostring,
lazy_init: lazy_initialized_classes(prog),
const_statics: prog
.classes
.iter()
.flat_map(|cl| {
cl.static_fields
.iter()
.filter(|f| {
f.is_final
&& constant_initializer(&cl.static_init, &f.name, &f.ty).is_some()
})
.map(|f| static_global(&cl.name, &f.name))
})
.collect(),
global_types: HashMap::default(),
scope: None,
methods,
global_decl_types: HashMap::default(),
global_decl_generic: HashMap::default(),
global_decl_wildcard: HashSet::default(),
classes,
this_class: None,
current_class: Some(prog.class_name.clone()),
temp_counter: 0,
has_exceptions: prog.uses_exceptions,
tries: Vec::new(),
finallys: Vec::new(),
pending_lambdas: Vec::new(),
lambda_counter: 0,
lambda_target: None,
lambda_ret_hint: None,
lambda_generic: None,
pending_target_generic: None,
method_access: {
let mut m: HashMap<String, Vec<(String, Vec<String>, Access)>> = HashMap::default();
let all = prog
.classes
.iter()
.flat_map(|cl| cl.methods.iter().map(move |x| (cl.name.as_str(), x)))
.chain(prog.methods.iter().map(|x| (x.owner.as_str(), x)));
for (owner, x) in all {
m.entry(owner.to_string()).or_default().push((
x.name.clone(),
x.params.iter().map(|p| p.ty.clone()).collect(),
x.access,
));
}
m
},
interface_statics: prog
.methods
.iter()
.filter(|m| {
prog.classes
.iter()
.any(|c| c.is_interface && c.name == m.owner)
})
.map(|m| (m.owner.clone(), m.name.clone()))
.collect(),
target_wildcard: None,
lambda_param_hint: None,
switch_is_statement: false,
ref_arity_hint: None,
lambda_param_types: Default::default(),
generic_memo: Default::default(),
java_type_memo: Default::default(),
query_depth: Default::default(),
param_generics,
ret_generics,
current_ret_generic: None,
current_ret_wildcard: false,
param_wildcards,
ret_wildcards,
current_ret: None,
yield_ops: Vec::new(),
yield_finally_depth: 0,
yield_target: None,
};
// ── main body (global scope) ──
// Class-level state exists before any user code runs, in Java's order:
// every `static` field takes its type's default value, enum constants are
// constructed (they are the first statics of their type), then the static
// initializers and `static { … }` blocks run in textual order.
c.emit_static_defaults(prog);
c.emit_eager_static_init(prog)?;
// `main`'s `String[]` parameter is the real program arguments.
c.bind_main_args(prog);
for stmt in &prog.main {
c.stmt(stmt)?;
}
// Patch any program-level `break`/`return;` to the position right after
// main. When subroutines follow, that position holds the skip-over jump.
// An exception that reached the top of `main` also lands here, so the
// uncaught report is emitted at exactly that position.
let end = c.b.current_pos();
if c.has_exceptions {
c.emit_uncaught_check();
}
let exit_ops = std::mem::take(&mut c.exit_ops);
for op in exit_ops {
c.b.patch_jump(op, end);
}
// ── subroutine bodies (static methods, then instance methods + ctors) ──
// Emitted after `main` and jumped over so control never falls into them;
// each is reached only via `Op::Call`.
let has_subs = !prog.methods.is_empty()
|| !c.pending_lambdas.is_empty()
|| !c.lazy_init.is_empty()
|| prog
.classes
.iter()
.any(|cl| !cl.methods.is_empty() || !cl.ctors.is_empty() || !cl.inst_init.is_empty());
if has_subs {
let skip = c.b.emit(Op::Jump(0), 0);
for m in &prog.methods {
c.compile_method(m)?;
}
for cl in &prog.classes {
for m in &cl.methods {
// Abstract methods (interface signatures, `abstract` class
// methods) have no body — no subroutine is emitted. A concrete
// implementor supplies the body reached by virtual dispatch.
if m.is_abstract {
continue;
}
c.compile_instance_method(&cl.name, m)?;
}
for ctor in &cl.ctors {
c.compile_ctor(cl, ctor)?;
}
if !cl.inst_init.is_empty() {
c.compile_inst_init(cl)?;
}
if c.lazy_init.contains(&cl.name) {
c.compile_clinit(cl)?;
}
}
// Lambda bodies last, and by draining rather than iterating: emitting one
// can queue another (a lambda that returns a lambda).
while let Some(pl) = c.pending_lambdas.pop() {
c.compile_lambda_body(pl)?;
}
let after = c.b.current_pos();
c.b.patch_jump(skip, after);
}
Ok(c.b.build())
}
/// Resolve every class's metadata with inheritance flattened: fields listed
/// ancestors-first (Java initialization order), field types merged, and each
/// `(method, arity)` mapped to its most-derived defining class.
/// The storage key of field `name` as `class` declares it: the bare name, or —
/// when an ancestor already declares one (`hides`) — the key
/// [`crate::ast::hidden_field_key`] mints for this declaration's own cell.
fn field_storage_key(class: &str, name: &str, hides: bool) -> String {
if hides {
crate::ast::hidden_field_key(class, name)
} else {
name.to_string()
}
}
fn resolve_classes(prog: &Program) -> Result<HashMap<String, ClassInfo>, String> {
let by_name: HashMap<&str, &Class> =
prog.classes.iter().map(|c| (c.name.as_str(), c)).collect();
// The ancestor chain of `name`, farthest ancestor first, `name` last.
let chain = |name: &str| -> Result<Vec<String>, String> {
let mut out = Vec::new();
let mut cur = Some(name.to_string());
let mut guard = 0;
while let Some(n) = cur {
if let Some(cl) = by_name.get(n.as_str()) {
out.push(n.clone());
cur = cl.superclass.clone();
} else {
// An unknown superclass (e.g. a JDK class) terminates the chain.
break;
}
guard += 1;
if guard > 1000 {
return Err(format!("javars: cyclic class hierarchy at `{name}`"));
}
}
out.reverse();
Ok(out)
};
// Collect a type's transitive interfaces, super-interfaces first (so a more
// specific interface's `default` overrides a less specific one), deduped.
fn collect_ifaces(
name: &str,
by_name: &HashMap<&str, &Class>,
order: &mut Vec<String>,
seen: &mut HashSet<String>,
) {
if !seen.insert(name.to_string()) {
return;
}
if let Some(cl) = by_name.get(name) {
for i in &cl.interfaces {
collect_ifaces(i, by_name, order, seen);
}
if cl.is_interface {
order.push(name.to_string());
}
}
}
let mut out = HashMap::default();
for cl in &prog.classes {
let ancestry = chain(&cl.name)?;
// The interfaces this type (and its superclass chain) brings in, super-
// interfaces first. `extends`-ed interfaces of an interface, and
// `implements`-ed interfaces of every class in the ancestry.
let mut iface_order = Vec::new();
let mut seen = HashSet::default();
for anc_name in &ancestry {
let anc = by_name[anc_name.as_str()];
for i in &anc.interfaces {
collect_ifaces(i, &by_name, &mut iface_order, &mut seen);
}
}
let mut fields = Vec::new();
let mut field_types = HashMap::default();
let mut field_keys: HashMap<String, String> = HashMap::default();
let mut field_generic: HashMap<String, (String, String)> = HashMap::default();
let mut field_wildcard = HashSet::default();
for anc_name in &ancestry {
let anc = by_name[anc_name.as_str()];
for f in anc.fields.iter().chain(&anc.static_fields) {
if let Some(g) = with_targs(&f.ty, &f.targs) {
field_generic.insert(f.name.clone(), (anc_name.clone(), g));
}
if f.wildcard {
field_wildcard.insert(f.name.clone());
} else {
field_wildcard.remove(&f.name);
}
}
}
// `static` fields, ancestors first so a subclass re-declaration shadows
// the inherited one (and interface constants are visible too).
let mut static_fields = HashMap::default();
for iface in &iface_order {
for f in &by_name[iface.as_str()].static_fields {
static_fields.insert(f.name.clone(), (iface.clone(), f.ty.clone()));
}
}
for anc_name in &ancestry {
for f in &by_name[anc_name.as_str()].static_fields {
static_fields.insert(f.name.clone(), (anc_name.clone(), f.ty.clone()));
}
}
// A *nested* class sees its encloser's `static` fields by their bare
// name, which no ancestry walk finds — a nested class is not a subclass
// of the class it sits in. The binary name is what records the nesting
// (`Outer$Nested`), so the enclosers are read off it, outermost first so
// a nearer one wins. Its own declarations still win over all of them,
// which is why this runs before the loop above would have to be undone —
// it does not, because `insert` here happens first.
let mut enclosing_statics: HashMap<String, (String, String)> = HashMap::default();
let mut prefix = cl.binary.as_str();
while let Some((outer, _)) = prefix.rsplit_once('$') {
let simple = outer.rsplit('$').next().unwrap_or(outer);
if let Some(oc) = by_name.get(simple) {
for f in &oc.static_fields {
enclosing_statics
.entry(f.name.clone())
.or_insert_with(|| (simple.to_string(), f.ty.clone()));
}
}
prefix = outer;
}
for (name, owner) in enclosing_statics {
static_fields.entry(name).or_insert(owner);
}
// Keyed by (name, param_types) so type-overloads coexist while an
// override (same name + same param types) replaces the inherited entry.
let mut methods: HashMap<(String, Vec<String>), MethodMeta> = HashMap::default();
let param_tys =
|m: &Method| -> Vec<String> { m.params.iter().map(|p| p.ty.clone()).collect() };
// 1. Interface methods (abstract + `default`), super-interfaces first —
// later (more specific) entries overwrite earlier ones.
for iface in &iface_order {
let icl = by_name[iface.as_str()];
for m in &icl.methods {
let ptys = param_tys(m);
methods.insert(
(m.name.clone(), ptys.clone()),
MethodMeta {
name: m.name.clone(),
param_tys: ptys,
defining: iface.clone(),
ret: m.ret.clone(),
is_abstract: m.is_abstract,
varargs: is_varargs(&m.params),
},
);
}
}
// 2. Class-chain fields and methods (ancestors first) — a class method
// always overrides an inherited interface `default`.
for anc_name in &ancestry {
let anc = by_name[anc_name.as_str()];
for f in &anc.fields {
let key = field_storage_key(anc_name, &f.name, field_keys.contains_key(&f.name));
field_keys.insert(f.name.clone(), key.clone());
field_types.insert(f.name.clone(), f.ty.clone());
fields.push(FieldInit {
name: f.name.clone(),
key,
ty: f.ty.clone(),
init: f.init.clone(),
});
}
for m in &anc.methods {
let ptys = param_tys(m);
methods.insert(
(m.name.clone(), ptys.clone()),
MethodMeta {
name: m.name.clone(),
param_tys: ptys,
defining: anc_name.clone(),
ret: m.ret.clone(),
is_abstract: m.is_abstract,
varargs: is_varargs(&m.params),
},
);
}
}
let methods: Vec<MethodMeta> = methods.into_values().collect();
let ctors: Vec<CtorSig> = cl
.ctors
.iter()
.map(|c| CtorSig {
param_tys: c.params.iter().map(|p| p.ty.clone()).collect(),
varargs: is_varargs(&c.params),
})
.collect();
let mut supertypes = Vec::new();
if let Some(sup) = &cl.superclass {
supertypes.push(sup.clone());
}
supertypes.extend(cl.interfaces.iter().cloned());
out.insert(
cl.name.clone(),
ClassInfo {
superclass: cl.superclass.clone(),
binary: cl.binary.clone(),
supertypes,
is_interface: cl.is_interface,
is_enum: cl.is_enum,
is_record: cl.is_record,
enum_constants: cl.enum_constants.iter().map(|c| c.name.clone()).collect(),
fields,
field_types,
field_keys,
field_generic,
field_wildcard,
type_params: cl.type_params.clone(),
super_targs: cl.super_targs.clone(),
is_sealed: cl.is_sealed,
is_abstract: cl.is_abstract || cl.is_interface,
permits: cl.permits.clone(),
interfaces: cl
.interfaces
.iter()
.cloned()
.zip(
cl.interface_targs
.iter()
.cloned()
.chain(std::iter::repeat(Vec::new())),
)
.collect(),
static_fields,
methods,
ctors,
has_inst_init: !cl.inst_init.is_empty(),
captures: cl
.captures
.iter()
.map(|p| (p.name.clone(), p.ty.clone()))
.collect(),
},
);
}
Ok(out)
}
impl Compiler {
// ── variable access (global `main` scope vs. slot-based method scope) ──
/// Emit a read of local/parameter `name`: a frame slot in a method scope,
/// or a global name-pool variable in `main`.
fn emit_get(&mut self, name: &str, line: u32) {
match &mut self.scope {
Some(scope) => {
let slot = scope.slot(name);
self.b.emit(Op::GetSlot(slot), line);
}
None => {
let idx = self.b.add_name(name);
self.b.emit(Op::GetVar(idx), line);
}
}
}
/// Emit a store of the top-of-stack into local/parameter `name`.
fn emit_set(&mut self, name: &str, line: u32) {
match &mut self.scope {
Some(scope) => {
let slot = scope.slot(name);
self.b.emit(Op::SetSlot(slot), line);
}
None => {
let idx = self.b.add_name(name);
self.b.emit(Op::SetVar(idx), line);
}
}
}
/// Emit a read of `this`. Slot 0 in an instance method or constructor; the
/// slot holding the captured receiver inside a lambda body.
fn emit_this(&mut self, line: u32) {
let slot = self.scope.as_ref().and_then(|s| s.this_slot).unwrap_or(0);
self.b.emit(Op::GetSlot(slot), line);
}
// ── enums ────────────────────────────────────────────────────────────
//
// An enum constant is a singleton created once, before any user code runs,
// and named from every frame. fusevm's `GetVar`/`SetVar` address a flat
// global table (frame slots are per-call), so each constant gets one global
// — `#enum#Color#RED` — that both `main` and a method body read directly.
// Everything after that is ordinary object machinery: the constants are
// instances of a normal class, so `==`, `instanceof`, virtual dispatch, and
// arrays of them all work with no further special cases.
/// Read the global holding an enum constant, from any frame.
fn emit_global_get(&mut self, name: &str, line: u32) {
let idx = self.b.add_name(name);
self.b.emit(Op::GetVar(idx), line);
}
/// Store the top of stack into a global, from any frame.
fn emit_global_set(&mut self, name: &str, line: u32) {
let idx = self.b.add_name(name);
self.b.emit(Op::SetVar(idx), line);
}
/// Build an enum's constants — each one's instance parked in its global.
/// They are the first statics of the type, so they run ahead of its other
/// static initializers, as part of the type's own initialization.
fn emit_enum_constants(&mut self, cl: &Class) -> Result<(), String> {
for (ordinal, constant) in cl.enum_constants.iter().enumerate() {
let line = cl.line;
// A constant with a body is an instance of its own synthetic
// subclass, but it is the *enum's* constructor that runs — Java
// gives an anonymous enum subclass no constructor of its own.
let runtime_class = constant.body_class.as_deref().unwrap_or(&cl.name);
self.new_object_as(runtime_class, &cl.name, &constant.args, None, line)?;
let obj = self.temp();
self.emit_set(&obj, line);
// … then the identity every enum constant carries.
for (field, value) in [
(ENUM_NAME, Expr::Str(constant.name.clone())),
(ENUM_ORDINAL, Expr::Int(ordinal as i64)),
] {
self.emit_get(&obj, line);
let name_c = self.b.add_constant(Value::str(field.to_string()));
self.b.emit(Op::LoadConst(name_c), line);
self.expr(&value)?;
self.emit_raising_builtin(crate::host::JFIELD_SET, 3, line);
self.b.emit(Op::Pop, line);
}
self.emit_get(&obj, line);
self.emit_global_set(&enum_global(&cl.name, &constant.name), line);
}
Ok(())
}
// ── `static` fields ──────────────────────────────────────────────────
//
// A `static` field is one cell shared by every instance and readable from
// every frame, which is exactly what a fusevm global is (frame slots are
// per-call). So each one gets a compiler-minted global — `#static#T#n` —
// seeded with the field's default before any user code runs, and both the
// qualified (`T.n`) and unqualified (`n`, inside the class) forms lower to
// a read/write of that global.
/// Seed every `static` field with its declared type's default value. Runs
/// before any initializer so a field read during another class's static
/// initialization sees `0`/`null` rather than nothing — Java's rule.
fn emit_static_defaults(&mut self, prog: &Program) {
for cl in &prog.classes {
for f in &cl.static_fields {
// A constant variable (JLS 4.12.4) is read without initializing
// its class, so it holds its value from the start.
let constant = f
.is_final
.then(|| constant_initializer(&cl.static_init, &f.name, &f.ty))
.flatten();
match constant {
Some(value) => self
.expr_targeted(value, Some(&f.ty))
.expect("a constant expression lowers without error"),
None => self.emit_type_default(&f.ty, cl.line),
}
self.emit_global_set(&static_global(&cl.name, &f.name), cl.line);
}
}
}
/// Run each class's static initialization — its field initializers and
/// `static { … }` blocks, in textual order — with the class in scope so an
/// unqualified name resolves to its own statics.
fn emit_eager_static_init(&mut self, prog: &Program) -> Result<(), String> {
// A class with an observable initializer waits for its first use (see
// [`Compiler::emit_class_init`]). One whose initializers only store
// literals can be initialized up front, since nothing can tell, and it
// runs ahead of the entry class's so the latter sees those values.
for cl in &prog.classes {
if cl.name == prog.class_name || self.lazy_init.contains(&cl.name) {
continue;
}
let saved = self.current_class.replace(cl.name.clone());
let result = cl.static_init.iter().try_for_each(|s| self.stmt(s));
self.current_class = saved;
result?;
}
let Some(cl) = prog.classes.iter().find(|c| c.name == prog.class_name) else {
return Ok(());
};
// The entry class's initialization is bracketed like a lazy one's
// (see [`Compiler::emit_clinit_guard`]): an exception escaping it
// reaches the uncaught report while the bracket is open, which is
// what reports it as the `ExceptionInInitializerError` it becomes.
let observable = !cl.static_init.is_empty() || !cl.enum_constants.is_empty();
let binary_c = self.b.add_constant(Value::str(cl.binary.clone()));
if observable {
self.b.emit(Op::LoadConst(binary_c), cl.line);
self.b
.emit(Op::CallBuiltin(crate::host::JCLINIT_ENTER, 1), cl.line);
self.b.emit(Op::Pop, cl.line);
}
if let Some(sup) = cl.superclass.clone() {
self.emit_clinit_guard(&sup, cl.line);
}
self.emit_enum_constants(cl)?;
let saved = self.current_class.replace(cl.name.clone());
let result = cl.static_init.iter().try_for_each(|s| self.stmt(s));
self.current_class = saved;
if observable {
self.b.emit(Op::LoadConst(binary_c), cl.line);
self.b
.emit(Op::CallBuiltin(crate::host::JCLINIT_EXIT, 1), cl.line);
self.b.emit(Op::Pop, cl.line);
}
result
}
/// Initialize `class` on this use unless it already has been: the first
/// `new`, static call, or non-constant static field access of a class runs
/// its static initializer (JLS 12.4.1). Nothing is emitted for a class with
/// no observable initializer, or when the code being compiled belongs to
/// the class itself or a subclass — it can only be running once the class
/// has been initialized.
fn emit_class_init(&mut self, class: &str, line: u32) {
if !self.lazy_init.contains(class) {
return;
}
let mut cur = self.current_class.as_deref();
while let Some(c) = cur {
if c == class {
return;
}
cur = self.classes.get(c).and_then(|ci| ci.superclass.as_deref());
}
self.emit_clinit_guard(class, line);
}
/// [`Compiler::emit_class_init`] for a read or write of `class.name`, which
/// a constant variable (JLS 4.12.4) does not trigger.
fn emit_static_field_init(&mut self, class: &str, name: &str, line: u32) {
if !self.const_statics.contains(&static_global(class, name)) {
self.emit_class_init(class, line);
}
}
/// `if (!initialized(class)) class.<clinit>()`. The flag is raised on entry
/// to the initializer, so a use of the class from inside its own
/// initialization falls through, as it does in Java.
fn emit_clinit_guard(&mut self, class: &str, line: u32) {
if !self.lazy_init.contains(class) {
return;
}
self.emit_global_get(&clinit_flag(class), line);
let done = self.b.emit(Op::JumpIfTrue(0), line);
// JLS 12.4.2: a class whose initialization failed is erroneous, so a
// later use throws `NoClassDefFoundError` rather than retrying, and an
// exception escaping the initializer leaves it wrapped in an
// `ExceptionInInitializerError` (an `Error` escapes as itself). The
// flag drops back to false on failure, so the next use reaches the
// check again.
let binary = self.classes.get(class).map_or(class, |ci| &ci.binary);
let binary_c = self.b.add_constant(Value::str(binary.to_string()));
self.b.emit(Op::LoadConst(binary_c), line);
self.emit_raising_builtin(crate::host::JCLINIT_ENTER, 1, line);
self.b.emit(Op::Pop, line);
let idx = self.b.add_name(&clinit_name(class));
self.b.emit(Op::Call(idx, 0), line);
self.b.emit(Op::Pop, line);
self.b.emit(Op::LoadConst(binary_c), line);
self.b
.emit(Op::CallBuiltin(crate::host::JCLINIT_EXIT, 1), line);
let ok = self.b.emit(Op::JumpIfFalse(0), line);
self.b.emit(Op::LoadFalse, line);
self.emit_global_set(&clinit_flag(class), line);
let checked = self.b.current_pos();
self.b.patch_jump(ok, checked);
self.emit_exc_check(line);
let after = self.b.current_pos();
self.b.patch_jump(done, after);
}
/// [`default_interfaces`] over the resolved class table.
fn default_interfaces_of(&self, cl: &Class) -> Vec<String> {
fn walk(c: &Compiler, name: &str, out: &mut Vec<String>) {
let Some(info) = c.classes.get(name) else {
return;
};
for sup in &info.supertypes {
walk(c, sup, out);
}
let has_default = info
.methods
.iter()
.any(|m| m.defining == name && !m.is_abstract);
if info.is_interface && has_default && !out.iter().any(|o| o == name) {
out.push(name.to_string());
}
}
let mut out = Vec::new();
if !cl.is_interface {
for i in &cl.interfaces {
walk(self, i, &mut out);
}
}
out
}
/// Lower a class's static initialization to the subroutine
/// [`Compiler::emit_clinit_guard`] calls: mark it initialized, initialize
/// the superclass first (JLS 12.4.2), build the enum constants, then run
/// the field initializers and `static { … }` blocks in textual order.
fn compile_clinit(&mut self, cl: &Class) -> Result<(), String> {
let entry = self.b.current_pos();
let name_idx = self.b.add_name(&clinit_name(&cl.name));
self.b.add_sub_entry(name_idx, entry);
self.scope = Some(MethodScope::new());
let saved_class = self.current_class.replace(cl.name.clone());
self.b.emit(Op::LoadTrue, cl.line);
self.emit_global_set(&clinit_flag(&cl.name), cl.line);
if let Some(sup) = cl.superclass.clone() {
self.emit_clinit_guard(&sup, cl.line);
}
for iface in self.default_interfaces_of(cl) {
self.emit_clinit_guard(&iface, cl.line);
}
let result = self
.emit_enum_constants(cl)
.and_then(|()| cl.static_init.iter().try_for_each(|s| self.stmt(s)));
self.b.emit(Op::LoadUndef, cl.line);
self.b.emit(Op::ReturnValue, cl.line);
self.scope = None;
self.current_class = saved_class;
result
}
/// Bind `main`'s `String[]` parameter to the real program arguments.
/// Nothing is emitted for a `main()` that declares no parameter.
fn bind_main_args(&mut self, prog: &Program) {
let Some(name) = &prog.main_param else {
return;
};
let name = name.clone();
self.declare_local(&name, "String[]", NumType::Other);
self.b.emit(Op::CallBuiltin(crate::host::JARGV, 0), 0);
self.emit_array_tag("String[]", 0);
self.emit_set(&name, 0);
}
/// Record the binary name `name` (an `Expr::Str`) as the `getClass()` of
/// the value on top of the stack, leaving it there.
fn emit_anon_class_name(&mut self, name: &Expr) {
if let Expr::Str(n) = name {
let c = self.b.add_constant(Value::str(n.clone()));
self.b.emit(Op::LoadConst(c), 0);
self.b.emit(Op::CallBuiltin(crate::host::JCLASS_NAME, 2), 0);
}
}
/// Record the array on top of the stack as having type `ty` (see
/// [`crate::host::JARRAY_TAG`]), leaving it there.
fn emit_array_tag(&mut self, ty: &str, line: u32) {
let c = self.b.add_constant(Value::str(ty.to_string()));
self.b.emit(Op::LoadConst(c), line);
self.b
.emit(Op::CallBuiltin(crate::host::JARRAY_TAG, 2), line);
}
/// The class declaring the `static` field an unqualified `name` refers to,
/// with its declared type. `None` when `name` is a local/parameter (which
/// shadows a field), or when the enclosing class has no such static.
fn static_field_owner(&self, name: &str) -> Option<(String, String)> {
if self.is_declared_var(name) {
return None;
}
let cur = self.current_class.as_deref()?;
self.classes.get(cur)?.static_fields.get(name).cloned()
}
/// When `e` is `ClassName.field` naming a `static` field, its declaring
/// class and declared type — the `Expr::Field` shape whose receiver is a
/// *type* rather than a value. A declared variable of the same name always
/// wins, exactly as it does for an enum constant.
fn static_field_ref(&self, e: &Expr) -> Option<(String, String)> {
let Expr::Field { recv, name } = e else {
return None;
};
// `Outer.Nested.f` names the nested class through its enclosers.
let class = match recv.as_ref() {
Expr::Var(class) if !self.is_declared_var(class) => class.clone(),
Expr::Field { .. } => self.user_class_ref(recv)?,
_ => return None,
};
self.classes.get(&class)?.static_fields.get(name).cloned()
}
/// The declaring class + declared type of whichever `static` field an
/// assignment target names — an unqualified `n` or a qualified `T.n`.
fn static_target(&self, recv: &Expr, name: &str) -> Option<(String, String)> {
match recv {
Expr::This => self.static_field_owner(name),
_ => self.static_field_ref(&Expr::Field {
recv: Box::new(recv.clone()),
name: name.to_string(),
}),
}
}
/// Lower `<static field> <op>= value` — a read/modify/write of the field's
/// global. `=` writes straight through.
fn static_assign(
&mut self,
class: &str,
ty: &str,
name: &str,
op: AssignOp,
value: &Expr,
line: u32,
) -> Result<(), String> {
self.emit_static_field_init(class, name, line);
let global = static_global(class, name);
if op != AssignOp::Assign {
return self.static_update(&global, ty, op, value, Yield::Nothing, line);
}
let ty = ty.to_string();
let generic = self
.classes
.get(class)
.and_then(|ci| ci.field_generic.get(name))
.map(|(_, g)| g.clone());
self.target_wildcard = Some(
self.classes
.get(class)
.is_some_and(|ci| ci.field_wildcard.contains(name)),
);
self.expr_targeted_generic(value, Some(&ty), generic)?;
self.emit_global_set(&global, line);
Ok(())
}
/// Read/modify/write of a static field's `global` cell under a compound
/// operator, leaving `want` on the stack — nothing for `C.n += 1`, the old
/// value for `C.n++`, the new one for `++C.n`. The cell is named rather than
/// re-derived from the class and field, which is all the class and field
/// were ever used for here.
fn static_update(
&mut self,
global: &str,
ty: &str,
op: AssignOp,
value: &Expr,
want: Yield,
line: u32,
) -> Result<(), String> {
self.emit_global_get(global, line);
let old_t = self.stash_if(want == Yield::Old, line);
self.emit_compound_update(op, value, Some(ty), line)?;
self.emit_global_set(global, line);
match (want, old_t) {
(Yield::Old, Some(t)) => self.emit_get(&t, line),
(Yield::New, _) => self.emit_global_get(global, line),
_ => {}
}
Ok(())
}
/// Copy the top of the stack into a fresh temp and push it back, so a later
/// read still sees the pre-update value. Emits nothing when `save` is false,
/// which keeps statement-position bytecode exactly as it was.
fn stash_if(&mut self, save: bool, line: u32) -> Option<String> {
if !save {
return None;
}
let t = self.temp();
self.emit_set(&t, line);
self.emit_get(&t, line);
Some(t)
}
/// When `e` is `EnumName.CONSTANT`, the enum's name — the one `Expr::Field`
/// shape that is a *type* reference rather than an instance field read.
/// `None` for every other expression, including a field of a variable that
/// happens to share an enum's name (a declared variable always wins).
fn enum_constant_ref(&self, e: &Expr) -> Option<String> {
let Expr::Field { recv, name } = e else {
return None;
};
// `Outer.Inner.RED` names the constant through the enclosers too.
let class = self.enum_type_ref(recv)?;
let info = self.classes.get(&class)?;
info.enum_constants
.iter()
.any(|c| c == name)
.then_some(class)
}
/// A bare `MUL` written inside `enum Op`'s own body names its constant —
/// Java allows the unqualified form only there and in a `switch` label.
/// A local of the same name shadows it, exactly as it shadows a field.
fn enclosing_enum_constant(&self, name: &str) -> Option<String> {
if self.is_local(name) {
return None;
}
let this = self.this_class.as_deref()?;
let info = self.classes.get(this)?;
info.enum_constants
.iter()
.any(|c| c == name)
.then(|| this.to_string())
}
/// The type of `EnumName.values()` / `EnumName.valueOf(s)` — the two enum
/// statics the compiler generates, which have no entry in any method table.
fn enum_static_type(&self, recv: &Expr, method: &str, argc: usize) -> Option<String> {
let class = self.enum_type_ref(recv)?;
match (method, argc) {
("values", 0) => Some(format!("{class}[]")),
("valueOf", 1) => Some(class),
_ => None,
}
}
/// An unqualified `values()` / `valueOf(s)` written inside an enum's own
/// code, rewritten to the qualified `Color.values()` it means. Every enum
/// has the two as implicit `static` members (JLS 8.9.3), so its methods,
/// constructors and constant bodies may call them bare; javars generates
/// them at the qualified call site, so the bare form is routed there. A
/// constant with a body lowers under a subclass of the enum, which is why
/// the superclass is consulted too.
fn implicit_enum_static(&self, name: &str, args: &[Expr], line: u32) -> Option<Expr> {
if !matches!((name, args.len()), ("values", 0) | ("valueOf", 1))
|| self.methods.contains_key(name)
{
return None;
}
let enclosing = [self.this_class.as_deref(), self.current_class.as_deref()];
let class = enclosing.into_iter().flatten().find_map(|c| {
let info = self.classes.get(c)?;
if info.is_enum {
return Some(c.to_string());
}
let sup = info.superclass.as_deref()?;
self.classes.get(sup)?.is_enum.then(|| sup.to_string())
})?;
Some(Expr::MethodCall {
recv: Box::new(Expr::Var(class)),
method: name.to_string(),
args: args.to_vec(),
line,
})
}
/// The user class named by a bare receiver (`Counter.reset()`), or `None`
/// when the receiver is a value rather than a type name. A declared variable
/// of the same name always wins.
fn user_class_ref(&self, recv: &Expr) -> Option<String> {
let name = match recv {
Expr::Var(name) => name,
// `Outer.Nested.f()` — a nested type named through its enclosers.
// javars flattens nested types into one namespace keyed by the
// simple name, so the chain names the class its last segment does,
// provided every earlier segment names a class too (which is what
// separates it from `someValue.field.f()`).
Expr::Field { recv: outer, name } => {
return self
.user_class_ref(outer)
.and_then(|_| self.classes.contains_key(name).then(|| name.clone()));
}
_ => return None,
};
if self.is_declared_var(name) || self.bare_var_type(name).is_some() {
return None;
}
self.classes.contains_key(name).then(|| name.clone())
}
/// The enum type named by a bare receiver (`Color.values()`), or `None` when
/// the receiver is a value rather than an enum type name.
/// A nested enum named through its enclosers (`Outer.Inner.values()`) is
/// the same type, resolved the way [`Compiler::user_class_ref`] resolves it.
fn enum_type_ref(&self, recv: &Expr) -> Option<String> {
let class = self.user_class_ref(recv)?;
self.classes.get(&class)?.is_enum.then_some(class)
}
/// `javac`'s two static checks on a `switch`'s labels (JLS 14.11.1):
/// a pattern label dominated by an earlier unguarded type pattern that
/// already covers its type is an error, and a `switch` expression — or a
/// statement that uses patterns, `case null`, or a selector type beyond the
/// legacy integral, `String` and enum ones — must be exhaustive: a
/// `default`, an unguarded pattern covering the selector type, every enum
/// constant, or every permitted subtype of a sealed type. `labels` is each
/// arm's (labels, is-default, is-guarded).
fn check_switch_labels(
&self,
disc: &Expr,
labels: &[(&[Expr], bool, bool)],
is_expr: bool,
line: u32,
) -> Result<(), String> {
let Some(sel) = self.expr_java_type(disc) else {
return Ok(());
};
fn pattern(e: &Expr) -> Option<&str> {
match e {
Expr::TypePattern { class, .. } => Some(class.as_str()),
_ => None,
}
}
// Dominance: an unguarded type pattern covers every later pattern of a
// subtype of its type.
let mut covering: Vec<&str> = Vec::new();
for (ls, _, guarded) in labels {
for l in ls.iter() {
if let Some(t) = pattern(l) {
if covering.iter().any(|c| self.type_covers(c, t)) {
return Err(format!(
"javars: this case label is dominated by a preceding case label (line {line})"
));
}
}
}
if !guarded {
covering.extend(ls.iter().filter_map(|l| match l {
Expr::TypePattern {
class, components, ..
} if components.is_empty() => Some(class.as_str()),
_ => None,
}));
}
}
// Two constant labels naming one value (JLS 14.11.1). A `char` and an
// `int` label are one domain, so `case 'a'` and `case 97` collide.
let mut constants: Vec<String> = Vec::new();
for (ls, _, _) in labels {
for l in ls.iter() {
let key = match l {
Expr::Str(s) => Some(format!("\"{s}")),
Expr::Var(n) => Some(n.clone()),
other => int_label_value(other).map(|n| format!("#{n}")),
};
if let Some(k) = key {
if constants.contains(&k) {
return Err(format!("javars: duplicate case label (line {line})"));
}
constants.push(k);
}
}
}
let uses_patterns = labels.iter().any(|(ls, _, _)| {
ls.iter()
.any(|l| pattern(l).is_some() || matches!(l, Expr::Var(n) if n == NULL_LITERAL))
});
let legacy = matches!(
sel.as_str(),
"char"
| "byte"
| "short"
| "int"
| "Character"
| "Byte"
| "Short"
| "Integer"
| "String"
) || self.classes.get(&sel).is_some_and(|ci| ci.is_enum);
if !is_expr && !uses_patterns && legacy {
return Ok(());
}
if labels.iter().any(|(_, d, _)| *d) {
return Ok(());
}
// The unguarded labels: type patterns (record patterns counted as
// covering their record) and enum constants.
let mut types: Vec<&str> = Vec::new();
let mut constants: Vec<&str> = Vec::new();
for (ls, _, guarded) in labels {
if *guarded {
continue;
}
for l in ls.iter() {
match l {
Expr::TypePattern { class, .. } => types.push(class),
Expr::Var(n) => constants.push(n),
Expr::Field { name, .. } => constants.push(name),
_ => {}
}
}
}
if self.switch_covers(&sel, &types, &constants, 0) {
return Ok(());
}
let what = if is_expr { "expression" } else { "statement" };
Err(format!(
"javars: the switch {what} does not cover all possible input values (line {line})"
))
}
/// Whether a pattern of type `t` matches every value of type `s`.
fn type_covers(&self, t: &str, s: &str) -> bool {
t == s
|| t == "Object"
|| (self.classes.contains_key(s) && self.is_subclass(s, t))
|| crate::host::jdk_is_subtype(s, t)
}
/// Whether the unguarded `types` and enum `constants` cover every value
/// of type `s`: a covering pattern, every constant of an enum, or — for a
/// sealed type — every permitted direct subtype (and the type itself
/// unless it is abstract).
fn switch_covers(&self, s: &str, types: &[&str], constants: &[&str], depth: usize) -> bool {
if types.iter().any(|t| self.type_covers(t, s)) {
return true;
}
let Some(info) = self.classes.get(s) else {
return false;
};
if info.is_enum {
return !info.enum_constants.is_empty()
&& info
.enum_constants
.iter()
.all(|c| constants.contains(&c.as_str()));
}
if !info.is_sealed || !info.is_abstract || depth > 32 {
return false;
}
let permitted: Vec<&String> = if info.permits.is_empty() {
self.classes
.iter()
.filter(|(_, ci)| {
ci.superclass.as_deref() == Some(s) || ci.supertypes.iter().any(|t| t == s)
})
.map(|(n, _)| n)
.collect()
} else {
info.permits.iter().collect()
};
!permitted.is_empty()
&& permitted
.iter()
.all(|p| self.switch_covers(p, types, constants, depth + 1))
}
/// Lower `EnumName.values()` — a fresh array of the constants, in
/// declaration order, exactly as Java hands out a fresh copy each call.
fn emit_enum_values(&mut self, class: &str, line: u32) {
self.emit_class_init(class, line);
let constants = self.classes[class].enum_constants.clone();
for (i, span) in array_build_chunks(constants.len()).into_iter().enumerate() {
let len = span.len();
for c in &constants[span] {
self.emit_global_get(&enum_global(class, c), line);
}
self.b.emit(array_build_op(i, len), line);
}
self.emit_array_tag(&format!("{class}[]"), line);
}
/// `Enum.valueOf(Color.class, s)` rewritten to the `Color.valueOf(s)` it is
/// (JLS 8.9.3 defines the implicit one as calling it), when the class
/// literal names a user enum.
fn enum_class_value_of(
&self,
recv: &Expr,
method: &str,
args: &[Expr],
line: u32,
) -> Option<Expr> {
let (Expr::Var(c), "valueOf", [Expr::ClassLit(lit), name]) = (recv, method, args) else {
return None;
};
if c != "Enum" || self.is_declared_var(c) {
return None;
}
let simple = self.class_lit_class(lit);
self.classes.get(simple)?.is_enum.then(|| Expr::MethodCall {
recv: Box::new(Expr::Var(simple.to_string())),
method: method.to_string(),
args: vec![name.clone()],
line,
})
}
/// Lower `EnumName.valueOf(s)` — a name-to-constant lookup, raising Java's
/// `IllegalArgumentException: No enum constant Color.PINK` on a miss.
fn emit_enum_value_of(&mut self, class: &str, arg: &Expr, line: u32) -> Result<(), String> {
self.emit_class_init(class, line);
let constants = self.classes[class].enum_constants.clone();
let key = self.temp();
self.expr(arg)?;
self.emit_set(&key, line);
let mut done = Vec::new();
for c in &constants {
self.emit_get(&key, line);
let cc = self.b.add_constant(Value::str(c.clone()));
self.b.emit(Op::LoadConst(cc), line);
self.b.emit(Op::StrEq, line);
let jf = self.b.emit(Op::JumpIfFalse(0), line);
self.emit_global_get(&enum_global(class, c), line);
done.push(self.b.emit(Op::Jump(0), line));
let next = self.b.current_pos();
self.b.patch_jump(jf, next);
}
// No match. `Enum.valueOf` names the type with its *canonical* name —
// `getCanonicalName()`, which is the binary name with `$` written as
// `.` — so a nested enum reports `T.E.Z` and not the simple `E.Z` the
// declaration site spells. The message needs the runtime argument, so
// it is built with a concatenation rather than a constant.
// A `null` name misses the constant directory too, and `Enum.valueOf`
// then answers `NullPointerException: Name is null` instead.
self.emit_get(&key, line);
self.expr(&Expr::Var(NULL_LITERAL.to_string()))?;
self.b.emit(Op::NumEq, line);
let not_null = self.b.emit(Op::JumpIfFalse(0), line);
let cls = self.b.add_constant(Value::str("NullPointerException"));
self.b.emit(Op::LoadConst(cls), line);
let m = self.b.add_constant(Value::str("Name is null"));
self.b.emit(Op::LoadConst(m), line);
self.b.emit(Op::CallBuiltin(crate::host::JFAULT, 2), line);
self.b.emit(Op::Pop, line);
self.emit_unwind(line);
let past = self.b.current_pos();
self.b.patch_jump(not_null, past);
let msg = self.temp();
// `Class.getCanonicalName()`, which is `null` for a local class or
// anything nested in one (a binary-name segment that starts with the
// digits `javac` numbers them by).
let binary = &self.classes[class].binary;
let local = binary
.split('$')
.skip(1)
.any(|s| s.starts_with(|c: char| c.is_ascii_digit()));
let canonical = if local {
"null".to_string()
} else {
binary.replace('$', ".")
};
let prefix = self
.b
.add_constant(Value::str(format!("No enum constant {canonical}.")));
self.b.emit(Op::LoadConst(prefix), line);
self.emit_get(&key, line);
self.b.emit(Op::Add, line);
self.emit_set(&msg, line);
let cls = self.b.add_constant(Value::str("IllegalArgumentException"));
self.b.emit(Op::LoadConst(cls), line);
self.emit_get(&msg, line);
self.b.emit(Op::CallBuiltin(crate::host::JFAULT, 2), line);
self.b.emit(Op::Pop, line);
self.emit_unwind(line);
// The unwind never falls through, but the jumps from a match do.
let end = self.b.current_pos();
for j in done {
self.b.patch_jump(j, end);
}
Ok(())
}
/// Record the declared numeric type of a local/parameter in the active scope.
fn declare_type(&mut self, name: &str, nt: NumType) {
match &mut self.scope {
Some(scope) => {
scope.types.insert(name.to_string(), nt);
}
None => {
self.global_types.insert(name.to_string(), nt);
}
}
}
/// Declare a local/parameter with its raw declared type: records the numeric
/// category (for `/` typing), the raw type string (for class-typed dispatch),
/// and marks the name as a true local (so it shadows any same-named field).
fn declare_local(&mut self, name: &str, ty: &str, nt: NumType) {
self.declare_type(name, nt);
match &mut self.scope {
Some(scope) => {
scope.decl_types.insert(name.to_string(), ty.to_string());
scope.decl_generic.remove(name);
scope.decl_wildcard.remove(name);
scope.declared.insert(name.to_string());
}
None => {
self.global_decl_types
.insert(name.to_string(), ty.to_string());
self.global_decl_generic.remove(name);
self.global_decl_wildcard.remove(name);
}
}
}
/// True when `name` resolves to a real local/parameter in the active scope
/// (rather than an implicit `this.field`). In `main`, every bare name is a
/// global "local".
fn is_local(&self, name: &str) -> bool {
match &self.scope {
Some(scope) => scope.declared.contains(name),
None => true,
}
}
/// True when `name` was actually declared as a variable in the active scope
/// (a real local/parameter, or a `main` global). Distinguishes a variable
/// receiver from a bare stdlib class name like `Math`.
fn is_declared_var(&self, name: &str) -> bool {
match &self.scope {
Some(scope) => scope.declared.contains(name),
None => {
self.global_types.contains_key(name) || self.global_decl_types.contains_key(name)
}
}
}
/// If `name` is not a local but is a field of the enclosing `this` class,
/// return that class — the receiver for an implicit `this.name` access.
fn implicit_this_field(&self, name: &str) -> Option<String> {
if self.is_local(name) {
return None;
}
let this = self.this_class.as_deref()?;
let info = self.classes.get(this)?;
info.field_types
.contains_key(name)
.then(|| this.to_string())
}
/// The declared type string of a variable in the active scope, if known.
fn var_decl_type(&self, name: &str) -> Option<&str> {
match &self.scope {
Some(scope) => scope.decl_types.get(name).map(|s| s.as_str()),
None => self.global_decl_types.get(name).map(|s| s.as_str()),
}
}
/// Record the type arguments a just-declared local carries (see
/// [`MethodScope::decl_generic`]). [`Compiler::declare_local`] has already
/// dropped whatever an earlier same-named local recorded.
fn declare_generic(&mut self, name: &str, generic: Option<String>) {
let Some(g) = generic else {
return;
};
match &mut self.scope {
Some(scope) => scope.decl_generic.insert(name.to_string(), g),
None => self.global_decl_generic.insert(name.to_string(), g),
};
}
/// Record that the local `name` was declared with a wildcard argument.
fn mark_wildcard(&mut self, name: &str) {
match &mut self.scope {
Some(scope) => scope.decl_wildcard.insert(name.to_string()),
None => self.global_decl_wildcard.insert(name.to_string()),
};
}
/// Whether the bare name `name` — resolved as [`Compiler::var_generic`]
/// resolves it — was declared with a wildcard type argument.
fn var_wildcard(&self, name: &str) -> bool {
if self.var_decl_type(name).is_some() {
return match &self.scope {
Some(scope) => scope.decl_wildcard.contains(name),
None => self.global_decl_wildcard.contains(name),
};
}
if let Some(ci) = self.this_class.as_ref().and_then(|t| self.classes.get(t)) {
if ci.field_types.contains_key(name) {
return ci.field_wildcard.contains(name);
}
}
self.static_field_owner(name)
.and_then(|(owner, _)| self.classes.get(&owner))
.is_some_and(|ci| ci.field_wildcard.contains(name))
}
/// Whether the field `recv.name` was declared with a wildcard argument.
fn field_wildcard(&self, recv: &Expr, name: &str) -> bool {
self.recv_class_generic(recv, None)
.and_then(|(rc, _)| self.classes.get(&rc))
.is_some_and(|ci| ci.field_wildcard.contains(name))
}
/// The generic declared type of a local/parameter in the active scope.
fn local_generic(&self, name: &str) -> Option<String> {
match &self.scope {
Some(scope) => scope.decl_generic.get(name).cloned(),
None => self.global_decl_generic.get(name).cloned(),
}
}
/// The generic declared type of a bare name, resolved the way
/// [`Compiler::bare_var_type`] resolves its erased one: a local first (and
/// a local without type arguments hides a generic field), then a field of
/// `this`, then an unqualified `static`.
fn var_generic(&self, name: &str) -> Option<String> {
if let Some(g) = self.lambda_param_override(name) {
return g.contains('<').then_some(g);
}
if self.var_decl_type(name).is_some() {
return self.local_generic(name);
}
if let Some(ci) = self.this_class.as_ref().and_then(|t| self.classes.get(t)) {
if ci.field_types.contains_key(name) {
return ci.field_generic.get(name).map(|(_, g)| g.clone());
}
}
let (owner, _) = self.static_field_owner(name)?;
let (_, g) = self.classes.get(&owner)?.field_generic.get(name)?;
Some(g.clone())
}
/// The static type of `e` with its type arguments, when it has any:
/// `List<Float>` for a local so declared, `Float` for its `get(0)`,
/// `Entry<String,Integer>` for an element of a map's `entrySet()`. This is
/// the part of `javac`'s typing that erasure-at-parse-time used to lose, and
/// [`Compiler::expr_java_type`] reads its erasure.
///
/// Memoized per node for the duration of one outermost query: typing a
/// generic call types each argument both for overload resolution and for
/// inference, which without the memo doubles per level of nesting
/// (`id(id(…id(5)…))`). The memo is dropped when the outermost query
/// returns, so it never outlives the scope it was computed in, and a hit
/// must match the [`memo_fingerprint`] of the node it was computed for,
/// so a temporary the compiler builds at a reused address cannot read
/// another node's answer.
fn expr_generic(&self, e: &Expr) -> Option<String> {
self.memoized(&self.generic_memo, e, |c| c.expr_generic_uncached(e))
}
/// Answer `compute` for `e` through `memo`, which (with every other typing
/// memo) lives only while an outermost typing query is in progress.
fn memoized(
&self,
memo: &TypeMemo,
e: &Expr,
compute: impl FnOnce(&Self) -> Option<String>,
) -> Option<String> {
let key = e as *const Expr as usize;
let print = memo_fingerprint(e);
if let Some((p, t)) = memo.borrow().get(&key) {
if *p == print {
return t.clone();
}
}
self.query_depth.set(self.query_depth.get() + 1);
let t = compute(self);
let depth = self.query_depth.get() - 1;
self.query_depth.set(depth);
if depth == 0 {
self.generic_memo.borrow_mut().clear();
self.java_type_memo.borrow_mut().clear();
} else {
memo.borrow_mut().insert(key, (print, t.clone()));
}
t
}
fn expr_generic_uncached(&self, e: &Expr) -> Option<String> {
match e {
Expr::Var(name) => self.var_generic(name),
// `(List<Float>) o` states the type outright.
Expr::Cast { ty, targs, .. } => with_targs(ty, targs),
// `new Box<Float>(…)` names its arguments; the diamond infers
// them from the constructor's arguments, as `javac` does when no
// target type supplies them (a `var` initializer).
Expr::NewObject {
class, args, targs, ..
} => match targs.as_deref()? {
[] => self.diamond_generic(class, args),
t => with_targs(class, t),
},
Expr::Field { recv, name } => {
if let Some((owner, _)) = self.static_field_ref(e) {
let (_, g) = self.classes.get(&owner)?.field_generic.get(name)?;
return Some(g.clone());
}
let (rc, g) = self.recv_class_generic(recv, self.expr_generic(recv))?;
let (owner, sig) = self.classes.get(&rc)?.field_generic.get(name)?;
Some(self.through_receiver(owner, &rc, g, sig))
}
// A user method declared to return a generic type.
// Asked only of a name with a generic overload, so a nest of plain
// calls (`f(g(h(x)))`) is not typed twice per level.
Expr::Call { name, args, .. } if self.has_generic_return(name) => {
let arg_tys = self.arg_types(args);
let resolved = self.resolve_static_call(name, &arg_tys)?;
let ret = self.ret_generics.get(&resolved.mangled)?;
let (names, types) = self.infer_bindings(&resolved.mangled, args);
Some(subst_tvars(ret, &names, &types))
}
Expr::MethodCall {
recv, method, args, ..
} => {
if let Expr::Var(class) = recv.as_ref() {
if is_static_class(class) && !self.is_declared_var(class) {
return self.jdk_factory_generic(class, method, args);
}
if class == "EnumSet" && !self.is_declared_var(class) {
return self.enum_set_generic(method, args);
}
}
if let Some(class) = self.user_class_ref(recv) {
if !self.has_generic_return(method) {
return None;
}
let arg_tys = self.arg_types(args);
let resolved = self.resolve_static_on(&class, method, &arg_tys)?;
let ret = self.ret_generics.get(&resolved.mangled)?;
let (names, types) = self.infer_bindings(&resolved.mangled, args);
return Some(subst_tvars(ret, &names, &types));
}
// A user type has its own signatures, read through the
// receiver's arguments; the prelude's functional interfaces are
// the JDK's, typed by the table. The receiver's generic type is
// read once, which keeps a long chain linear.
let recv_generic = self.expr_generic(recv);
if let Some(g) = self.call_ret_generic(recv, recv_generic.clone(), method, args) {
return Some(g);
}
// A primitive stream's `boxed()` and `mapToObj(f)` answer a
// `Stream` of the wrapper or of what `f` returns.
if recv_generic.is_none() {
let prim = self.primitive_stream_elem(recv)?;
return match (method.as_str(), args.as_slice()) {
("boxed", []) => Some(format!("Stream<{}>", wrapper_of(prim)?)),
("mapToObj", [f]) => {
let r = self.lambda_result_type(f, &[prim.to_string()])?;
Some(format!("Stream<{r}>"))
}
_ => None,
};
}
let (base, targs) = crate::ast::generic_parts(&recv_generic?);
if self.classes.contains_key(&base) && functional_type_arg_slots(&base).is_none() {
return None;
}
self.generic_member_type(&base, &targs, method, args)
}
_ => None,
}
}
/// The parameter and result types of a user generic functional
/// interface's single abstract method, with the interface's type variables
/// replaced by `targs`: on a `Gen<Integer>`, `T get()` answers `Integer`.
#[allow(clippy::type_complexity)]
fn user_sam_generics(
&self,
iface: &str,
targs: &[String],
) -> Option<(Vec<Option<String>>, Option<String>)> {
let sam = self.functional_sam_meta(iface)?;
let mangled = mangle(&sam.defining, &sam.name, &sam.param_tys);
let tparams = &self.classes.get(&sam.defining)?.type_params;
let sub = |s: &String| subst_tvars(s, tparams, targs);
let ps = match self.param_generics.get(&mangled) {
Some(gs) => gs.iter().map(|g| g.as_ref().map(sub)).collect(),
None => vec![None; sam.param_tys.len()],
};
Some((ps, self.ret_generics.get(&mangled).map(sub)))
}
/// `sig` — a member's declared generic type — as seen through a receiver
/// whose static type is `recv_generic`: the declaring class's type
/// variables are replaced by the receiver's type arguments, so `V get()`
/// on a `Box<Integer>` answers `Integer`.
///
/// A member `owner` declares in a supertype is written in that type's
/// variables, which the `extends`/`implements` clauses between `rc` and
/// `owner` bind: with `class FBox extends Box<Float>`, an `FBox`'s `V get()`
/// is a `Float`. A variable nothing binds keeps its `#T` and reads as
/// `Object`.
fn through_receiver(
&self,
owner: &str,
rc: &str,
recv_generic: Option<String>,
sig: &str,
) -> String {
let Some(info) = self.classes.get(rc) else {
return sig.to_string();
};
// The receiver's own variables, bound by its type arguments when it
// has them and otherwise left as themselves.
let mut args: Vec<String> = match recv_generic.map(|g| crate::ast::generic_parts(&g)) {
Some((base, targs)) if base == rc => targs,
_ => info.type_params.iter().map(|p| format!("#{p}")).collect(),
};
if rc != owner {
match self.supertype_args(rc, &args, owner, 0) {
Some(a) => args = a,
None => return sig.to_string(),
}
}
match self.classes.get(owner) {
Some(oi) => subst_tvars(sig, &oi.type_params, &args),
None => sig.to_string(),
}
}
/// The type arguments `owner` takes as a supertype of `cur` when `cur`'s
/// own variables are `args`, found by walking the `extends` and
/// `implements` clauses (each in its declarer's variables). `None` when
/// `owner` is not a supertype of `cur`.
fn supertype_args(
&self,
cur: &str,
args: &[String],
owner: &str,
depth: usize,
) -> Option<Vec<String>> {
if cur == owner {
return Some(args.to_vec());
}
let ci = self.classes.get(cur)?;
// A malformed cycle cannot reach here from a program `javac` accepts;
// the bound only keeps the walk finite.
if depth > 64 {
return None;
}
let up = |targs: &[String]| -> Vec<String> {
targs
.iter()
.map(|t| subst_tvars(t, &ci.type_params, args))
.collect()
};
let supers = ci
.superclass
.iter()
.map(|s| (s.as_str(), up(&ci.super_targs)))
.chain(ci.interfaces.iter().map(|(i, t)| (i.as_str(), up(t))));
for (sup, sup_args) in supers {
if let Some(found) = self.supertype_args(sup, &sup_args, owner, depth + 1) {
return Some(found);
}
}
None
}
/// The user class a receiver is statically an instance of, with its generic
/// type when it has one — read off the generic type when only that knows
/// the class (`boxes.get(0)` on a `List<Box<Integer>>`).
fn recv_class_generic(
&self,
recv: &Expr,
g: Option<String>,
) -> Option<(String, Option<String>)> {
let rc = self.expr_class(recv).or_else(|| {
let base = crate::ast::generic_parts(g.as_deref()?).0;
self.classes.contains_key(&base).then_some(base)
})?;
Some((rc, g))
}
/// The generic return type of the instance method `rc.method(args)`
/// resolves to, when its declaration names type arguments.
fn instance_ret_generic(
&self,
rc: &str,
method: &str,
args: &[Expr],
) -> Option<(String, String)> {
let arg_tys = self.arg_types(args);
let resolved = self.resolve_instance_call(rc, method, &arg_tys)?;
let meta = self
.classes
.get(rc)?
.methods
.iter()
.find(|m| m.name == method && m.param_tys == resolved.param_tys)?;
let mangled = mangle(&meta.defining, method, &meta.param_tys);
let sig = self.ret_generics.get(&mangled)?;
Some((meta.defining.clone(), sig.clone()))
}
/// The generic parameter types of the instance method `rc.method`
/// overload `param_tys` names, seen through `recv`'s type arguments: on a
/// `Box<Integer>`, `map(Function<V, R>)` takes a `Function<Integer, #R>`.
fn instance_param_generics(
&self,
recv: &Expr,
rc: &str,
method: &str,
param_tys: &[String],
) -> (Vec<Option<String>>, Vec<bool>) {
let Some(meta) = self.classes.get(rc).and_then(|ci| {
ci.methods
.iter()
.find(|m| m.name == method && m.param_tys == param_tys)
}) else {
return (Vec::new(), Vec::new());
};
let mangled = mangle(&meta.defining, method, &meta.param_tys);
let Some(sigs) = self.param_generics.get(&mangled) else {
return (Vec::new(), Vec::new());
};
let g = self.expr_generic(recv);
let generics = sigs
.iter()
.map(|s| {
s.as_ref()
.map(|s| self.through_receiver(&meta.defining, rc, g.clone(), s))
})
.collect();
let wildcards = self
.param_wildcards
.get(&mangled)
.cloned()
.unwrap_or_default();
(generics, wildcards)
}
/// [`Compiler::instance_ret_generic`] seen through `recv`'s own type
/// arguments.
fn call_ret_generic(
&self,
recv: &Expr,
recv_generic: Option<String>,
method: &str,
args: &[Expr],
) -> Option<String> {
let (rc, g) = self.recv_class_generic(recv, recv_generic)?;
let (owner, sig) = self.instance_ret_generic(&rc, method, args)?;
Some(self.through_receiver(&owner, &rc, g, &sig))
}
/// The type a JDK generic type's member answers for a receiver typed
/// `base<targs>`, substituted the way the JDK's own signature declares it
/// (`List<E>.get` is `E`, `Map<K,V>.entrySet` is `Set<Map.Entry<K,V>>`).
/// `None` for a member whose result does not mention a type argument —
/// the erased tables already type those.
fn generic_member_type(
&self,
base: &str,
targs: &[String],
method: &str,
args: &[Expr],
) -> Option<String> {
let arg = |i: usize| targs.get(i).cloned();
let of = |outer: &str, inner: &[String]| -> Option<String> {
(!inner.is_empty()).then(|| format!("{outer}<{}>", inner.join(",")))
};
let elem = || targs.first().map(std::slice::from_ref).unwrap_or(&[]);
let n = args.len();
// `List.remove` is `remove(int)` — the element — exactly when the
// argument is integral below `long`; otherwise it is `remove(Object)`.
let index_arg = || {
args.first()
.and_then(|a| self.expr_java_type(a))
.is_some_and(|t| matches!(t.as_str(), "int" | "short" | "byte" | "char"))
};
let is_list = matches!(
base,
"List" | "ArrayList" | "LinkedList" | "Vector" | "Stack"
);
match (base, method, n) {
("Optional", "get" | "orElseThrow", 0) | ("Optional", "orElse" | "orElseThrow", 1) => {
return arg(0)
}
("Optional", "filter" | "or", 1) => return of("Optional", elem()),
("Iterator" | "ListIterator", "next" | "previous", 0) => return arg(0),
(
"Stream",
"filter" | "sorted" | "distinct" | "limit" | "skip" | "peek" | "takeWhile"
| "dropWhile" | "parallel" | "sequential" | "unordered",
_,
) => return of("Stream", elem()),
("Stream", "findFirst" | "findAny", 0)
| ("Stream", "min" | "max", 1)
| ("Stream", "reduce", 1) => return of("Optional", elem()),
("Stream", "reduce", 2) => return arg(0),
("Stream", "toList", 0) => return of("List", elem()),
// `map(f)` is a `Stream<R>` (an `Optional<U>`) for the `R` the
// lambda's body returns given the element type, and `flatMap(f)`
// what the body returns itself.
("Stream" | "Optional", "map", 1) => {
let r = self.lambda_result_type(&args[0], elem())?;
return Some(format!("{base}<{r}>"));
}
("Stream" | "Optional", "flatMap", 1) => {
let r = self.lambda_result_type(&args[0], elem())?;
return (crate::ast::generic_parts(&r).0 == base).then_some(r);
}
("Stream", _, _) => return None,
("Function", "apply", 1) | ("BiFunction", "apply", 2) => return arg(n),
("UnaryOperator", "apply", 1)
| ("BinaryOperator", "apply", 2)
| ("Supplier" | "Callable", "get" | "call", 0)
| ("IntFunction" | "LongFunction" | "DoubleFunction", "apply", 1) => return arg(0),
_ => {}
}
match (collection_kind(base)?, method, n) {
("list", "get" | "elementAt", 1) if is_list => arg(0),
("list", "remove", 1) if is_list && index_arg() => arg(0),
("list", "set", 2) if is_list => arg(0),
("list", "push", 1) if base == "Stack" => arg(0),
(
"list" | "set" | "pq",
"getFirst" | "getLast" | "removeFirst" | "removeLast" | "peek" | "peekFirst"
| "peekLast" | "poll" | "pollFirst" | "pollLast" | "pop" | "element"
| "firstElement" | "lastElement" | "first" | "last" | "remove",
0,
) => arg(0),
("set", "floor" | "ceiling" | "higher" | "lower", 1) => arg(0),
("list" | "set" | "pq", "stream" | "parallelStream", 0) => of("Stream", elem()),
("list" | "set" | "pq", "iterator" | "descendingIterator", 0)
| ("list", "listIterator", 0 | 1) => of("Iterator", elem()),
("list", "subList", 2) => of("List", elem()),
("list" | "set", "reversed", 0) => of(base, targs),
("set", "headSet" | "tailSet", 1 | 2)
| ("set", "subSet", 2 | 4)
| ("set", "descendingSet", 0) => of("NavigableSet", elem()),
(
"map",
"get" | "remove" | "computeIfAbsent" | "computeIfPresent" | "compute"
| "getOrDefault" | "put" | "putIfAbsent" | "replace" | "merge",
_,
) => match (method, n) {
("get" | "remove", 1)
| ("computeIfAbsent" | "computeIfPresent" | "compute", 2)
| ("getOrDefault" | "put" | "putIfAbsent" | "replace", 2)
| ("merge", 3) => arg(1),
_ => None,
},
("map", "firstKey" | "lastKey", 0)
| ("map", "floorKey" | "ceilingKey" | "higherKey" | "lowerKey", 1) => arg(0),
("map", "keySet" | "navigableKeySet" | "descendingKeySet" | "sequencedKeySet", 0) => {
of("Set", elem())
}
("map", "values" | "sequencedValues", 0) => {
of("Collection", targs.get(1..2).unwrap_or(&[]))
}
("map", "entrySet" | "sequencedEntrySet", 0) => of("Set", &[of("Entry", targs)?]),
("map", "firstEntry" | "lastEntry" | "pollFirstEntry" | "pollLastEntry", 0)
| ("map", "floorEntry" | "ceilingEntry" | "higherEntry" | "lowerEntry", 1) => {
of("Entry", targs)
}
("map", "headMap" | "tailMap", 1 | 2)
| ("map", "subMap", 2 | 4)
| ("map", "descendingMap", 0) => of("NavigableMap", targs),
("map", "reversed", 0) => of(base, targs),
("entry", "getKey", 0) => arg(0),
("entry", "getValue", 0) | ("entry", "setValue", 1) => arg(1),
_ => None,
}
}
/// The generic type a diamond `new C<>(args)` infers: a user class's type
/// variables bound from its constructor's parameters, or a JDK
/// collection's element types copied from the collection it is built from
/// (`new ArrayList<>(aListOfFloat)` is an `ArrayList<Float>`).
fn diamond_generic(&self, class: &str, args: &[Expr]) -> Option<String> {
if let Some(info) = self.classes.get(class) {
let (param_tys, _) = self.resolve_ctor(class, &self.arg_types(args))?;
let mangled = mangle(class, "<init>", ¶m_tys);
let (names, types) = self.infer_bindings(&mangled, args);
let bound: Vec<String> = info
.type_params
.iter()
.map(|p| subst_tvars(&format!("#{p}"), &names, &types))
.collect();
return bound
.iter()
.any(|t| is_known_type(t))
.then(|| format!("{class}<{}>", bound.join(",")));
}
let [src] = args else {
return None;
};
let (base, targs) = crate::ast::generic_parts(&self.expr_generic(src)?);
let (want, have) = (collection_kind(class)?, collection_kind(&base)?);
let same = (want == "map") == (have == "map") && have != "entry";
same.then(|| with_targs(class, &targs)).flatten()
}
/// The generic type a JDK static factory answers when `javac` infers its
/// type argument from the arguments alone: `List.of(0.1f)` is a
/// `List<Float>`, `Map.of("a", 1)` a `Map<String, Integer>`. Arguments of
/// different types meet at a least upper bound javars does not compute, so
/// they type nothing.
fn jdk_factory_generic(&self, class: &str, method: &str, args: &[Expr]) -> Option<String> {
let ty = |a: &Expr| -> Option<String> {
self.expr_generic(a).or_else(|| {
let t = self.expr_java_type(a)?;
Some(wrapper_of(&t).map_or(t.clone(), str::to_string))
})
};
// One type shared by every expression in `es`.
let common = |es: &[&Expr]| -> Option<String> {
let mut tys = es.iter().map(|e| ty(e));
let first = tys.next()??;
(is_known_type(&crate::ast::generic_parts(&first).0) && first != NULL_LITERAL)
.then_some(())?;
tys.all(|t| t.as_deref() == Some(first.as_str()))
.then_some(first)
};
let elems: Vec<&Expr> = args.iter().collect();
let of = |outer: &str, inner: Option<String>| inner.map(|t| format!("{outer}<{t}>"));
match (class, method) {
("List" | "Set" | "Stream", "of") | ("Arrays", "asList") => {
let outer = if class == "Arrays" { "List" } else { class };
// A lone reference array is the varargs array itself.
if let [one] = args {
if let Some(el) = self
.expr_java_type(one)
.and_then(|t| t.strip_suffix("[]").map(str::to_string))
.filter(|el| is_reference_type(el))
{
return of(outer, Some(el));
}
}
of(outer, common(&elems))
}
("Optional", "of" | "ofNullable") | ("Collections", "singletonList") => {
let outer = if class == "Optional" {
"Optional"
} else {
"List"
};
of(outer, common(&elems))
}
("Collections", "singleton") => of("Set", common(&elems)),
("Collections", "nCopies") => of("List", common(elems.get(1..)?)),
("List" | "Set", "copyOf") => {
let (base, targs) = crate::ast::generic_parts(&self.expr_generic(args.first()?)?);
matches!(collection_kind(&base)?, "list" | "set" | "pq")
.then(|| of(class, targs.into_iter().next()))
.flatten()
}
("Map", "of") if args.len() % 2 == 0 && !args.is_empty() => {
let keys: Vec<&Expr> = args.iter().step_by(2).collect();
let vals: Vec<&Expr> = args.iter().skip(1).step_by(2).collect();
Some(format!("Map<{},{}>", common(&keys)?, common(&vals)?))
}
("Map", "entry") if args.len() == 2 => Some(format!(
"Entry<{},{}>",
common(&elems[..1])?,
common(&elems[1..])?
)),
_ => None,
}
}
/// The element type of an expression that is a primitive stream —
/// `int` for `IntStream.range(…)`, `s.chars()`, `mapToInt(…)` — read off
/// the call that made it, the way [`Compiler::stream_is_ref`] reads shape.
fn primitive_stream_elem(&self, e: &Expr) -> Option<&'static str> {
let by_name = |t: &str| match t {
"IntStream" => Some("int"),
"LongStream" => Some("long"),
"DoubleStream" => Some("double"),
_ => None,
};
let Expr::MethodCall {
recv, method, args, ..
} = e
else {
return by_name(&self.expr_java_type(e)?);
};
if let Expr::Var(c) = recv.as_ref() {
if !self.is_declared_var(c) {
if let Some(t) = by_name(c) {
return Some(t);
}
if c == "Arrays" && method == "stream" {
let ty = self.expr_java_type(args.first()?)?;
return match ty.as_str() {
"int[]" => Some("int"),
"long[]" => Some("long"),
"double[]" => Some("double"),
_ => None,
};
}
}
}
match method.as_str() {
"chars" | "codePoints" | "mapToInt" | "flatMapToInt" => Some("int"),
"mapToLong" | "asLongStream" | "flatMapToLong" => Some("long"),
"mapToDouble" | "asDoubleStream" | "flatMapToDouble" => Some("double"),
"filter" | "map" | "sorted" | "distinct" | "limit" | "skip" | "peek" | "parallel"
| "sequential" | "unordered" | "takeWhile" | "dropWhile" => {
self.primitive_stream_elem(recv)
}
_ => None,
}
}
/// The type a lambda parameter has while [`Compiler::lambda_result_type`]
/// types its body.
fn lambda_param_override(&self, name: &str) -> Option<String> {
let ps = self.lambda_param_types.borrow();
ps.iter()
.rev()
.find(|(n, _)| n == name)
.map(|(_, t)| t.clone())
}
/// The static type of what `lambda` returns when its parameters have the
/// types `param_types` — what `javac` infers a functional interface's
/// result variable from (JLS 18.2.1: `ap(1, x -> 0.1f)` binds `R` to
/// `Float`). A primitive result is boxed, as the inference variable is a
/// reference. An expression body is its expression; a block body is its
/// top-level `return` values when they all agree. `None` when the body is
/// not statically typed.
fn lambda_result_type(&self, lambda: &Expr, param_types: &[String]) -> Option<String> {
// A method reference answers as the lambda it abbreviates, when its
// arity is its own.
if let Expr::MethodRef { recv, method, line } = lambda {
let l = self.desugar_method_ref(recv, method, *line).ok()?;
return self.lambda_result_type(&l, param_types);
}
let Expr::Lambda { params, body, .. } = lambda else {
return None;
};
if params.len() != param_types.len() {
return None;
}
// Typing under these parameters changes what the body's nodes mean,
// so the per-query memos are dropped on the way in and out.
let clear = || {
self.generic_memo.borrow_mut().clear();
self.java_type_memo.borrow_mut().clear();
};
clear();
// A parameter whose type is not known is left untyped, as it is when
// the body is lowered without one.
let typed: Vec<(String, String)> = params
.iter()
.cloned()
.zip(param_types.iter().cloned())
.filter(|(_, t)| is_known_type(&crate::ast::generic_parts(t).0))
.collect();
let mut pushed = typed.len();
self.lambda_param_types.borrow_mut().extend(typed);
let result = match body {
LambdaBody::Expr(e) => self.lambda_value_type(e),
LambdaBody::Block(stmts) => {
let mut rets = Vec::new();
pushed += self.block_return_types(stmts, &mut rets);
match rets.split_first() {
Some((first, rest)) if rest.iter().all(|r| r == first) => first.clone(),
_ => None,
}
}
};
{
let mut ps = self.lambda_param_types.borrow_mut();
let keep = ps.len() - pushed;
ps.truncate(keep);
}
clear();
result
}
/// The type a lambda body's value has, boxed — what binds its interface's
/// result variable.
fn lambda_value_type(&self, e: &Expr) -> Option<String> {
self.expr_generic(e)
.filter(|g| is_known_type(&crate::ast::generic_parts(g).0))
.or_else(|| {
let t = self.expr_java_type(e)?;
Some(wrapper_of(&t).map_or(t.clone(), str::to_string))
})
.filter(|t| t != NULL_LITERAL && t != "void")
}
/// The types of the `return` values in a block lambda body, in order,
/// each typed with the locals declared before it in scope — the block's
/// own declarations, which are typed ahead of lowering by pushing them
/// as [`Compiler::lambda_param_types`] overrides. Answers how many it
/// pushed, for the caller to pop.
fn block_return_types(&self, stmts: &[Stmt], out: &mut Vec<Option<String>>) -> usize {
let mut pushed = 0;
let declare = |name: &str, ty: Option<String>, pushed: &mut usize| {
if let Some(t) = ty.filter(|t| t != "var") {
self.lambda_param_types
.borrow_mut()
.push((name.to_string(), t));
self.generic_memo.borrow_mut().clear();
self.java_type_memo.borrow_mut().clear();
*pushed += 1;
}
};
for s in stmts {
match &s.kind {
StmtKind::Local {
ty,
targs,
name,
init,
..
} => {
let t = if ty == "var" {
init.as_ref()
.and_then(|e| self.expr_generic(e).or_else(|| self.expr_java_type(e)))
} else {
Some(with_targs(ty, targs).unwrap_or_else(|| ty.clone()))
};
declare(name, t, &mut pushed);
}
StmtKind::Locals(decls) => pushed += self.block_return_types(decls, out),
StmtKind::Return(Some(e)) => out.push(self.lambda_value_type(e)),
StmtKind::If { then, els, .. } => {
pushed += self.block_return_types(then, out);
pushed += self.block_return_types(els, out);
}
StmtKind::While { body, .. } | StmtKind::DoWhile { body, .. } => {
pushed += self.block_return_types(body, out);
}
StmtKind::For { init, body, .. } => {
pushed += self.block_return_types(init, out);
pushed += self.block_return_types(body, out);
}
StmtKind::ForEach {
ty,
targs,
name,
iter,
body,
..
} => {
let t = if ty == "var" {
self.foreach_elem_generic(iter)
} else {
Some(with_targs(ty, targs).unwrap_or_else(|| ty.clone()))
};
declare(name, t, &mut pushed);
pushed += self.block_return_types(body, out);
}
StmtKind::Labeled { body, .. } => {
pushed += self.block_return_types(std::slice::from_ref(body), out);
}
StmtKind::Try {
body, finally_body, ..
} => {
pushed += self.block_return_types(body, out);
pushed += self.block_return_types(finally_body, out);
}
_ => {}
}
}
pushed
}
/// The `EnumSet<E>` an `EnumSet` factory answers: `E` from a class
/// literal (`allOf`/`noneOf`), from the constants passed (`of`, `range`),
/// or from the set it copies or complements.
fn enum_set_generic(&self, method: &str, args: &[Expr]) -> Option<String> {
let elem = match (method, args) {
("allOf" | "noneOf", [Expr::ClassLit(c)]) => self.class_lit_class(c).to_string(),
("of" | "range", _) => args
.iter()
.filter_map(|a| self.expr_java_type(a))
.find(|t| self.classes.get(t).is_some_and(|ci| ci.is_enum))?,
("copyOf" | "complementOf", [s]) => {
let (_, targs) = crate::ast::generic_parts(&self.expr_generic(s)?);
targs.into_iter().next()?
}
_ => return None,
};
self.classes
.get(&elem)
.is_some_and(|ci| ci.is_enum)
.then(|| format!("EnumSet<{elem}>"))
}
/// The erasure of [`Compiler::expr_generic`] when it says more than
/// `Object` — a type argument or an inferred type variable.
fn known_generic_type(&self, e: &Expr) -> Option<String> {
self.expr_generic(e)
.map(|g| crate::ast::generic_parts(&g).0)
.filter(|t| is_known_type(t))
}
/// The parameter types a lambda literal passed as argument `i` of
/// `recv.method(…)` (of `n` arguments) takes, read off the receiver's type
/// arguments the way the JDK signature declares them: `List<E>.replaceAll`
/// takes a `UnaryOperator<E>`, `Map<K,V>.merge`'s third argument a
/// `BiFunction<V,V,V>`. `None` when the receiver's arguments are unknown or
/// one of them erased to `Object`, which says no more than no hint does.
fn lambda_param_generics(
&self,
recv: &Expr,
method: &str,
n: usize,
i: usize,
) -> Option<Vec<String>> {
// A primitive stream's lambdas take its primitive element: `chars()`
// hands `mapToObj` an `int`, which is what selects the `(int)` overload
// of `Character.toUpperCase` there and its `(char)` one on a
// `Stream<Character>`. A static factory's receiver is the class name,
// not a stream, and is left alone.
let static_recv = matches!(recv, Expr::Var(c) if !self.is_declared_var(c));
if let Some(prim) = self.primitive_stream_elem(recv).filter(|_| !static_recv) {
let one = || Some(vec![prim.to_string()]);
let two = || Some(vec![prim.to_string(), prim.to_string()]);
return match (method, n, i) {
(
"filter" | "map" | "mapToObj" | "mapToInt" | "mapToLong" | "mapToDouble"
| "flatMap" | "forEach" | "forEachOrdered" | "anyMatch" | "allMatch"
| "noneMatch" | "peek" | "takeWhile" | "dropWhile",
1,
0,
) => one(),
("reduce", 1, 0) | ("reduce", 2, 1) => two(),
_ => None,
};
}
let (base, targs) = crate::ast::generic_parts(&self.expr_generic(recv)?);
if self.classes.contains_key(&base) {
return None;
}
let pick = |idx: &[usize]| -> Option<Vec<String>> {
let v: Option<Vec<String>> = idx.iter().map(|&k| targs.get(k).cloned()).collect();
v.filter(|v| v.iter().all(|t| is_known_type(t)))
};
let kind = match base.as_str() {
"Optional" | "Stream" | "Iterator" | "ListIterator" => base.as_str(),
b => collection_kind(b)?,
};
match (kind, method, n, i) {
("list" | "set" | "pq", "forEach" | "removeIf", 1, 0)
| ("list", "replaceAll", 1, 0)
| ("Iterator" | "ListIterator", "forEachRemaining", 1, 0)
| ("Optional", "map" | "flatMap" | "filter" | "ifPresent", 1, 0)
| ("Optional", "ifPresentOrElse", 2, 0)
| ("map", "computeIfAbsent", 2, 1)
| (
"Stream",
"filter" | "map" | "flatMap" | "forEach" | "forEachOrdered" | "anyMatch"
| "allMatch" | "noneMatch" | "peek" | "mapToInt" | "mapToLong" | "mapToDouble"
| "takeWhile" | "dropWhile",
1,
0,
) => pick(&[0]),
("list", "sort", 1, 0)
| ("Stream", "sorted" | "min" | "max", 1, 0)
| ("Stream", "reduce", 1, 0)
| ("Stream", "reduce", 2, 1) => pick(&[0, 0]),
("map", "forEach" | "replaceAll", 1, 0)
| ("map", "computeIfPresent" | "compute", 2, 1) => pick(&[0, 1]),
("map", "merge", 3, 2) => pick(&[1, 1]),
_ => None,
}
}
/// Lower one argument of a JDK generic call, handing a lambda literal the
/// parameter types [`Compiler::lambda_param_generics`] reads for it. A
/// method reference takes them too, for the lambda it desugars to:
/// `Character::toUpperCase` over an `IntStream` is the `(int)` overload,
/// over a `Stream<Character>` the `(char)` one.
fn with_lambda_param_hint(
&mut self,
a: &Expr,
hint: Option<Vec<String>>,
lower: impl FnOnce(&mut Self) -> Result<(), String>,
) -> Result<(), String> {
if matches!(a, Expr::Lambda { .. } | Expr::MethodRef { .. }) {
self.lambda_param_hint = hint;
}
let r = lower(self);
self.lambda_param_hint = None;
r
}
/// Lower an erased call's argument `i` of `n`, handing a method reference
/// the parameter count of the functional interface the JDK method takes
/// there (see [`jdk_functional_arity`]).
fn with_ref_arity_hint(
&mut self,
a: &Expr,
arity: Option<usize>,
lower: impl FnOnce(&mut Self) -> Result<(), String>,
) -> Result<(), String> {
if matches!(a, Expr::MethodRef { .. }) {
self.ref_arity_hint = arity;
}
let r = lower(self);
self.ref_arity_hint = None;
r
}
/// The generic type of one element of `iter`, for an enhanced `for` over a
/// collection whose type arguments are known (`for (var e : m.entrySet())`).
fn foreach_elem_generic(&self, iter: &Expr) -> Option<String> {
let (base, targs) = crate::ast::generic_parts(&self.expr_generic(iter)?);
match collection_kind(&base)? {
"list" | "set" | "pq" => targs.into_iter().next(),
_ => None,
}
}
/// The declared array-type string of an expression (`int[]`, `Shape[]`), if
/// statically known — a local/param variable or an instance field.
fn expr_array_type(&self, e: &Expr) -> Option<String> {
match e {
Expr::Var(name) => {
let ty = self.bare_var_type(name)?;
ty.ends_with("[]").then_some(ty)
}
Expr::Field { recv, name } => {
if let Some((_, ty)) = self.static_field_ref(e) {
return ty.ends_with("[]").then_some(ty);
}
let rc = self.expr_class(recv)?;
let ft = self.classes.get(&rc)?.field_types.get(name)?;
ft.ends_with("[]").then(|| ft.clone())
}
// `Color.values()` hands back a `Color[]`.
Expr::MethodCall {
recv, method, args, ..
} if method == "values" && args.is_empty() => self
.enum_type_ref(recv)
.map(|c| format!("{c}[]"))
.or_else(|| {
self.is_rounding_mode_ref(recv)
.then(|| "RoundingMode[]".to_string())
}),
Expr::Call { name, args, line } => match self.implicit_enum_static(name, args, *line) {
Some(call) => self.expr_array_type(&call),
None => self.expr_java_type(e).filter(|t| t.ends_with("[]")),
},
// A row of a multi-dimensional array: `int[][]` indexed once is an
// `int[]`, so `g[i][j]` types its element as `int`.
Expr::Index { array, .. } => {
let outer = self.expr_array_type(array)?;
let inner = outer.strip_suffix("[]")?;
inner.ends_with("[]").then(|| inner.to_string())
}
// Any other expression whose static type is an array — a call such
// as `Character.toChars(66)` or `s.toCharArray()` — so indexing its
// result straight away types the element (`toChars(66)[0]` is the
// `char` `B`, not the code point 66).
_ => self.expr_java_type(e).filter(|t| t.ends_with("[]")),
}
}
/// The user-class name an expression statically evaluates to (for instance
/// method/field dispatch), or `None` when it is not a known class type.
fn expr_class(&self, e: &Expr) -> Option<String> {
match e {
Expr::This => self.this_class.clone(),
Expr::Var(name) => {
let ty = self.bare_var_type(name)?;
self.classes.contains_key(&ty).then_some(ty)
}
Expr::Field { recv, name } => {
if let Some(class) = self.enum_constant_ref(e) {
return Some(class);
}
if let Some((_, ty)) = self.static_field_ref(e) {
return self.classes.contains_key(&ty).then_some(ty);
}
let rc = self.expr_class(recv)?;
let ty = self.classes.get(&rc)?.field_types.get(name)?;
self.classes.contains_key(ty).then(|| ty.to_string())
}
// Only a *user* class, on the rule every other arm here follows:
// `new ArrayList<>()` and `new Object()` are host values rather than
// class instances with a method table, so naming their type here
// would route `new ArrayList<>().size()` into user-class dispatch and
// reject it. (`Compiler::expr_java_type` still reports the type.)
Expr::NewObject { class, .. } => {
self.classes.contains_key(class).then(|| class.clone())
}
// A cast states the class outright, which is how `((Animal) x)`
// reaches `Animal`'s methods and how `println((Dog) a)` finds the
// `toString` override.
Expr::Cast { ty, expr, .. } => self
.classes
.contains_key(ty)
.then(|| ty.clone())
// A cast to a type javars does not model as a class (`Object`)
// does not erase what the operand is, so `println((Object) dog)`
// still finds `Dog`'s `toString`.
.or_else(|| self.expr_class(expr)),
// An element of a class-typed array (`Shape[] → Shape`).
Expr::Index { array, .. } => {
let arr_ty = self.expr_array_type(array)?;
let elem = arr_ty.strip_suffix("[]")?;
self.classes.contains_key(elem).then(|| elem.to_string())
}
// A bare call to a user `static` method: its declared return type.
Expr::Call { name, args, line } => {
if let Some(call) = self.implicit_enum_static(name, args, *line) {
return self.expr_class(&call);
}
let arg_tys: Vec<Option<String>> = self.arg_types(args);
let ret = self.resolve_static_call(name, &arg_tys)?.ret_name;
self.classes.contains_key(&ret).then_some(ret)
}
Expr::MethodCall {
recv, method, args, ..
} => {
if let Some(call) = self.enum_class_value_of(recv, method, args, 0) {
return self.expr_class(&call);
}
if let Some(t) = self.enum_static_type(recv, method, args.len()) {
return self.classes.contains_key(&t).then_some(t);
}
if let Some(class) = self.user_class_ref(recv) {
let arg_tys: Vec<Option<String>> = self.arg_types(args);
let ret = self.resolve_static_on(&class, method, &arg_tys)?.ret_name;
return self.classes.contains_key(&ret).then_some(ret);
}
let rc = self.expr_class(recv)?;
let arg_tys: Vec<Option<String>> = self.arg_types(args);
let ret_name = self.resolve_instance_call(&rc, method, &arg_tys)?.ret_name;
self.classes.contains_key(&ret_name).then_some(ret_name)
}
_ => None,
}
}
/// The direct superclass of the class whose body is being compiled — the
/// type `super` reads at. `None` outside an instance member, and for a class
/// whose parent is the implicit `java.lang.Object` (which javars keeps out
/// of the class table on purpose; see `new_object_as`).
fn super_class(&self) -> Option<String> {
let this = self.this_class.as_deref()?;
self.classes.get(this)?.superclass.clone()
}
/// The declared type-name of a bare variable read `name`: a local/param/
/// global declared type, else an instance field of the enclosing `this`.
fn bare_var_type(&self, name: &str) -> Option<String> {
// `super` and `this` are the same object; only the *static* type they
// are read at differs. Typing it as the superclass is what resolves
// `super.field` and the result type of `super.m()` one level up — and
// `super` cannot be shadowed, because it is a Java reserved word.
if name == SUPER {
return self.super_class();
}
if let Some(g) = self.lambda_param_override(name) {
return Some(crate::ast::generic_parts(&g).0);
}
if let Some(t) = self.var_decl_type(name) {
return Some(t.to_string());
}
if let Some(class) = self.enclosing_enum_constant(name) {
return Some(class);
}
if let Some(this) = self.this_class.as_ref() {
if let Some(t) = self
.classes
.get(this)
.and_then(|ci| ci.field_types.get(name))
{
return Some(t.clone());
}
}
// An unqualified `static` field of the enclosing class.
if let Some((_, ty)) = self.static_field_owner(name) {
return Some(ty);
}
// A field of an enclosing instance, from an inner class.
let (_, owner) = self.outer_field_recv(name)?;
self.classes.get(&owner)?.field_types.get(name).cloned()
}
/// The static Java type-name of an expression (`int`, `double`, `boolean`,
/// `String`, a class/interface name, an array type, `null`), or `None` when
/// it cannot be determined statically. Drives overload resolution by argument
/// type; an unknown type falls back to arity-only matching at the call site.
/// The binary name a `T.class` literal evaluates to.
///
/// A class is its binary name here, so this has to agree with what
/// `x.getClass()` produces for an instance of the same type — a DECLARED
/// class answers from the nesting-aware `binary` the compiler already keeps
/// (`T$A` for a nested one), and everything else is left as written for the
/// host to qualify the way it qualifies a runtime class name. A primitive
/// (`int.class`) is its own keyword and stays as it is.
/// The class a class literal's spelling names: `Outer.Inner.class` names
/// the nested type through its enclosers, which javars keys by the simple
/// name — so a chain of user classes is the class its last segment names.
/// Any other spelling is itself.
fn class_lit_class<'a>(&self, name: &'a str) -> &'a str {
match name.rsplit_once('.') {
Some((_, last)) if name.split('.').all(|s| self.classes.contains_key(s)) => last,
_ => name,
}
}
fn class_literal_name(&self, name: &str) -> String {
let name = self.class_lit_class(name);
// A qualified spelling (`java.util.List.class`) is already the name.
if let Some(c) = self.classes.get(name) {
// A type the prelude declares (a functional interface, a throwable)
// names its JDK package, not its bare simple name.
let functional = if c.is_interface {
crate::prelude::qualified_functional(name)
} else {
None
};
return crate::prelude::qualified_class(name)
.or(functional)
.unwrap_or_else(|| c.binary.clone());
}
crate::host::qualify_class_name(name)
}
/// The static types of a call's arguments, as overload resolution sees
/// them. A bare `null` is the null type (JLS 4.1): assignable to every
/// reference parameter and to no primitive one, which is what lets
/// `f(null)` pick `f(String)` over `f(Object)`. It is typed here rather
/// than in [`Compiler::expr_java_type`] because only a call site asks
/// "which reference parameters can this reach".
fn arg_types(&self, args: &[Expr]) -> Vec<Option<String>> {
args.iter()
.map(|a| match a {
Expr::Var(n) if n == NULL_LITERAL => Some(NULL_LITERAL.to_string()),
_ => self.expr_java_type(a),
})
.collect()
}
/// Memoized like [`Compiler::expr_generic`], within the same outermost
/// query: the two call each other on every subexpression of a call nest,
/// and an unmemoized one would type the whole nest again at every level.
fn expr_java_type(&self, e: &Expr) -> Option<String> {
self.memoized(&self.java_type_memo, e, |c| c.expr_java_type_uncached(e))
}
fn expr_java_type_uncached(&self, e: &Expr) -> Option<String> {
match e {
Expr::Int(_) => Some("int".to_string()),
Expr::Long(_) => Some("long".to_string()),
Expr::Float(_) => Some("double".to_string()),
Expr::Float32(_) => Some("float".to_string()),
Expr::Bool(_) => Some("boolean".to_string()),
Expr::Str(_) => Some("String".to_string()),
Expr::Char(_) => Some("char".to_string()),
Expr::This => self.this_class.clone(),
Expr::Var(name) => self.bare_var_type(name),
Expr::Unary { op, rhs } => match op {
// Unary numeric promotion (JLS 5.6.1): `+x`, `-x` and `~x` widen
// `byte`/`short`/`char` to `int` and leave every other type
// alone — a `double` operand stays `double`.
UnOp::Neg | UnOp::BitNot | UnOp::Plus => {
match self.expr_java_type(rhs).as_deref() {
Some("byte" | "short" | "char") => Some("int".to_string()),
other => other.map(|s| s.to_string()),
}
}
UnOp::Not => Some("boolean".to_string()),
},
Expr::Cast { ty, .. } => Some(ty.clone()),
Expr::Binary { op, lhs, rhs } => match op {
BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Mod => {
let l = self.expr_java_type(lhs);
let r = self.expr_java_type(rhs);
// `+` with a String operand is concatenation.
if matches!(op, BinOp::Add)
&& (l.as_deref() == Some("String") || r.as_deref() == Some("String"))
{
return Some("String".to_string());
}
let lr = l.as_deref().and_then(numeric_rank)?;
let rr = r.as_deref().and_then(numeric_rank)?;
Some(rank_name(lr.max(rr)).to_string())
}
// `&`/`|`/`^` are bitwise on integral operands and logical on
// booleans; the operand type decides which.
BinOp::BitAnd | BinOp::BitOr | BinOp::BitXor => {
let l = self.expr_java_type(lhs);
let r = self.expr_java_type(rhs);
if l.as_deref() == Some("boolean") || r.as_deref() == Some("boolean") {
return Some("boolean".to_string());
}
let lr = l.as_deref().and_then(numeric_rank)?;
let rr = r.as_deref().and_then(numeric_rank)?;
Some(rank_name(lr.max(rr)).to_string())
}
// A shift promotes only its *left* operand — `1L << 2` is a
// `long`, but `1 << 2L` is still an `int`.
BinOp::Shl | BinOp::Shr | BinOp::Ushr => {
match self.expr_java_type(lhs).as_deref() {
Some("long") => Some("long".to_string()),
Some(t) if numeric_rank(t).is_some() => Some("int".to_string()),
_ => None,
}
}
_ => Some("boolean".to_string()),
},
Expr::Ternary { then, els, .. } => {
let t = self.expr_java_type(then);
let e2 = self.expr_java_type(els);
if t == e2 {
return t;
}
// `flag ? "s" : null` has the other branch's type — boxed when
// that branch is a primitive (JLS 15.25, Table 15.25-A).
let is_null = |e: &Expr| matches!(e, Expr::Var(n) if n == NULL_LITERAL);
let other = match (is_null(then), is_null(els)) {
(true, false) => Some(e2.as_deref()),
(false, true) => Some(t.as_deref()),
_ => None,
};
if let Some(other) = other {
return other.map(|ty| wrapper_of(ty).unwrap_or(ty).to_string());
}
// JLS 15.25.2, the numeric conditional. Wrappers unbox first.
let (tp, ep) = (unwrapped_ty(t.as_deref()?), unwrapped_ty(e2.as_deref()?));
// A primitive against a reference that is no wrapper makes the
// conditional a reference one (JLS 15.25.3): the primitive boxes
// and the type is the lub of the two, which no call can tell
// from `Object`. Left untyped, an overloaded call taking it
// found no applicable method.
let primitive = |ty: &str| wrapper_of(ty).is_some();
if primitive(tp) != primitive(ep)
&& is_reference_type(if primitive(tp) { ep } else { tp })
{
return Some("Object".to_string());
}
let (tr, er) = (numeric_rank(tp)?, numeric_rank(ep)?);
if tp == ep {
return Some(tp.to_string());
}
// A `byte` against a `short` is a `short`.
if matches!((tp, ep), ("byte", "short") | ("short", "byte")) {
return Some("short".to_string());
}
// A `byte`/`short`/`char` against an `int` *constant* that fits
// it keeps the narrow type, so `flag ? 'a' : 98` prints `a`/`b`
// rather than 97/98. A non-constant `int` promotes as usual.
let fits = |ty: &str, e: &Expr| match (ty, e) {
("byte", Expr::Int(n)) => (-128..=127).contains(n),
("short", Expr::Int(n)) => (-32768..=32767).contains(n),
("char", Expr::Int(n)) => (0..=0xFFFF).contains(n),
_ => false,
};
if (ep == "int" && fits(tp, els)) || (tp == "int" && fits(ep, then)) {
return Some(if ep == "int" { tp } else { ep }.to_string());
}
// Otherwise binary numeric promotion: nothing narrower than `int`.
Some(rank_name(tr.max(er).max(3)).to_string())
}
Expr::Field { recv, name } => {
if let Some(class) = self.qualified_this(e) {
return Some(class.to_string());
}
if name == "length" {
return Some("int".to_string());
}
if let Some((_, ty)) = self.library_constant(e) {
return Some(ty.to_string());
}
if let Some((_, ty)) = self.wrapper_constant_ref(e) {
return Some(ty.to_string());
}
if let Some(class) = self.enum_constant_ref(e) {
return Some(class);
}
if let Some((_, ty)) = self.static_field_ref(e) {
return Some(ty);
}
// A field typed by a type variable, read through a receiver
// whose type arguments bind it: `Box<Float>`'s `V v` is a
// `Float`.
if let Some(t) = self
.expr_generic(e)
.map(|g| crate::ast::generic_parts(&g).0)
.filter(|t| is_known_type(t))
{
return Some(t);
}
let rc = self.expr_class(recv)?;
self.classes.get(&rc)?.field_types.get(name).cloned()
}
Expr::Index { array, .. } => {
let arr_ty = self.expr_array_type(array)?;
arr_ty.strip_suffix("[]").map(|s| s.to_string())
}
Expr::NewObject { class, .. } => Some(class.clone()),
Expr::NewArray {
elem_ty,
sizes,
extra_dims,
} => Some(format!(
"{elem_ty}{}",
"[]".repeat(sizes.len() + extra_dims)
)),
// `new int[]{…}` named its element type; a bare `{…}` did not, and
// takes its type from the declaration it initializes instead.
Expr::ArrayLit { elem_ty, .. } => elem_ty.as_ref().map(|t| format!("{t}[]")),
Expr::InstanceOf { .. } => Some("boolean".to_string()),
Expr::SwitchExpr { arms, .. } => self.switch_expr_type(arms),
Expr::PostIncDec { name, .. } | Expr::PreIncDec { name, .. } => {
self.bare_var_type(name)
}
// `a[i]++` is the element's type, `p.n++` the field's — the update
// never changes it (`char c; c++` stays a `char`).
Expr::IncDec { target, .. } => self.expr_java_type(target),
// An assignment's value has the target's type (JLS 15.26).
Expr::Assign { target, .. } => self.expr_java_type(target),
Expr::Call { name, args, line } => {
if let Some(call) = self.implicit_enum_static(name, args, *line) {
return self.expr_java_type(&call);
}
// A generic method's result through what its arguments bind:
// `first(aListOfFloat)` is a `Float`.
if let Some(t) = self.known_generic_type(e) {
return Some(t);
}
let arg_tys: Vec<Option<String>> = self.arg_types(args);
self.resolve_static_call(name, &arg_tys).map(|s| s.ret_name)
}
Expr::MethodCall {
recv, method, args, ..
} => {
if let Some(call) = self.enum_class_value_of(recv, method, args, 0) {
return self.expr_java_type(&call);
}
if let Some(t) = self.enum_static_type(recv, method, args.len()) {
return Some(t);
}
// A generic member on a receiver whose type arguments are
// known: `List<Float>.get` is a `Float`, and so is
// `Supplier<Float>.get` although the prelude declares that
// interface's `get` as answering `Object` — or a generic
// method's result through what its arguments bind.
if let Some(t) = self.known_generic_type(e) {
return Some(t);
}
// `T.helper(x)` — the named class's `static` method, resolved in
// that class's own inheritance chain.
if let Some(class) = self.user_class_ref(recv) {
let arg_tys: Vec<Option<String>> = self.arg_types(args);
return self
.resolve_static_on(&class, method, &arg_tys)
.map(|s| s.ret_name);
}
// A bare stdlib class receiver (`Integer.parseInt`) is a static
// call whose declared return type is known.
if let Expr::Var(class) = recv.as_ref() {
if is_static_class(class) && !self.is_declared_var(class) {
// `Arrays.copyOf`/`copyOfRange` return an array of the
// *source's* element type, which is what keeps a
// `char[]` copy rendering as characters.
if class == "Arrays"
&& matches!(method.as_str(), "copyOf" | "copyOfRange")
&& !args.is_empty()
{
return self.expr_java_type(&args[0]);
}
// `Math.round` is `long` over a `double` and `int` over
// a `float`, so the argument picks the return type —
// and only the `int` answer may take the 32-bit wrap.
if class == "Math" && method == "round" && args.len() == 1 {
return Some(if self.is_float32_expr(&args[0]) {
"int".to_string()
} else {
"long".to_string()
});
}
// The `float` overloads of the bit-pattern statics answer a
// `float` (`getExponent(float)` its `int`), so the result
// prints through `Float.toString`.
if self.math_float_overload(class, method, args) {
let t = if method == "getExponent" {
"int"
} else {
"float"
};
return Some(t.to_string());
}
// The width-overloaded family answers at the width its
// arguments selected, so `Math.addExact(1L, 2L)` is a
// `long` where `Math.addExact(1, 2)` is an `int` — and
// `Math.clamp(0.1f, 0f, 3f)` is a `float`, which is what
// makes it print `0.1` rather than the `double` widening.
// The case maps are overloaded `(char)` and `(int)`, and
// answer in the argument's type: `toUpperCase('a')` is
// the `char` `A`, `toUpperCase(97)` the `int` 65. A
// `byte`/`short` argument does not widen to `char`, so
// it too selects the `int` overload.
if class == "Character"
&& matches!(
method.as_str(),
"toUpperCase" | "toLowerCase" | "toTitleCase"
)
&& args.len() == 1
{
let ty = self.expr_java_type(&args[0]);
let char_arg = ty
.as_deref()
.is_none_or(|t| matches!(t, "char" | "Character"));
return Some(if char_arg { "char" } else { "int" }.to_string());
}
if let Some(t) = self.width_overload_java_type(class, method, args) {
return Some(t.to_string());
}
if let Some(t) = static_call_java_type(class, method) {
return Some(t.to_string());
}
// `Math.abs`/`max`/`min` are overloaded on every numeric
// type and return the promotion of their arguments —
// `abs(int)` is an `int` (and so wraps), `abs(long)` is
// not. Unknown argument types leave the result unknown.
if class == "Math"
&& matches!(
method.as_str(),
"scale"
| "precision"
| "stripTrailingZeros"
| "toPlainString"
| "unscaledValue"
| "toBigInteger"
| "plus"
| "ulp"
| "negate"
| "abs"
| "signum"
| "not"
| "bitLength"
| "bitCount"
| "max"
| "min"
)
{
let ranks: Option<Vec<u32>> = args
.iter()
.map(|a| self.expr_java_type(a).as_deref().and_then(numeric_rank))
.collect();
return ranks
.map(|r| rank_name(r.into_iter().max().unwrap_or(3)).to_string());
}
return None;
}
}
let arg_tys: Vec<Option<String>> = self.arg_types(args);
if let Some(rc) = self.expr_class(recv) {
if let Some(r) = self.resolve_instance_call(&rc, method, &arg_tys) {
return Some(r.ret_name);
}
}
// The receiver is typed once: every table below reads it, and
// a chained call (`s.filter(…).map(…)…`) would otherwise type
// each receiver once per table, exponentially in the chain.
let recv_ty = self.expr_java_type(recv);
// A `StringBuilder` receiver's known return types. `append` and
// friends answer the receiver, which is what makes the chained
// `sb.append(1).append('a')` keep its type — and `charAt` must
// report `char`, or the code point it answers would print as a
// number.
if let Some(t) = recv_ty
.as_deref()
.and_then(|t| builder_call_java_type(t, method, args.len()))
{
return Some(t.to_string());
}
if let Some(t) = recv_ty
.as_deref()
.and_then(|t| input_call_java_type(t, method))
{
return Some(t.to_string());
}
// A collection receiver's known return types.
if let Some(kind) = recv_ty.as_deref().and_then(collection_kind) {
if let Some(t) = collection_call_java_type(kind, method, args.len()) {
return Some(t.to_string());
}
return None;
}
// A boxed primitive's own methods. `charValue()` in particular
// must report `char`, or the code point it answers would print
// as a number.
if let Some(t) = boxed_call_java_type(method, args.len()) {
return Some(t.to_string());
}
// A `String` receiver's known return types.
match (method.as_str(), args.len()) {
("length", 0)
| ("indexOf", 1)
| ("compareTo", 1)
| ("compareToIgnoreCase", 1) => Some("int".to_string()),
("isEmpty", 0)
| ("contains", 1)
| ("equals", 1)
| ("startsWith", 1)
| ("endsWith", 1)
| ("equalsIgnoreCase", 1) => Some("boolean".to_string()),
("substring", _)
| ("toUpperCase", 0)
| ("toLowerCase", 0)
| ("trim", 0)
| ("concat", 1)
| ("replace", 2)
| ("repeat", 1) => Some("String".to_string()),
("charAt", 1) => Some("char".to_string()),
("toCharArray", 0) => Some("char[]".to_string()),
("getBytes", 0 | 1) => Some("byte[]".to_string()),
_ => None,
}
}
_ => None,
}
}
/// Look up the declared numeric type of `name`, defaulting to `Other` when
/// unknown (an undeclared read, or a type javars does not track). A name
/// that is not a local falls back to whatever the enclosing class makes it —
/// an instance field of `this` or a `static` field — so a bare `int` field
/// truncates its division the same way an `int` local does.
fn lookup_type(&self, name: &str) -> NumType {
if let Some(g) = self.lambda_param_override(name) {
return numtype_of_ty(&crate::ast::generic_parts(&g).0).unwrap_or(NumType::Other);
}
let map = match &self.scope {
Some(scope) => &scope.types,
None => &self.global_types,
};
if let Some(nt) = map.get(name) {
return *nt;
}
self.bare_var_type(name)
.as_deref()
.and_then(numtype_of_ty)
.unwrap_or(NumType::Other)
}
/// Mint a unique internal temp name (`#t0`, `#t1`, …). `#` is not a legal
/// Java identifier char, so these never collide with user variables.
fn temp(&mut self) -> String {
let t = format!("#t{}", self.temp_counter);
self.temp_counter += 1;
t
}
/// The conversion cost from static type `from` to a parameter type `to`, or
/// `None` when `from` is not assignable to `to`. `0` is an identity match;
/// numeric widening costs the rank distance; a reference upcast costs its
/// subtype distance. Lower cost = more specific (drives overload resolution).
fn assign_cost(&self, from: &str, to: &str) -> Option<u32> {
if from == to {
return Some(0);
}
// Phase 1 is *primitive* widening only (JLS 5.1.2). A wrapper is not a
// primitive here: `Integer` reaching an `int` parameter is unboxing,
// which belongs to phase 2 below, so `f(1)` against `f(int)`/`f(Integer)`
// picks `f(int)` at cost 0 instead of tying with the wrapper.
if !is_reference_type(from) && !is_reference_type(to) {
return primitive_widening_cost(from, to);
}
if from == "null" {
return is_reference_type(to).then_some(50);
}
if let Some(d) = self.subtype_distance(from, to) {
return Some(d);
}
if from == "String" && matches!(to, "Object" | "CharSequence") {
return Some(1);
}
// A modeled JDK type reaches its JDK supertypes (`StringBuilder` is a
// `CharSequence`, an `ArrayList` a `Collection`).
if !self.classes.contains_key(from) {
if let Some(d) = crate::host::jdk_subtype_distance(from, to) {
return Some(d);
}
}
if to == "Object" && is_reference_type(from) {
return Some(40);
}
// Boxing — Java's *second* resolution phase. A primitive converts to its
// wrapper and then widens like any other reference, which is what makes
// `f(1)` reach an `f(Object)` (and `h(1, 2)` reach an `h(Object... xs)`)
// at all. Priced above every widening conversion so a phase-1 match
// always wins: `f(double)` still beats `f(Object)` for `f(1)`.
const BOX: u32 = 60;
if let Some(w) = wrapper_of(from) {
if w == to {
return Some(BOX);
}
if let Some(d) = self.subtype_distance(w, to) {
return Some(BOX + d);
}
let numeric = numeric_rank(from).is_some();
if to == "Object" || to == "Comparable" || (to == "Number" && numeric) {
return Some(BOX + 1);
}
}
let prim = unwrapped_ty(from);
if prim != from {
// A wrapper is a class: it widens to its own supertypes in phase 1
// (`Long` reaches `Number` without unboxing, so `n(Long)` picks
// `n(Number)` over `n(double)`).
if to == "Comparable" || (to == "Number" && numeric_rank(prim).is_some()) {
return Some(1);
}
// Unboxing, then primitive widening (JLS 5.3): `Integer` reaches
// `int` and `long`, never `short` and never another wrapper.
if !is_reference_type(to) {
return primitive_widening_cost(prim, to).map(|c| BOX + c);
}
}
None
}
/// The number of supertype hops from `from` up to `to` (0 when equal), or
/// `None` when `to` is not a supertype of `from`. Walks superclass +
/// interface edges breadth-first for the shortest path.
fn subtype_distance(&self, from: &str, to: &str) -> Option<u32> {
if from == to {
return Some(0);
}
let mut frontier = vec![from.to_string()];
let mut seen = HashSet::default();
let mut dist = 0u32;
while !frontier.is_empty() {
dist += 1;
let mut next = Vec::new();
for cur in &frontier {
if let Some(ci) = self.classes.get(cur) {
for sup in &ci.supertypes {
if sup == to {
return Some(dist);
}
if seen.insert(sup.clone()) {
next.push(sup.clone());
}
}
}
}
frontier = next;
if dist > 10000 {
return None;
}
}
None
}
/// Choose the most-specific applicable overload for argument types `arg_tys`
/// among candidates whose parameter-type lists are `cands`. Returns the index
/// into `cands`, or an error naming the failure (none applicable / ambiguous).
/// An argument whose static type is unknown (`None`) matches any parameter
/// without contributing to specificity.
fn pick_overload(
&self,
cands: &[(&[String], bool)],
arg_tys: &[Option<String>],
) -> Result<usize, NoPick> {
// javars does not type-check (see BUGS.md), so a lone *fixed-arity*
// candidate of the right arity is taken whether or not its parameters
// accept the arguments — a `javac` type error may still run. A lone
// *variable-arity* candidate is not the same question: whether its
// declared `T[]` accepts the argument is precisely what separates
// `sum(intArray)` (passed straight through) from `sum(1)` (packed), so
// there applicability has to be checked.
if matches!(cands, [(_, false)]) {
return Ok(0);
}
let scored: Vec<(usize, u32)> = cands
.iter()
.enumerate()
.filter_map(|(i, (ptys, _))| self.signature_cost(ptys, arg_tys).map(|c| (i, c)))
.collect();
match Self::most_specific(scored.iter().copied()) {
Err(NoPick::Ambiguous) if arg_tys.iter().all(Option::is_some) => {
// A cost tie is settled by JLS 15.12.2.5 specificity: `f(null)`
// against `f(Object)`/`f(String)` costs the same for both, and
// `f(String)` wins because `String` converts to `Object` and not
// the reverse. Only when every argument's static type is known —
// an unknown one would let the tie-break pick for a type javars
// never saw, turning a refusal into a guess.
let best = scored.iter().map(|&(_, c)| c).min().unwrap_or(0);
let tied: Vec<usize> = scored
.iter()
.filter(|&&(_, c)| c == best)
.map(|&(i, _)| i)
.collect();
let mut winners = tied.iter().filter(|&&i| {
tied.iter()
.all(|&j| self.fixed_at_least_as_specific(cands[i].0, cands[j].0))
});
match (winners.next(), winners.next()) {
(Some(&i), None) => Ok(i),
_ => Err(NoPick::Ambiguous),
}
}
other => other,
}
}
/// Java's three resolution phases over one candidate set, in order: the
/// fixed-arity ones first, and the variable-arity one **only** when they
/// find nothing applicable. Returns the winning candidate's index and, for
/// a variable-arity win, the argument index where call-site packing starts.
///
/// This is the single entry point for all three kinds of user-declared
/// callable — `static` methods, instance methods, and constructors — so a
/// `T...` declaration means the same thing wherever it sits.
fn resolve_overload(
&self,
cands: &[(&[String], bool)],
arg_tys: &[Option<String>],
) -> Option<(usize, Option<usize>)> {
let of_arity: Vec<usize> = (0..cands.len())
.filter(|&i| cands[i].0.len() == arg_tys.len())
.collect();
let fixed: Vec<(&[String], bool)> = of_arity.iter().map(|&i| cands[i]).collect();
match self.pick_overload(&fixed, arg_tys) {
Ok(i) => Some((of_arity[i], None)),
Err(NoPick::Ambiguous) => None,
Err(NoPick::Inapplicable) => {
let (i, from) = self.pick_varargs(cands, arg_tys)?;
Some((i, Some(from)))
}
}
}
/// The total conversion cost of passing `arg_tys` to a fixed-arity
/// parameter list, or `None` when some argument is not assignable. An
/// argument whose static type is unknown matches any parameter without
/// contributing to specificity.
fn signature_cost(&self, ptys: &[String], arg_tys: &[Option<String>]) -> Option<u32> {
let mut total = 0;
for (p, a) in ptys.iter().zip(arg_tys) {
if let Some(at) = a {
total += self.assign_cost(at, p)?;
}
}
Some(total)
}
/// The single cheapest candidate out of `(index, cost)` pairs — Java's
/// most-specific rule, approximated by conversion cost. A tie is
/// [`NoPick::Ambiguous`]; an empty set is [`NoPick::Inapplicable`].
fn most_specific(scored: impl Iterator<Item = (usize, u32)>) -> Result<usize, NoPick> {
let mut best: Option<(usize, u32)> = None;
let mut tie = false;
for (i, cost) in scored {
match best {
Some((_, bc)) if cost > bc => {}
Some((_, bc)) if cost == bc => tie = true,
_ => {
best = Some((i, cost));
tie = false;
}
}
}
match best {
Some((i, _)) if !tie => Ok(i),
Some(_) => Err(NoPick::Ambiguous),
None => Err(NoPick::Inapplicable),
}
}
/// Java's **third** resolution phase (JLS 15.12.2.4), run only after both
/// fixed-arity phases report [`NoPick::Inapplicable`].
///
/// A candidate declared `(P0 … Pk-1, T[]…)` is applicable to `n ≥ k`
/// arguments when each of the first `k` is assignable to its own parameter
/// and every remaining one is assignable to the *component* type `T`. The
/// winner's trailing arguments are packed into a `T[]` at the call site.
///
/// Ordering matters and is not an implementation detail: because this phase
/// never runs while a fixed-arity candidate applies, `f(int,int)` beats
/// `f(int...)` for `f(1,2)`, and `sum(new int[]{1,2})` against
/// `sum(int... xs)` is a *fixed-arity* match on the declared `int[]` — so
/// the array passes straight through instead of being wrapped, which is
/// exactly what Java does (and why `f(null)` against `f(Object... xs)`
/// passes `null` as the whole array rather than an array holding `null`).
///
/// Among applicable variable-arity candidates the cheaper conversion wins.
/// A tie is settled by JLS 15.12.2.5 specificity over the *expanded*
/// parameter lists ([`Compiler::at_least_as_specific`]) — which is what
/// picks `h(String...)` over `h(Object...)` for the zero-argument `h()`,
/// where both convert at no cost. Mutually-specific candidates are
/// genuinely ambiguous and select nothing, exactly as `javac` reports for
/// `g(int, int...)` against `g(int...)`.
///
/// Returns the winning index and the argument index packing starts at.
fn pick_varargs(
&self,
cands: &[(&[String], bool)],
arg_tys: &[Option<String>],
) -> Option<(usize, usize)> {
let n = arg_tys.len();
let applicable = self.varargs_applicable(cands, arg_tys);
let best = applicable.iter().map(|&(_, c)| c).min()?;
let tied: Vec<usize> = applicable
.iter()
.filter(|&&(_, c)| c == best)
.map(|&(i, _)| i)
.collect();
let mut winners = tied.iter().filter(|&&i| {
tied.iter()
.all(|&j| self.at_least_as_specific(cands[i].0, cands[j].0, n))
});
let idx = *winners.next()?;
winners
.next()
.is_none()
.then(|| (idx, cands[idx].0.len() - 1))
}
/// The variable-arity candidates applicable to `arg_tys` in Java's third
/// phase, each with its conversion cost (see [`Compiler::pick_varargs`]).
fn varargs_applicable(
&self,
cands: &[(&[String], bool)],
arg_tys: &[Option<String>],
) -> Vec<(usize, u32)> {
let n = arg_tys.len();
cands
.iter()
.enumerate()
.filter_map(|(i, (ptys, varargs))| {
if !varargs || ptys.is_empty() || n + 1 < ptys.len() {
return None;
}
let fixed = ptys.len() - 1;
let elem = ptys[fixed].strip_suffix("[]")?;
let mut total = self.signature_cost(&ptys[..fixed], &arg_tys[..fixed])?;
for a in arg_tys[fixed..].iter().flatten() {
total += self.assign_cost(a, elem)?;
}
Some((i, total))
})
.collect()
}
/// Whether resolving `arg_tys` against `cands` failed for ambiguity —
/// some candidate applies in the deciding phase but none is most specific
/// — rather than because none applies. Only claimed when every argument's
/// static type is known.
fn overload_ambiguous(&self, cands: &[(&[String], bool)], arg_tys: &[Option<String>]) -> bool {
if !arg_tys.iter().all(Option::is_some) {
return false;
}
let fixed: Vec<(&[String], bool)> = cands
.iter()
.copied()
.filter(|c| c.0.len() == arg_tys.len())
.collect();
match self.pick_overload(&fixed, arg_tys) {
Ok(_) => false,
Err(NoPick::Ambiguous) => true,
Err(NoPick::Inapplicable) => {
self.pick_varargs(cands, arg_tys).is_none()
&& !self.varargs_applicable(cands, arg_tys).is_empty()
}
}
}
/// JLS 15.12.2.5 for two fixed-arity candidates of the same arity: every
/// declared parameter of `a` is assignable to `b`'s. A variable-arity
/// declaration competing here is read as its declared array (`Object...`
/// is `Object[]`), never expanded — which is what makes `f(null)` pick
/// `f(Object...)` over `f(Object)`, `Object[]` being the more specific.
fn fixed_at_least_as_specific(&self, a: &[String], b: &[String]) -> bool {
a.iter()
.zip(b)
.all(|(p, q)| self.assign_cost(p, q).is_some())
}
/// True when every expanded parameter of `a` is assignable to `b`'s — JLS
/// 15.12.2.5's "at least as specific", compared over
/// `max(n, arity(a), arity(b))` positions. Comparing at the *declared*
/// arity too is what separates `String...` from `Object...` when the call
/// passes no arguments at all.
fn at_least_as_specific(&self, a: &[String], b: &[String], n: usize) -> bool {
let k = n.max(a.len()).max(b.len());
(0..k).all(|i| {
self.assign_cost(expanded_param(a, i), expanded_param(b, i))
.is_some()
})
}
/// The argument list a call actually emits. `vararg_from` is `None` for a
/// fixed-arity call (the arguments pass through); for a variable-arity one
/// it is the index where packing starts, and everything from there becomes
/// a single array literal of the parameter's component type — the array the
/// callee's body sees as its `T[]` parameter.
fn effective_args(
args: &[Expr],
param_tys: &[String],
vararg_from: Option<usize>,
) -> Vec<Expr> {
let Some(from) = vararg_from else {
return args.to_vec();
};
let elem_ty = param_tys
.last()
.and_then(|t| t.strip_suffix("[]"))
.map(str::to_string);
let mut out = args[..from].to_vec();
out.push(Expr::ArrayLit {
elems: args[from..].to_vec(),
elem_ty,
});
out
}
/// Resolve an instance-method call on a static receiver class by argument
/// type. `None` when no method of that name resolves for these arguments.
fn resolve_instance_call(
&self,
class: &str,
method: &str,
arg_tys: &[Option<String>],
) -> Option<InstanceResolved> {
let info = self.classes.get(class)?;
let named: Vec<&MethodMeta> = info.methods.iter().filter(|m| m.name == method).collect();
let cands: Vec<(&[String], bool)> = named
.iter()
.map(|m| (m.param_tys.as_slice(), m.varargs))
.collect();
let (i, vararg_from) = self.resolve_overload(&cands, arg_tys)?;
let m = named[i];
Some(InstanceResolved {
param_tys: m.param_tys.clone(),
ret_name: m.ret.clone(),
ret: numtype_of_ty(&m.ret).unwrap_or(NumType::Other),
vararg_from,
})
}
/// The declared parameter types of the method `class` resolves to the
/// subroutine `mangled`, or none when it declares no such method.
fn instance_param_types(&self, class: &str, method: &str, mangled: &str) -> Vec<String> {
self.classes
.get(class)
.and_then(|ci| {
ci.methods.iter().find(|m| {
m.name == method && mangle(&m.defining, method, &m.param_tys) == mangled
})
})
.map(|m| m.param_tys.clone())
.unwrap_or_default()
}
/// Resolve the concrete implementation of an exact `(method, param_tys)`
/// signature visible on `class`: the mangled subroutine name and its return
/// type name. Used per-subclass for virtual dispatch (the overload is chosen
/// once statically; each runtime class supplies its own override body).
fn resolve_instance_sig(
&self,
class: &str,
method: &str,
param_tys: &[String],
) -> Option<(String, String)> {
let info = self.classes.get(class)?;
// Exact signature match to a concrete (bodied) method — the common case.
if let Some(m) = info
.methods
.iter()
.find(|m| !m.is_abstract && m.name == method && m.param_tys == param_tys)
{
return Some((mangle(&m.defining, method, &m.param_tys), m.ret.clone()));
}
// Erased-generic override: an interface/base method with a type-variable
// parameter (`score(T)`) is implemented with the concrete erased type
// (`score(String)`), so the raw strings differ. When exactly one concrete
// method of this name+arity exists on the class, it is that override.
let mut same_arity = info
.methods
.iter()
.filter(|m| !m.is_abstract && m.name == method && m.param_tys.len() == param_tys.len());
let only = same_arity.next()?;
if same_arity.next().is_none() {
return Some((
mangle(&only.defining, method, &only.param_tys),
only.ret.clone(),
));
}
None
}
/// Resolve a top-level user `static` method call by argument type: the
/// mangled target subroutine and its return type. `None` when no method of
/// that name+arity exists (an unresolved reference or arity mismatch).
/// The superclass chain of `class`, most-derived first — the order Java
/// searches for a `static` member, a subclass's declaration *hiding* the
/// one it inherits.
fn static_lookup_chain(&self, class: &str) -> Vec<String> {
let mut chain = Vec::new();
let mut cur = Some(class.to_string());
// The class graph is acyclic, but a malformed `extends` cycle would spin
// here, so the walk is bounded by the number of declared classes.
while let Some(c) = cur {
if chain.contains(&c) || chain.len() > self.classes.len() {
break;
}
cur = self
.classes
.get(&c)
.and_then(|ci| ci.superclass.clone())
.filter(|s| s != &c);
chain.push(c);
}
chain
}
/// Resolve `class.name(args)` — a **qualified** static call. Java looks the
/// name up in `class`'s own declarations first and only then in the classes
/// it inherits from; it never reaches an unrelated class. Restricting the
/// candidate set to that chain is what keeps `Q.f(1)` out of `P.f(int)`
/// when both `P` and `Q` declare an `f` — with one flat by-name pool the
/// nearest *signature* won regardless of receiver, which silently ran the
/// wrong method body.
fn resolve_static_on(
&self,
class: &str,
name: &str,
arg_tys: &[Option<String>],
) -> Option<StaticResolved> {
let overloads = self.methods.get(name)?;
// Each class in the chain is a separate resolution scope: the most
// derived one that declares the name at all wins, hiding the rest.
self.static_lookup_chain(class).into_iter().find_map(|c| {
let scoped: Vec<&MethodSig> = overloads.iter().filter(|s| s.owner == c).collect();
(!scoped.is_empty())
.then(|| self.pick_from(&scoped, name, arg_tys))
.flatten()
})
}
/// Resolve an **unqualified** `name(args)` call. The enclosing class's own
/// chain is searched first (Java's rule); the whole pool is the fallback,
/// which is what lets a nested class call a sibling's or the entry class's
/// static the way javars has always allowed.
fn resolve_static_call(
&self,
name: &str,
arg_tys: &[Option<String>],
) -> Option<StaticResolved> {
if let Some(cur) = self.current_class.as_deref() {
if let Some(r) = self.resolve_static_on(cur, name, arg_tys) {
return Some(r);
}
}
let overloads = self.methods.get(name)?;
let all: Vec<&MethodSig> = overloads.iter().collect();
self.pick_from(&all, name, arg_tys)
}
/// Choose the best-matching overload out of an already-scoped candidate set.
fn pick_from(
&self,
cands: &[&MethodSig],
name: &str,
arg_tys: &[Option<String>],
) -> Option<StaticResolved> {
let sigs: Vec<(&[String], bool)> = cands
.iter()
.map(|s| (s.param_tys.as_slice(), s.varargs))
.collect();
let (i, vararg_from) = self.resolve_overload(&sigs, arg_tys)?;
let s = cands[i];
Some(StaticResolved {
mangled: mangle_static(&s.owner, name, &s.param_tys),
owner: s.owner.clone(),
ret: s.ret,
ret_name: s.ret_name.clone(),
param_tys: s.param_tys.clone(),
vararg_from,
})
}
/// Resolve a constructor of `class` by argument type: the chosen ctor's
/// parameter-type list (for mangling the `<init>` subroutine) and its
/// variable-arity packing point. `None` when no constructor resolves.
fn resolve_ctor(
&self,
class: &str,
arg_tys: &[Option<String>],
) -> Option<(Vec<String>, Option<usize>)> {
let info = self.classes.get(class)?;
let cands: Vec<(&[String], bool)> = info
.ctors
.iter()
.map(|c| (c.param_tys.as_slice(), c.varargs))
.collect();
let (i, vararg_from) = self.resolve_overload(&cands, arg_tys)?;
Some((info.ctors[i].param_tys.clone(), vararg_from))
}
/// Emit a read of the receiver a synthesized constructor step runs on.
fn emit_recv(&mut self, recv: Recv<'_>, line: u32) {
match recv {
Recv::This => self.emit_this(line),
Recv::Temp(name) => self.emit_get(name, line),
}
}
/// Emit `Class.<instinit>(recv)` — the class's field initializers and bare
/// `{ … }` blocks, in textual order. A class with neither has no subroutine
/// to call.
fn emit_inst_init(&mut self, class: &str, recv: Recv<'_>, line: u32) {
if !self.classes.get(class).is_some_and(|ci| ci.has_inst_init) {
return;
}
self.emit_recv(recv, line);
let mangled = mangle(class, INST_INIT, &[]);
let idx = self.b.add_name(&mangled);
self.b.emit(Op::Call(idx, 1), line);
self.emit_exc_check(line);
self.b.emit(Op::Pop, line);
}
/// Emit the `super()` that a constructor of `class` runs when its body does
/// not open with an explicit `this(…)`/`super(…)` (JLS 8.8.7).
///
/// The direct superclass's no-argument constructor is called when it
/// declares one; when it declares none, javac gave that level a *default*
/// constructor, and that default is not a pass-through — it runs the
/// level's own `super()` chain and then its instance initializers. Skipping
/// such a level (as an ancestor walk that only looks for a declared
/// constructor does) therefore drops its `{ … }` blocks and field
/// initializers entirely, so it is synthesized here instead.
///
/// A superclass that declares constructors but no no-argument one is a
/// `javac` error, so emitting nothing there loses nothing a valid program
/// could observe.
fn emit_super_chain(&mut self, class: &str, recv: Recv<'_>, line: u32, depth: u32) {
if depth > 10_000 {
return;
}
let Some(sup) = self.classes.get(class).and_then(|ci| ci.superclass.clone()) else {
return;
};
let Some(info) = self.classes.get(&sup) else {
return;
};
if info.ctors.is_empty() {
self.emit_default_ctor(&sup, recv, line, depth + 1);
return;
}
// A capturing local superclass takes its captures as the only
// arguments of its implicit `super()`; the subclass holds the same
// captures as constructor parameters of its own (`capture_locals`).
let captured: Vec<(String, String)> = info.captures.clone();
let tys: Vec<String> = captured.iter().map(|(_, t)| t.clone()).collect();
if !info.ctors.iter().any(|c| c.param_tys == tys) {
return;
}
self.emit_recv(recv, line);
for (name, _) in &captured {
self.emit_get(name, line);
}
let mangled = mangle(&sup, "<init>", &tys);
let idx = self.b.add_name(&mangled);
self.b.emit(Op::Call(idx, 1 + captured.len() as u8), line);
self.emit_exc_check(line);
self.b.emit(Op::Pop, line);
}
/// A construction's arguments with `class`'s captured values appended.
///
/// A captured local is read by name where the construction is written:
/// the enclosing local itself at a `new` in the declaring method, the
/// class's own field at a `new` inside its body, and the constructor
/// parameter in a `this(…)`/`super(…)`. The enclosing instance of an inner
/// class ([`OUTER_THIS`]) is `outer` when the construction names one
/// (`o.new Inner()`, or the constructor parameter a `this(…)`/`super(…)`
/// forwards), else the innermost `this` of the enclosing type
/// ([`Compiler::enclosing_instance`]).
fn with_captures<'a>(
&self,
class: &str,
args: &'a [Expr],
outer: Option<&Expr>,
) -> Cow<'a, [Expr]> {
let Some(ci) = self.classes.get(class).filter(|ci| !ci.captures.is_empty()) else {
return Cow::Borrowed(args);
};
let mut all = args.to_vec();
for (name, ty) in &ci.captures {
all.push(if name == OUTER_THIS {
match outer {
Some(o) => o.clone(),
None => self.enclosing_instance(ty),
}
} else {
Expr::Var(name.clone())
});
}
Cow::Owned(all)
}
/// The class `e` names when it is a qualified `this` (`Outer.this`).
fn qualified_this<'e>(&self, e: &'e Expr) -> Option<&'e str> {
match e {
Expr::Field { recv, name } if name == "this" => match recv.as_ref() {
Expr::Var(class) if self.classes.contains_key(class) => Some(class),
_ => None,
},
_ => None,
}
}
/// `javac`'s refusal of a call that can reach only `private` methods of a
/// class in another top-level class (JLS 6.6.1: a private member is
/// accessible within the body of the top-level class that encloses it).
/// Every method of the receiver's class and its ancestors with the call's
/// name and arity is considered, so an accessible overload is never
/// refused.
fn check_private_access(
&self,
recv: &Expr,
method: &str,
argc: usize,
line: u32,
) -> Result<(), String> {
let Some(cur) = self.current_class.as_deref() else {
return Ok(());
};
let Some(class) = self.user_class_ref(recv).or_else(|| self.expr_class(recv)) else {
return Ok(());
};
let top = |c: &str| {
let b = self.classes.get(c).map_or(c, |ci| ci.binary.as_str());
b.split('$').next().unwrap_or(b).to_string()
};
let mut chain = vec![class.clone()];
let mut i = 0;
while i < chain.len() && chain.len() < 256 {
if let Some(ci) = self.classes.get(&chain[i]) {
for s in &ci.supertypes {
if !chain.contains(s) {
chain.push(s.clone());
}
}
}
i += 1;
}
let candidates: Vec<(&str, &Vec<String>, Access)> = chain
.iter()
.flat_map(|c| {
self.method_access
.get(c)
.into_iter()
.flatten()
.filter(|(n, ps, _)| n == method && ps.len() == argc)
.map(move |(_, ps, a)| (c.as_str(), ps, *a))
})
.collect();
let cur_top = top(cur);
let hidden = |(owner, _, a): &(&str, &Vec<String>, Access)| {
*a == Access::Private && top(owner) != cur_top
};
match candidates.first() {
Some(first) if candidates.iter().all(hidden) => Err(format!(
"javars: {method}({}) has private access in {} (line {line})",
first.1.join(","),
source_type_name(
self.classes
.get(first.0)
.map_or(first.0, |ci| ci.binary.as_str())
)
)),
_ => Ok(()),
}
}
/// `javac`'s refusal of `new Inner()` with no enclosing instance in scope
/// (JLS 15.9.2): from a static context of the enclosing class itself, `this`
/// is what is missing; from anywhere else, the enclosing instance.
fn check_enclosing_instance(&self, class: &str, line: u32) -> Result<(), String> {
let Some(outer) = self.outer_class(class) else {
return Ok(());
};
if !matches!(self.enclosing_instance(outer), Expr::Var(n) if n == NULL_LITERAL) {
return Ok(());
}
let binary = |c: &str| {
self.classes
.get(c)
.map_or(c.to_string(), |ci| ci.binary.clone())
};
// An anonymous or local class (`T$1`, `T$1Local`) in a static context
// simply has no enclosing instance; only a member class needs one.
let local = binary(class)
.rsplit('$')
.next()
.is_some_and(|s| s.starts_with(|c: char| c.is_ascii_digit()));
if local {
return Ok(());
}
let inside = self.current_class.as_deref().is_some_and(|cur| {
let (cur, out) = (binary(cur), binary(outer));
cur == out || cur.starts_with(&format!("{out}$"))
});
if inside {
return Err(format!(
"javars: non-static variable this cannot be referenced from a static context (line {line})"
));
}
Err(format!(
"javars: an enclosing instance that contains {} is required (line {line})",
source_type_name(&binary(class))
))
}
/// The enclosing class an inner member class holds an instance of.
fn outer_class(&self, class: &str) -> Option<&str> {
self.classes
.get(class)?
.captures
.iter()
.find(|(n, _)| n == OUTER_THIS)
.map(|(_, ty)| ty.as_str())
}
/// The innermost `this` whose class is `outer` or a subclass of it: `this`
/// itself, else `this.this$0`, `this.this$0.this$0`, … up the chain of
/// enclosing instances — JLS 15.9.2's "immediately enclosing instance" and
/// what `Outer.this` denotes. In a static context there is none; javac
/// rejects a bare `new Inner()` there, and javars passes `null`, which
/// only an inner class that actually reads its enclosing instance can
/// observe.
fn enclosing_instance(&self, outer: &str) -> Expr {
let null = Expr::Var(NULL_LITERAL.to_string());
let Some(mut cur) = self.this_class.as_deref() else {
return null;
};
let mut recv = Expr::This;
for _ in 0..64 {
if self.is_subclass(cur, outer) {
return recv;
}
let Some(next) = self.outer_class(cur) else {
break;
};
recv = Expr::Field {
recv: Box::new(recv),
name: OUTER_THIS.to_string(),
};
cur = next;
}
null
}
/// The receiver an unqualified name that is none of `this`'s own fields
/// reads when an enclosing instance declares it (JLS 6.5.6.1): the
/// `this.this$0…` chain up to the first enclosing class with a field
/// `name`, and that class.
fn outer_field_recv(&self, name: &str) -> Option<(Expr, String)> {
if self.is_local(name) {
return None;
}
let mut cur = self.this_class.as_deref()?;
let mut recv = Expr::This;
for _ in 0..64 {
let next = self.outer_class(cur)?;
recv = Expr::Field {
recv: Box::new(recv),
name: OUTER_THIS.to_string(),
};
if self.classes.get(next)?.field_types.contains_key(name) {
return Some((recv, next.to_string()));
}
cur = next;
}
None
}
/// The receiver an unqualified call to a method `this`'s class does not
/// have reaches when an enclosing instance's class does, as
/// [`Compiler::outer_field_recv`] does for a field.
fn outer_method_recv(&self, name: &str) -> Option<Expr> {
let mut cur = self.this_class.as_deref()?;
let mut recv = Expr::This;
for _ in 0..64 {
let next = self.outer_class(cur)?;
recv = Expr::Field {
recv: Box::new(recv),
name: OUTER_THIS.to_string(),
};
if self
.classes
.get(next)?
.methods
.iter()
.any(|m| m.name == name)
{
return Some(recv);
}
cur = next;
}
None
}
/// Emit the body of the default constructor javac synthesizes for a class
/// that declares none: `super()`, then the class's instance initializers,
/// then an empty body.
fn emit_default_ctor(&mut self, class: &str, recv: Recv<'_>, line: u32, depth: u32) {
self.emit_super_chain(class, recv, line, depth);
self.emit_inst_init(class, recv, line);
}
/// How a constructor body opens: with an explicit `super(…)`, with an
/// explicit `this(…)`, or with neither — in which case JLS 8.8.7 gives it an
/// implicit `super()`. The three cases place the instance initializers
/// differently, which is why this is not a bool.
fn ctor_chain(body: &[Stmt]) -> CtorChain {
match body.first().map(|s| &s.kind) {
Some(StmtKind::Expr(Expr::Call { name, .. })) if name == "super" => CtorChain::Super,
Some(StmtKind::Expr(Expr::Call { name, .. })) if name == "this" => CtorChain::This,
_ => CtorChain::Implicit,
}
}
/// True when `class` declares or inherits any method named `method` with
/// `argc` parameters (an existence check for dispatch decisions).
fn has_instance_method(&self, class: &str, method: &str, argc: usize) -> bool {
self.classes.get(class).is_some_and(|ci| {
ci.methods.iter().any(|m| {
m.name == method
&& (m.param_tys.len() == argc
// A variable-arity method accepts any count from its
// fixed parameters up, so a bare `f(1, 2, 3)` inside
// the class still routes to `this.f(int... xs)`.
|| (m.varargs && argc + 1 >= m.param_tys.len()))
})
})
}
/// The nearest class every one of `types` extends: the first class on the
/// superclass chain of `types[0]` that each of the others is a subclass of.
/// For a multi-catch's alternatives that chain always reaches `Throwable`,
/// which is therefore the answer when nothing nearer is shared.
fn superclass_lub(&self, types: &[String]) -> String {
let mut cur = types[0].as_str();
loop {
if types[1..].iter().all(|t| self.is_subclass(t, cur)) {
return cur.to_string();
}
match self
.classes
.get(cur)
.and_then(|ci| ci.superclass.as_deref())
{
Some(sup) => cur = sup,
None => return "Throwable".to_string(),
}
}
}
/// True when `class` is `base`, a (transitive) subclass of it, or a type
/// that implements/extends the interface `base` — walking the full supertype
/// graph (superclass + interfaces).
fn is_subclass<'a>(&'a self, class: &'a str, base: &str) -> bool {
if class == base {
return true;
}
// Both lists borrow their names — from the argument and from
// `self.classes` — so the walk allocates nothing but the two `Vec`s.
// It used to `to_string()` the root, `clone()` every name into a
// `HashSet`, and `cloned()` every supertype out of the class table; at
// 30,327 calls per compile of the 261-program corpus that was 19.2% of
// the phase's allocations. A class's supertype list is one to three
// names, and the whole visited set is the ancestor chain, so a linear
// scan of a `Vec` finds a repeat faster than hashing a `String` would.
let mut stack: Vec<&str> = vec![class];
let mut seen: Vec<&str> = Vec::new();
while let Some(cur) = stack.pop() {
if cur == base {
return true;
}
if seen.contains(&cur) {
continue;
}
seen.push(cur);
// The same bound the walk always carried, against a supertype graph
// with a cycle in it.
if seen.len() > 10000 {
return false;
}
if let Some(ci) = self.classes.get(cur) {
stack.extend(ci.supertypes.iter().map(String::as_str));
}
}
false
}
/// True when `rc` is a user interface whose `method(argc)` comes from a JDK
/// interface it extends rather than from any user declaration —
/// `interface Stack<E> extends Iterable<E>` has `iterator()`, `interface
/// Shape extends Comparable<Shape>` has `compareTo`. `javac` has already
/// accepted the call, so the method exists; the implementing classes hold
/// the bodies, which is where [`Compiler::virtual_targets`] looks.
fn inherits_jdk_method(&self, rc: &str, method: &str, argc: usize) -> bool {
self.classes.get(rc).is_some_and(|ci| ci.is_interface)
&& self
.implementors(rc)
.any(|k| self.has_instance_method(k, method, argc))
}
/// The concrete classes below `rc`, by name.
fn implementors<'a>(&'a self, rc: &'a str) -> impl Iterator<Item = &'a String> + 'a {
let mut names: Vec<&String> = self
.classes
.iter()
.filter(|(_, ci)| !ci.is_interface)
.map(|(k, _)| k)
.filter(move |k| self.is_subclass(k, rc))
.collect();
names.sort();
names.into_iter()
}
/// [`Compiler::resolve_instance_call`] for a method `rc` inherits from a JDK
/// interface (see [`Compiler::inherits_jdk_method`]): the overload is the
/// one the first implementing class (by name) resolves.
fn resolve_on_implementor(
&self,
rc: &str,
method: &str,
arg_tys: &[Option<String>],
) -> Option<InstanceResolved> {
if !self.inherits_jdk_method(rc, method, arg_tys.len()) {
return None;
}
self.implementors(rc)
.find_map(|k| self.resolve_instance_call(k, method, arg_tys))
}
/// The virtual-dispatch targets for `method(argc)` on a static receiver class
/// `rc`: for every class in `rc`'s subtree, its resolved `(class, mangled)`.
/// `None` when `rc` does not resolve the method at all. Sorted by class name
/// for deterministic bytecode.
fn virtual_targets(
&self,
rc: &str,
method: &str,
param_tys: &[String],
) -> Option<Vec<(String, String)>> {
// The method must exist on the static type (else it is a type error).
// An abstract-only method on an interface still gates dispatch — the
// concrete implementors below supply the bodies.
if !self.has_instance_method(rc, method, param_tys.len())
&& !self.inherits_jdk_method(rc, method, param_tys.len())
{
return None;
}
let mut v: Vec<(String, String)> = self
.classes
.iter()
// Only concrete (instantiable) classes are runtime dispatch targets;
// an interface is never a runtime class of any object.
.filter(|(_, ci)| !ci.is_interface)
.map(|(k, _)| k)
.filter(|k| self.is_subclass(k, rc))
.filter_map(|k| {
self.resolve_instance_sig(k, method, param_tys)
.map(|(m, _)| (k.clone(), m))
})
.collect();
v.sort();
Some(v)
}
/// Emit a call to instance `method(args)` on `recv` (whose static class is
/// `rc`), binding `recv` as `this`. When the method is not overridden anywhere
/// in `rc`'s subtree, a direct `Op::Call` is emitted; otherwise a runtime
/// dispatch chain keyed on the receiver's actual class selects the override
/// (true virtual dispatch — arguments are evaluated once into temps).
fn dispatch_instance_method(
&mut self,
recv: &Expr,
rc: &str,
method: &str,
args: &[Expr],
line: u32,
) -> Result<(), String> {
// Resolve which overload the static argument types select, then dispatch
// that exact signature virtually on the receiver's runtime class.
let arg_tys: Vec<Option<String>> = self.arg_types(args);
let resolved = self
.resolve_instance_call(rc, method, &arg_tys)
.or_else(|| self.resolve_on_implementor(rc, method, &arg_tys))
.ok_or_else(|| {
format!(
"javars: class `{rc}` has no method `{method}` taking {} argument(s) (line {line})",
args.len()
)
})?;
let param_tys = resolved.param_tys;
// A variable-arity call packs its trailing arguments into one array
// before anything is emitted, so every path below — the direct call,
// the virtual dispatch chain, and the argument temps — sees the same
// fixed-arity argument list the callee's parameters expect.
let packed = Self::effective_args(args, ¶m_tys, resolved.vararg_from);
let args: &[Expr] = &packed;
let targets = self
.virtual_targets(rc, method, ¶m_tys)
.ok_or_else(|| {
format!(
"javars: class `{rc}` has no method `{method}` taking {} argument(s) (line {line})",
args.len()
)
})?;
let distinct: HashSet<&str> = targets.iter().map(|(_, m)| m.as_str()).collect();
// Calling the single abstract method of a functional interface may land
// on a lambda, which is a closure rather than a class instance — so that
// receiver gets its own arm in the dispatch chain (keyed on the sentinel
// runtime class the host reports for a closure), and the fast path is
// given up even when only one class implements the interface.
let lambda_arm = matches!(
self.functional_sam(rc),
Some((sam, arity)) if sam == method && arity == args.len()
);
let (arg_generics, arg_wildcards) =
self.instance_param_generics(recv, rc, method, ¶m_tys);
// A functional interface's *other* methods — its `default` ones
// (`Predicate.negate`, `Function.andThen`) — are reachable on a lambda
// receiver too, and a closure's runtime class matches no concrete-class
// arm. The interface's own body is what Java runs for it, so it gets its
// own arm keyed on the same closure sentinel.
let default_arm: Option<String> = if lambda_arm || self.functional_sam(rc).is_none() {
None
} else {
self.resolve_instance_sig(rc, method, ¶m_tys)
.map(|(m, _)| m)
};
// Fast path: exactly one body is reachable. That is a single concrete
// implementation across the whole subtree — the concrete target's
// mangled name, not the static type's, so an interface- or
// abstract-typed receiver still calls a real subroutine — or, when no
// class implements the interface at all, its own `default` body, which
// is the only thing a lambda receiver can run.
let only_body = match (targets.first(), &default_arm) {
(None, Some(d)) => Some(d.clone()),
// No class implements the type, so the body its own declaration
// supplies (a `default` or `private` interface method) is the only
// one a call can reach — a private one is statically bound anyway.
(None, None) if !lambda_arm => self
.resolve_instance_sig(rc, method, ¶m_tys)
.map(|(m, _)| m),
(Some((_, m)), d) if distinct.len() == 1 && d.as_deref().unwrap_or(m) == m => {
Some(m.clone())
}
_ => None,
};
if !lambda_arm {
if let Some(mangled) = only_body {
self.expr(recv)?; // this (deepest)
self.call_args_with_generics(args, ¶m_tys, &arg_generics, &arg_wildcards)?;
let idx = self.b.add_name(&mangled);
self.b.emit(Op::Call(idx, args.len() as u8 + 1), line);
self.emit_exc_check(line);
return Ok(());
}
if targets.is_empty() {
return Err(format!(
"javars: no concrete implementation of `{method}` for `{rc}` (line {line})"
));
}
}
// Virtual path: stash receiver + args in temps (single evaluation), read
// the runtime class, then dispatch.
let recv_t = self.temp();
self.expr(recv)?;
self.emit_set(&recv_t, line);
let arg_ts: Vec<String> = args
.iter()
.enumerate()
.map(|(i, a)| {
let t = self.temp();
let want = param_tys.get(i).cloned();
let g = arg_generics.get(i).cloned().flatten();
self.expr_targeted_generic(a, want.as_deref(), g)?;
self.emit_set(&t, line);
Ok(t)
})
.collect::<Result<_, String>>()?;
let class_t = self.temp();
self.emit_get(&recv_t, line);
self.b.emit(Op::CallBuiltin(crate::host::JCLASSOF, 1), line);
self.emit_set(&class_t, line);
let argc = args.len() as u8 + 1;
let mut end_jumps = Vec::new();
if lambda_arm {
// if classof == "#lambda" { closure + args; JCLOSURE_CALL }
self.emit_get(&class_t, line);
let cc = self
.b
.add_constant(Value::str(crate::host::LAMBDA_CLASS.to_string()));
self.b.emit(Op::LoadConst(cc), line);
self.b.emit(Op::StrEq, line);
let skip = self.b.emit(Op::JumpIfFalse(0), line);
self.emit_get(&recv_t, line);
for t in &arg_ts {
self.emit_get(t, line);
}
self.emit_raising_builtin(crate::host::JCLOSURE_CALL, argc, line);
end_jumps.push(self.b.emit(Op::Jump(0), line));
let next = self.b.current_pos();
self.b.patch_jump(skip, next);
}
// A closure receiver of a functional interface whose `default` method a
// class overrides: the lambda runs the interface's own body, never the
// override of an unrelated implementor.
if let Some(default_body) = &default_arm {
self.emit_get(&class_t, line);
let cc = self
.b
.add_constant(Value::str(crate::host::LAMBDA_CLASS.to_string()));
self.b.emit(Op::LoadConst(cc), line);
self.b.emit(Op::StrEq, line);
let skip = self.b.emit(Op::JumpIfFalse(0), line);
self.emit_get(&recv_t, line);
for t in &arg_ts {
self.emit_get(t, line);
}
let idx = self.b.add_name(default_body);
self.b.emit(Op::Call(idx, argc), line);
self.emit_exc_check(line);
end_jumps.push(self.b.emit(Op::Jump(0), line));
let next = self.b.current_pos();
self.b.patch_jump(skip, next);
}
for (class, mangled) in &targets {
// if classof == "class" { this + args; Call(mangled) }
self.emit_get(&class_t, line);
let cc = self.b.add_constant(Value::str(class.clone()));
self.b.emit(Op::LoadConst(cc), line);
self.b.emit(Op::StrEq, line);
let skip = self.b.emit(Op::JumpIfFalse(0), line);
self.emit_get(&recv_t, line);
for t in &arg_ts {
self.emit_get(t, line);
}
let idx = self.b.add_name(mangled);
self.b.emit(Op::Call(idx, argc), line);
self.emit_exc_check(line);
end_jumps.push(self.b.emit(Op::Jump(0), line));
let next = self.b.current_pos();
self.b.patch_jump(skip, next);
}
// Fallback (unreachable at runtime — every concrete class is a target):
// call an arbitrary concrete target so the stack stays balanced. Using a
// real target (not the static type) keeps this valid when `rc` is an
// interface whose own method has no subroutine. A functional interface
// that no class implements has no such target, so its fallback is the
// closure call — which is also the arm that reports the Java
// `NullPointerException` when the target is null.
self.emit_get(&recv_t, line);
for t in &arg_ts {
self.emit_get(t, line);
}
match targets.first() {
Some((_, base)) => {
let idx = self.b.add_name(base);
self.b.emit(Op::Call(idx, argc), line);
self.emit_exc_check(line);
}
None => self.emit_raising_builtin(crate::host::JCLOSURE_CALL, argc, line),
}
let end = self.b.current_pos();
for j in end_jumps {
self.b.patch_jump(j, end);
}
Ok(())
}
/// Emit the Java default value for a declared type: `0` for integral, `0.0`
/// for floating point, `false` for `boolean`, `null` (`Undef`) for arrays,
/// `String`, and class references.
fn emit_type_default(&mut self, ty: &str, line: u32) {
match ty {
"int" | "long" | "short" | "byte" | "char" => {
self.b.emit(Op::LoadInt(0), line);
}
"double" | "float" => {
self.b.emit(Op::LoadFloat(0.0), line);
}
"boolean" => {
self.b.emit(Op::LoadFalse, line);
}
_ => {
self.b.emit(Op::LoadUndef, line);
}
}
}
// ── 32-bit `int` overflow wrapping ────────────────────────────────────
//
// fusevm's integers are 64-bit; Java's `int` is 32-bit and wraps. The two
// only disagree once a value leaves `int` range, and the compiler is the
// only place that knows which operations are `int` operations — the runtime
// value model has one integer type. So an operation whose *static* Java type
// is `int` gets a sign-extend of its low 32 bits appended, and every other
// operation is left alone.
//
// The sign-extend is `Shl 32; Shr 32` rather than a builtin because fusevm's
// `Shr` is an arithmetic shift both in the interpreter and in the Cranelift
// backend (`sshr`), so wrapping stays two native, JIT-traceable ops — a
// `CallBuiltin` would abort trace recording and cost hot loops their JIT.
/// True when `ty` is a static type whose arithmetic Java performs at 32-bit
/// `int` width. `byte`/`short`/`char` operands promote to `int` before any
/// binary operation, so they qualify; `long` (64-bit) and an unknown type do
/// not.
fn is_int_width(ty: Option<&str>) -> bool {
matches!(
ty.map(unwrapped_ty),
Some("int" | "short" | "byte" | "char")
)
}
/// True when `e`'s static Java type is `char`. A `char` runs as its code
/// point, so this is the flag that says "convert to a one-character String
/// before this value crosses into a String or a `Character` box".
fn is_char_expr(&self, e: &Expr) -> bool {
matches!(
self.expr_java_type(e).as_deref(),
Some("char" | "Character")
)
}
/// True when `e`'s static Java type is `char[]` — the array `toCharArray`
/// returns, whose elements are code points.
fn is_char_array_expr(&self, e: &Expr) -> bool {
self.expr_java_type(e).as_deref() == Some("char[]")
}
/// True when `e`'s static Java type is `float` (or `float[]`). fusevm has one
/// floating representation, so `float` is a `double` *kept* at 32-bit
/// precision — this is the flag that says where to narrow it and where to
/// print it as a `float` rather than as a `double`.
fn is_float32_expr(&self, e: &Expr) -> bool {
// `Float` too: its box holds the 32-bit value, so `Float x = 0.1f, y =
// 0.1f; x + y` is the `float` addition (0.2), not the `double` one
// (0.20000000298023224) the widened operands would give.
matches!(
self.expr_java_type(e).as_deref().map(unwrapped_ty),
Some("float" | "float[]")
)
}
/// Emit one arithmetic operation at 32-bit `float` width, with both operands
/// already on the stack. Java rounds a `float` operation once, at 32 bits;
/// computing it in `f64` and rounding afterwards rounds twice and can land a
/// ulp away (`16777217.0f * 0.2f`), so the operation itself moves to the
/// host rather than the narrowing being appended to a native op.
fn emit_f32_arith(&mut self, op: BinOp, line: u32) {
let code = match op {
BinOp::Sub => crate::host::f32_op::SUB,
BinOp::Mul => crate::host::f32_op::MUL,
BinOp::Div => crate::host::f32_op::DIV,
BinOp::Mod => crate::host::f32_op::REM,
_ => crate::host::f32_op::ADD,
};
self.b.emit(Op::LoadInt(code), line);
self.b
.emit(Op::CallBuiltin(crate::host::JF32_ARITH, 3), line);
}
/// The Java type of `lhs <op> rhs` under binary numeric promotion, or `None`
/// when either operand's type is unknown. Only the promoted *width* matters
/// to the caller, so the operator itself does not enter into it.
fn arith_result_type(&self, lhs: &Expr, rhs: &Expr) -> Option<&'static str> {
let l = self.expr_java_type(lhs)?;
let r = self.expr_java_type(rhs)?;
Some(rank_name(numeric_rank(&l)?.max(numeric_rank(&r)?)))
}
/// Evaluate `e` and, when its static type is `char` (or `char[]`), apply
/// Java's string conversion — the code point becomes the one-character
/// String. Every other expression is emitted unchanged, so this is safe to
/// use anywhere a value flows into a String or an erased (`Object`)
/// position.
fn emit_char_string(&mut self, e: &Expr) -> Result<(), String> {
self.emit_converted_arg(e, true)
}
/// The same conversion, with the `float` half switchable.
///
/// `String.format`'s numeric conversions (`%f`, `%e`, `%.9f`) must receive
/// the *number* — Java widens the `float` to a `double` for them, so
/// `%.9f` of `1.0f/3.0f` is `0.333333343`, which the shortest decimal
/// `0.33333334` cannot reproduce. Only its `%s`-family conversions want
/// `Float.toString`. A `char` has no such split: its one-character String
/// serves `%c` and `%s` alike.
fn emit_converted_arg(&mut self, e: &Expr, floats: bool) -> Result<(), String> {
self.expr(e)?;
if self.is_char_expr(e) || self.is_char_array_expr(e) {
self.b.emit(Op::CallBuiltin(crate::host::JCHR_STR, 1), 0);
} else if floats && self.is_float32_expr(e) {
// A `float` and a `double` holding the same bits print differently,
// and only the static type says which this is.
self.b.emit(Op::CallBuiltin(crate::host::JF32_STR, 1), 0);
}
Ok(())
}
/// True when `lhs + rhs` is Java's *string* concatenation rather than
/// arithmetic: one operand is a `String`, or one is a class instance whose
/// `toString()` the concatenation would call.
fn is_string_concat(&self, lhs: &Expr, rhs: &Expr) -> bool {
let is_str = |e: &Expr| {
self.expr_java_type(e).as_deref() == Some("String") || self.expr_class(e).is_some()
};
is_str(lhs) || is_str(rhs)
}
/// True when both operands of a binary arithmetic operation are statically
/// `int`-width, which makes the result an `int` that wraps at 32 bits.
fn operands_are_int(&self, lhs: &Expr, rhs: &Expr) -> bool {
Self::is_int_width(self.expr_java_type(lhs).as_deref())
&& Self::is_int_width(self.expr_java_type(rhs).as_deref())
}
/// True when a compound assignment (`x op= e`, `a[i] op= e`, `f op= e`,
/// `x++`) narrows back to a 32-bit `int`: the target is declared `int` and
/// the operand is statically `int`-width. A `long` target, or an operand
/// whose type is unknown, keeps the 64-bit result.
fn compound_wraps(&self, target_ty: Option<&str>, value: &Expr) -> bool {
target_ty == Some("int") && Self::is_int_width(self.expr_java_type(value).as_deref())
}
/// Sign-extend the low 32 bits of the value on top of the stack — Java's
/// `int` overflow wrap.
fn emit_wrap32(&mut self, line: u32) {
self.b.emit(Op::LoadInt(32), line);
self.b.emit(Op::Shl, line);
self.b.emit(Op::LoadInt(32), line);
self.b.emit(Op::Shr, line);
}
/// Narrow the value on top of the stack to a sub-`int` declared type. A
/// compound assignment and `++`/`--` carry an *implicit narrowing cast* back
/// to the target's type (JLS 15.26.2), so `byte b = 100; b += 100;` is -56
/// and `char c = 65535; c++;` is 0. `byte`/`short` sign-extend with the same
/// native shift pair `emit_wrap32` uses; `char` is unsigned, so it masks.
/// Every other type (including `int`, whose wrap is `emit_wrap32`'s job) is
/// left alone.
fn emit_narrow_to(&mut self, ty: Option<&str>, line: u32) {
match ty {
Some("byte") => {
self.b.emit(Op::LoadInt(56), line);
self.b.emit(Op::Shl, line);
self.b.emit(Op::LoadInt(56), line);
self.b.emit(Op::Shr, line);
}
Some("short") => {
self.b.emit(Op::LoadInt(48), line);
self.b.emit(Op::Shl, line);
self.b.emit(Op::LoadInt(48), line);
self.b.emit(Op::Shr, line);
}
Some("char" | "Character") => {
self.b.emit(Op::LoadInt(0xFFFF), line);
self.b.emit(Op::BitAnd, line);
}
_ => {}
}
}
/// The floating type an assignment of `e` into a `target`-typed slot widens
/// to, or `None` when no widening primitive conversion applies.
///
/// Java's assignment and method-invocation conversions (JLS 5.2 / 5.3)
/// change the *value*, not only its static type: `double d = 7;` stores 7.0
/// and prints `7.0`. javars's runtime is dynamically typed on the fusevm
/// value model, so the conversion has to be emitted at each site the
/// language performs one — every initializer, assignment, array-literal
/// element, argument, and `return` whose target is `float`/`double` and
/// whose source type is integral.
fn widen_target(&self, target: Option<&str>, e: &Expr) -> Option<&'static str> {
let t = match target? {
"double" => "double",
"float" => "float",
_ => return None,
};
let src = self.expr_java_type(e)?;
// A wrapper widens as the primitive it boxes: `double d = anInteger;` is
// an unboxing conversion followed by a widening one (JLS 5.2).
matches!(
unwrapped_ty(&src),
"int" | "long" | "short" | "byte" | "char"
)
.then_some(t)
}
/// Emit the widening primitive conversion for the value already on top of
/// the stack.
///
/// `double` is the native `Op::TruncFloat`: it converts its operand to `f64`
/// and truncates, and an integral operand is already whole, so the result is
/// the same value as a `double` — Java's widening exactly, with no builtin
/// call to break the JIT trace. `float` additionally rounds to 32-bit
/// precision, which is a real value change (`float f = 16777217;` is
/// 1.6777216E7), so it routes through the same host cast `(float) x` uses.
fn emit_widen(&mut self, ty: &str, line: u32) {
if ty == "float" {
let c = self.b.add_constant(Value::str("float".to_string()));
self.b.emit(Op::LoadConst(c), line);
self.b.emit(Op::CallBuiltin(crate::host::JCAST, 2), line);
} else {
self.b.emit(Op::TruncFloat, line);
}
}
/// The overload-width operand a `Math` static needs, or `None` for a static
/// that is not overloaded on width.
///
/// `0` selects the `int` overload, `1` the `long` one, `2` `float` and `3`
/// `double` — the codes [`crate::host::width`] names. Java resolves
/// these from the arguments' static types; javars does the same, and
/// *refuses* the call when it cannot type an argument rather than picking
/// one and being silently wrong at exactly the values these methods exist
/// to catch.
/// The value a grown copy of `arr` pads with, from `arr`'s **static** type:
/// a primitive array's element default. `None` for a reference array (whose
/// default is the `null` the host already falls back to) and for an
/// expression javars could not type.
///
/// See the call site in the static-dispatch lowering for why this cannot be
/// answered at run time.
fn array_element_default(&self, arr: &Expr) -> Option<Value> {
let ty = self.expr_java_type(arr)?;
let elem = ty.strip_suffix("[]")?;
Some(match elem {
"int" | "long" | "short" | "byte" | "char" => Value::Int(0),
"double" | "float" => Value::float(0.0),
"boolean" => Value::bool(false),
_ => return None,
})
}
fn overload_width(
&self,
class: &str,
method: &str,
args: &[Expr],
) -> Result<Option<i64>, String> {
if !is_width_overloaded(class, method, args.len()) {
return Ok(None);
}
let width = self.width_overload(class, method, args).ok_or_else(|| {
format!(
"javars: `Math.{method}` is overloaded on argument width and javars cannot infer an argument's type, so it cannot tell which overload the call selects"
)
})?;
// Only `clamp` has floating overloads. `Math.addExact(1.0, 2.0)` does
// not compile in Java either, and refusing here says so rather than
// inventing an integral answer for it.
if method != "clamp" && width > crate::host::width::LONG {
return Err(format!(
"javars: `Math.{method}` has no floating-point overload"
));
}
Ok(Some(width))
}
/// The [`crate::host::width`] code a width-overloaded `Math` static
/// resolves to, or `None` when an argument's type is not statically known.
///
/// Asked from two places, which is why it is separate from the diagnostic
/// [`Compiler::overload_width`] puts on top of it: the call site needs the
/// operand, and [`Compiler::expr_java_type`] needs the *result* type, since
/// `Math.addExact(1L, 2L)` is a `long` and `Math.addExact(1, 2)` an `int`.
fn width_overload(&self, class: &str, method: &str, args: &[Expr]) -> Option<i64> {
if !is_width_overloaded(class, method, args.len()) {
return None;
}
// `toIntExact(long)` has exactly one shape; the operand it carries is
// there to name the method, not to choose between overloads.
if method == "toIntExact" {
return self
.expr_java_type(&args[0])
.and(Some(crate::host::width::LONG));
}
let ranks: Option<Vec<u32>> = args
.iter()
.map(|a| self.expr_java_type(a).and_then(|t| numeric_rank(&t)))
.collect();
let ranks = ranks?;
// `clamp`'s overloads are picked by its *bounds*: `clamp(long, int, int)`
// answers an `int` and `clamp(long, long, long)` a `long`, so the first
// argument being wide does not widen the result. The floating overloads
// take all three at one type.
let deciding = if method == "clamp" {
&ranks[1..]
} else {
&ranks[..]
};
let top = deciding.iter().copied().max()?;
Some(match rank_name(top) {
"double" => crate::host::width::DOUBLE,
"float" => crate::host::width::FLOAT,
"long" => crate::host::width::LONG,
_ => crate::host::width::INT,
})
}
/// True when `Math.<method>(args)` selects the `float` overload of one of
/// the bit-pattern statics, which step or measure in 32-bit units:
/// `Math.ulp(1.0f)` is `1.1920929E-7`, not the `double` overload's
/// `2.220446049250313E-16`. The overload is a static-type choice, so the
/// call carries [`crate::host::width::FLOAT`] as one more operand, the way
/// [`Compiler::overload_width`] passes the `Exact` family's width.
///
/// `nextAfter(float, double)` and `scalb(float, int)` are chosen by their
/// first argument alone; `copySign` has only the all-`float` and
/// all-`double` overloads, so a `double` second argument selects the latter.
fn math_float_overload(&self, class: &str, method: &str, args: &[Expr]) -> bool {
if class != "Math" {
return false;
}
let deciding = match (method, args.len()) {
("ulp" | "nextUp" | "nextDown" | "signum" | "getExponent", 1)
| ("nextAfter" | "scalb", 2) => &args[..1],
("copySign", 2) => args,
_ => return false,
};
deciding.iter().all(|a| {
matches!(
self.expr_java_type(a).as_deref().map(unwrapped_ty),
Some("float")
)
})
}
/// The Java type a width-overloaded `Math` static answers, or `None` when
/// this is not one or its overload cannot be resolved.
///
/// `toIntExact` is the one whose result is not its operand width: it takes a
/// `long` and answers an `int`, which is what it is for.
fn width_overload_java_type(
&self,
class: &str,
method: &str,
args: &[Expr],
) -> Option<&'static str> {
if method == "toIntExact" {
return is_width_overloaded(class, method, args.len()).then_some("int");
}
Some(match self.width_overload(class, method, args)? {
crate::host::width::LONG => "long",
crate::host::width::FLOAT => "float",
crate::host::width::DOUBLE => "double",
_ => "int",
})
}
/// The wrapper class `e` autoboxes into when it crosses into a reference
/// position, or `None` when it crosses unchanged.
///
/// `char` and `boolean` are absent on purpose. A `char` is boxed to its
/// `Character` by each caller that needs one, since several positions want
/// its one-character String instead (a `String`-method argument, a string
/// conversion); `boolean` is not a boxed class here at all. An expression javars cannot type is left alone,
/// so it compares by value exactly as it did before.
fn autobox_code(&self, e: &Expr) -> Option<i64> {
let ty = self.expr_java_type(e)?;
let wrapper = match ty.as_str() {
"int" => "Integer",
"long" => "Long",
"short" => "Short",
"byte" => "Byte",
"float" => "Float",
"double" => "Double",
_ => return None,
};
crate::host::box_class_code(wrapper)
}
/// Lower `e` and unbox the result when its static type is a wrapper class.
///
/// For the operators that do **not** reach [`crate::host::numeric_hook`] —
/// `&`, `|`, `^`, the shifts, and `~`, which fusevm answers natively for
/// every operand shape. A boxed operand there is a heap handle, and the
/// native op reads it as 0: `Integer x = 1000, y = 6; x | y` answered 0.
/// Arithmetic and the comparisons need no such call, because a pair the
/// native op declines is delegated to the hook, which unboxes.
fn expr_unboxed(&mut self, e: &Expr) -> Result<(), String> {
self.expr(e)?;
if let Some(t) = self.expr_java_type(e) {
self.emit_checked_unbox(&t);
}
Ok(())
}
/// Box the primitive on top of the stack back into `ty` when it is a
/// wrapper class — the `valueOf` that ends a wrapper's `++` or `+=` — so the
/// result honours the `valueOf` cache as a fresh assignment would.
fn emit_rebox(&mut self, ty: &str) {
if let Some(code) = crate::host::box_class_code(ty) {
self.b.emit(Op::LoadInt(code), 0);
self.b.emit(Op::CallBuiltin(crate::host::JBOX, 2), 0);
}
}
/// Unbox the value on top of the stack when `ty` is a wrapper class, the
/// way Java's unboxing conversion does it: through `intValue()` (or its
/// sibling), so a `null` raises `NullPointerException` (JLS 5.1.8) rather
/// than reaching the primitive it was converted for. Any other `ty` emits
/// nothing.
fn emit_checked_unbox(&mut self, ty: &str) {
let code = match ty {
"Boolean" => crate::host::BOX_CLASSES.len() as i64,
_ => match crate::host::box_class_code(ty) {
Some(code) => code,
None => return,
},
};
self.b.emit(Op::LoadInt(code), 0);
self.emit_raising_builtin(crate::host::JUNBOX_NONNULL, 2, 0);
}
/// The text of a compile-time constant `String` expression, or `None` when
/// the expression is not one.
///
/// Java's constant expressions (JLS 15.29) are literals and operations over
/// them, and a concatenation of two is folded by the compiler into a single
/// interned literal. Only the shapes that can appear in a *string*
/// concatenation are folded here — a literal of any kind, and `+` over two
/// of them — because that is the whole of what makes the difference
/// observable: `("a" + "b") == "ab"` is `true` in Java and would be `false`
/// against a concatenation built at run time.
///
/// A `final` local or field initialized to a literal is a constant in Java
/// too; javars does not track that, so `f + "b"` concatenates at run time
/// and compares by identity. That is a `false` where Java answers `true`,
/// and it is noted in BUGS.md rather than guessed at here.
fn const_string(&self, e: &Expr) -> Option<String> {
Some(match e {
Expr::Str(s) => s.clone(),
// A `static final String CONST = "ab"` is a constant *variable*, so
// Java folds its uses. `Expr::Field` covers the qualified spelling
// (`T.CONST`), whose field name is the same key.
Expr::Var(name) => self.string_constants.get(name)?.clone(),
Expr::Field { name, .. } => self.string_constants.get(name)?.clone(),
Expr::Int(n) | Expr::Long(n) => n.to_string(),
Expr::Bool(b) => b.to_string(),
Expr::Char(c) => c.to_string(),
Expr::Binary {
op: BinOp::Add,
lhs,
rhs,
} if self.is_string_concat(lhs, rhs) => {
crate::jstr::concat(&self.const_string(lhs)?, &self.const_string(rhs)?)
}
_ => return None,
})
}
/// The constant-pool index of a Java `String` literal, adding it only the
/// first time that text appears.
///
/// This is Java's string interning, done where it costs nothing: one pool
/// entry per distinct text means every `Op::LoadConst` of that literal hands
/// back a clone of one `Arc`, and `==` — which compares those pointers —
/// answers `true` for two occurrences of the same literal, as Java's does.
///
/// Only *Java* literals come through here. The compiler's own constants
/// (class names, method names, format tags) keep using `add_constant`
/// directly: they never reach a user `==`, and pooling them beside the
/// literals would let an internal string share a literal's identity.
fn string_literal(&mut self, text: &str) -> u16 {
if let Some(&c) = self.literals.get(text) {
return c;
}
let c = self.b.add_constant(Value::str(text.to_string()));
self.literals.insert(text.to_string(), c);
c
}
/// Emit Java's *boxing* or *unboxing* conversion (JLS 5.1.7 / 5.1.8) for the
/// value already on top of the stack, when the target type calls for one.
///
/// This sits in [`Compiler::expr_targeted`] because that is the one place
/// javars lowers a value into a slot of a declared type — a local, a field,
/// an array element, a method argument, a `return`, a conditional branch.
/// Java's boxing conversions happen in exactly those *assignment contexts*,
/// so putting the rule here covers them all rather than at six call sites
/// that could drift.
///
/// A source whose type javars cannot pin down converts neither way. That is
/// deliberate: an unboxed value in a wrapper-typed slot behaves as it always
/// did, whereas boxing a value that is already a reference would turn
/// `Integer b = a;` — an aliasing assignment Java performs no conversion for
/// — into a fresh object, and `a == b` would answer `false` where Java says
/// `true`.
fn emit_boxing_conversion(&mut self, target: &str, e: &Expr) {
// A wrapper-typed target names the class outright. Every *other*
// reference target — `Object`, `Number`, `Comparable`, an erased type
// variable — takes the class Java autoboxes the source primitive into
// (JLS 5.2: a boxing conversion followed by a widening reference one),
// which is what makes `((Object) aLong).getClass()` answer
// `java.lang.Long` rather than the `Integer` one `Value::Int` reads as.
let code = match crate::host::box_class_code(target) {
Some(code) => {
if self
.expr_java_type(e)
.is_some_and(|src| is_reference_type(&src))
{
return;
}
code
}
// `char` and `boolean` are absent from `autobox_code` for the
// reasons it gives, and a `char` bound to a reference slot has
// already been converted to its one-character String above.
None if is_reference_type(target) => match self.autobox_code(e) {
Some(code) => code,
None => return,
},
None => return,
};
self.b.emit(Op::LoadInt(code), 0);
self.b.emit(Op::CallBuiltin(crate::host::JBOX, 2), 0);
}
/// The reverse of [`Compiler::emit_boxing_conversion`]: a wrapper flowing
/// into a primitive slot.
///
/// Without it the handle would sit in an `int` variable, and `==` between
/// two such variables would compare the handles they were copied from
/// rather than the numbers they hold.
fn emit_unboxing_conversion(&mut self, target: &str, e: &Expr) {
// A `void` target discards the value — the expression body of a
// `Runnable` lambda (`() -> map.put(k, null)`) converts nothing, so an
// `Integer` result that is `null` is not unboxed.
if is_reference_type(target) || target == "void" {
return;
}
// A source javars cannot type unboxes too. `int x = list.get(0)` reads
// an element whose static type erasure has thrown away, and that element
// may be a box — leaving it in an `int` slot would make `==` between two
// such variables compare handles. The call is `JUNBOX`, which is the
// identity on everything that is not a box, so a source that was never
// boxed is unaffected.
// Erasure is also why such a source unboxes as the *target's* wrapper:
// `javac` reaches `int v = map.get(k)` through a cast to `Integer`, so a
// `null` there raises the same `intValue()` fault a typed one does.
match self.expr_java_type(e) {
Some(src) => self.emit_checked_unbox(&src),
None => match wrapper_of(target) {
Some(wrapper) => self.emit_checked_unbox(wrapper),
None => {
self.b.emit(Op::CallBuiltin(crate::host::JUNBOX, 1), 0);
}
},
}
}
/// The type a conditional's two branches are promoted to when it is a
/// *floating* one — `flag ? 1 : 2.0` is a `double` conditional, so the `int`
/// branch widens to 1.0 (JLS 15.25 binary numeric promotion). `None` for
/// every other conditional, including the integral ones, whose branches are
/// already represented identically.
fn ternary_promotion(&self, then: &Expr, els: &Expr) -> Option<&'static str> {
let t = numeric_rank(self.expr_java_type(then)?.as_str())?;
let e = numeric_rank(self.expr_java_type(els)?.as_str())?;
match rank_name(t.max(e)) {
"double" => Some("double"),
"float" => Some("float"),
_ => None,
}
}
/// The declared type name of the field `name` on `recv`'s static class, when
/// both are statically known.
fn field_type_name(&self, recv: &Expr, name: &str) -> Option<String> {
let rc = self.expr_class(recv)?;
self.classes.get(&rc)?.field_types.get(name).cloned()
}
/// The instance-map key of the field `name` on `recv`: the cell of the
/// declaration `recv`'s static class sees (JLS 15.11.1 — a field access
/// is resolved against the static type, never the runtime class). The bare
/// name when the class is not statically known, which is the topmost
/// declaration's cell and the only one a program without hiding has.
fn field_key(&self, recv: &Expr, name: &str) -> String {
self.expr_class(recv)
.and_then(|c| self.classes.get(&c)?.field_keys.get(name).cloned())
.unwrap_or_else(|| name.to_string())
}
/// The static numeric category of `e` under Java's binary numeric promotion.
/// Drives the truncating-vs-floating choice for `/`.
fn expr_type(&self, e: &Expr) -> NumType {
match e {
// A class literal is a reference value, so it has no numeric
// category — the same answer a String literal gets.
Expr::ClassLit(_) => NumType::Other,
// A pattern label is a `switch` label, never a value; it has no
// numeric category because it never reaches an operator.
Expr::TypePattern { .. } => NumType::Other,
Expr::Int(_) | Expr::Long(_) => NumType::Int,
Expr::Float(_) | Expr::Float32(_) => NumType::Float,
Expr::Str(_) | Expr::Bool(_) => NumType::Other,
// `char` is integral, so `'a' / 2` truncates like any other `int`
// division.
Expr::Char(_) => NumType::Int,
Expr::Var(name) => self.lookup_type(name),
Expr::Unary { op, rhs } => match op {
// `+x`/`-x` keep the operand's numeric type; `~x` is always
// integral; `!b` is boolean.
UnOp::Neg | UnOp::Plus => self.expr_type(rhs),
UnOp::BitNot => NumType::Int,
UnOp::Not => NumType::Other,
},
// A cast states the type outright.
Expr::Cast { ty, .. } => numtype_of_ty(ty).unwrap_or(NumType::Other),
Expr::Binary { op, lhs, rhs } => match op {
// Shifts and bitwise ops on integral operands stay integral;
// `&`/`|`/`^` on booleans do not, which `expr_java_type`
// distinguishes.
BinOp::Shl | BinOp::Shr | BinOp::Ushr => NumType::Int,
BinOp::BitAnd | BinOp::BitOr | BinOp::BitXor => {
if self.expr_type(lhs) == NumType::Int && self.expr_type(rhs) == NumType::Int {
NumType::Int
} else {
NumType::Other
}
}
BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Mod => {
let l = self.expr_type(lhs);
let r = self.expr_type(rhs);
// A non-numeric operand (String `+` concat, or unknown) is
// not integral; otherwise a float operand promotes to float.
if l == NumType::Other || r == NumType::Other {
NumType::Other
} else if l == NumType::Float || r == NumType::Float {
NumType::Float
} else {
NumType::Int
}
}
// Comparisons and logical ops yield `boolean`.
_ => NumType::Other,
},
Expr::PostIncDec { name, .. } | Expr::PreIncDec { name, .. } => self.lookup_type(name),
// `a[i]++` has the element's type, `p.n++` the field's — whichever
// the target expression already reports.
Expr::IncDec { target, .. } => self.expr_type(target),
Expr::Assign { target, .. } => self.expr_type(target),
Expr::Println { .. } => NumType::Other,
// A conditional expression's numeric category is the promotion of
// its two result branches (Java's conditional-expression typing).
Expr::Ternary { then, els, .. } => {
let t = self.expr_type(then);
let e = self.expr_type(els);
if t == NumType::Other || e == NumType::Other {
NumType::Other
} else if t == NumType::Float || e == NumType::Float {
NumType::Float
} else {
NumType::Int
}
}
Expr::Call { name, args, .. } => {
if let Some(nt) = self.known_generic_type(e).and_then(|t| numtype_of_ty(&t)) {
return nt;
}
let arg_tys: Vec<Option<String>> = self.arg_types(args);
self.resolve_static_call(name, &arg_tys)
.map(|s| s.ret)
.unwrap_or(NumType::Other)
}
Expr::MethodCall {
recv, method, args, ..
} => {
// A JDK generic member typed by its receiver's type arguments.
if let Some(nt) = self
.expr_generic(e)
.and_then(|g| numtype_of_ty(&crate::ast::generic_parts(&g).0))
{
return nt;
}
// `T.helper(x)` — the named class's declared return type.
if let Some(class) = self.user_class_ref(recv) {
let arg_tys: Vec<Option<String>> = self.arg_types(args);
return self
.resolve_static_on(&class, method, &arg_tys)
.map(|s| s.ret)
.unwrap_or(NumType::Other);
}
// Static stdlib calls that yield an `int` participate in `/`
// truncation typing.
if let Expr::Var(class) = recv.as_ref() {
// The width-overloaded `Math` statics answer at the width
// their arguments selected, and `/` truncation follows it:
// `Math.addExact(1L, 2L) / 2` is integral division.
if let Some(t) = self.width_overload_java_type(class, method, args) {
return numtype_of_ty(t).unwrap_or(NumType::Other);
}
if let Some(nt) = static_call_numtype(class, method) {
return nt;
}
}
// A user-class instance method's declared return type.
if let Some(rc) = self.expr_class(recv) {
let arg_tys: Vec<Option<String>> = self.arg_types(args);
if let Some(r) = self.resolve_instance_call(&rc, method, &arg_tys) {
return r.ret;
}
}
// The `String` instance methods that return `int`.
match method.as_str() {
"length" | "indexOf" => NumType::Int,
_ => NumType::Other,
}
}
// An array element's category comes from the array's declared type
// (`int[]` → int, `double[]` → double); `.length` is always `int`.
Expr::Index { array, .. } => match array.as_ref() {
Expr::Var(name) => self
.var_decl_type(name)
.map(array_elem_numtype)
.unwrap_or(NumType::Other),
_ => NumType::Other,
},
Expr::Field { recv, name } => {
if name == "length" {
return NumType::Int;
}
// `Long.MAX_VALUE` / `Integer.MIN_VALUE` / `Math.PI` — a
// wrapper's `static final`. [`Compiler::expr_java_type`] already
// reads this table; without the same arm here the constant's
// category is `Other`, which sends `Long.MAX_VALUE / 2` down the
// *floating* division path and answers 4.611686018427388E18.
// The `int`-width constants hid the gap: their division is
// followed by [`Compiler::emit_wrap32`], which truncated the
// float back to the right integer by accident.
if let Some((_, ty)) = self.wrapper_constant_ref(e) {
return numtype_of_ty(ty).unwrap_or(NumType::Other);
}
if let Some((_, ty)) = self.static_field_ref(e) {
return numtype_of_ty(&ty).unwrap_or(NumType::Other);
}
self.expr_class(recv)
.and_then(|rc| {
self.classes
.get(&rc)
.and_then(|ci| ci.field_types.get(name))
.and_then(|ty| numtype_of_ty(ty))
})
.unwrap_or(NumType::Other)
}
// Reference- and boolean-valued expressions are never a numeric
// category.
Expr::NewArray { .. }
| Expr::ArrayLit { .. }
| Expr::NewObject { .. }
| Expr::InstanceOf { .. }
| Expr::Lambda { .. }
| Expr::MethodRef { .. }
| Expr::This => NumType::Other,
// A `switch` expression's category is that of its type (JLS
// 15.28.1), which promotes across *every* result expression: one
// `double` arm makes the whole switch `double`.
Expr::SwitchExpr { arms, .. } => self
.switch_expr_type(arms)
.and_then(|t| numtype_of_ty(&t))
.or_else(|| switch_result_exprs(arms).first().map(|e| self.expr_type(e)))
.unwrap_or(NumType::Other),
}
}
/// Lower one user-defined static method to a call-frame subroutine. Args
/// arrive on the value stack (`arg0` deepest); the prologue binds them into
/// frame slots `0..arity`, the body runs in slot scope, and every exit
/// leaves exactly one value on the stack (`Undef` for `void`) so a call is
/// always stack-balanced.
fn compile_method(&mut self, m: &Method) -> Result<(), String> {
let entry = self.b.current_pos();
let param_tys: Vec<String> = m.params.iter().map(|p| p.ty.clone()).collect();
let mangled = mangle_static(&m.owner, &m.name, ¶m_tys);
let name_idx = self.b.add_name(&mangled);
self.b.add_sub_entry(name_idx, entry);
self.current_ret_generic = self.ret_generics.get(&mangled).cloned();
self.current_ret_wildcard = self.ret_wildcards.contains(&mangled);
let mut scope = MethodScope::new();
register_params(&mut scope, &m.params);
self.scope = Some(scope);
// A `static` method sees its own class's statics unqualified.
let saved_class = self.current_class.replace(m.owner.clone());
let saved_ret = self.current_ret.replace(m.ret.clone());
// Prologue: pop args into their slots. The last parameter is on top of
// the stack, so bind slots high-to-low.
for i in (0..m.params.len()).rev() {
self.b.emit(Op::SetSlot(i as u16), m.line);
}
let result = m.body.iter().try_for_each(|s| self.stmt(s));
// Implicit `return;` on fall-off — `void` methods yield `null`.
self.b.emit(Op::LoadUndef, m.line);
self.b.emit(Op::ReturnValue, m.line);
self.scope = None;
self.current_class = saved_class;
self.current_ret = saved_ret;
self.current_ret_generic = None;
result
}
// ── lambdas ──────────────────────────────────────────────────────────
//
// A lambda is a value that outlives the frame it was written in, but a
// javars local lives in a fusevm call-frame slot that does not. So the
// literal site emits a heap closure carrying a *snapshot* of the enclosing
// locals, and the body becomes an ordinary subroutine whose slots hold the
// parameters first and those captured values after. Java only lets a lambda
// read effectively-final locals, so the snapshot is observationally exact —
// and it is what gives the enhanced `for` Java's per-iteration capture,
// which a by-name read of javars's shared loop variable would not.
/// Build a closure value at a lambda literal: push the captured upvalues,
/// then the body's name index, parameter count, and capture count, and call
/// [`crate::host::JMAKE_CLOSURE`] (which returns the handle). The body itself
/// is queued for emission with the other subroutines.
fn compile_lambda(
&mut self,
params: &[String],
body: &LambdaBody,
line: u32,
) -> Result<(), String> {
// The interface this lambda implements (when the assignment context
// named one) types its parameters, so `Calc c = x -> 100 / x;` divides
// integrally exactly where `int of(int)` says it should.
// The interface's declared *return* type comes along for the same
// reason: a `double of(int)` lambda widens its body's `int` result, so
// `F f = a -> a; f.of(4)` is 4.0 exactly as Java's assignment
// conversion on the `return` makes it.
let target = self.lambda_target.take();
let hint = self.lambda_ret_hint.take();
let param_hint = self.lambda_param_hint.take();
let lambda_generic = self.lambda_generic.take();
let sam = target.as_deref().and_then(|t| self.functional_sam_meta(t));
let mut param_tys: Vec<String> = sam.map(|s| s.param_tys.clone()).unwrap_or_default();
let mut ret_ty: Option<String> = sam.map(|s| s.ret.clone()).or(hint);
let mut param_generic: Vec<Option<String>> = vec![None; params.len()];
// A lambda handed to a JDK generic method takes its parameter types
// from the receiver's type arguments, there being no target interface
// in scope to read them off.
if let Some(hint) = param_hint.filter(|h| sam.is_none() && h.len() == params.len()) {
param_generic = hint.iter().map(|t| Some(t.clone())).collect();
param_tys = hint;
}
// `Function<Integer, Integer> f = x -> x * 2;` — javac types `x` and
// the result as `Integer`, so the product wraps at 32 bits.
if let Some((base, targs)) = lambda_generic
.map(|g| crate::ast::generic_parts(&g))
.filter(|(base, _)| target.as_deref() == Some(base.as_str()))
{
// The JDK interfaces by their table, a user generic interface by
// its single abstract method's own declared generic signature.
let sigs = match functional_type_arg_slots(&base) {
Some((slots, ret)) => Some((
slots.iter().map(|&i| targs.get(i).cloned()).collect(),
ret.and_then(|i| targs.get(i).cloned()),
)),
None => self.user_sam_generics(&base, &targs),
};
let known = |t: &String| is_known_type(&crate::ast::generic_parts(t).0);
if let Some((ps, ret)) = sigs {
for ((slot, g), t) in param_tys.iter_mut().zip(&mut param_generic).zip(ps) {
if let Some(t) = t.filter(|t| slot == "Object" && known(t)) {
*slot = t.clone();
*g = Some(t);
}
}
if let Some(t) = ret.filter(known) {
if ret_ty.as_deref() == Some("Object") {
ret_ty = Some(t);
}
}
}
}
// A type argument keeps its own arguments; the slots take the erasure.
for t in param_tys.iter_mut().chain(ret_ty.as_mut()) {
if t.contains('<') {
*t = crate::ast::generic_parts(t).0;
}
}
// Capture every name declared in the enclosing scope that the lambda's
// own parameters do not shadow. Compiler temps are deliberately not in
// `declared`, so none are captured.
let mut visible: Vec<String> = match &self.scope {
Some(sc) => sc.declared.iter().cloned().collect(),
None => self
.global_decl_types
.keys()
.chain(self.global_types.keys())
.cloned()
.collect(),
};
visible.sort();
visible.dedup();
let captures: Vec<Capture> = visible
.into_iter()
.filter(|n| !params.contains(n))
.map(|n| Capture {
decl_ty: self.var_decl_type(&n).map(str::to_string),
generic: self.local_generic(&n),
num_ty: self.lookup_type(&n),
name: n,
})
.collect();
for c in &captures {
let name = c.name.clone();
self.emit_get(&name, line);
}
let captures_this = self.this_class.is_some();
if captures_this {
self.emit_this(line);
}
// The functional interface the lambda converts to is its type for
// `instanceof` and a checked cast (JLS 15.27.3). It rides in the body's
// subroutine name, with the class that wrote it, where the host reads
// it back ([`crate::host`]'s `lambda_iface`) — so a closure carries it
// without any work at creation.
let mut sub_name = format!("#lambda#{}", self.lambda_counter);
if let Some(iface) = target.filter(|t| self.functional_sam_meta(t).is_some()) {
let encloser = self.current_class.clone().unwrap_or_default();
let encloser = self
.classes
.get(&encloser)
.map_or(encloser.clone(), |ci| ci.binary.clone());
sub_name = format!("{sub_name}#{iface}#{encloser}");
}
let name_idx = self.b.add_name(&sub_name);
self.lambda_counter += 1;
let ncap = captures.len() + usize::from(captures_this);
self.pending_lambdas.push(PendingLambda {
name_idx,
params: params.to_vec(),
param_tys,
param_generic,
ret_ty,
captures,
captures_this,
body: body.clone(),
this_class: self.this_class.clone(),
current_class: self.current_class.clone(),
line,
});
self.b.emit(Op::LoadInt(name_idx as i64), line);
self.b.emit(Op::LoadInt(params.len() as i64), line);
self.b.emit(Op::LoadInt(ncap as i64), line);
self.b.emit(
Op::CallBuiltin(crate::host::JMAKE_CLOSURE, ncap as u8 + 3),
line,
);
Ok(())
}
/// Emit a queued lambda body as a subroutine. Slots hold the parameters
/// (`0..n`), then the captured upvalues, then `this` when one was captured;
/// the prologue binds all of them high-to-low, exactly like a method's.
///
/// The body is its own frame for `break`/`continue`/`return`/`try`, so those
/// stacks are swapped out around it — a `return` inside a lambda returns from
/// the *lambda*, not from the method that wrote it.
fn compile_lambda_body(&mut self, pl: PendingLambda) -> Result<(), String> {
let entry = self.b.current_pos();
self.b.add_sub_entry(pl.name_idx, entry);
let line = pl.line;
let mut scope = MethodScope::new();
for (i, p) in pl.params.iter().enumerate() {
scope.slot(p);
scope.declared.insert(p.clone());
if let Some(ty) = pl.param_tys.get(i) {
scope.decl_types.insert(p.clone(), ty.clone());
scope
.types
.insert(p.clone(), numtype_of_ty(ty).unwrap_or(NumType::Other));
}
if let Some(g) = pl
.param_generic
.get(i)
.cloned()
.flatten()
.filter(|g| g.contains('<'))
{
scope.decl_generic.insert(p.clone(), g);
}
}
for c in &pl.captures {
scope.slot(&c.name);
scope.declared.insert(c.name.clone());
scope.types.insert(c.name.clone(), c.num_ty);
if let Some(t) = &c.decl_ty {
scope.decl_types.insert(c.name.clone(), t.clone());
}
if let Some(g) = &c.generic {
scope.decl_generic.insert(c.name.clone(), g.clone());
}
}
let total = pl.params.len() + pl.captures.len() + usize::from(pl.captures_this);
if pl.captures_this {
// `this` rides in the slot after the last named capture; nothing
// reads it by name, so it needs no `declared` entry.
scope.this_slot = Some((total - 1) as u16);
scope.next_slot = total as u16;
}
let saved_scope = self.scope.replace(scope);
let saved_this = std::mem::replace(&mut self.this_class, pl.this_class.clone());
let saved_current = std::mem::replace(&mut self.current_class, pl.current_class.clone());
let saved_scopes = std::mem::take(&mut self.scopes);
let saved_tries = std::mem::take(&mut self.tries);
let saved_finallys = std::mem::take(&mut self.finallys);
let saved_exits = std::mem::take(&mut self.exit_ops);
let saved_ret = std::mem::replace(&mut self.current_ret, pl.ret_ty.clone());
let saved_ret_generic = self.current_ret_generic.take();
let saved_ret_wildcard = std::mem::take(&mut self.current_ret_wildcard);
for i in (0..total).rev() {
self.b.emit(Op::SetSlot(i as u16), line);
}
let result = match &pl.body {
// An expression body's value is the lambda's result, converted to
// the single abstract method's declared return type.
LambdaBody::Expr(e) => self.expr_targeted(e, pl.ret_ty.as_deref()).map(|()| {
self.b.emit(Op::ReturnValue, line);
}),
LambdaBody::Block(stmts) => stmts.iter().try_for_each(|s| self.stmt(s)),
};
// Fall-off (and a bare `return;`) yields `null`, which is what a `void`
// functional interface wants and what a value-returning one never reaches.
let end = self.b.current_pos();
let exits = std::mem::replace(&mut self.exit_ops, saved_exits);
for op in exits {
self.b.patch_jump(op, end);
}
self.b.emit(Op::LoadUndef, line);
self.b.emit(Op::ReturnValue, line);
self.scope = saved_scope;
self.this_class = saved_this;
self.current_class = saved_current;
self.scopes = saved_scopes;
self.tries = saved_tries;
self.finallys = saved_finallys;
self.current_ret = saved_ret;
self.current_ret_generic = saved_ret_generic;
self.current_ret_wildcard = saved_ret_wildcard;
result
}
/// The single abstract method of a functional interface: `(name, arity)`.
///
/// Any interface with exactly one abstract method is a lambda target — Java's
/// own rule, and the reason a user-declared `interface Calc { int of(int a); }`
/// works with no registration. The `java.util.function` interfaces reach here
/// the same way, because [`crate::prelude`] declares them as ordinary
/// one-method interfaces.
fn functional_sam(&self, ty: &str) -> Option<(String, usize)> {
let sam = self.functional_sam_meta(ty)?;
Some((sam.name.clone(), sam.param_tys.len()))
}
/// The full signature of a functional interface's single abstract method.
fn functional_sam_meta(&self, ty: &str) -> Option<&MethodMeta> {
let ci = self.classes.get(ty)?;
if !ci.is_interface {
return None;
}
let mut abstracts = ci.methods.iter().filter(|m| m.is_abstract);
let sam = abstracts.next()?;
abstracts.next().is_none().then_some(sam)
}
/// Lower `e` knowing the type it is being assigned to — the site of Java's
/// *assignment conversion*. A lambda (or the method reference that desugars
/// to one) reads the target as its functional interface; an integral
/// expression assigned into a `float`/`double` slot is widened; a `char`
/// entering a reference slot is boxed; and a bare `{…}` array literal takes
/// its element type from the declaration it initializes.
fn expr_targeted(&mut self, e: &Expr, target: Option<&str>) -> Result<(), String> {
// An anonymous class javars lowered (see `parser::anonymous_named`)
// takes the target itself — its lambda is the one the target types.
if let Expr::Call { name, args, .. } = e {
if name == crate::parser::ANON_CLASS_CALL {
self.expr_targeted(&args[0], target)?;
self.emit_anon_class_name(&args[1]);
return Ok(());
}
}
let generic = self.pending_target_generic.take();
let exact = self.target_wildcard.take().map(|w| !w);
if let Some(msg) =
target.and_then(|t| self.incompatible_inferred_return(t, generic.as_deref(), exact, e))
{
return Err(msg);
}
// A targeted `switch` expression is a poly expression: the target
// reaches each result expression, which converts on its own.
if let (Expr::SwitchExpr { disc, arms, line }, Some(_)) = (e, target) {
return self.switch_expr(disc, arms, *line, target);
}
if !matches!(e, Expr::Lambda { .. } | Expr::MethodRef { .. }) {
// A `char` bound to a reference-typed slot (`Object o = 'x';`, an
// `Object` parameter, an `Object`-returning method) is *boxed* in
// Java. It boxes here too — as a real `Character`, which is what
// makes `((Object) 'x').getClass()` answer `java.lang.Character` and
// `o instanceof Character` `true`. A `Character` box renders as its
// character, so it prints exactly as the one-character String this
// used to produce. A collection element boxes the same way.
// The *primitive* `char` only: a `Character`-typed expression is
// already a reference, and boxing it again would make
// `Character c = 'z'; Object o = c; o == c` `false` where Java —
// which performs no conversion on that assignment — says `true`.
if let Some(t) = target {
if is_reference_type(t) && self.expr_java_type(e).as_deref() == Some("char") {
self.expr(e)?;
let code = crate::host::box_class_code("Character")
.expect("`Character` is a boxed class");
self.b.emit(Op::LoadInt(code), 0);
self.b.emit(Op::CallBuiltin(crate::host::JBOX, 2), 0);
return Ok(());
}
}
// `double[] a = {1, 2};` — the untyped literal takes its element
// type from the declaration, and every element is assigned into a
// slot of that type, so the conversion applies element-wise.
if let Expr::ArrayLit {
elems,
elem_ty: None,
} = e
{
if let Some(el) = target.and_then(|t| t.strip_suffix("[]")) {
let el = el.to_string();
return self.array_lit(elems, Some(&el));
}
}
if let Some(t) = target.filter(|t| !is_reference_type(t) && *t != "void") {
if self.expr_java_type(e).as_deref() == Some("String") {
return Err(string_to_primitive(t));
}
}
let widen = self.widen_target(target, e);
self.expr(e)?;
// Unboxing runs *before* any widening and boxing *after* it, which
// is the order Java converts in: `double d = anInteger` unboxes to
// an `int` and then widens (JLS 5.2), and widening a handle would
// read it as 0.
if let Some(t) = target {
self.emit_unboxing_conversion(t, e);
}
if let Some(w) = widen {
self.emit_widen(w, 0);
}
if let Some(t) = target {
self.emit_boxing_conversion(t, e);
}
return Ok(());
}
let saved = std::mem::replace(&mut self.lambda_target, target.map(str::to_string));
let result = self.expr(e);
self.lambda_target = saved;
result
}
/// [`Compiler::expr_targeted`] for a target whose type arguments are known:
/// a lambda literal reads its parameter and return types off them, the way
/// `Function<Integer, Integer> f = x -> x * 2` types `x` as an `Integer`.
fn expr_targeted_generic(
&mut self,
e: &Expr,
target: Option<&str>,
generic: Option<String>,
) -> Result<(), String> {
if matches!(e, Expr::Lambda { .. } | Expr::MethodRef { .. }) {
self.lambda_generic = generic.clone();
}
self.pending_target_generic = generic;
let r = self.expr_targeted(e, target);
self.lambda_generic = None;
r
}
/// [`Compiler::call_args_targeted`] for a call to the user method or
/// constructor `mangled`, whose parameters' type arguments (when it
/// declared any) reach the lambda literals passed to them.
fn call_args_generic(
&mut self,
args: &[Expr],
param_tys: &[String],
mangled: &str,
) -> Result<(), String> {
let (names, types) = self.infer_bindings(mangled, args);
let generics: Vec<Option<String>> = self
.param_generics
.get(mangled)
.map(|gs| {
gs.iter()
.map(|g| g.as_ref().map(|g| subst_tvars(g, &names, &types)))
.collect()
})
.unwrap_or_default();
let wildcards = self
.param_wildcards
.get(mangled)
.cloned()
.unwrap_or_default();
self.call_args_with_generics(args, param_tys, &generics, &wildcards)
}
/// True when some user `static` method named `name` declares a generic
/// return type — the only calls [`Compiler::expr_generic`] has to resolve.
fn has_generic_return(&self, name: &str) -> bool {
self.methods.get(name).is_some_and(|sigs| {
sigs.iter().any(|s| {
self.ret_generics
.contains_key(&mangle_static(&s.owner, name, &s.param_tys))
})
})
}
/// The type variables a call to `mangled` binds from its arguments, as
/// parallel name and type lists for [`subst_tvars`] — the simple cases of
/// `javac`'s inference (JLS 18.5.1): a parameter typed `E` binds `E` to its
/// argument's static type (boxed, as a primitive argument is), and a
/// `List<E>` parameter binds it to the argument's own type argument.
fn infer_bindings(&self, mangled: &str, args: &[Expr]) -> (Vec<String>, Vec<String>) {
self.infer_bindings_with(mangled, args, true)
}
/// [`Compiler::infer_bindings`], optionally without the lambda pass —
/// what `javac`'s applicability inference sees before a lambda's body is
/// pertinent (JLS 18.5.1).
fn infer_bindings_with(
&self,
mangled: &str,
args: &[Expr],
lambdas: bool,
) -> (Vec<String>, Vec<String>) {
let Some(params) = self.param_generics.get(mangled) else {
return (Vec::new(), Vec::new());
};
let mut bound: Vec<(String, String)> = Vec::new();
for (p, a) in params.iter().zip(args) {
let Some(p) = p else { continue };
let actual = self.expr_generic(a).or_else(|| {
self.expr_java_type(a)
.map(|t| wrapper_of(&t).map_or(t.clone(), str::to_string))
});
if let Some(actual) = actual.filter(|t| t != NULL_LITERAL) {
unify_tvars(p, &actual, &mut bound);
}
}
// A lambda argument binds its functional interface's result variable
// from its body, typed under the parameter types the other arguments
// have already bound (JLS 18.2.1) — `ap(1, x -> 0.1f)` makes `R` a
// `Float` once `S` is an `Integer`.
for (p, a) in params.iter().zip(args).filter(|_| lambdas) {
let Some(p) = p
.as_ref()
.filter(|_| matches!(a, Expr::Lambda { .. } | Expr::MethodRef { .. }))
else {
continue;
};
let (names, types): (Vec<String>, Vec<String>) = bound.iter().cloned().unzip();
let (base, targs) = crate::ast::generic_parts(&subst_tvars(p, &names, &types));
let Some((ps, Some(ret))) = self.functional_shape(&base, &targs) else {
continue;
};
let ps: Vec<String> = ps.into_iter().map(Option::unwrap_or_default).collect();
// `ret` came through the bindings, so a variable still free in it is
// one the body binds.
if let Some(actual) = self.lambda_result_type(a, &ps) {
unify_tvars(&ret, &actual, &mut bound);
}
}
bound.into_iter().unzip()
}
/// `javac`'s rejection of a generic call assigned to a primitive whose
/// return type is a bare type variable that only a lambda's result binds
/// (JLS 18.5.2.1): with no argument binding `R` beforehand, the primitive
/// target makes `R` its wrapper, and a lambda returning anything else
/// leaves `R` with incompatible bounds — `double d = ap(1, x -> 9)` binds
/// `R` to both `Double` and `Integer`. `Some(message)` for such a call.
fn incompatible_inferred_return(
&self,
target: &str,
generic: Option<&str>,
exact: Option<bool>,
init: &Expr,
) -> Option<String> {
let (name, args, line) = match init {
Expr::Call { name, args, line } => (name.as_str(), args, *line),
_ => return None,
};
if !self.has_generic_return(name) {
return None;
}
let resolved = self.resolve_static_call(name, &self.arg_types(args))?;
let var = self
.ret_generics
.get(&resolved.mangled)?
.strip_prefix('#')?;
let (before, before_types) = self.infer_bindings_with(&resolved.mangled, args, false);
let from_args = before
.iter()
.position(|n| n == var)
.map(|k| before_types[k].clone());
let (names, types) = self.infer_bindings(&resolved.mangled, args);
let got = names
.iter()
.position(|n| n == var)
.map(|k| types[k].clone())?;
let reject = || {
Some(format!(
"javars: incompatible types: inference variable {var} has incompatible bounds (target {target}, lower bounds: {got}) on line {line}"
))
};
match (wrapper_of(target), from_args) {
// A primitive target, the variable bound by an argument: the bound
// must unbox to a primitive that widens to the target (`long x =
// id(1)` is fine, `int x = id(1.5)` is not).
(Some(_), Some(_)) => {
let prim = unwrapped_ty(&got);
let widens = prim == target
|| matches!(
(prim, target),
("byte", "short" | "int" | "long" | "float" | "double")
| ("short" | "char", "int" | "long" | "float" | "double")
| ("int", "long" | "float" | "double")
| ("long", "float" | "double")
| ("float", "double")
);
let fits = prim != got.as_str() && widens;
if fits {
None
} else {
reject()
}
}
// Bound only by a lambda's result: the primitive target fixes the
// variable as its wrapper first, and the result must be exactly it.
(Some(want), None) => (got != want).then(reject).flatten(),
// A reference target: the bound must be assignable to it. Only
// what javars can decide is refused — a final JDK class the bound
// is not, or two user classes that are unrelated.
(None, _) => {
if got == target || target == "Object" || !is_reference_type(target) {
return None;
}
let final_jdk = |t: &str| {
matches!(
t,
"String"
| "Integer"
| "Long"
| "Short"
| "Byte"
| "Character"
| "Boolean"
| "Double"
| "Float"
)
};
let user = |t: &str| self.classes.contains_key(t);
let unrelated = (final_jdk(target) && (final_jdk(&got) || user(&got)))
|| (user(target)
&& (final_jdk(&got) || (user(&got) && !self.is_subclass(&got, target))));
if unrelated {
return reject();
}
// Any other JDK target — an interface, or a class a user class
// could extend — is decided when every supertype of the bound
// is known: a final JDK class's are fixed, and a user class's
// are its declared ones plus what the JDK interfaces among
// them extend.
// A JDK target: one javars does not model as a class, or one of
// the functional interfaces the prelude declares.
let base = erased_simple_name(target);
let jdk_target = jdk_supertype_entry(base).is_some()
&& (!user(base) || crate::prelude::is_functional(base));
if !jdk_target {
return None;
}
// The bound's own class counts, with its own type arguments
// (`List<Integer>` against `List<String>`).
let (own, own_args) = crate::ast::generic_parts(&got);
let sups = if erased_simple_name(&own) == base {
vec![(base.to_string(), own_args)]
} else {
// Its supertypes' arguments, in terms of its own type
// parameters, take the arguments the bound gives them.
let params: Vec<String> = match jdk_supertype_entry(erased_simple_name(&own)) {
Some((ps, _)) => ps.iter().map(|p| format!("#{p}")).collect(),
None => Vec::new(),
};
let subst = |a: &String| match params.iter().position(|p| p == a) {
Some(i) if params.len() == own_args.len() => own_args[i].clone(),
_ => a.clone(),
};
self.known_supertypes(&got)?
.into_iter()
.map(|(s, args)| (s, args.iter().map(subst).collect()))
.collect()
};
let Some((_, have)) = sups.iter().find(|(s, _)| s == base) else {
return reject();
};
// The target's type arguments against the ones the bound
// gives that supertype (`Integer` is `Comparable<Integer>`).
// Written exactly, an argument must be the same type
// (`Comparable<Number> c = id(5)` is refused); one written as a
// wildcard arrives as its upper bound, so it conflicts only
// when neither type is a subtype of the other.
let want = generic
.map(|g| crate::ast::generic_parts(g).1)
.unwrap_or_default();
let conflict = have.iter().zip(&want).position(|(h, w)| {
let concrete = |t: &str| !t.contains(['#', '?']);
let differ = match exact {
Some(true) => h.replace(' ', "") != w.replace(' ', ""),
Some(false) => w != "Object" && !self.related(h, w),
None => false,
};
concrete(h) && concrete(w) && differ
})?;
// A generic call passed as the argument is inferred jointly
// with this one, so `javac` reports the type argument it
// supplies against that call's own variable.
let named = self.nested_poly_var(&resolved.mangled, var, args, base, conflict);
Some(format!(
"javars: incompatible types: inference variable {} has incompatible bounds (target {target}, lower bounds: {got}) on line {line}",
named.as_deref().unwrap_or(var)
))
}
}
}
/// The inference variable `javac` names when type argument `slot` of the
/// bound of `var` (the variable a call to `mangled` returns) conflicts
/// with the target, and the argument binding `var` is itself a generic
/// call returning a type parameterized by its own variables — a poly
/// expression (JLS 15.12), inferred together with the outer call: that
/// call's variable at `slot` (`id(List.of(1))` against `List<String>` is
/// `List.of`'s `E`). `None` when the argument is anything else.
fn nested_poly_var(
&self,
mangled: &str,
var: &str,
args: &[Expr],
base: &str,
slot: usize,
) -> Option<String> {
let params = self.param_generics.get(mangled)?;
let at = params
.iter()
.position(|p| p.as_deref().and_then(|p| p.strip_prefix('#')) == Some(var))?;
let pick = |vars: &[&str]| -> Option<String> {
let v = if vars.len() == 1 {
vars[0]
} else {
*vars.get(slot)?
};
(!v.is_empty()).then(|| v.to_string())
};
match args.get(at)? {
Expr::Call { name, args, .. } => {
let resolved = self.resolve_static_call(name, &self.arg_types(args))?;
let ret = self.ret_generics.get(&resolved.mangled)?;
let (_, targs) = crate::ast::generic_parts(ret);
let vars: Vec<&str> = targs
.iter()
.map(|t| t.strip_prefix('#').unwrap_or(""))
.collect();
pick(&vars)
}
Expr::MethodCall {
recv, method, args, ..
} => {
let Expr::Var(class) = recv.as_ref() else {
return None;
};
if self.var_decl_type(class).is_some() {
return None;
}
let mut found = crate::jdk_generic_statics::JDK_GENERIC_STATICS
.iter()
.filter(|(c, m, n, varargs, _)| {
c == class
&& m == method
&& (*n == args.len() || (*varargs && args.len() + 1 >= *n))
})
.map(|(.., vars)| *vars);
let first = found.next()?;
found.all(|v| v == first).then_some(())?;
pick(first)
}
// A diamond `new C<>(…)` is a poly expression too: the variable is
// `C`'s own type parameter that supplies the target's argument at
// `slot` (`id(new HashMap<>(Map.of(1, "a")))` against
// `Map<String, Integer>` is `HashMap`'s `K`).
Expr::NewObject {
class,
targs: Some(t),
..
} if t.is_empty() => {
let (params, sups) = jdk_supertype_entry(class)?;
if class == base {
return params.get(slot).map(|p| p.to_string());
}
let (_, sup_args) = sups.iter().find(|(s, _)| *s == base)?;
sup_args.get(slot)?.strip_prefix('#').map(str::to_string)
}
_ => None,
}
}
/// Every supertype of `t` (`Object` aside), each with its type arguments
/// in terms of `t`'s own type parameters (`#E`), as concrete simple names,
/// or `?` — when javars can know them all: a JDK type's from the table
/// generated off the real JDK (`src/jdk_supertypes.rs`), a user class's
/// from its declared supertypes and theirs. `None` when one of them is a
/// type javars knows nothing of.
fn known_supertypes(&self, t: &str) -> Option<Vec<(String, Vec<String>)>> {
self.known_supertypes_depth(t, 0)
}
fn known_supertypes_depth(&self, t: &str, depth: usize) -> Option<Vec<(String, Vec<String>)>> {
let t = erased_simple_name(t);
if !self.classes.contains_key(t) {
let (_, sups) = jdk_supertype_entry(t)?;
return Some(
sups.iter()
.map(|(s, args)| (s.to_string(), args.iter().map(|a| a.to_string()).collect()))
.collect(),
);
}
// A cycle is a program javac rejects; the bound keeps the walk finite.
if depth > 64 {
return None;
}
let ci = self.classes.get(t)?;
let mut direct: Vec<(String, Vec<String>)> = ci.interfaces.clone();
if let Some(sup) = &ci.superclass {
direct.insert(0, (sup.clone(), ci.super_targs.clone()));
}
let mut out: Vec<(String, Vec<String>)> = Vec::new();
for (name, args) in direct {
let name = erased_simple_name(&name).to_string();
let params: Vec<String> = match self.classes.get(&name) {
Some(sci) => sci.type_params.clone(),
None => jdk_supertype_entry(&name)?
.0
.iter()
.map(|p| p.to_string())
.collect(),
};
// A supertype's arguments are written in its own parameters;
// `subst` rewrites them into `t`'s.
let subst = |a: &str| -> String {
match a
.strip_prefix('#')
.and_then(|p| params.iter().position(|q| q == p))
{
Some(i) => args.get(i).cloned().unwrap_or_else(|| "?".to_string()),
None => a.to_string(),
}
};
let inherited = self.known_supertypes_depth(&name, depth + 1)?;
if !out.iter().any(|(s, _)| *s == name) {
out.push((name, args.clone()));
}
for (s, sargs) in inherited {
if !out.iter().any(|(o, _)| *o == s) {
out.push((s, sargs.iter().map(|a| subst(a)).collect()));
}
}
}
Some(out)
}
/// Whether one of two class names is a subtype of the other, as far as
/// javars can tell — `true` when it cannot, so a caller refusing on
/// `false` refuses only what it knows.
fn related(&self, a: &str, b: &str) -> bool {
let (a, b) = (erased_simple_name(a), erased_simple_name(b));
let below = |x: &str, y: &str| match self.known_supertypes(x) {
Some(sups) => sups.iter().any(|(s, _)| s == y),
None => true,
};
a == b || below(a, b) || below(b, a)
}
/// The parameter and result types of the functional interface `base`
/// with type arguments `targs`: the JDK's by their table, a user generic
/// interface by its single abstract method's declared signature.
#[allow(clippy::type_complexity)]
fn functional_shape(
&self,
base: &str,
targs: &[String],
) -> Option<(Vec<Option<String>>, Option<String>)> {
match functional_type_arg_slots(base) {
Some((slots, ret)) => Some((
slots.iter().map(|&i| targs.get(i).cloned()).collect(),
ret.and_then(|i| targs.get(i).cloned()),
)),
None => self.user_sam_generics(base, targs),
}
}
/// Lower a call's arguments, each targeted at its parameter's type and
/// handed that parameter's generic type for a lambda literal to read.
fn call_args_with_generics(
&mut self,
args: &[Expr],
param_tys: &[String],
generics: &[Option<String>],
wildcards: &[bool],
) -> Result<(), String> {
for (i, a) in args.iter().enumerate() {
let g = generics.get(i).cloned().flatten();
if g.is_some() {
self.target_wildcard = Some(wildcards.get(i).copied().unwrap_or(false));
}
self.expr_targeted_generic(a, param_tys.get(i).map(String::as_str), g)?;
}
Ok(())
}
/// Lower a call's arguments, giving each the declared parameter type as its
/// lambda target. `param_tys` may be shorter than `args` (an unresolved
/// signature), in which case the extras lower untargeted.
fn call_args_targeted(&mut self, args: &[Expr], param_tys: &[String]) -> Result<(), String> {
for (i, a) in args.iter().enumerate() {
self.expr_targeted(a, param_tys.get(i).map(String::as_str))?;
}
Ok(())
}
/// Desugar a method reference into the lambda it abbreviates.
///
/// Java infers the reference's arity from its *target* type; javars has no
/// target-typing pass, so the arity is taken from the referenced member's own
/// declaration instead. That resolves every unambiguous form and rejects the
/// rest with a diagnostic rather than guessing.
fn desugar_method_ref(&self, recv: &Expr, method: &str, line: u32) -> Result<Expr, String> {
// Synthesized parameter names. `#` is not a legal Java identifier char,
// so they cannot collide with (or be shadowed by) a user variable.
let mk = |arity: usize| -> Vec<String> { (0..arity).map(|i| format!("#p{i}")).collect() };
let vars =
|ps: &[String]| -> Vec<Expr> { ps.iter().map(|p| Expr::Var(p.clone())).collect() };
let lambda = |params: Vec<String>, body: Expr| Expr::Lambda {
body: LambdaBody::Expr(Box::new(body)),
params,
finals: Vec::new(),
line,
};
// `System.out::println` — the print statement, not a dispatchable method.
if let Expr::Field { recv: sys, name } = recv {
if matches!(&**sys, Expr::Var(v) if v == "System") {
let err = name == "err";
let newline = match method {
"println" => true,
"print" => false,
_ => {
return Err(format!(
"javars: `System.{name}::{method}` is not a supported method reference (line {line})"
))
}
};
let ps = mk(1);
let arg = Expr::Var(ps[0].clone());
return Ok(lambda(
ps,
Expr::Println {
newline,
err,
arg: Some(Box::new(arg)),
},
));
}
}
// `Map.Entry::getKey` — the nested interface, spelled through its
// owner. The type parser flattens `Map.Entry` to `Entry`, and so does
// this.
if let Expr::Field { recv: owner, name } = recv {
if name == "Entry"
&& matches!(&**owner, Expr::Var(v) if v == "Map" && !self.is_declared_var(v))
{
if let Some(e) = self.type_method_ref("Entry", method, line, &mk, &vars, &lambda)? {
return Ok(e);
}
}
}
// `String[]::new` — `n -> new String[n]`, the generator
// `toArray(IntFunction)` and `Stream.toArray` take.
if let Expr::Var(name) = recv {
if let Some(elem) = name.strip_suffix("[]") {
if method == "new" {
let ps = mk(1);
let (base, extra) = {
let base = elem.trim_end_matches("[]");
(base.to_string(), (elem.len() - base.len()) / 2)
};
return Ok(lambda(
ps.clone(),
Expr::NewArray {
elem_ty: base,
sizes: vars(&ps),
extra_dims: extra,
},
));
}
}
}
// A bare type name on the left: `Point::new`, `Point::area`,
// `Integer::parseInt`, `String::length`.
if let Expr::Var(name) = recv {
if !self.is_declared_var(name) {
if let Some(e) = self.type_method_ref(name, method, line, &mk, &vars, &lambda)? {
return Ok(e);
}
}
}
// Otherwise the left side is a value: `obj::method`, `this::method`. The
// receiver must be a plain name so the synthesized lambda captures it —
// Java evaluates the receiver once, at the reference, and a captured
// local is exactly that. A string literal (`"*"::repeat`) qualifies
// too: re-reading a constant at each call is indistinguishable from
// reading it once.
if !matches!(recv, Expr::Var(_) | Expr::This | Expr::Str(_)) {
return Err(format!(
"javars: a bound method reference needs a variable or `this` receiver (line {line})"
));
}
let arity = match self.expr_class(recv) {
Some(rc) => self.unique_method_arity(&rc, method).ok_or_else(|| {
format!(
"javars: `{rc}::{method}` has no single method reference can name (line {line})"
)
})?,
// A `String`, `StringBuilder` or modeled collection receiver names
// one of the JDK instance methods the unbound forms
// (`String::length`, `StringBuilder::append`, `List::add`) admit, at the same unambiguous arity.
None => {
let ty = self.expr_java_type(recv).ok_or_else(|| {
format!("javars: cannot resolve the receiver of `::{method}` (line {line})")
})?;
let arity = if ty == "String" {
string_instance_ref_arity(method)
} else if collection_kind(&ty).is_some() {
collection_instance_ref_arity(method)
} else if matches!(ty.as_str(), "StringBuilder" | "StringBuffer") {
// `sb::append` — the collector a `forEach` writes into.
builder_instance_ref_arity(method)
} else {
None
};
arity.ok_or_else(|| {
format!(
"javars: `{ty}::{method}` is not a method reference javars models (line {line})"
)
})?
}
};
let ps = mk(arity);
Ok(lambda(
ps.clone(),
Expr::MethodCall {
recv: Box::new(recv.clone()),
method: method.to_string(),
args: vars(&ps),
line,
},
))
}
/// The type-name form of [`Compiler::desugar_method_ref`]. Returns `None`
/// when `name` is not a type javars knows, so the caller can fall through to
/// the bound (value receiver) form.
#[allow(clippy::type_complexity)]
fn type_method_ref(
&self,
name: &str,
method: &str,
line: u32,
mk: &dyn Fn(usize) -> Vec<String>,
vars: &dyn Fn(&[String]) -> Vec<Expr>,
lambda: &dyn Fn(Vec<String>, Expr) -> Expr,
) -> Result<Option<Expr>, String> {
if let Some(ci) = self.classes.get(name) {
// `Point::new` — a constructor reference.
if method == "new" {
let arity = match ci.ctors.len() {
0 => 0,
// Captured values are appended at the `new` itself.
1 => ci.ctors[0].param_tys.len() - ci.captures.len(),
_ => {
return Err(format!(
"javars: `{name}::new` is ambiguous — {} constructors (line {line})",
ci.ctors.len()
))
}
};
let ps = mk(arity);
return Ok(Some(lambda(
ps.clone(),
Expr::NewObject {
targs: None,
class: name.to_string(),
args: vars(&ps),
outer: None,
line,
},
)));
}
// `Point::area` — an unbound instance reference takes the receiver as
// its first parameter.
if let Some(arity) = self.unique_method_arity(name, method) {
let ps = mk(arity + 1);
return Ok(Some(lambda(
ps.clone(),
Expr::MethodCall {
recv: Box::new(Expr::Var(ps[0].clone())),
method: method.to_string(),
args: vars(&ps[1..]),
line,
},
)));
}
// `Helper::twice` — a `static` method of a user class.
if let Some(arity) = self.unique_static_arity(method) {
let ps = mk(arity);
return Ok(Some(lambda(
ps.clone(),
Expr::Call {
name: method.to_string(),
args: vars(&ps),
line,
},
)));
}
return Err(format!(
"javars: class `{name}` has no member `{method}` a method reference can name (line {line})"
));
}
// `ArrayList::new`, `StringBuilder::new`, `String::new` — a constructor
// reference to a *modeled stdlib* type rather than a declared one. Every
// one of these was a hard error before: `ArrayList` is not in
// [`is_static_class`], so the reference fell out of this resolver
// entirely and was reported as an unresolvable receiver, and `String` is,
// so it reached the end and was reported as unmodeled. Both spellings
// are ordinary Java — `Collectors.toCollection(ArrayList::new)` and
// `map.computeIfAbsent(k, ArrayList::new)` are how the idiom is written.
//
// javars does not target-type a method reference, so the constructor
// this can name is the **no-argument** one. That is the constructor
// every `Supplier`-shaped use means; the capacity-taking overload is
// only reachable through a functional type javars would have to infer.
if method == "new" && has_no_arg_constructor(name) {
let fresh = |args: Vec<Expr>| Expr::NewObject {
targs: None,
class: name.to_string(),
args,
outer: None,
line,
};
// `Object` has no one-argument constructor, so its reference is
// only ever a `Supplier`.
if name == "Object" {
return Ok(Some(lambda(Vec::new(), fresh(Vec::new()))));
}
// Every other type here also has a one-argument constructor, and
// a `Function`-shaped use means it: `map(String::new)` copies each
// string (or builds one from a `char[]`), `map(StringBuilder::new)`
// starts a builder from each, `collectingAndThen(toList(),
// ArrayList::new)` copies. A `Supplier` call passes no argument and
// the synthesized parameter reads `null`, which picks the
// no-argument constructor. The one call the two readings confuse
// is a `Function` handed an actual `null`, where Java's
// constructor would throw.
let ps = mk(1);
let p = Expr::Var(ps[0].clone());
return Ok(Some(lambda(
ps,
Expr::Ternary {
cond: Box::new(Expr::Binary {
op: BinOp::Eq,
lhs: Box::new(p.clone()),
rhs: Box::new(Expr::Var("null".to_string())),
}),
then: Box::new(fresh(Vec::new())),
els: Box::new(fresh(vec![p])),
},
)));
}
// `List::stream`, `Map.Entry::getKey`, `Collection::size` — an unbound
// instance method of a modeled collection interface or class, the
// mapper a `flatMap`/`flatMapping` over nested collections is written
// with.
if !self.classes.contains_key(name) && collection_kind(name).is_some() {
if let Some(arity) = collection_instance_ref_arity(method) {
let ps = mk(arity + 1);
return Ok(Some(lambda(
ps.clone(),
Expr::MethodCall {
recv: Box::new(Expr::Var(ps[0].clone())),
method: method.to_string(),
args: vars(&ps[1..]),
line,
},
)));
}
}
// `StringBuilder::append`, `StringBuilder::reverse` — an unbound builder
// method, the accumulator and combiner of the three-argument
// `collect(StringBuilder::new, StringBuilder::append,
// StringBuilder::append)`.
// `MatchResult::group`, `Matcher::start` — the mappers a `results()`
// pipeline is written with.
// `Object::toString`, `Object::hashCode` — `java.lang.Object`'s methods
// on any receiver, dispatched on its runtime class.
let regex_ref = (matches!(name, "MatchResult" | "Matcher")
&& matches!(method, "group" | "start" | "end" | "groupCount"))
|| (name == "Object" && matches!(method, "toString" | "hashCode"))
|| (name == "Optional"
&& matches!(
method,
"stream" | "isPresent" | "isEmpty" | "get" | "orElseThrow"
));
if regex_ref && !self.classes.contains_key(name) {
let ps = mk(1);
return Ok(Some(lambda(
ps.clone(),
Expr::MethodCall {
recv: Box::new(Expr::Var(ps[0].clone())),
method: method.to_string(),
args: Vec::new(),
line,
},
)));
}
if matches!(name, "StringBuilder" | "StringBuffer") && !self.classes.contains_key(name) {
if let Some(arity) = builder_instance_ref_arity(method) {
let ps = mk(arity + 1);
return Ok(Some(lambda(
ps.clone(),
Expr::MethodCall {
recv: Box::new(Expr::Var(ps[0].clone())),
method: method.to_string(),
args: vars(&ps[1..]),
line,
},
)));
}
}
// `BigInteger::add`, `BigInteger::valueOf` — the unbound instance
// methods and the one static a stream pipeline over big values names.
if matches!(name, "BigInteger" | "BigDecimal") && !self.classes.contains_key(name) {
if method == "valueOf" {
let ps = mk(1);
return Ok(Some(lambda(
ps.clone(),
Expr::MethodCall {
recv: Box::new(Expr::Var(name.to_string())),
method: method.to_string(),
args: vars(&ps),
line,
},
)));
}
if let Some(arity) = bignum_instance_ref_arity(method) {
let ps = mk(arity + 1);
return Ok(Some(lambda(
ps.clone(),
Expr::MethodCall {
recv: Box::new(Expr::Var(ps[0].clone())),
method: method.to_string(),
args: vars(&ps[1..]),
line,
},
)));
}
}
if !is_static_class(name) {
return Ok(None);
}
// `Integer::parseInt` — a modeled stdlib static.
let overloaded = self
.ref_arity_hint
.filter(|n| stdlib_static_ref_arities(name, method).contains(n));
if let Some(arity) = stdlib_static_ref_arity(name, method).or(overloaded) {
let ps = mk(arity);
return Ok(Some(lambda(
ps.clone(),
Expr::MethodCall {
recv: Box::new(Expr::Var(name.to_string())),
method: method.to_string(),
args: vars(&ps),
line,
},
)));
}
// `Integer::intValue` — an unbound instance method on a wrapper class.
// These are the converters `Number` declares plus the two `Object` ones
// every box answers, and they are what a `mapToInt`/`sorted`/`map`
// pipeline over boxed elements is written with.
if crate::host::box_class_code(name).is_some() {
if let Some(arity) = boxed_instance_ref_arity(method) {
let ps = mk(arity + 1);
return Ok(Some(lambda(
ps.clone(),
Expr::MethodCall {
recv: Box::new(Expr::Var(ps[0].clone())),
method: method.to_string(),
args: vars(&ps[1..]),
line,
},
)));
}
}
// `List::stream`, `Map.Entry::getKey`, `Collection::size` — an unbound
// instance method of a modeled collection interface or class, the
// mapper a `flatMap`/`flatMapping` over nested collections is written
// with.
if !self.classes.contains_key(name) && collection_kind(name).is_some() {
if let Some(arity) = collection_instance_ref_arity(method) {
let ps = mk(arity + 1);
return Ok(Some(lambda(
ps.clone(),
Expr::MethodCall {
recv: Box::new(Expr::Var(ps[0].clone())),
method: method.to_string(),
args: vars(&ps[1..]),
line,
},
)));
}
}
// `String::length` — an unbound `String` instance method.
if name == "String" {
if let Some(arity) = string_instance_ref_arity(method) {
let ps = mk(arity + 1);
return Ok(Some(lambda(
ps.clone(),
Expr::MethodCall {
recv: Box::new(Expr::Var(ps[0].clone())),
method: method.to_string(),
args: vars(&ps[1..]),
line,
},
)));
}
}
Err(format!(
"javars: `{name}::{method}` is not a method reference javars models (line {line})"
))
}
/// The parameter count of `class.method` when the class declares exactly one
/// method of that name; `None` when there is none or several (an overloaded
/// name gives a method reference no unambiguous arity).
fn unique_method_arity(&self, class: &str, method: &str) -> Option<usize> {
let ci = self.classes.get(class)?;
let mut it = ci.methods.iter().filter(|m| m.name == method);
let first = it.next()?;
it.next().is_none().then_some(first.param_tys.len())
}
/// The parameter count of a user `static` method with exactly one overload.
fn unique_static_arity(&self, method: &str) -> Option<usize> {
let sigs = self.methods.get(method)?;
(sigs.len() == 1).then(|| sigs[0].param_tys.len())
}
/// Lower one instance method to a subroutine named `Class#method#argc`. Slot
/// 0 holds `this`; parameters take slots `1..=argc`. The prologue binds all
/// `argc + 1` incoming values (this deepest).
fn compile_instance_method(&mut self, class: &str, m: &Method) -> Result<(), String> {
let entry = self.b.current_pos();
let param_tys: Vec<String> = m.params.iter().map(|p| p.ty.clone()).collect();
let mangled = mangle(class, &m.name, ¶m_tys);
let name_idx = self.b.add_name(&mangled);
self.b.add_sub_entry(name_idx, entry);
self.current_ret_generic = self.ret_generics.get(&mangled).cloned();
self.current_ret_wildcard = self.ret_wildcards.contains(&mangled);
let mut scope = MethodScope::for_instance();
register_params(&mut scope, &m.params);
self.scope = Some(scope);
self.this_class = Some(class.to_string());
let saved_class = self.current_class.replace(class.to_string());
let saved_ret = self.current_ret.replace(m.ret.clone());
// Prologue: bind `this` (slot 0) + params (slots 1..=n), high-to-low.
for i in (0..=m.params.len()).rev() {
self.b.emit(Op::SetSlot(i as u16), m.line);
}
let result = m.body.iter().try_for_each(|s| self.stmt(s));
self.b.emit(Op::LoadUndef, m.line);
self.b.emit(Op::ReturnValue, m.line);
self.scope = None;
self.this_class = None;
self.current_class = saved_class;
self.current_ret = saved_ret;
self.current_ret_generic = None;
result
}
/// Lower a class's instance initialization — its field initializers and its
/// bare `{ … }` blocks, in textual order — to a subroutine named
/// `Class#<instinit>`. [`Compiler::new_object`] seeds the type defaults and
/// then calls this on the fresh instance, so `this` is bound (slot 0) while
/// the initializers run: a block can call an instance method, and a field
/// initializer can read a field declared above it.
fn compile_inst_init(&mut self, cl: &Class) -> Result<(), String> {
let entry = self.b.current_pos();
let mangled = mangle(&cl.name, INST_INIT, &[]);
let name_idx = self.b.add_name(&mangled);
self.b.add_sub_entry(name_idx, entry);
self.scope = Some(MethodScope::for_instance());
self.this_class = Some(cl.name.clone());
let saved_class = self.current_class.replace(cl.name.clone());
self.b.emit(Op::SetSlot(0), cl.line); // bind `this`
let result = cl.inst_init.iter().try_for_each(|s| self.stmt(s));
self.b.emit(Op::LoadUndef, cl.line);
self.b.emit(Op::ReturnValue, cl.line);
self.scope = None;
self.this_class = None;
self.current_class = saved_class;
result
}
/// Lower a constructor to a subroutine named `Class#<init>#argc`. Field
/// *defaults* are emitted by [`Compiler::new_object`] before the call — Java
/// zeroes the whole object at allocation — but the field *initializers* and
/// `{ … }` blocks run here, in the order JLS 12.5 fixes:
///
/// 1. the superclass constructor (explicit `super(…)`, or the implicit
/// `super()` of JLS 8.8.7),
/// 2. this class's instance initializers,
/// 3. the programmer's constructor statements.
///
/// A body opening with `this(…)` runs none of 1 and 2: the constructor it
/// delegates to already did, and running the initializers again would apply
/// them twice.
///
/// The order matters wherever the superclass constructor can observe the
/// subclass: a virtual call made from it must see the subclass's fields at
/// their defaults, and a field the superclass constructor assigns must not
/// be overwritten by an initializer that has not run yet.
///
/// `this` is slot 0; the ctor returns `null` (discarded).
fn compile_ctor(&mut self, cl: &Class, ctor: &Ctor) -> Result<(), String> {
let entry = self.b.current_pos();
let param_tys: Vec<String> = ctor.params.iter().map(|p| p.ty.clone()).collect();
let mangled = mangle(&cl.name, "<init>", ¶m_tys);
let name_idx = self.b.add_name(&mangled);
self.b.add_sub_entry(name_idx, entry);
let mut scope = MethodScope::for_instance();
register_params(&mut scope, &ctor.params);
self.scope = Some(scope);
self.this_class = Some(cl.name.clone());
let saved_class = self.current_class.replace(cl.name.clone());
for i in (0..=ctor.params.len()).rev() {
self.b.emit(Op::SetSlot(i as u16), ctor.line);
}
// A local class stores its captured locals first, as javac does, so the
// superclass constructor and the instance initializers can read them.
for c in &cl.captures {
let store = StmtKind::FieldAssign {
recv: Expr::This,
name: c.name.clone(),
op: AssignOp::Assign,
value: Expr::Var(c.name.clone()),
};
self.stmt(&Stmt::new(ctor.line, store))?;
}
// JLS 8.8.7: a body that does not open with `this(…)`/`super(…)` runs an
// implicit `super()` first. Without it a superclass constructor body
// never ran at all, so anything it did — a field it set, a virtual call
// it made — was silently lost.
let result = match Self::ctor_chain(&ctor.body) {
// `this(…)` first: the delegate ran the super chain *and* the
// instance initializers, so this body adds neither.
CtorChain::This => ctor.body.iter().try_for_each(|s| self.stmt(s)),
// `super(…)` first: emit it, then the initializers, then the rest.
CtorChain::Super => {
let (head, rest) = ctor.body.split_at(1);
head.iter().try_for_each(|s| self.stmt(s)).and_then(|()| {
self.emit_inst_init(&cl.name, Recv::This, ctor.line);
rest.iter().try_for_each(|s| self.stmt(s))
})
}
CtorChain::Implicit => {
self.emit_super_chain(&cl.name, Recv::This, ctor.line, 0);
self.emit_inst_init(&cl.name, Recv::This, ctor.line);
ctor.body.iter().try_for_each(|s| self.stmt(s))
}
};
self.b.emit(Op::LoadUndef, ctor.line);
self.b.emit(Op::ReturnValue, ctor.line);
self.scope = None;
self.this_class = None;
self.current_class = saved_class;
result
}
fn stmt(&mut self, s: &Stmt) -> Result<(), String> {
// In debug mode, emit a line marker before the statement so `--dap` can
// stop on it. `CallBuiltin` always pushes its return value, so pop it.
if self.debug && s.line != 0 {
self.b
.emit(Op::CallBuiltin(crate::host::DBG_LINE, 0), s.line);
self.b.emit(Op::Pop, s.line);
}
let line = s.line;
match &s.kind {
// `int a = 1, b = 2;` — one declaration statement, several
// declarators, lowered left to right so a later initializer sees the
// earlier names (Java's evaluation order).
StmtKind::Locals(decls) => {
for d in decls {
self.stmt(d)?;
}
Ok(())
}
StmtKind::Local {
ty,
targs,
wildcard,
name,
init,
..
} => {
// Record the declared numeric type (for `/` truncation); `var`
// and untracked types are inferred from the initializer. The raw
// type string powers class-typed dispatch — for `var`, infer the
// class from the initializer.
let nt = numtype_of_ty(ty)
.or_else(|| init.as_ref().map(|e| self.expr_type(e)))
.unwrap_or(NumType::Other);
let raw = if ty == "var" {
// Infer `var`'s type from the initializer: a user class when
// there is one, else the initializer's static Java type
// (`int`, `String`, `int[]`, …). Keeping the inferred type —
// rather than the literal string `var` — is what lets a
// `var` loop counter participate in `int` wrapping and in
// array-element typing.
init.as_ref()
.and_then(|e| self.expr_class(e).or_else(|| self.expr_java_type(e)))
.unwrap_or_else(|| ty.clone())
} else {
ty.clone()
};
// The type arguments come from the declaration, or for `var`
// from the initializer's own generic type.
let generic = if ty == "var" {
init.as_ref().and_then(|e| self.expr_generic(e))
} else {
with_targs(ty, targs)
};
self.declare_local(name, &raw, nt);
self.declare_generic(name, generic.clone());
if *wildcard {
self.mark_wildcard(name);
}
if let Some(e) = init {
self.target_wildcard = Some(*wildcard);
self.expr_targeted_generic(e, Some(&raw), generic)?;
self.emit_set(name, line);
}
// An uninitialized local is simply unbound until first assigned
// (Java's definite-assignment check is not enforced yet).
Ok(())
}
StmtKind::Assign { name, op, value } => {
// A bare name that is a field of `this` (not a local) is an
// implicit `this.name = …` field assignment.
if self.implicit_this_field(name).is_some() {
let recv = Expr::This;
return self.field_assign(&recv, name, *op, value, line);
}
// A bare name that is a `static` field of the enclosing class
// writes that class's shared cell.
if let Some((class, ty)) = self.static_field_owner(name) {
return self.static_assign(&class, &ty, name, *op, value, line);
}
// A field of an enclosing instance, from an inner class.
if let Some((recv, _)) = self.outer_field_recv(name) {
return self.field_assign(&recv, name, *op, value, line);
}
let l = self.lookup_type(name);
// A wrapper variable is updated through its primitive (JLS
// 15.26.2): `Integer x; x += 1` is `x = Integer.valueOf(x + 1)`.
let decl = self.var_decl_type(name).map(str::to_string);
let prim = decl.as_deref().map(unwrapped_ty);
// A compound assignment back into an `int` variable wraps.
let wrap = *op != AssignOp::Assign && self.compound_wraps(prim, value);
match op {
AssignOp::Assign => {
let target = self.var_decl_type(name).map(str::to_string);
let generic = self.var_generic(name);
self.target_wildcard = Some(self.var_wildcard(name));
self.expr_targeted_generic(value, target.as_deref(), generic)?;
}
// `x <op>= e` → `x = x <op> e`, through the one shared
// lowering that also handles `/=`'s int truncation, `%=`'s
// zero check, the shifts' width masking, and the logical
// `&=`/`|=`/`^=` on booleans.
_ => {
self.emit_get(name, line);
if let Some(d) = decl.as_deref() {
self.emit_checked_unbox(d);
}
self.emit_compound(*op, value, l, prim, wrap, line)?;
self.emit_narrow_to(prim, line);
if let Some(d) = decl.as_deref() {
self.emit_rebox(d);
}
}
}
self.emit_set(name, line);
Ok(())
}
StmtKind::IndexAssign {
array,
index,
op,
value,
} => self.index_assign(array, index, *op, value, line),
StmtKind::FieldAssign {
recv,
name,
op,
value,
} => self.field_assign(recv, name, *op, value, line),
StmtKind::Expr(Expr::Println { newline, err, arg }) => {
// The print builtin returns `null`; discard it in statement
// position.
self.println(*newline, *err, arg.as_deref())?;
self.b.emit(Op::Pop, line);
Ok(())
}
StmtKind::Expr(Expr::PostIncDec { name, inc }) => self.post_inc_dec(name, *inc),
// `a[i]++;` / `++p.n;` in statement position — the same update, with
// the result discarded rather than left on the stack.
StmtKind::Expr(Expr::IncDec {
target, inc, line, ..
}) => self.inc_dec(target, *inc, Yield::Nothing, *line),
// An arrow-form `switch` written as a statement is a switch
// *statement*: it need not be exhaustive unless it uses patterns.
StmtKind::Expr(e @ Expr::SwitchExpr { .. }) => {
self.switch_is_statement = true;
let r = self.expr(e);
self.switch_is_statement = false;
r?;
self.b.emit(Op::Pop, line);
Ok(())
}
StmtKind::Expr(e) => {
self.expr(e)?;
self.b.emit(Op::Pop, line);
Ok(())
}
StmtKind::If { cond, then, els } => self.if_stmt(cond, then, els),
StmtKind::While { cond, body } => self.while_stmt(cond, body),
StmtKind::DoWhile { body, cond } => self.do_while_stmt(body, cond),
StmtKind::For {
init,
cond,
update,
body,
} => self.for_stmt(init, cond, update, body),
StmtKind::ForEach {
ty,
targs,
name,
iter,
body,
..
} => self.foreach_stmt(ty, targs, name, iter, body, line),
StmtKind::Switch { disc, groups } => self.switch_stmt(disc, groups),
StmtKind::Labeled { label, body } => {
// A label prefixing a loop/`switch` is consumed by that
// construct's own `BreakScope` (via `pending_label`). A label on
// any other statement (a block, an `if`) gets a break-only scope
// so `break label;` can still exit it.
if is_breakable(body) {
self.pending_label = Some(label.clone());
self.stmt(body)?;
// If the construct did not consume the label (should not
// happen for breakables), clear it so it cannot leak.
self.pending_label = None;
} else {
self.scopes
.push(BreakScope::switch_scope(Some(label.clone())));
self.stmt(body)?;
let scope = self.scopes.pop().unwrap();
let end = self.b.current_pos();
for op in scope.break_ops {
self.b.patch_jump(op, end);
}
}
Ok(())
}
StmtKind::Try {
body,
catches,
finally_body,
} => self.try_stmt(body, catches, finally_body, line),
StmtKind::Throw(e) => self.throw_stmt(e, line),
// A disabled assertion evaluates neither expression (JLS 14.10).
StmtKind::Assert { .. } => Ok(()),
// The class itself was hoisted and is compiled with the others.
StmtKind::LocalClass(_) => Ok(()),
// `yield v;` — leave the value on the stack (running any cleanup
// block opened inside this arm first, exactly as `return` does),
// then jump to the arm's exit.
StmtKind::Yield(e) => {
let target = self.yield_target.clone();
self.expr_targeted(e, target.as_deref())?;
let keep = self.yield_finally_depth;
self.emit_finallys_down_to(keep)?;
let j = self.b.emit(Op::Jump(0), line);
self.yield_ops.push(j);
Ok(())
}
StmtKind::Break(label) => self.break_stmt(label.as_deref(), line),
StmtKind::Continue(label) => self.continue_stmt(label.as_deref(), line),
StmtKind::Return(val) => {
if self.scope.is_some() {
// In a method: return a value (or `null` for `void`).
// Java evaluates the returned expression *before* running
// the cleanup blocks, so a `finally` that reassigns the
// variable cannot change the value already computed.
match val {
Some(e) => {
let want = self.current_ret.clone();
let generic = self.current_ret_generic.clone();
self.target_wildcard = Some(self.current_ret_wildcard);
self.expr_targeted_generic(e, want.as_deref(), generic)?;
}
None => {
self.b.emit(Op::LoadUndef, line);
}
}
self.emit_finallys_down_to(0)?;
self.b.emit(Op::ReturnValue, line);
} else {
// In `main` (void): a bare `return;` ends the program; a
// value return is a type error javars does not accept.
if val.is_some() {
return Err(format!(
"javars: `return <value>` from void main is not supported (line {line})"
));
}
self.emit_finallys_down_to(0)?;
let op = self.b.emit(Op::Jump(0), line);
self.exit_ops.push(op);
}
Ok(())
}
}
}
fn if_stmt(&mut self, cond: &Expr, then: &[Stmt], els: &[Stmt]) -> Result<(), String> {
self.expr_unboxed(cond)?;
let jf = self.b.emit(Op::JumpIfFalse(0), 0);
for s in then {
self.stmt(s)?;
}
if els.is_empty() {
let end = self.b.current_pos();
self.b.patch_jump(jf, end);
} else {
let jend = self.b.emit(Op::Jump(0), 0);
let else_start = self.b.current_pos();
self.b.patch_jump(jf, else_start);
for s in els {
self.stmt(s)?;
}
let end = self.b.current_pos();
self.b.patch_jump(jend, end);
}
Ok(())
}
/// Lower `while (cond) { … }` **rotated**: the test is emitted twice — once
/// ahead of the body as an entry guard, once after it as a *conditional*
/// backward branch — instead of once at the top with an unconditional
/// `Jump` back to it.
///
/// The shape is what decides whether the loop ever leaves the interpreter.
/// fusevm's tracing JIT closes a trace only on a conditional backward
/// branch; recorded from a top-test loop it reaches an unconditional `Jump`
/// and declines, which is why `java --tiers` reported
/// `trace-eligible=true traced=false` for every `for` and `while` javars
/// emitted while `do { … } while (…)` — the one form that already ended in
/// a conditional branch — reported `traced=true`.
///
/// Evaluation order and count are unchanged: a top-test loop runs the test
/// `n + 1` times for `n` iterations, and so does this (one entry test, then
/// one after each body run). Rotation costs one static copy of the
/// condition's code and saves one jump per iteration.
fn while_stmt(&mut self, cond: &Expr, body: &[Stmt]) -> Result<(), String> {
let label = self.pending_label.take();
self.expr_unboxed(cond)?;
let jf = self.b.emit(Op::JumpIfFalse(0), 0);
let top = self.b.current_pos();
self.scopes.push(BreakScope::loop_scope(label));
for s in body {
self.stmt(s)?;
}
// `continue` re-tests the condition — which is now the bottom copy of
// it, emitted just below.
let test = self.b.current_pos();
let l = self.scopes.pop().unwrap();
for op in &l.continue_ops {
self.b.patch_jump(*op, test);
}
self.expr_unboxed(cond)?;
self.b.emit(Op::JumpIfTrue(top), 0);
let end = self.b.current_pos();
self.b.patch_jump(jf, end);
for op in l.break_ops {
self.b.patch_jump(op, end);
}
Ok(())
}
/// `do { body } while (cond);` — the body runs once unconditionally, then
/// the condition gates a backward jump. `continue` targets the condition
/// test; `break` targets the exit.
fn do_while_stmt(&mut self, body: &[Stmt], cond: &Expr) -> Result<(), String> {
let label = self.pending_label.take();
let top = self.b.current_pos();
self.scopes.push(BreakScope::loop_scope(label));
for s in body {
self.stmt(s)?;
}
// `continue` re-tests the condition — target it at the test emitted next.
let test = self.b.current_pos();
let l = self.scopes.pop().unwrap();
for op in &l.continue_ops {
self.b.patch_jump(*op, test);
}
self.expr_unboxed(cond)?;
self.b.emit(Op::JumpIfTrue(top), 0);
let end = self.b.current_pos();
for op in l.break_ops {
self.b.patch_jump(op, end);
}
Ok(())
}
/// Lower the C-style `for (init; cond; update)`, rotated for the reason
/// [`Compiler::while_stmt`] gives. `continue` still runs the update clause,
/// which now sits immediately before the bottom copy of the test.
///
/// `for (;;)` has no test to branch on, so its back edge stays
/// unconditional — and with it, its ineligibility for a trace.
fn for_stmt(
&mut self,
init: &[Stmt],
cond: &Option<Expr>,
update: &[Stmt],
body: &[Stmt],
) -> Result<(), String> {
let label = self.pending_label.take();
for s in init {
self.stmt(s)?;
}
let jf = match cond {
Some(c) => {
self.expr(c)?;
Some(self.b.emit(Op::JumpIfFalse(0), 0))
}
None => None,
};
let top = self.b.current_pos();
// `continue` runs the update clause, then re-tests — target it at the
// step label emitted after the body.
self.scopes.push(BreakScope::loop_scope(label));
for s in body {
self.stmt(s)?;
}
// step label: the continue target is the update clause (or, when there
// is no update, the bottom re-test that follows it).
let step = self.b.current_pos();
for s in update {
self.stmt(s)?;
}
match cond {
Some(c) => {
self.expr(c)?;
self.b.emit(Op::JumpIfTrue(top), 0);
}
None => {
self.b.emit(Op::Jump(top), 0);
}
}
let end = self.b.current_pos();
if let Some(jf) = jf {
self.b.patch_jump(jf, end);
}
let l = self.scopes.pop().unwrap();
for op in l.continue_ops {
self.b.patch_jump(op, step);
}
for op in l.break_ops {
self.b.patch_jump(op, end);
}
Ok(())
}
// ── exceptions (`throw` / `try` / `catch` / `finally`) ────────────────
//
// fusevm has no unwind opcode. javars models the in-flight exception as a
// host-side pending value ([`crate::host::JTHROW`]) plus two compiler-side
// pieces:
//
// * inside a frame, an unwind is a `Jump` to the innermost enclosing
// handler — backpatched through [`Compiler::tries`];
// * across frames, an unwind is `LoadUndef; ReturnValue`, and every call
// site is followed by a pending-exception check that repeats the unwind
// in the caller. `Op::ReturnValue` truncates the value stack to the
// frame base, so the abandoned operands of the callee cost nothing.
//
// Only the second piece has a runtime cost, and only in a program that uses
// exceptions at all ([`Compiler::has_exceptions`]).
/// Abandon the current computation: jump to the innermost handler in this
/// frame, or leave the frame so the caller's post-call check picks the
/// exception up. In `main` (no frame to leave) it jumps to the program exit,
/// where the uncaught report runs.
fn emit_unwind(&mut self, line: u32) {
if !self.tries.is_empty() {
let op = self.b.emit(Op::Jump(0), line);
self.tries.last_mut().unwrap().unwind_ops.push(op);
} else if self.scope.is_some() {
// A method/constructor frame: return a placeholder so the frame is
// popped and the stack rebalanced. The caller discards it — the
// pending exception, not the value, is what it acts on.
self.b.emit(Op::LoadUndef, line);
self.b.emit(Op::ReturnValue, line);
} else {
let op = self.b.emit(Op::Jump(0), line);
self.exit_ops.push(op);
}
}
/// Emit the post-call check: if the call left an exception in flight, unwind.
/// A no-op for a program with no exceptions, which is why those programs'
/// bytecode is unchanged. Must follow *every* `Op::Call` — a call path that
/// skips it swallows the exception and resumes with a placeholder value.
fn emit_exc_check(&mut self, line: u32) {
if !self.has_exceptions {
return;
}
self.b
.emit(Op::CallBuiltin(crate::host::JEXC_PENDING, 0), line);
let jf = self.b.emit(Op::JumpIfFalse(0), line);
self.emit_unwind(line);
let after = self.b.current_pos();
self.b.patch_jump(jf, after);
}
/// Emit a call to a builtin that can raise a Java exception (an array index,
/// a null receiver, `Integer.parseInt`, …), followed by the pending check.
///
/// Every raising builtin is emitted through here rather than by a bare
/// `Op::CallBuiltin`, because a fault site that skips the check would leave
/// the throwable parked forever: the `Undef` the builtin returned would flow
/// on as a value and the program would keep running past the exception.
fn emit_raising_builtin(&mut self, id: u16, argc: u8, line: u32) {
self.b.emit(Op::CallBuiltin(id, argc), line);
self.emit_exc_check(line);
}
/// Raise a `java.lang` throwable from compiler-emitted code and unwind — the
/// integer division-by-zero path, where the fault is visible statically but
/// only the runtime knows the divisor.
fn emit_fault(&mut self, class: &str, msg: &str, line: u32) {
let c = self.b.add_constant(Value::str(class.to_string()));
self.b.emit(Op::LoadConst(c), line);
let m = self.b.add_constant(Value::str(msg.to_string()));
self.b.emit(Op::LoadConst(m), line);
self.b.emit(Op::CallBuiltin(crate::host::JFAULT, 2), line);
self.b.emit(Op::Pop, line);
self.emit_unwind(line);
}
/// Emit the end-of-`main` uncaught-exception report: an exception that no
/// handler claimed prints Java's `Exception in thread "main" …` line and
/// exits non-zero.
fn emit_uncaught_check(&mut self) {
self.b
.emit(Op::CallBuiltin(crate::host::JEXC_PENDING, 0), 0);
let jf = self.b.emit(Op::JumpIfFalse(0), 0);
self.b.emit(Op::CallBuiltin(crate::host::JEXC_ABORT, 0), 0);
self.b.emit(Op::Pop, 0);
let after = self.b.current_pos();
self.b.patch_jump(jf, after);
}
/// Lower `throw <expr>;`: evaluate the throwable, park it as the pending
/// exception, then unwind.
fn throw_stmt(&mut self, e: &Expr, line: u32) -> Result<(), String> {
self.expr(e)?;
self.b.emit(Op::CallBuiltin(crate::host::JTHROW, 1), line);
self.b.emit(Op::Pop, line);
self.emit_unwind(line);
Ok(())
}
/// Lower `try { … } catch (E e) { … }* [finally { … }]`.
///
/// Layout:
///
/// ```text
/// depth = JEXC_DEPTH ; so the handler can drop abandoned operands
/// <try body> ; unwinds inside it jump to `handler`
/// Jump normal
/// handler:
/// JEXC_CUT(depth); exc = JEXC_TAKE
/// if (exc instanceof E1) { e1 = exc; <catch 1>; Jump normal }
/// …
/// Jump rethrow ; no arm matched — `exc` continues outward
/// pad: ; a catch arm threw: same treatment, but the
/// JEXC_CUT(depth); exc = JEXC_TAKE ; NEW exception replaces `exc`
/// rethrow:
/// <finally> ; the cleanup still runs …
/// JTHROW(exc); <unwind> ; … then the exception continues outward
/// normal:
/// <finally>
/// ```
///
/// The `finally` body is emitted twice — once per path — rather than shared
/// through a subroutine, because a shared copy would need a return address
/// and fusevm's frames are for calls, not for local jumps. Duplication is
/// what `javac` itself did before `jsr`/`ret` were dropped, and it is why a
/// `return`/`break`/`continue` leaving the block emits its own copy (see
/// [`Compiler::emit_finallys_down_to`]).
///
/// The exception is parked back into the pending slot only *after* the
/// `finally` has run: leaving it in flight would make the cleanup block's
/// own post-call checks fire immediately and skip it.
/// `javac`'s two checks on a `try`'s catch types (JLS 11.2.3, 14.20): a
/// clause whose type an earlier clause already catches is unreachable, and
/// the alternatives of one multi-catch may not be related by subclassing.
fn check_catch_order(&self, catches: &[CatchArm], line: u32) -> Result<(), String> {
let mut caught: Vec<&str> = Vec::new();
for arm in catches {
let types: Vec<&str> = arm.types.iter().map(|t| erased_simple_name(t)).collect();
for (i, t) in types.iter().enumerate() {
if let Some(earlier) = types[..i]
.iter()
.chain(types[i + 1..].iter())
.find(|u| self.is_subclass(t, u))
{
return Err(format!(
"javars: Alternatives in a multi-catch statement cannot be related by subclassing (alternative {t} is a subclass of alternative {earlier}) (line {line})"
));
}
if caught.iter().any(|u| self.is_subclass(t, u)) {
return Err(format!(
"javars: exception {t} has already been caught (line {line})"
));
}
}
caught.extend(types);
}
Ok(())
}
fn try_stmt(
&mut self,
body: &[Stmt],
catches: &[CatchArm],
finally_body: &[Stmt],
line: u32,
) -> Result<(), String> {
self.check_catch_order(catches, line)?;
// Record the stack depth so the handler can discard whatever the
// abandoned expression had already pushed.
let depth_t = self.temp();
self.b
.emit(Op::CallBuiltin(crate::host::JEXC_DEPTH, 0), line);
self.emit_set(&depth_t, line);
// The cleanup block is in scope for the try body AND for every catch
// arm — a `return` from either runs it.
let has_finally = !finally_body.is_empty();
if has_finally {
self.finallys.push(FinallyScope {
body: finally_body.to_vec(),
scope_depth: self.scopes.len(),
tries_depth: self.tries.len(),
});
}
self.tries.push(TryScope {
unwind_ops: Vec::new(),
});
for s in body {
self.stmt(s)?;
}
let scope = self.tries.pop().unwrap();
let to_normal = self.b.emit(Op::Jump(0), line);
// ── handler ──
let handler = self.b.current_pos();
for op in scope.unwind_ops {
self.b.patch_jump(op, handler);
}
let exc_t = self.temp();
self.emit_claim_exception(&depth_t, &exc_t, line);
// `catch` arms, in source order — the first type match wins. An unwind
// raised *inside* an arm belongs to the enclosing try, but must still
// run this `finally`, so the arms get their own landing pad.
self.tries.push(TryScope {
unwind_ops: Vec::new(),
});
let mut matched_jumps = Vec::new();
for arm in catches {
// A multi-catch's alternatives are tested in order: any hit jumps
// straight to the shared body, and only the last miss skips the arm.
let mut hits = Vec::new();
let mut jf = None;
let last = arm.types.len().saturating_sub(1);
for (i, ty) in arm.types.iter().enumerate() {
// A catch type javars does not know matched nothing, silently:
// the arm compiled, `JINSTANCEOF` answered `false` for every
// throwable, and the handler was dead code. So
// `catch (StackOverflowError e)` and `catch (IOException e)`
// both *compiled* and then never fired, which reads as "javars
// handles this" at the exact place a program says what it
// handles. `javac` rejects an unresolvable catch type outright
// ("cannot find symbol"), and so does javars now — the same
// diagnostic `new Unknown()` already produced.
if !self.classes.contains_key(ty) {
return Err(format!("javars: unknown class `{ty}` (line {line})"));
}
self.emit_get(&exc_t, line);
let c = self.b.add_constant(Value::str(ty.clone()));
self.b.emit(Op::LoadConst(c), line);
self.b
.emit(Op::CallBuiltin(crate::host::JINSTANCEOF, 2), line);
if i == last {
jf = Some(self.b.emit(Op::JumpIfFalse(0), line));
} else {
hits.push(self.b.emit(Op::JumpIfTrue(0), line));
}
}
let jf = jf.expect("a catch arm always names at least one type");
let body_start = self.b.current_pos();
for h in hits {
self.b.patch_jump(h, body_start);
}
// A multi-catch parameter is typed as the alternatives' least upper
// bound (JLS 14.20). Typing it as the first alternative instead
// built `"" + e`'s `toString` dispatch over that alternative's
// subclasses only, so a caught `UnsupportedOperationException` in
// `catch (IllegalArgumentException | UnsupportedOperationException
// e)` printed as `java.lang.UnsupportedOperationException@1`.
let ty = self.superclass_lub(&arm.types);
self.declare_local(&arm.name, &ty, NumType::Other);
self.emit_get(&exc_t, line);
self.emit_set(&arm.name, line);
for s in &arm.body {
self.stmt(s)?;
}
matched_jumps.push(self.b.emit(Op::Jump(0), line));
let next = self.b.current_pos();
self.b.patch_jump(jf, next);
}
let catch_scope = self.tries.pop().unwrap();
// Falling out of the arm chain means no arm matched: `exc_t` already
// holds the exception, so skip the pad that re-reads a new one.
let skip_pad = (!catch_scope.unwind_ops.is_empty()).then(|| self.b.emit(Op::Jump(0), line));
if !catch_scope.unwind_ops.is_empty() {
let pad = self.b.current_pos();
for op in catch_scope.unwind_ops {
self.b.patch_jump(op, pad);
}
self.emit_claim_exception(&depth_t, &exc_t, line);
}
// Either way the cleanup runs, then the exception continues outward.
let rethrow = self.b.current_pos();
if let Some(j) = skip_pad {
self.b.patch_jump(j, rethrow);
}
if has_finally {
self.finallys.pop();
}
for s in finally_body {
self.stmt(s)?;
}
self.emit_get(&exc_t, line);
self.b.emit(Op::CallBuiltin(crate::host::JTHROW, 1), line);
self.b.emit(Op::Pop, line);
self.emit_unwind(line);
// ── normal completion (try fell through, or a catch arm finished) ──
let normal = self.b.current_pos();
self.b.patch_jump(to_normal, normal);
for op in matched_jumps {
self.b.patch_jump(op, normal);
}
for s in finally_body {
self.stmt(s)?;
}
Ok(())
}
/// Take the in-flight exception into `exc_t` and drop the operands the
/// abandoned expression left behind (back to the depth recorded in
/// `depth_t`). Both handler entry points start with exactly this.
fn emit_claim_exception(&mut self, depth_t: &str, exc_t: &str, line: u32) {
self.emit_get(depth_t, line);
self.b.emit(Op::CallBuiltin(crate::host::JEXC_CUT, 1), line);
self.b.emit(Op::Pop, line);
self.b
.emit(Op::CallBuiltin(crate::host::JEXC_TAKE, 0), line);
self.emit_set(exc_t, line);
}
/// Emit the `finally` blocks a jump is about to leave, innermost first,
/// down to `keep` remaining. The stack is temporarily shortened while a body
/// is lowered so a `return` *inside* a cleanup block does not re-emit that
/// same block, then restored — the statements after the jump are still
/// inside the same `try`.
///
/// The handler stack is shortened the same way, to the depth each block's
/// `try` was entered at (JLS 14.20.2: an exception from a `finally` is
/// not handled by that statement's `catch` clauses). Lowered under the
/// full stack, a throw from `try { return 1; } catch (RuntimeException e)
/// { … } finally { throw … }` landed in the `catch`, which ran and then
/// ran the `finally` a second time.
fn emit_finallys_down_to(&mut self, keep: usize) -> Result<(), String> {
if self.finallys.len() <= keep {
return Ok(());
}
let pending = self.finallys.split_off(keep);
let mut result = Ok(());
'outer: for f in pending.iter().rev() {
let inner_tries = self.tries.split_off(f.tries_depth.min(self.tries.len()));
for s in &f.body {
if let Err(e) = self.stmt(s) {
result = Err(e);
self.tries.extend(inner_tries);
break 'outer;
}
}
self.tries.extend(inner_tries);
}
self.finallys.extend(pending);
result
}
/// The number of enclosing `finally` blocks that stay in scope when a jump
/// targets breakable scope `idx` — the ones entered *outside* it. A jump
/// leaving the frame entirely (`return`) keeps none.
fn finallys_outside(&self, idx: usize) -> usize {
self.finallys
.iter()
.take_while(|f| f.scope_depth <= idx)
.count()
}
/// Lower the enhanced `for (T x : arr) { … }` over an array.
///
/// Java specifies the array form as exactly this index loop, with the array
/// and the cursor held in variables the program cannot name — so both live in
/// compiler-minted `#t` temps here. Evaluating the iterable once matters:
/// `for (int v : make())` must call `make()` a single time, and re-reading
/// `.length` from the temp (rather than from the source expression) keeps
/// that true.
///
/// `continue` targets the increment, `break` the exit — the same contract
/// the C-style loop uses, so labeled `break`/`continue` work unchanged.
/// The enhanced `for` over a user `Iterable`, desugared to the basic `for`
/// over its iterator (see [`Compiler::foreach_stmt`]). Unlike a collection,
/// which is snapshotted, this runs the class's own `hasNext`/`next`, so an
/// iterator that computes its elements, or never ends, behaves as in Java.
fn foreach_iterable(
&mut self,
ty: &str,
name: &str,
iter: &Expr,
body: &[Stmt],
line: u32,
) -> Result<(), String> {
let it = format!("#it{}", self.temp_counter);
self.temp_counter += 1;
let call = |recv: Expr, method: &str| Expr::MethodCall {
recv: Box::new(recv),
method: method.to_string(),
args: Vec::new(),
line,
};
let mut loop_body = vec![Stmt::new(
line,
StmtKind::Local {
targs: Vec::new(),
wildcard: false,
super_slots: Vec::new(),
ty: ty.to_string(),
name: name.to_string(),
init: Some(call(Expr::Var(it.clone()), "next")),
is_final: false,
},
)];
loop_body.extend(body.iter().cloned());
let desugared = StmtKind::For {
init: vec![Stmt::new(
line,
StmtKind::Local {
targs: Vec::new(),
wildcard: false,
super_slots: Vec::new(),
ty: "Iterator".to_string(),
name: it.clone(),
init: Some(call(iter.clone(), "iterator")),
is_final: false,
},
)],
cond: Some(call(Expr::Var(it), "hasNext")),
update: Vec::new(),
body: loop_body,
};
self.stmt(&Stmt::new(line, desugared))
}
fn foreach_stmt(
&mut self,
ty: &str,
targs: &[String],
name: &str,
iter: &Expr,
body: &[Stmt],
line: u32,
) -> Result<(), String> {
// A user class that implements `Iterable` is iterated the way JLS
// 14.14.2 specifies, through its own `iterator()`:
// `for (I #it = e.iterator(); #it.hasNext(); ) { T x = #it.next(); … }`.
if let Some(class) = self.expr_java_type(iter) {
let class = class.split('<').next().unwrap_or_default();
// An interface that extends `Iterable` declares no `iterator()` of
// its own, but its static type is just as much an `Iterable`: the
// call dispatches to the runtime class's method.
// A bare `Iterable` (a lambda or method reference assigned to the
// interface) is walked through its `iterator()` the same way.
let user_iterable = class == "Iterable"
|| (self.classes.contains_key(class) && self.is_subclass(class, "Iterable"));
if self.has_instance_method(class, "iterator", 0) || user_iterable {
return self.foreach_iterable(ty, name, iter, body, line);
}
}
let label = self.pending_label.take();
// `var` takes its type from the array's element type when that is
// statically known (`String[]` → `String`), so the loop variable still
// participates in `/` typing and class-typed dispatch.
// Over a collection it is the collection's element type argument, so
// `for (var e : m.entrySet())` is a `Map.Entry<K, V>`.
let generic = if ty == "var" {
self.foreach_elem_generic(iter)
} else {
with_targs(ty, targs)
};
let elem_ty = if ty == "var" {
self.expr_array_type(iter)
.and_then(|t| t.strip_suffix("[]").map(str::to_string))
.or_else(|| {
generic
.as_deref()
.map(|g| crate::ast::generic_parts(g).0)
.filter(|t| is_known_type(t))
})
.unwrap_or_else(|| ty.to_string())
} else {
ty.to_string()
};
let nt = numtype_of_ty(&elem_ty).unwrap_or(NumType::Other);
self.declare_local(name, &elem_ty, nt);
self.declare_generic(name, generic);
// The array and the index cursor, evaluated/initialised once. When the
// iterable is not *statically* an array it goes through `JITER_ARRAY`,
// which returns an array handle unchanged and snapshots a collection
// into a fresh one — so `for (String s : list)` works and an array loop
// emits exactly the ops it did before.
let arr_t = self.temp();
// A collection is walked the way a Java iterator walks it: fail-fast on
// a structural modification, a `List` read live. `watch_t` names what
// the modification token is taken from — the iterable itself, or the map
// behind a `keySet()`/`values()`/`entrySet()` view, which is a copy here
// and so cannot see the map change.
let is_array = self.expr_array_type(iter).is_some();
let src_t = self.temp();
let watch_t = self.temp();
let tok_t = self.temp();
self.expr(iter)?;
if is_array {
self.emit_set(&arr_t, line);
} else {
self.emit_set(&src_t, line);
self.emit_get(&src_t, line);
self.emit_raising_builtin(crate::host::JITER_ARRAY, 1, line);
self.emit_set(&arr_t, line);
match Self::map_view_owner(iter) {
Some(owner) => self.expr(owner)?,
None => self.emit_get(&src_t, line),
}
self.emit_set(&watch_t, line);
self.emit_get(&watch_t, line);
self.b
.emit(Op::CallBuiltin(crate::host::JITER_TOKEN, 1), line);
self.emit_set(&tok_t, line);
}
let idx_t = self.temp();
self.b.emit(Op::LoadInt(0), line);
self.emit_set(&idx_t, line);
// `i < arr.length`, as an entry guard — the loop is rotated for the
// reason [`Compiler::while_stmt`] gives, so the same test is emitted
// again at the bottom as the conditional backward branch.
self.emit_foreach_has(is_array, [&src_t, &idx_t, &arr_t], line);
let jf = self.b.emit(Op::JumpIfFalse(0), line);
let top = self.b.current_pos();
// The loop variable is rebound from `arr[i]` at the top of every
// iteration, before the body runs.
if is_array {
self.emit_get(&arr_t, line);
self.emit_get(&idx_t, line);
self.emit_raising_builtin(crate::host::JARRAY_GET, 2, line);
} else {
for t in [&src_t, &idx_t, &arr_t, &watch_t, &tok_t] {
self.emit_get(t, line);
}
self.emit_raising_builtin(crate::host::JITER_GET, 5, line);
}
self.emit_set(name, line);
self.scopes.push(BreakScope::loop_scope(label));
for s in body {
self.stmt(s)?;
}
// step label: `continue` lands on the increment.
let step = self.b.current_pos();
self.emit_get(&idx_t, line);
self.b.emit(Op::LoadInt(1), line);
self.b.emit(Op::Add, line);
self.emit_set(&idx_t, line);
self.emit_foreach_has(is_array, [&src_t, &idx_t, &arr_t], line);
self.b.emit(Op::JumpIfTrue(top), line);
let end = self.b.current_pos();
self.b.patch_jump(jf, end);
let l = self.scopes.pop().unwrap();
for op in l.continue_ops {
self.b.patch_jump(op, step);
}
for op in l.break_ops {
self.b.patch_jump(op, end);
}
Ok(())
}
/// Leave "the enhanced `for` has another element" on the stack: `i <
/// arr.length` for an array, [`JITER_HAS`](crate::host::JITER_HAS) — the
/// live-size test of a Java `ArrayList` iterator — for a collection.
fn emit_foreach_has(&mut self, is_array: bool, [src, idx, arr]: [&str; 3], line: u32) {
if is_array {
self.emit_get(idx, line);
self.emit_get(arr, line);
self.emit_field_get("length", line);
self.b.emit(Op::NumLt, line);
} else {
for t in [src, idx, arr] {
self.emit_get(t, line);
}
self.emit_raising_builtin(crate::host::JITER_HAS, 3, line);
}
}
/// The map behind `m.keySet()`, `m.values()` or `m.entrySet()` when `m` is a
/// name or field chain that can be evaluated a second time without effect.
fn map_view_owner(iter: &Expr) -> Option<&Expr> {
let Expr::MethodCall {
recv, method, args, ..
} = iter
else {
return None;
};
let view = matches!(method.as_str(), "keySet" | "values" | "entrySet");
let pure = |mut e: &Expr| loop {
match e {
Expr::Var(_) | Expr::This => return true,
Expr::Field { recv, .. } => e = recv,
_ => return false,
}
};
(view && args.is_empty() && pure(recv)).then_some(recv.as_ref())
}
/// The standalone type of a `switch` expression (JLS 15.28.1), read off
/// every result expression — each expression arm and each `yield` of a
/// block arm.
///
/// Arms of one type give that type. Numeric arms promote (JLS 5.6): one
/// `double` arm makes the switch `double`, so `case 1 -> 7; default -> 2.5`
/// yields 7.0, not 7. `char` arms mixed only with `int` constants that fit
/// a `char` stay `char`, as a conditional's do (JLS 15.25). Anything else —
/// a result javars cannot type, or reference arms of different types —
/// keeps the first typed arm's type, the answer this gave before.
fn switch_expr_type(&self, arms: &[SwitchArm]) -> Option<String> {
let results = switch_result_exprs(arms);
let types: Vec<Option<String>> = results.iter().map(|e| self.expr_java_type(e)).collect();
let first = types.iter().flatten().next().cloned();
let known: Vec<&str> = types.iter().filter_map(|t| t.as_deref()).collect();
if known.len() != types.len() || known.iter().all(|t| Some(*t) == first.as_deref()) {
return first;
}
let fits_char = |e: &Expr| matches!(e, Expr::Int(n) if (0..=0xFFFF).contains(n));
if known.contains(&"char")
&& results
.iter()
.zip(&known)
.all(|(e, t)| *t == "char" || (*t == "int" && fits_char(e)))
{
return Some("char".to_string());
}
let ranks: Option<Vec<u32>> = known.iter().map(|t| numeric_rank(t)).collect();
match ranks {
Some(ranks) => ranks.into_iter().max().map(|r| rank_name(r).to_string()),
None => first,
}
}
/// The type each result expression of a `switch` expression is converted
/// to. In an assignment or invocation context the switch is a poly
/// expression and every arm is assigned to the *target* on its own (JLS
/// 15.28.1), which is why `Object o = switch (n) { case 2 -> 7; default ->
/// 2.5; }` holds the `Integer` 7. Standalone (`var`, an operand, a
/// concatenation), each arm takes the switch's promoted floating type, the
/// conversion a conditional's integral branch gets.
fn switch_arm_target(&self, arms: &[SwitchArm], target: Option<&str>) -> Option<String> {
match target {
Some(t) if t != "var" => Some(t.to_string()),
_ => self
.switch_expr_type(arms)
.filter(|t| matches!(t.as_str(), "double" | "float")),
}
}
/// Lower an arrow `switch` expression:
/// `switch (d) { case A, B -> e; default -> { … yield v; } }`.
///
/// Arms do not fall through, so this is a `?:` chain rather than the classic
/// `switch`'s laid-out group bodies: the discriminant is evaluated once into
/// a temp, each arm's labels are compared against it, and the matching arm's
/// value is left on the stack before a jump to the end. Exactly one arm runs,
/// which is what makes the construct an expression at all.
///
/// A block arm's value comes from its `yield`, which is compiled as "leave
/// the value on the stack, then jump to the end" — the same shape a matching
/// expression arm produces, so the two are indistinguishable downstream.
fn switch_expr(
&mut self,
disc: &Expr,
arms: &[SwitchArm],
line: u32,
target: Option<&str>,
) -> Result<(), String> {
let labels: Vec<(&[Expr], bool, bool)> = arms
.iter()
.map(|a| (a.labels.as_slice(), a.is_default, a.guard.is_some()))
.collect();
// Set only for the switch itself, not for one nested in an arm.
let is_expr = !std::mem::replace(&mut self.switch_is_statement, false);
self.check_switch_labels(disc, &labels, is_expr, line)?;
let arm_target = self.switch_arm_target(arms, target);
// Java writes `case RED ->` unqualified when switching on an enum; the
// label's meaning comes from the discriminant's static type.
let enum_disc = self
.expr_java_type(disc)
.filter(|t| self.classes.get(t).is_some_and(|ci| ci.is_enum));
let disc_t = self.temp();
self.expr(disc)?;
self.emit_switch_null_check(disc, arms.iter().flat_map(|a| a.labels.iter()), line);
// See the note in `switch_stmt`: a `String` discriminant switches by
// value, so a `new String(…)` handle is read as its text.
if self.expr_java_type(disc).as_deref() == Some("String") {
self.b.emit(Op::CallBuiltin(crate::host::JUNBOX, 1), line);
}
self.emit_set(&disc_t, line);
let mut end_jumps: Vec<usize> = Vec::new();
let mut default_arm: Option<&SwitchArm> = None;
for arm in arms {
if arm.is_default {
// `default` is laid out last whatever its source position, so an
// arm written before it still gets to match.
default_arm = Some(arm);
continue;
}
// if (disc matches L1 || disc matches L2 …) { <arm>; jump end }
let mut hits: Vec<usize> = Vec::new();
let mut miss: Vec<usize> = Vec::new();
for (i, label) in arm.labels.iter().enumerate() {
self.emit_case_test(&disc_t, label, enum_disc.as_ref(), line)?;
if i + 1 == arm.labels.len() {
miss.push(self.b.emit(Op::JumpIfFalse(0), line));
} else {
hits.push(self.b.emit(Op::JumpIfTrue(0), line));
}
}
// A `when` guard runs after a label matched, and a failed guard is a
// miss like any other — the arm is skipped and the next one tried.
if let Some(guard) = &arm.guard {
let at_guard = self.b.current_pos();
for j in hits.drain(..) {
self.b.patch_jump(j, at_guard);
}
self.expr(guard)?;
miss.push(self.b.emit(Op::JumpIfFalse(0), line));
}
let body_at = self.b.current_pos();
for j in hits {
self.b.patch_jump(j, body_at);
}
self.emit_switch_arm_body(&arm.body, arm_target.as_deref(), line)?;
end_jumps.push(self.b.emit(Op::Jump(0), line));
let next = self.b.current_pos();
for j in miss {
self.b.patch_jump(j, next);
}
}
match default_arm {
Some(arm) => self.emit_switch_arm_body(&arm.body, arm_target.as_deref(), line)?,
// No `default`: `javac` only accepts that for an exhaustive `enum`
// switch, so no value can be missing in a program it compiled. The
// placeholder keeps the stack balanced if one somehow is.
None => {
self.b.emit(Op::LoadUndef, line);
}
}
let end = self.b.current_pos();
for j in end_jumps {
self.b.patch_jump(j, end);
}
Ok(())
}
/// Emit one arrow arm's body so that it leaves exactly one value on the
/// stack, converted to `target` (see [`Compiler::switch_arm_target`]). An
/// expression arm is that expression; a block arm runs its
/// statements and takes its value from `yield` (or `null` on fall-off, which
/// is what an arrow-`switch` *statement*'s arms all do).
fn emit_switch_arm_body(
&mut self,
body: &SwitchArmBody,
target: Option<&str>,
line: u32,
) -> Result<(), String> {
match body {
SwitchArmBody::Expr(e) => self.expr_targeted(e, target),
SwitchArmBody::Block(stmts) => {
let outer_target =
std::mem::replace(&mut self.yield_target, target.map(str::to_string));
let outer = std::mem::take(&mut self.yield_ops);
let outer_depth =
std::mem::replace(&mut self.yield_finally_depth, self.finallys.len());
for s in stmts {
self.stmt(s)?;
}
// Falling off the end of the block pushes `null` — which is what
// an arrow-`switch` *statement*'s arms all do, and what a
// value-producing arm never reaches because its `yield` jumped
// straight past this instruction.
self.b.emit(Op::LoadUndef, line);
self.yield_finally_depth = outer_depth;
self.yield_target = outer_target;
let yields = std::mem::replace(&mut self.yield_ops, outer);
let end = self.b.current_pos();
for j in yields {
self.b.patch_jump(j, end);
}
Ok(())
}
}
}
/// Lower a classic `switch`. The discriminant is evaluated once into an
/// internal temp, then a dispatch chain compares it (via `==`, matching
/// javars's value-equality model for both `int` and `String`) against each
/// group's labels and jumps to the first match. Group bodies are laid out
/// consecutively so control falls through into the next group unless a
/// `break` intervenes; an unmatched discriminant jumps to `default` (or the
/// switch exit when there is no default).
/// A `switch` over a reference with no `case null` label throws
/// `NullPointerException` on `null`, before any label is tried (JLS 14.11.3):
/// the lowering Java uses calls `hashCode()`/`ordinal()`/`xxxValue()` on the
/// discriminant, or `Objects.requireNonNull` for a pattern switch. A `case
/// null` label opts out, and a primitive discriminant can never be `null`.
fn emit_switch_null_check<'a>(
&mut self,
disc: &Expr,
mut labels: impl Iterator<Item = &'a Expr>,
line: u32,
) {
if labels.any(|l| matches!(l, Expr::Var(n) if n == NULL_LITERAL)) {
return;
}
let ty = self.expr_java_type(disc);
let call = match ty.as_deref() {
Some("String") => "String.hashCode()".to_string(),
Some(t) if !is_reference_type(t) => return,
Some(t) if crate::host::box_class_code(t).is_some() => {
let prim = unwrapped_ty(t);
format!("java.lang.{t}.{prim}Value()")
}
Some(t) if self.classes.get(t).is_some_and(|ci| ci.is_enum) => {
format!("{}.ordinal()", self.classes[t].binary)
}
_ => String::new(),
};
let c = self.b.add_constant(Value::str(call));
self.b.emit(Op::LoadConst(c), line);
self.emit_raising_builtin(crate::host::JSWITCH_NONNULL, 2, line);
}
fn switch_stmt(&mut self, disc: &Expr, groups: &[SwitchGroup]) -> Result<(), String> {
let labels: Vec<(&[Expr], bool, bool)> = groups
.iter()
.map(|g| (g.labels.as_slice(), g.is_default, g.guard.is_some()))
.collect();
self.check_switch_labels(disc, &labels, false, 0)?;
let label = self.pending_label.take();
// Evaluate the discriminant once and stash it in an internal temp. The
// name uses `#` (not a legal Java identifier char) so it never collides
// with a user variable.
let temp = format!("#switch{}", self.switch_counter);
self.switch_counter += 1;
// Java writes `case RED:` unqualified when switching on an enum; the
// label's meaning comes from the discriminant's static type.
let enum_disc = self
.expr_java_type(disc)
.filter(|t| self.classes.get(t).is_some_and(|ci| ci.is_enum));
self.expr(disc)?;
self.emit_switch_null_check(disc, groups.iter().flat_map(|g| g.labels.iter()), 0);
// Java's `switch` on a `String` compares with `equals`, not `==`, so a
// `new String(…)` handle must be read as its text. Unboxing once here
// is enough: a `String`-typed discriminant can carry no pattern label,
// which is the only thing that would want the handle.
if self.expr_java_type(disc).as_deref() == Some("String") {
self.b.emit(Op::CallBuiltin(crate::host::JUNBOX, 1), 0);
}
self.emit_set(&temp, 0);
// Dispatch: for each group's labels, compare and jump-if-equal to that
// group's body. Body positions are not known yet, so collect the jumps
// and backpatch once the bodies are emitted.
let mut group_jumps: Vec<Vec<usize>> = Vec::with_capacity(groups.len());
let mut default_group: Option<usize> = None;
for (gi, g) in groups.iter().enumerate() {
let mut jumps = Vec::new();
// A `when` guard applies to the whole group, so a label that matched
// still has to clear it. The label jumps forward to the guard rather
// than straight to the body, and only the guard reaches the body.
let mut hits = Vec::new();
for lab in &g.labels {
self.emit_case_test(&temp, lab, enum_disc.as_ref(), 0)?;
let target = if g.guard.is_some() {
&mut hits
} else {
&mut jumps
};
target.push(self.b.emit(Op::JumpIfTrue(0), 0));
}
if let Some(guard) = &g.guard {
let skip = self.b.emit(Op::Jump(0), 0);
let at_guard = self.b.current_pos();
for j in hits {
self.b.patch_jump(j, at_guard);
}
self.expr(guard)?;
jumps.push(self.b.emit(Op::JumpIfTrue(0), 0));
let after = self.b.current_pos();
self.b.patch_jump(skip, after);
}
if g.is_default {
default_group = Some(gi);
}
group_jumps.push(jumps);
}
// No label matched: jump to the default body (patched later) or the exit.
let to_default = self.b.emit(Op::Jump(0), 0);
// Bodies, laid out in source order for fall-through.
self.scopes.push(BreakScope::switch_scope(label));
let mut group_starts = Vec::with_capacity(groups.len());
for g in groups {
group_starts.push(self.b.current_pos());
for s in &g.body {
self.stmt(s)?;
}
}
let end = self.b.current_pos();
let scope = self.scopes.pop().unwrap();
// Patch each label's jump to its group body.
for (gi, jumps) in group_jumps.into_iter().enumerate() {
for op in jumps {
self.b.patch_jump(op, group_starts[gi]);
}
}
// Patch the no-match jump to the default body, or the exit.
match default_group {
Some(gi) => self.b.patch_jump(to_default, group_starts[gi]),
None => self.b.patch_jump(to_default, end),
}
for op in scope.break_ops {
self.b.patch_jump(op, end);
}
Ok(())
}
/// Emit the test for one `case` label, leaving a boolean on the stack.
///
/// `disc_t` names the temp holding the already-evaluated discriminant, so
/// the label is tested against it however many labels the group has and
/// whatever the label's shape.
///
/// A **pattern** label is an `instanceof` against that discriminant, and it
/// binds its variable exactly as `Expr::InstanceOf`'s does — unconditionally,
/// because Java's flow scoping already guarantees no arm but the matching
/// one can read it. A **constant** label is the value comparison every
/// `switch` has always used: `NumEq`, which is value equality for `int` and
/// `String` and handle identity for an enum singleton.
fn emit_case_test(
&mut self,
disc_t: &str,
label: &Expr,
enum_disc: Option<&String>,
line: u32,
) -> Result<(), String> {
if let Expr::TypePattern {
class,
binding,
components,
} = label
{
return self.emit_pattern_test(disc_t, class, binding, components, line);
}
self.emit_get(disc_t, line);
match (enum_disc, label) {
(Some(class), Expr::Var(c)) => self.emit_global_get(&enum_global(class, c), line),
_ => self.expr(label)?,
}
// Java's `switch` on a `String` selects with `equals`, not with `==`, so
// a `String` label compares by text. The label's own shape decides it:
// a string literal there means the selector is a `String`, whatever
// javars could infer about the selector's type. Without this a
// discriminant built at run time matched no label at all, `NumEq` on two
// strings having become an identity test.
if matches!(label, Expr::Str(_)) {
self.b.emit(Op::StrEq, line);
} else {
self.b.emit(Op::NumEq, line);
}
Ok(())
}
/// Emit a pattern's test against the value in the temp `subject`, leaving a
/// boolean on the stack.
///
/// A plain type pattern binds unconditionally and tests with `instanceof`:
/// Java's flow scoping is a compile-time rule, so `javac` has already
/// rejected every program that reads the binding where the pattern did not
/// match, and a conditional store would cost a branch to protect a value no
/// valid program can observe.
///
/// A **record** pattern cannot do that. Its components are read through the
/// record's accessors, which a value of the wrong class does not have — so
/// the reads are guarded by the type test, and each nested component pattern
/// is itself a test that can fail. The shape is
/// `type-test && c1-matches && c2-matches && …`, with every failure landing
/// on one `false`.
fn emit_pattern_test(
&mut self,
subject: &str,
class: &str,
binding: &Option<String>,
components: &[Expr],
line: u32,
) -> Result<(), String> {
// A component pattern whose type is a primitive or `var` always
// matches: the accessor's type is fixed by the record's declaration, so
// `javac` has already checked it and there is nothing to test at
// runtime. It binds and answers `true`.
if components.is_empty() && (class == "var" || !is_reference_type(class)) {
if let Some(name) = binding {
let ty = class.to_string();
self.declare_local(name, &ty, numtype_of_ty(&ty).unwrap_or(NumType::Other));
self.emit_get(subject, line);
self.emit_set(name, line);
}
self.b.emit(Op::LoadTrue, line);
return Ok(());
}
if let Some(name) = binding {
let ty = class.to_string();
self.declare_local(name, &ty, numtype_of_ty(&ty).unwrap_or(NumType::Other));
self.emit_get(subject, line);
self.emit_set(name, line);
}
self.emit_get(subject, line);
let class_c = self.b.add_constant(Value::str(class.to_string()));
self.b.emit(Op::LoadConst(class_c), line);
self.b
.emit(Op::CallBuiltin(crate::host::JINSTANCEOF, 2), line);
if components.is_empty() {
return Ok(());
}
let names = self.record_component_names(class).ok_or_else(|| {
format!(
"javars: `{class}` is not a record, so it has no component pattern (line {line})"
)
})?;
if names.len() != components.len() {
return Err(format!(
"javars: record pattern for `{class}` has {} component(s), but `{class}` declares {} (line {line})",
components.len(),
names.len()
));
}
// The accessor calls are built as ordinary method calls on the subject,
// so the subject has to be a *declared* local of the record's type for
// the dispatch to resolve it. Declaring it here is also what types the
// call's result.
self.declare_local(subject, class, NumType::Other);
let mut misses = vec![self.b.emit(Op::JumpIfFalse(0), line)];
for (comp, accessor) in components.iter().zip(names) {
let Expr::TypePattern {
class: cty,
binding: cbind,
components: nested,
} = comp
else {
return Err(format!(
"javars: a record pattern's components must themselves be patterns (line {line})"
));
};
// Read the component through its accessor, into a temp the nested
// pattern can test and re-read.
let slot = self.temp();
self.expr(&Expr::MethodCall {
recv: Box::new(Expr::Var(subject.to_string())),
method: accessor.clone(),
args: Vec::new(),
line,
})?;
self.declare_local(&slot, cty, numtype_of_ty(cty).unwrap_or(NumType::Other));
self.emit_set(&slot, line);
self.emit_pattern_test(&slot, cty, cbind, nested, line)?;
misses.push(self.b.emit(Op::JumpIfFalse(0), line));
}
self.b.emit(Op::LoadTrue, line);
let to_end = self.b.emit(Op::Jump(0), line);
let at_false = self.b.current_pos();
for j in misses {
self.b.patch_jump(j, at_false);
}
self.b.emit(Op::LoadFalse, line);
let end = self.b.current_pos();
self.b.patch_jump(to_end, end);
Ok(())
}
/// A record's component accessor names, in component order, or `None` for a
/// class that is not a record.
///
/// Taken from the class's instance fields, which for a record *are* its
/// components in declaration order — the parser lowers each component to a
/// field before anything else can add one, and Java forbids a record any
/// other instance field.
fn record_component_names(&self, class: &str) -> Option<Vec<String>> {
let info = self.classes.get(class)?;
info.is_record
.then(|| info.fields.iter().map(|f| f.name.clone()).collect())
}
/// Lower `break;` / `break label;`. An unlabeled break targets the innermost
/// loop or `switch`; a labeled break targets the matching named construct.
fn break_stmt(&mut self, label: Option<&str>, line: u32) -> Result<(), String> {
// The target is resolved first: the `finally` blocks the jump leaves are
// exactly those entered inside the targeted construct, and their bodies
// have to be emitted *before* the jump itself.
match self.find_scope(label, |_| true) {
Some(idx) => {
let keep = self.finallys_outside(idx);
self.emit_finallys_down_to(keep)?;
let op = self.b.emit(Op::Jump(0), line);
self.scopes[idx].break_ops.push(op);
Ok(())
}
None if label.is_none() => {
// A top-level `break` (no enclosing construct) ends the program,
// preserving javars's existing behavior.
self.emit_finallys_down_to(0)?;
let op = self.b.emit(Op::Jump(0), line);
self.exit_ops.push(op);
Ok(())
}
None => Err(format!(
"javars: undefined label `{}` for break (line {line})",
label.unwrap()
)),
}
}
/// Lower `continue;` / `continue label;`. Targets the innermost enclosing
/// loop (skipping `switch` scopes), or the named loop for a labeled form.
fn continue_stmt(&mut self, label: Option<&str>, line: u32) -> Result<(), String> {
match self.find_scope(label, |s| s.kind == ScopeKind::Loop) {
Some(idx) => {
let keep = self.finallys_outside(idx);
self.emit_finallys_down_to(keep)?;
let op = self.b.emit(Op::Jump(0), line);
self.scopes[idx].continue_ops.push(op);
Ok(())
}
None => Err(match label {
Some(l) => format!("javars: undefined label `{l}` for continue (line {line})"),
None => "javars: `continue` outside a loop".to_string(),
}),
}
}
/// Find the index of the innermost enclosing scope satisfying `pred`. With a
/// label, the scope must also carry that label; without one, the innermost
/// matching scope is used.
fn find_scope(&self, label: Option<&str>, pred: impl Fn(&BreakScope) -> bool) -> Option<usize> {
self.scopes.iter().enumerate().rev().find_map(|(i, s)| {
let label_ok = match label {
Some(l) => s.label.as_deref() == Some(l),
None => true,
};
if label_ok && pred(s) {
Some(i)
} else {
None
}
})
}
/// Lower `name++` / `++name` in value position, where `name` is a local, a
/// global, an implicit `this` field, or a static of the enclosing class.
/// Post yields the value read before the mutation, pre the one read after.
fn var_inc_dec(&mut self, name: &str, inc: bool, want: Yield) -> Result<(), String> {
if want == Yield::Old {
self.emit_named_read(name);
}
self.post_inc_dec(name, inc)?;
if want == Yield::New {
self.emit_named_read(name);
}
Ok(())
}
/// Emit a read of a bare name, resolving it the way `post_inc_dec` writes
/// it: an implicit `this` field, a static of the enclosing class, or a
/// local/global.
fn emit_named_read(&mut self, name: &str) {
if self.implicit_this_field(name).is_some() {
self.emit_this(0);
let key = self.field_key(&Expr::This, name);
self.emit_field_get(&key, 0);
} else if let Some((class, _)) = self.static_field_owner(name) {
self.emit_static_field_init(&class, name, 0);
self.emit_global_get(&static_global(&class, name), 0);
} else if let Some((recv, _)) = self.outer_field_recv(name) {
self.emit_this_chain(&recv);
let key = self.field_key(&recv, name);
self.emit_field_get(&key, 0);
} else {
self.emit_get(name, 0);
}
}
/// Emit `this`, or the `this.this$0…` chain [`Compiler::outer_field_recv`]
/// and [`Compiler::enclosing_instance`] build.
fn emit_this_chain(&mut self, recv: &Expr) {
match recv {
Expr::Field { recv, name } => {
self.emit_this_chain(recv);
let key = self.field_key(recv, name);
self.emit_field_get(&key, 0);
}
_ => self.emit_this(0),
}
}
/// Lower `lv++` / `++lv` where `lv` is an array element or a field.
///
/// JLS 15.14.2/15.15.1 define these as `lv += 1` / `lv -= 1` with the
/// implicit narrowing cast a compound assignment carries, so the compound
/// path does the work — which is also what evaluates the array, index, or
/// receiver exactly once, as Java requires when it has side effects.
fn inc_dec(&mut self, target: &Expr, inc: bool, want: Yield, line: u32) -> Result<(), String> {
let op = if inc { AssignOp::Add } else { AssignOp::Sub };
let one = Expr::Int(1);
match target {
Expr::Index { array, index } => self.index_update(array, index, op, &one, want, line),
Expr::Field { recv, name } => self.field_update(recv, name, op, &one, want, line),
// A parenthesized variable still reaches here as `Expr::Var`.
Expr::Var(name) => self.var_inc_dec(name, inc, want),
_ => Err(format!(
"javars: `{}` needs a variable, an array element, or a field (line {line})",
if inc { "++" } else { "--" }
)),
}
}
/// Lower an assignment in value position — `(n = next()) != -1`,
/// `a = b = 0`, `(a[i] += 2) > 5` — leaving the value the target holds
/// after the store (JLS 15.26). A compound form reuses the `++`/`--`
/// read/modify/write with `Yield::New`; a plain `=` stashes the converted
/// right-hand side, so the array, index, or receiver is evaluated once.
fn assign_value(
&mut self,
target: &Expr,
op: AssignOp,
value: &Expr,
line: u32,
) -> Result<(), String> {
match target {
// A bare name — local, implicit `this` field, or static — stores
// through the statement lowering and is read back by name; the name
// has no subexpression that a second read could re-run.
Expr::Var(name) => {
self.stmt(&Stmt {
line: 0,
kind: StmtKind::Assign {
name: name.clone(),
op,
value: value.clone(),
},
})?;
self.emit_named_read(name);
Ok(())
}
Expr::Index { array, index } if op != AssignOp::Assign => {
self.index_update(array, index, op, value, Yield::New, line)
}
Expr::Field { recv, name } if op != AssignOp::Assign => {
self.field_update(recv, name, op, value, Yield::New, line)
}
Expr::Index { array, index } => {
let elem_ty = self
.expr_array_type(array)
.and_then(|t| t.strip_suffix("[]").map(str::to_string));
let (arr_t, idx_t, val_t) = (self.temp(), self.temp(), self.temp());
self.expr(array)?;
self.emit_set(&arr_t, line);
self.expr_unboxed(index)?;
self.emit_set(&idx_t, line);
self.expr_targeted(value, elem_ty.as_deref())?;
self.emit_set(&val_t, line);
self.emit_get(&arr_t, line);
self.emit_get(&idx_t, line);
self.emit_get(&val_t, line);
self.emit_raising_builtin(crate::host::JARRAY_SET, 3, line);
self.b.emit(Op::Pop, line);
self.emit_get(&val_t, line);
Ok(())
}
Expr::Field { recv, name } => {
if let Some((class, ty)) = self.static_target(recv, name) {
self.static_assign(&class, &ty, name, op, value, line)?;
self.emit_global_get(&static_global(&class, name), line);
return Ok(());
}
let field_ty_name = self.field_type_name(recv, name);
let key = self.field_key(recv, name);
let (obj_t, val_t) = (self.temp(), self.temp());
self.expr(recv)?;
self.emit_set(&obj_t, line);
self.expr_targeted(value, field_ty_name.as_deref())?;
self.emit_set(&val_t, line);
self.emit_get(&obj_t, line);
let name_c = self.b.add_constant(Value::str(key.clone()));
self.b.emit(Op::LoadConst(name_c), line);
self.emit_get(&val_t, line);
self.emit_raising_builtin(crate::host::JFIELD_SET, 3, line);
self.b.emit(Op::Pop, line);
self.emit_get(&val_t, line);
Ok(())
}
_ => Err(format!(
"javars: the left-hand side of an assignment must be a variable (line {line})"
)),
}
}
/// Lower `name++` / `name--` as a statement (result discarded), mutating a
/// local/global or — when `name` is an implicit `this` field — that field.
fn post_inc_dec(&mut self, name: &str, inc: bool) -> Result<(), String> {
let op = if inc { AssignOp::Add } else { AssignOp::Sub };
if self.implicit_this_field(name).is_some() {
return self.field_assign(&Expr::This, name, op, &Expr::Int(1), 0);
}
if let Some((class, ty)) = self.static_field_owner(name) {
return self.static_assign(&class, &ty, name, op, &Expr::Int(1), 0);
}
if let Some((recv, _)) = self.outer_field_recv(name) {
return self.field_assign(&recv, name, op, &Expr::Int(1), 0);
}
let decl = self.var_decl_type(name).map(str::to_string);
// A wrapper variable is unboxed, stepped, and reboxed (JLS 15.14.2), so
// a `null` one throws and the result is a fresh `valueOf` box.
let prim = decl.as_deref().map(unwrapped_ty);
let wrap = prim == Some("int");
self.emit_get(name, 0);
if let Some(d) = decl.as_deref() {
self.emit_checked_unbox(d);
}
self.b.emit(Op::LoadInt(1), 0);
// `float f; f++;` is a 32-bit addition like every other `float`
// operation, not a 64-bit one narrowed afterwards.
if prim == Some("float") {
self.emit_f32_arith(if inc { BinOp::Add } else { BinOp::Sub }, 0);
} else {
self.b.emit(if inc { Op::Add } else { Op::Sub }, 0);
if wrap {
self.emit_wrap32(0);
}
// `++` carries the same implicit narrowing cast a compound
// assignment does, so `char c = 65535; c++;` is 0 rather than 65536.
self.emit_narrow_to(prim, 0);
}
if let Some(d) = decl.as_deref() {
self.emit_rebox(d);
}
self.emit_set(name, 0);
Ok(())
}
/// Lower `System.out.print[ln](arg)` (or the `System.err` variant when
/// `err`) to the Java-formatting print builtin. Leaves the builtin's `null`
/// return value on the stack.
fn println(&mut self, newline: bool, err: bool, arg: Option<&Expr>) -> Result<(), String> {
let n = match arg {
// `println(char[])` is its own `PrintStream` overload and writes the
// *characters*: `System.out.println(new char[]{'h','i'})` is `hi`,
// where `"" + cs` is still `[C@…` because string concatenation has
// no such overload. javars rendered the handle for both, so the one
// idiom that spells a char array out printed `[@2`. `String.valueOf`
// is the same join, so the conversion routes through it rather than
// growing a second one.
Some(e) if self.is_char_array_expr(e) => {
self.emit_char_string(e)?;
let class_c = self.b.add_constant(Value::str("String".to_string()));
self.b.emit(Op::LoadConst(class_c), 0);
let method_c = self.b.add_constant(Value::str("valueOf".to_string()));
self.b.emit(Op::LoadConst(method_c), 0);
self.emit_raising_builtin(crate::host::JSTATIC_DISPATCH, 3, 0);
1
}
Some(e) => {
self.emit_stringified(e)?;
1
}
None => 0,
};
let id = match (err, newline) {
(false, true) => crate::host::JPRINTLN,
(false, false) => crate::host::JPRINT,
(true, true) => crate::host::JEPRINTLN,
(true, false) => crate::host::JEPRINT,
};
self.b.emit(Op::CallBuiltin(id, n), 0);
Ok(())
}
/// Evaluate `e`, dispatching a user-defined `toString()` when `e` is an
/// instance of a class whose (subtree) declares one — so `println(obj)` and
/// string concatenation (`"x " + obj`) honour the override. Otherwise
/// evaluate normally (the host's `java_str` renders the default `Class@hash`
/// form, which is what `String.valueOf(obj)` still gets — see BUGS.md).
///
/// The dispatch is keyed on the receiver's *runtime* class even when the
/// static type already declares `toString`, because that is also the test
/// that catches a `null`: Java's string conversion of a null reference is
/// the text "null", not a call on nothing.
fn emit_stringified(&mut self, e: &Expr) -> Result<(), String> {
if self.is_char_expr(e) || self.is_float32_expr(e) {
return self.emit_char_string(e);
}
// A `Class` is its binary name here, but its string conversion adds the
// `class `/`interface ` keyword.
if let Some(interface) = self.class_value_kind(e) {
self.expr(e)?;
self.b.emit(Op::LoadInt(i64::from(interface)), 0);
self.b.emit(Op::CallBuiltin(crate::host::JCLASS_STR, 2), 0);
return Ok(());
}
// A `List` operand's string conversion is its `toString()`, and for a
// `subList` view that call is what reports a backing list which moved
// underneath it. Routing a statically-known list through the collection
// dispatch (instead of the host's infallible rendering) is what lets
// the `ConcurrentModificationException` surface from `"x " + view`; it
// produces the identical text for every other list.
// A `null` list is the text "null" (JLS 5.1.11), not a call on nothing.
if self.expr_java_type(e).as_deref().and_then(collection_kind) == Some("list") {
let list_t = self.temp();
self.expr(e)?;
self.emit_set(&list_t, 0);
self.emit_get(&list_t, 0);
self.expr(&Expr::Var(NULL_LITERAL.to_string()))?;
self.b.emit(Op::NumEq, 0);
let not_null = self.b.emit(Op::JumpIfFalse(0), 0);
let null_c = self.b.add_constant(Value::str("null".to_string()));
self.b.emit(Op::LoadConst(null_c), 0);
let done = self.b.emit(Op::Jump(0), 0);
let call = self.b.current_pos();
self.b.patch_jump(not_null, call);
self.emit_get(&list_t, 0);
let name_c = self.b.add_constant(Value::str("toString".to_string()));
self.b.emit(Op::LoadConst(name_c), 0);
self.emit_raising_builtin(crate::host::JCOLL_DISPATCH, 2, 0);
let end = self.b.current_pos();
self.b.patch_jump(done, end);
return Ok(());
}
let Some(rc) = self.expr_class(e) else {
return self.emit_host_stringified(e);
};
let overriders = self.to_string_overriders(&rc);
if overriders.is_empty() {
return self.emit_host_stringified(e);
}
self.emit_virtual_to_string(e, &overriders)
}
/// Whether `e` denotes a `java.lang.Class`, and if so whether it is an
/// interface's: a class literal, `x.getClass()`, `e.getDeclaringClass()`, or
/// a variable declared `Class<…>`.
fn class_value_kind(&self, e: &Expr) -> Option<bool> {
match e {
Expr::ClassLit(name) => {
let name = self.class_lit_class(name);
let user = self.classes.get(name).map(|c| c.is_interface);
Some(user.unwrap_or_else(|| crate::host::is_jdk_interface(name)))
}
Expr::MethodCall { method, args, .. }
if args.is_empty()
&& matches!(method.as_str(), "getClass" | "getDeclaringClass") =>
{
Some(false)
}
Expr::Var(name) => self
.var_decl_type(name)
.is_some_and(|t| t == "Class" || t.starts_with("Class<"))
.then_some(false),
_ => None,
}
}
/// The fall-through of [`Compiler::emit_stringified`]: an operand whose
/// static type does not name a user class — an `Object`, a `Map`, an erased
/// `get()` — so the compiler cannot build a dispatch chain for it.
///
/// When the program declares a `toString()` anywhere, the value goes through
/// the [`JSTRINGIFY`](crate::host::JSTRINGIFY) builtin, which holds a `&mut
/// VM` and can therefore run the override the runtime class resolves, at
/// every depth of a nested collection. Left to fusevm's `Op::Add` instead,
/// the operand would be stringified by the numeric hook — three values and
/// no VM — so `"" + o` would print `Pt@1` while `println(o)`, which is a
/// builtin, printed `Pt<1>`. One rendering that is wrong is a documented
/// model; two renderings of one object in one program is a trap.
///
/// A program with no override emits exactly the bytecode it always did: the
/// `Op::Add` lowering is the JIT-visible one, and this must not cost
/// anything when there is nothing to dispatch to.
fn emit_host_stringified(&mut self, e: &Expr) -> Result<(), String> {
self.expr(e)?;
if self.has_user_tostring && !self.renders_without_a_class(e) {
self.emit_raising_builtin(crate::host::JSTRINGIFY, 1, 0);
}
Ok(())
}
/// Whether `e` is statically known to be something no `toString()` override
/// can answer for — a literal, or a value whose declared type is a primitive,
/// a wrapper, or `String`. javars models every one of those as a scalar
/// `Value`, never a heap handle, so routing it through the rendering builtin
/// would only add a call to every `"x " + i` in a program that happens to
/// declare one override somewhere.
fn renders_without_a_class(&self, e: &Expr) -> bool {
if matches!(
e,
Expr::Int(_)
| Expr::Long(_)
| Expr::Float(_)
| Expr::Float32(_)
| Expr::Str(_)
| Expr::Char(_)
| Expr::Bool(_)
) {
return true;
}
matches!(
self.expr_java_type(e).as_deref(),
Some(
"int"
| "long"
| "short"
| "byte"
| "char"
| "boolean"
| "double"
| "float"
| "Integer"
| "Long"
| "Short"
| "Byte"
| "Character"
| "Boolean"
| "Double"
| "Float"
| "String"
)
)
}
/// Every concrete subtype of `rc` that resolves a no-arg `toString`, as
/// `(class, mangled subroutine)`, sorted for deterministic bytecode.
fn to_string_overriders(&self, rc: &str) -> Vec<(String, String)> {
let mut v: Vec<(String, String)> = self
.classes
.iter()
.filter(|(_, ci)| !ci.is_interface)
.map(|(k, _)| k)
.filter(|k| self.is_subclass(k, rc))
.filter_map(|k| {
self.resolve_instance_sig(k, "toString", &[])
.map(|(m, _)| (k.clone(), m))
})
.collect();
v.sort();
v
}
/// Render `e` through whichever `toString` its *runtime* class supplies,
/// falling through to the host's default `Class@hash` when it has none. The
/// receiver is evaluated exactly once, into a temp.
fn emit_virtual_to_string(
&mut self,
e: &Expr,
overriders: &[(String, String)],
) -> Result<(), String> {
let recv_t = self.temp();
self.expr(e)?;
self.emit_set(&recv_t, 0);
let class_t = self.temp();
self.emit_get(&recv_t, 0);
self.b.emit(Op::CallBuiltin(crate::host::JCLASSOF, 1), 0);
self.emit_set(&class_t, 0);
let mut end_jumps = Vec::new();
for (class, mangled) in overriders {
self.emit_get(&class_t, 0);
let cc = self.b.add_constant(Value::str(class.clone()));
self.b.emit(Op::LoadConst(cc), 0);
self.b.emit(Op::StrEq, 0);
let skip = self.b.emit(Op::JumpIfFalse(0), 0);
self.emit_get(&recv_t, 0);
let idx = self.b.add_name(mangled);
self.b.emit(Op::Call(idx, 1), 0);
self.emit_exc_check(0);
end_jumps.push(self.b.emit(Op::Jump(0), 0));
let next = self.b.current_pos();
self.b.patch_jump(skip, next);
}
// No override for this runtime class: the value renders itself.
self.emit_get(&recv_t, 0);
let end = self.b.current_pos();
for j in end_jumps {
self.b.patch_jump(j, end);
}
Ok(())
}
fn expr(&mut self, e: &Expr) -> Result<(), String> {
match e {
// `T.class` — the one `Class` object for the binary name the
// source spells, the same object `x.getClass()` answers for an
// instance of it. Whether it is an interface is known here and
// nowhere at run time, and `toString()` reads it.
Expr::ClassLit(name) => {
let interface = self.class_value_kind(e).unwrap_or(false);
let c = self.string_literal(&self.class_literal_name(name));
self.b.emit(Op::LoadConst(c), 0);
self.b.emit(Op::LoadInt(i64::from(interface)), 0);
self.b.emit(Op::CallBuiltin(crate::host::JCLASS_LIT, 2), 0);
}
// A pattern label carries no subject of its own — the `switch`
// supplies its discriminant — so it is lowered by
// [`Compiler::emit_case_test`] and never reaches here.
Expr::TypePattern { class, .. } => {
return Err(format!(
"javars: `{class}` pattern is only valid as a `case` label"
))
}
Expr::Int(n) | Expr::Long(n) => {
self.b.emit(Op::LoadInt(*n), 0);
}
Expr::Float(f) => {
let c = self.b.add_constant(Value::float(*f));
self.b.emit(Op::LoadConst(c), 0);
}
// A `float` literal is stored already rounded to 32-bit precision,
// so `0.1f` is the `f64` nearest `0.1f32` from the start.
Expr::Float32(f) => {
let c = self.b.add_constant(Value::float(*f as f32 as f64));
self.b.emit(Op::LoadConst(c), 0);
}
Expr::Str(s) => {
let c = self.string_literal(s);
self.b.emit(Op::LoadConst(c), 0);
}
// A `char` runs as its code point; the static type is what turns it
// back into a one-character String at a string conversion.
Expr::Char(c) => {
self.b
.emit(Op::LoadInt(i64::from(crate::jstr::char_value(*c))), 0);
}
Expr::Bool(b) => {
self.b
.emit(if *b { Op::LoadTrue } else { Op::LoadFalse }, 0);
}
Expr::Var(name) => {
// `super` denotes the same object `this` does, so it evaluates
// to the receiver — the superclass view is entirely a
// compile-time matter (`bare_var_type` supplies the type,
// `super_call` the non-virtual dispatch). Emitting the receiver
// is what makes `super.f` read and write `this`'s field cell.
if name == SUPER {
if self.this_class.is_none() {
return Err("javars: `super` used outside an instance method".to_string());
}
self.emit_this(0);
}
// A bare name that is a field of `this` (not a local) reads
// `this.name`; otherwise it is a plain local/global.
else if let Some(class) = self.enclosing_enum_constant(name) {
self.emit_class_init(&class, 0);
self.emit_global_get(&enum_global(&class, name), 0);
} else if self.implicit_this_field(name).is_some() {
self.emit_this(0); // this
let key = self.field_key(&Expr::This, name);
self.emit_field_get(&key, 0);
} else if let Some((class, _)) = self.static_field_owner(name) {
self.emit_static_field_init(&class, name, 0);
self.emit_global_get(&static_global(&class, name), 0);
} else if let Some((recv, _)) = self.outer_field_recv(name) {
self.emit_this_chain(&recv);
let key = self.field_key(&recv, name);
self.emit_field_get(&key, 0);
} else if !self.is_declared_var(name) && name != NULL_LITERAL {
// Nothing declares this name. Java's answer is "cannot find
// symbol"; javars read the unset cell instead and got
// `null`, so `undefinedVar` printed `null` and
// `undefinedVar + 1` printed `null1` — a typo becoming
// output rather than a diagnostic. It is also what made
// naming an unmodeled class a *runtime* failure:
// `IntStream.range(0, 3)` reported
// `NullPointerException: Cannot invoke "String.range()"`,
// because `IntStream` is, to javars, just an undeclared
// name.
return Err(format!("javars: cannot find symbol: `{name}`"));
} else {
self.emit_get(name, 0);
}
}
Expr::This => {
if self.this_class.is_none() {
return Err("javars: `this` used outside an instance method".to_string());
}
self.emit_this(0);
}
Expr::NewArray {
elem_ty,
sizes,
extra_dims,
} => {
if sizes.len() == 1 && *extra_dims == 0 {
// Single dimension — the direct allocate builtin.
self.expr(&sizes[0])?;
self.emit_type_default(elem_ty, 0);
self.emit_raising_builtin(crate::host::JARRAY_NEW, 2, 0);
} else {
// Multi-dimensional: push each sized dimension, then the leaf
// default (the element-type default when fully sized, else
// `null` for the inner unsized levels).
for s in sizes {
self.expr(s)?;
}
if *extra_dims > 0 {
self.b.emit(Op::LoadUndef, 0);
} else {
self.emit_type_default(elem_ty, 0);
}
self.emit_raising_builtin(
crate::host::JARRAY_NEW_MULTI,
sizes.len() as u8 + 1,
0,
);
}
let dims = sizes.len() + extra_dims;
self.emit_array_tag(&format!("{elem_ty}{}", "[]".repeat(dims)), 0);
}
Expr::ArrayLit { elems, elem_ty } => {
let elem_ty = elem_ty.clone();
self.array_lit(elems, elem_ty.as_deref())?;
}
Expr::Index { array, index } => {
self.expr(array)?;
self.expr_unboxed(index)?;
self.emit_raising_builtin(crate::host::JARRAY_GET, 2, 0);
}
Expr::Field { recv, name } => {
// `Outer.this` — the enclosing instance of that class.
if let Some(class) = self.qualified_this(e) {
match self.enclosing_instance(class) {
Expr::Var(_) => {
return Err(format!(
"javars: `{class}.this` names no enclosing instance here"
))
}
inst => self.emit_this_chain(&inst),
}
}
// `Integer.MAX_VALUE` / `Math.PI` / … — a `static final` of a
// `java.lang` type javars does not model as a class, folded to
// its literal value.
else if let Some((v, _)) = self.wrapper_constant_ref(e) {
let c = self.b.add_constant(v);
self.b.emit(Op::LoadConst(c), 0);
}
// `BigInteger.ONE` — the shared constant, built through `valueOf`.
else if let Some((call, _)) = self.library_constant(e) {
self.expr(&call)?;
}
// `Color.RED` names an enum constant's singleton, not a field of
// a value — there is no receiver to evaluate.
else if let Some(class) = self.enum_constant_ref(e) {
self.emit_class_init(&class, 0);
self.emit_global_get(&enum_global(&class, name), 0);
} else if let Some((class, _)) = self.static_field_ref(e) {
// `T.n` names a `static` field's shared cell — the receiver
// is a type, so there is nothing to evaluate.
self.emit_static_field_init(&class, name, 0);
self.emit_global_get(&static_global(&class, name), 0);
} else {
self.expr(recv)?;
let key = self.field_key(recv, name);
self.emit_field_get(&key, 0);
}
}
Expr::NewObject {
class,
args,
outer,
line,
..
} => {
// An enum's instances are its constants (JLS 8.9): `new` on one
// is a compile error.
if self.classes.get(class).is_some_and(|ci| ci.is_enum) {
return Err(format!(
"javars: enum classes may not be instantiated (line {line})"
));
}
self.new_object(class, args, outer.as_deref(), *line)?
}
Expr::InstanceOf {
expr,
class,
binding,
components,
} => {
// The subject is evaluated once into a temp, because a record
// pattern reads it again for each component accessor.
let subject = self.temp();
self.expr(expr)?;
self.emit_set(&subject, 0);
self.emit_pattern_test(&subject, class, binding, components, 0)?;
}
Expr::Unary { op, rhs } => {
if self.expr_java_type(rhs).as_deref() == Some("String") {
let sym = match op {
UnOp::Neg => "-",
UnOp::Not => "!",
UnOp::BitNot => "~",
UnOp::Plus => "+",
};
return Err(format!(
"javars: bad operand type String for unary operator '{sym}'"
));
}
// Unary numeric promotion and `!` both unbox a wrapper operand
// (JLS 5.6.1, 15.15.6), so a `null` one throws. `~` needs the
// number besides: it is answered natively for every operand
// shape, and a boxed operand would be read as the handle.
self.expr_unboxed(rhs)?;
match op {
UnOp::Neg => {
self.b.emit(Op::Negate, 0);
// `-Integer.MIN_VALUE` is `Integer.MIN_VALUE`.
if Self::is_int_width(self.expr_java_type(rhs).as_deref()) {
self.emit_wrap32(0);
}
}
UnOp::Not => {
self.b.emit(Op::LogNot, 0);
}
UnOp::BitNot => {
self.b.emit(Op::BitNot, 0);
}
// Unary `+` changes no bits — only the static type, which
// `expr_java_type` already reports as the promoted one.
UnOp::Plus => {}
}
}
Expr::Cast {
ty,
targs,
expr,
line,
} => {
// `(Function<Integer, Integer>) x -> x * 2` gives the lambda its
// target (JLS 15.16), typed by the cast's arguments as a
// declaration's would type it.
if matches!(expr.as_ref(), Expr::Lambda { .. }) {
self.lambda_target = Some(ty.clone());
self.lambda_generic = with_targs(ty, targs);
}
let r = self.cast(ty, expr, *line);
self.lambda_generic = None;
r?
}
Expr::Binary { op, lhs, rhs } => self.binary(*op, lhs, rhs)?,
Expr::Ternary { cond, then, els } => self.ternary(cond, then, els)?,
// Println/PostIncDec in value position are handled as statements;
// if one reaches here (nested), the print builtin already leaves its
// `null` return value on the stack.
Expr::Println { newline, err, arg } => {
self.println(*newline, *err, arg.as_deref())?;
}
Expr::PostIncDec { name, inc } => self.var_inc_dec(name, *inc, Yield::Old)?,
Expr::PreIncDec { name, inc } => self.var_inc_dec(name, *inc, Yield::New)?,
Expr::IncDec {
target,
inc,
post,
line,
} => self.inc_dec(
target,
*inc,
if *post { Yield::Old } else { Yield::New },
*line,
)?,
Expr::Assign {
target,
op,
value,
line,
} => self.assign_value(target, *op, value, *line)?,
Expr::Call { name, args, .. } if name == crate::parser::ANON_CLASS_CALL => {
self.expr(&args[0])?;
self.emit_anon_class_name(&args[1]);
}
Expr::Call { name, args, line } => match self.implicit_enum_static(name, args, *line) {
Some(call) => self.expr(&call)?,
None => self.call(name, args, *line)?,
},
Expr::MethodCall {
recv,
method,
args,
line,
} => self.method_call(recv, method, args, *line)?,
Expr::SwitchExpr { disc, arms, line } => self.switch_expr(disc, arms, *line, None)?,
Expr::Lambda {
params, body, line, ..
} => self.compile_lambda(params, body, *line)?,
Expr::MethodRef { recv, method, line } => {
// The arity a reference to an arity-overloaded method resolves
// at: the target interface's, or the JDK method's slot's.
let target_arity = self
.lambda_target
.as_deref()
.and_then(|t| self.functional_sam(t))
.map(|(_, n)| n);
self.ref_arity_hint = target_arity.or(self.ref_arity_hint.take());
let lambda = self.desugar_method_ref(recv, method, *line);
self.ref_arity_hint = None;
let lambda = lambda?;
self.expr(&lambda)?;
}
}
Ok(())
}
/// `Iterable.forEach(action)` as the interface's `default` body:
/// `for (T x : recv) action.accept(x)`, with `action` evaluated once.
fn iterable_for_each(&mut self, recv: &Expr, args: &[Expr], line: u32) -> Result<(), String> {
let action = format!("#fe{}", self.temp_counter);
self.temp_counter += 1;
let each = format!("#fe{}", self.temp_counter);
self.temp_counter += 1;
let accept = Expr::MethodCall {
recv: Box::new(Expr::Var(action.clone())),
method: "accept".to_string(),
args: vec![Expr::Var(each.clone())],
line,
};
self.stmt(&Stmt::new(
line,
StmtKind::Local {
targs: Vec::new(),
wildcard: false,
super_slots: Vec::new(),
ty: "Consumer".to_string(),
name: action,
init: Some(args[0].clone()),
is_final: false,
},
))?;
self.stmt(&Stmt::new(
line,
StmtKind::ForEach {
targs: Vec::new(),
super_slots: Vec::new(),
ty: "var".to_string(),
name: each,
iter: recv.clone(),
body: vec![Stmt::new(line, StmtKind::Expr(accept))],
is_final: false,
},
))?;
self.b.emit(Op::LoadUndef, line);
Ok(())
}
/// Lower an instance method call `recv.method(args...)`. Dispatch order:
/// a bare stdlib class receiver (`Math.abs`) → the static-dispatch builtin;
/// a user-class receiver (resolved by the receiver's static type) → a direct
/// `Op::Call` to the class's mangled instance-method subroutine, with the
/// receiver bound as `this` (frame slot 0); anything else → the `String`
/// method-dispatch builtin.
fn method_call(
&mut self,
recv: &Expr,
method: &str,
args: &[Expr],
line: u32,
) -> Result<(), String> {
self.check_private_access(recv, method, args.len(), line)?;
// A static interface method is called through its interface's name,
// never through a value (JLS 15.12.3).
if self.user_class_ref(recv).is_none() {
if let Some(class) = self.expr_class(recv) {
let static_only = self
.interface_statics
.contains(&(class.clone(), method.to_string()))
&& !self.has_instance_method(&class, method, args.len());
if static_only {
return Err(format!(
"javars: illegal static interface method call (line {line})"
));
}
}
}
// A call whose receiver is a bare capitalized class name (`Math.abs`,
// `Integer.parseInt`, `String.valueOf`) is a static stdlib call: the
// receiver is not a value, so it is not evaluated. Args, then the class
// and method names, are handed to the static-dispatch builtin.
// `x.getClass()` — javars has no `Class` object, so the call evaluates
// to the receiver's runtime class *name*, and `Class`'s two accessors
// (`getName`, `getSimpleName`) are String methods over it. A user class
// that declares its own `getClass` is not shadowed, because Java forbids
// overriding it.
// `s.mapMulti(m)` is `s.flatMap(e -> { buf = []; m.accept(e, buf::add);
// return buf; })` (the JDK's own default body, which pushes each
// accepted element downstream in order). The mapper adapter is the
// prelude's `BiConsumer.mapMulti$`, so the user's lambda is lowered
// against `BiConsumer` and its consumer argument is a real `Consumer`.
// `out.printf(fmt, args…)` on a `PrintWriter`/`PrintStream` is
// `String.format(fmt, args…)` written through the receiver — the one
// formatter, which only the static call site can give each argument's
// type to — then the autoflush a `println` would do.
if matches!(method, "printf" | "format")
&& !args.is_empty()
&& matches!(
self.expr_java_type(recv).as_deref(),
Some("PrintWriter" | "PrintStream")
)
{
let text = Expr::MethodCall {
recv: Box::new(Expr::Var("String".to_string())),
method: "format".to_string(),
args: args.to_vec(),
line,
};
return self.method_call(recv, "#printf", &[text], line);
}
// A leading `Locale` constant — `String.format(Locale.US, …)`,
// `s.toUpperCase(Locale.ROOT)` — names one of the locales javars's
// root-locale formatting already matches (see `wrapper_constant`), so
// the call is the one without it. Only a constant or a variable is
// dropped, since neither has a side effect to lose.
let locale_first = args.first().is_some_and(|l| {
(matches!(l, Expr::Var(_))
|| matches!(l, Expr::Field { recv: c, .. } if matches!(c.as_ref(), Expr::Var(n) if n == "Locale")))
&& self.expr_java_type(l).as_deref() == Some("Locale")
});
if locale_first {
let string_static =
matches!(recv, Expr::Var(c) if c == "String" && !self.is_declared_var(c));
let strips = match method {
"format" => string_static && args.len() >= 2,
"toUpperCase" | "toLowerCase" => args.len() == 1 && !string_static,
_ => false,
};
if strips {
return self.method_call(recv, method, &args[1..], line);
}
}
if method == "mapMulti" && args.len() == 1 && self.expr_class(recv).is_none() {
let adapter = Expr::MethodCall {
recv: Box::new(Expr::Var("BiConsumer".to_string())),
method: "mapMulti$".to_string(),
args: args.to_vec(),
line,
};
return self.method_call(recv, "flatMap", &[adapter], line);
}
if method == "getClass" && args.is_empty() {
self.expr(recv)?;
// An array's element type is erased at runtime, so `[I` versus
// `[Ljava.lang.String;` is recoverable only from the receiver's
// static type. The *source* spelling goes across — the host turns
// it into a descriptor, because resolving a user component's
// binary name (`A` → `T$A`) needs the map only the host holds.
// Every other shape is decided from the value.
let array_type = self
.expr_java_type(recv)
.filter(|t| t.ends_with("[]"))
.unwrap_or_default();
let d = self.b.add_constant(Value::str(array_type));
self.b.emit(Op::LoadConst(d), line);
self.b
.emit(Op::CallBuiltin(crate::host::JBINARY_CLASS, 2), line);
return Ok(());
}
// `Map.Entry.comparingByKey()` / `comparingByValue()` — the two
// comparators an `entrySet()` is nearly always sorted with. Each is
// synthesized as the lambda the JDK's own implementation is, so it
// reaches the same erased `compareTo` dispatch every other comparator
// does and needs no host support of its own. The receiver is the *type*
// `Map.Entry`, which parses as a field access on `Map` and would
// otherwise be looked up as a variable.
if let Expr::Field { recv: outer, name } = recv {
if name == "Entry"
&& matches!(outer.as_ref(), Expr::Var(c) if c == "Map")
&& !self.is_declared_var("Map")
&& args.is_empty()
{
if let Some(accessor) = match method {
"comparingByKey" => Some("getKey"),
"comparingByValue" => Some("getValue"),
_ => None,
} {
return self.expr(&entry_comparator(accessor, line));
}
}
}
// A sort with no comparator orders by the elements' own `compareTo`,
// which only a Java-level call can reach — the host's `natural_cmp`
// knows numbers and strings and answers "equal" for everything else, so
// a `List` of a user `Comparable` came back in its original order. The
// missing comparator is supplied here instead, as the same
// `(a, b) -> a.compareTo(b)` lambda `Comparator.naturalOrder()` is.
// `Collections.reverseOrder()` is the comparator `Comparator.reverseOrder()`
// is, and `reverseOrder(cmp)` is `cmp.reversed()` — `null` meaning the
// natural order, as the JDK specifies. Both already exist in the prelude.
if method == "reverseOrder"
&& matches!(recv, Expr::Var(c) if c == "Collections")
&& !self.is_declared_var("Collections")
{
let natural = Expr::MethodCall {
recv: Box::new(Expr::Var("Comparator".to_string())),
method: "reverseOrder".to_string(),
args: vec![],
line,
};
match args {
[] => return self.expr(&natural),
[Expr::Var(n)] if n == NULL_LITERAL => return self.expr(&natural),
[c] => {
return self.expr(&Expr::MethodCall {
recv: Box::new(c.clone()),
method: "reversed".to_string(),
args: vec![],
line,
})
}
_ => {}
}
}
if method == "sort" {
let collections_sort = matches!(recv, Expr::Var(c) if c == "Collections")
&& !self.is_declared_var("Collections");
let arrays_sort =
matches!(recv, Expr::Var(c) if c == "Arrays") && !self.is_declared_var("Arrays");
let explicit_null = |e: &Expr| matches!(e, Expr::Var(n) if n == NULL_LITERAL);
let natural = if collections_sort {
match args {
[l] => Some(vec![l.clone(), natural_order_comparator(line)]),
[l, c] if explicit_null(c) => {
Some(vec![l.clone(), natural_order_comparator(line)])
}
_ => None,
}
} else if arrays_sort {
// Only a reference array: an `int[]` sorts numerically on the host,
// and an array whose type is unknown keeps the host's order too.
let reference = args
.first()
.and_then(|a| self.expr_java_type(a))
.is_some_and(|t| t.strip_suffix("[]").is_some_and(is_reference_type));
let nat = || natural_order_comparator(line);
match args {
_ if !reference => None,
[a] => Some(vec![a.clone(), nat()]),
[a, c] if explicit_null(c) => Some(vec![a.clone(), nat()]),
[a, f, t] => Some(vec![a.clone(), f.clone(), t.clone(), nat()]),
[a, f, t, c] if explicit_null(c) => {
Some(vec![a.clone(), f.clone(), t.clone(), nat()])
}
_ => None,
}
} else {
match args {
[c] if explicit_null(c) => Some(vec![natural_order_comparator(line)]),
_ => None,
}
};
if let Some(args) = natural {
return self.method_call(recv, method, &args, line);
}
}
// `Collections.max`/`min`/`binarySearch` with no comparator (or a
// `null` one) order by the elements' own `compareTo`, for the reason the
// comparator-less sort above does: the host's natural order cannot reach
// a user `Comparable`, and answered "equal" for every pair of them.
if matches!(method, "max" | "min" | "binarySearch")
&& matches!(recv, Expr::Var(c) if c == "Collections")
&& !self.is_declared_var("Collections")
{
let explicit_null = |e: &Expr| matches!(e, Expr::Var(n) if n == NULL_LITERAL);
let nat = || natural_order_comparator(line);
let natural = match (method, args) {
("max" | "min", [c]) => Some(vec![c.clone(), nat()]),
("max" | "min", [c, n]) if explicit_null(n) => Some(vec![c.clone(), nat()]),
("binarySearch", [l, k]) => Some(vec![l.clone(), k.clone(), nat()]),
("binarySearch", [l, k, n]) if explicit_null(n) => {
Some(vec![l.clone(), k.clone(), nat()])
}
_ => None,
};
if let Some(args) = natural {
return self.method_call(recv, method, &args, line);
}
}
// `super.method(args)` is the one call that must NOT go through the
// virtual dispatch chain: it names the superclass's implementation of a
// method the receiver's own class overrides. It is intercepted here,
// ahead of every receiver-typed branch below, because `expr_class` types
// a `super` receiver as the superclass — which would otherwise dispatch
// it virtually and call the override back on itself. (`getClass` is
// above this on purpose: it is `final` in Java, so `super.getClass()` is
// `this.getClass()`.)
if matches!(recv, Expr::Var(n) if n == SUPER) {
return self.super_call(method, args, line);
}
// `I.super.m(args)` — the default method of a direct superinterface
// `I`, called on `this` without virtual dispatch (JLS 15.12.1), which is
// how an implementation reaches the default it overrides.
if let Expr::Field { recv: owner, name } = recv {
if let (Expr::Var(iface), true) = (&**owner, name == SUPER) {
if self.classes.get(iface).is_some_and(|ci| ci.is_interface) {
let iface = iface.clone();
return self.interface_super_call(&iface, method, args, line);
}
}
}
// A fully-qualified stdlib receiver (`java.util.Arrays.sort(x)`) names
// exactly the class its simple name does — javars keys every type on the
// simple name, so the package qualifier is dropped and the call re-enters
// through the ordinary static path.
if let Some(simple) = qualified_static_class(recv) {
return self.method_call(&Expr::Var(simple), method, args, line);
}
if let Some(call) = self.enum_class_value_of(recv, method, args, line) {
return self.expr(&call);
}
// `Color.values()` / `Color.valueOf(s)` — the two statics every enum has.
// They are compiler-generated because javars keeps no per-class static
// method table.
if let Some(class) = self.enum_type_ref(recv) {
match (method, args.len()) {
("values", 0) => {
self.emit_enum_values(&class, line);
return Ok(());
}
("valueOf", 1) => return self.emit_enum_value_of(&class, &args[0], line),
// A `static` method the enum declares itself goes through the
// ordinary qualified-static path below.
_ if self
.methods
.get(method)
.is_some_and(|ms| ms.iter().any(|s| s.owner == class)) => {}
_ => {
return Err(format!(
"javars: enum `{class}` has no static method `{method}` taking {} argument(s) (line {line})",
args.len()
))
}
}
}
// `T.helper(x)` on a user class is a call to that class's `static`
// method. It resolves in `T`'s own inheritance chain — NOT through the
// flat by-name pool a bare `helper(x)` falls back to — so a same-named
// static on an unrelated class can never be selected.
if let Some(class) = self.user_class_ref(recv) {
if self.methods.contains_key(method) {
let arg_tys: Vec<Option<String>> = self.arg_types(args);
if let Some(resolved) = self.resolve_static_on(&class, method, &arg_tys) {
let args =
Self::effective_args(args, &resolved.param_tys, resolved.vararg_from);
self.call_args_generic(&args, &resolved.param_tys, &resolved.mangled)?;
self.emit_class_init(&resolved.owner, line);
let name_idx = self.b.add_name(&resolved.mangled);
self.b.emit(Op::Call(name_idx, args.len() as u8), line);
self.emit_exc_check(line);
return Ok(());
}
if !is_static_class(&class) {
return Err(format!(
"javars: class `{class}` has no static method `{method}` taking {} argument(s) (line {line})",
args.len()
));
}
} else if !is_static_class(&class) {
return Err(format!(
"javars: class `{class}` has no static method `{method}` (line {line})"
));
}
// A class the *host* also models falls through to its static table
// rather than erroring here. That is what lets a prelude type — a
// functional interface whose defaults are written in Java — reach a
// static only the host can answer: `Comparator.isKeyExtractor`
// reads a lambda's parameter count, which no Java body can.
}
// `EnumSet`'s factories. An `EnumSet` iterates in ordinal order, which
// is an enum's natural order, so javars models one as the `TreeSet` it
// behaves as and each factory as the matching `TreeSet` construction.
if let Expr::Var(c) = recv {
if c == "EnumSet" && !self.classes.contains_key(c) && !self.is_declared_var(c) {
// `range` and `complementOf` need the enum's constants, which
// only the static type names: they reach the host with the
// `values()` array first.
if matches!((method, args.len()), ("range", 2) | ("complementOf", 1)) {
let elem = self
.expr_generic(&Expr::MethodCall {
recv: Box::new(recv.clone()),
method: method.to_string(),
args: args.to_vec(),
line,
})
.and_then(|g| crate::ast::generic_parts(&g).1.into_iter().next())
.filter(|e| self.classes.get(e).is_some_and(|ci| ci.is_enum))
.ok_or_else(|| {
format!("javars: `EnumSet.{method}` needs a statically known enum type (line {line})")
})?;
self.emit_enum_values(&elem, line);
for a in args {
self.expr(a)?;
}
let cc = self.b.add_constant(Value::str("EnumSet"));
self.b.emit(Op::LoadConst(cc), line);
let mc = self.b.add_constant(Value::str(method.to_string()));
self.b.emit(Op::LoadConst(mc), line);
self.emit_raising_builtin(
crate::host::JSTATIC_DISPATCH,
args.len() as u8 + 3,
line,
);
return Ok(());
}
let made = enum_set_factory(method, args, line).ok_or_else(|| {
format!(
"javars: `EnumSet.{method}` with {} argument(s) is not modeled (line {line})",
args.len()
)
})?;
return self.expr(&made);
}
}
if let Expr::Var(class) = recv {
if is_static_class(class) && !self.is_declared_var(class) {
// `List.of(E...)` and its kin take a lone array argument *as*
// their varargs array only when it is an array of references:
// an `int[]` is no `E[]` (JLS 15.12.2.4), so it is the one
// element of the result. The host spreads a lone array, so a
// primitive one is handed over inside a one-element array.
if let [arg] = args {
let prim_array = self.expr_java_type(arg).filter(|t| {
t.strip_suffix("[]")
.is_some_and(|el| !is_reference_type(el) && el != "void")
});
if let (Some(t), ("List" | "Set" | "Stream", "of") | ("Arrays", "asList")) =
(prim_array, (class.as_str(), method))
{
return self.expr(&Expr::MethodCall {
recv: Box::new(recv.clone()),
method: method.to_string(),
args: vec![Expr::ArrayLit {
elems: vec![arg.clone()],
elem_ty: Some(t),
}],
line,
});
}
}
// A static whose parameter renders the value as text takes the
// `char`'s one-character String; `Math.max(c, 5)` and the
// `Character` predicates take the code point unchanged.
let stringify = takes_char_as_string(class, method);
// `String.format` is the one static that treats its arguments
// differently from each other: the slots a `%s` consumes want
// `Float.toString`, the slots a `%f` consumes want the number.
let text_slots = (class == "String" && method == "format")
.then(|| match args.first() {
Some(Expr::Str(fmt)) => Some(text_conversion_slots(fmt)),
// A non-literal format string cannot be scanned, so the
// numeric conversions are kept exact and `%s` of a
// `float` prints its `double` form (see BUGS.md).
_ => Some(Vec::new()),
})
.flatten();
// Every `java.util.Objects` static takes `Object`, so every
// primitive argument crosses into a reference position and
// autoboxes there. `Objects.equals(a, b)` runs `a.equals(b)`,
// which compares references, so `Objects.equals(aLong, 1000)` is
// `false` in Java; and a `char` has to arrive as a `Character`
// rather than as its code point, or `Objects.toString('c')`
// renders 99 where the reference renders `c`.
let box_args = class == "Objects"
// The collection factories build *elements*, so their
// arguments autobox exactly as `list.add(x)`'s does — which
// is what keeps `List.of(128, 128).get(0) == get(1)` the
// `false` Java answers and `Map.of(1, …, 1.0, …, 1L, …)` at
// three entries. `Arrays.fill` is deliberately not here: its
// second argument is an *array element*, and an `int[]` slot
// holds the primitive.
|| matches!(
(class.as_str(), method),
("List", "of") | ("Set", "of") | ("Map", "of") | ("Arrays", "asList")
| ("Stream", "of")
| ("Stream", "iterate")
| ("Optional", "of")
| ("Optional", "ofNullable")
);
for (i, a) in args.iter().enumerate() {
let floats = match &text_slots {
Some(slots) => i > 0 && slots.contains(&(i - 1)),
// A factory that boxes its arguments makes a `float` a
// `Float` element, which renders through `Float.toString`
// by itself; its text would not be a number any more.
None => stringify && !box_args,
};
// Every lambda a `Collectors` factory takes answers a
// reference (a key, a value, a mapped element, a merged
// result) except its predicates, its `ToXFunction`s, and
// its comparators — so a `char` body boxes to `Character`
// as `groupingBy(s -> s.charAt(0))` does on the JDK.
if class == "Collectors"
&& matches!(a, Expr::Lambda { .. })
&& !matches!(
method,
"partitioningBy"
| "filtering"
| "summingInt"
| "summingLong"
| "summingDouble"
| "averagingInt"
| "averagingLong"
| "averagingDouble"
| "minBy"
| "maxBy"
| "summarizingInt"
| "summarizingLong"
| "summarizingDouble"
)
{
self.lambda_ret_hint = Some("Object".to_string());
}
// `Stream.iterate`'s step (its last argument — the middle one of
// three is a predicate) and `Stream.generate`'s supplier answer
// the element type, a reference; `IntStream`'s take primitive
// functions and are not named here.
// `Objects`' suppliers (`requireNonNullElseGet`'s value,
// `requireNonNull`'s message) answer a reference too.
if class == "Objects" && matches!(a, Expr::Lambda { .. }) {
self.lambda_ret_hint = Some("Object".to_string());
}
if class == "Stream"
&& matches!(a, Expr::Lambda { .. } | Expr::MethodRef { .. })
&& ((method == "iterate" && i + 1 == args.len()) || method == "generate")
{
self.lambda_ret_hint = Some("Object".to_string());
}
// `Arrays.fill`'s value is assigned into an element, so it
// takes the array's element type: `fill(new double[2], 2)`
// stores `2.0`.
let fill_value =
class == "Arrays" && method == "fill" && i > 0 && i + 1 == args.len();
// A factory element boxes a `char` to its `Character` below
// rather than taking the text.
let boxed_char = (box_args || class == "Collections")
&& self.expr_java_type(a).as_deref() == Some("char");
if stringify && !boxed_char {
self.emit_converted_arg(a, floats)?;
} else if fill_value {
let elem = self
.expr_array_type(&args[0])
.and_then(|t| t.strip_suffix("[]").map(str::to_string));
self.expr_targeted(a, elem.as_deref())?;
} else {
self.expr(a)?;
}
self.lambda_ret_hint = None;
if box_args || boxed_char {
// `autobox_code` has no `char` arm — a `char` is a code
// point, not one of the numeric boxes — so the
// `Character` box is named here, the same way
// `emit_erased_arg` names it for `x.equals('z')`.
// Without it `Objects.toString('c')` rendered the code
// point, 99, where the reference renders `c`.
let code = match self.expr_java_type(a).as_deref() {
Some("char") => crate::host::box_class_code("Character"),
_ => self.autobox_code(a),
};
if let Some(code) = code {
self.b.emit(Op::LoadInt(code), line);
self.b.emit(Op::CallBuiltin(crate::host::JBOX, 2), line);
}
}
}
// `java.util.Formatter` rejects a conversion whose argument is
// the wrong boxed type, and only the compiler knows which box
// each argument is — `Value::Int` is `Integer`, `Long`,
// `Short`, `Byte` and `char` all at once. So `String.format`
// gets its own builtin, taking the static types alongside the
// values. An argument whose type javars could not infer sends
// an empty tag and is classified from its runtime value.
if text_slots.is_some() {
let tags: Vec<String> = args
.iter()
.skip(1)
.map(|a| self.expr_java_type(a).unwrap_or_default())
.collect();
let tags_c = self.b.add_constant(Value::str(tags.join("\x1f")));
self.b.emit(Op::LoadConst(tags_c), line);
self.emit_raising_builtin(crate::host::JFORMAT, args.len() as u8 + 1, line);
return Ok(());
}
// `Math.round` is two Java methods: the `double` one answers a
// `long`, the `float` one an `int`, and they disagree at the
// extremes (`Math.round(1.0e20f)` is `Integer.MAX_VALUE`, not
// `Long.MAX_VALUE`). Only the static type says which overload
// this call selected, so the `float` one gets its own builtin —
// the same split `JF32_ARITH` makes, and unlike `Math.abs`
// below the narrowing saturates rather than wraps.
if class == "Math"
&& method == "round"
&& args.len() == 1
&& self.is_float32_expr(&args[0])
{
self.b
.emit(Op::CallBuiltin(crate::host::JF32_ROUND, 1), line);
return Ok(());
}
// `Math`'s `Exact` family and `clamp` are overloaded on `int`
// AND `long`, and the two disagree exactly where they are
// interesting: `Math.addExact(2000000000, 2000000000)` throws
// for the `int` overload and answers 4000000000 for the `long`
// one. Only the arguments' static types say which overload the
// call selected, so the width goes to the host as one more
// operand — which is also what makes the arity it dispatches on
// (`("Math", "addExact", 3)`) distinct from any real overload's.
let widened = if self.math_float_overload(class, method, args) {
Some(crate::host::width::FLOAT)
} else {
self.overload_width(class, method, args)?
};
if let Some(code) = widened {
self.b.emit(Op::LoadInt(code), line);
}
// `Arrays.copyOf`/`copyOfRange` pad a grown copy with the
// *element type's* default, and the element type is erased at
// run time — the host reads it off element 0, which an **empty**
// source does not have. So `Arrays.copyOf(new int[0], 2)`
// answered `[null, null]` where Java answers `[0, 0]`, and
// likewise for every other primitive element type. The source's
// static type is known here and nowhere else, so the pad goes to
// the host as one more operand — the same route `overload_width`
// takes above.
let pad = (class == "Arrays" && matches!(method, "copyOf" | "copyOfRange"))
.then(|| args.first().and_then(|a| self.array_element_default(a)))
.flatten();
if let Some(v) = pad.clone() {
let c = self.b.add_constant(v);
self.b.emit(Op::LoadConst(c), line);
}
// `System.arraycopy` checks the two arrays' element types
// against each other and names them in its messages
// (`int[5]`, `object array[2]`); only the static types carry
// them, so both ride along as two more operands.
//
// `Arrays.compare` is overloaded on the element type, and the
// `byte[]`/`short[]` overloads answer the *difference* of the
// first mismatching pair where the others answer -1/0/1, so it
// takes the two static types the same way.
let tagged = match (class.as_str(), method, args.len()) {
("System", "arraycopy", 5) => Some([&args[0], &args[2]]),
("Arrays", "compare", 2) => Some([&args[0], &args[1]]),
_ => None,
};
let array_tags = tagged.is_some();
if let Some(tagged) = tagged {
for a in tagged {
let ty = self.expr_java_type(a).unwrap_or_default();
let c = self.b.add_constant(Value::str(ty));
self.b.emit(Op::LoadConst(c), line);
}
}
let class_c = self.b.add_constant(Value::str(class.clone()));
self.b.emit(Op::LoadConst(class_c), line);
// `String.valueOf` of a reference that is statically not a `char[]` is
// the `valueOf(Object)` overload, which renders an array as a handle.
let object_overload = class == "String"
&& method == "valueOf"
&& args.len() == 1
&& !self.is_char_array_expr(&args[0])
&& self
.expr_java_type(&args[0])
.is_some_and(|t| is_reference_type(&t));
let name = if object_overload {
crate::host::VALUE_OF_OBJECT
} else {
method
};
let method_c = self.b.add_constant(Value::str(name.to_string()));
self.b.emit(Op::LoadConst(method_c), line);
// argc counts the args plus the class-name and method-name
// strings, plus the width operand and the array pad when there
// is one of each.
self.emit_raising_builtin(
crate::host::JSTATIC_DISPATCH,
args.len() as u8
+ 2
+ u8::from(widened.is_some())
+ u8::from(pad.is_some())
+ 2 * u8::from(array_tags),
line,
);
// The `Math` overloads that overflow at `int` width:
// `Math.abs(Integer.MIN_VALUE)` is `Integer.MIN_VALUE` because
// negating it does not fit an `int`, and
// `Math.floorDiv(Integer.MIN_VALUE, -1)` is the same value for
// the same reason (it answered 2147483648, the `long` the host
// computed). The host has no argument width to work from, so the
// narrowing is emitted here — and only when *every* argument is
// `int`-width, since the `long` overloads must keep 64 bits.
let int_overflowing = matches!(
(class.as_str(), method, args.len()),
("Math", "abs", 1)
| ("Math", "floorDiv" | "floorMod" | "ceilDiv" | "ceilMod", 2)
);
if int_overflowing
&& args
.iter()
.all(|a| Self::is_int_width(self.expr_java_type(a).as_deref()))
{
self.emit_wrap32(line);
}
// `Integer.valueOf(x)` and its siblings are Java's *explicit*
// boxing conversion, cache and all — which is what makes
// `Integer.valueOf(127) == Integer.valueOf(127)` `true` and the
// same pair at 128 `false`. The host dispatch answers the
// primitive; the box goes on here, where the class is known.
if method == "valueOf" && args.len() == 1 {
if let Some(code) = crate::host::box_class_code(class) {
self.b.emit(Op::LoadInt(code), line);
self.b.emit(Op::CallBuiltin(crate::host::JBOX, 2), line);
}
}
return Ok(());
}
}
// A user-class receiver: dispatch on the receiver's runtime class
// (virtual dispatch), collapsing to a direct call when not overridden.
//
// `equals`/`toString` a class does not declare are the ones it inherits
// from `Object`, which has no Java-level body here — so they fall
// through to the host, where they are reference identity and
// `getClass().getName() + "@" + hex`. A class that declares either wins,
// which is what keeps a `record`'s and an `enum`'s own versions in play.
// `hashCode` is in that set too, now that a `record` synthesizes its own
// (which therefore wins here). It was excluded while records had none,
// because an identity hash for a value type would have been a silently
// wrong number rather than the compile error it was; for a plain class
// the identity hash IS `Object`'s specified answer.
// A receiver typed as the bare interface (a lambda or a collection held as
// an `Iterable`) gets the same default `forEach`.
if method == "forEach"
&& args.len() == 1
&& self.expr_class(recv).is_none()
&& self
.expr_java_type(recv)
.as_deref()
.map(|t| t.split('<').next().unwrap_or_default())
== Some("Iterable")
{
return self.iterable_for_each(recv, args, line);
}
if let Some(rc) = self.expr_class(recv) {
// `Iterable.forEach(action)` is a `default` method, so a user class
// that implements `Iterable` and declares no `forEach` inherits it:
// `for (T x : this) action.accept(x)`, with `action` evaluated once.
if method == "forEach"
&& args.len() == 1
&& self.is_subclass(&rc, "Iterable")
&& !self.has_instance_method(&rc, "forEach", 1)
{
return self.iterable_for_each(recv, args, line);
}
// `Iterator.forEachRemaining(action)` is the interface's `default`
// body, inherited the same way: `Objects.requireNonNull(action);
// while (hasNext()) action.accept(next());`, with the receiver and
// then `action` evaluated once each, in that order.
if method == "forEachRemaining"
&& args.len() == 1
&& self.is_subclass(&rc, "Iterator")
&& !self.has_instance_method(&rc, "forEachRemaining", 1)
{
let it = format!("#fr{}", self.temp_counter);
self.temp_counter += 1;
let action = format!("#fr{}", self.temp_counter);
self.temp_counter += 1;
let call = |recv: &str, method: &str, args: Vec<Expr>| Expr::MethodCall {
recv: Box::new(Expr::Var(recv.to_string())),
method: method.to_string(),
args,
line,
};
let body = [
StmtKind::Local {
targs: Vec::new(),
wildcard: false,
super_slots: Vec::new(),
ty: rc.clone(),
name: it.clone(),
init: Some(recv.clone()),
is_final: false,
},
StmtKind::Local {
targs: Vec::new(),
wildcard: false,
super_slots: Vec::new(),
ty: "Consumer".to_string(),
name: action.clone(),
init: Some(args[0].clone()),
is_final: false,
},
StmtKind::Expr(call(
"Objects",
"requireNonNull",
vec![Expr::Var(action.clone())],
)),
StmtKind::While {
cond: call(&it, "hasNext", vec![]),
body: vec![Stmt::new(
line,
StmtKind::Expr(call(
&action,
"accept",
vec![call(&it, "next", vec![])],
)),
)],
},
];
for kind in body {
self.stmt(&Stmt::new(line, kind))?;
}
self.b.emit(Op::LoadUndef, line);
return Ok(());
}
let arg_tys: Vec<Option<String>> = self.arg_types(args);
// A `static` method called through an instance expression
// (`b.who()`) is chosen by the expression's *static* type and never
// dispatches on the object (JLS 15.12.4.1): the receiver is
// evaluated for its side effects, discarded, and the class-qualified
// call is made.
if self.resolve_instance_call(&rc, method, &arg_tys).is_none()
&& self.resolve_static_on(&rc, method, &arg_tys).is_some()
{
self.expr(recv)?;
self.b.emit(Op::Pop, line);
let qualified = Expr::MethodCall {
recv: Box::new(Expr::Var(rc.clone())),
method: method.to_string(),
args: args.to_vec(),
line,
};
return self.expr(&qualified);
}
let inherited = matches!(
(method, args.len()),
("equals", 1) | ("toString", 0) | ("hashCode", 0)
) && self.resolve_instance_call(&rc, method, &arg_tys).is_none();
if !inherited {
return self.dispatch_instance_method(recv, &rc, method, args, line);
}
}
// A `java.util` collection receiver. The runtime path in `b_str_dispatch`
// catches a collection whose static type javars could not determine
// (an erased `Map.get` result), so this is a diagnostics-and-clarity
// shortcut rather than the only route.
if let Some(kind) = self
.expr_java_type(recv)
.as_deref()
.and_then(collection_kind)
{
// `List` declares BOTH `remove(int)` and `remove(Object)`, and Java
// picks between them from the argument's *static* type: an integral
// primitive removes by index, anything else (a boxed `Integer`, a
// `String`, an `Object`) removes the first equal element. Selecting
// by index unconditionally silently removed the wrong element
// (`l.remove(Integer.valueOf(20))` on `[10,20,30]` gave `[10,20]`
// instead of `[10,30]`) or threw a bogus `IndexOutOfBoundsException`
// when the value exceeded the size. The choice is a compile-time one
// because it is a static-type question, so it is made here and the
// by-value overload reaches the host under its own name.
// An argument whose static type javars could not infer keeps the
// by-index reading it has always had, so only a *known* reference
// type switches overload. A boxed `Character` is a reference type in
// Java and selects `remove(Object)` there too.
// `Collection`, `Queue`, `Deque`, and `ArrayDeque` declare no
// `remove(int)` at all, so on a receiver of one of those static types
// an integral argument is still the element `remove(Object)` boxes.
let no_index_overload = self.expr_java_type(recv).is_some_and(|t| {
matches!(
t.split('<').next().unwrap_or_default(),
"Collection" | "Queue" | "Deque" | "ArrayDeque" | "Iterable"
)
});
let by_value = kind == "list"
&& method == "remove"
&& args.len() == 1
&& (no_index_overload
|| is_boxing_call(&args[0])
|| self
.expr_java_type(&args[0])
.is_some_and(|t| !matches!(t.as_str(), "int" | "short" | "byte" | "char")));
let method = if by_value { "removeObject" } else { method };
self.expr(recv)?;
// A `char` entering an element or key position boxes to a real
// `Character`, as every other primitive boxes to its wrapper —
// which is what keeps a `Map` keyed on `1`, which is what keeps a `Map` keyed on `1`, `1.0` and `1L`
// at three entries the way Java's is. An *index* argument is not an
// element and stays the `int` it is.
for (i, a) in args.iter().enumerate() {
if list_index_arg(kind, method, args.len(), i) {
self.expr_unboxed(a)?;
continue;
}
// A function argument whose result is a reference by signature
// (`computeIfAbsent`, `merge`, `List.replaceAll`, …) boxes a
// `char` body to a `Character`, as `lambda_returns_reference`
// says for the erased calls.
let ref_result = matches!(a, Expr::Lambda { .. } | Expr::MethodRef { .. })
&& self.lambda_returns_reference(recv, method);
if ref_result {
self.lambda_ret_hint = Some("Object".to_string());
}
if matches!(a, Expr::Lambda { .. } | Expr::MethodRef { .. }) {
self.lambda_param_hint =
self.lambda_param_generics(recv, method, args.len(), i);
}
let r = if self.is_float32_expr(a) {
// A `float` element boxes to the `Float` it is, not to its
// `Float.toString` text: the box renders through the same
// rule, and the text would make `l.get(0) * 2` a type error
// and `l.get(0) + 1` a concatenation.
self.expr(a)
} else if self.expr_java_type(a).as_deref() == Some("char") {
// Likewise a `char` is the `Character` it boxes to, not its
// text: `stack.peek() == '('` unboxes it, `c + 1` adds it,
// and `getClass()` is `Character`.
self.expr(a).map(|()| {
let code = crate::host::box_class_code("Character")
.expect("`Character` is a boxed class");
self.b.emit(Op::LoadInt(code), line);
self.b.emit(Op::CallBuiltin(crate::host::JBOX, 2), line);
})
} else {
self.emit_char_string(a)
};
self.lambda_ret_hint = None;
self.lambda_param_hint = None;
r?;
if let Some(code) = self.autobox_code(a) {
self.b.emit(Op::LoadInt(code), line);
self.b.emit(Op::CallBuiltin(crate::host::JBOX, 2), line);
}
}
let name_c = self.b.add_constant(Value::str(method.to_string()));
self.b.emit(Op::LoadConst(name_c), line);
self.emit_raising_builtin(crate::host::JCOLL_DISPATCH, args.len() as u8 + 2, line);
return Ok(());
}
self.emit_erased_call(recv, method, args, line)
}
/// Lower `recv.method(args)` where the receiver's static class is **not** a
/// user class — a boxed primitive, a `String`, an erased `List.get` result,
/// a lambda parameter, an `Object` upcast.
///
/// Two things can be true of such a receiver at runtime that the static type
/// does not say, and both used to be answered wrongly:
///
/// * It may be an instance of a user class. `Comparator.comparing(P::n)`
/// calls `n()` on a lambda parameter; `list.get(0).compareTo(x)` calls a
/// user `Comparable`'s own method. Both reached [`crate::host::JSTR_DISPATCH`]
/// and were answered by the `String` method of that name — a wrong
/// answer for `compareTo` (two `toString`s compared as text) and an
/// "unsupported String method" for everything else. So the receiver's
/// *runtime* class is read and matched against every concrete user class
/// declaring that name and arity, exactly as virtual dispatch does when
/// the static class is known.
/// * For `compareTo` specifically, the boxed type decides the answer, so
/// the receiver's static Java type rides along to
/// [`crate::host::JCOMPARE_TO`] as a tag.
///
/// The `String` method remains the last arm, which is what keeps a genuine
/// `String` receiver — and the collection and closure receivers
/// `b_str_dispatch` resolves at runtime — behaving as before.
fn emit_erased_call(
&mut self,
recv: &Expr,
method: &str,
args: &[Expr],
line: u32,
) -> Result<(), String> {
let tag = self.expr_java_type(recv).unwrap_or_default();
// `StringBuilder.append(char[])` and `append(Object)` are one value at
// runtime and two methods in Java: the array one reads the array's
// length, so `sb.append((char[]) null)` is an NPE where
// `sb.append((Object) null)` appends `"null"`. Only the argument's
// static type says which was called, so the choice is made here and the
// array overload reaches the host under a name of its own.
let method = if matches!(tag.as_str(), "StringBuilder" | "StringBuffer")
&& method == "append"
&& matches!(args.len(), 1 | 3)
&& self.expr_java_type(&args[0]).as_deref() == Some("char[]")
{
"appendChars"
} else {
method
};
let is_compare = method == "compareTo" && args.len() == 1;
// A `char`/`Character` receiver compares as a code point, so `compareTo`
// keeps its argument a number; every other call keeps the
// one-character-String spelling the rest of the frontend uses.
let raw_args = is_compare && matches!(tag.as_str(), "char" | "Character");
// The concrete user classes declaring this name and arity, as
// (runtime class, subroutine). A receiver the compiler already typed as
// a boxed primitive or a `String` can never be one of them.
let param_tys: Vec<String> = vec!["Object".to_string(); args.len()];
// An erasure (`Object`, or no inferred type at all) is what leaves the
// door open; a receiver already typed as a boxed primitive, a `String`
// or a collection is never a user instance and needs no chain.
let erased = !matches!(
tag.as_str(),
"int"
| "long"
| "short"
| "byte"
| "char"
| "boolean"
| "double"
| "float"
| "Integer"
| "Long"
| "Short"
| "Byte"
| "Character"
| "Boolean"
| "Double"
| "Float"
| "String"
| "CharSequence"
) && collection_kind(&tag).is_none();
let mut targets: Vec<(String, String)> = if erased {
self.classes
.iter()
.filter(|(_, ci)| !ci.is_interface)
.map(|(k, _)| k.clone())
.filter_map(|k| {
self.resolve_instance_sig(&k, method, ¶m_tys)
.map(|(m, _)| (k, m))
})
.collect()
} else {
Vec::new()
};
targets.sort();
// The last arm: `compareTo`'s typed comparison, or the `String` method.
let fallback = |c: &mut Self| {
if is_compare {
let tag_c = c.b.add_constant(Value::str(tag.clone()));
c.b.emit(Op::LoadConst(tag_c), line);
c.emit_raising_builtin(crate::host::JCOMPARE_TO, 3, line);
} else {
let name_c = c.b.add_constant(Value::str(method.to_string()));
c.b.emit(Op::LoadConst(name_c), line);
// argc counts the receiver, the arguments, and the method name.
c.emit_raising_builtin(crate::host::JSTR_DISPATCH, args.len() as u8 + 2, line);
}
};
// `x.equals(y)` compares *references*, so `y` crosses into a reference
// position and is autoboxed there. Java's answer depends on it:
// `Integer.valueOf(1000).equals(1000L)` is `false` because the argument
// boxes to a `Long`, and a bare `Value::Int` has no class to disagree
// with. Only `equals` gets this — every other erased call reads its
// argument as a number, where a box would be an allocation for nothing.
let box_arg = method == "equals" && args.len() == 1;
// Every other `char` argument boxes to its `Character` too — the
// receiver may be an erased collection (`m.get(k).add(c)`), where the
// element must be the box a typed `add` makes — except for the
// `String`/`StringBuilder` methods that take a `char` as one
// (`replace('a', 'b')`, `append('c')`), which read text, and `remove`,
// where javac widens a `char` to the `remove(int)` index.
let box_char = !matches!(
method,
"replace" | "append" | "insert" | "setCharAt" | "remove"
);
let ref_result = self.lambda_returns_reference(recv, method);
let hints: Vec<Option<Vec<String>>> = (0..args.len())
.map(|i| self.lambda_param_generics(recv, method, args.len(), i))
.collect();
let arities: Vec<Option<usize>> = (0..args.len())
.map(|i| jdk_functional_arity(method, args.len(), i))
.collect();
if targets.is_empty() {
self.expr(recv)?;
for (i, (a, hint)) in args.iter().zip(&hints).enumerate() {
let arity = arities[i];
self.with_ref_arity_hint(a, arity, |c| {
c.with_lambda_param_hint(a, hint.clone(), |c| {
c.emit_erased_arg_hinted(a, raw_args, box_arg, box_char, ref_result)
})
})?;
}
fallback(self);
return Ok(());
}
// Evaluate receiver and arguments once, then branch on the runtime class.
let recv_t = self.temp();
self.expr(recv)?;
self.emit_set(&recv_t, line);
let arg_ts: Vec<String> = args
.iter()
.zip(&hints)
.zip(&arities)
.map(|((a, hint), arity)| {
let t = self.temp();
self.with_ref_arity_hint(a, *arity, |c| {
c.with_lambda_param_hint(a, hint.clone(), |c| {
c.emit_erased_arg_hinted(a, raw_args, box_arg, box_char, ref_result)
})
})?;
self.emit_set(&t, line);
Ok(t)
})
.collect::<Result<_, String>>()?;
let class_t = self.temp();
self.emit_get(&recv_t, line);
self.b.emit(Op::CallBuiltin(crate::host::JCLASSOF, 1), line);
self.emit_set(&class_t, line);
let argc = args.len() as u8 + 1;
let mut end_jumps = Vec::new();
for (class, mangled) in &targets {
self.emit_get(&class_t, line);
let cc = self.b.add_constant(Value::str(class.clone()));
self.b.emit(Op::LoadConst(cc), line);
self.b.emit(Op::StrEq, line);
let skip = self.b.emit(Op::JumpIfFalse(0), line);
self.emit_get(&recv_t, line);
// The receiver's class was unknown when the arguments were lowered,
// so the method's own parameter types convert them here: an `int`
// reaching a `double` parameter widens, as it does on a typed call.
let params = self.instance_param_types(class, method, mangled);
for (i, t) in arg_ts.iter().enumerate() {
self.emit_get(t, line);
if let Some(p) = params
.get(i)
.filter(|p| matches!(p.as_str(), "double" | "float"))
{
let arg_ty = self.expr_java_type(&args[i]);
if arg_ty.as_deref().map(unwrapped_ty) != Some(p.as_str()) {
let c = self.b.add_constant(Value::str(p.clone()));
self.b.emit(Op::LoadConst(c), line);
self.b.emit(Op::CallBuiltin(crate::host::JCAST, 2), line);
}
}
}
let idx = self.b.add_name(mangled);
self.b.emit(Op::Call(idx, argc), line);
self.emit_exc_check(line);
end_jumps.push(self.b.emit(Op::Jump(0), line));
let next = self.b.current_pos();
self.b.patch_jump(skip, next);
}
// Not one of them: a `String`, a boxed primitive, a collection, or a
// closure — all of which the fallback resolves.
self.emit_get(&recv_t, line);
for t in &arg_ts {
self.emit_get(t, line);
}
fallback(self);
let end = self.b.current_pos();
for j in end_jumps {
self.b.patch_jump(j, end);
}
Ok(())
}
/// Lower an erased call's argument, handing a lambda literal the reference
/// result type the JDK method fixes for it when `ref_result` says so.
fn emit_erased_arg_hinted(
&mut self,
a: &Expr,
raw: bool,
boxed: bool,
box_char: bool,
ref_result: bool,
) -> Result<(), String> {
if ref_result && matches!(a, Expr::Lambda { .. } | Expr::MethodRef { .. }) {
self.lambda_ret_hint = Some("Object".to_string());
}
let r = self.emit_erased_arg(a, raw, boxed, box_char);
self.lambda_ret_hint = None;
r
}
/// Whether a lambda passed to `recv.method(…)` returns a *reference* in the
/// JDK's signature for that method. `mapToObj` exists only on the primitive
/// streams and always does; `map` does on a `Stream` (`Function`) and does
/// not on an `IntStream` (`IntUnaryOperator`), where the same `(char) c`
/// body widens to the `int` 97 rather than boxing to `'a'` — so `map` is
/// hinted only when the receiver is recognisably a `Stream`.
///
/// The other JDK methods whose function parameter answers a reference by
/// signature box the same way: `Optional`'s `map`/`flatMap`/`or`/
/// `orElseGet`, `Map`'s `compute*`/`merge`/`replaceAll`, `List.replaceAll`
/// (a `UnaryOperator<E>`), a `Stream`'s `reduce`, and `Stream.iterate`/
/// `generate` named on `Stream` itself (`IntStream`'s take primitive
/// functions). Without it `Optional.of("q").map(s -> s.charAt(0))` held
/// the code point 113 where Java holds the `Character` `q`.
fn lambda_returns_reference(&self, recv: &Expr, method: &str) -> bool {
match method {
"mapToObj" => true,
"map" | "flatMap" => self.stream_is_ref(recv) == Some(true) || self.is_optional(recv),
"or" | "orElseGet" => self.is_optional(recv),
"computeIfAbsent" | "computeIfPresent" | "compute" | "merge" | "replaceAll" => true,
"reduce" => self.stream_is_ref(recv) == Some(true),
"iterate" | "generate" => {
matches!(recv, Expr::Var(c) if c == "Stream" && !self.is_declared_var(c))
}
_ => false,
}
}
/// Whether `e` is recognisably a `java.util.Optional` (not one of the
/// primitive `OptionalInt` family): an `Optional`-typed name, an
/// `Optional.of`/`ofNullable`/`empty`, a reference stream's
/// `findFirst`/`findAny`/`max`/`min`/one-argument `reduce`, or an
/// `Optional`'s own `map`/`filter`/`flatMap`/`or`.
fn is_optional(&self, e: &Expr) -> bool {
if let Some(t) = self.expr_java_type(e) {
if t == "Optional" || t.starts_with("Optional<") {
return true;
}
}
let Expr::MethodCall {
recv, method, args, ..
} = e
else {
return false;
};
match (recv.as_ref(), method.as_str()) {
(Expr::Var(c), "of" | "ofNullable" | "empty") if c == "Optional" => {
!self.is_declared_var(c)
}
(_, "findFirst" | "findAny" | "max" | "min") => self.stream_is_ref(recv) == Some(true),
(_, "reduce") if args.len() == 1 => self.stream_is_ref(recv) == Some(true),
(_, "map" | "filter" | "flatMap" | "or") => self.is_optional(recv),
_ => false,
}
}
/// `Some(true)` for an expression that is a `Stream`, `Some(false)` for an
/// `IntStream`/`LongStream`/`DoubleStream`, and `None` when it is neither
/// recognisably — read off the pipeline's shape, since the static types of
/// stream expressions are not otherwise tracked.
fn stream_is_ref(&self, e: &Expr) -> Option<bool> {
let Expr::MethodCall {
recv, method, args, ..
} = e
else {
let ty = self.expr_java_type(e)?;
return match ty.split('<').next()? {
"Stream" => Some(true),
"IntStream" | "LongStream" | "DoubleStream" => Some(false),
_ => None,
};
};
if let Expr::Var(c) = recv.as_ref() {
if !self.is_declared_var(c) {
match c.as_str() {
"Stream" => return Some(true),
"IntStream" | "LongStream" | "DoubleStream" => return Some(false),
"Arrays" if method == "stream" => {
let ty = self.expr_java_type(args.first()?)?;
return Some(!matches!(ty.as_str(), "int[]" | "long[]" | "double[]"));
}
_ => {}
}
}
}
match method.as_str() {
"stream" | "parallelStream" if args.is_empty() => Some(true),
"mapToObj" | "boxed" => Some(true),
"chars" | "codePoints" | "mapToInt" | "mapToLong" | "mapToDouble" | "asLongStream"
| "asDoubleStream" | "flatMapToInt" | "flatMapToLong" | "flatMapToDouble" => {
Some(false)
}
"filter" | "map" | "sorted" | "distinct" | "limit" | "skip" | "peek" | "parallel"
| "sequential" | "unordered" | "takeWhile" | "dropWhile" | "flatMap" => {
self.stream_is_ref(recv)
}
_ => None,
}
}
/// Lower one argument of an erased instance call.
///
/// `raw` keeps a `char` as its code point (only `compareTo` on a `char`
/// receiver wants that); otherwise a `char` becomes the one-character String
/// the rest of the frontend uses. `boxed` additionally autoboxes a primitive
/// — see the note at [`Compiler::emit_erased_call`]'s `box_arg`.
fn emit_erased_arg(
&mut self,
a: &Expr,
raw: bool,
boxed: bool,
box_char: bool,
) -> Result<(), String> {
if raw {
return self.expr(a);
}
// A `char` argument to `equals` boxes as a `Character` rather than
// becoming the one-character String: `((Object) 'z').equals('z')` is
// `true` in Java, and a String argument would compare against the box's
// code point and answer `false`.
if (boxed || box_char) && self.expr_java_type(a).as_deref() == Some("char") {
self.expr(a)?;
let code = crate::host::box_class_code("Character").expect("`Character` is boxed");
self.b.emit(Op::LoadInt(code), 0);
self.b.emit(Op::CallBuiltin(crate::host::JBOX, 2), 0);
return Ok(());
}
// A `float` that is about to box keeps its number: `Float.equals`
// compares the boxed values, and its `Float.toString` text would
// never equal the receiver's.
if boxed && self.is_float32_expr(a) {
self.expr(a)?;
} else {
self.emit_char_string(a)?;
}
if boxed {
if let Some(code) = self.autobox_code(a) {
self.b.emit(Op::LoadInt(code), 0);
self.b.emit(Op::CallBuiltin(crate::host::JBOX, 2), 0);
}
}
Ok(())
}
/// Lower `super.method(args)` — a **non-virtual** call to the
/// implementation the enclosing class inherits.
///
/// Resolution starts at the *declaring* class's superclass, never at the
/// receiver's runtime class, which is exactly what lets an override call the
/// version it overrides (`String toString() { return "D[" +
/// super.toString() + "]"; }` terminates instead of recursing). The body it
/// selects is the one visible from the superclass, so a grandparent's method
/// is reached when the parent does not declare it.
///
/// Everything *inside* that body still dispatches virtually: a `super.m()`
/// whose body calls an unqualified `n()` reaches the subclass's `n`, because
/// only this one call site is de-virtualized — which is Java's rule.
/// `I.super.method(args)`: `I`'s own (default) body for `method`, run on
/// `this` with no virtual dispatch.
fn interface_super_call(
&mut self,
iface: &str,
method: &str,
args: &[Expr],
line: u32,
) -> Result<(), String> {
if self.this_class.is_none() {
return Err(format!(
"javars: `{iface}.super` used outside an instance method (line {line})"
));
}
let arg_tys: Vec<Option<String>> = self.arg_types(args);
let resolved = self
.resolve_instance_call(iface, method, &arg_tys)
.ok_or_else(|| {
format!(
"javars: interface `{iface}` has no method `{method}` taking {} argument(s) (line {line})",
args.len()
)
})?;
let param_tys = resolved.param_tys;
let packed = Self::effective_args(args, ¶m_tys, resolved.vararg_from);
let (mangled, _) = self
.resolve_instance_sig(iface, method, ¶m_tys)
.ok_or_else(|| {
format!("javars: `{iface}.{method}` has no default body to call (line {line})")
})?;
self.emit_this(line);
self.call_args_targeted(&packed, ¶m_tys)?;
let idx = self.b.add_name(&mangled);
self.b.emit(Op::Call(idx, packed.len() as u8 + 1), line);
self.emit_exc_check(line);
Ok(())
}
fn super_call(&mut self, method: &str, args: &[Expr], line: u32) -> Result<(), String> {
let this_class = self.this_class.clone().ok_or_else(|| {
format!("javars: `super` used outside an instance method (line {line})")
})?;
let arg_tys: Vec<Option<String>> = self.arg_types(args);
if let Some(sup) = self.super_class() {
if let Some(resolved) = self.resolve_instance_call(&sup, method, &arg_tys) {
let param_tys = resolved.param_tys;
let packed = Self::effective_args(args, ¶m_tys, resolved.vararg_from);
let (mangled, _) = self
.resolve_instance_sig(&sup, method, ¶m_tys)
.ok_or_else(|| {
format!(
"javars: `{sup}` declares `{method}` but no superclass of \
`{this_class}` supplies a body for it (line {line})"
)
})?;
self.emit_this(line); // this (deepest)
self.call_args_targeted(&packed, ¶m_tys)?;
let idx = self.b.add_name(&mangled);
self.b.emit(Op::Call(idx, packed.len() as u8 + 1), line);
self.emit_exc_check(line);
return Ok(());
}
}
// No user class up the chain declares it, so Java resolves the call to
// `java.lang.Object`'s own member. `Object` has no Java-level body here
// (see `new_object_as`), and the host supplies exactly the three
// observable ones — reference-identity `equals`, the `Class@hash`
// `toString`, and the identity `hashCode`.
if matches!(
(method, args.len()),
("toString", 0) | ("hashCode", 0) | ("equals", 1) | ("clone", 0)
) {
self.emit_this(line);
for a in args {
self.emit_char_string(a)?;
}
let name_c = self.b.add_constant(Value::str(method.to_string()));
self.b.emit(Op::LoadConst(name_c), line);
self.emit_raising_builtin(crate::host::JSTR_DISPATCH, args.len() as u8 + 2, line);
return Ok(());
}
Err(format!(
"javars: no superclass of `{this_class}` has a method `{method}` taking {} argument(s) (line {line})",
args.len()
))
}
/// Emit `recv.field` read given the receiver value is already on the stack:
/// push the field name and call the field-get builtin.
fn emit_field_get(&mut self, name: &str, line: u32) {
let name_c = self.b.add_constant(Value::str(name.to_string()));
self.b.emit(Op::LoadConst(name_c), line);
self.emit_raising_builtin(crate::host::JFIELD_GET, 2, line);
}
/// Lower `new ClassName(args...)`: allocate the instance, seed its fields
/// (defaults then declared initializers, ancestors first), run the matching
/// constructor, and leave the instance handle on the stack.
fn new_object(
&mut self,
class: &str,
args: &[Expr],
outer: Option<&Expr>,
line: u32,
) -> Result<(), String> {
self.new_object_as(class, class, args, outer, line)
}
/// Lower a construction whose *runtime class* and *constructor* differ.
///
/// They coincide for `new C(…)`; an `enum` constant with a body is the one
/// case they do not — the instance is of the constant's synthetic subclass
/// (so its overrides dispatch) while the constructor that runs is the
/// enum's, because Java gives an anonymous enum subclass none of its own.
fn new_object_as(
&mut self,
class: &str,
ctor_class: &str,
args: &[Expr],
outer: Option<&Expr>,
line: u32,
) -> Result<(), String> {
if outer.is_some() && self.outer_class(ctor_class).is_none() {
return Err(format!(
"javars: `{ctor_class}` is not an inner class, so a qualified `new` names no enclosing instance for it (line {line})"
));
}
if outer.is_none() {
self.check_enclosing_instance(ctor_class, line)?;
}
let args = self.with_captures(ctor_class, args, outer);
let args: &[Expr] = &args;
// `new Integer(5)` and its siblings: the deprecated wrapper constructors
// always allocate, so the result is a fresh box outside the `valueOf`
// cache — `new Integer(5) == new Integer(5)` is `false`. The operand is
// converted exactly as `valueOf` converts it (`new Double("1.5")` parses).
self.emit_class_init(class, line);
if !self.classes.contains_key(class) && args.len() == 1 {
let code = crate::host::box_class_code(class).filter(|_| class != "Character");
if let Some(code) = code {
let value = Expr::MethodCall {
recv: Box::new(Expr::Var(class.to_string())),
method: "valueOf".to_string(),
args: args.to_vec(),
line,
};
self.expr(&value)?;
self.b.emit(Op::LoadInt(code), line);
self.b.emit(Op::LoadInt(1), line);
self.b.emit(Op::CallBuiltin(crate::host::JBOX, 3), line);
return Ok(());
}
}
// `new EnumMap<>(K.class)` / `new EnumMap<>(otherMap)`. An `EnumMap`
// iterates its keys in ordinal order, an enum's natural order, so
// javars models it as the `TreeMap` it behaves as; the class literal
// only names the key type, which the erased map does not need.
if !self.classes.contains_key(class) && class == "EnumMap" {
let rest: Vec<Expr> = args
.iter()
.filter(|a| !matches!(a, Expr::ClassLit(_)))
.cloned()
.collect();
return self.new_object_as("TreeMap", "TreeMap", &rest, None, line);
}
// `new String(cs)` / `new String(s)` / `new String()` — javars models a
// `String` as a primitive value rather than an instance, so constructing
// one is exactly the conversion `String.valueOf` performs.
if !self.classes.contains_key(class) && class == "String" {
// `new String(byte[] [, offset, length] [, charsetName])` decodes
// the bytes; only the static type tells a `byte[]` from the
// `char[]` a code-point array also is.
if args
.first()
.is_some_and(|a| self.expr_java_type(a).as_deref() == Some("byte[]"))
{
for a in args {
self.expr(a)?;
}
let class_c = self.b.add_constant(Value::str("String".to_string()));
self.b.emit(Op::LoadConst(class_c), line);
let method_c = self.b.add_constant(Value::str("#fromBytes".to_string()));
self.b.emit(Op::LoadConst(method_c), line);
self.emit_raising_builtin(
crate::host::JSTATIC_DISPATCH,
args.len() as u8 + 2,
line,
);
self.b
.emit(Op::CallBuiltin(crate::host::JNEW_STRING, 1), line);
return Ok(());
}
// `new String(int[] codePoints, offset, count)` builds from code
// points; the `char[]` overload of the same shape reads `char`s,
// and only the static type tells the two arrays apart.
if args.len() == 3 && self.expr_java_type(&args[0]).as_deref() == Some("int[]") {
for a in args {
self.expr(a)?;
}
let class_c = self.b.add_constant(Value::str("String".to_string()));
self.b.emit(Op::LoadConst(class_c), line);
let method_c = self
.b
.add_constant(Value::str("#fromCodePoints".to_string()));
self.b.emit(Op::LoadConst(method_c), line);
self.emit_raising_builtin(crate::host::JSTATIC_DISPATCH, 5, line);
self.b
.emit(Op::CallBuiltin(crate::host::JNEW_STRING, 1), line);
return Ok(());
}
match args.first() {
// A `char[]` argument is a code-point array; `String.valueOf`
// concatenates its *characters*, so convert element-wise first.
Some(a) => self.emit_char_string(a)?,
None => {
let empty = self.b.add_constant(Value::str(String::new()));
self.b.emit(Op::LoadConst(empty), line);
}
}
// `new String(chars, offset, count)` is `String.valueOf` with the
// same three arguments.
if args.len() == 3 {
self.expr(&args[1])?;
self.expr(&args[2])?;
}
let class_c = self.b.add_constant(Value::str("String".to_string()));
self.b.emit(Op::LoadConst(class_c), line);
let method_c = self.b.add_constant(Value::str("valueOf".to_string()));
self.b.emit(Op::LoadConst(method_c), line);
self.emit_raising_builtin(
crate::host::JSTATIC_DISPATCH,
if args.len() == 3 { 5 } else { 3 },
line,
);
// `new String(…)` is specified to produce a *fresh* object, which is
// the only reason the expression is ever written — so the text gets
// an identity of its own here. Without it `new String("ab") == "ab"`
// was `true`, javars's `String` being a value with nothing to
// distinguish.
self.b
.emit(Op::CallBuiltin(crate::host::JNEW_STRING, 1), line);
return Ok(());
}
// `new Object()` — the fieldless root instance programs use as a lock or
// a sentinel. `Object` is deliberately *not* in the class table (it is
// also the erasure of every type variable, and a receiver statically
// typed `Object` has to keep dispatching dynamically), so the allocation
// is emitted here directly: a `HostObj::Instance` with no fields and no
// constructor, which the heap already gives a distinct identity.
if !self.classes.contains_key(class) && class == "Object" {
if !args.is_empty() {
return Err(format!(
"javars: `Object` has only a no-argument constructor (line {line})"
));
}
let class_c = self.b.add_constant(Value::str("Object".to_string()));
self.b.emit(Op::LoadConst(class_c), line);
self.b.emit(Op::CallBuiltin(crate::host::JNEW, 1), line);
return Ok(());
}
// `new StringBuilder(…)` / `new StringBuffer(…)` — a host shape, like a
// collection. A user class of the same name wins, for the same reason
// and by the same ordering.
if !self.classes.contains_key(class) && matches!(class, "StringBuilder" | "StringBuffer") {
if args.len() > 1 {
return Err(format!(
"javars: `new {class}(…)` takes no argument, a capacity, or an \
initial string (line {line})"
));
}
let kind_c = self.b.add_constant(Value::str(class.to_string()));
self.b.emit(Op::LoadConst(kind_c), line);
match args.first() {
// `new StringBuilder('x')` is not a Java constructor, but the
// conversion is what makes `new StringBuilder(aCharSequence)`
// and a `float` argument reach the host as text.
Some(a) => self.emit_char_string(a)?,
// `StringBuilder()` is `StringBuilder(16)` — the JDK's own
// definition, and the spelling that keeps `Undef` free to mean
// the `(String) null` argument, which is an NPE rather than an
// empty builder.
None => {
self.b
.emit(Op::LoadInt(crate::host::SB_DEFAULT_CAP as i64), line);
}
}
self.emit_raising_builtin(crate::host::JSB_NEW, 2, line);
return Ok(());
}
// `new Scanner(System.in)`, `new BufferedReader(new
// InputStreamReader(System.in))`, `new StringTokenizer(line)` — the
// input classes are host shapes (see `crate::jio`), built by the
// `#new` static their class answers to.
if !self.classes.contains_key(class)
&& (is_input_class(class) || is_host_value_class(class))
{
let new_call = Expr::MethodCall {
recv: Box::new(Expr::Var(class.to_string())),
method: "#new".to_string(),
args: args.to_vec(),
line,
};
return self.expr(&new_call);
}
// `new PriorityQueue<>(…)` — every JDK overload but the `SortedSet` one:
// `()`, `(int)`, `(Comparator)`, `(int, Comparator)`, `(Collection)`.
// The host tells them apart by runtime shape; the natural-order
// comparator rides along for the ones that name none, so an element's
// own `compareTo` orders the heap exactly as `Comparable` does.
if !self.classes.contains_key(class) && class == "PriorityQueue" {
if args.len() > 2 {
return Err(format!(
"javars: `new PriorityQueue<>(…)` takes at most two arguments (line {line})"
));
}
let kind_c = self.b.add_constant(Value::str(class.to_string()));
self.b.emit(Op::LoadConst(kind_c), line);
for i in 0..2 {
match args.get(i) {
Some(a) => self.expr(a)?,
None => {
self.b.emit(Op::LoadUndef, line);
}
}
}
self.expr(&natural_order_comparator(line))?;
self.emit_raising_builtin(crate::host::JCOLL_NEW, 4, line);
return Ok(());
}
// `new ArrayList<>()` / `new HashMap<>(other)` — a `java.util`
// collection, allocated by the host rather than laid out as an instance.
// A user class of the same name wins, because `self.classes` is checked
// by the branch below only after this one declines.
// `new LinkedHashMap<>(capacity, loadFactor, accessOrder)` — the access
// order is a property of the object, so only a literal flag is modeled.
if !self.classes.contains_key(class) && class == "LinkedHashMap" && args.len() == 3 {
let kind = match &args[2] {
Expr::Bool(true) => "LinkedHashMap$access",
Expr::Bool(false) => "LinkedHashMap",
_ => {
return Err(format!(
"javars: `new LinkedHashMap<>(…, accessOrder)` needs a `true`/`false` literal for `accessOrder` (line {line})"
))
}
};
let kind_c = self.b.add_constant(Value::str(kind.to_string()));
self.b.emit(Op::LoadConst(kind_c), line);
self.b.emit(Op::LoadUndef, line);
self.emit_raising_builtin(crate::host::JCOLL_NEW, 2, line);
return Ok(());
}
if !self.classes.contains_key(class) && is_concrete_collection(class) {
if args.len() > 1 {
return Err(format!(
"javars: `new {class}(…)` takes no argument or one collection (line {line})"
));
}
let kind_c = self.b.add_constant(Value::str(class.to_string()));
self.b.emit(Op::LoadConst(kind_c), line);
match args.first() {
// `new ArrayList<>(other)` copies; `new HashMap<>(64)` is an
// initial capacity, which the host turns into the table a hash
// container starts with (it decides the iteration order) and
// into the JDK's refusal of a negative one.
Some(a) => self.expr(a)?,
None => {
self.b.emit(Op::LoadUndef, line);
}
}
self.emit_raising_builtin(crate::host::JCOLL_NEW, 2, line);
return Ok(());
}
let info = self
.classes
.get(class)
.ok_or_else(|| format!("javars: unknown class `{class}` (line {line})"))?;
if info.is_interface {
return Err(format!(
"javars: `{class}` is an interface and cannot be instantiated (line {line})"
));
}
// Constructor resolution up front (immutable borrow released before we
// emit anything mutating `self`). The chosen overload's parameter types
// mangle the `<init>` target.
let ctor_info = self
.classes
.get(ctor_class)
.ok_or_else(|| format!("javars: unknown class `{ctor_class}` (line {line})"))?;
let has_any_ctor = !ctor_info.ctors.is_empty();
let ctor_arities: Vec<usize> = ctor_info.ctors.iter().map(|c| c.param_tys.len()).collect();
let info = &self.classes[class];
// Field-init plan (storage key, type, optional init expr), cloned so the
// ChunkBuilder borrow does not alias `self.classes`.
let field_plan: Vec<(String, String, Option<Expr>)> = info
.fields
.iter()
.map(|f| (f.key.clone(), f.ty.clone(), f.init.clone()))
.collect();
// Allocate: push class name, call JNEW → instance handle.
let class_c = self.b.add_constant(Value::str(class.to_string()));
self.b.emit(Op::LoadConst(class_c), line);
self.b.emit(Op::CallBuiltin(crate::host::JNEW, 1), line);
let obj = self.temp();
self.emit_set(&obj, line);
// Seed each field: default value, then its declared initializer if any.
for (fname, fty, finit) in &field_plan {
self.emit_get(&obj, line);
let name_c = self.b.add_constant(Value::str(fname.clone()));
self.b.emit(Op::LoadConst(name_c), line);
match finit {
Some(e) => self.expr_targeted(e, Some(fty))?,
None => self.emit_type_default(fty, line),
}
self.emit_raising_builtin(crate::host::JFIELD_SET, 3, line);
self.b.emit(Op::Pop, line);
}
// The instance initializers are NOT run here. JLS 12.5 places them
// between the superclass constructor and the constructor body, so each
// level's `<instinit>` is emitted inside that level's constructor; a
// class that declares none has its default constructor synthesized
// below.
// Run the constructor (resolving the overload by argument type). A class
// with no declared ctor accepts only `new C()`.
let arg_tys: Vec<Option<String>> = self.arg_types(args);
let ctor_sig = self.resolve_ctor(ctor_class, &arg_tys);
if let Some((param_tys, vararg_from)) = ctor_sig {
let args = Self::effective_args(args, ¶m_tys, vararg_from);
self.emit_get(&obj, line); // this
let mangled = mangle(ctor_class, "<init>", ¶m_tys);
self.call_args_generic(&args, ¶m_tys, &mangled)?;
let name_idx = self.b.add_name(&mangled);
self.b.emit(Op::Call(name_idx, args.len() as u8 + 1), line);
self.emit_exc_check(line);
self.b.emit(Op::Pop, line); // discard the ctor's (Undef) result
} else if has_any_ctor || !args.is_empty() {
return Err(format!(
"javars: class `{ctor_class}` has no constructor taking {} argument(s) (declared arities: {:?}) (line {line})",
args.len(),
ctor_arities
));
} else {
// The class declares no constructor, so Java gave it a default one:
// `super()` followed by its instance initializers. There is no
// subroutine to call for it, so its body is emitted here.
self.emit_default_ctor(ctor_class, Recv::Temp(&obj), line, 0);
}
// An enum constant's body is an anonymous subclass whose implicit
// constructor is `super(args)` followed by its own instance
// initializers (JLS 15.9.5.1) — the enum's constructor ran above, so
// the body's field initializers and `{ … }` blocks run now.
if class != ctor_class {
self.emit_inst_init(class, Recv::Temp(&obj), line);
}
// The expression value is the new instance.
self.emit_get(&obj, line);
Ok(())
}
/// Lower `a[i] <op>= v`. A plain assignment writes directly; a compound one
/// reads the element, applies the operator, and writes it back — evaluating
/// the array and index once (into temps) so their side effects don't repeat.
fn index_assign(
&mut self,
array: &Expr,
index: &Expr,
op: AssignOp,
value: &Expr,
line: u32,
) -> Result<(), String> {
// The element's declared type decides the assignment conversion, the
// compound-`/` truncation, and the 32-bit wrap.
if op != AssignOp::Assign {
return self.index_update(array, index, op, value, Yield::Nothing, line);
}
let elem_ty = self
.expr_array_type(array)
.and_then(|t| t.strip_suffix("[]").map(str::to_string));
self.expr(array)?;
self.expr_unboxed(index)?;
self.expr_targeted(value, elem_ty.as_deref())?;
self.emit_raising_builtin(crate::host::JARRAY_SET, 3, line);
self.b.emit(Op::Pop, line);
Ok(())
}
/// Read/modify/write of `a[i]` under a compound operator, leaving `want` on
/// the stack — nothing for `a[i] += 1`, the old element for `a[i]++`, the
/// new one for `++a[i]`. The array and index expressions are evaluated once
/// into temps, so `a[i++]++` steps `i` a single time.
fn index_update(
&mut self,
array: &Expr,
index: &Expr,
op: AssignOp,
value: &Expr,
want: Yield,
line: u32,
) -> Result<(), String> {
let elem_ty = self
.expr_array_type(array)
.and_then(|t| t.strip_suffix("[]").map(str::to_string));
let arr_t = self.temp();
let idx_t = self.temp();
self.expr(array)?;
self.emit_set(&arr_t, line);
self.expr_unboxed(index)?;
self.emit_set(&idx_t, line);
// old element
self.emit_get(&arr_t, line);
self.emit_get(&idx_t, line);
self.emit_raising_builtin(crate::host::JARRAY_GET, 2, line);
let old_t = self.stash_if(want == Yield::Old, line);
self.emit_compound_update(op, value, elem_ty.as_deref(), line)?;
let new_t = self.temp();
self.emit_set(&new_t, line);
// write back
self.emit_get(&arr_t, line);
self.emit_get(&idx_t, line);
self.emit_get(&new_t, line);
self.emit_raising_builtin(crate::host::JARRAY_SET, 3, line);
self.b.emit(Op::Pop, line);
match (want, old_t) {
(Yield::Old, Some(t)) => self.emit_get(&t, line),
(Yield::New, _) => self.emit_get(&new_t, line),
_ => {}
}
Ok(())
}
/// Lower `recv.field <op>= v` (and implicit `this.field`). Plain assignment
/// writes directly; a compound one reads the field, applies the operator, and
/// writes it back — evaluating the receiver once (into a temp).
fn field_assign(
&mut self,
recv: &Expr,
name: &str,
op: AssignOp,
value: &Expr,
line: u32,
) -> Result<(), String> {
if op != AssignOp::Assign {
return self.field_update(recv, name, op, value, Yield::Nothing, line);
}
// `T.n = …` (or a bare `n` naming a static) writes the class's shared
// cell, not a field of an object.
if let Some((class, ty)) = self.static_target(recv, name) {
return self.static_assign(&class, &ty, name, op, value, line);
}
let field_ty_name = self.field_type_name(recv, name);
let key = self.field_key(recv, name);
let generic = self.expr_generic(&Expr::Field {
recv: Box::new(recv.clone()),
name: name.to_string(),
});
self.expr(recv)?;
let name_c = self.b.add_constant(Value::str(key.clone()));
self.b.emit(Op::LoadConst(name_c), line);
self.target_wildcard = Some(self.field_wildcard(recv, name));
self.expr_targeted_generic(value, field_ty_name.as_deref(), generic)?;
self.emit_raising_builtin(crate::host::JFIELD_SET, 3, line);
self.b.emit(Op::Pop, line);
Ok(())
}
/// Read/modify/write of `recv.field` under a compound operator, leaving
/// `want` on the stack — nothing for `p.n += 1`, the old value for `p.n++`,
/// the new one for `++p.n`. The receiver is evaluated once, into a temp.
fn field_update(
&mut self,
recv: &Expr,
name: &str,
op: AssignOp,
value: &Expr,
want: Yield,
line: u32,
) -> Result<(), String> {
if let Some((class, ty)) = self.static_target(recv, name) {
self.emit_static_field_init(&class, name, line);
return self.static_update(&static_global(&class, name), &ty, op, value, want, line);
}
// The field's declared type drives both the compound-`/` truncation and
// the 32-bit wrap, so it is resolved here rather than at each call site.
let field_ty_name = self.field_type_name(recv, name);
let key = self.field_key(recv, name);
let obj_t = self.temp();
self.expr(recv)?;
self.emit_set(&obj_t, line);
// old field value
self.emit_get(&obj_t, line);
self.emit_field_get(&key, line);
let old_t = self.stash_if(want == Yield::Old, line);
self.emit_compound_update(op, value, field_ty_name.as_deref(), line)?;
let new_t = self.temp();
self.emit_set(&new_t, line);
// write back
self.emit_get(&obj_t, line);
let name_c = self.b.add_constant(Value::str(key.clone()));
self.b.emit(Op::LoadConst(name_c), line);
self.emit_get(&new_t, line);
self.emit_raising_builtin(crate::host::JFIELD_SET, 3, line);
self.b.emit(Op::Pop, line);
match (want, old_t) {
(Yield::Old, Some(t)) => self.emit_get(&t, line),
(Yield::New, _) => self.emit_get(&new_t, line),
_ => {}
}
Ok(())
}
/// Apply compound operator `op` with `value` to the target value already on
/// the stack, whose declared type is `ty`, leaving the value to store. The
/// operator runs at the target's primitive type with the implicit narrowing
/// cast (JLS 15.26.2); a wrapper target is unboxed first — a `null` one
/// throws — and the result reboxed, as `x = Integer.valueOf(x + v)` would.
fn emit_compound_update(
&mut self,
op: AssignOp,
value: &Expr,
ty: Option<&str>,
line: u32,
) -> Result<(), String> {
let prim = ty.map(unwrapped_ty);
if let Some(t) = ty {
self.emit_checked_unbox(t);
}
let target = prim.and_then(numtype_of_ty).unwrap_or(NumType::Other);
let wrap = self.compound_wraps(prim, value);
self.emit_compound(op, value, target, prim, wrap, line)?;
self.emit_narrow_to(prim, line);
if let Some(t) = ty {
self.emit_rebox(t);
}
Ok(())
}
/// Push the right operand of a compound assignment. Into a primitive
/// target the operator runs on primitives (JLS 15.26.2 applies the
/// operator's numeric promotion, which unboxes), so a wrapper operand is
/// unboxed through [`Self::emit_checked_unbox`] and a `null` one throws
/// `NullPointerException` — `int w = 0; Integer n = null; w += n;`. A
/// reference target (`String +=`) takes the operand as it is.
fn compound_operand(&mut self, value: &Expr, target_ty: Option<&str>) -> Result<(), String> {
if target_ty.is_some_and(|t| !is_reference_type(t)) {
self.expr_unboxed(value)
} else {
self.expr(value)
}
}
/// Combine an already-pushed left operand with `value` under a compound
/// operator, leaving the result on the stack. `/=` truncates when both the
/// target and the value are statically integral (Java `int /= int`).
fn emit_compound(
&mut self,
op: AssignOp,
value: &Expr,
target: NumType,
target_ty: Option<&str>,
wrap32: bool,
line: u32,
) -> Result<(), String> {
// `javac`'s refusals of a `String` in a compound assignment: only `+=`
// takes one, and then only into a `String` (or reference) target.
let value_string = self.expr_java_type(value).as_deref() == Some("String");
if target_ty == Some("String") || value_string {
let primitive_target = target_ty.is_some_and(|t| !is_reference_type(t));
let sym = match op {
AssignOp::Add if value_string && primitive_target => {
return Err(string_to_primitive(target_ty.unwrap_or_default()));
}
AssignOp::Sub => "-",
AssignOp::Mul => "*",
AssignOp::Div => "/",
AssignOp::Mod => "%",
AssignOp::Shl => "<<",
AssignOp::Shr => ">>",
AssignOp::Ushr => ">>>",
_ => "",
};
if !sym.is_empty() {
return Err(format!(
"javars: bad operand types for binary operator '{sym}'"
));
}
}
// `float f; f *= x;` is one 32-bit operation, not a 64-bit one narrowed
// afterwards — the same reason the binary path routes through the host.
// A `double` operand makes the operation a `double` one (JLS 5.6.2), which
// is rounded to `float` only by the implicit cast afterwards.
let via_double = target_ty == Some("float")
&& self.expr_java_type(value).as_deref().map(unwrapped_ty) == Some("double");
if target_ty == Some("float") && !via_double {
if let Some(bop) = compound_binop(op) {
self.compound_operand(value, target_ty)?;
self.emit_f32_arith(bop, line);
return Ok(());
}
}
// `long x; x += f;` with a `float` operand is a `float` operation
// (JLS 5.6.2: the promoted type is `float`, not `double`), narrowed back
// by the cast below — the same reason a `float` target runs at 32 bits.
if matches!(target_ty, Some("int" | "long" | "short" | "byte" | "char"))
&& self.expr_java_type(value).as_deref().map(unwrapped_ty) == Some("float")
{
if let Some(bop) = compound_binop(op).filter(|b| {
matches!(
b,
BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Mod
)
}) {
self.compound_operand(value, target_ty)?;
self.emit_f32_arith(bop, line);
if let Some(t) = target_ty {
let c = self.b.add_constant(Value::str(t.to_string()));
self.b.emit(Op::LoadConst(c), line);
self.b.emit(Op::CallBuiltin(crate::host::JCAST, 2), line);
}
return Ok(());
}
}
if matches!(op, AssignOp::Shl | AssignOp::Shr | AssignOp::Ushr) {
// Same width rule as the binary shifts (JLS 15.19): the left operand
// is promoted to `int` or stays `long`, the distance is masked to
// *that* width, and `>>>` zero-fills at it. A `byte`/`short`/`char`
// target shifts as the `int` it promotes to and is narrowed after.
let wide = !matches!(target_ty, Some("int" | "short" | "byte" | "char"));
self.compound_operand(value, target_ty)?;
self.b.emit(Op::LoadInt(if wide { 63 } else { 31 }), line);
self.b.emit(Op::BitAnd, line);
match op {
AssignOp::Shl => self.b.emit(Op::Shl, line),
AssignOp::Shr => self.b.emit(Op::Shr, line),
_ => {
self.b.emit(Op::LoadInt(if wide { 64 } else { 32 }), line);
self.b.emit(Op::CallBuiltin(crate::host::JUSHR, 3), line)
}
};
} else if matches!(op, AssignOp::BitAnd | AssignOp::BitOr | AssignOp::BitXor)
&& self.expr_type(value) != NumType::Int
{
// `b &= c` on booleans is the logical form, and its result must
// stay a boolean rather than the 0/1 an integer op would leave.
self.compound_operand(value, target_ty)?;
let vop = match op {
AssignOp::BitAnd => Op::LogAnd,
AssignOp::BitOr => Op::LogOr,
_ => Op::NumNe,
};
self.b.emit(vop, line);
} else if op == AssignOp::Div {
let r = self.expr_type(value);
self.compound_operand(value, target_ty)?;
// `wrap32` is exactly "the target is a declared `int` and the
// operand is `int`-width", which is the condition under which the
// native float division is exact; a `long /=` must not take it.
self.emit_div(target, r, value, wrap32, line);
} else {
// `s += x` on a String target is concatenation, so the operand takes
// Java's string conversion; a numeric target makes it arithmetic,
// which is what keeps `int n = 0; n += c;` adding code points.
if op == AssignOp::Add && target == NumType::Other {
self.emit_stringified(value)?;
} else {
self.compound_operand(value, target_ty)?;
}
// `x %= 0` throws the same `ArithmeticException` as `x / 0`.
if op == AssignOp::Mod
&& target == NumType::Int
&& self.expr_type(value) == NumType::Int
{
self.emit_zero_divisor_check(value, line);
}
self.b.emit(compound_op(op), line);
}
// JLS 15.26.2: `E1 op= E2` is `E1 = (T)(E1 op E2)` — an implicit *cast*
// to the left-hand type, not merely a width mask. When `T` is integral
// and `E2` promotes the arithmetic to floating point, that cast is the
// narrowing one, so `int x = 1; x += 1.5;` is 2 and not 2.5. It is the
// same conversion `(int) expr` performs, including its saturation at the
// target's range, so it routes through the same host builtin.
if let Some(t) = target_ty.filter(|t| self.compound_narrows_float(op, t, value)) {
let c = self.b.add_constant(Value::str(t.to_string()));
self.b.emit(Op::LoadConst(c), line);
self.b.emit(Op::CallBuiltin(crate::host::JCAST, 2), line);
}
if via_double {
self.b.emit(Op::CallBuiltin(crate::host::JF32, 1), line);
}
// An `int` target is an `int` whatever the right-hand side's width: the
// implicit cast of JLS 15.26.2 wraps a `long` operation back to 32 bits.
if wrap32 || target_ty == Some("int") {
self.emit_wrap32(line);
}
Ok(())
}
/// True when `target <op>= value` needs the narrowing cast back to an
/// integral `target` because `value` makes the promoted arithmetic floating
/// point. The shift and bitwise operators are excluded: `javac` rejects a
/// floating operand for them outright, so no valid program reaches this.
fn compound_narrows_float(&self, op: AssignOp, target: &str, value: &Expr) -> bool {
matches!(target, "int" | "long" | "short" | "byte" | "char")
&& matches!(
op,
AssignOp::Add | AssignOp::Sub | AssignOp::Mul | AssignOp::Div | AssignOp::Mod
)
&& matches!(
self.expr_java_type(value).as_deref(),
Some("float" | "double")
)
}
/// Lower a bare-identifier call `name(args...)`. Slice 1 declares no user
/// methods, so the only calls that resolve are the inline-Rust FFI ones:
///
/// - `__rust_compile("<base64>", line)` — the desugar target of a
/// `rust { ... }` block. Compile the base64 body and register its exports
/// via the `JFFI_COMPILE` builtin; the call evaluates to `null`.
/// - any other name, **when a `rust { ... }` block is present** — an export
/// registered at runtime, dispatched by name through the `JFFI_CALL`
/// builtin (args pushed deepest-first, then the name on top).
///
/// With no FFI block in the program, an unknown name stays a compile-time
/// "unresolved reference" error — javars's existing diagnostic is preserved.
/// Every branch leaves exactly one value on the stack (the builtin's return,
/// or the error path never emits).
fn call(&mut self, name: &str, args: &[Expr], line: u32) -> Result<(), String> {
if name == RUST_COMPILE {
// Compile only the base64 body (first arg); the line arg is metadata
// the builtin does not need.
if let Some(body) = args.first() {
self.expr(body)?;
self.b
.emit(Op::CallBuiltin(crate::host::JFFI_COMPILE, 1), line);
} else {
self.b.emit(Op::LoadUndef, line);
}
return Ok(());
}
// `super(args)` — chain to the superclass constructor. Field defaults
// (including inherited ones) are already seeded by `new_object`, so this
// just runs the parent constructor on the same `this`; that parent runs
// its own instance initializers.
if name == "super" {
if let Some(this_class) = self.this_class.clone() {
if let Some(sup) = self
.classes
.get(&this_class)
.and_then(|ci| ci.superclass.clone())
{
let this0 = Expr::Var(OUTER_THIS.to_string());
let args = self.with_captures(&sup, args, Some(&this0));
let args: &[Expr] = &args;
let arg_tys: Vec<Option<String>> = self.arg_types(args);
if let Some((param_tys, vararg_from)) = self.resolve_ctor(&sup, &arg_tys) {
let args = Self::effective_args(args, ¶m_tys, vararg_from);
self.emit_this(line); // this
self.call_args_targeted(&args, ¶m_tys)?;
let mangled = mangle(&sup, "<init>", ¶m_tys);
let idx = self.b.add_name(&mangled);
self.b.emit(Op::Call(idx, args.len() as u8 + 1), line);
self.emit_exc_check(line);
return Ok(());
}
// An explicit `super()` naming a superclass that declares no
// constructor: it names the default one, which has no
// subroutine, so its body is synthesized here. Emitting
// nothing would drop that level's instance initializers.
if args.is_empty()
&& self.classes.get(&sup).is_some_and(|ci| ci.ctors.is_empty())
{
self.emit_default_ctor(&sup, Recv::This, line, 0);
self.b.emit(Op::LoadUndef, line);
return Ok(());
}
}
}
// No user-class superclass constructor for this arity — a no-op that
// still leaves a (discarded) value for statement position.
self.b.emit(Op::LoadUndef, line);
return Ok(());
}
// `this(args)` — delegate to another constructor of the same class on the
// same `this` (JLS 8.8.7.1). The delegate runs the `super()` chain, so
// the delegating constructor emits none of its own (see
// `Compiler::chains_explicitly`).
if name == "this" {
if let Some(this_class) = self.this_class.clone() {
let this0 = Expr::Var(OUTER_THIS.to_string());
let args = self.with_captures(&this_class, args, Some(&this0));
let args: &[Expr] = &args;
let arg_tys: Vec<Option<String>> = self.arg_types(args);
let (param_tys, vararg_from) =
self.resolve_ctor(&this_class, &arg_tys).ok_or_else(|| {
format!(
"javars: class `{this_class}` has no constructor taking {} argument(s) (line {line})",
args.len()
)
})?;
let args = Self::effective_args(args, ¶m_tys, vararg_from);
self.emit_this(line);
self.call_args_targeted(&args, ¶m_tys)?;
let mangled = mangle(&this_class, "<init>", ¶m_tys);
let idx = self.b.add_name(&mangled);
self.b.emit(Op::Call(idx, args.len() as u8 + 1), line);
self.emit_exc_check(line);
return Ok(());
}
self.b.emit(Op::LoadUndef, line);
return Ok(());
}
// A user-defined static method resolves to the native call-frame ABI,
// choosing the overload that matches the argument types.
if self.methods.contains_key(name) {
let arg_tys: Vec<Option<String>> = self.arg_types(args);
let resolved = self.resolve_static_call(name, &arg_tys).ok_or_else(|| {
let sigs: Vec<(&[String], bool)> = self.methods[name]
.iter()
.map(|s| (s.param_tys.as_slice(), s.varargs))
.collect();
if self.overload_ambiguous(&sigs, &arg_tys) {
format!("javars: reference to {name} is ambiguous (line {line})")
} else {
format!(
"javars: no `{name}` overload matches {} argument(s) (line {line})",
args.len()
)
}
})?;
let args = Self::effective_args(args, &resolved.param_tys, resolved.vararg_from);
self.call_args_generic(&args, &resolved.param_tys, &resolved.mangled)?;
self.emit_class_init(&resolved.owner, line);
let name_idx = self.b.add_name(&resolved.mangled);
self.b.emit(Op::Call(name_idx, args.len() as u8), line);
self.emit_exc_check(line);
return Ok(());
}
// A bare call inside an instance method/ctor that names an instance
// method of `this` is an implicit `this.name(args)` — dispatched
// virtually on `this`'s runtime class.
if let Some(this_class) = self.this_class.clone() {
if self.has_instance_method(&this_class, name, args.len()) {
return self.dispatch_instance_method(&Expr::This, &this_class, name, args, line);
}
// The `java.lang.Object` methods every class inherits are not in the
// class table (they have no Java-level body here), so the check above
// cannot see them — yet an unqualified `getClass()` inside an
// instance member is an implicit `this.getClass()` exactly like a
// declared method is. Without this a `toString()` override written
// the ordinary way — `getClass().getSimpleName() + …` — failed to
// compile at all.
// `hashCode` is left out on purpose, matching the qualified
// `x.hashCode()` path: a class that does not declare one has no
// answer javars can give that is not silently wrong (see the
// `hashCode` entry in BUGS.md), so it stays a compile error rather
// than becoming an identity hash.
if matches!(
(name, args.len()),
("getClass", 0) | ("toString", 0) | ("equals", 1)
) {
return self.expr(&Expr::MethodCall {
recv: Box::new(Expr::This),
method: name.to_string(),
args: args.to_vec(),
line,
});
}
// An inner class calling a method of an enclosing instance.
if let Some(recv) = self.outer_method_recv(name) {
return self.expr(&Expr::MethodCall {
recv: Box::new(recv),
method: name.to_string(),
args: args.to_vec(),
line,
});
}
}
if self.has_ffi {
for a in args {
self.expr(a)?;
}
let c = self.b.add_constant(Value::str(name.to_string()));
self.b.emit(Op::LoadConst(c), line);
self.b.emit(
Op::CallBuiltin(crate::host::JFFI_CALL, args.len() as u8 + 1),
line,
);
return Ok(());
}
Err(format!(
"javars: unresolved reference: {name} (line {line})"
))
}
/// Lower `cond ? then : els`. Evaluates `cond`, jumps to the `els` branch
/// when false, and leaves exactly one branch's value on the stack.
/// Whether a conditional is a *numeric* (or boolean) conditional that
/// converts its operands (JLS 15.25): both are primitives or wrappers of
/// one, and they are not the very same wrapper type. Its operands then
/// unbox, so `flag ? integerOrNull : 0` throws on a `null` `Integer`
/// where a reference conditional would pass it through.
fn ternary_unboxes(&self, then: &Expr, els: &Expr) -> bool {
let (Some(t), Some(e)) = (self.expr_java_type(then), self.expr_java_type(els)) else {
return false;
};
let convertible =
|ty: &str| numeric_rank(ty).is_some() || matches!(ty, "boolean" | "Boolean");
let primitive = |ty: &str| !is_reference_type(ty);
convertible(&t) && convertible(&e) && (primitive(&t) || primitive(&e) || t != e)
}
/// The unboxing conversion for a branch of a numeric conditional.
fn emit_checked_unbox_of(&mut self, e: &Expr) {
if let Some(t) = self.expr_java_type(e) {
self.emit_checked_unbox(&t);
}
}
fn ternary(&mut self, cond: &Expr, then: &Expr, els: &Expr) -> Result<(), String> {
// A floating conditional widens whichever branch is integral, so
// `flag ? 1 : 2.0` yields 1.0 rather than 1 (JLS 15.25).
let promote = self.ternary_promotion(then, els);
let unbox = self.ternary_unboxes(then, els);
// A `char` beside a non-numeric reference (`o == null ? "null" : s.charAt(0)`)
// makes a reference conditional, so the `char` is boxed to a `Character`
// rather than left the code point it is as a primitive.
let char_vs_reference = |a: &Expr, b: &Expr| {
self.expr_java_type(a).as_deref() == Some("char")
&& self.expr_java_type(b).is_some_and(|t| {
is_reference_type(&t)
&& numeric_rank(&t).is_none()
&& t != "null"
&& t != "Boolean"
})
};
let box_then = char_vs_reference(then, els);
let box_els = char_vs_reference(els, then);
let (promote_then, promote_els) = (
if box_then { Some("Object") } else { promote },
if box_els { Some("Object") } else { promote },
);
self.expr_unboxed(cond)?;
let jf = self.b.emit(Op::JumpIfFalse(0), 0);
self.expr_targeted(then, promote_then)?;
if unbox {
self.emit_checked_unbox_of(then);
}
let jend = self.b.emit(Op::Jump(0), 0);
let else_start = self.b.current_pos();
self.b.patch_jump(jf, else_start);
self.expr_targeted(els, promote_els)?;
if unbox {
self.emit_checked_unbox_of(els);
}
let end = self.b.current_pos();
self.b.patch_jump(jend, end);
Ok(())
}
/// Lower an array literal, each element lowered as an assignment into a slot
/// of the array's element type — which is what widens a `double[]`
/// literal's integral elements and boxes a `char` into an `Object[]`.
/// `elem_ty` is `None` for a bare `{…}` in a position javars cannot type,
/// in which case the elements lower untargeted.
fn array_lit(&mut self, elems: &[Expr], elem_ty: Option<&str>) -> Result<(), String> {
for (i, span) in array_build_chunks(elems.len()).into_iter().enumerate() {
let len = span.len();
for el in &elems[span] {
self.expr_targeted(el, elem_ty)?;
}
self.b.emit(array_build_op(i, len), 0);
}
if let Some(t) = elem_ty {
self.emit_array_tag(&format!("{t}[]"), 0);
}
Ok(())
}
/// `javac`'s operand check for a statically-`String` operand: `+` is the
/// one operator a `String` takes, besides `==`/`!=` against another
/// reference. Without it `"b" - 1` ran (it once answered 97, the host
/// reading a one-character String as a `char`) where `javac` refuses the
/// program.
fn check_string_operands(&self, op: BinOp, lhs: &Expr, rhs: &Expr) -> Result<(), String> {
if op == BinOp::Add {
return Ok(());
}
let ty = |e: &Expr| self.expr_java_type(e);
let (l, r) = (ty(lhs), ty(rhs));
let is_string = |t: &Option<String>| t.as_deref() == Some("String");
if !is_string(&l) && !is_string(&r) {
return Ok(());
}
let primitive = |t: &Option<String>| t.as_deref().is_some_and(|t| !is_reference_type(t));
let bad = match op {
BinOp::Eq | BinOp::Ne => primitive(&l) || primitive(&r),
_ => true,
};
if bad {
return Err(format!(
"javars: bad operand types for binary operator '{}'",
binop_symbol(op)
));
}
Ok(())
}
fn binary(&mut self, op: BinOp, lhs: &Expr, rhs: &Expr) -> Result<(), String> {
self.check_string_operands(op, lhs, rhs)?;
// `&&` / `||` short-circuit: keep the deciding operand as the result.
match op {
BinOp::And => {
self.expr_unboxed(lhs)?;
let jf = self.b.emit(Op::JumpIfFalseKeep(0), 0);
self.b.emit(Op::Pop, 0);
self.expr_unboxed(rhs)?;
let end = self.b.current_pos();
self.b.patch_jump(jf, end);
return Ok(());
}
BinOp::Or => {
self.expr_unboxed(lhs)?;
let jt = self.b.emit(Op::JumpIfTrueKeep(0), 0);
self.b.emit(Op::Pop, 0);
self.expr_unboxed(rhs)?;
let end = self.b.current_pos();
self.b.patch_jump(jt, end);
return Ok(());
}
_ => {}
}
// Shifts and the bitwise trio need Java's operand widths, which the
// generic path below has no way to express.
match op {
BinOp::Shl | BinOp::Shr | BinOp::Ushr => return self.shift(op, lhs, rhs),
BinOp::BitAnd | BinOp::BitOr | BinOp::BitXor => return self.bitwise(op, lhs, rhs),
_ => {}
}
// A `float`-typed arithmetic operation runs at 32-bit width throughout.
if matches!(
op,
BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Mod
) && self.arith_result_type(lhs, rhs) == Some("float")
&& !(op == BinOp::Add && self.is_string_concat(lhs, rhs))
{
self.expr_unboxed(lhs)?;
self.expr_unboxed(rhs)?;
self.emit_f32_arith(op, 0);
return Ok(());
}
// `/` truncation is decided from the operands' static types.
if let BinOp::Div = op {
let l = self.expr_type(lhs);
let r = self.expr_type(rhs);
let wrap = self.operands_are_int(lhs, rhs);
self.expr_unboxed(lhs)?;
self.expr_unboxed(rhs)?;
self.emit_div(l, r, rhs, wrap, 0);
// `Integer.MIN_VALUE / -1` is the one division that overflows.
if wrap {
self.emit_wrap32(0);
}
return Ok(());
}
// `+` with a String or class-typed operand is string concatenation, and
// Java concatenation applies its string conversion to the other operand
// — the operand's `toString()` for an object, the one-character String
// for a `char`. Arithmetic `+` (which is what `'a' + 1` is) must not.
if op == BinOp::Add && self.is_string_concat(lhs, rhs) {
// A concatenation of compile-time constants IS a constant, and Java
// folds it in the compiler — which is why `("a" + "b") == "ab"` is
// `true` there: both sides end up the same interned literal. Folding
// it here is what keeps that true once `==` compares identities.
if let Some(folded) = self.const_string(&Expr::Binary {
op,
lhs: Box::new(lhs.clone()),
rhs: Box::new(rhs.clone()),
}) {
let c = self.string_literal(&folded);
self.b.emit(Op::LoadConst(c), 0);
return Ok(());
}
self.emit_stringified(lhs)?;
self.emit_stringified(rhs)?;
} else if matches!(op, BinOp::Eq | BinOp::Ne) {
// `==` unboxes a wrapper only against a primitive (JLS 15.21.1);
// between two references it compares identities and must not.
let primitive = |t: Option<String>| t.is_some_and(|t| !is_reference_type(&t));
let numeric =
primitive(self.expr_java_type(lhs)) || primitive(self.expr_java_type(rhs));
for e in [lhs, rhs] {
if numeric {
self.expr_unboxed(e)?;
} else {
self.expr(e)?;
}
}
} else if op == BinOp::Add && self.has_user_tostring {
// Neither operand is statically a String or a user class, yet one may
// be an object at run time (an erased `get()`): a heap object that is
// not a box is stringified, so `+` concatenates it through its
// `toString()` instead of the numeric hook's default rendering.
for e in [lhs, rhs] {
self.expr_unboxed(e)?;
if !self.renders_without_a_class(e) {
self.b
.emit(Op::CallBuiltin(crate::host::JSTRINGIFY_OBJ, 1), 0);
}
}
} else {
// Every other operator here is numeric, and numeric promotion
// unboxes a wrapper operand first — a `null` one throws (JLS 5.6).
self.expr_unboxed(lhs)?;
self.expr_unboxed(rhs)?;
}
// Integral `%` by zero throws `ArithmeticException` in Java, exactly as
// `/` does; the floating `%` yields NaN and needs no check.
if op == BinOp::Mod
&& self.expr_type(lhs) == NumType::Int
&& self.expr_type(rhs) == NumType::Int
{
self.emit_zero_divisor_check(rhs, 0);
}
let vop = match op {
BinOp::Add => Op::Add,
BinOp::Sub => Op::Sub,
BinOp::Mul => Op::Mul,
BinOp::Mod => Op::Mod,
BinOp::Eq => Op::NumEq,
BinOp::Ne => Op::NumNe,
BinOp::Lt => Op::NumLt,
BinOp::Gt => Op::NumGt,
BinOp::Le => Op::NumLe,
BinOp::Ge => Op::NumGe,
BinOp::Div => unreachable!("handled above"),
BinOp::And | BinOp::Or => unreachable!("handled above"),
BinOp::BitAnd
| BinOp::BitOr
| BinOp::BitXor
| BinOp::Shl
| BinOp::Shr
| BinOp::Ushr => unreachable!("handled above"),
};
self.b.emit(vop, 0);
// An `int` arithmetic result wraps at 32 bits. Comparisons yield a
// boolean and `+` on a String concatenates, so neither wraps.
if matches!(op, BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Mod)
&& self.operands_are_int(lhs, rhs)
{
self.emit_wrap32(0);
}
Ok(())
}
/// Whether `e` names `java.math.RoundingMode` (not shadowed by a user type),
/// the one JDK enum javars holds as its constant names.
fn is_rounding_mode_ref(&self, e: &Expr) -> bool {
matches!(e, Expr::Var(c) if c == "RoundingMode" && !self.classes.contains_key(c) && !self.is_declared_var(c))
}
/// `BigInteger.ONE`, `BigDecimal.TEN`, `MathContext.DECIMAL128` — the shared
/// constants of the `java.math` classes, as the call that builds each (so
/// the object is made by the same code `valueOf`/`new` use) and its type.
/// `None` when `e` names none, or a user class shadows the name.
fn library_constant(&self, e: &Expr) -> Option<(Expr, &'static str)> {
let Expr::Field { recv, name } = e else {
return None;
};
let Expr::Var(class) = &**recv else {
return None;
};
if self.classes.contains_key(class) || self.is_declared_var(class) {
return None;
}
let (ty, method, arg) = match (class.as_str(), name.as_str()) {
("BigInteger", "ZERO") => ("BigInteger", "valueOf", Expr::Int(0)),
("BigInteger", "ONE") => ("BigInteger", "valueOf", Expr::Int(1)),
("BigInteger", "TWO") => ("BigInteger", "valueOf", Expr::Int(2)),
("BigInteger", "TEN") => ("BigInteger", "valueOf", Expr::Int(10)),
("BigDecimal", "ZERO") => ("BigDecimal", "valueOf", Expr::Int(0)),
("BigDecimal", "ONE") => ("BigDecimal", "valueOf", Expr::Int(1)),
("BigDecimal", "TWO") => ("BigDecimal", "valueOf", Expr::Int(2)),
("BigDecimal", "TEN") => ("BigDecimal", "valueOf", Expr::Int(10)),
("MathContext", "DECIMAL32" | "DECIMAL64" | "DECIMAL128" | "UNLIMITED") => {
("MathContext", "#const", Expr::Str(name.clone()))
}
(
"RoundingMode",
"UP" | "DOWN" | "CEILING" | "FLOOR" | "HALF_UP" | "HALF_DOWN" | "HALF_EVEN"
| "UNNECESSARY",
) => ("RoundingMode", "#const", Expr::Str(name.clone())),
_ => return None,
};
let call = Expr::MethodCall {
recv: Box::new(Expr::Var(ty.to_string())),
method: method.to_string(),
args: vec![arg],
line: 0,
};
Some((call, ty))
}
/// `Integer.MAX_VALUE` / `Double.NaN` / `Math.PI` / … — the value and Java
/// type of a `static final` constant on a `java.lang` type, when `e` names
/// one. A user class of the same name shadows it.
fn wrapper_constant_ref(&self, e: &Expr) -> Option<(Value, &'static str)> {
let Expr::Field { recv, name } = e else {
return None;
};
let Expr::Var(class) = &**recv else {
return None;
};
if self.classes.contains_key(class) {
return None;
}
wrapper_constant(class, name)
}
/// Lower `&`, `|`, `^`.
///
/// On integral operands these are the bitwise operators and fusevm's native
/// ops match exactly (both sides are already inside their Java width, and
/// `&`/`|`/`^` cannot widen a value). On `boolean` operands they are Java's
/// *non-short-circuiting* logical operators, and the result has to stay a
/// boolean rather than the 0/1 an integer op would leave.
fn bitwise(&mut self, op: BinOp, lhs: &Expr, rhs: &Expr) -> Result<(), String> {
let is_bool = |t: Option<String>| t.as_deref().map(unwrapped_ty) == Some("boolean");
let boolean = is_bool(self.expr_java_type(lhs)) || is_bool(self.expr_java_type(rhs));
self.expr_unboxed(lhs)?;
self.expr_unboxed(rhs)?;
let vop = match (op, boolean) {
(BinOp::BitAnd, true) => Op::LogAnd,
(BinOp::BitOr, true) => Op::LogOr,
// `^` on two booleans is exactly "they differ".
(_, true) => Op::NumNe,
(BinOp::BitAnd, false) => Op::BitAnd,
(BinOp::BitOr, false) => Op::BitOr,
(_, false) => Op::BitXor,
};
self.b.emit(vop, 0);
Ok(())
}
/// Lower `<<`, `>>`, `>>>`.
///
/// Java masks the shift distance to the width of the *left* operand — 5 bits
/// for `int` (so `1 << 33` is `1 << 1`), 6 for `long` — and promotes only
/// that operand, so `1 << 2L` is still an `int`. fusevm's `Shl`/`Shr` always
/// mask to 6 bits and work on 64 bits, so the mask is emitted explicitly and
/// an `int` result is narrowed afterwards. `>>>` zero-fills at the operand's
/// width, which no fusevm op carries, so it routes through the host.
fn shift(&mut self, op: BinOp, lhs: &Expr, rhs: &Expr) -> Result<(), String> {
let long = self.expr_java_type(lhs).as_deref().map(unwrapped_ty) == Some("long");
self.expr_unboxed(lhs)?;
self.expr_unboxed(rhs)?;
self.b.emit(Op::LoadInt(if long { 63 } else { 31 }), 0);
self.b.emit(Op::BitAnd, 0);
if op == BinOp::Ushr {
self.b.emit(Op::LoadInt(if long { 64 } else { 32 }), 0);
self.b.emit(Op::CallBuiltin(crate::host::JUSHR, 3), 0);
return Ok(());
}
self.b
.emit(if op == BinOp::Shl { Op::Shl } else { Op::Shr }, 0);
if !long {
self.emit_wrap32(0);
}
Ok(())
}
/// Lower `(ty) expr`.
///
/// Java's *narrowing* primitive conversions are real value changes —
/// `(int) 3.9` is 3, `(byte) 200` is -56, `(int) 1e18` saturates to
/// `Integer.MAX_VALUE` — so those route through the host, which applies the
/// conversion at the right width. A widening or identity cast between types
/// javars already represents identically is emitted as the operand alone, so
/// the common `(int) i` stays native. A *reference* cast has no runtime
/// effect here: the host heap already carries each object's class and
/// a value already in reference form carries its own, so it changes no
/// representation — but it is still *checked*, and a cast the runtime class
/// does not satisfy throws `ClassCastException` the way Java's does. A cast
/// to a wrapper class whose operand is a *primitive* is not that at all: it
/// is Java's explicit boxing conversion, and is emitted as one.
fn cast(&mut self, ty: &str, e: &Expr, line: u32) -> Result<(), String> {
let src = self.expr_java_type(e);
if src.as_deref() == Some("String") && !is_reference_type(ty) && ty != "void" {
return Err(string_to_primitive(ty));
}
let identity = matches!(
(ty, src.as_deref()),
("int", Some("int" | "short" | "byte"))
| ("long", Some("int" | "long" | "short" | "byte"))
// `(double) f` widens exactly, `(float) f` is the identity; only
// `(float) d` narrows, and rounds to 32-bit precision.
| ("double", Some("double" | "float"))
| ("float", Some("float"))
| ("boolean", Some("boolean"))
);
let primitive = matches!(
ty,
"int" | "long" | "short" | "byte" | "char" | "float" | "double" | "boolean"
);
if !primitive {
// `(Integer) 5` and `(Object) 5L` are *boxing* conversions, not
// checked downcasts: the operand is a primitive, so there is no
// class to verify and the cast's whole effect is to produce the
// wrapper — the one the target names, or the one the operand
// autoboxes into when the target is `Object` or another supertype.
// `(Integer) someObj` still checks, because there the operand is
// already a reference.
// A `char` boxes to `Character` (JLS 5.1.7) whatever reference type
// the cast names, so `(Object) c` prints `c` and its class is
// `Character`. [`Compiler::autobox_code`] leaves `char` out because
// its other callers turn a `char` into a String first.
if src.as_deref() == Some("char") {
let code = crate::host::box_class_code("Character").expect("`Character` is boxed");
self.expr(e)?;
self.b.emit(Op::LoadInt(code), line);
self.b.emit(Op::CallBuiltin(crate::host::JBOX, 2), line);
return Ok(());
}
if src.as_deref().is_some_and(|t| !is_reference_type(t)) {
let code = crate::host::box_class_code(ty).or_else(|| self.autobox_code(e));
if let Some(code) = code {
self.expr(e)?;
self.b.emit(Op::LoadInt(code), line);
self.b.emit(Op::CallBuiltin(crate::host::JBOX, 2), line);
return Ok(());
}
}
return self.reference_cast(ty, e, line);
}
if identity {
return self.expr(e);
}
self.expr(e)?;
let c = self.b.add_constant(Value::str(ty.to_string()));
self.b.emit(Op::LoadConst(c), line);
self.b.emit(Op::CallBuiltin(crate::host::JCAST, 2), line);
Ok(())
}
/// Lower `(RefType) expr` — a *checked* reference cast.
///
/// The cast changes no representation (the host heap already carries each
/// object's class), so all it can do is verify one. It is emitted when the
/// target is a user class or interface, or a JDK type javars models — which
/// is [`crate::host::is_checkable_cast_target`], the same list the host
/// decides the check against, rather than a second and narrower copy kept
/// here. `Object` is always satisfied, and an unknown name — a type
/// *variable* after erasure, an array type — is passed through rather than
/// checked, because a check javars cannot decide must not invent a failure.
fn reference_cast(&mut self, ty: &str, e: &Expr, line: u32) -> Result<(), String> {
self.expr(e)?;
// An array target is checked against the type the array recorded.
let checkable = self.classes.contains_key(ty)
|| crate::host::is_checkable_cast_target(ty)
|| ty.ends_with("[]");
if !checkable {
return Ok(());
}
let c = self.b.add_constant(Value::str(ty.to_string()));
self.b.emit(Op::LoadConst(c), line);
self.emit_raising_builtin(crate::host::JCHECKCAST, 2, line);
Ok(())
}
/// Emit a division of two already-pushed operands. Java `/` divides as
/// floating point (fusevm's `Op::Div`) and truncates toward zero to an
/// integer only when both operands are statically integral — reproduced
/// with a trailing `Op::TruncInt`.
/// Lower `/`.
///
/// `int`-width integral division keeps the native op pair so the JIT can
/// trace it. Integral division at 64-bit width routes through the `JIDIV`
/// builtin, because fusevm's `Op::Div` computes in `f64`: that is exact for
/// two `int` operands but not for a `long`, where an operand above 2^53 does
/// not survive the round trip and `Long.MIN_VALUE / -1` saturates instead of
/// wrapping (see [`crate::host::JIDIV`]).
///
/// Anything else — a floating operand, or an operand whose type is not
/// statically known — routes through the `JDIV` builtin, because Java
/// floating division is IEEE-754: `x / 0.0` is a signed infinity and
/// `0.0 / 0.0` is NaN, where the native op yields `Undef`.
fn emit_div(&mut self, l: NumType, r: NumType, divisor: &Expr, int_width: bool, line: u32) {
if l == NumType::Int && r == NumType::Int {
self.emit_zero_divisor_check(divisor, line);
if int_width {
self.b.emit(Op::Div, line);
self.b.emit(Op::TruncInt, line);
} else {
self.b.emit(Op::CallBuiltin(crate::host::JIDIV, 2), line);
}
} else {
// Neither side is statically floating, so at least one is unknown:
// only the runtime values can say whether this is `int` division.
if l != NumType::Float && r != NumType::Float {
self.emit_raising_builtin(crate::host::JDIV_DYN, 2, line);
return;
}
self.b.emit(Op::CallBuiltin(crate::host::JDIV, 2), line);
}
}
/// Emit Java's integral division-by-zero check for the divisor already on
/// top of the stack: `int / 0` and `int % 0` throw `ArithmeticException`,
/// where fusevm's native `Div`/`Mod` (shell/awk flavoured, with no
/// infinities) yield `Undef`. The floating path needs no check — IEEE-754
/// division by zero is an infinity, which `JDIV` already produces.
///
/// A literal non-zero divisor is checked at compile time and emits nothing,
/// so `x / 2` and every constant-divisor loop keep the bare native op pair
/// and stay JIT-traceable.
fn emit_zero_divisor_check(&mut self, divisor: &Expr, line: u32) {
if let Expr::Int(n) = divisor {
if *n != 0 {
return;
}
}
self.b.emit(Op::Dup, line);
self.b.emit(Op::LoadInt(0), line);
self.b.emit(Op::NumEq, line);
let jf = self.b.emit(Op::JumpIfFalse(0), line);
// The unwind abandons both operands; the handler's `JEXC_CUT` (or the
// frame's `ReturnValue`) drops them.
self.emit_fault("ArithmeticException", "/ by zero", line);
let after = self.b.current_pos();
self.b.patch_jump(jf, after);
}
}
// ── FFI detection (does the program contain a `rust { ... }` block?) ────────
/// True if any statement in `body` (recursively) evaluates a `__rust_compile`
/// call — the desugar target of an inline `rust { ... }` block.
fn body_has_ffi(body: &[Stmt]) -> bool {
body.iter().any(|s| match &s.kind {
StmtKind::Local { init, .. } => init.as_ref().is_some_and(expr_has_ffi),
StmtKind::Locals(decls) => body_has_ffi(decls),
StmtKind::Assign { value, .. } => expr_has_ffi(value),
StmtKind::IndexAssign {
array,
index,
value,
..
} => expr_has_ffi(array) || expr_has_ffi(index) || expr_has_ffi(value),
StmtKind::FieldAssign { recv, value, .. } => expr_has_ffi(recv) || expr_has_ffi(value),
StmtKind::Expr(e) => expr_has_ffi(e),
StmtKind::If { cond, then, els } => {
expr_has_ffi(cond) || body_has_ffi(then) || body_has_ffi(els)
}
StmtKind::While { cond, body } => expr_has_ffi(cond) || body_has_ffi(body),
StmtKind::DoWhile { body, cond } => body_has_ffi(body) || expr_has_ffi(cond),
StmtKind::For {
init,
cond,
update,
body,
} => {
body_has_ffi(init)
|| cond.as_ref().is_some_and(expr_has_ffi)
|| body_has_ffi(update)
|| body_has_ffi(body)
}
StmtKind::ForEach { iter, body, .. } => expr_has_ffi(iter) || body_has_ffi(body),
StmtKind::Switch { disc, groups } => {
expr_has_ffi(disc)
|| groups
.iter()
.any(|g| g.labels.iter().any(expr_has_ffi) || body_has_ffi(&g.body))
}
StmtKind::Labeled { body, .. } => body_has_ffi(std::slice::from_ref(body)),
StmtKind::Return(val) => val.as_ref().is_some_and(expr_has_ffi),
StmtKind::Try {
body,
catches,
finally_body,
} => {
body_has_ffi(body)
|| catches.iter().any(|c| body_has_ffi(&c.body))
|| body_has_ffi(finally_body)
}
StmtKind::Throw(e) | StmtKind::Yield(e) => expr_has_ffi(e),
StmtKind::Assert { .. } | StmtKind::LocalClass(_) => false,
StmtKind::Break(_) | StmtKind::Continue(_) => false,
})
}
fn expr_has_ffi(e: &Expr) -> bool {
match e {
Expr::ClassLit(_) => false,
Expr::TypePattern { .. } => false,
Expr::Call { name, args, .. } => name == RUST_COMPILE || args.iter().any(expr_has_ffi),
Expr::Unary { rhs, .. } => expr_has_ffi(rhs),
Expr::Cast { expr, .. } => expr_has_ffi(expr),
Expr::PreIncDec { .. } => false,
// The target is an lvalue — an index or a field chain — whose
// subexpressions can still carry a `rust { … }` call.
Expr::IncDec { target, .. } => expr_has_ffi(target),
Expr::Assign { target, value, .. } => expr_has_ffi(target) || expr_has_ffi(value),
Expr::Binary { lhs, rhs, .. } => expr_has_ffi(lhs) || expr_has_ffi(rhs),
Expr::Ternary { cond, then, els } => {
expr_has_ffi(cond) || expr_has_ffi(then) || expr_has_ffi(els)
}
Expr::Println { arg, .. } => arg.as_deref().is_some_and(expr_has_ffi),
Expr::MethodCall { recv, args, .. } => expr_has_ffi(recv) || args.iter().any(expr_has_ffi),
Expr::NewArray { sizes, .. } => sizes.iter().any(expr_has_ffi),
Expr::ArrayLit { elems, .. } => elems.iter().any(expr_has_ffi),
Expr::Index { array, index } => expr_has_ffi(array) || expr_has_ffi(index),
Expr::Field { recv, .. } => expr_has_ffi(recv),
Expr::NewObject { args, .. } => args.iter().any(expr_has_ffi),
Expr::InstanceOf { expr, .. } => expr_has_ffi(expr),
Expr::Lambda { body, .. } => match body {
LambdaBody::Expr(e) => expr_has_ffi(e),
LambdaBody::Block(b) => body_has_ffi(b),
},
Expr::MethodRef { recv, .. } => expr_has_ffi(recv),
Expr::SwitchExpr { disc, arms, .. } => {
expr_has_ffi(disc)
|| arms.iter().any(|a| {
a.labels.iter().any(expr_has_ffi)
|| match &a.body {
SwitchArmBody::Expr(e) => expr_has_ffi(e),
SwitchArmBody::Block(b) => body_has_ffi(b),
}
})
}
Expr::Int(_)
| Expr::Long(_)
| Expr::Float(_)
| Expr::Float32(_)
| Expr::Str(_)
| Expr::Char(_)
| Expr::Bool(_)
| Expr::Var(_)
| Expr::This
| Expr::PostIncDec { .. } => false,
}
}
/// The mangled subroutine name for a class member: `Class#member#ty1,ty2`. `#`
/// is not a legal Java identifier char, so mangled names never collide with a
/// user-declared static method. Including the parameter types disambiguates
/// same-name/same-arity overloads. Constructors use the member name `<init>`.
/// The global holding whether `class`'s static initializer has started.
fn clinit_flag(class: &str) -> String {
format!("#clinit-done#{class}")
}
/// The subroutine that runs `class`'s static initializer.
fn clinit_name(class: &str) -> String {
format!("#clinit#{class}")
}
/// The constant expression a `static final` field is initialized with, when it
/// is a *constant variable* (JLS 4.12.4): a primitive or `String` field whose
/// initializer is a constant expression (JLS 15.29). Its value is known to the
/// compiler, and reading it does not initialize its class — while a `final`
/// field of any other type (`static final Integer I = 4`) is an ordinary field
/// whose read does. The parser lowers the field's initializer to the
/// assignment that seeds its cell.
fn constant_initializer<'a>(static_init: &'a [Stmt], field: &str, ty: &str) -> Option<&'a Expr> {
let constant_type = ty == "String" || !is_reference_type(ty);
if !constant_type {
return None;
}
static_init.iter().find_map(|st| match &st.kind {
StmtKind::Assign {
name,
op: AssignOp::Assign,
value,
} if name == field && is_constant_expr(value) => Some(value),
_ => None,
})
}
/// A constant expression javars recognizes (JLS 15.29): literals combined by
/// the unary, binary and conditional operators and by casts to a primitive
/// type or `String`. A name, even of another constant, is not followed; and an
/// integral division by a literal zero is left out, since it does not complete
/// normally and so is no constant.
fn is_constant_expr(e: &Expr) -> bool {
match e {
Expr::Unary { rhs, .. } => is_constant_expr(rhs),
Expr::Binary { op, lhs, rhs } => {
let by_zero = matches!(op, BinOp::Div | BinOp::Mod)
&& matches!(rhs.as_ref(), Expr::Int(0) | Expr::Long(0));
!by_zero && is_constant_expr(lhs) && is_constant_expr(rhs)
}
Expr::Ternary { cond, then, els } => {
is_constant_expr(cond) && is_constant_expr(then) && is_constant_expr(els)
}
Expr::Cast { ty, expr, .. } => {
(ty == "String" || !is_reference_type(ty)) && is_constant_expr(expr)
}
_ => is_literal(e),
}
}
/// The value of an integral constant-expression `case` label — literals,
/// `char`s, the unary and binary integer operators and casts to an integral
/// type, at `int` width (JLS 15.29). `None` for anything else, a division by
/// zero included.
fn int_label_value(e: &Expr) -> Option<i32> {
Some(match e {
Expr::Int(n) => *n as i32,
Expr::Char(c) => crate::jstr::char_value(*c) as i32,
Expr::Unary { op, rhs } => {
let v = int_label_value(rhs)?;
match op {
UnOp::Neg => v.wrapping_neg(),
UnOp::Plus => v,
UnOp::BitNot => !v,
UnOp::Not => return None,
}
}
Expr::Cast { ty, expr, .. } => {
let v = int_label_value(expr)?;
match ty.as_str() {
"int" => v,
"char" => i32::from(v as u16),
"short" => i32::from(v as i16),
"byte" => i32::from(v as i8),
_ => return None,
}
}
Expr::Binary { op, lhs, rhs } => {
let (a, b) = (int_label_value(lhs)?, int_label_value(rhs)?);
match op {
BinOp::Add => a.wrapping_add(b),
BinOp::Sub => a.wrapping_sub(b),
BinOp::Mul => a.wrapping_mul(b),
BinOp::Div if b != 0 => a.wrapping_div(b),
BinOp::Mod if b != 0 => a.wrapping_rem(b),
BinOp::BitAnd => a & b,
BinOp::BitOr => a | b,
BinOp::BitXor => a ^ b,
BinOp::Shl => a.wrapping_shl(b as u32),
BinOp::Shr => a.wrapping_shr(b as u32),
BinOp::Ushr => (a as u32).wrapping_shr(b as u32) as i32,
_ => return None,
}
}
_ => return None,
})
}
/// A literal, or a negated numeric literal.
fn is_literal(e: &Expr) -> bool {
match e {
Expr::Int(_)
| Expr::Long(_)
| Expr::Float(_)
| Expr::Float32(_)
| Expr::Str(_)
| Expr::Char(_)
| Expr::Bool(_) => true,
Expr::Unary { op: UnOp::Neg, rhs } => matches!(
rhs.as_ref(),
Expr::Int(_) | Expr::Long(_) | Expr::Float(_) | Expr::Float32(_)
),
_ => false,
}
}
/// The classes whose static initialization has to wait for first use.
///
/// Java initializes a class when it is first used, so an initializer with a
/// side effect — a call, a `static { … }` block, an enum's constructors — is
/// observable in *when* it runs. A class whose initializers only store
/// literals is not: the values are seeded up front and nothing can tell. The
/// entry class is initialized before `main` and so is never lazy. A subclass
/// of a lazy class is lazy too, because initializing it initializes the
/// superclass first.
/// The superinterfaces of the class `cl` that initializing it initializes, in
/// the order JLS 12.4.2 step 7 fixes: those declaring a non-abstract instance
/// method (a `default`), enumerated depth-first over `implements` order with an
/// interface's own superinterfaces ahead of it. An interface itself initializes
/// none.
fn default_interfaces(cl: &Class, by_name: &HashMap<&str, &Class>) -> Vec<String> {
fn walk(name: &str, by_name: &HashMap<&str, &Class>, out: &mut Vec<String>) {
let Some(i) = by_name.get(name) else {
return;
};
for sup in &i.interfaces {
walk(sup, by_name, out);
}
if i.methods.iter().any(|m| !m.is_abstract) && !out.iter().any(|o| o == name) {
out.push(name.to_string());
}
}
let mut out = Vec::new();
if !cl.is_interface {
for i in &cl.interfaces {
walk(i, by_name, &mut out);
}
}
out
}
fn lazy_initialized_classes(prog: &Program) -> HashSet<String> {
let by_name: HashMap<&str, &Class> =
prog.classes.iter().map(|c| (c.name.as_str(), c)).collect();
let observable = |c: &Class| {
!c.enum_constants.is_empty()
|| c.static_init.iter().any(|st| {
!matches!(&st.kind, StmtKind::Assign { op: AssignOp::Assign, value, .. } if is_constant_expr(value))
})
};
let lazy = |c: &Class| {
let mut cur = Some(c);
while let Some(cl) = cur {
if cl.name != prog.class_name && observable(cl) {
return true;
}
let init_ifaces = default_interfaces(cl, &by_name);
if init_ifaces.iter().any(|i| observable(by_name[i.as_str()])) {
return true;
}
cur = cl
.superclass
.as_deref()
.and_then(|s| by_name.get(s).copied());
}
false
};
prog.classes
.iter()
.filter(|c| c.name != prog.class_name && lazy(c))
.map(|c| c.name.clone())
.collect()
}
fn mangle(class: &str, member: &str, param_tys: &[String]) -> String {
format!("{class}#{member}#{}", param_tys.join(","))
}
/// The mangled subroutine name for a top-level user `static` method, including
/// its parameter types so overloads get distinct subroutines. Prefixed with `#`
/// so it never collides with an instance mangle or a user identifier.
fn mangle_static(owner: &str, name: &str, param_tys: &[String]) -> String {
format!("#s#{owner}#{name}#{}", param_tys.join(","))
}
/// The numeric widening rank of a primitive type (`byte` < `short`/`char` <
/// `int` < `long` < `float` < `double`); `None` for non-numeric types. Used by
/// overload resolution to score widening conversions.
/// The result expressions of a `switch` expression, in source order: each
/// expression arm's body and every `yield` value in a block arm (JLS 15.28.1).
///
/// A `yield` inside a nested `switch` *statement*, loop, `if` or `try` still
/// belongs to this switch, so statements are walked; expressions are not,
/// because a `yield` inside a nested `switch` expression or a lambda belongs to
/// that.
fn switch_result_exprs(arms: &[SwitchArm]) -> Vec<&Expr> {
fn walk<'a>(stmts: &'a [Stmt], out: &mut Vec<&'a Expr>) {
for s in stmts {
match &s.kind {
StmtKind::Yield(e) => out.push(e),
StmtKind::While { body, .. }
| StmtKind::DoWhile { body, .. }
| StmtKind::For { body, .. }
| StmtKind::ForEach { body, .. } => walk(body, out),
StmtKind::If { then, els, .. } => {
walk(then, out);
walk(els, out);
}
StmtKind::Switch { groups, .. } => {
for g in groups {
walk(&g.body, out);
}
}
StmtKind::Labeled { body, .. } => walk(std::slice::from_ref(&**body), out),
StmtKind::Try {
body,
catches,
finally_body,
} => {
walk(body, out);
for c in catches {
walk(&c.body, out);
}
walk(finally_body, out);
}
_ => {}
}
}
}
let mut out = Vec::new();
for arm in arms {
match &arm.body {
SwitchArmBody::Expr(e) => out.push(&**e),
SwitchArmBody::Block(stmts) => walk(stmts, &mut out),
}
}
out
}
fn numeric_rank(ty: &str) -> Option<u32> {
Some(match unwrapped_ty(ty) {
"byte" => 1,
"short" | "char" => 2,
"int" => 3,
"long" => 4,
"float" => 5,
"double" => 6,
_ => return None,
})
}
/// The primitive a type name denotes: a wrapper class answers as the primitive
/// it boxes, and every other name answers as itself.
///
/// Java's binary numeric promotion, its shift-distance mask, and its
/// `&`/`|`/`^` overloading are all defined on the *primitive* — a wrapper
/// operand is unboxed first (JLS 5.6.2) — so every predicate that asks "how
/// wide is this operand" asks through here. Without it `Long l; l << 33` masked
/// the distance to 5 bits instead of 6 and `Boolean b; b & false` compiled to
/// the integer `&`.
fn unwrapped_ty(ty: &str) -> &str {
match ty {
"Integer" => "int",
"Long" => "long",
"Short" => "short",
"Byte" => "byte",
"Character" => "char",
"Float" => "float",
"Double" => "double",
"Boolean" => "boolean",
other => other,
}
}
/// The type name for a numeric rank, promoted to at least `int` (Java's binary
/// numeric promotion never yields a sub-`int` result).
fn rank_name(rank: u32) -> &'static str {
match rank.max(3) {
3 => "int",
4 => "long",
5 => "float",
_ => "double",
}
}
/// True when `ty` is a reference type (a class, interface, array, or `String`)
/// rather than a primitive or `void`.
/// A primitive type's wrapper class, or `None` when `ty` is not a primitive.
/// `void` has no boxing conversion, so it is deliberately absent.
/// The cost of JLS 5.1.2 widening primitive conversion from `from` to `to`
/// (both primitives): `Some(0)` for identity, the rank distance for a widening,
/// `None` otherwise. `char` is unsigned, so it widens to `int` and up but not
/// to `short`, and neither `byte` nor `short` widens to `char`.
fn primitive_widening_cost(from: &str, to: &str) -> Option<u32> {
if from == to {
return Some(0);
}
if matches!((from, to), ("char", "short") | ("byte" | "short", "char")) {
return None;
}
let (f, t) = (numeric_rank(from)?, numeric_rank(to)?);
(f <= t).then(|| t - f)
}
fn wrapper_of(ty: &str) -> Option<&'static str> {
Some(match ty {
"int" => "Integer",
"long" => "Long",
"double" => "Double",
"float" => "Float",
"short" => "Short",
"byte" => "Byte",
"char" => "Character",
"boolean" => "Boolean",
_ => return None,
})
}
fn is_reference_type(ty: &str) -> bool {
!matches!(
ty,
"int" | "long" | "short" | "byte" | "char" | "float" | "double" | "boolean" | "void"
)
}
/// Register a subroutine's formal parameters into its scope: allocate slots in
/// declaration order and record each parameter's numeric type, raw declared
/// type, and its status as a true local (so a same-named field is shadowed).
fn register_params(scope: &mut MethodScope, params: &[Param]) {
for p in params {
scope.slot(&p.name);
scope.types.insert(
p.name.clone(),
numtype_of_ty(&p.ty).unwrap_or(NumType::Other),
);
scope.decl_types.insert(p.name.clone(), p.ty.clone());
if let Some(g) = with_targs(&p.ty, &p.targs) {
scope.decl_generic.insert(p.name.clone(), g);
}
if p.wildcard {
scope.decl_wildcard.insert(p.name.clone());
}
scope.declared.insert(p.name.clone());
}
}
/// Which type argument of a `java.util.function` interface each parameter of
/// its single abstract method, and its result, is declared as: `Function<T, R>`
/// applies `T` and answers `R`, so it is `([0], Some(1))`. `None` for an
/// interface whose abstract method mentions no type argument.
fn functional_type_arg_slots(base: &str) -> Option<(&'static [usize], Option<usize>)> {
Some(match base {
"Function" => (&[0], Some(1)),
"BiFunction" => (&[0, 1], Some(2)),
"UnaryOperator" => (&[0], Some(0)),
"BinaryOperator" => (&[0, 0], Some(0)),
"Supplier" | "Callable" => (&[], Some(0)),
"Consumer" | "Predicate" => (&[0], None),
"BiConsumer" | "BiPredicate" => (&[0, 1], None),
"Comparator" => (&[0, 0], None),
"ToIntFunction" | "ToLongFunction" | "ToDoubleFunction" => (&[0], None),
"ToIntBiFunction" | "ToLongBiFunction" | "ToDoubleBiFunction" => (&[0, 1], None),
"IntFunction" | "LongFunction" | "DoubleFunction" => (&[], Some(0)),
"ObjIntConsumer" | "ObjLongConsumer" | "ObjDoubleConsumer" => (&[0], None),
_ => return None,
})
}
/// Every user method's and constructor's parameter and return types with their
/// type arguments, keyed by the mangled name a call resolves to — the tables
/// behind [`Compiler::param_generics`] and [`Compiler::ret_generics`]. A
/// signature that declares no type arguments has no entry.
#[allow(clippy::type_complexity)]
fn signature_generics(
prog: &Program,
) -> (
HashMap<String, Vec<Option<String>>>,
HashMap<String, String>,
HashMap<String, Vec<bool>>,
HashSet<String>,
) {
let mut params = HashMap::default();
let mut rets = HashMap::default();
let mut param_wildcards = HashMap::default();
let mut ret_wildcards = HashSet::default();
let mut record = |mangled: String, ps: &[Param], ret: Option<(&str, &[String], bool)>| {
let gs: Vec<Option<String>> = ps.iter().map(|p| with_targs(&p.ty, &p.targs)).collect();
if gs.iter().any(Option::is_some) {
params.insert(mangled.clone(), gs);
}
if ps.iter().any(|p| p.wildcard) {
param_wildcards.insert(mangled.clone(), ps.iter().map(|p| p.wildcard).collect());
}
if ret.is_some_and(|(_, _, w)| w) {
ret_wildcards.insert(mangled.clone());
}
if let Some(g) = ret.and_then(|(ty, targs, _)| with_targs(ty, targs)) {
rets.insert(mangled, g);
}
};
let tys = |ps: &[Param]| -> Vec<String> { ps.iter().map(|p| p.ty.clone()).collect() };
for m in &prog.methods {
let mangled = mangle_static(&m.owner, &m.name, &tys(&m.params));
record(
mangled,
&m.params,
Some((&m.ret, &m.ret_targs, m.ret_wildcard)),
);
}
for cl in &prog.classes {
for m in &cl.methods {
let mangled = mangle(&cl.name, &m.name, &tys(&m.params));
record(
mangled,
&m.params,
Some((&m.ret, &m.ret_targs, m.ret_wildcard)),
);
}
for c in &cl.ctors {
record(mangle(&cl.name, "<init>", &tys(&c.params)), &c.params, None);
}
}
(params, rets, param_wildcards, ret_wildcards)
}
/// `ty` written with its type arguments (`List<Float>`), the form
/// [`crate::ast::generic_parts`] splits — or `None` when there are none to
/// record. An array type never carries its element's arguments.
fn with_targs(ty: &str, targs: &[String]) -> Option<String> {
// A declaration typed by a bare type variable (`T v`) records the
// variable itself, `#T`, as its one argument over the erasure `Object`.
if let [t] = targs {
if ty == "Object" && t.starts_with('#') {
return Some(t.clone());
}
}
(!targs.is_empty() && !ty.ends_with("[]")).then(|| format!("{ty}<{}>", targs.join(",")))
}
/// A typing memo: node address → (its [`memo_fingerprint`], the answer).
type TypeMemo = std::cell::RefCell<HashMap<usize, (String, Option<String>)>>;
/// A constant-size summary of an expression node — its kind, its name or
/// member, its argument count and line — that tells a memoized node from a
/// different one later built at the same address.
fn memo_fingerprint(e: &Expr) -> String {
match e {
Expr::Var(n) => format!("v{n}"),
Expr::Call { name, args, line } => format!("c{name}/{}@{line}", args.len()),
Expr::MethodCall {
method, args, line, ..
} => format!("m{method}/{}@{line}", args.len()),
Expr::Field { name, .. } => format!("f{name}"),
Expr::NewObject {
class, args, line, ..
} => format!("n{class}/{}@{line}", args.len()),
Expr::Cast { ty, line, .. } => format!("k{ty}@{line}"),
other => format!("{:?}", std::mem::discriminant(other)),
}
}
/// Replace each type variable `#P` in the generic type text `sig` by the
/// argument at `P`'s position in `params`, where `args` has one; a variable it
/// does not bind stays `#P`, which reads as `Object`.
fn subst_tvars(sig: &str, params: &[String], args: &[String]) -> String {
let mut out = String::with_capacity(sig.len());
let mut rest = sig;
while let Some(i) = rest.find('#') {
out.push_str(&rest[..i]);
let tail = &rest[i + 1..];
let end = tail
.find(|c: char| !(c.is_alphanumeric() || c == '_' || c == '$'))
.unwrap_or(tail.len());
let name = &tail[..end];
match params
.iter()
.position(|p| p == name)
.and_then(|k| args.get(k))
{
Some(a) => out.push_str(a),
None => {
out.push('#');
out.push_str(name);
}
}
rest = &tail[end..];
}
out.push_str(rest);
out
}
/// Bind the type variables of the declared generic type `sig` against the
/// argument type `actual`, appending to `out`; the first binding of a variable
/// wins. Only a matching shape binds: `#E` against anything known, `List<#E>`
/// against a `List<…>` (or another collection of the same kind).
fn unify_tvars(sig: &str, actual: &str, out: &mut Vec<(String, String)>) {
if let Some(name) = sig.strip_prefix('#') {
if is_known_type(&crate::ast::generic_parts(actual).0)
&& !out.iter().any(|(n, _)| n == name)
{
out.push((name.to_string(), actual.to_string()));
}
return;
}
let (sb, sargs) = crate::ast::generic_parts(sig);
let (ab, aargs) = crate::ast::generic_parts(actual);
let same_shape =
sb == ab || collection_kind(&sb).is_some_and(|k| collection_kind(&ab) == Some(k));
if sargs.is_empty() || sargs.len() != aargs.len() || !same_shape {
return;
}
for (s, a) in sargs.iter().zip(&aargs) {
unify_tvars(s, a, out);
}
}
/// True when a type from a generic position says more than its erasure: not
/// `Object`, and not a type variable (`#T`) no type argument has replaced.
fn is_known_type(t: &str) -> bool {
t != "Object" && !t.starts_with('#')
}
/// The numeric category of an array's elements from its declared type string:
/// `int[]`/`long[]`/… → int, `double[]`/`float[]` → float, else non-numeric.
fn array_elem_numtype(array_ty: &str) -> NumType {
match array_ty.strip_suffix("[]") {
Some("int" | "long" | "short" | "byte" | "char") => NumType::Int,
Some("double" | "float") => NumType::Float,
_ => NumType::Other,
}
}
/// True when `name` is a stdlib class whose methods javars dispatches
/// statically (rather than treating `name` as a value/receiver).
/// The simple name of a fully-qualified stdlib class reference
/// (`java.util.Arrays` → `Arrays`), when `e` is a dotted chain rooted at a
/// package name.
///
/// Only `java`/`javax` roots qualify, so an ordinary field access on a user
/// expression can never be mistaken for a package path.
fn qualified_static_class(e: &Expr) -> Option<String> {
fn is_package(e: &Expr) -> bool {
match e {
Expr::Var(v) => v == "java" || v == "javax",
Expr::Field { recv, .. } => is_package(recv),
_ => false,
}
}
let Expr::Field { recv, name } = e else {
return None;
};
(is_package(recv) && is_static_class(name)).then(|| name.clone())
}
fn is_static_class(name: &str) -> bool {
matches!(
name,
"RoundingMode"
| "Math"
| "StrictMath"
| "Integer"
| "Long"
| "Short"
| "Byte"
| "Double"
| "Float"
| "Boolean"
| "String"
| "Character"
| "Arrays"
| "Collections"
| "List"
| "Set"
| "Map"
| "Optional"
| "OptionalInt"
| "OptionalLong"
| "OptionalDouble"
| "Stream"
| "IntStream"
| "LongStream"
| "DoubleStream"
| "Collectors"
| "Comparator"
| "Objects"
// `System`'s statics beyond its two streams, and the input
// classes, whose constructors `new` lowers to the `#new` static.
| "System"
| "Scanner"
| "BufferedReader"
| "InputStreamReader"
| "StringReader"
| "StringTokenizer"
| "PrintWriter"
| "BufferedWriter"
| "OutputStreamWriter"
| "StringWriter"
| "PrintStream"
| "BufferedOutputStream"
| "Random"
| "IntSummaryStatistics"
| "LongSummaryStatistics"
| "DoubleSummaryStatistics"
| "Pattern"
| "Matcher"
| "BitSet"
| "BigInteger"
| "BigDecimal"
| "MathContext"
| "AtomicInteger"
| "AtomicLong"
| "AtomicBoolean"
| "SimpleEntry"
| "SimpleImmutableEntry"
| "StringJoiner"
)
}
/// The binary operator a compound assignment applies, or `None` for the ones
/// whose lowering is not a plain binary op (the shifts, and `=` itself).
fn compound_binop(op: AssignOp) -> Option<BinOp> {
Some(match op {
AssignOp::Add => BinOp::Add,
AssignOp::Sub => BinOp::Sub,
AssignOp::Mul => BinOp::Mul,
AssignOp::Div => BinOp::Div,
AssignOp::Mod => BinOp::Mod,
_ => return None,
})
}
/// The argument positions (0-based, counted after the format string) a format
/// string consumes with a *text* conversion — `%s`, `%S`, `%h`, `%H`, `%b`,
/// `%B`. Those are the ones a `float` reaches as `Float.toString`; every other
/// conversion widens it to a `double` the way Java does.
///
/// Explicit argument indexes (`%2$s`) select a slot without advancing the
/// implicit cursor, and `%%`/`%n` consume no argument at all.
fn text_conversion_slots(fmt: &str) -> Vec<usize> {
let cs: Vec<char> = fmt.chars().collect();
let mut out = Vec::new();
let mut next = 0usize;
let mut i = 0usize;
while i < cs.len() {
if cs[i] != '%' {
i += 1;
continue;
}
i += 1;
// `%<n>$` — an explicit, 1-based argument index.
let start = i;
while i < cs.len() && cs[i].is_ascii_digit() {
i += 1;
}
let explicit = if i < cs.len() && cs[i] == '$' && i > start {
let n: usize = cs[start..i].iter().collect::<String>().parse().unwrap_or(1);
i += 1;
Some(n.saturating_sub(1))
} else {
i = start;
None
};
// flags, width, `.precision`
while i < cs.len() && "-+ 0,(#".contains(cs[i]) {
i += 1;
}
while i < cs.len() && (cs[i].is_ascii_digit() || cs[i] == '.') {
i += 1;
}
let Some(&conv) = cs.get(i) else { break };
i += 1;
if conv == '%' || conv == 'n' {
continue;
}
let slot = explicit.unwrap_or_else(|| {
let s = next;
next += 1;
s
});
if matches!(conv, 's' | 'S' | 'h' | 'H' | 'b' | 'B') {
out.push(slot);
}
}
out
}
/// True when a stdlib static renders a `char` argument as text, so the code
/// point has to be converted to its one-character String first. `String`'s
/// statics all do (`valueOf`, `format`, `join`); `Arrays`'s rendering pair does,
/// which is what makes `Arrays.toString(s.toCharArray())` print `[a, b, c]`;
/// `List.of`/`Set.of` box their elements. `Math` and the `Character` predicates
/// take the code point itself and are deliberately absent.
fn takes_char_as_string(class: &str, method: &str) -> bool {
match class {
"String" | "List" | "Set" | "Collections" => true,
"Arrays" => matches!(method, "toString" | "deepToString" | "asList"),
_ => false,
}
}
/// The declared Java return type of a boxed primitive's own instance method —
/// `Number`'s six converters, `Boolean.booleanValue`, `Character.charValue`,
/// and `Object.hashCode`.
///
/// Consulted only after a user class's own methods have been resolved, so a
/// user `intValue()` still wins. Feeds the 32-bit `int` wrap decision and, for
/// `charValue()`, the choice to render a code point as a character.
fn boxed_call_java_type(method: &str, argc: usize) -> Option<&'static str> {
if argc != 0 {
return None;
}
Some(match method {
"intValue" | "hashCode" => "int",
"longValue" => "long",
"shortValue" => "short",
"byteValue" => "byte",
"doubleValue" => "double",
"floatValue" => "float",
"booleanValue" => "boolean",
"isNaN" | "isInfinite" => "boolean",
"charValue" => "char",
_ => return None,
})
}
/// The declared Java return type of a known stdlib static call, or `None` when
/// javars does not model it statically. `Math.abs`/`max`/`min` are deliberately
/// absent: their result is `int` or `double` depending on the argument, and
/// claiming either would mis-type the other. Feeds overload resolution and the
/// 32-bit `int` wrap decision.
fn static_call_java_type(class: &str, method: &str) -> Option<&'static str> {
Some(match (class, method) {
("System", "currentTimeMillis" | "nanoTime") => "long",
("System", "lineSeparator" | "getProperty" | "getenv") => "String",
("System", "#in") => "InputStream",
("System", "#out" | "#err") => "PrintStream",
("PrintWriter", "#new") => "PrintWriter",
("BufferedWriter", "#new") => "BufferedWriter",
("OutputStreamWriter", "#new") => "OutputStreamWriter",
("StringWriter", "#new") => "StringWriter",
("PrintStream", "#new") => "PrintStream",
("BufferedOutputStream", "#new") => "BufferedOutputStream",
("Scanner", "#new") => "Scanner",
("BufferedReader", "#new") => "BufferedReader",
("InputStreamReader", "#new") => "InputStreamReader",
("StringReader", "#new") => "StringReader",
("StringTokenizer", "#new") => "StringTokenizer",
("SimpleEntry", "#new") => "SimpleEntry",
("SimpleImmutableEntry", "#new") => "SimpleImmutableEntry",
("Random", "#new") => "Random",
("BitSet", "#new") => "BitSet",
("BigInteger", "#new" | "valueOf") => "BigInteger",
("BigDecimal", "#new" | "valueOf") => "BigDecimal",
("MathContext", "#new" | "#const") => "MathContext",
("RoundingMode", "#const" | "valueOf") => "RoundingMode",
("StringJoiner", "#new") => "StringJoiner",
("AtomicInteger", "#new") => "AtomicInteger",
("AtomicLong", "#new") => "AtomicLong",
("AtomicBoolean", "#new") => "AtomicBoolean",
("Pattern", "compile") => "Pattern",
("Pattern", "matches") => "boolean",
("Pattern", "quote") | ("Matcher", "quoteReplacement") => "String",
("IntSummaryStatistics", "#new") => "IntSummaryStatistics",
("LongSummaryStatistics", "#new") => "LongSummaryStatistics",
("DoubleSummaryStatistics", "#new") => "DoubleSummaryStatistics",
("Math", "random") => "double",
("Integer", "parseInt") => "int",
// The wrapper `valueOf`s answer a *reference*, and saying so is what
// makes `Integer.valueOf(128) == Integer.valueOf(128)` compare handles
// (`false`, as in Java) rather than the numbers behind them. Their
// numeric category is still integral — `numtype_of_ty` maps a wrapper
// to the primitive it boxes — so `Integer.valueOf(7) / 2` still
// truncates.
("Integer", "valueOf") => "Integer",
("Long", "valueOf") => "Long",
("Short", "valueOf") => "Short",
("Byte", "valueOf") => "Byte",
("Character", "valueOf") => "Character",
("Double", "valueOf") => "Double",
// `Long.parseLong` and `Math.round` are 64-bit results in Java, so they
// must NOT be treated as `int` — that is exactly the case where the
// wrap would be wrong.
("Long", "parseLong") | ("Math", "round") => "long",
("Long", "parseUnsignedLong") => "long",
// The `double`-returning `Math` statics: the exactly specified ones (an
// IEEE operation or a bit-pattern walk) and the transcendentals answered
// from the fdlibm port (`crate::fdlibm`), `sin`/`cos` from the port of
// HotSpot's aarch64 intrinsic (`crate::hotspot_trig`).
(
"Math",
"pow" | "sqrt" | "floor" | "ceil" | "rint" | "copySign" | "ulp" | "nextUp" | "nextDown"
| "nextAfter" | "fma" | "scalb" | "sin" | "cos" | "tan" | "asin" | "acos" | "atan"
| "atan2" | "exp" | "log" | "log10" | "log1p" | "expm1" | "cbrt" | "hypot" | "sinh"
| "cosh" | "tanh" | "asinh" | "acosh" | "atanh" | "IEEEremainder",
) => "double",
("Math", "getExponent") => "int",
// `StrictMath`'s own two; every other `StrictMath` member is aliased
// to `Math` by the parser (see `strict_math_alias`).
("StrictMath", "sin" | "cos") => "double",
("Float", "parseFloat") => "float",
("Float", "valueOf") => "Float",
("Float", "toString") => "String",
("Double" | "Float", "toHexString") => "String",
("Float", "compare") => "int",
("Float", "isNaN") | ("Float", "isInfinite") => "boolean",
("Double", "doubleToLongBits" | "doubleToRawLongBits") => "long",
("Double", "longBitsToDouble") => "double",
("Float", "floatToIntBits" | "floatToRawIntBits") => "int",
("Float", "intBitsToFloat") => "float",
("Integer", "toString") | ("String", "valueOf") | ("String", "format") => "String",
("Arrays", "toString" | "deepToString") => "String",
("Arrays", "hashCode" | "deepHashCode") => "int",
// The collection factories answer the interface type, which is what
// lets a call such as `l.remove(List.of(x))` select `remove(Object)`.
("List", "of" | "copyOf") | ("Arrays", "asList") => "List",
("Set", "of" | "copyOf")
| ("Collections", "emptySet" | "singleton" | "emptySortedSet" | "emptyNavigableSet") => {
"Set"
}
("Collections", "nCopies" | "list") => "List",
("Map", "of" | "copyOf" | "ofEntries") | ("Collections", "emptyMap" | "singletonMap") => {
"Map"
}
("Boolean", "parseBoolean") => "boolean",
("Boolean", "valueOf") => "Boolean",
("Collections", "addAll" | "disjoint") => "boolean",
("Collections", "frequency" | "binarySearch" | "indexOfSubList" | "lastIndexOfSubList") => {
"int"
}
// `Character.toUpperCase(char)` returns a `char`, so its result keeps
// rendering as a character rather than as a code point.
("Character", "toUpperCase" | "toLowerCase" | "toTitleCase" | "reverseBytes") => "char",
("Short", "reverseBytes") => "short",
("Math", "multiplyHigh" | "unsignedMultiplyHigh") => "long",
("Character", "toString" | "getName") => "String",
("Character", "getNumericValue" | "getType") => "int",
(
"Character",
"isIdeographic"
| "isDefined"
| "isDigit"
| "isLetter"
| "isLetterOrDigit"
| "isWhitespace"
| "isUpperCase"
| "isLowerCase"
| "isAlphabetic"
| "isSpaceChar"
| "isISOControl"
| "isJavaIdentifierStart"
| "isJavaIdentifierPart",
) => "boolean",
("Character", "toChars") => "char[]",
("Character", "highSurrogate" | "lowSurrogate") => "char",
(
"Character",
"isSurrogate"
| "isHighSurrogate"
| "isLowSurrogate"
| "isSurrogatePair"
| "isValidCodePoint"
| "isBmpCodePoint"
| "isSupplementaryCodePoint",
) => "boolean",
("Character", "toCodePoint" | "codePointAt" | "codePointBefore" | "codePointCount") => {
"int"
}
("String", "copyValueOf") => "String",
("Character", "forDigit") => "char",
("Character", "digit" | "compare" | "charCount") => "int",
("Double" | "Float", "isFinite") => "boolean",
("Double", "max" | "min" | "sum") => "double",
("Float", "max" | "min" | "sum") => "float",
("Boolean", "logicalAnd" | "logicalOr" | "logicalXor") => "boolean",
(
"Integer",
"decode" | "parseUnsignedInt" | "compareUnsigned" | "divideUnsigned"
| "remainderUnsigned",
) => "int",
("Integer", "toUnsignedLong") => "long",
("Long", "divideUnsigned" | "remainderUnsigned") => "long",
("Long", "compareUnsigned") => "int",
("Long", "decode") => "long",
("Integer" | "Long", "toUnsignedString") => "String",
("Short", "parseShort") => "short",
("Byte", "parseByte") => "byte",
("Short" | "Byte", "compare" | "hashCode" | "toUnsignedInt") => "int",
("Short" | "Byte", "toString") => "String",
_ => return None,
})
}
/// The static numeric category of a known stdlib static call, when it is
/// statically `int`-typed (so it participates in `/` truncation). Methods whose
/// result is `int`-or-`double` at runtime (`Math.abs`/`max`/`min`) stay `None`
/// (treated as `Other`) rather than mis-typing a `double` result as `int`.
fn static_call_numtype(class: &str, method: &str) -> Option<NumType> {
match (class, method) {
("Integer", "parseInt") | ("Integer", "valueOf") => Some(NumType::Int),
("Long", "parseLong") | ("Long", "valueOf") => Some(NumType::Int),
("Short", "valueOf") | ("Byte", "valueOf") | ("Character", "valueOf") => Some(NumType::Int),
("Math", "round") => Some(NumType::Int),
_ => None,
}
}
/// The `java.util` collection types javars models, mapped to the collection
/// *shape* the host allocates. A user class of the same name wins (the compiler
/// checks `self.classes` first), so declaring your own `List` is still legal.
/// True when `e` is an explicit *boxing* call — `Integer.valueOf(x)` and the
/// other wrapper factories. Its static Java type in Java is the wrapper class,
/// but javars types it as the primitive it wraps (so `Integer.valueOf(7) / 2`
/// still truncates), which leaves the reference-ness invisible to
/// `expr_java_type`. The one place that distinction changes an *answer* is
/// `List.remove`, where the wrapper picks `remove(Object)` and the primitive
/// picks `remove(int)`, so it is recognised syntactically here.
/// The comparator `Comparator.naturalOrder()` denotes, as a lambda expression:
/// `(a, b) -> a.compareTo(b)`. Synthesized for the sorts that name no
/// comparator, so they order by the element's own `compareTo` through the same
/// erased-receiver dispatch every other `compareTo` call uses. The `#` in the
/// parameter names is not a legal Java identifier character, so they cannot
/// collide with (or be shadowed by) a user variable.
fn natural_order_comparator(line: u32) -> Expr {
let (a, b) = ("#cmp0".to_string(), "#cmp1".to_string());
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: "compareTo".to_string(),
args: vec![Expr::Var(b)],
line,
})),
line,
}
}
/// The comparator `Map.Entry.comparingByKey()` denotes, as a lambda:
/// `(a, b) -> a.getKey().compareTo(b.getKey())` — and the same with `getValue`
/// for `comparingByValue()`. The `#` in the parameter names is not a legal Java
/// identifier character, so they cannot collide with a user variable.
fn entry_comparator(accessor: &str, line: u32) -> Expr {
let (a, b) = ("#ent0".to_string(), "#ent1".to_string());
let read = |v: String| Expr::MethodCall {
recv: Box::new(Expr::Var(v)),
method: accessor.to_string(),
args: vec![],
line,
};
Expr::Lambda {
params: vec![a.clone(), b.clone()],
finals: Vec::new(),
body: LambdaBody::Expr(Box::new(Expr::MethodCall {
recv: Box::new(read(a)),
method: "compareTo".to_string(),
args: vec![read(b)],
line,
})),
line,
}
}
fn is_boxing_call(e: &Expr) -> bool {
matches!(
e,
Expr::MethodCall { recv, method, args, .. }
if method == "valueOf"
&& args.len() == 1
&& matches!(
recv.as_ref(),
Expr::Var(c) if matches!(
c.as_str(),
"Integer" | "Long" | "Short" | "Byte" | "Character"
| "Double" | "Float" | "Boolean"
)
)
)
}
/// The declared Java return type of a `StringBuilder`/`StringBuffer` method.
///
/// The mutators all answer `this`, which is what makes a chain
/// (`sb.append(1).append('a')`) keep its static type — and therefore keep
/// reaching this table for the next link. `charAt` is the entry that has to be
/// here rather than left unknown: it answers a `char`, and an untyped code
/// point renders as its number.
fn builder_call_java_type(recv_ty: &str, method: &str, argc: usize) -> Option<&'static str> {
let this = match recv_ty {
"StringBuilder" => "StringBuilder",
"StringBuffer" => "StringBuffer",
_ => return None,
};
Some(match (method, argc) {
("append", 1)
// `append(char[], int, int)` answers the receiver like every other
// `append`; without it a chained call lost the builder's static type
// and the second link dispatched as a `String` method.
| ("append", 3)
| ("appendCodePoint", 1)
| ("insert", 2)
| ("delete", 2)
| ("deleteCharAt", 1)
| ("replace", 3)
| ("reverse", 0)
| ("repeat", 2) => this,
("toString", 0) | ("substring", 1) | ("substring", 2) | ("subSequence", 2) => "String",
("length", 0)
| ("capacity", 0)
| ("indexOf", 1)
| ("indexOf", 2)
| ("lastIndexOf", 1)
| ("lastIndexOf", 2)
| ("codePointAt", 1)
| ("codePointBefore", 1)
| ("codePointCount", 2)
| ("compareTo", 1) => "int",
("charAt", 1) => "char",
("isEmpty", 0) | ("equals", 1) => "boolean",
_ => return None,
})
}
/// True when a static call is one of the `Math` methods overloaded on argument
/// width, at an arity one of those overloads has.
///
/// The set is closed and small, and the arity is part of it: `Math.clamp` takes
/// three arguments and the `Exact` family two (one for `toIntExact`), so a
/// user's own `Math`-named static cannot fall in by having the same name.
fn is_width_overloaded(class: &str, method: &str, argc: usize) -> bool {
class == "Math"
&& match method {
"addExact" | "subtractExact" | "multiplyExact" | "divideExact" | "floorDivExact"
| "ceilDivExact" => argc == 2,
"toIntExact" | "incrementExact" | "decrementExact" | "negateExact" | "absExact" => {
argc == 1
}
"clamp" => argc == 3,
_ => false,
}
}
/// True when argument `i` of a collection call is an **index** rather than an
/// element or a key.
///
/// `java.util.List` is the only one of the three that takes an `int` position,
/// and the set of methods that do is closed — so the table is the whole
/// question rather than a heuristic. Getting it wrong in either direction is
/// silent: an index boxed as an `Integer` would index nothing, and an element
/// left unboxed would compare by value where Java compares references.
/// `remove(int)` is here because the by-value overload has already been renamed
/// to `removeObject` by the time this is asked.
fn list_index_arg(kind: &str, method: &str, argc: usize, i: usize) -> bool {
kind == "list"
&& matches!(
(method, argc, i),
("get", 1, 0)
| ("remove", 1, 0)
| ("set", 2, 0)
| ("add", 2, 0)
| ("addAll", 2, 0)
| ("listIterator", 1, 0)
| ("subList", 2, 0)
| ("subList", 2, 1)
)
}
/// The spans an array of `n` elements is gathered in, in order.
///
/// Java puts no bound on an array initializer's length and the VM passes an
/// argument count in a `u8`, so one call cannot carry more than 255 elements.
/// Emitting `n as u8` truncated the count silently: a 4000-element table became
/// a 160-element one holding the *last* 160 values, and every index into it
/// read the wrong element or ran off the end. The elements are pushed and
/// gathered a chunk at a time instead — invisible for the lengths a program
/// usually writes (one span, exactly the call it emitted before) and correct
/// for the lengths a lookup table occasionally reaches.
///
/// The first span makes the array and may hold 255; each later one appends to
/// the array already on the stack, which costs one of the 255 slots.
fn array_build_chunks(n: usize) -> Vec<std::ops::Range<usize>> {
const FIRST: usize = u8::MAX as usize;
const REST: usize = FIRST - 1;
let head = n.min(FIRST);
let mut spans = Vec::new();
spans.push(0..head);
let mut at = head;
while at < n {
let end = (at + REST).min(n);
spans.push(at..end);
at = end;
}
spans
}
/// The op that gathers the `len` values on top of the stack: the first span
/// builds the array, every later one appends to it.
fn array_build_op(span_index: usize, len: usize) -> Op {
if span_index == 0 {
Op::CallBuiltin(crate::host::JARRAY_LIT, len as u8)
} else {
Op::CallBuiltin(crate::host::JARRAY_EXTEND, len as u8 + 1)
}
}
fn collection_kind(ty: &str) -> Option<&'static str> {
Some(match ty {
"ArrayList" | "LinkedList" | "ArrayDeque" | "Vector" | "Stack" => "list",
"List" | "Collection" | "Iterable" | "Deque" | "Queue" => "list",
"HashMap" | "LinkedHashMap" | "TreeMap" | "EnumMap" | "Map" | "SortedMap"
| "NavigableMap" => "map",
"HashSet" | "LinkedHashSet" | "TreeSet" | "EnumSet" | "Set" | "SortedSet"
| "NavigableSet" => "set",
// Not a `List`: it has no `remove(int)`, so an integral argument is an
// element there, never an index.
"PriorityQueue" => "pq",
// `Map.Entry`, which the type parser flattens to its simple name. It is
// not a collection, but it reaches the host down the same route: the
// dispatch builtin takes any receiver whose methods the host models,
// and `entry_method` answers before the collection tables are consulted.
"Entry" | "SimpleEntry" | "SimpleImmutableEntry" => "entry",
_ => return None,
})
}
/// True when `ty` names a collection *implementation* — the types `new` can
/// construct. The interfaces (`List`, `Map`, `Set`) are declaration-only.
/// The modeled stdlib types whose no-argument constructor a `T::new` reference
/// can name. The collection implementations plus the three other types Java
/// programs default-construct.
fn has_no_arg_constructor(ty: &str) -> bool {
is_concrete_collection(ty)
|| matches!(
ty,
"String" | "StringBuilder" | "StringBuffer" | "Object" | "PriorityQueue"
)
}
fn is_concrete_collection(ty: &str) -> bool {
matches!(
ty,
"ArrayList"
| "LinkedList"
| "ArrayDeque"
| "Vector"
| "Stack"
| "HashMap"
| "LinkedHashMap"
| "TreeMap"
| "HashSet"
| "LinkedHashSet"
| "TreeSet"
)
}
/// The declared Java return type of a collection method, for the ones whose
/// result javars can type statically. `get`/`put`/`remove` return the erased
/// element type, which javars does not track, so they stay unknown.
fn collection_call_java_type(kind: &str, method: &str, argc: usize) -> Option<&'static str> {
Some(match (method, argc) {
("size", 0) | ("indexOf", 1) | ("lastIndexOf", 1) => "int",
("isEmpty", 0) | ("contains", 1) | ("containsKey", 1) | ("containsValue", 1) => "boolean",
("empty", 0) if kind == "list" => "boolean",
("search", 1) | ("capacity", 0) if kind == "list" => "int",
("add", 1) | ("addAll", 1) | ("equals", 1) => "boolean",
("remove", 1) if kind == "set" || kind == "pq" => "boolean",
// The compiler-selected `List.remove(Object)` overload.
("removeObject" | "removeFirstOccurrence" | "removeLastOccurrence", 1) => "boolean",
("toString", 0) => "String",
("keySet", 0) => "Set",
("entrySet", 0) => "Set",
("values", 0) => "List",
// A `Map.Entry`'s own methods. `getKey`/`getValue` answer the erased
// key and value types, which javars does not track, so they stay
// unknown — the same place `Map.get` leaves its result.
("setValue", 1) if kind == "entry" => return None,
// A `subList` view is a `List`, so methods chain off it and a nested
// `subList` resolves through the collection path rather than falling
// through to the `String` methods.
("subList", 2) if kind == "list" => "List",
// The navigable range and descending views, which chain as the
// collections they are.
("headMap" | "tailMap", 1 | 2) | ("subMap", 2 | 4) | ("descendingMap", 0)
if kind == "map" =>
{
"NavigableMap"
}
("navigableKeySet" | "descendingKeySet", 0) if kind == "map" => "NavigableSet",
("headSet" | "tailSet", 1 | 2) | ("subSet", 2 | 4) | ("descendingSet", 0)
if kind == "set" =>
{
"NavigableSet"
}
("removeAll", 1) | ("retainAll", 1) | ("containsAll", 1) => "boolean",
_ => return None,
})
}
/// The parameter count of a modeled stdlib static a method reference can name.
///
/// Only the single-arity entries are listed: `Integer.toString` and
/// `String.valueOf` take one *or* two arguments in Java, and a method reference
/// to an overloaded name has no arity until it is target-typed — which javars
/// does not do — so naming one is an error rather than a guess.
/// The argument count (receiver excluded) of a collection instance method an
/// unbound reference can name. Only names with one arity across `List`, `Set`,
/// `Map`, and `Map.Entry` are listed: `remove` is overloaded in `List` on the
/// argument's type (`remove(int)` and `remove(Object)`), so `javac` would need
/// the target type to choose. `add` is listed at its one-argument reading: the
/// other, `add(int, E)`, needs a three-parameter target that no
/// `java.util.function` interface declares, so a reference to it with any JDK
/// functional type is `add(E)` — the accumulator of `collect(ArrayList::new,
/// ArrayList::add, ArrayList::addAll)`.
fn collection_instance_ref_arity(method: &str) -> Option<usize> {
Some(match method {
"stream" | "size" | "isEmpty" | "iterator" | "keySet" | "values" | "entrySet"
| "getKey" | "getValue" | "clear" | "toString" | "hashCode" => 0,
"contains" | "containsKey" | "containsValue" | "get" | "add" | "addAll" | "putAll"
| "equals" => 1,
"put" => 2,
_ => return None,
})
}
/// The parameter counts of a modeled stdlib static overloaded on *arity*,
/// whose reference only a target's arity resolves: `Arrays::stream` is
/// `stream(T[])` for a one-parameter interface and the `(array, from, to)`
/// form for a three-parameter one. Each is static-only, so no instance method
/// makes the reference ambiguous the way `Integer::toString` is.
fn stdlib_static_ref_arities(class: &str, method: &str) -> &'static [usize] {
match (class, method) {
("Arrays", "stream") => &[1, 3],
("Objects", "toString" | "requireNonNull") => &[1, 2],
_ => &[],
}
}
/// The parameter count of the functional interface a JDK method takes as
/// argument `i` of `n`, for the names whose every overload agrees: a stream's
/// `map`/`filter`/`flatMap*`/`forEach`… take one, its `reduce` and `sorted`
/// two.
fn jdk_functional_arity(method: &str, n: usize, i: usize) -> Option<usize> {
match (method, n, i) {
(
"map" | "filter" | "flatMap" | "flatMapToInt" | "flatMapToLong" | "flatMapToDouble"
| "mapToObj" | "mapToInt" | "mapToLong" | "mapToDouble" | "forEach" | "forEachOrdered"
| "peek" | "anyMatch" | "allMatch" | "noneMatch" | "takeWhile" | "dropWhile"
| "removeIf" | "ifPresent",
1,
0,
) => Some(1),
("sorted" | "min" | "max" | "reduce", 1, 0) | ("reduce", 2, 1) => Some(2),
_ => None,
}
}
fn stdlib_static_ref_arity(class: &str, method: &str) -> Option<usize> {
Some(match (class, method) {
("Integer", "parseInt")
| ("Long", "parseLong")
| ("Boolean", "parseBoolean")
| ("Math", "sqrt")
| ("Math", "floor")
| ("Math", "ceil")
| ("Math", "round")
| ("Arrays", "toString")
// `String::valueOf` is the commonest mapper in a stream pipeline. Its
// overloads all take one argument, so the arity is unambiguous even
// though the type is not — which is what `javac` needs the target type
// for and javars does not, being dynamically typed underneath.
| ("String", "valueOf")
// The box factories. `Integer.valueOf` is overloaded on *type*
// (`int` and `String`) but not on arity, which is all a reference needs
// here — javars is dynamically typed underneath, so the one synthesized
// lambda serves both.
| ("Integer", "valueOf")
| ("Long", "valueOf")
| ("Double", "valueOf")
| ("Float", "valueOf")
| ("Double", "parseDouble")
// The `java.lang.Math` statics javars models at arity 1, the fdlibm
// transcendentals among them.
| (
"Math",
"sin" | "cos" | "tan" | "asin" | "acos" | "atan" | "exp" | "log" | "log10" | "log1p" | "expm1"
| "cbrt" | "sinh" | "cosh" | "tanh" | "asinh" | "acosh" | "atanh",
)
| ("StrictMath", "sin" | "cos")
| ("Math", "abs")
| ("Math", "signum")
| ("Math", "toRadians")
| ("Math", "toDegrees")
| ("Math", "rint")
| ("Math", "ulp")
| ("Math", "nextUp")
| ("Math", "nextDown")
// The bit-twiddling statics, on both widths.
| ("Integer" | "Long", "bitCount")
| ("Integer" | "Long", "reverse")
| ("Integer" | "Long", "reverseBytes")
| ("Integer" | "Long", "highestOneBit")
| ("Integer" | "Long", "lowestOneBit")
| ("Integer" | "Long", "numberOfLeadingZeros")
| ("Integer" | "Long", "numberOfTrailingZeros")
| ("Integer" | "Long", "signum")
// `Objects::toString` and `Objects::requireNonNull` are overloaded on
// *arity* (1 and 2), so neither has an unambiguous one and neither is
// here; `javac` picks by target type, which [`stdlib_static_ref_arities`]
// resolves from the target's arity.
//
// `Integer::hashCode` and its siblings are absent for a stronger
// reason: `javac` *rejects* them. The static `hashCode(int)` and the
// inherited `hashCode()` both match an arity-1 reference, and the
// error is "reference to hashCode is ambiguous" — measured on
// openjdk 21.0.12.1 — so listing one here would make javars run a
// program the reference refuses to compile.
| ("Objects", "isNull")
| ("Objects", "nonNull")
| ("Objects", "hashCode")
// `Character`'s predicates and `getNumericValue` are overloaded on
// `char` and `int` only, and `Character` declares no instance method of
// the same name, so a reference to one is unambiguous. The case maps
// answer in their argument's type — `(int)` an `int`, `(char)` a `char` —
// which the lambda the reference desugars to reads off its parameter, typed
// from the stream or collection it is handed to (`lambda_param_generics`).
// `toChars` has a three-argument overload javars does not model, so the
// one-argument form is the only reading. `getName` takes an `int` only. The surrogate predicates are
// `(char)` only, which javac refuses an `IntStream` element for and javars
// accepts.
//
// `Character::toString` names the static `toString(char)`/`(int)` and
// the instance `toString()`. `javac` rejects it as ambiguous wherever
// the element is a `Character` and selects the static `(int)` overload
// wherever it is an `int` or `Integer` (`Stream.of(65)` maps to `"A"`),
// so the static call is the reading of every program it compiles.
| (
"Character",
"isLetter" | "isDigit" | "isLetterOrDigit" | "isAlphabetic" | "isWhitespace"
| "isSpaceChar" | "isUpperCase" | "isLowerCase" | "isISOControl"
| "isJavaIdentifierStart" | "isJavaIdentifierPart" | "getNumericValue"
| "charCount" | "toString"
| "toUpperCase" | "toLowerCase" | "toTitleCase" | "toChars" | "isDefined" | "getName"
| "isIdeographic" | "getType" | "isSurrogate" | "isHighSurrogate"
| "isLowSurrogate" | "isValidCodePoint" | "isBmpCodePoint"
| "isSupplementaryCodePoint",
)
=> 1,
("Math", "max") | ("Math", "min") | ("Math", "pow") => 2,
// `Integer::sum` is the canonical `reduce`/`merge` operator and was the
// reference this table most often refused.
("Integer" | "Long", "sum") => 2,
("Integer" | "Long", "max") | ("Integer" | "Long", "min") => 2,
("Integer" | "Long" | "Double" | "Boolean", "compare") => 2,
("Integer" | "Long", "rotateLeft") | ("Integer" | "Long", "rotateRight") => 2,
("Math", "floorDiv") | ("Math", "floorMod") | ("Math", "copySign") => 2,
("Math", "atan2" | "hypot" | "IEEEremainder") => 2,
("Objects", "equals") | ("Objects", "requireNonNullElse") => 2,
// The floating wrappers' operators, the `reduce` identities of a
// `double` pipeline. Each is static-only, so no instance method makes
// the reference ambiguous.
("Double" | "Float", "sum" | "max" | "min") => 2,
// The radix renderings, static-only on both widths.
("Integer" | "Long", "toBinaryString" | "toHexString" | "toOctalString") => 1,
// The remaining static-only wrapper members with a single public arity.
("Float", "parseFloat") | ("Double" | "Float", "isFinite") | ("Integer" | "Long", "decode") => 1,
("Boolean", "logicalAnd" | "logicalOr" | "logicalXor") => 2,
// The `Collections` factories and wrappers with one public arity — the
// finisher a `collectingAndThen` is written with
// (`Collections::unmodifiableList`). `max`/`min`/`sort`/`shuffle` are
// public at two arities, so only the target type could choose, and
// they stay out for the reason `Objects::toString` does.
("Collections", "emptyList" | "emptySet" | "emptyMap") => 0,
(
"Collections",
"unmodifiableList"
| "unmodifiableSet"
| "unmodifiableMap"
| "unmodifiableCollection"
| "unmodifiableSortedSet"
| "unmodifiableSortedMap"
| "unmodifiableNavigableSet"
| "unmodifiableNavigableMap"
| "synchronizedList"
| "synchronizedSet"
| "synchronizedMap"
| "synchronizedCollection"
| "singletonList"
| "singleton"
| "reverse",
) => 1,
("Collections", "nCopies" | "frequency" | "disjoint" | "singletonMap") => 2,
_ => return None,
})
}
/// The parameter count of a `String` instance method a method reference can name
/// (`String::length` → 0, so the synthesized lambda takes 1: the receiver).
/// `substring` and `indexOf` are overloaded on arity in Java and so are absent.
/// The parameter count of an unbound instance-method reference on a wrapper
/// class (`Integer::intValue`), *excluding* the receiver, or `None` for a name
/// no box answers.
///
/// The set is `Number`'s six converters, `Boolean.booleanValue`,
/// `Character.charValue`, and the two `Object` methods a box overrides — the
/// same set [`crate::host::boxed_method`] serves, because a reference that
/// desugars to a call javars cannot make would be a worse error than refusing
/// the reference.
fn boxed_instance_ref_arity(method: &str) -> Option<usize> {
Some(match method {
"intValue" | "longValue" | "shortValue" | "byteValue" | "doubleValue" | "floatValue"
| "booleanValue" | "charValue" | "hashCode" | "toString" => 0,
"equals" | "compareTo" => 1,
_ => return None,
})
}
/// The parameter count of a `StringBuilder` instance method an unbound
/// reference can name, receiver excluded. `append` is overloaded on its
/// argument's type but has one single-argument reading per type, which is all
/// a dynamically typed call needs.
fn builder_instance_ref_arity(method: &str) -> Option<usize> {
Some(match method {
"reverse" | "toString" | "length" => 0,
"append" | "charAt" => 1,
_ => return None,
})
}
fn string_instance_ref_arity(method: &str) -> Option<usize> {
Some(match method {
"length" | "isEmpty" | "toUpperCase" | "toLowerCase" | "trim" | "strip"
| "stripLeading" | "stripTrailing" | "isBlank" | "chars" | "codePoints" | "lines"
| "intern" | "hashCode" => 0,
"charAt"
| "matches"
| "contentEquals"
| "contains"
| "startsWith"
| "endsWith"
| "equals"
| "equalsIgnoreCase"
| "concat"
| "repeat"
| "compareTo"
| "compareToIgnoreCase" => 1,
"replace" => 2,
_ => return None,
})
}
/// True when a statement is a loop or `switch` — a construct that owns its own
/// [`BreakScope`] and therefore consumes a prefixing label directly.
fn is_breakable(s: &Stmt) -> bool {
matches!(
s.kind,
StmtKind::While { .. }
| StmtKind::DoWhile { .. }
| StmtKind::For { .. }
| StmtKind::ForEach { .. }
| StmtKind::Switch { .. }
)
}
/// The value and Java type of a `static final` constant on a `java.lang` type
/// (`Integer.MAX_VALUE`, `Double.NaN`, `Math.PI`, …).
///
/// javars does not model the wrapper classes as classes, so these are folded to
/// their literal value at compile time rather than read from a field.
fn wrapper_constant(class: &str, name: &str) -> Option<(Value, &'static str)> {
Some(match (class, name) {
// `java.util.Locale`'s English constants and `ROOT`, modeled as the
// text their `toString()` answers. Each formats numbers exactly as the
// root locale javars always formats in, which is why only these are
// named: `Locale.GERMANY` would need a `,` decimal separator.
("Locale", "ROOT") => (Value::str(String::new()), "Locale"),
("Locale", "US") => (Value::str("en_US".to_string()), "Locale"),
("Locale", "UK") => (Value::str("en_GB".to_string()), "Locale"),
("Locale", "ENGLISH") => (Value::str("en".to_string()), "Locale"),
("Locale", "CANADA") => (Value::str("en_CA".to_string()), "Locale"),
// `java.nio.charset.StandardCharsets`: a `Charset` is modeled as its
// canonical name, which is also what its `toString()` answers.
("StandardCharsets", "UTF_8") => (Value::str("UTF-8".to_string()), "Charset"),
("StandardCharsets", "ISO_8859_1") => (Value::str("ISO-8859-1".to_string()), "Charset"),
("StandardCharsets", "US_ASCII") => (Value::str("US-ASCII".to_string()), "Charset"),
("Integer", "MAX_VALUE") => (Value::Int(i32::MAX as i64), "int"),
("Integer", "MIN_VALUE") => (Value::Int(i32::MIN as i64), "int"),
("Long", "MAX_VALUE") => (Value::Int(i64::MAX), "long"),
("Long", "MIN_VALUE") => (Value::Int(i64::MIN), "long"),
("Short", "MAX_VALUE") => (Value::Int(i16::MAX as i64), "short"),
("Short", "MIN_VALUE") => (Value::Int(i16::MIN as i64), "short"),
("Byte", "MAX_VALUE") => (Value::Int(i8::MAX as i64), "byte"),
("Byte", "MIN_VALUE") => (Value::Int(i8::MIN as i64), "byte"),
// `char` is unsigned, so its bounds are not a signed type's: Java's
// `Character.MIN_VALUE` is `'