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
//! Java source emission from the statement/expression tree.
use crate::types::JavaType;
use crate::ctx::MethodBody;
use crate::ir::expr::{BinOp, ConcatPart, ConstVal, Expr, LambdaKind, TypeRef, UnOp};
use crate::ir::stmt::{CaseGroup, Catch, Stmt};
use crate::var::VarTable;
pub struct Printer<'a> {
/// Front-end services: naming, nesting, type queries, nested bodies.
pub ctx: &'a dyn crate::ctx::Ctx,
pub vt: &'a VarTable,
out: String,
indent: usize,
/// Depth guard for recursive lambda printing.
lambda_depth: usize,
/// Names visible in enclosing lambda/method scopes BEYOND self.vt,
/// accumulated down the lambda print chain: a nested lambda's locals
/// must not redeclare ANY of them (jdk26 PackageSnippets
/// .fooToBarUnrolled: the depth-2 codeBuilder lambda's foreach `i$`
/// collided with the METHOD-level `i$` — the depth-1 rename only
/// consulted depth-1's vt, 已在方法中定义了变量 i$).
outer_names: Vec<String>,
/// Sequence for unbound catch parameters (`ignored`, `ignored2`, …):
/// two catch scopes can NEST (a try inside a catch body) and javac
/// rejects duplicate names across overlapping scopes ("已在方法
/// invokeSuspend(Object)中定义了变量 ignored", weixin hl5/m ×56).
ignored_seq: u32,
/// True when the enclosing method returns boolean.
/// Reused per-statement line buffer (millions of statements: the
/// fresh-String-per-line pattern re-allocated and re-grew each time).
line_buf: String,
pub ret_bool: bool,
/// True while rendering the ROOT of an expression statement: a
/// signature-polymorphic call there must stay bare (`NEXT.compareAndSet
/// (b, n, p);`) — `(boolean) call();` is not a legal statement.
suppress_poly_cast: bool,
/// True while rendering the direct child of a cast expression: a cast
/// gives the diamond NO target type, so ` (T) new X<>(args)` infers
/// Object bounds and then fails the cast — while the bare/raw form
/// `(T) new X(args)` compiles (unchecked).
suppress_diamond: bool,
/// True while rendering a conditional expression's branches. Pre-Java-8
/// (major < 52) conditionals are NOT poly expressions: a diamond branch
/// (`c ? new HashMap<>(..) : new LinkedHashMap<>(..)`) infers each side
/// standalone to <Object,Object> and fails the assignment target (jdk7
/// HashSet.readObject 不兼容的类型 — the golden source carried explicit
/// <E,Object> args). Diamond branches print RAW there instead:
/// unchecked but always compilable.
in_cond: bool,
/// Instantiated SAM return type while rendering the Lambda directly
/// inside a cast to a generic functional interface: the lambda body's
/// returns may need `(R) value` witnesses (jdk17 Collectors
/// `(Function<I,R>) i -> i`).
lambda_sam_ret: Option<TypeRef>,
/// The method's generic signature return (functional-interface or
/// array form): a lambda in RETURN position has no cast node to hang
/// the SAM witness on, so the Return arm derives it from this.
ret_sam: Option<TypeRef>,
/// True when the enclosing method returns char: int constants in the
/// returned expression render as char literals (bytecode chars are
/// ints; `return cond ? 63 : 105;` in a char method is a lossy
/// conversion — source was `? '?' : 'i'`, jdk XML Parser x23).
pub ret_char: bool,
/// Narrowing-return markers: int-valued expressions in the return
/// need `(byte)`/`(short)` casts (jdk11 MemberName:
/// `byte normalVirtual = cond ? 5 : 9;`).
pub ret_byte: bool,
pub ret_short: bool,
/// Memoized twin-exists probe for the same-package member-shadow
/// check, keyed by first segment (class_name is constant per ctx;
/// shared with sub-printers). The chain-walk does up to 4 registry
/// lookups per level — per-call that cost ~30% on weixin; per
/// distinct segment it is amortized to nothing.
twin_cache: std::rc::Rc<
std::cell::RefCell<std::collections::HashMap<String, bool>>,
>,
}
impl<'a> Printer<'a> {
pub fn new(ctx: &'a dyn crate::ctx::Ctx, vt: &'a VarTable) -> Self {
Printer {
ctx,
vt,
out: String::new(),
indent: 0,
lambda_depth: 0,
outer_names: Vec::new(),
ignored_seq: 0,
line_buf: String::new(),
ret_bool: false,
suppress_poly_cast: false,
suppress_diamond: false,
in_cond: false,
lambda_sam_ret: None,
ret_sam: None,
ret_char: false,
ret_byte: false,
ret_short: false,
twin_cache: std::rc::Rc::new(std::cell::RefCell::new(
std::collections::HashMap::new(),
)),
}
}
pub fn with_ret_bool(mut self, b: bool) -> Self {
self.ret_bool = b;
self
}
pub fn with_ret_sam(mut self, t: Option<TypeRef>) -> Self {
self.ret_sam = t;
self
}
pub fn with_ret_char(mut self, b: bool) -> Self {
self.ret_char = b;
self
}
pub fn with_ret_narrow(mut self, byte: bool, short: bool) -> Self {
self.ret_byte = byte;
self.ret_short = short;
self
}
/// Printer rendering into a caller-provided buffer: the method text
/// (signature, braces) and the printed body land in ONE string —
/// ddc used to render the body separately and copy it line-by-line
/// into the class buffer (a full extra pass over every method).
pub fn with_output(mut self, out: String) -> Self {
self.out = out;
self
}
/// Printer starting at a fixed indentation level (method bodies at 1).
pub fn with_indent(mut self, indent: usize) -> Self {
self.indent = indent;
self
}
pub fn into_string(mut self, body: &Stmt) -> String {
// The old unconditional truncate_dead_ends rebuilt (deep-cloned)
// the whole statement tree per method — a top profile cost. The
// truncation case is rare: probe read-only first.
if tree_has_dead_end(body) {
let truncated = truncate_dead_ends(body);
self.stmt(&truncated);
} else {
self.stmt(body);
}
self.out
}
/// Print an expression that appears in a boolean context; int 0/1
/// constants become true/false.
fn bool_ish_expr(x: &Expr) -> bool {
match x {
Expr::Const(ConstVal::Int(n)) => *n == 0 || *n == 1,
Expr::Cond { t, f, .. } => {
matches!(&**t, Expr::Const(ConstVal::Int(0 | 1)))
&& matches!(&**f, Expr::Const(ConstVal::Int(0 | 1)))
}
Expr::Un {
op: crate::ir::expr::UnOp::Not,
..
}
| Expr::InstanceOf { .. } => true,
Expr::Bin { op, .. } => matches!(
op,
crate::ir::expr::BinOp::Eq
| crate::ir::expr::BinOp::Ne
| crate::ir::expr::BinOp::Lt
| crate::ir::expr::BinOp::Ge
| crate::ir::expr::BinOp::Gt
| crate::ir::expr::BinOp::Le
| crate::ir::expr::BinOp::RefEq
| crate::ir::expr::BinOp::RefNe
| crate::ir::expr::BinOp::LogAnd
| crate::ir::expr::BinOp::LogOr
),
other => other.type_ref().erased() == crate::types::JavaType::Boolean,
}
}
/// bool_ish_expr with VarTable resolution: booleanize retypes the vt
/// while embedded Local tys stay frozen, and a bitwise bin over
/// bool-ish sides is itself boolean (jdk26 LinkedTransferQueue
/// `(spin & !upc) == 0`).
fn bool_ish_vt(&self, x: &Expr) -> bool {
match x {
Expr::Local { var, .. } => {
matches!(
self.vt.var(*var).ty.erased(),
crate::types::JavaType::Boolean
)
}
Expr::Bin {
op: crate::ir::expr::BinOp::And | crate::ir::expr::BinOp::Or | crate::ir::expr::BinOp::Xor,
l,
r,
..
} => self.bool_ish_vt(l) && self.bool_ish_vt(r),
_ => Self::bool_ish_expr(x),
}
}
pub fn expr_bool(&mut self, e: &Expr, out: &mut String) {
match e {
Expr::Const(ConstVal::Int(n)) => {
out.push_str(if *n != 0 { "true" } else { "false" });
}
// Bitwise ops over boolean-ish operands print as their
// logical form: javac computes `a != b` over booleans as
// IXOR of 0/1 ints (jdk17 DecimalFormat isNegative:
// `(c1 ? 1 : 0) ^ (c2 ? 1 : 0)` against a boolean local —
// "int无法转换为boolean").
Expr::Bin { op: bop, l, r, .. }
if matches!(
bop,
crate::ir::expr::BinOp::Xor
| crate::ir::expr::BinOp::And
| crate::ir::expr::BinOp::Or
) && self.bool_ish_vt(l)
&& self.bool_ish_vt(r) =>
{
let sym = match bop {
crate::ir::expr::BinOp::Xor => "^",
crate::ir::expr::BinOp::And => "&",
_ => "|",
};
// Parenthesize composite sides: expr_bool renders `||`/
// `&&` conditions bare and ^ binds LOOSER than && but
// TIGHTER than || (a || b && c ^ d would regroup).
for (i, side) in [l.as_ref(), r.as_ref()].iter().enumerate() {
if i > 0 {
out.push(' ');
out.push_str(sym);
out.push(' ');
}
let needs = matches!(
side,
Expr::Bin { .. } | Expr::Cond { .. } | Expr::Assign { .. }
);
if needs {
out.push('(');
}
self.expr_bool(side, out);
if needs {
out.push(')');
}
}
}
Expr::Cond { c, t, f } => {
// `x ? true : false` → x ; `x ? false : true` → !x
let tb = const_bool(t);
let fb = const_bool(f);
match (tb, fb) {
(Some(true), Some(false)) => self.expr_bool(c, out),
(Some(false), Some(true)) => {
// !(!x) collapses to x
if let Expr::Un {
op: crate::ir::expr::UnOp::Not,
e: inner,
} = &**c
{
self.expr_bool(inner, out);
} else {
out.push('!');
// expr_bool renders composite conditions bare:
// `!` + `ssign != 45` would regroup as
// `(!ssign) != 45` (jdk26 FloatingDecimal
// "一元运算符 '!' 的操作数类型int错误").
let needs = matches!(
&**c,
Expr::Bin { .. } | Expr::Cond { .. } | Expr::Assign { .. }
);
if needs {
out.push('(');
}
self.expr_bool(c, out);
if needs {
out.push(')');
}
}
}
_ => {
self.expr(c, 3, out);
out.push_str(" ? ");
self.expr_bool(t, out);
out.push_str(" : ");
self.expr_bool(f, out);
}
}
}
_ => self.expr(e, 1, out),
}
}
// ---------------- statements ----------------
/// Unique name for an unbound catch parameter; bound ones take
/// their recorded/var-table name. Uniqueness covers the printer's
/// own sequence, the var table and every enclosing-scope name the
/// lambda chain accumulated (a lambda body may not redeclare a
/// name visible outside it).
fn catch_var_name(&mut self, c: &crate::ir::stmt::Catch) -> String {
if c.var != u32::MAX {
return c
.var_name
.clone()
.unwrap_or_else(|| self.vt.var(c.var).name.clone());
}
loop {
self.ignored_seq += 1;
let name = if self.ignored_seq == 1 {
"ignored".to_string()
} else {
format!("ignored{}", self.ignored_seq)
};
let clash = self.vt.vars.iter().any(|v| v.name == name)
|| self.outer_names.contains(&name);
if !clash {
return name;
}
}
}
fn line(&mut self, s: &str) {
self.push_indent();
self.out.push_str(s);
self.out.push('\n');
}
/// Indentation as one contiguous push (the per-level push_str loop
/// ran per printed line).
fn push_indent(&mut self) {
const UNIT: &str = " "; // 32 spaces
let mut n = self.indent * 4;
while n >= 32 {
self.out.push_str(UNIT);
n -= 32;
}
if n > 0 {
self.out.push_str(&UNIT[..n]);
}
}
/// Render an int-typed expression in a byte/short target: constants
/// and ternary branches get the narrowing cast (javac's conditional
/// expression only narrows when the target type is known — a return
/// or local-decl of byte/short with int constants needs explicit
/// casts: `byte normalVirtual = !if() ? (byte) 5 : (byte) 9;`).
pub fn expr_narrow(&mut self, e: &Expr, ty: &crate::types::JavaType, out: &mut String) {
self.expr_narrow_f(e, ty, false, out)
}
/// `force_consts`: the enclosing conditional's condition is not a
/// compile-time constant, so the whole expression is not a constant
/// expression and javac's assignment-context narrowing does NOT apply
/// to in-range int constants either (byte getDirectionality: `return
/// (ch & 0xFFFE) == 0xFFFE ? -1 : 0` — 从int转换到byte可能会有损失;
/// the source branches are byte static finals the bytecode inlined).
fn expr_narrow_f(
&mut self,
e: &Expr,
ty: &crate::types::JavaType,
force_consts: bool,
out: &mut String,
) {
match e {
Expr::Const(ConstVal::Int(n)) => {
let (lo, hi) = match ty {
crate::types::JavaType::Byte => (-128i64, 127i64),
crate::types::JavaType::Short => (-32768i64, 32767i64),
_ => (i32::MIN as i64, i32::MAX as i64),
};
if force_consts || (*n as i64) < lo || (*n as i64) > hi {
out.push('(');
out.push_str(&self.type_name(&TypeRef::J(ty.clone())));
out.push_str(") ");
}
out.push_str(&n.to_string());
}
Expr::Cond { c, t, f } => {
let force = force_consts || !matches!(&**c, Expr::Const(_));
self.expr(c, 3, out);
out.push_str(" ? ");
let prev = std::mem::replace(&mut self.in_cond, true);
self.expr_narrow_f(t, ty, force, out);
out.push_str(" : ");
self.expr_narrow_f(f, ty, force, out);
self.in_cond = prev;
}
// An int-typed local (typically a branch-merge stack temp)
// under a byte/short target needs the explicit narrowing cast
// (jdk17 InvokerBytecodeGenerator `return stack61;` —
// 从int转换到byte可能会有损失; the merged branches carried
// byte values the evidence widened to int).
Expr::Local { var, .. } => {
if matches!(
(self.vt.var(*var).ty.erased(), ty),
(crate::types::JavaType::Int, crate::types::JavaType::Byte)
| (crate::types::JavaType::Int, crate::types::JavaType::Short)
) {
out.push('(');
out.push_str(&self.type_name(&TypeRef::J(ty.clone())));
out.push_str(") ");
}
self.expr(e, 1, out);
}
_ => self.expr(e, 1, out),
}
}
/// Call-argument variant of expr_narrow: invocation conversion never
/// narrows, so in-range int constants keep the explicit cast too, and
/// int conditionals get it per branch.
fn expr_narrow_arg(&mut self, e: &Expr, ty: &crate::types::JavaType, out: &mut String) {
match e {
Expr::Const(ConstVal::Int(n)) => {
out.push('(');
out.push_str(&self.type_name(&TypeRef::J(ty.clone())));
out.push_str(") ");
out.push_str(&n.to_string());
}
Expr::Cond { c, t, f } => {
self.expr(c, 3, out);
out.push_str(" ? ");
let prev = std::mem::replace(&mut self.in_cond, true);
self.expr_narrow_arg(t, ty, out);
out.push_str(" : ");
self.expr_narrow_arg(f, ty, out);
self.in_cond = prev;
}
_ => self.expr(e, 1, out),
}
}
/// Render an expression in a char-typed target: int constants become
/// char literals, ternary branches recurse (the lossy-conversion fix
/// for `char name2type(..) { return c ? 63 : 105; }`).
pub fn expr_char(&mut self, e: &Expr, out: &mut String) {
match e {
Expr::Const(ConstVal::Int(n)) => push_char_lit(out, *n),
Expr::Cond { c, t, f } => {
self.expr(c, 3, out);
out.push_str(" ? ");
let prev = std::mem::replace(&mut self.in_cond, true);
self.expr_char(t, out);
out.push_str(" : ");
self.expr_char(f, out);
self.in_cond = prev;
}
_ => self.expr(e, 1, out),
}
}
fn stmt(&mut self, s: &Stmt) {
match s {
Stmt::Block(v) => {
for x in v {
self.stmt(x);
}
}
Stmt::ExprStmt(e) => {
if !is_statement_expr(e) {
// Only assignments/calls/inc-dec/new are legal
// expression statements; a leftover pure concat
// (`"" + 48;`) renders as a comment instead.
let mut text = String::new();
self.expr(e, 0, &mut text);
self.line(&format!("/* {text}; */"));
return;
}
let mut line = std::mem::take(&mut self.line_buf);
line.clear();
if matches!(e, Expr::Method { .. }) {
self.suppress_poly_cast = true;
}
self.expr(e, 0, &mut line);
self.suppress_poly_cast = false;
line.push(';');
self.line(&line);
self.line_buf = line;
}
Stmt::LocalDef {
var,
init,
is_final,
force_type,
} => {
let _ = force_type;
let info = self.vt.var(*var);
let mut line = std::mem::take(&mut self.line_buf);
line.clear();
if *is_final {
line.push_str("final ");
}
line.push_str(&self.local_decl_ty(*var, &info.ty));
line.push(' ');
line.push_str(&java_ident(&info.name));
if let Some(e) = init {
line.push_str(" = ");
// A lambda initializing a generically-typed SAM local:
// the declared type is the only record of the
// instantiated SAM return (the indy's
// instantiatedMethodType is erased — IntFunction<T[]>
// records (I)[Object), so prime the lambda-body cast
// from it (jdk11 ForEachOps: `IntFunction<T[]>
// generator = size -> (T[]) new Object[size]` —
// without the cast "lambda 表达式中的返回类型错误").
if let (TypeRef::G(g @ crate::types::GenericType::Class(_)), Expr::Lambda(l)) =
(&info.ty, e)
{
if self.lambda_sam_ret.is_none() {
self.lambda_sam_ret = self.sam_ret_cast(g, &l.sam_name);
}
}
// Assigning a concrete type to a type-variable local
// needs the (erased-away) cast back in source form.
let need_cast =
matches!(&info.ty, TypeRef::G(crate::types::GenericType::TypeVar(_)))
&& e.type_ref() != info.ty;
if need_cast {
line.push('(');
line.push_str(&self.type_name(&info.ty));
line.push_str(") ");
self.expr(e, 14, &mut line);
} else if info.ty.erased() == crate::types::JavaType::Boolean {
self.expr_bool(e, &mut line);
} else if info.ty.erased() == crate::types::JavaType::Char {
self.expr_char(e, &mut line);
} else if info.ty.erased() == crate::types::JavaType::Byte
|| info.ty.erased() == crate::types::JavaType::Short
{
let t = info.ty.erased();
self.expr_narrow(e, &t, &mut line);
} else {
self.expr(e, 1, &mut line);
}
}
line.push(';');
self.line(&line);
self.line_buf = line;
}
Stmt::Return(Some(e)) => {
let mut line = String::from("return ");
if self.ret_bool {
self.expr_bool(e, &mut line);
} else if self.ret_char {
self.expr_char(e, &mut line);
} else if self.ret_byte {
self.expr_narrow(e, &crate::types::JavaType::Byte, &mut line);
} else if self.ret_short {
self.expr_narrow(e, &crate::types::JavaType::Short, &mut line);
} else {
// Lambda in return position of a generic method: the
// SAM return witnesses the erased body value
// (castingIdentity `return i -> (R) i`, toArray
// `() -> (T[]) new Object[]{..}` — jdk17 Collectors).
if let (Some(TypeRef::G(g)), Expr::Lambda(l)) = (&self.ret_sam, e) {
self.lambda_sam_ret = match g {
crate::types::GenericType::Class(_) => {
self.sam_ret_cast(g, &l.sam_name)
}
crate::types::GenericType::Array(_) => Some(TypeRef::G(g.clone())),
_ => None,
};
}
self.expr(e, 1, &mut line);
self.lambda_sam_ret = None;
}
line.push(';');
self.line(&line);
}
Stmt::Return(None) => self.line("return;"),
Stmt::Throw(e) => {
let mut line = String::from("throw ");
self.expr(e, 1, &mut line);
line.push(';');
self.line(&line);
}
Stmt::If {
cond,
then_stmt,
else_stmt,
} => {
self.print_if(cond, then_stmt, else_stmt.as_deref(), "");
}
Stmt::While { cond, body } => {
let mut head = String::from("while (");
if matches!(cond, Expr::Const(ConstVal::Int(1))) {
head.push_str("true");
} else {
head.push_str(&self.cond_str(cond));
}
head.push(')');
self.block_stmt(&head, body);
}
Stmt::DoWhile { body, cond } => {
self.line("do {");
self.indent += 1;
self.stmt(body);
self.indent -= 1;
let mut tail = String::from("} while (");
tail.push_str(&self.cond_str(cond));
tail.push_str(");");
self.line(&tail);
}
Stmt::For {
init,
cond,
update,
body,
} => {
let mut head = String::from("for (");
for (i, s) in init.iter().enumerate() {
if i > 0 {
head.push_str(", ");
}
self.stmt_inline(s, &mut head);
}
head.push_str("; ");
if let Some(c) = cond {
let cs = self.cond_str(c);
head.push_str(&cs);
}
head.push_str("; ");
for (i, u) in update.iter().enumerate() {
if i > 0 {
head.push_str(", ");
}
self.expr(u, 1, &mut head);
}
head.push(')');
self.block_stmt(&head, body);
}
Stmt::ForEach {
var,
iterable,
is_array,
body,
} => {
let _ = is_array;
let info = self.vt.var(*var);
let mut head = String::from("for (");
head.push_str(&self.type_name(&info.ty));
head.push(' ');
head.push_str(&java_ident(&info.name));
head.push_str(" : ");
self.expr(iterable, 1, &mut head);
head.push(')');
self.block_stmt(&head, body);
}
Stmt::Switch {
selector,
cases,
default,
on_string,
} => {
let _ = on_string;
let mut head = String::from("switch (");
self.expr(selector, 1, &mut head);
head.push(')');
self.line(&format!("{} {{", head));
self.indent += 1;
for c in cases {
// MULTIPLE pattern labels in one arm cannot share a
// colon body: neither stacked (`case P1 x:` `case P2
// y:` — 贯穿到模式非法) nor comma-joined (`case P1 x,
// P2 y:` — javac still demands a break between pattern
// labels) compile. Duplicate the body per label — the
// source's arrow-form multi-pattern arm
// (`case A _, B _ -> r;`, jdk26 ParserVerifier
// valueSize) in colon form.
if c.raw_labels.len() > 1
&& c.labels.is_empty()
&& c.string_labels.is_empty()
&& c.enum_labels.is_empty()
{
for l in &c.raw_labels {
match &c.guard {
Some(g) => {
let mut gtxt = String::new();
self.expr(g, 1, &mut gtxt);
self.line(&format!("case {} when {}:", l, gtxt));
}
None => self.line(&format!("case {}:", l)),
}
self.line("{");
self.indent += 1;
for st in &c.body {
self.stmt(st);
}
self.indent -= 1;
self.line("}");
}
continue;
}
for l in &c.enum_labels {
self.line(&format!("case {}:", l));
}
if let Some(g) = &c.guard {
// Folded pattern guard: the desugared restart shape
// (`if (guard) body else { state=N; continue; }`)
// restored to `case T v when guard:` (jdk26
// DecimalFormat — duplicate type-pattern labels are
// "此 case 标签由前一个 case 标签支配" without it).
let mut gtxt = String::new();
self.expr(g, 1, &mut gtxt);
let joined = c
.raw_labels
.iter()
.map(|l| format!("{} when {}", l, gtxt))
.collect::<Vec<_>>()
.join(", ");
self.line(&format!("case {}:", joined));
} else if !c.raw_labels.is_empty() {
// Pattern labels of one arm MUST be comma-joined:
// stacked `case P1 x:` / `case P2 y:` lines are a
// fall-through between patterns ("从模式贯穿非法",
// jdk26 ParserVerifier `case OfConstant _,
// OfClass _ -> 2`).
self.line(&format!("case {}:", c.raw_labels.join(", ")));
}
for l in &c.labels {
self.line(&format!("case {}:", l));
}
for l in &c.string_labels {
self.line(&format!("case \"{}\":", escape_string(l)));
}
// Braces give each case its own scope: pattern-switch
// restorations reuse binding names across cases.
self.line("{");
self.indent += 1;
for st in &c.body {
self.stmt(st);
}
self.indent -= 1;
self.line("}");
}
if let Some(d) = default {
self.line("default:");
self.indent += 1;
self.stmt(d);
self.indent -= 1;
}
self.indent -= 1;
self.line("}");
}
Stmt::Try {
body,
catches,
finally,
} => {
self.line("try {");
self.indent += 1;
self.stmt(body);
self.indent -= 1;
for c in catches {
let exc_name = if c.exc.is_empty() {
"Throwable".to_string()
} else {
c.exc
.iter()
.map(|e| self.shorten(e))
.collect::<Vec<_>>()
.join(" | ")
};
let var_name = self.catch_var_name(c);
self.line(&format!("}} catch ({} {}) {{", exc_name, var_name));
self.indent += 1;
self.stmt(&c.body);
self.indent -= 1;
}
if let Some(f) = finally {
self.line("} finally {");
self.indent += 1;
self.stmt(f);
self.indent -= 1;
}
// A try with no catches and no finally is not valid Java
// (the structurer can emit a bare degenerate try); an
// empty finally keeps the statement compilable.
if catches.is_empty() && finally.is_none() {
self.line("} finally {");
}
self.line("}");
}
Stmt::TryWithResources {
resources,
body,
catches,
finally,
} => {
let mut res: Vec<String> = Vec::new();
for r in resources {
if let Stmt::LocalDef { var, init, .. } = r {
let info = self.vt.var(*var);
let mut t = String::new();
t.push_str(&self.type_name(&info.ty));
t.push(' ');
t.push_str(&java_ident(&info.name));
if let Some(e) = init {
t.push_str(" = ");
self.expr(e, 1, &mut t);
}
res.push(t);
} else {
// The resource is not a declaration: a reused
// variable was rewritten to a plain assignment by
// dedupe_declarations, and `try (x = expr)` is not
// Java. Print it as the statement it is, BEFORE the
// try (resource init runs before the body anyway) —
// emitting nothing turned the header into the
// illegal `try () {`.
self.stmt(r);
}
}
if res.is_empty() && catches.is_empty() && finally.is_none() {
// Vestigial try-with-resources: the resource was
// hoisted into a plain assignment above and its close
// is a sibling statement, so nothing is left to head
// the statement — a bare `try {` does not compile
// ("'try' without 'catch', 'finally' or resource
// declarations"). A handler-less try IS a block.
self.line("{");
} else if res.is_empty() {
self.line("try {");
} else {
self.line(&format!("try ({}) {{", res.join("; ")));
}
self.indent += 1;
self.stmt(body);
self.indent -= 1;
for c in catches {
let exc_name = if c.exc.is_empty() {
"Throwable".to_string()
} else {
c.exc
.iter()
.map(|e| self.shorten(e))
.collect::<Vec<_>>()
.join(" | ")
};
let var_name = self.catch_var_name(c);
self.line(&format!("}} catch ({} {}) {{", exc_name, var_name));
self.indent += 1;
self.stmt(&c.body);
self.indent -= 1;
}
if let Some(f) = finally {
self.line("} finally {");
self.indent += 1;
self.stmt(f);
self.indent -= 1;
}
self.line("}");
}
Stmt::Assert { cond, msg } => {
let mut line = String::from("assert ");
// The assert-condition is boolean-typed: the synthesized
// `assert false` carries Const Int(0) — plain expr would
// print `assert 0` (int无法转换为boolean, jdk17 URI).
self.expr_bool(cond, &mut line);
if let Some(m) = msg {
line.push_str(" : ");
self.expr(m, 1, &mut line);
}
line.push(';');
self.line(&line);
}
Stmt::Synchronized { lock, body } => {
let mut head = String::from("synchronized (");
self.expr(lock, 1, &mut head);
head.push(')');
self.block_stmt(&head, body);
}
Stmt::TernaryValue { e } => {
let mut line = String::from("/* ternary */ ");
self.expr(e, 1, &mut line);
line.push(';');
self.line(&line);
}
Stmt::MonitorEnter(e) => {
// The lock expression goes INSIDE the comment: a bare
// local/field is not a valid expression statement
// (`/* monitorenter */ a;` failed javac).
let mut line = String::from("/* monitorenter ");
self.expr(e, 1, &mut line);
line.push_str(" */");
self.line(&line);
}
Stmt::MonitorExit(e) => {
let mut line = String::from("/* monitorexit ");
self.expr(e, 1, &mut line);
line.push_str(" */");
self.line(&line);
}
Stmt::ClassDecl { header, body, .. } => {
let kw = if header.starts_with("record ")
|| header.starts_with("interface ")
|| header.starts_with("enum ")
{
String::new()
} else {
"class ".to_string()
};
self.line(&format!("{}{} {{", kw, header));
for line in body.lines() {
if line.trim().is_empty() {
self.out.push('\n');
} else {
for _ in 0..self.indent + 1 {
self.out.push_str(" ");
}
self.out.push_str(line.trim_start());
self.out.push('\n');
}
}
self.line("}");
}
Stmt::Labeled { label, body } => {
// label prefix on the following statement's line
let save = self.out.len();
self.stmt(body);
// prepend "label: " before the first line just emitted
let indent_str = " ".repeat(self.indent);
let emitted = self.out[save..].to_string();
self.out.truncate(save);
if let Some(rest) = emitted.strip_prefix(&indent_str) {
self.out.push_str(&indent_str);
self.out.push_str(label);
self.out.push_str(": ");
self.out.push_str(rest);
} else {
self.out.push_str(&emitted);
}
}
Stmt::Break(lbl) => match lbl {
Some(l) => self.line(&format!("break {};", l)),
None => self.line("break;"),
},
Stmt::Continue(lbl) => match lbl {
Some(l) => self.line(&format!("continue {};", l)),
None => self.line("continue;"),
},
Stmt::Label(id) => {
// Emitted by breaking the following statement; standalone
// labels are invalid before non-statements, so use a marker.
self.line(&format!("L{}: ;", id));
}
Stmt::Goto(id) => self.line(&format!("break L{};", id)),
Stmt::Comment(c) => self.line(&format!("// {}", c)),
}
}
/// `head {` + body + `}`.
fn block_stmt(&mut self, head: &str, body: &Stmt) {
self.line(&format!("{} {{", head));
self.indent += 1;
self.stmt(body);
self.indent -= 1;
self.line("}");
}
/// Print an if statement; `opener` is "" for the first if and
/// "} else " when continuing an else-if chain on the closing line.
/// The statement-condition position already supplies its own
/// parentheses; an expression that renders fully wrapped in ONE
/// balanced layer (`((a & b))`, `((v))` — inner parens from a
/// composite-boolean fold or a cast-precedence wrap) carries a
/// redundant outer layer. Strip only when the FIRST `(` matches
/// the LAST `)` (a complete wrap), so `(a) & (b)` and `(cast) x
/// <= 0` keep their structural parens.
fn strip_outer_parens(s: &str) -> &str {
let b = s.as_bytes();
if b.len() < 2 || b[0] != b'(' || b[b.len() - 1] != b')' {
return s;
}
let mut depth = 0i32;
for (i, &c) in b.iter().enumerate() {
if c == b'(' {
depth += 1;
} else if c == b')' {
depth -= 1;
if depth == 0 {
if i + 1 == b.len() {
let inner = &s[1..s.len() - 1];
// Recurse: `((x))` peels to `x` — the balanced
// check stops at any structural paren.
return Self::strip_outer_parens(inner);
}
return s;
}
}
}
s
}
fn cond_str(&mut self, cond: &Expr) -> String {
let mut c = String::new();
self.expr_bool(cond, &mut c);
let stripped = Self::strip_outer_parens(&c);
stripped.to_string()
}
fn print_if(&mut self, cond: &Expr, then_stmt: &Stmt, else_stmt: Option<&Stmt>, opener: &str) {
let mut head = String::from(opener);
head.push_str("if (");
head.push_str(&self.cond_str(cond));
head.push_str(") {");
self.line(&head);
self.indent += 1;
self.stmt(then_stmt);
self.indent -= 1;
match else_stmt {
Some(Stmt::If {
cond: c2,
then_stmt: t2,
else_stmt: e2,
}) => {
self.print_if(c2, t2, e2.as_deref(), "} else ");
}
Some(other) => {
self.line("} else {");
self.indent += 1;
self.stmt(other);
self.indent -= 1;
self.line("}");
}
None => self.line("}"),
}
}
fn stmt_inline(&self, s: &Stmt, out: &mut String) {
match s {
Stmt::ExprStmt(e) => {
let mut p = self.sub();
if matches!(e, Expr::Method { .. }) {
p.suppress_poly_cast = true;
}
p.expr(e, 1, out);
}
Stmt::LocalDef { var, init, .. } => {
let info = self.vt.var(*var);
out.push_str(&self.local_decl_ty(*var, &info.ty));
out.push(' ');
out.push_str(&java_ident(&info.name));
if let Some(e) = init {
out.push_str(" = ");
let mut p = self.sub();
p.expr(e, 1, out);
}
}
other => {
let mut p = self.sub();
p.stmt(other);
out.push_str(p.out.trim_end());
}
}
}
fn sub(&self) -> Printer<'a> {
Printer {
ctx: self.ctx,
vt: self.vt,
out: String::new(),
line_buf: String::new(),
indent: 0,
lambda_depth: self.lambda_depth,
ignored_seq: self.ignored_seq,
outer_names: self.outer_names.clone(),
ret_bool: self.ret_bool,
ret_char: self.ret_char,
ret_byte: self.ret_byte,
ret_short: self.ret_short,
suppress_poly_cast: self.suppress_poly_cast,
suppress_diamond: self.suppress_diamond,
in_cond: self.in_cond,
lambda_sam_ret: self.lambda_sam_ret.clone(),
ret_sam: self.ret_sam.clone(),
twin_cache: self.twin_cache.clone(),
}
}
// ---------------- expressions ----------------
pub fn expr(&mut self, e: &Expr, outer_prec: u8, out: &mut String) {
let parens = e.needs_parens(outer_prec, false);
if parens {
out.push('(');
}
match e {
Expr::Const(c) => self.const_val(c, out),
Expr::Raw(t) if t == "\u{3}" => out.push_str("this"),
Expr::Raw(t) => out.push_str(t),
Expr::RawT(t, _) => out.push_str(t),
Expr::Local { var, .. } => {
let info = self.vt.var(*var);
// The receiver var carries the dex debug name "this" —
// reads render as the keyword (legal in expression
// position, and it is never declared).
if info.name == "this" {
out.push_str("this");
} else {
out.push_str(&java_ident(&info.name));
}
}
Expr::This => out.push_str("this"),
Expr::New {
cls,
args,
ty,
arg_tys,
..
} => {
// The dex invoke-direct descriptor's formals, when the
// node carries them at full arity: GROUND TRUTH for the
// typed-arg rendering. The arity-based ctx lookup picks
// `ctors_by_arity(..).first()` — a class with two
// same-arity ctors (netease EnterLive: `(long,boolean)`
// beside `(List,int)`) got the WRONG overload's formals
// and the boolean formal rendered the int const arg as
// `false` ("找不到合适的构造器" ×1,053-family).
let pinned: Option<&[crate::types::JavaType]> =
if !arg_tys.is_empty() && arg_tys.len() == args.len() {
Some(arg_tys.as_slice())
} else {
None
};
let no_diamond = self.suppress_diamond;
self.suppress_diamond = false;
// Explicit type arguments pinned by the AST passes
// (diamond_explicit_args_from_call_args): print them
// instead of the diamond.
let explicit = match ty {
TypeRef::G(crate::types::GenericType::Class(cs))
if cs.parts.last().map(|p| !p.args.is_empty()).unwrap_or(false)
&& crate::typeutil::classsig_internal(cs).as_str() == cls.as_ref() =>
{
let rendered: Vec<String> = cs
.parts
.last()
.unwrap()
.args
.iter()
.map(|a| self.generic_name(a))
.collect();
Some(format!("<{}>", rendered.join(", ")))
}
_ => None,
};
// A wildcard-typed ctor argument dooms diamond inference
// (the inference variable gets an equality constraint from
// the capture and a different bound from the context —
// "cannot infer type arguments for Entry<>", jdk11
// Hashtable `tab[i] = new Entry<>(hash, key, value, e)`
// with e: Entry<?,?>; the source declared e as Entry<K,V>
// via an unchecked cast that leaves no bytecode trace).
// The raw form is always applicable (unchecked).
let args_wildcard = args.iter().any(|a| {
matches!(a.type_ref(), TypeRef::G(ref g)
if crate::typeutil::g_has_wildcard(g))
});
let diamond: std::borrow::Cow<str> = match &explicit {
Some(x) => x.as_str().into(),
// Pre-Java-8 conditional branches are not poly
// expressions: the diamond cannot see the assignment
// target through the `?:` and infers <Object,Object>
// (jdk7 HashSet.readObject map-ternary 不兼容的类型).
// Raw is unchecked but always compilable.
None if no_diamond
|| args_wildcard
|| (self.in_cond && self.ctx.source_level() < 52) =>
{
"".into()
}
None => self.diamond_for(cls).into(),
};
let diamond = diamond.as_ref();
if let Some(local) = cls.strip_prefix('\u{2}') {
out.push_str("new ");
out.push_str(local);
out.push_str(diamond);
out.push('(');
// Local records/classes keep bytecode-arity ctors:
// typed rendering turns an int constant into the
// char/boolean literal the ctor expects (jdk17
// MessageFormat `new Qchar(39, quoted)`).
// Nested local-class method printing runs under a
// TAKEN LOCAL_CLASS_INTERNALS registry — resolve a
// self-construction (`new BitSetSpliterator(..)` inside
// BitSetSpliterator.trySplit) through the printer's
// own class when the registry misses. Local-class
// ctors capture the enclosing instance as a leading
// param that the printed new-site omits; the this$0
// fallback in ctor_param_types lines the formals up
// (jdk11 BitSet$1BitSetSpliterator(BitSet,int,int,int,
// boolean) — the boolean formal rendered its arg `0`).
let internal = self.ctx.local_class_internal(local).or_else(|| {
let tail = self.ctx.class_name().rsplit('$').next().unwrap_or("");
let simple = tail.trim_start_matches(|c: char| c.is_ascii_digit());
if !simple.is_empty() && simple == local {
return Some(self.ctx.class_name().to_string());
}
// Probe the nested-name space of the printing
// context (javac numbers method-local classes
// `$1Name`): the new-site needs the real class to
// resolve its ctor formals.
let base = format!("{}${}", self.ctx.class_name(), local);
if self.ctx.has_class(&base) {
return Some(base);
}
for d in 0..10 {
let cand = format!("{}${}{}", self.ctx.class_name(), d, local);
if self.ctx.has_class(&cand) {
return Some(cand);
}
}
None
});
match internal
.as_deref()
.and_then(|i| self.ctor_param_types(i, 0, args.len(), args))
{
Some(pt) => self.args_typed(args, &pt, out),
None => self.args(args, out),
}
out.push(')');
} else if self.is_member_inner(cls)
&& !args.is_empty()
&& !matches!(args[0], Expr::This)
&& !is_this_expr(&args[0])
// A constant (null/0) as the first argument is a real
// parameter value, not the synthetic outer instance —
// `0.new a()` / `null.new a()` are not valid Java.
&& !matches!(args[0], Expr::Const(_))
// Anonymous classes (digit tails) are emitted as
// separate top-level-ish classes — a qualified
// `this.new 1(...)` is not valid Java; the flat
// `new Outer$1(...)` form is. Test the RAW tail:
// inner_simple already sanitizes a leading digit to
// `_`, which silently bypassed this guard and emitted
// `this.new _1(..)` against a flat top-level
// declaration (weibo HorseRaceDetector$4 family).
&& !cls
.rsplit('$')
.next()
.map(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()))
.unwrap_or(false)
{
// `outerExpr.new Inner(rest...)` — the first ctor arg
// is the synthetic outer instance when the class has a
// this$0 field, or when the ctor forwards it straight
// to super (no field of its own; is_member_inner
// detected it). Either way the qualified-new form
// supplies the outer implicitly, so skip args[0].
self.expr(&args[0], 15, out);
out.push_str(".new ");
out.push_str(&inner_simple(cls));
out.push_str(diamond);
out.push('(');
if let Some(pt) = pinned {
self.args_typed(&args[1..], &pt[1..], out);
} else {
match self.ctor_param_types(cls, 1, args.len() - 1, &args[1..]) {
Some(pt) => self.args_typed(&args[1..], &pt, out),
None => self.args(&args[1..], out),
}
}
out.push(')');
} else {
out.push_str("new ");
let digit_tail = cls
.rsplit('$')
.next()
.map(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()))
.unwrap_or(false);
// A digit-tail class (anonymous `Outer$1`, d8 lambda)
// is rendered as a SEPARATE top-level file declaring
// `class Outer$1` with the outer instance as an
// ordinary ctor parameter — the ctor signature keeps
// that parameter (the inner-ctor strip excludes
// digit tails for exactly this shape). The member
// form `this.new _1(..)` would look for a member of
// the enclosing class that does not exist there —
// the flat `new Outer$1(outer, ..)` with ALL args is
// the shape that matches the declaration.
let member_this = self.is_member_inner(cls)
&& !digit_tail
&& !args.is_empty()
&& matches!(args[0], Expr::This);
let shown = if member_this {
// `new Inner()` from inside the outer class
inner_simple(cls)
} else if digit_tail {
// Digit-suffixed class at a `new` site: a d8/R8-
// desugared lambda (`...$lambda$N$$inlined$log$1`,
// `Outer$$ExternalSyntheticLambda0`) or an anonymous
// class (`Outer$1`). Both are concrete, pool-rendered
// classes, so print the real binary name — NOT the
// abstract SAM interface `shorten` falls back to
// (which yields an invalid `new Iface(..)`: "a是抽象
// 的; 无法实例化", the biggest abstract-instantiation
// family on Kotlin corpora, v6.a/l/p = Function0/1/2).
// Type positions keep `shorten` (interface), so the
// declaration stays phi-compatible across branches
// that mint different lambdas: `Iface v = new C(..)`.
self.shorten_concrete(cls)
} else {
self.shorten(cls)
};
out.push_str(&shown);
out.push_str(diamond);
out.push('(');
if member_this {
if let Some(pt) = pinned {
self.args_typed(&args[1..], &pt[1..], out);
} else {
match self.ctor_param_types(cls, 1, args.len() - 1, &args[1..]) {
Some(pt) => self.args_typed(&args[1..], &pt, out),
None => self.args(&args[1..], out),
}
}
} else {
// Pinned generic instantiation: prime lambda args
// from the ctor's instantiated Signature formals.
let sam_rets: Vec<Option<TypeRef>> = match ty {
TypeRef::G(crate::types::GenericType::Class(cs))
if explicit.is_some()
&& crate::typeutil::classsig_internal(cs).as_str() == cls.as_ref() =>
{
let pinned = cs.parts.last().map(|p| p.args.clone());
let formals = self.ctx.ctor_formals_by_arity(cls, args.len());
// The raw ctor formals carry the class's
// own typevars — substitute the pinned
// instantiation before reading the SAM
// return (an unsubstituted R printed `(R)`
// — 找不到符号).
let class_params = self.ctx.class_type_params(cls);
args.iter()
.enumerate()
.map(|(i, a)| {
if !matches!(a, Expr::Lambda(_)) {
return None;
}
let f = formals.as_ref()?.get(i)?;
let pinned = pinned.as_ref()?;
if pinned.len() != class_params.len() {
return None;
}
let inst = crate::typeutil::subst_typevars(
f,
&class_params,
pinned,
);
let Expr::Lambda(l) = a else { return None };
self.sam_ret_cast(&inst, &l.sam_name)
})
.collect()
}
_ => Vec::new(),
};
if let Some(pt) = pinned {
self.args_typed_sam(args, pt, &sam_rets, out);
} else {
match self.ctor_param_types(cls, 0, args.len(), args) {
Some(pt) => self.args_typed_sam(args, &pt, &sam_rets, out),
None => self.args(args, out),
}
}
}
out.push(')');
}
}
Expr::NewArray {
elem,
dims,
trailing_dims,
init,
} => {
out.push_str("new ");
out.push_str(&self.type_name(elem));
match init {
Some(vals) => {
for _ in 0..=*trailing_dims {
out.push_str("[]");
}
out.push_str(" {");
// boolean[]/char[] initializers hold int constants
// in bytecode (iconst + bastore/castore): render
// them as true/false and char literals (jdk11
// PKCS9Attribute `new boolean[] {0, 0, 1, ..}` x18).
let elem_bool = elem.erased() == crate::types::JavaType::Boolean;
let elem_char = elem.erased() == crate::types::JavaType::Char;
for (i, v) in vals.iter().enumerate() {
if i > 0 {
out.push_str(", ");
}
if elem_bool {
self.expr_bool(v, out);
} else if elem_char {
self.expr_char(v, out);
} else {
self.expr(v, 1, out);
}
}
out.push('}');
}
None => {
for d in dims {
out.push('[');
self.expr(d, 1, out);
out.push(']');
}
for _ in 0..*trailing_dims {
out.push_str("[]");
}
}
}
}
Expr::NewMultiArray { ty, dims } => {
// Strip the dims.len() leading array levels from the type.
let mut base = ty.erased();
for _ in 0..dims.len() {
match base {
crate::types::JavaType::Array(inner) => base = *inner,
_ => break,
}
}
out.push_str("new ");
out.push_str(&self.type_name(&TypeRef::J(base)));
for d in dims {
out.push('[');
self.expr(d, 1, out);
out.push(']');
}
}
Expr::Field {
owner,
cls,
name,
is_static,
..
} => {
// javac reserves `$assertionsDisabled`; the declaration and
// all references are emitted under a private alias.
let name: &str = if name.as_ref() == "$assertionsDisabled" {
crate::analysis::ASSERT_FIELD
} else {
name
};
if name == crate::analysis::ASSERT_FIELD {
// Assert guards print bare: the field is declared on
// the enclosing emitted class or inlined body; the
// bytecode owner is often a synthetic holder class
// (`ConstantGroup$1`) whose shorten() fallback is
// `Object` — a qualified read can never resolve.
out.push_str(&java_ident(name));
} else if name == "length" && cls.is_empty() {
if let Some(o) = owner {
if let Expr::Const(_) = o.as_ref() {
// Receiver tracking lost: `0.length` is not
// parseable — cast-null array form.
out.push_str("((java.lang.Object[]) null)");
} else {
self.expr(o, 15, out);
}
}
out.push_str(".length");
} else if let Some(o) = owner {
if let Expr::Const(cv) = o.as_ref() {
if matches!(
cv,
crate::ir::expr::ConstVal::Str(_)
| crate::ir::expr::ConstVal::ClassLit(_)
) {
// Literal receivers keep their value (see the
// Method arm): `Foo.class.name`, not
// `((Class) null).name`.
self.expr(o, 15, out);
out.push('.');
} else {
// Receiver tracking lost (a null placeholder leaked
// through): `0.b` is not parseable — the same
// cast-null form the Method arm uses.
out.push_str("((");
out.push_str(&self.shorten(cls));
out.push_str(") null).");
}
out.push_str(&java_ident(name));
} else if matches!(o.as_ref(), Expr::Raw(t) if t == "\u{3}") {
// Outer anonymous class member: unqualified lexical
// resolution (an anon outer has no nameable this).
out.push_str(&java_ident(name));
} else if self.private_super_field(cls, name, o.as_ref()) {
// A private field of a SUPERCLASS is not inherited
// into the subclass's member scope: `this.algorithm`
// inside Delegate (extends MessageDigest, algorithm
// private) is "private access" even though the
// source comment says it all — jdk11
// MessageDigest.Delegate.clone casts
// `((MessageDigest)this).algorithm`.
out.push_str("((");
out.push_str(&self.shorten(cls));
out.push_str(") ");
if matches!(o.as_ref(), Expr::This) {
out.push_str("this");
} else {
self.expr(o, 14, out);
}
out.push_str(").");
out.push_str(&java_ident(name));
} else if match o.type_ref().erased() {
crate::types::JavaType::Object(ref n) => {
n.as_ref() != cls.as_ref()
&& !matches!(o.as_ref(), Expr::Raw(_) | Expr::RawT(..) | Expr::This)
&& (n.as_ref() == "java/lang/Object"
|| self.ctx.is_subtype_of(
&crate::types::JavaType::Object(
std::sync::Arc::from(cls.as_ref()),
),
n,
))
}
_ => false,
} {
// The receiver's static type is a strict SUPERTYPE
// of the declaring class: either widened to Object
// (when-materialization residue) or a register
// reuse the vt kept at the supertype (`v9.label`
// with v9: ContinuationImpl, label on the suspend
// frame subclass — weibo coroutine cluster ×1.3k).
// The downcast is what the bytecode's field
// resolution did; same honest cast as the Method
// arm. Concrete name: a `$<digits>` declaring
// class loses its pushed-down members under the
// anon fallback.
out.push_str("((");
out.push_str(&self.shorten_concrete(cls));
out.push_str(") ");
self.expr(o, 14, out);
out.push_str(").");
out.push_str(&java_ident(name));
} else {
self.expr(o, 15, out);
out.push('.');
out.push_str(&java_ident(name));
}
} else if *is_static {
// A same-class static read prints bare — unless a local
// of this method shadows the field name: javac resolves
// the bare name as the LOCAL (jdk17 Socket.setImpl's
// `SocketImplFactory factory = factory;` self-reference
// — 可能尚未初始化变量factory x2 sites). Qualify with the
// class name to reach the field.
let shadowed_by_local = cls.as_ref() == self.ctx.class_name()
&& self.vt.vars.iter().any(|v| v.name == name);
// ENCLOSING-class static fields read from a nested
// class print bare too (lexical scope) — and MUST when
// the class name itself is shadowed by a member of the
// same name: jdk26 HPKE$Impl reads the outer
// `byte[] HPKE`/PSK_ID_HASH/SECRET/EXP/KEY constants;
// `HPKE.PSK_ID_HASH` resolves the qualifier as the
// byte[] FIELD (variables obscure type names in
// expression names) — 找不到符号 变量 PSK_ID_HASH x6.
let enclosing_static = cls.as_ref() != self.ctx.class_name()
&& self.renders_nested_in(cls)
&& !self.vt.vars.iter().any(|v| v.name == name)
&& {
let mut cur = self.ctx.class_name().to_string();
let mut shadow = false;
while cur.as_str() != cls.as_ref() {
// Inherited fields shadow too (superclass
// chain — see the method-side twin).
let mut sup = Some(cur.clone());
while let Some(c) = sup.take() {
{
// Display-space: the reference's
// name is the registry DISPLAY
// (the lift applied it), so the
// shadow comparison must be too —
// the nested class's raw `a`
// displaying `a17` shadows the
// outer field that displays a17
// (lark ch6/b$a: `a17.length` bound
// to the List instead of the
// outer array).
if self.ctx.declares_field_display(&c, name) {
shadow = true;
break;
}
sup = self.ctx.super_name(&c);
}
}
if shadow {
break;
}
match cur.rfind('$') {
Some(i) => cur.truncate(i),
None => break,
}
}
!shadow
};
if !enclosing_static && (cls.as_ref() != self.ctx.class_name() || shadowed_by_local) {
// JLS 6.4.2 obscured-owner escape: the dotted
// render's first segment binds to an in-scope
// variable (inherited field), the member chain
// dangles. The import-simple route dies the same
// way when a field owns the simple name — fall
// to the single-static-import (bare member).
// A local named like the member captures the
// bare form (same rule as shadowed_by_local).
if !shadowed_by_local
&& !self.vt.vars.iter().any(|v| v.name == name)
&& self.ctx.obscured_member_escape(cls, name)
{
// bare: the trailing name print below covers
// the member (Method-arm twin structure — the
// escape only suppresses the qualifier)
} else {
// The owner must name a DECLARABLE class: the
// anonymous→interface/Object fallback (right for
// phi-compatible type positions) leaves the field
// unresolvable — `Object.$SwitchMap$java$math$
// RoundingMode` (485 weibo / 308 lark / 217
// weixin cannot-finds; the synthetic holder
// `LongMath$1` IS rendered as a flat file with
// the field, 0 own errors). Fall back to the
// concrete `$N` name — `$` and digits are legal
// Java identifier characters, and the holder
// always sits in the referring class's package.
// The qualifier of a STATIC member is always the
// CONCRETE name: anon/lambda classes emit as flat
// `$`-named top-level files, while shorten()'s
// anon fallback renders the SAM interface — which
// does not declare the member. `Function0.INSTANCE`
// (1.7k weibo lines) is the sget of
// ActivityResultRegistry$generateRandomNumber$1
// .INSTANCE; the same trap took $SwitchMap holders
// to `Object.` before (the narrow rendered=="Object"
// check this replaces).
out.push_str(&self.shorten_concrete(cls));
out.push('.');
}
}
out.push_str(&java_ident(name));
} else if self.private_super_field(cls, name, &Expr::This) {
out.push_str("((");
out.push_str(&self.shorten(cls));
out.push_str(") this).");
out.push_str(&java_ident(name));
} else {
out.push_str("this.");
out.push_str(&java_ident(name));
}
}
Expr::Method {
owner,
cls,
name,
desc,
args,
is_static,
is_special,
is_super,
type_args,
..
} => {
// Signature-polymorphic calls need the descriptor return cast
// in source form (see classdec::polymorphic_ret_cast) — except
// at the root of an expression statement, where the bare call
// is the only legal form. Consume the flag so a poly call
// NESTED in the args still gets its cast.
let bare_stmt_root = self.suppress_poly_cast;
self.suppress_poly_cast = false;
if !bare_stmt_root {
if let Some(t) = self.ctx.polymorphic_ret_cast(cls, name, desc) {
out.push('(');
out.push_str(&self.type_name(&crate::ir::expr::TypeRef::J(t)));
out.push_str(") ");
}
}
if name.as_ref() == "<init>" && *is_special {
// The ctor fold normally turns `new X; <init>` into a
// New expr at the LIFT. When the new-instance view was
// lost (crossed a merge / got materialized), the call
// arrives here with a NON-this receiver: rendering a
// this/super delegation produced `this.super(...)`,
// which is not valid Java. The allocation did happen —
// print the construction call.
let lost_alloc = owner
.as_deref()
.is_some_and(|o| !is_this_expr(o) && !matches!(o, Expr::This));
if lost_alloc {
// A member-inner construction call carries the
// synthetic outer as args[0] and the emitted
// ctor signature drops it (the inner-ctor
// normalization) — supply it implicitly with the
// qualified-new form, mirroring the New-expr
// branches. Digit-tail classes keep the flat
// full-args form (their ctor declares the
// outer parameter).
let digit_tail = cls
.rsplit('$')
.next()
.map(|s| !s.is_empty() && s.chars().all(|c| c.is_ascii_digit()))
.unwrap_or(false);
if self.is_member_inner(cls)
&& !digit_tail
&& !args.is_empty()
&& !matches!(args[0], Expr::Const(_))
{
if matches!(args[0], Expr::This) || is_this_expr(&args[0]) {
out.push_str("this.new ");
} else {
self.expr(&args[0], 15, out);
out.push_str(".new ");
}
out.push_str(&inner_simple(cls));
out.push('(');
match self.ctor_param_types(cls, 1, args.len() - 1, &args[1..]) {
Some(pt) => self.args_typed(&args[1..], &pt, out),
None => self.args(&args[1..], out),
}
out.push(')');
return;
}
out.push_str("new ");
out.push_str(&self.shorten(cls));
out.push('(');
self.args(args, out);
out.push(')');
return;
}
// super(...) / this(...)
let is_super_form = *is_super || cls.as_ref() != self.ctx.class_name();
// Qualified super for a STATIC class extending an
// INNER superclass: javac synthesizes the enclosing
// instance as the ctor's first param, and the source
// form is `outer.super(rest)` (jdk11/17/26
// BoundMethodHandle.SpeciesData extends
// ClassSpecializer<..>.SpeciesData — plain
// super(outer, key) is "需要包含..的封闭实例" x3 trees).
let qualified_outer = if is_super_form
&& !args.is_empty()
&& cls.contains('$')
&& !self.ctx.class_has_this0(self.ctx.class_name())
{
let enclosing = cls.rsplit_once('$').map(|(o, _)| o.to_string());
match enclosing {
Some(enc)
if self.ctx.class_has_this0(cls)
&& self
.ctx
.is_subtype_of(&args[0].type_ref().erased(), &enc) =>
{
Some(enc)
}
_ => None,
}
} else {
None
};
// The enclosing instance passed explicitly is `this`
// itself (qualified_outer found the enclosing, but the
// argument IS this class's own outer): the source form
// is plain `super(rest...)` — the implicit outer —
// because `this.super(...)` is not valid Java (weibo
// HorseRaceDetector, reqable androidx.fragment.app.d).
let this_outer =
is_super_form && !args.is_empty() && is_this_expr(&args[0]);
let skip_outer_arg = qualified_outer.is_some() || this_outer;
if qualified_outer.is_some() && !this_outer {
self.expr(&args[0], 15, out);
out.push_str(".super(");
} else if is_super_form {
out.push_str("super(");
} else {
out.push_str("this(");
}
// Typed rendering: boolean/char params must not receive
// raw 0/1 int constants (`this(refKind, false)`). The
// methodref's descriptor `desc.args` is the EXACT invoked
// ctor signature, so prefer it over `ctor_param_types`
// (which matches by arg count and picks the wrong
// overload when a class has several ctors of equal arity,
// e.g. jdk26 Thread(ThreadGroup,Runnable,String,long,
// boolean) vs (...,long,Thread[])).
let _ = is_super_form;
// Upcast restoration only for SELF delegation: this(..)
// overload resolution binds the arg's static type (a
// JarEntry arg would recurse into JarEntry(JarEntry)
// instead of the descriptor's JarEntry(ZipEntry)).
// super(..) resolution is unambiguous through the
// generic formals — casting there broke FindOps
// `super(parent, spliterator)` (K := FindTask<..>
// accepts the arg fine; the raw erasure cast does not).
if skip_outer_arg {
if desc.args.len() == args.len() && !desc.args.is_empty() {
self.args_typed(&args[1..], &desc.args[1..], out);
} else {
self.args(&args[1..], out);
}
} else if desc.args.len() == args.len() {
if is_super_form {
self.args_typed(args, &desc.args, out);
} else {
self.args_delegation(args, &desc.args, out);
}
} else if !is_super_form {
// desc is the EXACT invoked ctor signature and the
// args are outer-stripped: args_delegation aligns
// by tail (jdk11 ZipFileInflaterInputStream —
// ctor_param_types' arity match would pick the
// wrong same-arity overload and cast against
// shifted formals, (ZipFile) zfin x3).
self.args_delegation(args, &desc.args, out);
} else {
match self.ctor_param_types(cls, 0, args.len(), args) {
Some(pt) if pt.len() == args.len() => self.args_typed(args, &pt, out),
_ => self.args(args, out),
}
}
out.push(')');
} else {
if *is_super {
// invokespecial on `this` targeting another class:
// a superclass method call. Interface targets are
// qualified `Iface.super.m()` (JDK8 default-method
// invocations from implementors) — but only a
// DIRECT superinterface may carry the qualifier
// (JLS 15.11.2). A default reached through a
// SUBINTERFACE (weixin jsapi/f0 implements e0
// extends l; `l.super.m()` = "不是封闭类: l" ×67)
// qualifies with the direct interface inheriting
// it; one reached only through the superclass
// chain falls back to plain `super.` (the super
// inherits the default as its own member).
let itf = self.ctx.is_interface(cls);
if itf {
let mut qual: Option<String> = None;
if let Some((ifs, _)) =
self.ctx.class_bases(self.ctx.class_name())
{
if ifs.iter().any(|i| i.as_str() == cls.as_ref()) {
qual = Some(cls.to_string());
} else {
qual = ifs.into_iter().find(|i| {
self.ctx.is_subtype_of(
&crate::types::JavaType::Object(
i.as_str().into(),
),
cls,
)
});
}
}
if let Some(q) = qual {
out.push_str(&self.shorten(&q));
out.push('.');
}
}
out.push_str("super.");
} else if let Some(o) = owner {
if let Expr::Const(cv) = o.as_ref() {
if matches!(
cv,
crate::ir::expr::ConstVal::Str(_)
| crate::ir::expr::ConstVal::ClassLit(_)
) {
// A literal receiver is valid, faithful
// Java (`"http".equalsIgnoreCase(x)`,
// `Foo.class.getName()`). Rendering it as
// cast-null silently DROPPED the constant
// — 73.5k sites across the 4 corpora
// (`((String) null).m()`), invisible to
// javac (it compiles) and an NPE at run
// time. Only valueless placeholders take
// the cast-null path below.
self.expr(o, 15, out);
out.push('.');
} else {
// Receiver tracking lost: a null placeholder
// (const/4 0) leaked through as the receiver —
// `0.close()` is not parseable. Cast-null keeps
// the statement compilable and honestly marks
// the value as unknown on this path.
out.push_str("((");
out.push_str(&self.shorten(cls));
out.push_str(") null).");
}
} else if let Expr::Lambda(l) = o.as_ref() {
// A lambda RECEIVER needs the source's SAM cast
// (`((BooleanSupplier) () -> ..).getAsBoolean()`
// — a bare lambda cannot own a call: 此处不应为
// lambda 表达式, jdk26 Proxy assert).
if !l.sam_cls.is_empty() {
out.push_str("((");
out.push_str(&self.shorten(&l.sam_cls));
out.push_str(") ");
self.expr(o, 14, out);
out.push_str(").");
} else {
self.expr(o, 15, out);
out.push('.');
}
} else if matches!(o.as_ref(), Expr::Raw(t) if t == "\u{3}") {
// Outer anonymous member call: unqualified
// lexical resolution.
} else if self.needs_owner_cast(cls, name, desc, o) {
// Private / cross-package members are NOT
// inherited by the receiver's static type:
// the source cast to the declaring class
// (`((ZipFile) jar).getManifestNum()`) leaves
// no bytecode trace when the receiver is
// already a subtype.
out.push_str("((");
out.push_str(&self.shorten_concrete(cls));
out.push_str(") ");
self.expr(o, 14, out);
out.push_str(").");
} else {
self.expr(o, 15, out);
out.push('.');
}
} else if *is_static && (cls.as_ref() != self.ctx.class_name() || !type_args.is_empty())
{
// A static member of an ENCLOSING class resolves
// through lexical scope unqualified — and the
// qualified form is a TRAP when a field/local is
// named after the class: expression-name
// resolution prefers variables, so jdk26
// HPKE$Impl's `private static final byte[] HPKE`
// hijacked `HPKE.usePSK(psk)` into a member
// lookup on the array (找不到符号 方法
// usePSK(SecretKey) 位置: 类型为byte[]的变量
// HPKE). Keep the qualifier when an own or
// intermediate class declares a same-named
// method (real member shadowing) or when type
// witnesses need an explicit receiver.
// renders_nested_in: flat-rendered (digit-tail)
// nested classes have NO lexical scope.
let enclosing_static = type_args.is_empty()
&& self.renders_nested_in(cls)
&& {
let mut cur = self.ctx.class_name().to_string();
let mut shadow = false;
while cur.as_str() != cls.as_ref() {
// Inherited members shadow too: the
// lexical member scope of a class
// includes its whole superclass chain
// (jdk26 GaloisCounterMode$GCMDecrypt
// extends GCMEngine, whose own
// implGCMCrypt(ByteBuffer,..) hijacks
// the bare 9-arg call to the OUTER
// static — 无法将方法应用到给定类型).
let mut sup = Some(cur.clone());
while let Some(c) = sup.take() {
{
if self.ctx.declares_method_named(&c, name) {
shadow = true;
break;
}
sup = self.ctx.super_name(&c);
}
}
if shadow {
break;
}
match cur.rfind('$') {
Some(i) => cur.truncate(i),
None => break,
}
}
!shadow
};
if self.ctx.obscured_member_escape(cls, name)
&& !self.vt.vars.iter().any(|v| *v.name == **name)
{
// JLS 6.4.2 obscured-owner escape (method twin
// of the static-field arm): single-static-import,
// bare member call.
} else if !enclosing_static {
// Concrete name: same anon-class trap as the
// static FIELD qualifier (the SAM interface
// does not declare the synthetic static).
out.push_str(&self.shorten_concrete(cls));
out.push('.');
}
} else if !type_args.is_empty() {
// Type witnesses require an explicit receiver.
out.push_str("this.");
}
if !type_args.is_empty() {
out.push('<');
out.push_str(&type_args.join(", "));
out.push('>');
}
// A BARE `yield(...)` invocation trips Java 13's
// restricted identifier (Kotlin suspend funs name
// their continuation entry `yield`; news_article
// ships CoroutineExtKt$yield). Qualified calls are
// fine — when no receiver was printed, add one.
if name.as_ref() == "yield" && !out.ends_with('.') && !out.ends_with('>') {
out.push_str(&self.shorten(cls));
out.push('.');
}
out.push_str(&java_ident(name));
out.push('(');
// Lambda args of a GENERIC call: prime each one's
// body-return cast from the instantiated formal's SAM
// return (jdk17 AbstractPipeline.opEvaluateParallelLazy:
// `i -> (E_OUT[]) new Object[i]` — the erasure-equal
// cast leaves no bytecode trace and without it the
// IntFunction<E_OUT[]> formal starves: Object[]无法
// 转换为E_OUT[]).
let sam_rets: Vec<Option<TypeRef>> = {
let mut v: Vec<Option<TypeRef>> =
std::iter::repeat_with(|| None).take(args.len()).collect();
if self.ctx.is_generic_call(e) {
if let Some((formals, mtvars)) = self.ctx.generic_call_formals(e) {
if formals.len() == args.len() {
for (i, (a, f)) in args.iter().zip(formals.iter()).enumerate() {
// A raw-SAM-cast wrapper still
// exposes the lambda (the overload
// disambiguation cast; the primed
// body return types the lambda
// precisely).
let a_inner = match a {
Expr::Cast { e: ce, .. } => ce.as_ref(),
other => other,
};
if let Expr::Lambda(l) = a_inner {
// A formal still carrying the
// callee's own method typevars
// is not denotable at this
// call site.
if crate::typeutil::g_mentions_any(f, &mtvars) {
continue;
}
v[i] = self.sam_ret_cast(f, &l.sam_name);
}
}
}
}
}
v
};
if sam_rets.iter().any(|x| x.is_some()) {
self.args_typed_sam(args, &desc.args, &sam_rets, out);
} else {
self.args_typed(args, &desc.args, out);
}
out.push(')');
}
}
Expr::ArrayIndex { array, index } => {
self.expr(array, 15, out);
out.push('[');
// Array indexes are int by definition: a long-typed index
// local (slot-sharing/merge typed the foreach lowering's
// counter long — jdk26 Files.copy `options[i]`,
// 从long转换到int可能会有损失) needs the narrowing cast.
let idx_ty = match &**index {
Expr::Local { var, .. } => self.vt.var(*var).ty.erased(),
other => other.type_ref().erased(),
};
if matches!(idx_ty, crate::types::JavaType::Long) {
out.push_str("(int) ");
}
self.expr(index, 1, out);
out.push(']');
}
Expr::Cast { ty, e } => {
// `(T) (Serializable) lambda` is invalid Java: the source
// form of a serializable-lambda cast is the intersection
// `(T & Serializable) lambda`.
if let Expr::Cast {
ty: inner_ty,
e: inner_e,
} = &**e
{
let is_serializable = |t: &crate::ir::expr::TypeRef| {
t.erased() == crate::types::JavaType::Object("java/io/Serializable".into())
};
if matches!(&**inner_e, Expr::Lambda(_)) && is_serializable(inner_ty) {
out.push('(');
out.push_str(&self.type_name(ty));
out.push_str(" & ");
out.push_str(&self.type_name(inner_ty));
out.push_str(") ");
self.expr(inner_e, 14, out);
return;
}
}
// CLASS-argument generic casts only: a TYPEVAR cast is
// load-bearing (`(T) new SimpleEntry<>(..)` — jdk11
// IdentityHashMap.toArray: the diamond infers from the
// ctor args and the unchecked (T) makes the T[] store
// legal; dropping it left the diamond to infer from the
// array target T — 无法推断SimpleEntry<>的类型参数).
if let (TypeRef::G(crate::types::GenericType::Class(_)), Expr::New { cls, .. }) =
(ty, &**e)
{
if !self.diamond_for(cls).is_empty() {
// Synthetic generics-only cast around a diamond new:
// DROP the cast and keep the diamond. A generic-typed
// cast is always jcdc's own witness (a real checkcast
// carries only erasure), and every cast form loses
// here: with the diamond the cast starves inference
// (`(PendingFuture<Void,A>) new PendingFuture<>(..)`
// infers Object bounds and fails the cast), and the
// bare/raw form makes the whole creation raw so
// method-ref/lambda arguments stop type-checking
// (jdk17 Collectors `(Collector<T,?,C>) new
// CollectorImpl(.., Collection::add, ..)`). Cast-free
// `return new CollectorImpl<>(..)` / `x = new
// PendingFuture<>(..)` target-types the diamond —
// the source shape.
self.expr(e, outer_prec, out);
return;
}
}
out.push('(');
// A cast to a pool `$<digits>` class (desugared lambda /
// coroutine frame) must keep the CONCRETE name: the
// anon-fallback would print the SAM interface/super and
// drop exactly the members the cast exists to reach
// (weibo `(($reportWhenComplete$1) continuation).label`
// rendered `(ContinuationImpl) …` — label lives on the
// frame class only, R8 pushed it down; 找不到符号 ×420).
match ty {
TypeRef::J(crate::types::JavaType::Object(n))
if self.ctx.has_class(n)
&& n.rsplit('$')
.next()
.is_some_and(|l| !l.is_empty() && l.chars().all(|c| c.is_ascii_digit())) =>
{
out.push_str(&self.shorten_concrete(n));
}
_ => out.push_str(&self.type_name(ty)),
}
out.push_str(") ");
// Inconvertible direct casts from mis-joined stack-merge
// vars (jdk26 AnnotationReader: `(SupertypeTarget)
// var3_341` with var3 typed Iterator — sealed targets
// reject the cross-cast): relay through Object, which is
// always legal and semantically identical (the runtime
// value IS the target type).
if self.needs_object_relay(ty, e) {
out.push_str("(Object) ");
}
if matches!(&**e, Expr::New { .. }) {
self.suppress_diamond = true;
}
if let (TypeRef::G(g), Expr::Lambda(l)) = (ty, &**e) {
self.lambda_sam_ret = self.sam_ret_cast(g, &l.sam_name);
}
self.expr(e, 14, out);
self.suppress_diamond = false;
self.lambda_sam_ret = None;
}
Expr::InstanceOf { e, ty } => {
// `error2 instanceof CodecException` with error2: Error
// is "不兼容的类型" — instanceof demands castability
// exactly like a cast, so it takes the same Object
// relay (semantics unchanged: instanceof is a runtime
// type test).
if self.needs_object_relay(ty, e) {
out.push_str("((Object) ");
self.expr(e, 14, out);
out.push(')');
} else {
self.expr(e, 10, out);
}
out.push_str(" instanceof ");
out.push_str(&self.type_name(ty));
}
Expr::Un { op, e } => {
out.push_str(match op {
UnOp::Neg => "-",
UnOp::Not => "!",
UnOp::BitNot => "~",
});
self.expr(e, 14, out);
}
Expr::Bin { op, l, r, .. } => {
// Boolean context special cases: `b == 0` → `!b`. A
// Local's embedded type can be stale (booleanize retypes
// the VarTable), and a boolified bitwise bin over
// bool-ish operands is boolean too (jdk26
// LinkedTransferQueue `(spin & !upc) == 0` — the frozen-Int
// And with an int-form ternary side printed
// `spin & (!upc ? 1 : 0)`: boolean & int).
let lt = match &**l {
Expr::Local { var, .. } => self.vt.var(*var).ty.erased(),
other => other.type_ref().erased(),
};
let l_bool = lt == JavaType::Boolean;
let l_boolish = l_bool || self.bool_ish_vt(l);
if matches!(op, BinOp::Eq | BinOp::Ne | BinOp::RefEq | BinOp::RefNe) && l_boolish {
if let Expr::Const(ConstVal::Int(n)) = &**r {
let polarity = matches!(op, BinOp::Eq | BinOp::RefEq);
let want_true = (*n != 0) == polarity;
if !want_true {
out.push('!');
}
if l_bool {
self.expr(l, 14, out);
} else if matches!(
&**l,
Expr::Bin { .. } | Expr::Cond { .. } | Expr::Assign { .. }
) {
// Composite boolean (a bitwise bin): parenthesize
// so a leading `!` binds the whole value. A BARE
// operand — the 0/1 boolean encoding of a const,
// a local whose vt type is stale-Int, a Not —
// cannot regroup and renders bare: the
// unconditional parens wrapped every folded
// comparison into `x = (false)` / `return (!v)`
// (kimi: ~85k noise sites).
out.push('(');
self.expr_bool(l, out);
out.push(')');
} else {
self.expr_bool(l, out);
}
if parens {
out.push(')');
}
return;
}
}
// Mixed boolean/int equality on non-constants (stack-merge
// vars of an assert desugaring: jdk26 VirtualThread
// `stack38 == stack39` with stack38 boolean, stack39 int
// 0/1 — "boolean和int不可比较"): normalize the int side
// through `!= 0`.
{
let rt = r.type_ref().erased();
if matches!(op, BinOp::Eq | BinOp::Ne)
&& ((lt == crate::types::JavaType::Boolean
&& rt == crate::types::JavaType::Int)
|| (lt == crate::types::JavaType::Int
&& rt == crate::types::JavaType::Boolean))
{
for (i, side) in [l, r].iter().enumerate() {
if i > 0 {
out.push(' ');
out.push_str(op.symbol());
out.push(' ');
}
if side.type_ref().erased() == crate::types::JavaType::Boolean {
self.expr_bool(side, out);
} else {
out.push('(');
self.expr(side, 1, out);
out.push_str(" != 0)");
}
}
if parens {
out.push(')');
}
return;
}
}
let p = op.precedence();
self.expr(l, p, out);
out.push(' ');
out.push_str(op.symbol());
out.push(' ');
self.expr(r, p + 1, out);
}
Expr::Cond { c, t, f } => {
self.expr(c, 3, out);
out.push_str(" ? ");
let prev = std::mem::replace(&mut self.in_cond, true);
self.expr(t, 2, out);
out.push_str(" : ");
self.expr(f, 2, out);
self.in_cond = prev;
}
Expr::Assign { target, op, value } => {
// The local's VarTable type is authoritative: booleanize
// flips vt types after the embedded Local tys were frozen
// (Security `boolean var4_122 = 1` printed the int form —
// "int无法转换为boolean").
let tgt_er = match &**target {
Expr::Local { var, .. } => self.vt.var(*var).ty.erased(),
other => other.type_ref().erased(),
};
self.expr(target, 1, out);
out.push(' ');
out.push_str(op.symbol());
out.push(' ');
if matches!(op, crate::ir::expr::AssignOp::Plain) {
// Narrow-target assignments render int constants in the
// target's form (jdk11/17/26 xml Parser: `mESt = ch !=
// 116 ? 512 : 60` against `private char mESt` —
// "从int转换到char可能会有损失").
match tgt_er {
crate::types::JavaType::Boolean => self.expr_bool(value, out),
crate::types::JavaType::Char => self.expr_char(value, out),
crate::types::JavaType::Byte => {
self.expr_narrow(value, &crate::types::JavaType::Byte, out)
}
crate::types::JavaType::Short => {
self.expr_narrow(value, &crate::types::JavaType::Short, out)
}
_ => self.expr(value, 1, out),
}
} else {
self.expr(value, 1, out);
}
}
Expr::PreIncDec { e, delta, .. } => {
out.push_str(if *delta > 0 { "++" } else { "--" });
self.expr(e, 14, out);
}
Expr::PostIncDec { e, delta, .. } => {
self.expr(e, 14, out);
out.push_str(if *delta > 0 { "++" } else { "--" });
}
Expr::Lambda(l) => self.lambda(l, out),
Expr::AnonNew {
base, args, body, ..
} => {
out.push_str("new ");
let base_s = self.type_name(base);
out.push_str(&base_s);
out.push('(');
// Render the ctor args through the base class's matching
// <init> descriptor: an int 0/1 at a boolean parameter
// must print as false/true (jdk11 Console's anonymous
// PrintWriter subclass — `new PrintWriter(out, 1)` finds
// no ctor). Pick the arity-matching ctor whose param
// erasures best fit the actual arg types.
let base_internal = match base {
TypeRef::J(crate::types::JavaType::Object(n)) => Some(n.clone()),
TypeRef::G(crate::types::GenericType::Class(cs)) => {
Some(crate::typeutil::classsig_internal(cs).into())
}
_ => None,
};
// Overload choice for the ctor args (int 0/1 at a boolean
// formal must print false/true) reads the base class's own
// `<init>` set: front-end metadata.
let ctor_params = base_internal
.and_then(|bi| self.ctx.ctor_param_types(&bi, 0, args.len(), args));
match ctor_params {
Some(pt) => self.args_typed(args, &pt, out),
None => self.args(args, out),
}
out.push_str(") {\n");
for line in body.lines() {
for _ in 0..self.indent + 1 {
out.push_str(" ");
}
out.push_str(line.trim_start_matches(' '));
out.push('\n');
}
for _ in 0..self.indent {
out.push_str(" ");
}
out.push('}');
}
Expr::StringConcat(parts) => {
let mut first = true;
// Java semantics: the concatenation must start with a
// String. NOT for an empty parts list: the trailing
// is_empty guard below already prints `""` — both firing
// printed four quotes.
let needs_prefix =
!parts.is_empty() && !matches!(parts.first(), Some(ConcatPart::Const(_)));
if needs_prefix {
out.push_str("\"\"");
first = false;
}
for p in parts {
// Right-hand operands of `+` need parens at equal
// precedence to keep arithmetic grouping (`"t" + (x+1)`).
let is_first = first;
if !first {
out.push_str(" + ");
}
first = false;
match p {
ConcatPart::Const(s) => {
out.push('"');
out.push_str(&escape_string(s));
out.push('"');
}
ConcatPart::Str(e) => self.expr(e, if is_first { 12 } else { 13 }, out),
}
}
if parts.is_empty() {
out.push_str("\"\"");
}
}
Expr::Invokedynamic {
name,
args,
bsm_text,
..
} => {
if name.starts_with('\u{0}') {
out.push_str("/*bad-cmp*/0");
} else {
out.push_str("/* invokedynamic ");
out.push_str(name);
out.push(' ');
out.push_str(bsm_text);
out.push_str(" */ (");
self.args(args, out);
out.push(')');
}
}
}
if parens {
out.push(')');
}
}
fn args(&mut self, args: &[Expr], out: &mut String) {
for (i, a) in args.iter().enumerate() {
if i > 0 {
out.push_str(", ");
}
self.expr(a, 1, out);
}
}
/// Print call args applying boolean-parameter constant adjustment.
/// Delegation (this(..)/super(..)) args: typed rendering PLUS the
/// elided-upcast restoration when the arg's static type differs from
/// the descriptor formal — overload resolution binds the arg's type,
/// not the descriptor (jdk17 JarEntry copy ctor: `this(je)` resolves
/// recursively to JarEntry(JarEntry); the source `this((ZipEntry) je)`
/// upcast is elided from bytecode because je <: ZipEntry is provable).
fn args_delegation(
&mut self,
args: &[Expr],
param_types: &[crate::types::JavaType],
out: &mut String,
) {
// Inner-class ctor descriptors carry the synthetic outer param
// while the expression args are outer-stripped: align the formals
// with the TRAIL of the args, like apply_ctor_param_casts (jdk11
// ZipFileInflaterInputStream this(zfin, res, res.getInflater(),
// size) was cast against the shifted descriptor formals —
// (ZipFile) zfin, (ZipFileInputStream) res... x3 inconvertible).
let off = param_types.len().saturating_sub(args.len());
for (i, a) in args.iter().enumerate() {
if i > 0 {
out.push_str(", ");
}
match param_types.get(off + i) {
Some(pt @ crate::types::JavaType::Object(_)) => {
let have = a.type_ref().erased();
// Generically-typed args (typevars/parameterized) are
// already source-typed: casting them to the descriptor
// erasure breaks convertibility to typevar formals
// (jdk17 StreamSpliterators SliceSpliterator.OfPrimitive
// this((Spliterator.OfPrimitive) s, ..) against a
// T_SPLITR formal — OfPrimitive无法转换为T_SPLITR).
if &have != pt
&& !matches!(a.type_ref(), TypeRef::G(_))
&& !matches!(
a,
Expr::Cast { .. }
| Expr::Const(_)
| Expr::Lambda(_)
| Expr::New { .. }
| Expr::AnonNew { .. }
)
{
out.push('(');
out.push_str(&self.type_name(&TypeRef::J(pt.clone())));
out.push_str(") ");
self.expr(a, 14, out);
continue;
}
self.expr(a, 1, out);
}
Some(crate::types::JavaType::Boolean) => self.expr_bool(a, out),
Some(crate::types::JavaType::Char) => self.expr_char(a, out),
Some(pt @ (crate::types::JavaType::Byte | crate::types::JavaType::Short)) => {
self.expr_narrow_arg(a, pt, out)
}
_ => self.expr(a, 1, out),
}
}
}
fn args_typed(
&mut self,
args: &[Expr],
param_types: &[crate::types::JavaType],
out: &mut String,
) {
self.args_typed_sam(args, param_types, &[], out)
}
/// args_typed with per-argument SAM-return priming: a lambda actual at
/// a parameterized-SAM formal of a pinned generic ctor gets its body
/// return cast from the formal's instantiated SAM return (jdk11/17/26
/// Collectors.toUnmodifiable*'s finisher `list -> (List<T>)
/// List.of(list.toArray())` — the erased instantiatedMethodType says
/// only List, so the generic cast is recoverable solely from the
/// diamond's resolved formal).
fn args_typed_sam(
&mut self,
args: &[Expr],
param_types: &[crate::types::JavaType],
sam_rets: &[Option<TypeRef>],
out: &mut String,
) {
for (i, a) in args.iter().enumerate() {
if i > 0 {
out.push_str(", ");
}
match param_types.get(i) {
Some(crate::types::JavaType::Boolean) => self.expr_bool(a, out),
// Char/narrow params: expr_char/expr_narrow render both
// constants AND conditional branches in the target form
// (jdk17 BasicAuthentication `super(!isProxy ? 115 : 112,
// ..)` — the char param needs `!isProxy ? 's' : 'p'`;
// a plain int ternary is "条件表达式中的类型错误").
Some(crate::types::JavaType::Char) => self.expr_char(a, out),
// Byte/short parameters: an int literal argument needs an
// explicit cast (invocation conversion never narrows, even
// for in-range constants) — and so do the branches of an
// int conditional (jdk CompressedResourceHeader
// `buffer.put(isTerminal ? (byte) 1 : (byte) 0)` — the
// byte casts fold away in bytecode; a bare int ternary is
// "对于put(int), 找不到合适的方法" x3 trees).
Some(crate::types::JavaType::Byte) | Some(crate::types::JavaType::Short) => {
self.expr_narrow_arg(a, ¶m_types[i].clone(), out);
}
_ => {
let lam_under_cast = matches!(a, Expr::Lambda(_))
|| matches!(a, Expr::Cast { e: ce, .. } if matches!(&**ce, Expr::Lambda(_)));
match sam_rets.get(i).and_then(|x| x.as_ref()) {
Some(t) if lam_under_cast => {
let prev = self.lambda_sam_ret.replace(t.clone());
self.expr(a, 1, out);
self.lambda_sam_ret = prev;
}
_ => self.expr(a, 1, out),
}
}
}
}
}
fn const_val(&self, c: &ConstVal, out: &mut String) {
match c {
ConstVal::Int(i) => out.push_str(&i.to_string()),
ConstVal::Long(l) => {
if *l == i64::MIN {
out.push_str("-9223372036854775808L");
} else {
out.push_str(&format!("{}L", l));
}
}
ConstVal::Float(f) => out.push_str(&format_float(*f as f64, true)),
ConstVal::Double(d) => out.push_str(&format_float(*d, false)),
ConstVal::Str(s) => {
out.push('"');
out.push_str(&escape_string(s));
out.push('"');
}
ConstVal::Null => out.push_str("null"),
ConstVal::ClassLit(t) => {
out.push_str(&self.type_name(t));
out.push_str(".class");
}
}
}
fn lambda(&mut self, l: &crate::ir::expr::LambdaExpr, out: &mut String) {
// A `lambda$...` implementation method in the current class is a
// compiler-generated lambda body, never a real method reference —
// emit the body inline even when classified as a reference (the
// method itself is hidden from the output).
let synthetic_self_lambda =
l.impl_name.starts_with("lambda$") && l.impl_owner == self.ctx.class_name();
match l.kind {
LambdaKind::MethodRef if !synthetic_self_lambda => {
// Determine receiver form.
if l.impl_name == "<init>" {
out.push_str(&self.shorten(&l.impl_owner));
out.push_str("::new");
return;
}
if let Some(recv) = &l.ref_receiver {
out.push_str(&self.shorten(recv));
out.push_str("::");
out.push_str(&l.impl_name);
} else if !l.captures.is_empty() {
// bound receiver: first capture is the instance
// A method-ref/lambda receiver needs its functional
// type spelled out: `A::new::get` parses as a
// QUALIFIED reference and is rejected — the source form
// is `((Supplier<A>) A::new)::get`.
let cap = &l.captures[0];
let func_ty = match cap {
Expr::Lambda(l2) => Some(l2.sam_cls.clone()),
Expr::Cast { ty, e } if matches!(**e, Expr::Lambda(_)) => {
Some(ty.erased().to_descriptor())
}
_ => None,
};
if let Some(f) = func_ty {
out.push_str("((");
out.push_str(&self.shorten(&f));
out.push_str(") ");
self.expr(cap, 1, out);
out.push(')');
} else {
self.expr(cap, 15, out);
}
out.push_str("::");
out.push_str(&l.impl_name);
} else {
out.push_str(&self.shorten(&l.impl_owner));
out.push_str("::");
out.push_str(&l.impl_name);
}
}
_ => {
if self.lambda_depth >= 8 {
out.push_str("/*nested-lambda*/null");
return;
}
// The nested-body preparation — decompiling the impl
// method and running the front-end's idiom recovery
// (anonymous inlining, capture snapshots, enum switches,
// witness casts, outer-this substitution, label pruning,
// ...) — belongs to the front-end: that is where
// machine-specific desugaring lives. Ask it for a finished
// statement tree and print that.
// The nested-body preparation — decompiling the impl method
// and running the front-end's idiom recovery (anonymous
// inlining, capture snapshots, enum switches, witness casts,
// outer-this substitution, label pruning, ...) — belongs to
// the front-end: that is where machine-specific desugaring
// lives. Ask it for a finished statement tree and print that.
let nested = self.ctx.nested_method(l, self.vt);
// params: prefer the impl method's own parameter names so the
// printed parameter list matches the body's references
// (instance lambda impls carry only the SAM params).
let mut pnames = l.param_names.clone();
if let Some(MethodBody { vt, .. }) = &nested {
let mut vt_params: Vec<String> = vt
.vars
.iter()
.filter(|v| v.is_param && v.name != "this")
.map(|v| v.name.clone())
.collect();
if vt_params.len() == pnames.len() {
pnames = vt_params;
} else if vt_params.len() > pnames.len() {
// The impl method's signature is (captures..., SAM
// params...): take the TRAILING SAM slice so the
// printed parameter list matches the body's variable
// references (ConcurrentMap.replaceAll printed
// `(x0, x1) -> { .. replace(k, v, ..) }` — undefined
// symbols; the captured `function` occupied the first
// impl slot, breaking the exact-length alignment).
let n = pnames.len();
pnames = vt_params.split_off(vt_params.len() - n);
}
}
let single = pnames.len() == 1;
if !single {
out.push('(');
}
for (i, n) in pnames.iter().enumerate() {
if i > 0 {
out.push_str(", ");
}
out.push_str(n);
}
if !single {
out.push(')');
}
out.push_str(" -> ");
let sam_wrap = self.lambda_sam_ret.take();
match nested {
Some(MethodBody {
mut body, mut vt, ..
}) => {
// Single-return body → expression lambda.
let mut single_expr = match &body {
Stmt::Return(Some(e)) => Some(e.clone()),
Stmt::Block(v) if v.len() == 1 => match &v[0] {
Stmt::Return(Some(e)) => Some(e.clone()),
_ => None,
},
_ => None,
};
// Witness the instantiated SAM return on the body's
// returns: the impl method is erased, so `i -> i`
// under `(Function<I,R>)` fails inference without
// `(R) i`.
fn sam_ok(t: &TypeRef, e: &Expr) -> bool {
!matches!(e, Expr::Cast { .. } | Expr::Const(_)) && e.type_ref() != *t
}
fn wrap_returns(s: &mut Stmt, t: &TypeRef) {
match s {
Stmt::Return(Some(e)) => {
if sam_ok(t, e) {
let v = std::mem::replace(e, Expr::This);
*e = Expr::Cast {
ty: t.clone(),
e: Box::new(v),
};
}
}
Stmt::Block(v) => v.iter_mut().for_each(|x| wrap_returns(x, t)),
Stmt::If {
then_stmt,
else_stmt,
..
} => {
wrap_returns(then_stmt, t);
if let Some(x) = else_stmt {
wrap_returns(x, t);
}
}
Stmt::While { body, .. }
| Stmt::DoWhile { body, .. }
| Stmt::ForEach { body, .. }
| Stmt::Labeled { body, .. }
| Stmt::Synchronized { body, .. } => wrap_returns(body, t),
Stmt::For { init, body, .. } => {
init.iter_mut().for_each(|i| wrap_returns(i, t));
wrap_returns(body, t);
}
Stmt::Switch { cases, default, .. } => {
for c in cases.iter_mut() {
for st in c.body.iter_mut() {
wrap_returns(st, t);
}
}
if let Some(d) = default {
wrap_returns(d, t);
}
}
Stmt::Try {
body,
catches,
finally,
} => {
wrap_returns(body, t);
for c in catches.iter_mut() {
wrap_returns(&mut c.body, t);
}
if let Some(f) = finally {
wrap_returns(f, t);
}
}
_ => {}
}
}
if let Some(t) = &sam_wrap {
if let Some(e) = &mut single_expr {
if sam_ok(t, e) {
let v = std::mem::replace(e, Expr::This);
*e = Expr::Cast {
ty: t.clone(),
e: Box::new(v),
};
} else if let TypeRef::G(_) = t {
// The body already carries the erasure
// checkcast: retype it to the generic
// SAM return (jdk26
// CopyOnWriteArrayList.toArray `i ->
// (T[]) new Object[i]` printed
// `(Object[])` — Object[]无法转换为T[]
// against IntFunction<T[]>).
if let Expr::Cast { ty: ct, e: ce } = e {
if ct.erased() == t.erased()
&& !matches!(&**ce, Expr::Cast { .. })
{
*ct = t.clone();
}
}
}
} else {
wrap_returns(&mut body, t);
}
} else if let Some(inst) = &l.inst_sam_desc {
if crate::dbg_flag!("JCDC_DBG_LAMRET") {
eprintln!(
"LAMRET impl={}.{} inst_ret={:?} single={}",
l.impl_owner,
l.impl_name,
inst.ret,
single_expr.is_some()
);
}
// The invokedynamic's instantiatedMethodType
// records the lambda's inferred return at the
// call site; a source upcast can be elided from
// the bytecode when provable (jdk17
// JrtFileSystem.iteratorOf: `(Path)` around
// path.resolve(..) inside map(child -> ...) —
// JrtPath <: Path needs no checkcast, but
// without the cast map infers Stream<JrtPath>
// and .iterator() fails the Iterator<Path>
// return). Restore it when the expression body
// is typed a strict subtype of the recorded
// return.
fn upcast_ok(
e: &Expr,
target: &crate::types::JavaType,
ctx: &dyn crate::ctx::Ctx,
) -> bool {
let crate::types::JavaType::Object(t) = target else {
return false;
};
// A parameterized (generic) value whose
// erasure IS the target reaches it unchecked
// (jdk17 CompletionStage exceptionallyCompose:
// the cond branch fn.apply(ex) types as the
// capture ? extends CompletionStage<T>; the
// erased impl return CompletionStage needs no
// cast, and printing one breaks the outer
// chain's inference).
if let TypeRef::G(crate::types::GenericType::Class(cs)) =
e.type_ref()
{
if crate::typeutil::classsig_internal(&cs).as_str() == t.as_ref() {
return true;
}
}
let crate::types::JavaType::Object(e0) = e.type_ref().erased()
else {
return false;
};
if &e0 == t {
return false;
}
let mut queue = vec![e0];
let mut seen = std::collections::HashSet::new();
while let Some(cur) = queue.pop() {
if !seen.insert(cur.clone()) {
continue;
}
if !ctx.has_class(&cur) {
continue;
}
for (sup, _) in ctx.class_supers_args(&cur, &[]) {
if sup.as_str() == t.as_ref() {
return true;
}
queue.push(sup.into());
}
}
false
}
let want = TypeRef::J(inst.ret.clone());
// The sam_wrap prime (declared local / pinned
// ctor formal / generic-call formal) carries the
// GENERIC SAM return the erased
// instantiatedMethodType lost: upgrade an
// existing erasure-equal cast on the body (jdk26
// CopyOnWriteArrayList.toArray's `i -> (T[]) new
// Object[i]` printed `(Object[])` — the real
// checkcast erases T[] and Object[] alike;
// Object[]无法转换为T[] against
// IntFunction<T[]>).
let g_want: Option<TypeRef> = sam_wrap.as_ref().and_then(|t| {
if let TypeRef::G(g) = t {
if TypeRef::G(g.clone()).erased() == inst.ret {
return Some(t.clone());
}
}
None
});
if let Some(e) = &mut single_expr {
if crate::dbg_flag!("JCDC_DBG_LAMRET") {
eprintln!(
"LAMRET2 inst_ret={:?} expr_ty={:?} sam_ok={} upcast_ok={} g_want={:?}",
inst.ret,
e.type_ref(),
sam_ok(&want, e),
upcast_ok(e, &inst.ret, self.ctx),
g_want
);
}
let mut upgraded = false;
if let Some(gw) = &g_want {
if let Expr::Cast { ty, e: ce } = e {
if ty.erased() == inst.ret
&& !matches!(&**ce, Expr::Cast { .. })
{
*ty = gw.clone();
upgraded = true;
}
}
}
if !upgraded
&& sam_ok(&want, e)
&& upcast_ok(e, &inst.ret, self.ctx)
{
let v = std::mem::replace(e, Expr::This);
*e = Expr::Cast {
ty: want,
e: Box::new(v),
};
}
}
}
// A nested lambda body shares the ENCLOSING
// lambda's scope rules: its own locals must not
// redeclare names visible there (jdk26
// MethodHandleProxies.createTemplate — the clb
// lambda's foreach-desugared `i$`/`mi` collided
// with the nested cob lambda's own `i$`/`mi`,
// 已在方法中定义了变量 x2). Rename the inner
// impl's non-param locals on collision; the
// method-level twin is handled by
// disambiguate_lambda_locals.
{
let mut outer_names: std::collections::HashSet<&str> =
self.vt.vars.iter().map(|v| v.name.as_str()).collect();
outer_names.extend(self.outer_names.iter().map(|n| n.as_str()));
let mut used: std::collections::HashSet<String> =
vt.vars.iter().map(|v| v.name.clone()).collect();
for v in vt.vars.iter_mut() {
if v.is_param || !outer_names.contains(v.name.as_str()) {
continue;
}
let base = v.name.clone();
let mut k = 1;
loop {
let cand = format!("{}${}", base, k);
if !used.contains(&cand) && !outer_names.contains(cand.as_str())
{
used.insert(cand.clone());
v.name = cand;
break;
}
k += 1;
}
}
}
let mut sub = Printer {
ctx: self.ctx,
vt: &vt,
out: String::new(),
line_buf: String::new(),
indent: self.indent,
lambda_depth: self.lambda_depth + 1,
ignored_seq: self.ignored_seq,
outer_names: {
let mut n = self.outer_names.clone();
n.extend(self.vt.vars.iter().map(|v| v.name.clone()));
n
},
// The SAM's return type governs the impl
// body's renders: boolean SAMs must print
// `return true;` not the JVM-int `return 1;`
// (jdk26 Gatherers.fold's ofGreedy lambda).
ret_bool: l.sam_desc.ret == crate::types::JavaType::Boolean,
ret_char: l.sam_desc.ret == crate::types::JavaType::Char,
ret_byte: l.sam_desc.ret == crate::types::JavaType::Byte,
ret_short: l.sam_desc.ret == crate::types::JavaType::Short,
suppress_poly_cast: false,
suppress_diamond: false,
// A lambda body is a fresh expression context:
// the enclosing conditional's pre-8 non-poly
// rule does not propagate into it (the lambda
// is a standalone method body).
in_cond: false,
lambda_sam_ret: None,
ret_sam: None,
twin_cache: self.twin_cache.clone(),
};
if let Some(e) = single_expr {
if l.sam_desc.ret == crate::types::JavaType::Boolean {
sub.expr_bool(&e, out);
} else {
sub.expr(&e, 1, out);
}
} else {
out.push_str("{\n");
sub.indent += 1;
sub.stmt(&body);
let text = sub.out;
out.push_str(&text);
for _ in 0..self.indent {
out.push_str(" ");
}
out.push('}');
}
}
None => {
out.push_str("/* lambda body in ");
out.push_str(&l.impl_owner);
out.push('.');
out.push_str(&l.impl_name);
out.push_str(" */ {}");
}
}
}
}
}
// ---------------- names & types ----------------
/// True if `cls` is a member inner class (declares this$0) per the pool.
/// Parameter types of the `<init>` matching `skip + n` descriptor args,
/// returning the tail after `skip` leading synthetic params. Used to
/// print `new` arguments with boolean/char constant adjustment.
fn ctor_param_types(
&self,
cls: &str,
skip: usize,
n: usize,
args: &[Expr],
) -> Option<Vec<crate::types::JavaType>> {
// Overload/parameter recovery from the class's own `<init>` set is
// container metadata: the front-end answers it.
self.ctx.ctor_param_types(cls, skip, n, args)
}
fn is_member_inner(&self, cls: &str) -> bool {
// Front-end metadata question: synthetic outer field, or an enclosing
// instance forwarded to super?
if self.ctx.class_has_this0(cls) {
return true;
}
if !cls.contains('$') || self.ctx.nested_is_static(cls) {
return false;
}
self.ctx.outer_param_via_super(cls)
}
/// Is `cls` lexically enclosing the CURRENT class in the RENDERED
/// layout? Digit-tail classes (anonymous/d8-lambda shapes) and
/// `-`-tail classes (Kotlin `X$-CC` facades — `-` is not a Java
/// identifier start, so the class renders as a flat mangled
/// top-level file, mirroring ddc-dec's clean_member_tail) are
/// emitted as separate flat top-level files — the nested lexical
/// scope they would provide does not exist there, so members of an
/// outer class must be QUALIFIED from them (weibo
/// CronetUrlRequest$3: bare `_$$Nest$misDoneLocked(..)` calls of
/// the outer's statics were unresolvable).
fn renders_nested_in(&self, cls: &str) -> bool {
let cur = self.ctx.class_name();
if !cur.starts_with(&format!("{}$", cls)) {
return false;
}
let mut c = cur.to_string();
while c.as_str() != cls {
let tail = c.rsplit('$').next().unwrap_or(&c);
if tail.is_empty()
|| tail.chars().next().is_some_and(|ch| ch.is_ascii_digit())
|| tail.starts_with('-')
{
return false; // flat-rendered boundary: no lexical scope
}
match c.rfind('$') {
Some(i) => c.truncate(i),
None => return false,
}
}
true
}
/// Instantiated SAM return for a cast to a generic functional
/// interface (`(Function<I,R>) lambda`): resolves the interface's SAM
/// method Signature return against the cast's type arguments. Only
/// meaningful when the result still contains a type variable — the
/// erased impl body then needs `(R) value` witnesses on its returns
/// (javac: "return type I cannot be converted to R" for `i -> i`).
fn sam_ret_cast(&self, g: &crate::types::GenericType, sam_name: &str) -> Option<TypeRef> {
// Resolving a functional interface's SAM return against a cast's type
// arguments reads the interface's method signatures: front-end
// metadata.
self.ctx.sam_ret_cast(g, sam_name)
}
/// `<>` when `new cls(...)` should carry a diamond: the class is
/// generic (class-level Signature with type params) and THIS file is
/// Java 7+. A bare generic new compiles under old-style inference
/// (standalone, not target-typed), which collapses to Object when
/// implicitly-typed lambda args are involved — jdk11 Collectors.
/// summingInt's `new CollectorImpl<>(() -> new int[1], (a, t) -> ...)`
/// fails as bare `new CollectorImpl(...)` ("array required, but found
/// Object", 72 errors in the concurrent-family closure). Bytecode
/// cannot distinguish diamond from bare, so always prefer the diamond
/// for generic classes.
fn diamond_for(&self, cls: &str) -> &'static str {
if self.ctx.source_level() < 51 {
return "";
}
if self.ctx.class_declares_generics(cls) {
"<>"
} else {
""
}
}
/// Shorten an internal class name for emission: java.lang.* and same
/// package use simple names; others fully qualified dotted.
/// True when `cls.name` is a PRIVATE instance field and the owner
/// expression's compile-time type is a strict subclass of cls: the
/// field is not in the subclass's member scope, so the source must
/// cast the owner to the declaring class
/// (`((MessageDigest)this).algorithm` — jdk11 Delegate.clone x3,
/// Signature.clone).
fn private_super_field(&self, cls: &str, name: &str, o: &Expr) -> bool {
if matches!(o, Expr::Raw(_) | Expr::RawT(..)) {
return false;
}
let owner_ct = if matches!(o, Expr::This) {
self.ctx.class_name().into()
} else {
match o.type_ref().erased() {
crate::types::JavaType::Object(n) => n,
_ => return false,
}
};
if owner_ct.as_ref() == cls {
return false;
}
let Some(flags) = self.ctx.field_flags(cls, name) else {
return false;
};
if flags.contains(crate::types::FieldAccessFlags::STATIC)
|| !flags.contains(crate::types::FieldAccessFlags::PRIVATE)
{
return false;
}
// cls must be a strict superclass of the owner's compile-time type.
let mut cur = owner_ct;
for _ in 0..64 {
let Some(sup) = self.ctx.super_name(&cur) else {
return false;
};
if sup == cls {
return true;
}
cur = sup.into();
}
false
}
fn needs_owner_cast(
&self,
cls: &str,
name: &str,
desc: &crate::types::MethodDescriptor,
o: &Expr,
) -> bool {
// Raw-rendered owners (qualified `HashMap.this`, substituted
// capture text) carry no trustworthy static type — and casting
// them to a RAW class erases the whole generic member chain
// (`((HashMap) HashMap.this).<T>keysToArray(..)` made the call
// raw: "Object[]无法转换为T[]").
if matches!(o, Expr::Raw(_) | Expr::RawT(..) | Expr::This) {
return false;
}
let crate::types::JavaType::Object(on) = o.type_ref().erased() else {
return false;
};
if on.as_ref() == cls {
return false;
}
// A receiver widened to Object (Kotlin `when` materialization
// residue — every branch's value lowered into one slot) cannot
// resolve ANY member: cast to the invoke's resolved class. The
// bytecode guarantees the runtime type (invokevirtual dispatch
// on exactly this object), so the cast is always honest.
if on.as_ref() == "java/lang/Object" && cls != "java/lang/Object" {
return true;
}
let want = format!(
"({}){}",
desc.args
.iter()
.map(|t| t.to_descriptor())
.collect::<String>(),
desc.ret.to_descriptor()
);
// The receiver's static type is a strict SUPERTYPE of the
// resolved class (register reuse left the vt at the supertype):
// the member lives on `cls`, and the downcast is exactly what
// the bytecode's resolution performed. ONLY when the owner type
// cannot resolve the member itself: an interface-typed owner
// whose IMPL the dex named resolves fine through the
// interface, and casting to the impl sprinkles obscured/flat
// impl names into expression position (weixin +3.3k
// cannot-find when this fired unguarded).
if self.ctx.is_subtype_of(
&crate::types::JavaType::Object(std::sync::Arc::from(cls)),
on.as_ref(),
) && self.ctx.method_flags(on.as_ref(), name, &want).is_none()
{
return true;
}
let Some(acc) = self.ctx.method_flags(cls, name, &want) else {
return false;
};
use crate::types::MethodAccessFlags as M;
if acc.contains(M::PRIVATE) {
return true;
}
if !acc.contains(M::PUBLIC) && !acc.contains(M::PROTECTED) {
fn pkg(n: &str) -> &str {
n.rsplit_once('/').map(|(p, _)| p).unwrap_or("")
}
return pkg(&on) != pkg(cls);
}
false
}
fn needs_object_relay(&self, ty: &TypeRef, e: &Expr) -> bool {
if matches!(e, Expr::Cast { .. } | Expr::Const(_)) {
return false;
}
let (crate::types::JavaType::Object(from), crate::types::JavaType::Object(to)) =
(e.type_ref().erased(), ty.erased())
else {
return false;
};
if from == to || from.as_ref() == "java/lang/Object" || to.as_ref() == "java/lang/Object" {
return false;
}
// A KNOWN interface on either side keeps the direct form legal
// (casts/instanceof against an interface compile regardless of
// the operand's class).
let known_itf = |n: &str| self.ctx.has_class(n) && self.ctx.is_interface(n);
if known_itf(&from) || known_itf(&to) {
if self.ctx.has_class(&from) && self.ctx.has_class(&to) {
if self.ctx.is_subtype_of(&e.type_ref().erased(), &to)
|| self.ctx.is_subtype_of(&ty.erased(), &from)
{
return false;
}
return self.ctx.is_sealed(&from) || self.ctx.is_sealed(&to);
}
return false;
}
if self.ctx.has_class(&from) && self.ctx.has_class(&to) {
if self.ctx.is_subtype_of(&e.type_ref().erased(), &to)
|| self.ctx.is_subtype_of(&ty.erased(), &from)
{
return false;
}
let both_classes = !self.ctx.is_interface(&from) && !self.ctx.is_interface(&to);
return both_classes || self.ctx.is_sealed(&from) || self.ctx.is_sealed(&to);
}
// Off-pool (framework) side: the hierarchy is unknowable here.
// A direct cast fails exactly when both sides are classes and
// unrelated — treat unknowns as classes (java/lang/Throwable,
// Error, android.media.MediaCodec$CodecException all are) and
// relay through Object; the relay never changes cast semantics
// (`(T) e` vs `(T)(Object) e` — same runtime check), it only
// widens compile legality (weixin EncoderWriter
// `(CodecException) error2` with error2: Error, ry0/d4
// `(k) th3x` with th3x: Throwable — 不兼容的类型 ×250+).
true
}
pub fn shorten(&self, internal: &str) -> String {
// NOTE: deliberately NOT memoized across Printers — shorten_inner
// consults per-Printer state (the emitting class's package via
// ctx.class_name, its fields, and this method's vt.vars for the
// shadowed-simple-name check), so the result is not a pure
// function of (pool, internal).
// Class-file names may contain characters Java cannot parse
// (R8 desugared `Collection$-EL`) — EVERY return path runs the
// deterministic sanitizer (early returns bypassed it).
sanitize_source_name(&self.shorten_inner(internal, true))
}
/// Like `shorten` but WITHOUT the anonymous-class → interface/super
/// fallback: used at `new <cls>` sites so a d8/R8-desugared lambda
/// class (which ends in `$<digits>` like an anonymous class) prints as
/// its concrete, instantiable binary name instead of its abstract SAM
/// interface. Type positions keep using `shorten` (interface), so the
/// declaration and the constructor disagree in the correct direction:
/// `Function0 v = new Outer$..$log$1(..)`.
pub fn shorten_concrete(&self, internal: &str) -> String {
// Field-obscured package first segments (JLS 6.4.2): the
// qualified render is captured by the field, but the simple
// resolves through the file's import (JLS 7.5.1 legally
// shadows same-package siblings — the blocked set proved this
// file uses none of them). Static-member qualifiers printed
// qualified through the capture (lark pq/e: field `e2` ate
// `e2.c.b(..)` — "变量 c" ×47); digit-tail names never reach
// here (obscured_render_pub rejects un-importable simples).
if let Some(simple) = self.ctx.obscured_simple(internal) {
return sanitize_source_name(&simple);
}
sanitize_source_name(&self.shorten_inner(internal, false))
}
/// Nesting-aware display chain: a `$` boundary dots ONLY when the
/// prefix has a resolvable outer (a true member); when the prefix
/// is itself an emission-unit top-level (R8 deleted the outer —
/// weixin matrix `JiffiesMonitorFeature` gone, `$JiffiesSnapshot`
/// survives as a flat file), its `$` stays and the member tail dots
/// onto it: `...JiffiesMonitorFeature$JiffiesSnapshot.ThreadJiffiesEntry`.
/// Blind `$`→`.` rendered a chain through the missing type
/// ("是在不可访问的类或接口中定义的").
fn nested_display(&self, internal: &str) -> String {
if let Some(o) = self.ctx.find_outer(internal) {
// The nesting boundary must be a literal `$` — a pool prefix
// followed by another char (`c$1` inside `c$1-IA`) is not an
// outer of this name.
if internal.len() > o.len() + 1
&& internal.starts_with(&o)
&& internal.as_bytes()[o.len()] == b'$'
{
let tail = &internal[o.len() + 1..];
if !tail.is_empty() && !tail.starts_with('$') && !tail.contains('/') {
// The tail may span several member levels
// (`a17$a18`): below a RESOLVED outer they are all
// inline members of the family file — dot them.
return format!(
"{}.{}",
self.nested_display(&o),
tail.replace('$', ".")
);
}
}
}
// Base: a POOL class with no resolvable outer is a flat `$`-named
// emission unit — keep the `$` (its file name carries it). An
// off-pool name is a framework member class (android.jar's
// `LinearLayout$LayoutParams`) — dot it like the old blind
// replace; the jar declares it as a member.
if self.ctx.has_class(internal) {
internal.replace('/', ".")
} else {
internal.replace(['/', '$'], ".")
}
}
/// Walk the MEMBER-TYPE scope of the emitting class: every lexical
/// `$`-outer level, and at each level its superclass chain and direct
/// interfaces — JLS 8.1.6: member types are INHERITED into scope, so
/// a superclass's nested `a` captures the bare simple name `a` exactly
/// like an own nestee (weixin pk4.d extends k0: same-package class ref
/// `a.d` bound to inherited k0$a — "找不到符号 变量 d, 位置: 类 a").
/// `f` is called with each in-scope class's internal name; the walk
/// stops early when `f` returns true.
fn scope_member_walk<F: FnMut(&str) -> bool>(&self, f: &mut F) -> bool {
let mut cur: &str = self.ctx.class_name();
loop {
let mut stack: Vec<String> = vec![cur.to_string()];
let mut seen: crate::FxHashSet<String> = crate::FxHashSet::default();
while let Some(c) = stack.pop() {
if !seen.insert(c.clone()) {
continue;
}
if f(&c) {
return true;
}
if let Some((ifaces, sup)) = self.ctx.class_bases(&c) {
for i in ifaces {
stack.push(i);
}
if let Some(s) = sup {
if s != "java/lang/Object" {
stack.push(s);
}
}
}
}
match cur.rfind('$') {
Some(i) => cur = &cur[..i],
None => break,
}
}
false
}
fn shorten_inner(&self, internal: &str, anon_fallback: bool) -> String {
if internal.is_empty() {
return String::new();
}
// An import-resolved obscured reference renders its simple name
// (the qualified form binds to an in-scope class — JLS 6.4.2).
if let Some(simple) = self.ctx.obscured_simple(internal) {
return simple;
}
// Case-collision renames (`X/Cua` → `X/Cua_2`): the registry is
// empty for ordinary corpora — one relaxed atomic load.
let orig_internal = internal;
// Framework-shadow stub: the reference means the PLATFORM class —
// the raw FQN (only the stub's own file identity relocated).
let cow = if self.ctx.is_fw_shadow(internal) {
std::borrow::Cow::Borrowed(internal)
} else {
crate::rename::apply_class_rename(internal)
};
let internal: &str = &cow;
// Literal-$ top-level class (in pool, no InnerClasses nesting
// evidence): the $ is part of the SOURCE name (jextract-generated
// errno_h$shared) — never dot it into a nested qualifier. Same rule
// whenever dotting could not parse: `DolTest2$$dollah$$` has empty
// segments, and `$` is a legal identifier character while `A..b` is
// not.
let dot_safe = |simple: &str| -> bool {
// A LEADING `$` (`$Gson$Types`) is part of the source name —
// dotting it yields `.Gson.Types` with a leading dot.
simple.split('$').all(|seg| {
!seg.is_empty()
&& seg
.chars()
.next()
.map(|c| c.is_ascii_alphabetic() || c == '_')
.unwrap_or(false)
})
};
let simple_here = internal.rsplit('/').next().unwrap_or(internal).to_string();
// Identifier-unsafe characters ANYWHERE in the name (Kotlin's
// `-IA`/`-EL` hyphen markers: `org/a/c/c$1-IA`; R8 unicode
// obfuscation: the Thai/Yi/Syriac classes of bin.mt.plus,
// ejfkdev/ddc#4) are not source identifiers and can never be
// nested members or local classes — they emit as FLAT sanitized
// files, so references must render the same sanitized full name
// (`_u<hex>` escapes on BOTH sides). The local-class digit-strip
// path mangled them (`1-IA` → `-IA` → `_IA`, weibo ×157), and a
// raw-unicode ref never resolves against the escaped decl.
if !internal
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$' || c == '/')
{
let dotted = sanitize_source_name(&internal.replace('/', "."));
// NESTED member whose tail is structurally clean (starts an
// identifier) but carries unsafe characters (weibo's Kotlin
// `header/a$a-IA` → member `class a_u2dIA` INSIDE a.java):
// the reference must dot the `$` boundary like the decl side
// does — the flat `header.a$a_u2dIA` resolves to nothing
// (找不到符号 类 ×~500: b2/a$a_u2dIA/b$a_u2dIA families).
// Digit-start tails (`j$1-IA`) are flat emission-unit files
// KEEPING the `$`, and non-pool names (framework
// `Collection$-EL`) have no decl at all — both stay flat.
if !simple_here.contains("$$ExternalSynthetic") {
if let Some(i) = internal.rfind('$') {
let tail = &internal[i + 1..];
let outer = &internal[..i];
let tail_clean = tail.chars().next().is_some_and(|c| {
(c.is_ascii_alphabetic() || c == '_') && !c.is_ascii_digit()
});
let outer_safe = outer
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$' || c == '/');
// has_class on BOTH forms: when an outer rename rule
// moved the family (obscuring a → a2), `internal` is
// the DISPLAY chain and the pool key is the original
// (weibo page/discover a$a-IA displayed under a2).
if tail_clean
&& outer_safe
&& (self.ctx.has_class(internal)
|| self.ctx.has_class(orig_internal))
{
return format!(
"{}.{}",
sanitize_source_name(&outer.replace('/', ".")),
sanitize_source_name(tail)
);
}
}
}
return dotted;
}
// d8's synthetic outline/lambda/backport classes
// (`X$$ExternalSyntheticLambda0`, `…ApiModelOutline0`,
// `…BackportWithForwarding0`) are TOP-LEVEL synthetics emitted as
// flat files with their full `$` name. The local-class digit-strip
// path below mangles them to the bare innermost segment
// (`ExternalSyntheticBackportWithForwarding0`) when the outer chain
// has a digit segment (`PreviewView$1$$…`), which resolves to
// nothing cross-package ("找不到符号 变量 ExternalSynthetic…", weibo
// ×467). Render the full dotted name, like the hyphen case.
if simple_here.contains("$$ExternalSynthetic") {
return sanitize_source_name(&internal.replace('/', "."));
}
let keep_dollar_pool = internal.contains('$')
&& self.ctx.has_class(internal)
&& self.ctx.find_outer(internal).is_none();
// R8 desugared-library names carry `$` inside the PACKAGE path
// (`j$/util/Collection$-EL`): a `$` followed by `/` is never a
// nesting boundary — dotting it produced `j..util`.
let dollar_in_pkg = internal.contains("$/");
let keep_dollar = keep_dollar_pool
|| dollar_in_pkg
|| (internal.contains('$') && !dot_safe(&simple_here));
// Anonymous class types (all-digit last segment) have no source
// name: print the base interface/superclass instead. Skipped for
// `new <cls>` sites (anon_fallback=false): a d8/R8-desugared
// LAMBDA class also ends in `$<digits>` (`...$lambda$N$$inlined
// $log$1`, `Outer$$ExternalSyntheticLambda0`) but IS a concrete,
// pool-rendered class — printing its SAM interface there yields an
// invalid `new Iface(..)` ("a是抽象的; 无法实例化", the biggest
// abstract-instantiation family on Kotlin corpora: v6.a/l/p =
// Function0/1/2). The var/phi TYPE positions keep the interface
// (shorten with fallback), so `Iface v = new ConcreteLambda(..)`
// stays phi-compatible across branches that mint different lambdas.
if anon_fallback {
if let Some(last) = internal.rsplit('$').next() {
if !last.is_empty() && last.chars().all(|c| c.is_ascii_digit()) {
if let Some((ifaces, sup)) = self.ctx.class_bases(internal) {
if let Some(n) = ifaces.first() {
return self.shorten(n);
}
if let Some(sup) = sup {
if sup != "java/lang/Object" {
return self.shorten(&sup);
}
}
return "Object".to_string();
}
}
}
}
// Local classes are emitted with their simple source name.
if let Some(last) = internal.rsplit('$').next() {
if !keep_dollar_pool
&& !last.is_empty()
&& !last.chars().all(|c| c.is_ascii_digit())
&& internal.contains('$')
{
// Nested-class names print as Outer.Inner, except local
// classes whose outer chain includes digits (e.g. Foo$1Bar).
let mut segs = internal.split('$');
if let Some(first) = segs.next() {
let rest: Vec<&str> = segs.collect();
if rest
.iter()
.any(|r| r.starts_with(|c: char| c.is_ascii_digit()))
{
// Local/synthetic class (digit-led segment): javac
// encodes a method-local class as `Outer$1Name`; its
// source name is the digit prefix stripped, declared
// `class Name` at its use site and referenced only
// within that scope. Printing the binary name leaves
// an unresolvable symbol (ClassSpecializer$Factory$1Var).
if let Some(last) = internal.rsplit('$').next() {
let stripped = last.trim_start_matches(|c: char| c.is_ascii_digit());
if !stripped.is_empty()
&& !stripped.chars().next().unwrap().is_ascii_digit()
{
return stripped.to_string();
}
}
return internal.replace('/', ".");
}
let _ = first;
let _ = last;
}
}
}
let dotted = internal.replace('/', ".");
// A simple type name shadowed by an in-scope VARIABLE (a field of
// this class or a method local) cannot qualify a static access:
// javac resolves the leading name as the variable first
// (无法取消引用int — jdk26 VerificationType declares
// `private static final int Integer` and the source spells
// java.lang.Integer.toHexString in full). Keep the fully-qualified
// form whenever the leading segment collides.
let shadowed = |first: &str| {
self.ctx.declares_field(self.ctx.class_name(), first)
|| self.vt.vars.iter().any(|v| v.name == first)
};
if internal.starts_with("java/lang/") && !internal[10..].contains('/') {
let simple = if keep_dollar {
internal[10..].to_string()
} else {
internal[10..].replace('$', ".")
};
let first = simple.split('.').next().unwrap_or(simple.as_str());
if !shadowed(first) {
return simple;
}
return dotted.replace('$', ".");
}
if pkg_of(internal) == pkg_of(self.ctx.class_name()) {
let simple = if keep_dollar {
internal.rsplit('/').next().unwrap_or(internal).to_string()
} else {
let d = self.nested_display(internal);
let pkg_dotted = pkg_of(internal).replace('/', ".");
d.strip_prefix(&pkg_dotted)
.and_then(|r| r.strip_prefix('.'))
.map(str::to_string)
.unwrap_or(d)
};
let first = simple.split('.').next().unwrap_or(simple.as_str());
// Member-type shadow: the emitting class's OWN nested type
// with the same simple name captures the bare render
// (member types outrank same-package types in class scope) —
// weibo PhoneInfoUtils: `b2.b(ctx,..)` for sibling class
// com/weibo/ssosdk/b2 bound to nested PhoneInfoUtils$b2
// (找不到符号 方法 b). The reference to the twin itself (or
// its own nestees) keeps the simple form. FQN fallback is
// unambiguous — no field/variable can shadow a dotted
// package chain past its first segment.
// Member-type twin shadow: a nested type of ANY enclosing
// level whose display simple name equals `first` captures
// the bare render (member types outrank same-package types
// in class scope — weixin d2's `((w1) h0)` bound to nested
// d2$$w1, not sibling viewitems/w1: 1,045 h0→w1 lines).
// Walk the `$`-chain of the emitting class (the ctx may be a
// nested `d2$$c`, whose lexical scope still sees d2's
// members); R8 orphans use `$$`, normalization displays use
// `$`, and rename displays live only in the registry's
// reverse index — check all four shapes per level.
let twin_exists = {
// The borrow temp must die before the else arm's
// borrow_mut (if-let scrutinee temps live across the
// whole statement — RefCell double-borrow panic).
let cached = self.twin_cache.borrow().get(first).copied();
if let Some(v) = cached {
v
} else {
// Own nestees AND inherited member types (the scope
// walk) capture the bare simple name alike.
let v = self.scope_member_walk(&mut |c| {
let t1 = format!("{c}${first}");
let t2 = format!("{c}$${first}");
self.ctx.has_class(&t1)
|| self.ctx.has_class(&t2)
|| crate::rename::is_renamed_display(&t1)
|| crate::rename::is_renamed_display(&t2)
});
self.twin_cache
.borrow_mut()
.insert(first.to_string(), v);
v
}
};
// is_twin_ref only matters when a twin exists (otherwise
// `!twin_exists` already grants the simple form) — keep it
// off the hot path.
let is_twin_ref = twin_exists
&& self.scope_member_walk(&mut |c| {
let t1 = format!("{c}${first}");
let t2 = format!("{c}$${first}");
internal == t1
|| internal == t2
|| internal.starts_with(&format!("{t1}$"))
|| internal.starts_with(&format!("{t2}$"))
});
if !shadowed(first) && (is_twin_ref || !twin_exists) {
return simple;
}
}
if keep_dollar {
dotted
} else {
self.nested_display(internal)
}
}
pub fn type_name(&self, ty: &TypeRef) -> String {
match ty {
TypeRef::J(t) => self.java_type_name(t),
TypeRef::G(g) => {
// Render generic signature with shortened class names.
self.generic_name(g)
}
}
}
/// Declared-type name for a local: normally `type_name` (which lets a
/// `$<digits>` class fall back to its SAM interface for phi-friendly
/// readability), but a var in `force_concrete_vars` keeps its concrete
/// binary name so concrete-member accesses (`v.L$0`, the Kotlin
/// coroutine capture fields) resolve — interfaces have no instance
/// fields.
fn local_decl_ty(&self, var: u32, ty: &TypeRef) -> String {
if self.vt.force_concrete_vars.contains(&var) {
if let TypeRef::J(JavaType::Object(cls)) = ty {
return sanitize_source_name(&self.shorten_concrete(cls));
}
}
self.type_name(ty)
}
fn java_type_name(&self, t: &JavaType) -> String {
// An import-resolved obscured class renders its simple name in
// every type position (signatures, casts, type refs).
if let JavaType::Object(c) = t {
if let Some(simple) = self.ctx.obscured_simple(c) {
// The simple is a RAW `$`/path tail — digit-leading and
// other illegal source forms must pass the sanitizer
// like every other name path (WhatsApp `11o_2 v21;`
// local-decl types, 需要';' ×16,926).
return sanitize_source_name(&simple);
}
}
match t {
JavaType::Object(n) => self.shorten(n),
JavaType::Array(inner) => format!("{}[]", self.java_type_name(inner)),
other => other.to_java(false),
}
}
fn generic_name(&self, g: &crate::types::GenericType) -> String {
use crate::types::{GenericType, WildcardBound};
match g {
GenericType::Primitive(c) => prim_name(*c).to_string(),
GenericType::Class(cs) => {
// The signature parser splits a literal-$ top-level name
// (jextract-generated errno_h$shared) into nested-looking
// parts [errno_h, shared]; rejoin and, when the pool
// proves the class is NOT nested, render the binary name
// through shorten (same-package simple form keeps the $).
if cs.parts.len() > 1 && cs.parts.iter().skip(1).all(|p| p.args.is_empty()) {
let joined = cs
.parts
.iter()
.map(|p| p.name.as_str())
.collect::<Vec<_>>()
.join("$");
let full = if cs.package.is_empty() {
joined
} else {
format!("{}/{}", cs.package, joined)
};
let literal = self.ctx.has_class(&full) && self.ctx.find_outer(&full).is_none();
if literal {
return self.shorten(&full);
}
}
let mut s = String::new();
if !cs.package.is_empty() {
let full = format!(
"{}/{}",
cs.package,
cs.parts.first().map(|p| p.name.as_str()).unwrap_or("")
);
s.push_str(&self.shorten(&full));
} else {
s.push_str(&cs.parts.first().map(|p| p.name.clone()).unwrap_or_default());
}
if let Some(first) = cs.parts.first() {
if !first.args.is_empty() {
s.push('<');
for (i, a) in first.args.iter().enumerate() {
if i > 0 {
s.push_str(", ");
}
s.push_str(&self.generic_name(a));
}
s.push('>');
}
}
for p in cs.parts.iter().skip(1) {
let digit_led = p
.name
.chars()
.next()
.map(|c| c.is_ascii_digit())
.unwrap_or(false);
let stripped = p.name.trim_start_matches(|c: char| c.is_ascii_digit());
if digit_led && !stripped.is_empty() && p.args.is_empty() {
// javac's local-class encoding `Outer$1Name`: the
// source name is the prefix-stripped simple name,
// referenced WITHOUT qualification (there is no
// legal `DocLint.1Pair` — `> or ',' expected`).
s = stripped.to_string();
continue;
}
s.push('.');
s.push_str(&p.name);
if !p.args.is_empty() {
s.push('<');
for (i, a) in p.args.iter().enumerate() {
if i > 0 {
s.push_str(", ");
}
s.push_str(&self.generic_name(a));
}
s.push('>');
}
}
s
}
GenericType::Array(inner) => format!("{}[]", self.generic_name(inner)),
GenericType::TypeVar(n) => n.clone(),
GenericType::Wildcard(w) => match w {
WildcardBound::Any => "?".to_string(),
WildcardBound::Extends(t) => format!("? extends {}", self.generic_name(t)),
WildcardBound::Super(t) => format!("? super {}", self.generic_name(t)),
},
}
}
}
fn inner_simple(cls: &str) -> String {
// Apply the class-rename registry FIRST: a renamed nested class must
// print its display tail at `outer.new Inner(..)` sites too — this
// free function was the one emit-side path bypassing the registry
// (round-55: declarations carried the rename while `this.new b()`
// printed the raw tail → cannot-find).
// Framework-shadow stub: keep the raw framework name (refs mean the
// platform class; only the file identity relocated).
let shadowed = crate::rename::fw_shadow_contains(cls);
let cow = if shadowed {
std::borrow::Cow::Borrowed(cls)
} else {
crate::rename::apply_class_rename(cls)
};
let cls: &str = &cow;
let last = cls.rsplit('/').next().unwrap_or(cls);
// R8 leaves class names ending in `$` (rimet's `ThreadMsg$$$`):
// the last `$`-segment is EMPTY — fall back to the whole simple
// name instead of printing `receiver.new (args)`.
let seg = last.rsplit('$').next().unwrap_or(last);
let last = if seg.is_empty() { last } else { seg };
// Obfuscators name classes after keywords (`v10.new do("")`): the
// qualified-new form prints this simple name raw.
let name = last.to_string();
if is_java_keyword(name.as_str())
|| is_restricted_type_name(name.as_str())
|| name.chars().next().is_some_and(|c| c.is_ascii_digit())
{
format!("_{name}")
} else if name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$')
{
name
} else {
// Non-ASCII single chars (Alipay names a field `支`) map to a
// lone `_` — itself reserved since Java 9. Escape it.
let mapped: String = name
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '_' || c == '$' {
c
} else {
'_'
}
})
.collect();
if mapped == "_" {
"__".to_string()
} else {
mapped
}
}
}
fn push_char_lit(out: &mut String, n: i32) {
let c = (n as u16) as u32;
match char::from_u32(c) {
Some('\'') => out.push_str("'\\''"),
Some('\\') => out.push_str("'\\\\'"),
Some('\n') => out.push_str("'\\n'"),
Some('\r') => out.push_str("'\\r'"),
Some('\t') => out.push_str("'\\t'"),
Some(ch) if ch.is_control() => out.push_str(&format!("'\\u{:04x}'", c)),
Some(ch) => {
out.push('\'');
out.push(ch);
out.push('\'');
}
None => out.push_str(&format!("'\\u{:04x}'", c)),
}
}
fn const_bool(e: &Expr) -> Option<bool> {
match e {
Expr::Const(ConstVal::Int(n)) => Some(*n != 0),
_ => None,
}
}
fn pkg_of(n: &str) -> &str {
n.rfind('/').map(|i| &n[..i]).unwrap_or("")
}
fn prim_name(c: char) -> &'static str {
match c {
'V' => "void",
'Z' => "boolean",
'B' => "byte",
'C' => "char",
'S' => "short",
'I' => "int",
'F' => "float",
'J' => "long",
'D' => "double",
_ => "?",
}
}
/// Kotlin emits method names like `invokeSuspend$lambda-0` — `-` and any
/// other non-identifier character is not legal Java. Deterministic
/// mapping; ddc's classdec applies the identical rule at declarations.
pub fn java_ident(name: &str) -> std::borrow::Cow<'_, str> {
let clean = name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$');
let keyword = is_java_keyword(name);
// A simple name may not START with a digit either (nova names fields
// `1x`/`2x`/`3x`): ddc's declaration side has the same branch.
let digit_start = name.chars().next().is_some_and(|c| c.is_ascii_digit());
if clean && !keyword && !digit_start {
// The overwhelmingly common case: borrow, zero allocation (this
// runs per rendered IDENTIFIER).
std::borrow::Cow::Borrowed(name)
} else if keyword || digit_start {
std::borrow::Cow::Owned(format!("_{name}"))
} else {
// Non-ASCII single chars (Alipay names a field `支`) map to a
// lone `_` — itself reserved since Java 9. Escape it.
let mapped: String = name
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '_' || c == '$' {
c
} else {
'_'
}
})
.collect();
if mapped == "_" {
std::borrow::Cow::Owned("__".to_string())
} else {
std::borrow::Cow::Owned(mapped)
}
}
}
/// Java reserved words (plus the null/true/false literals, and `_` — a
/// reserved IDENTIFIER since Java 9: Alipay's instant-run patch system
/// names fields `_`, and `javac` rejects it with "underscores are not
/// allowed here"): Kotlin emits methods and fields named `default`
/// (Companion.default()) — no Java program can name them, so both ddc's
/// declarations and these call sites map them to `_<name>` identically
/// (which turns `_` into `__`). NOTE: these are MEMBER-level escapes —
/// locals/fields/params MAY legally carry the restricted contextual
/// type names below (rt.jar has `var` locals), so those live in their
/// own predicate.
pub fn is_java_keyword(name: &str) -> bool {
matches!(
name,
"abstract" | "assert" | "boolean" | "break" | "byte" | "case" | "catch" | "char"
| "class" | "const" | "continue" | "default" | "do" | "double" | "else" | "enum"
| "extends" | "final" | "finally" | "float" | "for" | "goto" | "if" | "implements"
| "import" | "instanceof" | "int" | "interface" | "long" | "native" | "new"
| "package" | "private" | "protected" | "public" | "return" | "short" | "static"
| "strictfp" | "super" | "switch" | "synchronized" | "this" | "throw" | "throws"
| "transient" | "try" | "void" | "volatile" | "while" | "true" | "false" | "null"
| "_"
)
}
/// Restricted CONTEXTUAL type names — javac rejects them in TYPE
/// declarations and type references (`'var' 是受限类型名称`), but they
/// stay legal as member/local names (rt.jar compiles `var` locals).
/// Consulted ONLY where a CLASS name renders: type declarations,
/// segment sanitizers, the qualified-new simple name.
pub fn is_restricted_type_name(name: &str) -> bool {
matches!(
name,
"var" | "yield" | "record" | "sealed" | "permits"
)
}
/// `this` in its Raw encoding (prints as `this`; see the Raw arm).
fn is_this_expr(e: &Expr) -> bool {
matches!(e, Expr::This) || matches!(e, Expr::Raw(t) if t == "\u{3}" || t == "this")
}
/// Class-file names may contain characters Java source identifiers
/// cannot (R8 desugared `Collection$-EL`); deterministic -→_ mapping,
/// matching ddc's declaration-site java_ident.
/// Legal Java expression-statement forms (JLS 14.8): assignment, method
/// invocation, inc/dec, class instance creation.
fn is_statement_expr(e: &Expr) -> bool {
matches!(
e,
Expr::Assign { .. }
| Expr::Method { .. }
| Expr::New { .. }
| Expr::PreIncDec { .. }
| Expr::PostIncDec { .. }
)
}
pub fn sanitize_source_name(name: &str) -> String {
// Obfuscators emit classes named `if`/`do`, PACKAGES named `do`
// (weixin `package do;`) and `..badge.new..` paths (qq), WhatsApp
// nests digit-start simple names (`X/0Xx`), Kotlin mints hyphenated
// synthetic markers (`c$1-IA`, `Collection$-EL`) and R8 hardening
// even names classes in Thai/Yi/Syriac code points (bin.mt.plus —
// ejfkdev/ddc#4). EVERY identifier-unsafe character escapes to
// `_u<hex>` per code point, then identifier-position repairs apply.
// Byte-for-byte the mapping the DECLARATION side uses (ddc
// `classdec::sanitize_fq_seg`): declaration, file name and every
// reference must agree, and the escape must be INJECTIVE — the old
// fold-everything-to-`_` mapping collapsed 22,636 distinct classes
// onto 3 file names.
let segs: Vec<&str> = name.split('.').collect();
let clean = name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '$' || c == '.')
&& segs.iter().all(|seg| {
let first = seg.chars().next().unwrap_or('a');
!is_java_keyword(seg)
&& !is_restricted_type_name(seg)
&& !first.is_ascii_digit()
&& *seg != "_"
});
if clean {
return name.to_string();
}
segs.iter()
.copied()
.map(sanitize_ident_seg)
.collect::<Vec<_>>()
.join(".")
}
/// One identifier segment: escape every ident-unsafe character as
/// `_u<hex>`, then repair identifier positions (keyword / restricted
/// type name / digit start gain a leading `_`; the lone `_` reserved
/// since Java 9 becomes `__`). Mirrors ddc `sanitize_fq_seg` exactly.
fn sanitize_ident_seg(seg: &str) -> String {
let plain = seg
.chars()
.all(|c| c.is_ascii() && (c.is_ascii_alphanumeric() || c == '_' || c == '$'));
let mut out = if plain {
seg.to_string()
} else {
use std::fmt::Write as _;
let mut s = String::with_capacity(seg.len() + 8);
for c in seg.chars() {
if c.is_ascii() && (c.is_ascii_alphanumeric() || c == '_' || c == '$') {
s.push(c);
} else {
s.push_str("_u");
let _ = write!(s, "{:x}", c as u32);
}
}
s
};
if is_java_keyword(&out)
|| is_restricted_type_name(&out)
|| out.chars().next().is_some_and(|c| c.is_ascii_digit())
{
out.insert(0, '_');
}
if out == "_" {
out = "__".to_string();
}
out
}
pub fn escape_string(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
'\u{0}' => out.push_str("\\0"),
'\u{8}' => out.push_str("\\b"),
'\u{C}' => out.push_str("\\f"),
c if (c as u32) < 0x20 || (c as u32) == 0x7F => {
out.push_str(&format!("\\u{:04x}", c as u32));
}
c => out.push(c),
}
}
out
}
pub fn escape_char(c: char) -> String {
match c {
'\'' => "\\'".to_string(),
'\\' => "\\\\".to_string(),
'\n' => "\\n".to_string(),
'\r' => "\\r".to_string(),
'\t' => "\\t".to_string(),
'\0' => "\\0".to_string(),
c if (c as u32) < 0x20 || (c as u32) == 0x7F => format!("\\u{:04x}", c as u32),
c => c.to_string(),
}
}
pub fn format_float(v: f64, is_float: bool) -> String {
let suffix = if is_float { "f" } else { "" };
// Arithmetic literals, not `Double.NaN`/`POSITIVE_INFINITY` field refs:
// inside java.lang.Double/Float themselves a field reference would be
// a self-reference initializing the very field being printed.
if v.is_nan() {
return if is_float {
"(0.0f / 0.0f)".into()
} else {
"(0.0 / 0.0)".into()
};
}
if v.is_infinite() {
let one = if is_float { "1.0f" } else { "1.0" };
let zero = if is_float { "0.0f" } else { "0.0" };
return if v < 0.0 {
format!("(-{} / {})", one, zero)
} else {
format!("({} / {})", one, zero)
};
}
let mut s = format!("{}", v);
if !s.contains('.') && !s.contains('e') && !s.contains('E') {
s.push_str(".0");
}
// Java doesn't accept exponent forms like "1e-7"? It does: 1e-7 is a valid
// double literal. But "inf"/"nan" handled above.
format!("{}{}", s, suffix)
}
// ---------------------------------------------------------------------------
// Unreachable-code truncation (final statement tree)
// ---------------------------------------------------------------------------
/// Drop statements that follow a `while (true)` which cannot complete
/// normally (no `break` in its body binds to it): javac rejects them as
/// 无法访问的语句, and the structurers only emitted them as shared-tail
/// copies whose real arrivals all render INSIDE the loop arms (jdk17/26
/// Pattern.clazz's for(;;){switch}: case-93's `return prev/negate` tail
/// landed after the never-completing loop). Runs on the FINAL tree (after
/// switch restoration and goto resolution) so the break inventory is
/// exactly what gets emitted; every unknown shape stays conservative
/// (assumes the loop can complete).
fn tree_has_dead_end(s: &Stmt) -> bool {
match s {
Stmt::Block(v) => {
for (i, x) in v.iter().enumerate() {
if i > 0 && dead_end_infinite_while(&v[i - 1]) {
return true;
}
if tree_has_dead_end(x) {
return true;
}
}
false
}
Stmt::If {
then_stmt,
else_stmt,
..
} => tree_has_dead_end(then_stmt) || else_stmt.as_deref().is_some_and(tree_has_dead_end),
Stmt::While { body, .. } | Stmt::DoWhile { body, .. } => tree_has_dead_end(body),
Stmt::For { init, body, .. } => {
init.iter().any(tree_has_dead_end) || tree_has_dead_end(body)
}
Stmt::ForEach { body, .. } => tree_has_dead_end(body),
Stmt::Switch { cases, default, .. } => {
cases.iter().any(|c| c.body.iter().any(tree_has_dead_end))
|| default.as_deref().is_some_and(tree_has_dead_end)
}
Stmt::Try {
body,
catches,
finally,
} => {
tree_has_dead_end(body)
|| catches.iter().any(|c| tree_has_dead_end(&c.body))
|| finally.as_deref().is_some_and(tree_has_dead_end)
}
Stmt::TryWithResources {
resources,
body,
catches,
finally,
..
} => {
resources.iter().any(tree_has_dead_end)
|| tree_has_dead_end(body)
|| catches.iter().any(|c| tree_has_dead_end(&c.body))
|| finally.as_deref().is_some_and(tree_has_dead_end)
}
Stmt::Synchronized { body, .. } | Stmt::Labeled { body, .. } => tree_has_dead_end(body),
_ => false,
}
}
fn truncate_dead_ends(s: &Stmt) -> Stmt {
match s {
Stmt::Block(v) => {
let mut out: Vec<Stmt> = Vec::with_capacity(v.len());
for x in v {
if !out.is_empty() && dead_end_infinite_while(out.last().unwrap()) {
if crate::dbg_flag!("JCDC_DBG_GOTO") {
eprintln!(
"DEADEND truncate {} unreachable stmt(s)",
v.len() - out.len()
);
}
break;
}
out.push(truncate_dead_ends(x));
}
Stmt::Block(out)
}
Stmt::If {
cond,
then_stmt,
else_stmt,
} => Stmt::If {
cond: cond.clone(),
then_stmt: Box::new(truncate_dead_ends(then_stmt)),
else_stmt: else_stmt.as_deref().map(truncate_dead_ends).map(Box::new),
},
Stmt::While { cond, body } => Stmt::While {
cond: cond.clone(),
body: Box::new(truncate_dead_ends(body)),
},
Stmt::DoWhile { body, cond } => Stmt::DoWhile {
body: Box::new(truncate_dead_ends(body)),
cond: cond.clone(),
},
Stmt::For {
init,
cond,
update,
body,
} => Stmt::For {
init: init.iter().map(truncate_dead_ends).collect(),
cond: cond.clone(),
update: update.clone(),
body: Box::new(truncate_dead_ends(body)),
},
Stmt::ForEach {
var,
iterable,
is_array,
body,
} => Stmt::ForEach {
var: *var,
iterable: iterable.clone(),
is_array: *is_array,
body: Box::new(truncate_dead_ends(body)),
},
Stmt::Switch {
selector,
cases,
default,
on_string,
} => Stmt::Switch {
selector: selector.clone(),
cases: cases
.iter()
.map(|c| CaseGroup {
labels: c.labels.clone(),
string_labels: c.string_labels.clone(),
enum_labels: c.enum_labels.clone(),
raw_labels: c.raw_labels.clone(),
guard: c.guard.clone(),
body: c.body.iter().map(truncate_dead_ends).collect(),
})
.collect(),
default: default.as_deref().map(truncate_dead_ends).map(Box::new),
on_string: *on_string,
},
Stmt::Try {
body,
catches,
finally,
} => Stmt::Try {
body: Box::new(truncate_dead_ends(body)),
catches: catches
.iter()
.map(|c| Catch {
exc: c.exc.clone(),
var: c.var,
var_name: c.var_name.clone(),
body: Box::new(truncate_dead_ends(&c.body)),
})
.collect(),
finally: finally.as_deref().map(truncate_dead_ends).map(Box::new),
},
Stmt::TryWithResources {
resources,
body,
catches,
finally,
} => Stmt::TryWithResources {
resources: resources.iter().map(truncate_dead_ends).collect(),
body: Box::new(truncate_dead_ends(body)),
catches: catches
.iter()
.map(|c| Catch {
exc: c.exc.clone(),
var: c.var,
var_name: c.var_name.clone(),
body: Box::new(truncate_dead_ends(&c.body)),
})
.collect(),
finally: finally.as_deref().map(truncate_dead_ends).map(Box::new),
},
Stmt::Synchronized { lock, body } => Stmt::Synchronized {
lock: lock.clone(),
body: Box::new(truncate_dead_ends(body)),
},
Stmt::Labeled { label, body } => Stmt::Labeled {
label: label.clone(),
body: Box::new(truncate_dead_ends(body)),
},
other => other.clone(),
}
}
/// True when `s` is a `while (true)` (labeled or not) whose body holds
/// no `break` binding to it — it can never complete normally.
pub(crate) fn dead_end_infinite_while(s: &Stmt) -> bool {
let (label, body, cond) = match s {
Stmt::While { cond, body } => (None, body.as_ref(), cond),
Stmt::Labeled { label, body } => match &**body {
Stmt::While { cond, body } => (Some(label.as_str()), body.as_ref(), cond),
_ => return false,
},
_ => return false,
};
if !matches!(cond, Expr::Const(ConstVal::Int(1))) {
return false;
}
// JLS 14.14: `while (true)` completes normally iff its body holds a
// reachable break that exits IT: an unlabeled break not captured by
// an inner breakable construct, or `break L` where L is THIS loop's
// own label. A labeled break to any OTHER label — inner (Pattern
// .clazz's `break L4`) or OUTER (jdk11/26 ThreadPoolExecutor
// .addWorker's `break retry` inside the inner for(;;)) — completes
// the while ABRUPTLY: javac's flow model marks the statements after
// such a loop unreachable (the w26 `continue;` after the inner
// while(true) was a latent 无法访问的语句 masked by alphabetically
// earlier census errors).
!has_break_exiting(body, label, 0)
}
fn has_break_exiting(s: &Stmt, lbl: Option<&str>, depth: usize) -> bool {
match s {
Stmt::Break(None) => depth == 0,
// Only this loop's OWN label completes it; any other labeled
// break exits abruptly (JLS 14.14/14.17).
Stmt::Break(Some(l)) => Some(l.as_str()) == lbl,
Stmt::Continue(_) | Stmt::Return(_) | Stmt::Throw(_) => false,
Stmt::Goto(_) => true,
Stmt::Block(v) => v.iter().any(|x| has_break_exiting(x, lbl, depth)),
Stmt::If {
then_stmt,
else_stmt,
..
} => {
has_break_exiting(then_stmt, lbl, depth)
|| else_stmt
.as_deref()
.map(|e| has_break_exiting(e, lbl, depth))
.unwrap_or(false)
}
Stmt::While { body, .. }
| Stmt::DoWhile { body, .. }
| Stmt::For { body, .. }
| Stmt::ForEach { body, .. } => has_break_exiting(body, lbl, depth + 1),
Stmt::Switch { cases, default, .. } => {
cases
.iter()
.any(|c| c.body.iter().any(|x| has_break_exiting(x, lbl, depth + 1)))
|| default
.as_deref()
.map(|d| has_break_exiting(d, lbl, depth + 1))
.unwrap_or(false)
}
Stmt::Try {
body,
catches,
finally,
}
| Stmt::TryWithResources {
body,
catches,
finally,
..
} => {
has_break_exiting(body, lbl, depth)
|| catches
.iter()
.any(|c| has_break_exiting(&c.body, lbl, depth))
|| finally
.as_deref()
.map(|f| has_break_exiting(f, lbl, depth))
.unwrap_or(false)
}
Stmt::Synchronized { body, .. } => has_break_exiting(body, lbl, depth),
Stmt::Labeled { body, .. } => has_break_exiting(body, lbl, depth),
// Plain leaf statements never contain a break.
Stmt::ExprStmt(_)
| Stmt::LocalDef { .. }
| Stmt::Assert { .. }
| Stmt::TernaryValue { .. }
| Stmt::MonitorEnter(_)
| Stmt::MonitorExit(_)
| Stmt::Comment(_) => false,
// Opaque shapes (raw labels, inline class decls, anything new):
// keep truncation off when an escape cannot be ruled out.
_ => true,
}
}