uniffi-bindgen-java 0.5.1

a java bindings generator for uniffi rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
use anyhow::{Context, Result};
use askama::Template;
use core::fmt::Debug;
use heck::{ToLowerCamelCase, ToShoutySnakeCase, ToUpperCamelCase};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use std::{
    borrow::Borrow,
    collections::{HashMap, HashSet},
};
use uniffi_bindgen::{interface::*, to_askama_error};

mod callback_interface;
mod compounds;
mod custom;
mod enum_;
mod miscellany;
mod object;
mod primitives;
mod record;
mod variant;

/// Insert a JSpecify `@Nullable` TYPE_USE annotation at the correct position
/// in a (possibly fully-qualified) Java type name.
///
/// Per JLS §9.7.4, TYPE_USE annotations must appear directly before the simple
/// name of the type, not before the package/enclosing-class qualifier:
///   - `java.lang.String`          → `java.lang.@Nullable String`
///   - `UniffiCleaner.Cleanable`   → `UniffiCleaner.@Nullable Cleanable`
///   - `String`                    → `@Nullable String`
///   - `java.util.Map<K, V>`       → `java.util.@Nullable Map<K, V>`
pub(crate) fn nullable_type_label(type_label: &str) -> String {
    const ANNOTATION: &str = "@org.jspecify.annotations.Nullable ";
    // Only look at the portion before any generic '<' to find the right '.'
    let before_generics = type_label.find('<').unwrap_or(type_label.len());
    let prefix = &type_label[..before_generics];
    if let Some(dot_pos) = prefix.rfind('.') {
        format!(
            "{}{}{}",
            &type_label[..dot_pos + 1],
            ANNOTATION,
            &type_label[dot_pos + 1..]
        )
    } else {
        format!("{}{}", ANNOTATION, type_label)
    }
}

pub fn potentially_add_external_package(
    config: &Config,
    ci: &ComponentInterface,
    type_name: &str,
    display_name: String,
) -> String {
    match ci.get_type(type_name) {
        Some(typ) => {
            if ci.is_external(&typ) {
                format!(
                    "{}.{}",
                    config.external_type_package_name(typ.module_path().unwrap(), &display_name),
                    display_name
                )
            } else {
                display_name
            }
        }
        None => display_name,
    }
}

trait CodeType: Debug {
    /// The language specific label used to reference this type. This will be used in
    /// method signatures and property declarations.
    fn type_label(&self, ci: &ComponentInterface, config: &Config) -> String;

    /// The primitive type label if this type is a primitive (int, long, boolean, etc.).
    /// Returns None for non-primitive types.
    fn type_label_primitive(&self) -> Option<String> {
        None
    }

    /// A representation of this type label that can be used as part of another
    /// identifier. e.g. `read_foo()`, or `FooInternals`.
    ///
    /// This is especially useful when creating specialized objects or methods to deal
    /// with this type only.
    fn canonical_name(&self) -> String;

    /// Instance of the FfiConverter
    ///
    /// This is the object that contains the lower, write, lift, and read methods for this type.
    /// Depending on the binding this will either be a singleton or a class with static methods.
    ///
    /// This is the newer way of handling these methods and replaces the lower, write, lift, and
    /// read CodeType methods.
    fn ffi_converter_name(&self) -> String {
        format!("FfiConverter{}", self.canonical_name())
    }

    /// Name of the FfiConverter
    ///
    /// This is the object that contains the lower, write, lift, and read methods for this type.
    /// Depending on the binding this will either be a singleton or a class with static methods.
    ///
    /// This is the newer way of handling these methods and replaces the lower, write, lift, and
    /// read CodeType methods.
    fn ffi_converter_instance(&self, _config: &Config, _ci: &ComponentInterface) -> String {
        format!("{}.INSTANCE", self.ffi_converter_name())
    }

    /// Function to run at startup
    fn initialization_fn(&self) -> Option<String> {
        None
    }
}

// taken from https://docs.oracle.com/javase/specs/ section 3.9
static KEYWORDS: Lazy<HashSet<String>> = Lazy::new(|| {
    let kwlist = vec![
        "abstract",
        "continue",
        "for",
        "new",
        "switch",
        "assert",
        "default",
        "if",
        "package",
        "synchronized",
        "boolean",
        "do",
        "goto",
        "private",
        "this",
        "break",
        "double",
        "implements",
        "protected",
        "throw",
        "byte",
        "else",
        "import",
        "public",
        "throws",
        "case",
        "enum",
        "instanceof",
        "return",
        "transient",
        "catch",
        "extends",
        "int",
        "short",
        "try",
        "char",
        "final",
        "interface",
        "static",
        "void",
        "class",
        "finally",
        "long",
        "strictfp",
        "volatile",
        "const",
        "float",
        "native",
        "super",
        "while",
        "_",
    ];
    HashSet::from_iter(kwlist.into_iter().map(|s| s.to_string()))
});

// config options to customize the generated Java.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Config {
    pub(super) package_name: Option<String>,
    pub(super) cdylib_name: Option<String>,
    generate_immutable_records: Option<bool>,
    #[serde(default)]
    omit_checksums: bool,
    #[serde(default)]
    custom_types: HashMap<String, CustomTypeConfig>,
    #[serde(default)]
    pub(super) external_packages: HashMap<String, String>,
    #[serde(default)]
    android: bool,
    #[serde(default)]
    nullness_annotations: bool,
    /// Renames for types, fields, methods, variants, and arguments.
    /// Uses dot notation: "OldRecord" = "NewRecord", "OldRecord.field" = "new_field"
    #[serde(default)]
    pub(super) rename: toml::Table,
}

impl Config {
    pub fn omit_checksums(&self) -> bool {
        self.omit_checksums
    }

    /// Whether to generate PanamaPort imports for Android compatibility.
    /// When true, post-processes generated code to replace `java.lang.foreign.*` with
    /// PanamaPort's `com.v7878.foreign.*` and `java.lang.invoke.VarHandle` with
    /// `com.v7878.invoke.VarHandle`.
    pub fn android(&self) -> bool {
        self.android
    }

    /// Whether to generate JSpecify `@NullMarked` and `@Nullable` annotations.
    pub fn nullness_annotations(&self) -> bool {
        self.nullness_annotations
    }
}

impl Config {
    pub fn package_name(&self) -> String {
        if let Some(package_name) = &self.package_name {
            package_name.clone()
        } else {
            "uniffi".into()
        }
    }

    pub fn cdylib_name(&self) -> String {
        if let Some(cdylib_name) = &self.cdylib_name {
            cdylib_name.clone()
        } else {
            "uniffi".into()
        }
    }

    /// Whether to generate immutable records (`record` instead of `class`)
    pub fn generate_immutable_records(&self) -> bool {
        self.generate_immutable_records.unwrap_or(false)
    }

    // Get the package name for an external type
    pub fn external_type_package_name(&self, module_path: &str, namespace: &str) -> String {
        // config overrides are keyed by the crate name, default fallback is the namespace.
        let crate_name = module_path.split("::").next().unwrap();
        match self.external_packages.get(crate_name) {
            Some(name) => name.clone(),
            // unreachable in library mode - all deps are in our config with correct namespace.
            None => format!("uniffi.{namespace}"),
        }
    }
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct CustomTypeConfig {
    imports: Option<Vec<String>>,
    type_name: Option<String>,
    into_custom: String, // backcompat alias for lift
    lift: String,
    from_custom: String, // backcompat alias for lower
    lower: String,
}

// functions replace literal "{}" in strings with a specified value.
impl CustomTypeConfig {
    fn lift(&self, name: &str) -> String {
        let converter = if self.lift.is_empty() {
            &self.into_custom
        } else {
            &self.lift
        };
        converter.replace("{}", name)
    }
    fn lower(&self, name: &str) -> String {
        let converter = if self.lower.is_empty() {
            &self.from_custom
        } else {
            &self.lower
        };
        converter.replace("{}", name)
    }
}

/// Askama inlines every `include` into one generated `render_into`, and as of 0.16 the resulting
/// frame overruns the 2 MiB a spawned thread gets by default in unoptimized builds. Rendering on
/// an explicitly sized thread keeps that independent of whatever stack the caller happens to have.
const RENDER_STACK_SIZE: usize = 32 * 1024 * 1024;

/// `ForeignBytes` is a borrow that only survives one inbound call, so it works for arguments
/// travelling foreign -> Rust and nowhere else. UniFFI nevertheless puts it in the vtable for a
/// foreign-implemented method taking `&[u8]`, where it would arrive as a pointer the JVM never
/// owned; fail the build rather than emit bindings that read it.
fn reject_borrowed_bytes_in_callbacks(ci: &ComponentInterface) -> Result<()> {
    let offenders = ci
        .callback_interface_definitions()
        .iter()
        .flat_map(|cbi| cbi.methods().into_iter().map(|m| (cbi.name(), m)))
        .chain(
            ci.object_definitions()
                .iter()
                .filter(|obj| obj.has_callback_interface())
                .flat_map(|obj| obj.methods().into_iter().map(|m| (obj.name(), m))),
        )
        .filter_map(|(owner, method)| {
            let args = method
                .arguments()
                .iter()
                .filter(|arg| arg.is_borrowed_bytes())
                .map(|arg| arg.name().to_string())
                .collect::<Vec<_>>();
            (!args.is_empty()).then(|| format!("{}.{}: {}", owner, method.name(), args.join(", ")))
        })
        .collect::<Vec<_>>();

    if offenders.is_empty() {
        Ok(())
    } else {
        anyhow::bail!(
            "zero-copy `&[u8]` is only supported for arguments passed into Rust, but it appears on \
             foreign-implemented method(s): {}. Use `Vec<u8>` for these arguments.",
            offenders.join("; ")
        )
    }
}

// Generate Java bindings for the given ComponentInterface, as a string.
pub fn generate_bindings(config: &Config, ci: &ComponentInterface) -> Result<String> {
    reject_borrowed_bytes_in_callbacks(ci)?;
    std::thread::scope(|scope| {
        std::thread::Builder::new()
            .stack_size(RENDER_STACK_SIZE)
            .spawn_scoped(scope, || render_bindings(config, ci))
            .context("failed to spawn the bindings render thread")?
            .join()
            .map_err(|_| anyhow::anyhow!("the bindings render thread panicked"))?
    })
}

fn render_bindings(config: &Config, ci: &ComponentInterface) -> Result<String> {
    let output = JavaWrapper::new(config.clone(), ci)
        .render()
        .context("failed to render java bindings")?;

    if config.android() {
        // PanamaPort provides the FFM API under a different package prefix.
        // The API surface is identical so a global string replacement is sufficient.
        // `java.lang.invoke.MethodHandle/MethodHandles/MethodType` are available on
        // Android API 26+ and are intentionally left unchanged.
        Ok(output
            .replace("java.lang.foreign.", "com.v7878.foreign.")
            .replace("java.lang.invoke.VarHandle", "com.v7878.invoke.VarHandle"))
    } else {
        Ok(output)
    }
}

#[derive(Template)]
#[template(syntax = "java", escape = "none", path = "wrapper.java")]
pub struct JavaWrapper<'a> {
    config: Config,
    ci: &'a ComponentInterface,
    type_helper_code: String,
}

impl<'a> JavaWrapper<'a> {
    pub fn new(config: Config, ci: &'a ComponentInterface) -> Self {
        let type_helper_code = render_type_helpers(&config, ci).unwrap();
        Self {
            config,
            ci,
            type_helper_code,
        }
    }

    pub fn initialization_fns(&self) -> Vec<String> {
        self.ci
            .iter_local_types()
            .map(|t| JavaCodeOracle.find(t))
            .filter_map(|ct| ct.initialization_fn())
            .collect()
    }

    /// Get the namespace class name, avoiding collisions with type names.
    /// If the namespace name (after camelCase conversion) collides with any type,
    /// append "Lib" suffix repeatedly until there's no collision.
    pub fn namespace_class_name(&self) -> String {
        let base_name = JavaCodeOracle.class_name(self.ci, self.ci.namespace());

        // Collect all type names for collision checking
        let type_names: HashSet<String> = self
            .ci
            .iter_local_types()
            .map(|t| JavaCodeOracle.find(t).type_label(self.ci, &self.config))
            .collect();

        // Keep adding "Lib" suffix until there's no collision
        let mut candidate = base_name;
        while type_names.contains(&candidate) {
            candidate = format!("{}Lib", candidate);
        }
        candidate
    }
}

/// Renders the fixed helper classes and the runtime support shared by all types.
#[derive(Template)]
#[template(syntax = "java", escape = "none", path = "Types.java")]
pub struct TypeRenderer<'a> {
    config: &'a Config,
    ci: &'a ComponentInterface,
}

/// Askama inlines an `include` into the including template's `render_into`, so a single template
/// covering every type compiles into one function large enough to dominate this crate's build:
/// roughly 10 GB of rustc memory and 110s, against 380 MB and 1s for everything else combined.
/// Giving each type its own template keeps those functions small.
///
/// There is a companion match in [`JavaCodeOracle::create_code_type`]; both need an arm when a
/// type is added.
fn render_type_helpers(config: &Config, ci: &ComponentInterface) -> Result<String> {
    let mut out = TypeRenderer { config, ci }
        .render()
        .context("failed to render shared type helpers")?;
    for type_ in ci.iter_local_types() {
        out.push_str(&render_one_type(type_, config, ci)?);
    }
    for type_ in ci.iter_external_types() {
        let name = type_
            .name()
            .ok_or_else(|| anyhow::anyhow!("external type {type_:?} has no name"))?;
        let module_path = type_
            .module_path()
            .ok_or_else(|| anyhow::anyhow!("external type {type_:?} has no module path"))?;
        out.push_str(
            &ExternalTypeRenderer {
                config,
                ci,
                name,
                module_path,
            }
            .render()
            .with_context(|| format!("failed to render external type {name}"))?,
        );
    }
    Ok(out)
}

/// Whether `type_` appears anywhere in `ci` in a hashed position: as a `Set` element or `Map`
/// key, or nested under one along the `Sequence`/`Optional` spine. See [`compounds::Hashed`].
fn used_in_hashed_position(ci: &ComponentInterface, type_: &Type) -> bool {
    fn on_spine(root: &Type, target: &Type) -> bool {
        root == target
            || match root {
                Type::Sequence { inner_type } | Type::Optional { inner_type } => {
                    on_spine(inner_type, target)
                }
                _ => false,
            }
    }
    ci.iter_local_types()
        .chain(ci.iter_external_types())
        .any(|t| match t {
            Type::Set { inner_type } => on_spine(inner_type, type_),
            Type::Map { key_type, .. } => on_spine(key_type, type_),
            _ => false,
        })
}

/// Whether some type in `ci` already renders a converter with this canonical name. The
/// [`compounds::Hashed`] `bytes` aliasing can make a hashed variant coincide with a plain
/// converter; emitting both would duplicate the class.
fn universe_has_canonical(ci: &ComponentInterface, canonical: &str) -> bool {
    ci.iter_local_types()
        .chain(ci.iter_external_types())
        .any(|t| JavaCodeOracle.find(t).canonical_name() == canonical)
}

/// The hashed converter variant for `type_`, rendered if a hashed position anywhere in `ci`
/// needs it and no plain converter already has its name. Empty otherwise.
fn render_hashed_variant(type_: &Type, config: &Config, ci: &ComponentInterface) -> Result<String> {
    if !compounds::needs_hashed_rendering(type_) || !used_in_hashed_position(ci, type_) {
        return Ok(String::new());
    }
    let hashed = compounds::Hashed(type_).as_codetype();
    if universe_has_canonical(ci, &hashed.canonical_name()) {
        return Ok(String::new());
    }
    let ffi_converter_name = hashed.ffi_converter_name();
    match type_ {
        Type::Sequence { inner_type } => SequenceTypeRenderer {
            config,
            ci,
            ffi_converter_name,
            inner_type: compounds::Hashed(inner_type),
        }
        .render(),
        Type::Optional { inner_type } => OptionalTypeRenderer {
            config,
            ci,
            ffi_converter_name,
            inner_type: compounds::Hashed(inner_type),
        }
        .render(),
        Type::Bytes => SequenceTypeRenderer {
            config,
            ci,
            ffi_converter_name,
            inner_type: Type::Int8,
        }
        .render(),
        _ => unreachable!("needs_hashed_rendering matches only Sequence, Optional, and Bytes"),
    }
    .map_err(Into::into)
}

fn render_one_type(type_: &Type, config: &Config, ci: &ComponentInterface) -> Result<String> {
    let type_name = JavaCodeOracle.find(type_).type_label(ci, config);
    let ffi_converter_name = JavaCodeOracle.find(type_).ffi_converter_name();
    let contains_object_references = ci.item_contains_object_references(type_);

    let rendered = match type_ {
        Type::Boolean => BooleanHelperRenderer { config }.render(),
        Type::Bytes => ByteArrayHelperRenderer { config }.render(),
        Type::Duration => DurationHelperRenderer { config }.render(),
        Type::String => StringHelperRenderer { config }.render(),
        Type::Timestamp => TimestampHelperRenderer { config }.render(),
        Type::Int8 | Type::UInt8 => Int8HelperRenderer { config }.render(),
        Type::Int16 | Type::UInt16 => Int16HelperRenderer { config }.render(),
        Type::Int32 | Type::UInt32 => Int32HelperRenderer { config }.render(),
        Type::Int64 | Type::UInt64 => Int64HelperRenderer { config }.render(),
        Type::Float32 => Float32HelperRenderer { config }.render(),
        Type::Float64 => Float64HelperRenderer { config }.render(),

        Type::CallbackInterface { name, .. } => CallbackInterfaceTypeRenderer {
            config,
            ci,
            ffi_converter_name,
            name: name.clone(),
            cbi: ci
                .get_callback_interface_definition(name)
                .ok_or_else(|| anyhow::anyhow!("callback interface not found: {name}"))?,
        }
        .render(),

        Type::Custom { name, builtin, .. } => {
            if ci.is_external(type_) {
                Ok(String::new())
            } else {
                CustomTypeRenderer {
                    config,
                    ci,
                    type_name,
                    ffi_converter_name,
                    name: name.clone(),
                    builtin,
                }
                .render()
            }
        }

        Type::Enum { name, .. } => {
            let e = ci
                .get_enum_definition(name)
                .ok_or_else(|| anyhow::anyhow!("enum not found: {name}"))?;
            if ci.is_name_used_as_error(name) {
                ErrorTypeRenderer {
                    config,
                    ci,
                    type_,
                    contains_object_references,
                    e,
                }
                .render()
            } else {
                EnumTypeRenderer {
                    config,
                    ci,
                    type_name,
                    contains_object_references,
                    e,
                }
                .render()
            }
        }

        Type::Map {
            key_type,
            value_type,
        } => MapTypeRenderer {
            config,
            ci,
            ffi_converter_name,
            key_type: compounds::Hashed(key_type),
            value_type,
        }
        .render(),

        Type::Optional { inner_type } => OptionalTypeRenderer {
            config,
            ci,
            ffi_converter_name,
            inner_type,
        }
        .render(),

        Type::Object { name, .. } => ObjectTypeRenderer {
            config,
            ci,
            type_name,
            ffi_converter_instance: JavaCodeOracle
                .find(type_)
                .ffi_converter_instance(config, ci),
            name: name.clone(),
            obj: ci
                .get_object_definition(name)
                .ok_or_else(|| anyhow::anyhow!("object not found: {name}"))?,
            is_error: ci.is_name_used_as_error(name),
        }
        .render(),

        Type::Record { name, .. } => RecordTypeRenderer {
            config,
            ci,
            type_name,
            contains_object_references,
            name,
        }
        .render(),

        Type::Sequence { inner_type } => match inner_type.as_ref() {
            Type::Int16 | Type::UInt16 => Int16ArrayHelperRenderer { config }.render(),
            Type::Int32 | Type::UInt32 => Int32ArrayHelperRenderer { config }.render(),
            Type::Int64 | Type::UInt64 => Int64ArrayHelperRenderer { config }.render(),
            Type::Float32 => Float32ArrayHelperRenderer { config }.render(),
            Type::Float64 => Float64ArrayHelperRenderer { config }.render(),
            Type::Boolean => BooleanArrayHelperRenderer { config }.render(),
            _ => SequenceTypeRenderer {
                config,
                ci,
                ffi_converter_name,
                inner_type,
            }
            .render(),
        },

        Type::Set { inner_type } => SetTypeRenderer {
            config,
            ci,
            ffi_converter_name,
            inner_type: compounds::Hashed(inner_type),
        }
        .render(),

        Type::Box { .. } => Ok(String::new()),
    };

    let rendered = rendered.with_context(|| format!("failed to render type {type_:?}"))?;
    Ok(rendered + &render_hashed_variant(type_, config, ci)?)
}

/// Templates whose only input is the package name.
macro_rules! simple_type_renderer {
    ($($name:ident => $path:literal),* $(,)?) => {$(
        #[derive(Template)]
        #[template(syntax = "java", escape = "none", path = $path)]
        struct $name<'a> {
            config: &'a Config,
        }
    )*};
}

simple_type_renderer! {
    BooleanHelperRenderer => "BooleanHelper.java",
    ByteArrayHelperRenderer => "ByteArrayHelper.java",
    DurationHelperRenderer => "DurationHelper.java",
    StringHelperRenderer => "StringHelper.java",
    TimestampHelperRenderer => "TimestampHelper.java",
    Int8HelperRenderer => "Int8Helper.java",
    Int16HelperRenderer => "Int16Helper.java",
    Int32HelperRenderer => "Int32Helper.java",
    Int64HelperRenderer => "Int64Helper.java",
    Float32HelperRenderer => "Float32Helper.java",
    Float64HelperRenderer => "Float64Helper.java",
    Int16ArrayHelperRenderer => "Int16ArrayHelper.java",
    Int32ArrayHelperRenderer => "Int32ArrayHelper.java",
    Int64ArrayHelperRenderer => "Int64ArrayHelper.java",
    Float32ArrayHelperRenderer => "Float32ArrayHelper.java",
    Float64ArrayHelperRenderer => "Float64ArrayHelper.java",
    BooleanArrayHelperRenderer => "BooleanArrayHelper.java",
}

#[derive(Template)]
#[template(
    syntax = "java",
    escape = "none",
    path = "CallbackInterfaceTemplate.java"
)]
struct CallbackInterfaceTypeRenderer<'a> {
    config: &'a Config,
    ci: &'a ComponentInterface,
    ffi_converter_name: String,
    // Used by the nested CallbackInterfaceImpl.java
    name: String,
    cbi: &'a CallbackInterface,
}

#[derive(Template)]
#[template(syntax = "java", escape = "none", path = "CustomTypeTemplate.java")]
struct CustomTypeRenderer<'a> {
    config: &'a Config,
    ci: &'a ComponentInterface,
    type_name: String,
    ffi_converter_name: String,
    name: String,
    builtin: &'a Type,
}

#[derive(Template)]
#[template(syntax = "java", escape = "none", path = "EnumTemplate.java")]
struct EnumTypeRenderer<'a> {
    config: &'a Config,
    ci: &'a ComponentInterface,
    type_name: String,
    contains_object_references: bool,
    e: &'a uniffi_bindgen::interface::Enum,
}

#[derive(Template)]
#[template(syntax = "java", escape = "none", path = "ErrorTemplate.java")]
struct ErrorTypeRenderer<'a> {
    config: &'a Config,
    ci: &'a ComponentInterface,
    type_: &'a Type,
    contains_object_references: bool,
    e: &'a uniffi_bindgen::interface::Enum,
}

#[derive(Template)]
#[template(syntax = "java", escape = "none", path = "MapTemplate.java")]
struct MapTypeRenderer<'a> {
    config: &'a Config,
    ci: &'a ComponentInterface,
    ffi_converter_name: String,
    key_type: compounds::Hashed<'a>,
    value_type: &'a Type,
}

#[derive(Template)]
#[template(syntax = "java", escape = "none", path = "OptionalTemplate.java")]
struct OptionalTypeRenderer<'a, T: AsCodeType> {
    config: &'a Config,
    ci: &'a ComponentInterface,
    ffi_converter_name: String,
    inner_type: T,
}

#[derive(Template)]
#[template(syntax = "java", escape = "none", path = "ObjectTemplate.java")]
struct ObjectTypeRenderer<'a> {
    config: &'a Config,
    ci: &'a ComponentInterface,
    type_name: String,
    ffi_converter_instance: String,
    // Used by the nested CallbackInterfaceImpl.java
    name: String,
    obj: &'a Object,
    is_error: bool,
}

#[derive(Template)]
#[template(syntax = "java", escape = "none", path = "RecordTemplate.java")]
struct RecordTypeRenderer<'a> {
    config: &'a Config,
    ci: &'a ComponentInterface,
    type_name: String,
    contains_object_references: bool,
    name: &'a str,
}

#[derive(Template)]
#[template(syntax = "java", escape = "none", path = "SequenceTemplate.java")]
struct SequenceTypeRenderer<'a, T: AsCodeType> {
    config: &'a Config,
    ci: &'a ComponentInterface,
    ffi_converter_name: String,
    inner_type: T,
}

#[derive(Template)]
#[template(syntax = "java", escape = "none", path = "SetTemplate.java")]
struct SetTypeRenderer<'a> {
    config: &'a Config,
    ci: &'a ComponentInterface,
    ffi_converter_name: String,
    inner_type: compounds::Hashed<'a>,
}

#[derive(Template)]
#[template(syntax = "java", escape = "none", path = "ExternalTypeTemplate.java")]
struct ExternalTypeRenderer<'a> {
    config: &'a Config,
    ci: &'a ComponentInterface,
    name: &'a str,
    module_path: &'a str,
}

impl ExternalTypeRenderer<'_> {
    // Used by ExternalTypeTemplate.java
    fn external_type_package_name(&self, module_path: &str, namespace: &str) -> String {
        self.config
            .external_type_package_name(module_path, namespace)
    }
}

fn fixup_keyword(name: String) -> String {
    if KEYWORDS.contains(&name) {
        format!("_{name}")
    } else {
        name
    }
}

#[derive(Clone)]
pub struct JavaCodeOracle;

impl JavaCodeOracle {
    fn find(&self, type_: &Type) -> Box<dyn CodeType> {
        type_.clone().as_type().as_codetype()
    }

    /// Get the idiomatic Java rendering of a class name (for enums, records, errors, etc).
    fn class_name(&self, ci: &ComponentInterface, nm: &str) -> String {
        let name = nm.to_string().to_upper_camel_case();
        // fixup errors.
        fixup_keyword(if ci.is_name_used_as_error(nm) {
            self.convert_error_suffix(&name)
        } else {
            name
        })
    }

    fn convert_error_suffix(&self, nm: &str) -> String {
        match nm.strip_suffix("Error") {
            Some(stripped) if !stripped.is_empty() => format!("{stripped}Exception"),
            _ => nm.to_string(),
        }
    }

    /// Get the idiomatic Java rendering of a function name.
    fn fn_name(&self, nm: &str) -> String {
        fixup_keyword(nm.to_string().to_lower_camel_case())
    }

    /// Get the idiomatic Java rendering of a variable name.
    pub fn var_name(&self, nm: &str) -> String {
        fixup_keyword(self.var_name_raw(nm))
    }

    /// `var_name` without the reserved word alteration.  Useful for struct field names.
    pub fn var_name_raw(&self, nm: &str) -> String {
        nm.to_string().to_lower_camel_case()
    }

    /// Get the idiomatic setter name for a variable.
    pub fn setter(&self, nm: &str) -> String {
        format!("set{}", fixup_keyword(nm.to_string().to_upper_camel_case()))
    }

    /// Get the idiomatic Java rendering of an individual enum variant.
    fn enum_variant_name(&self, nm: &str) -> String {
        nm.to_string().to_shouty_snake_case()
    }

    /// Get the idiomatic Java rendering of an FFI callback function name
    fn ffi_callback_name(&self, nm: &str) -> String {
        format!("Uniffi{}", nm.to_upper_camel_case())
    }

    /// Get the idiomatic Java rendering of an FFI struct name
    fn ffi_struct_name(&self, nm: &str) -> String {
        format!("Uniffi{}", nm.to_upper_camel_case())
    }

    /// FFI type label for use in method signatures and MethodHandle wrapper methods.
    /// In FFM, primitives stay as primitives, everything else is MemorySegment
    /// (except Handle/RustArcPtr which are long).
    fn ffi_type_label(
        &self,
        ffi_type: &FfiType,
        _config: &Config,
        _ci: &ComponentInterface,
    ) -> String {
        match ffi_type {
            // Note that unsigned values in Java don't have true native support. Signed primitives
            // can contain unsigned values and there are methods like `Integer.compareUnsigned`
            // that respect the unsigned value, but knowledge outside the type system is required.
            // TODO(java): improve callers knowledge of what contains an unsigned value
            FfiType::Int8 | FfiType::UInt8 => "byte".to_string(),
            FfiType::Int16 | FfiType::UInt16 => "short".to_string(),
            FfiType::Int32 | FfiType::UInt32 => "int".to_string(),
            FfiType::Int64 | FfiType::UInt64 => "long".to_string(),
            FfiType::Float32 => "float".to_string(),
            FfiType::Float64 => "double".to_string(),
            FfiType::Handle => "long".to_string(),
            // In FFM, all struct types, buffers, pointers, and callbacks are MemorySegment
            FfiType::RustBuffer(_)
            | FfiType::RustCallStatus
            | FfiType::ForeignBytes
            | FfiType::Callback(_)
            | FfiType::Struct(_)
            | FfiType::VoidPointer
            | FfiType::Reference(_)
            | FfiType::MutReference(_) => "java.lang.foreign.MemorySegment".to_string(),
        }
    }

    /// FFI type label using boxed types for use in generic contexts (e.g. FfiConverter<T, Long>).
    /// Java generics don't accept primitives.
    fn ffi_type_label_boxed(&self, ffi_type: &FfiType) -> String {
        match ffi_type {
            FfiType::Int8 | FfiType::UInt8 => "java.lang.Byte".to_string(),
            FfiType::Int16 | FfiType::UInt16 => "java.lang.Short".to_string(),
            FfiType::Int32 | FfiType::UInt32 => "java.lang.Integer".to_string(),
            FfiType::Int64 | FfiType::UInt64 => "java.lang.Long".to_string(),
            FfiType::Float32 => "java.lang.Float".to_string(),
            FfiType::Float64 => "java.lang.Double".to_string(),
            FfiType::Handle => "java.lang.Long".to_string(),
            _ => "java.lang.foreign.MemorySegment".to_string(),
        }
    }

    /// Maps FfiType to ValueLayout constant for FunctionDescriptor construction
    fn ffi_value_layout(&self, ffi_type: &FfiType) -> String {
        match ffi_type {
            FfiType::Int8 | FfiType::UInt8 => "java.lang.foreign.ValueLayout.JAVA_BYTE".to_string(),
            FfiType::Int16 | FfiType::UInt16 => {
                "java.lang.foreign.ValueLayout.JAVA_SHORT".to_string()
            }
            FfiType::Int32 | FfiType::UInt32 => {
                "java.lang.foreign.ValueLayout.JAVA_INT".to_string()
            }
            FfiType::Int64 | FfiType::UInt64 => {
                "java.lang.foreign.ValueLayout.JAVA_LONG".to_string()
            }
            FfiType::Float32 => "java.lang.foreign.ValueLayout.JAVA_FLOAT".to_string(),
            FfiType::Float64 => "java.lang.foreign.ValueLayout.JAVA_DOUBLE".to_string(),
            FfiType::Handle => "java.lang.foreign.ValueLayout.JAVA_LONG".to_string(),
            FfiType::RustBuffer(_) => "RustBuffer.LAYOUT".to_string(),
            // RustCallStatus is passed as a pointer in the C ABI
            FfiType::RustCallStatus => "java.lang.foreign.ValueLayout.ADDRESS".to_string(),
            FfiType::ForeignBytes => "ForeignBytes.LAYOUT".to_string(),
            FfiType::Struct(name) => format!("{}.LAYOUT", self.ffi_struct_name(name)),
            FfiType::Callback(_)
            | FfiType::VoidPointer
            | FfiType::Reference(_)
            | FfiType::MutReference(_) => "java.lang.foreign.ValueLayout.ADDRESS".to_string(),
        }
    }

    /// Returns the alignment requirement (in bytes) for an FFI type
    fn ffi_type_alignment(&self, ffi_type: &FfiType) -> usize {
        match ffi_type {
            FfiType::Int8 | FfiType::UInt8 => 1,
            FfiType::Int16 | FfiType::UInt16 => 2,
            FfiType::Int32 | FfiType::UInt32 | FfiType::Float32 => 4,
            FfiType::Int64 | FfiType::UInt64 | FfiType::Float64 | FfiType::Handle => 8,
            // Pointers are pointer-aligned (8 bytes on 64-bit)
            FfiType::Callback(_)
            | FfiType::VoidPointer
            | FfiType::Reference(_)
            | FfiType::MutReference(_) => 8,
            // Structs: alignment is the max alignment of their fields.
            // RustBuffer has JAVA_LONG (8) as first field → 8-byte aligned
            // RustCallStatus starts with JAVA_BYTE but contains RustBuffer → 8-byte aligned
            // ForeignBytes starts with JAVA_INT → but contains ADDRESS → 8-byte aligned
            FfiType::RustBuffer(_)
            | FfiType::RustCallStatus
            | FfiType::ForeignBytes
            | FfiType::Struct(_) => 8,
        }
    }

    /// Returns the size (in bytes) for an FFI type
    fn ffi_type_size(&self, ffi_type: &FfiType) -> usize {
        match ffi_type {
            FfiType::Int8 | FfiType::UInt8 => 1,
            FfiType::Int16 | FfiType::UInt16 => 2,
            FfiType::Int32 | FfiType::UInt32 | FfiType::Float32 => 4,
            FfiType::Int64 | FfiType::UInt64 | FfiType::Float64 | FfiType::Handle => 8,
            FfiType::Callback(_)
            | FfiType::VoidPointer
            | FfiType::Reference(_)
            | FfiType::MutReference(_) => 8,
            // Struct sizes: these are hardcoded based on their layouts
            FfiType::RustBuffer(_) => 24,  // long + long + pointer
            FfiType::RustCallStatus => 32, // byte + 7 pad + RustBuffer(24)
            FfiType::ForeignBytes => 16,   // int + 4 pad + pointer
            FfiType::Struct(_) => 0,       // unknown at codegen time, handled by LAYOUT
        }
    }

    /// Maps FfiType to layout for use as a struct field in StructLayout definitions.
    /// Unlike ffi_value_layout (for FunctionDescriptors), embedded structs use their
    /// full LAYOUT here rather than ADDRESS.
    fn ffi_struct_field_layout(&self, ffi_type: &FfiType) -> String {
        match ffi_type {
            FfiType::RustBuffer(_) => "RustBuffer.LAYOUT".to_string(),
            FfiType::RustCallStatus => "UniffiRustCallStatus.LAYOUT".to_string(),
            FfiType::ForeignBytes => "ForeignBytes.LAYOUT".to_string(),
            FfiType::Struct(name) => format!("{}.LAYOUT", self.ffi_struct_name(name)),
            _ => self.ffi_value_layout(ffi_type),
        }
    }

    /// Maps FfiType to UNALIGNED ValueLayout for struct field access
    fn ffi_value_layout_unaligned(&self, ffi_type: &FfiType) -> String {
        match ffi_type {
            FfiType::Int8 | FfiType::UInt8 => "java.lang.foreign.ValueLayout.JAVA_BYTE".to_string(), // byte has no alignment
            FfiType::Int16 | FfiType::UInt16 => {
                "java.lang.foreign.ValueLayout.JAVA_SHORT_UNALIGNED".to_string()
            }
            FfiType::Int32 | FfiType::UInt32 => {
                "java.lang.foreign.ValueLayout.JAVA_INT_UNALIGNED".to_string()
            }
            FfiType::Int64 | FfiType::UInt64 => {
                "java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED".to_string()
            }
            FfiType::Float32 => "java.lang.foreign.ValueLayout.JAVA_FLOAT_UNALIGNED".to_string(),
            FfiType::Float64 => "java.lang.foreign.ValueLayout.JAVA_DOUBLE_UNALIGNED".to_string(),
            FfiType::Handle => "java.lang.foreign.ValueLayout.JAVA_LONG_UNALIGNED".to_string(),
            FfiType::Callback(_)
            | FfiType::VoidPointer
            | FfiType::Reference(_)
            | FfiType::MutReference(_) => {
                "java.lang.foreign.ValueLayout.ADDRESS_UNALIGNED".to_string()
            }
            // Structs use slice-based access, not ValueLayout access
            _ => self.ffi_value_layout(ffi_type),
        }
    }

    /// Cast prefix needed for invokeExact() return values
    fn ffi_invoke_exact_cast(&self, ffi_type: &FfiType) -> String {
        match ffi_type {
            FfiType::Int8 | FfiType::UInt8 => "(byte) ".to_string(),
            FfiType::Int16 | FfiType::UInt16 => "(short) ".to_string(),
            FfiType::Int32 | FfiType::UInt32 => "(int) ".to_string(),
            FfiType::Int64 | FfiType::UInt64 => "(long) ".to_string(),
            FfiType::Float32 => "(float) ".to_string(),
            FfiType::Float64 => "(double) ".to_string(),
            FfiType::Handle => "(long) ".to_string(),
            FfiType::RustBuffer(_)
            | FfiType::RustCallStatus
            | FfiType::ForeignBytes
            | FfiType::Callback(_)
            | FfiType::Struct(_)
            | FfiType::VoidPointer
            | FfiType::Reference(_)
            | FfiType::MutReference(_) => "(java.lang.foreign.MemorySegment) ".to_string(),
        }
    }

    /// Returns true if the FFI type is a struct that requires a SegmentAllocator
    /// as the first argument to invokeExact() for downcall handles
    fn ffi_type_is_struct(&self, ffi_type: &FfiType) -> bool {
        // RustCallStatus is passed as a pointer, not by value, so it doesn't need SegmentAllocator
        matches!(
            ffi_type,
            FfiType::RustBuffer(_) | FfiType::ForeignBytes | FfiType::Struct(_)
        )
    }

    /// Returns true if this FFI type is an embedded struct inside another struct
    /// (uses slice-based access rather than primitive get/set)
    fn ffi_type_is_embedded_struct(&self, ffi_type: &FfiType) -> bool {
        matches!(
            ffi_type,
            FfiType::RustBuffer(_)
                | FfiType::RustCallStatus
                | FfiType::ForeignBytes
                | FfiType::Struct(_)
        )
    }

    /// Get the struct class name for an FfiType::Struct
    fn ffi_struct_type_name(&self, ffi_type: &FfiType) -> String {
        match ffi_type {
            FfiType::Struct(name) => self.ffi_struct_name(name),
            FfiType::RustBuffer(_) => "RustBuffer".to_string(),
            FfiType::RustCallStatus => "UniffiRustCallStatus".to_string(),
            FfiType::ForeignBytes => "ForeignBytes".to_string(),
            _ => panic!("ffi_struct_type_name called on non-struct type: {ffi_type:?}"),
        }
    }

    /// Get the name of the interface and class name for an object.
    ///
    /// If we support callback interfaces, the interface name is the object name, and the class name is derived from that.
    /// Otherwise, the class name is the object name and the interface name is derived from that.
    ///
    /// This split determines what types `FfiConverter.lower()` inputs.  If we support callback
    /// interfaces, `lower` must lower anything that implements the interface.  If not, then lower
    /// only lowers the concrete class.
    fn object_names(&self, ci: &ComponentInterface, obj: &Object) -> (String, String) {
        let class_name = self.class_name(ci, obj.name());
        if obj.has_callback_interface() {
            let impl_name = format!("{class_name}Impl");
            (class_name, impl_name)
        } else {
            (format!("{class_name}Interface"), class_name)
        }
    }
}

trait AsCodeType {
    fn as_codetype(&self) -> Box<dyn CodeType>;
}

// Workaround for the possibility of upstream additions of AsType breaking compilation
// Downside to this is new types need to be manually added
impl AsCodeType for Type {
    fn as_codetype(&self) -> Box<dyn CodeType> {
        // Map `Type` instances to a `Box<dyn CodeType>` for that type.
        //
        // There is a companion match in `templates/Types.java` which performs a similar function for the
        // template code.
        //
        //   - When adding additional types here, make sure to also add a match arm to the `Types.java` template.
        //   - To keep things manageable, let's try to limit ourselves to these 2 mega-matches
        match self.as_type() {
            Type::UInt8 | Type::Int8 => Box::new(primitives::Int8CodeType),
            Type::UInt16 | Type::Int16 => Box::new(primitives::Int16CodeType),
            Type::UInt32 | Type::Int32 => Box::new(primitives::Int32CodeType),
            Type::UInt64 | Type::Int64 => Box::new(primitives::Int64CodeType),
            Type::Float32 => Box::new(primitives::Float32CodeType),
            Type::Float64 => Box::new(primitives::Float64CodeType),
            Type::Boolean => Box::new(primitives::BooleanCodeType),
            Type::String => Box::new(primitives::StringCodeType),
            Type::Bytes => Box::new(primitives::BytesCodeType),

            Type::Timestamp => Box::new(miscellany::TimestampCodeType),
            Type::Duration => Box::new(miscellany::DurationCodeType),

            Type::Enum { name, .. } => Box::new(enum_::EnumCodeType::new(name.clone())),
            Type::Object { name, imp, .. } => {
                Box::new(object::ObjectCodeType::new(name.clone(), imp))
            }
            Type::Record { name, .. } => Box::new(record::RecordCodeType::new(name.clone())),
            Type::CallbackInterface { name, .. } => Box::new(
                callback_interface::CallbackInterfaceCodeType::new(name.clone()),
            ),
            Type::Optional { inner_type } => {
                Box::new(compounds::OptionalCodeType::new((*inner_type).clone()))
            }
            Type::Sequence { inner_type } => {
                match compounds::primitive_array_code_type(&inner_type) {
                    Some(array_type) => array_type,
                    None => Box::new(compounds::SequenceCodeType::new((*inner_type).clone())),
                }
            }
            Type::Set { inner_type } => {
                Box::new(compounds::SetCodeType::new((*inner_type).clone()))
            }
            Type::Map {
                key_type,
                value_type,
            } => Box::new(compounds::MapCodeType::new(
                (*key_type).clone(),
                (*value_type).clone(),
            )),
            Type::Custom { name, .. } => Box::new(custom::CustomCodeType::new(name.clone())),
            // `Box<T>` only exists for scaffolding; it's transparent to the bindings.
            Type::Box { inner_type } => inner_type.as_codetype(),
        }
    }
}
impl AsCodeType for &'_ Type {
    fn as_codetype(&self) -> Box<dyn CodeType> {
        (*self).as_codetype()
    }
}
impl AsCodeType for &&'_ Type {
    fn as_codetype(&self) -> Box<dyn CodeType> {
        (**self).as_codetype()
    }
}
impl AsCodeType for &'_ Field {
    fn as_codetype(&self) -> Box<dyn CodeType> {
        self.as_type().as_codetype()
    }
}
impl AsCodeType for &'_ uniffi_bindgen::interface::Enum {
    fn as_codetype(&self) -> Box<dyn CodeType> {
        self.as_type().as_codetype()
    }
}
impl AsCodeType for &'_ uniffi_bindgen::interface::Object {
    fn as_codetype(&self) -> Box<dyn CodeType> {
        self.as_type().as_codetype()
    }
}
impl AsCodeType for &'_ Box<uniffi_meta::Type> {
    fn as_codetype(&self) -> Box<dyn CodeType> {
        self.as_type().as_codetype()
    }
}
impl AsCodeType for &'_ Argument {
    fn as_codetype(&self) -> Box<dyn CodeType> {
        self.as_type().as_codetype()
    }
}
impl AsCodeType for &'_ uniffi_bindgen::interface::Record {
    fn as_codetype(&self) -> Box<dyn CodeType> {
        self.as_type().as_codetype()
    }
}
impl AsCodeType for &'_ uniffi_bindgen::interface::CallbackInterface {
    fn as_codetype(&self) -> Box<dyn CodeType> {
        self.as_type().as_codetype()
    }
}

mod filters {
    #![allow(unused_variables)]
    use super::*;
    use uniffi_meta::AsType;

    // Askama passes a Values parameter to every filter, hence the unused `_v` throughout.

    #[askama::filter_fn]
    pub(super) fn ffi_type(
        type_: &impl AsType,
        _v: &dyn askama::Values,
    ) -> Result<FfiType, askama::Error> {
        Ok(type_.as_type().into())
    }

    #[askama::filter_fn]
    pub(super) fn type_name(
        as_ct: &impl AsCodeType,
        _v: &dyn askama::Values,
        ci: &ComponentInterface,
        config: &Config,
    ) -> Result<String, askama::Error> {
        Ok(as_ct.as_codetype().type_label(ci, config))
    }

    /// Generate a fully qualified type name including the package.
    /// This is needed for enum variant fields to avoid naming collisions
    /// when a variant field type has the same name as the enum itself.
    #[askama::filter_fn]
    pub(super) fn qualified_type_name<T>(
        as_type: &T,
        _v: &dyn askama::Values,
        ci: &ComponentInterface,
        config: &Config,
    ) -> Result<String, askama::Error>
    where
        T: AsCodeType + AsType,
    {
        fully_qualified_type_label(&as_type.as_type(), ci, config)
            .map_err(|e| askama::Error::Custom(e.into()))
    }

    fn fully_qualified_type_label(
        ty: &Type,
        ci: &ComponentInterface,
        config: &Config,
    ) -> anyhow::Result<String> {
        match ty {
            Type::Optional { inner_type } => {
                let inner = fully_qualified_type_label(inner_type, ci, config)?;
                if config.nullness_annotations() {
                    Ok(nullable_type_label(&inner))
                } else {
                    Ok(inner)
                }
            }
            Type::Sequence { inner_type } => {
                // Primitive array labels are already unqualified.
                match compounds::primitive_array_code_type(inner_type) {
                    Some(array_type) => Ok(array_type.type_label(ci, config)),
                    None => Ok(format!(
                        "java.util.List<{}>",
                        fully_qualified_type_label(inner_type, ci, config)?
                    )),
                }
            }
            Type::Set { inner_type } => Ok(format!(
                "java.util.Set<{}>",
                hashed_fully_qualified_type_label(inner_type, ci, config)?
            )),
            Type::Map {
                key_type,
                value_type,
            } => Ok(format!(
                "java.util.Map<{}, {}>",
                hashed_fully_qualified_type_label(key_type, ci, config)?,
                fully_qualified_type_label(value_type, ci, config)?
            )),
            // `Box<T>` exists only in scaffolding; the bindings name `T`.
            Type::Box { inner_type } => fully_qualified_type_label(inner_type, ci, config),
            Type::Enum { .. }
            | Type::Record { .. }
            | Type::Object { .. }
            | Type::CallbackInterface { .. }
            | Type::Custom { .. } => {
                let class_name = ty
                    .name()
                    .map(|nm| JavaCodeOracle.class_name(ci, nm))
                    .ok_or_else(|| anyhow::anyhow!("type {:?} has no name", ty))?;
                let package_name = package_for_type(ty, ci, config)?;
                Ok(format!("{}.{}", package_name, class_name))
            }
            _ => Ok(JavaCodeOracle.find(ty).type_label(ci, config)),
        }
    }

    /// As [`fully_qualified_type_label`], for a `Set` element or `Map` key. See
    /// [`compounds::Hashed`].
    fn hashed_fully_qualified_type_label(
        ty: &Type,
        ci: &ComponentInterface,
        config: &Config,
    ) -> anyhow::Result<String> {
        if !compounds::needs_hashed_rendering(ty) {
            return fully_qualified_type_label(ty, ci, config);
        }
        match ty {
            Type::Sequence { inner_type } => Ok(format!(
                "java.util.List<{}>",
                hashed_fully_qualified_type_label(inner_type, ci, config)?
            )),
            Type::Optional { inner_type } => {
                let inner = hashed_fully_qualified_type_label(inner_type, ci, config)?;
                Ok(if config.nullness_annotations() {
                    nullable_type_label(&inner)
                } else {
                    inner
                })
            }
            Type::Bytes => Ok("java.util.List<java.lang.Byte>".to_string()),
            _ => unreachable!("needs_hashed_rendering matches only Sequence, Optional, and Bytes"),
        }
    }

    fn package_for_type(
        ty: &Type,
        ci: &ComponentInterface,
        config: &Config,
    ) -> anyhow::Result<String> {
        if ci.is_external(ty) {
            let module_path = ty
                .module_path()
                .ok_or_else(|| anyhow::anyhow!("external type {:?} missing module path", ty))?;
            let namespace = ci.namespace_for_module_path(module_path)?;
            Ok(config.external_type_package_name(module_path, namespace))
        } else {
            Ok(config.package_name())
        }
    }

    /// Returns the [`ComponentInterface`] that owns `module_path`.
    ///
    /// If `module_path` belongs to the current crate, returns `ci` directly.
    /// Otherwise looks up an external component interface by the full module
    /// path first, then by the crate name (first `::` segment).
    fn component_interface_for_module_path<'a>(
        ci: &'a ComponentInterface,
        module_path: &str,
    ) -> Option<&'a ComponentInterface> {
        let crate_name = module_path.split("::").next().unwrap_or(module_path);
        if crate_name == ci.crate_name() {
            Some(ci)
        } else {
            ci.find_component_interface(module_path)
                .or_else(|| ci.find_component_interface(crate_name))
        }
    }

    #[askama::filter_fn]
    pub(super) fn canonical_name(
        as_ct: &impl AsCodeType,
        _v: &dyn askama::Values,
    ) -> Result<String, askama::Error> {
        Ok(as_ct.as_codetype().canonical_name())
    }

    /// Check if a type is external (from another crate)
    #[askama::filter_fn]
    pub(super) fn is_external(
        as_type: &impl AsType,
        _v: &dyn askama::Values,
        ci: &ComponentInterface,
    ) -> Result<bool, askama::Error> {
        Ok(ci.is_external(&as_type.as_type()))
    }

    #[askama::filter_fn]
    pub(super) fn ffi_converter_instance(
        as_ct: &impl AsCodeType,
        _v: &dyn askama::Values,
        config: &Config,
        ci: &ComponentInterface,
    ) -> Result<String, askama::Error> {
        Ok(as_ct.as_codetype().ffi_converter_instance(config, ci))
    }

    #[askama::filter_fn]
    pub(super) fn ffi_converter_name(
        as_ct: &impl AsCodeType,
        _v: &dyn askama::Values,
    ) -> Result<String, askama::Error> {
        Ok(as_ct.as_codetype().ffi_converter_name())
    }

    #[askama::filter_fn]
    pub(super) fn lower_fn(
        as_ct: &impl AsCodeType,
        _v: &dyn askama::Values,
        config: &Config,
        ci: &ComponentInterface,
    ) -> Result<String, askama::Error> {
        Ok(format!(
            "{}.lower",
            as_ct.as_codetype().ffi_converter_instance(config, ci)
        ))
    }

    #[askama::filter_fn]
    pub(super) fn allocation_size_fn(
        as_ct: &impl AsCodeType,
        _v: &dyn askama::Values,
        config: &Config,
        ci: &ComponentInterface,
    ) -> Result<String, askama::Error> {
        Ok(format!(
            "{}.allocationSize",
            as_ct.as_codetype().ffi_converter_instance(config, ci)
        ))
    }

    #[askama::filter_fn]
    pub(super) fn write_fn(
        as_ct: &impl AsCodeType,
        _v: &dyn askama::Values,
        config: &Config,
        ci: &ComponentInterface,
    ) -> Result<String, askama::Error> {
        Ok(format!(
            "{}.write",
            as_ct.as_codetype().ffi_converter_instance(config, ci)
        ))
    }

    #[askama::filter_fn]
    pub(super) fn lift_fn(
        as_ct: &impl AsCodeType,
        _v: &dyn askama::Values,
        config: &Config,
        ci: &ComponentInterface,
    ) -> Result<String, askama::Error> {
        Ok(format!(
            "{}.lift",
            as_ct.as_codetype().ffi_converter_instance(config, ci)
        ))
    }

    #[askama::filter_fn]
    pub(super) fn read_fn(
        as_ct: &impl AsCodeType,
        _v: &dyn askama::Values,
        config: &Config,
        ci: &ComponentInterface,
    ) -> Result<String, askama::Error> {
        Ok(format!(
            "{}.read",
            as_ct.as_codetype().ffi_converter_instance(config, ci)
        ))
    }

    // Get the idiomatic Java rendering of an integer.
    fn int_literal(t: &Option<Type>, base10: String) -> Result<String, askama::Error> {
        if let Some(t) = t {
            match t {
                // Byte and Short need explicit casts in Java
                Type::Int8 | Type::UInt8 => Ok(format!("(byte){}", base10)),
                Type::Int16 | Type::UInt16 => Ok(format!("(short){}", base10)),
                Type::Int32 => Ok(base10),
                // Java literals are signed and unsuffixed ones parse as `int`, so longs need the
                // `L` suffix, and the upper half of an unsigned repr only fits as hex, which
                // carries the bit pattern into the signed type.
                Type::UInt32 => match base10.parse::<u32>() {
                    Ok(v) if v > i32::MAX as u32 => Ok(format!("0x{:X}", v)),
                    Ok(_) => Ok(base10),
                    Err(_) => Err(to_askama_error(&format!("invalid u32 literal: {base10}"))),
                },
                Type::Int64 => Ok(format!("{}L", base10)),
                Type::UInt64 => match base10.parse::<u64>() {
                    Ok(v) if v > i64::MAX as u64 => Ok(format!("0x{:X}L", v)),
                    Ok(_) => Ok(format!("{}L", base10)),
                    Err(_) => Err(to_askama_error(&format!("invalid u64 literal: {base10}"))),
                },
                _ => Err(to_askama_error("Only ints are supported.")),
            }
        } else {
            Err(to_askama_error("Enum hasn't defined a repr"))
        }
    }

    // Get the idiomatic Java rendering of an individual enum variant's discriminant
    #[askama::filter_fn]
    pub fn variant_discr_literal(
        e: &Enum,
        _v: &dyn askama::Values,
        index: &usize,
    ) -> Result<String, askama::Error> {
        let literal = e.variant_discr(*index).expect("invalid index");
        match literal {
            // Java doesn't convert between signed and unsigned by default
            // so we'll need to make sure we define the type as appropriately
            Literal::UInt(v, _, _) => int_literal(e.variant_discr_type(), v.to_string()),
            Literal::Int(v, _, _) => int_literal(e.variant_discr_type(), v.to_string()),
            _ => Err(to_askama_error("Only ints are supported.")),
        }
    }

    /// FFI type name (primitive for scalars, MemorySegment for everything else)
    #[askama::filter_fn]
    pub fn ffi_type_name(
        type_: &FfiType,
        _v: &dyn askama::Values,
        config: &Config,
        ci: &ComponentInterface,
    ) -> Result<String, askama::Error> {
        Ok(JavaCodeOracle.ffi_type_label(type_, config, ci))
    }

    /// Returns the primitive call suffix (e.g. "Long", "Int") for primitive-specialized
    /// uniffiRustCall variants. Returns empty string for types where the high-level Java
    /// primitive doesn't match the FFI primitive (e.g. Boolean→byte) or non-primitive types.
    #[askama::filter_fn]
    pub fn primitive_call_suffix(
        as_ct: &impl AsCodeType,
        _v: &dyn askama::Values,
    ) -> Result<String, askama::Error> {
        // Only bypass FfiConverter when the Java primitive matches the FFI primitive.
        // Boolean is excluded because it's `boolean` in Java but `byte` at the FFI level.
        Ok(
            match as_ct.as_codetype().type_label_primitive().as_deref() {
                Some("byte") => "Byte",
                Some("short") => "Short",
                Some("int") => "Int",
                Some("long") => "Long",
                Some("float") => "Float",
                Some("double") => "Double",
                _ => "",
            }
            .to_string(),
        )
    }

    /// Returns true if the argument's FFI type is a primitive where the Java type matches
    /// the FFI type directly (no conversion needed). Used to skip lower_fn for primitive args.
    /// Excludes boolean (Java `boolean` vs FFI `byte`).
    #[askama::filter_fn]
    pub fn has_primitive_ffi_type(
        as_ct: &impl AsCodeType,
        _v: &dyn askama::Values,
    ) -> Result<bool, askama::Error> {
        Ok(matches!(
            as_ct.as_codetype().type_label_primitive().as_deref(),
            Some("byte" | "short" | "int" | "long" | "float" | "double")
        ))
    }

    /// Maps FfiType to ValueLayout constant for FunctionDescriptor
    #[askama::filter_fn]
    pub fn ffi_value_layout(
        type_: &FfiType,
        _v: &dyn askama::Values,
    ) -> Result<String, askama::Error> {
        Ok(JavaCodeOracle.ffi_value_layout(type_))
    }

    /// Generate the full structLayout body for an FfiStruct, with computed padding
    #[askama::filter_fn]
    pub fn ffi_struct_layout_body(
        ffi_struct: &uniffi_bindgen::interface::FfiStruct,
        _v: &dyn askama::Values,
    ) -> Result<String, askama::Error> {
        let mut parts = Vec::new();
        let mut offset: usize = 0;
        for field in ffi_struct.fields() {
            let field_type = field.type_();
            let alignment = JavaCodeOracle.ffi_type_alignment(&field_type);
            // Insert padding if needed for alignment
            let padding = if !offset.is_multiple_of(alignment) {
                alignment - (offset % alignment)
            } else {
                0
            };
            if padding > 0 {
                parts.push(format!(
                    "java.lang.foreign.MemoryLayout.paddingLayout({})",
                    padding
                ));
                offset += padding;
            }
            let layout = JavaCodeOracle.ffi_struct_field_layout(&field_type);
            let field_name = JavaCodeOracle.var_name_raw(field.name());
            parts.push(format!("{}.withName(\"{}\")", layout, field_name));
            // Advance offset
            let size = JavaCodeOracle.ffi_type_size(&field_type);
            if size > 0 {
                offset += size;
            } else {
                // Unknown size (e.g., user-defined FfiStruct) - can't compute further padding
                // but alignment was already handled
                offset = 0; // reset; further padding may be wrong but this is rare
            }
        }
        Ok(parts.join(",\n        "))
    }

    /// Maps FfiType to UNALIGNED ValueLayout for struct field access
    #[askama::filter_fn]
    pub fn ffi_value_layout_unaligned(
        type_: &FfiType,
        _v: &dyn askama::Values,
    ) -> Result<String, askama::Error> {
        Ok(JavaCodeOracle.ffi_value_layout_unaligned(type_))
    }

    /// Cast prefix for invokeExact() return values
    #[askama::filter_fn]
    pub fn ffi_invoke_exact_cast(
        type_: &FfiType,
        _v: &dyn askama::Values,
    ) -> Result<String, askama::Error> {
        Ok(JavaCodeOracle.ffi_invoke_exact_cast(type_))
    }

    /// Returns true if the FFI return type is a struct needing SegmentAllocator
    #[askama::filter_fn]
    pub fn ffi_type_is_struct(
        type_: &FfiType,
        _v: &dyn askama::Values,
    ) -> Result<bool, askama::Error> {
        Ok(JavaCodeOracle.ffi_type_is_struct(type_))
    }

    /// Returns true if this is an embedded struct (slice-based access in struct fields)
    #[askama::filter_fn]
    pub fn ffi_type_is_embedded_struct(
        type_: &FfiType,
        _v: &dyn askama::Values,
    ) -> Result<bool, askama::Error> {
        Ok(JavaCodeOracle.ffi_type_is_embedded_struct(type_))
    }

    /// Get the struct class name for an FFI struct type
    #[askama::filter_fn]
    pub fn ffi_struct_type_name(
        type_: &FfiType,
        _v: &dyn askama::Values,
    ) -> Result<String, askama::Error> {
        Ok(JavaCodeOracle.ffi_struct_type_name(type_))
    }

    /// FFI type name using boxed types for generic contexts (accepts high-level Type)
    #[askama::filter_fn]
    pub fn ffi_type_name_boxed(
        type_: &impl AsType,
        _v: &dyn askama::Values,
    ) -> Result<String, askama::Error> {
        let ffi_type: FfiType = type_.as_type().into();
        Ok(JavaCodeOracle.ffi_type_label_boxed(&ffi_type))
    }

    /// Get the interface name for a trait implementation (for external trait interfaces).
    #[askama::filter_fn]
    pub fn trait_interface_name(
        trait_ty: &Type,
        _v: &dyn askama::Values,
        ci: &ComponentInterface,
    ) -> Result<String, askama::Error> {
        trait_interface_name_for(trait_ty, ci)
    }

    pub(super) fn trait_interface_name_for(
        trait_ty: &Type,
        ci: &ComponentInterface,
    ) -> Result<String, askama::Error> {
        let Some(module_path) = trait_ty.module_path() else {
            return Err(to_askama_error(&format!(
                "Invalid trait_type: {trait_ty:?}"
            )));
        };
        let Some(ci_look) = component_interface_for_module_path(ci, module_path) else {
            return Err(to_askama_error(&format!(
                "no interface with module_path: {}",
                module_path
            )));
        };

        let (obj_name, has_callback_interface) = match trait_ty {
            Type::Object { name, .. } => {
                let Some(obj) = ci_look.get_object_definition(name) else {
                    return Err(to_askama_error(&format!(
                        "trait interface not found: {}",
                        name
                    )));
                };
                (name, obj.has_callback_interface())
            }
            Type::CallbackInterface { name, .. } => (name, true),
            _ => {
                return Err(to_askama_error(&format!(
                    "Invalid trait_type: {trait_ty:?}"
                )));
            }
        };

        let class_name = JavaCodeOracle.class_name(ci_look, obj_name);
        if has_callback_interface {
            Ok(class_name)
        } else {
            Ok(format!("{}Interface", class_name))
        }
    }

    /// Get the idiomatic Java rendering of a class name from a string.
    #[askama::filter_fn]
    pub fn class_name<S: AsRef<str>>(
        nm: S,
        _v: &dyn askama::Values,
        ci: &ComponentInterface,
    ) -> Result<String, askama::Error> {
        Ok(JavaCodeOracle.class_name(ci, nm.as_ref()))
    }

    /// Get the idiomatic Java rendering of a class name from a Type.
    #[askama::filter_fn]
    pub fn class_name_from_type(
        as_type: &impl AsType,
        _v: &dyn askama::Values,
        ci: &ComponentInterface,
    ) -> Result<String, askama::Error> {
        let type_ = as_type.as_type();
        let name = match &type_ {
            Type::Enum { name, .. } => name,
            Type::Object { name, .. } => name,
            Type::Record { name, .. } => name,
            Type::Custom { name, .. } => name,
            Type::CallbackInterface { name, .. } => name,
            _ => {
                return Err(to_askama_error(&format!(
                    "class_name_from_type: unsupported type {:?}",
                    type_
                )));
            }
        };
        Ok(JavaCodeOracle.class_name(ci, name))
    }

    /// Get the idiomatic Java rendering of a function name.
    #[askama::filter_fn]
    pub fn fn_name<S: AsRef<str>>(nm: S, _v: &dyn askama::Values) -> Result<String, askama::Error> {
        Ok(JavaCodeOracle.fn_name(nm.as_ref()))
    }

    /// Get the idiomatic Java rendering of a variable name.
    #[askama::filter_fn]
    pub fn var_name<S: AsRef<str>>(
        nm: S,
        _v: &dyn askama::Values,
    ) -> Result<String, askama::Error> {
        Ok(JavaCodeOracle.var_name(nm.as_ref()))
    }

    /// Get the idiomatic Java rendering of a variable name, without altering reserved words.
    #[askama::filter_fn]
    pub fn var_name_raw<S: AsRef<str>>(
        nm: S,
        _v: &dyn askama::Values,
    ) -> Result<String, askama::Error> {
        Ok(JavaCodeOracle.var_name_raw(nm.as_ref()))
    }

    /// Get the idiomatic Java setter method name.
    #[askama::filter_fn]
    pub fn setter<S: AsRef<str>>(nm: S, _v: &dyn askama::Values) -> Result<String, askama::Error> {
        Ok(JavaCodeOracle.setter(nm.as_ref()))
    }

    /// Get a String representing the name used for an individual enum variant.
    #[askama::filter_fn]
    pub fn variant_name(
        variant: &Variant,
        _v: &dyn askama::Values,
    ) -> Result<String, askama::Error> {
        Ok(JavaCodeOracle.enum_variant_name(variant.name()))
    }

    #[askama::filter_fn]
    pub fn error_variant_name(
        variant: &Variant,
        _v: &dyn askama::Values,
    ) -> Result<String, askama::Error> {
        let name = variant.name().to_string().to_upper_camel_case();
        Ok(JavaCodeOracle.convert_error_suffix(&name))
    }

    /// Get the idiomatic Java rendering of an FFI callback function name
    #[askama::filter_fn]
    pub fn ffi_callback_name<S: AsRef<str>>(
        nm: S,
        _v: &dyn askama::Values,
    ) -> Result<String, askama::Error> {
        Ok(JavaCodeOracle.ffi_callback_name(nm.as_ref()))
    }

    /// Get the idiomatic Java rendering of an FFI struct name
    #[askama::filter_fn]
    pub fn ffi_struct_name<S: AsRef<str>>(
        nm: S,
        _v: &dyn askama::Values,
    ) -> Result<String, askama::Error> {
        Ok(JavaCodeOracle.ffi_struct_name(nm.as_ref()))
    }

    #[askama::filter_fn]
    pub fn object_names(
        obj: &Object,
        _v: &dyn askama::Values,
        ci: &ComponentInterface,
    ) -> Result<(String, String), askama::Error> {
        Ok(JavaCodeOracle.object_names(ci, obj))
    }

    // `#[askama::filter_fn]` turns each filter into a struct, so filters can't call each other.
    fn inner_return_type(
        callable: &impl Callable,
        ci: &ComponentInterface,
        config: &Config,
    ) -> String {
        callable.return_type().map_or_else(
            || "java.lang.Void".to_string(),
            |t| t.as_codetype().type_label(ci, config),
        )
    }

    #[askama::filter_fn]
    pub fn async_inner_return_type(
        callable: impl Callable,
        _v: &dyn askama::Values,
        ci: &ComponentInterface,
        config: &Config,
    ) -> Result<String, askama::Error> {
        Ok(inner_return_type(&callable, ci, config))
    }

    #[askama::filter_fn]
    pub fn async_return_type(
        callable: impl Callable,
        _v: &dyn askama::Values,
        ci: &ComponentInterface,
        config: &Config,
    ) -> Result<String, askama::Error> {
        let inner_type = inner_return_type(&callable, ci, config);
        if callable.is_async() {
            Ok(format!(
                "java.util.concurrent.CompletableFuture<{inner_type}>"
            ))
        } else {
            Ok(inner_type)
        }
    }

    #[askama::filter_fn]
    pub fn async_poll(
        callable: impl Callable,
        _v: &dyn askama::Values,
        ci: &ComponentInterface,
    ) -> Result<String, askama::Error> {
        let ffi_func = callable.ffi_rust_future_poll(ci);
        Ok(format!(
            "(future, callback, continuationHandle) -> UniffiLib.{ffi_func}(future, callback, continuationHandle)"
        ))
    }

    #[askama::filter_fn]
    pub fn async_complete(
        callable: impl Callable,
        _v: &dyn askama::Values,
        ci: &ComponentInterface,
        config: &Config,
    ) -> Result<String, askama::Error> {
        let ffi_func = callable.ffi_rust_future_complete(ci);
        // The complete function returns a RustBuffer for types that use RustBuffer FFI,
        // which is a struct and needs a SegmentAllocator.
        let needs_allocator = callable.return_type().is_some_and(|t| {
            let ffi_type: FfiType = t.into();
            JavaCodeOracle.ffi_type_is_struct(&ffi_type)
        });
        let allocator_arg = if needs_allocator { "_allocator, " } else { "" };
        let call = format!("UniffiLib.{ffi_func}({allocator_arg}future, continuation)");
        Ok(format!("(_allocator, future, continuation) -> {call}"))
    }

    #[askama::filter_fn]
    pub fn async_free(
        callable: impl Callable,
        _v: &dyn askama::Values,
        ci: &ComponentInterface,
    ) -> Result<String, askama::Error> {
        let ffi_func = callable.ffi_rust_future_free(ci);
        Ok(format!("(future) -> UniffiLib.{ffi_func}(future)"))
    }

    /// Remove the "`" chars we put around function/variable names
    ///
    /// These are used to avoid name clashes with java identifiers, but sometimes you want to
    /// render the name unquoted.  One example is the message property for errors where we want to
    /// display the name for the user.
    #[askama::filter_fn]
    pub fn unquote<S: AsRef<str>>(nm: S, _v: &dyn askama::Values) -> Result<String, askama::Error> {
        Ok(nm.as_ref().trim_matches('`').to_string())
    }

    /// Get the idiomatic Java rendering of docstring
    #[askama::filter_fn]
    pub fn docstring<S: AsRef<str>>(
        docstring: S,
        _v: &dyn askama::Values,
        spaces: &i32,
    ) -> Result<String, askama::Error> {
        let middle = textwrap::indent(&textwrap::dedent(docstring.as_ref()), " * ");
        let wrapped = format!("/**\n{middle}\n */");

        let spaces = usize::try_from(*spaces).unwrap_or_default();
        Ok(textwrap::indent(&wrapped, &" ".repeat(spaces)))
    }

    /// Returns the type name suitable for use in field declarations, method parameters, and return types.
    /// For non-optional primitives, returns the primitive type (int, long, boolean, etc.).
    /// For optional types and all other types, returns the boxed/object type.
    #[askama::filter_fn]
    pub fn type_name_for_field(
        as_ct: &impl AsCodeType,
        _v: &dyn askama::Values,
        ci: &ComponentInterface,
        config: &Config,
    ) -> Result<String, askama::Error> {
        Ok(field_type_label(as_ct, ci, config))
    }

    fn field_type_label(
        as_ct: &impl AsCodeType,
        ci: &ComponentInterface,
        config: &Config,
    ) -> String {
        let codetype = as_ct.as_codetype();
        codetype
            .type_label_primitive()
            .unwrap_or_else(|| codetype.type_label(ci, config))
    }

    /// Java type for an argument being passed *to* Rust. A zero-copy `&[u8]` takes a direct
    /// `java.nio.ByteBuffer`, the only Java type with a stable native address.
    #[askama::filter_fn]
    pub fn lower_type_name_for_arg(
        arg: &Argument,
        _v: &dyn askama::Values,
        ci: &ComponentInterface,
        config: &Config,
    ) -> Result<String, askama::Error> {
        if arg.is_borrowed_bytes() {
            Ok("java.nio.ByteBuffer".to_string())
        } else {
            Ok(field_type_label(&arg, ci, config))
        }
    }

    #[askama::filter_fn]
    pub fn has_borrowed_bytes_args(
        callable: impl Callable,
        _v: &dyn askama::Values,
    ) -> Result<bool, askama::Error> {
        Ok(callable.arguments().iter().any(|a| a.is_borrowed_bytes()))
    }

    /// Rust reads the buffer during the call while nothing in the generated Java touches it again,
    /// so without a fence the JIT is free to treat it as dead and let the buffer be collected -
    /// freeing the memory Rust is reading. The lambda that lowers the argument happens to keep it
    /// reachable today; the fence stops that being load-bearing.
    #[askama::filter_fn]
    pub fn reachability_fences(
        callable: impl Callable,
        _v: &dyn askama::Values,
    ) -> Result<String, askama::Error> {
        Ok(callable
            .arguments()
            .iter()
            .filter(|a| a.is_borrowed_bytes())
            .map(|a| {
                format!(
                    "java.lang.ref.Reference.reachabilityFence({});",
                    JavaCodeOracle.var_name(a.name())
                )
            })
            .collect::<Vec<_>>()
            .join("\n            "))
    }

    #[askama::filter_fn]
    pub fn lower_fn_for_arg(
        arg: &Argument,
        _v: &dyn askama::Values,
        config: &Config,
        ci: &ComponentInterface,
    ) -> Result<String, askama::Error> {
        if arg.is_borrowed_bytes() {
            Ok("FfiConverterByRefBytes.INSTANCE.lower".to_string())
        } else {
            Ok(format!(
                "{}.lower",
                arg.as_codetype().ffi_converter_instance(config, ci)
            ))
        }
    }

    /// Always returns the boxed type name, for use in generic contexts like CompletableFuture<T>.
    /// This is the same as type_name but with a clearer name for template readability.
    #[askama::filter_fn]
    pub fn boxed_type_name(
        as_ct: &impl AsCodeType,
        _v: &dyn askama::Values,
        ci: &ComponentInterface,
        config: &Config,
    ) -> Result<String, askama::Error> {
        Ok(as_ct.as_codetype().type_label(ci, config))
    }

    /// Generates an equality expression for comparing two values of a field's type.
    /// For primitives: returns "left == right"
    /// For floats: "Type.compare(left, right) == 0", which agrees with `Type.hashCode` on NaN
    /// and signed zero where `==` does not
    /// For other primitives: "left == right"
    /// For array-holding types (see [`compounds::contains_array_rendering`]): "UniffiDeepValue.equals(left, right)"
    /// For objects: returns "java.util.Objects.equals(left, right)"
    #[askama::filter_fn]
    pub fn equals_expr<T: AsCodeType + AsType, L: std::fmt::Display, R: std::fmt::Display>(
        field: &T,
        _v: &dyn askama::Values,
        left: L,
        right: R,
    ) -> Result<String, askama::Error> {
        match field.as_type() {
            Type::Float32 => Ok(format!("java.lang.Float.compare({}, {}) == 0", left, right)),
            Type::Float64 => Ok(format!(
                "java.lang.Double.compare({}, {}) == 0",
                left, right
            )),
            _ if field.as_codetype().type_label_primitive().is_some() => {
                Ok(format!("{} == {}", left, right))
            }
            ty if compounds::contains_array_rendering(&ty) => {
                Ok(format!("UniffiDeepValue.equals({}, {})", left, right))
            }
            _ => Ok(format!("java.util.Objects.equals({}, {})", left, right)),
        }
    }

    /// A field's contribution to a hash accumulation. Primitives dispatch to their boxed type's
    /// static hashCode so nothing boxes; array-holding types (see
    /// [`compounds::contains_array_rendering`]) go through `UniffiDeepValue`.
    #[askama::filter_fn]
    pub fn hash_code_expr<T: AsType, V: std::fmt::Display>(
        field: &T,
        _v: &dyn askama::Values,
        value: V,
    ) -> Result<String, askama::Error> {
        match field.as_type() {
            Type::Boolean => Ok(format!("java.lang.Boolean.hashCode({})", value)),
            Type::Int8 | Type::UInt8 => Ok(format!("java.lang.Byte.hashCode({})", value)),
            Type::Int16 | Type::UInt16 => Ok(format!("java.lang.Short.hashCode({})", value)),
            Type::Int32 | Type::UInt32 => Ok(format!("java.lang.Integer.hashCode({})", value)),
            Type::Int64 | Type::UInt64 => Ok(format!("java.lang.Long.hashCode({})", value)),
            Type::Float32 => Ok(format!("java.lang.Float.hashCode({})", value)),
            Type::Float64 => Ok(format!("java.lang.Double.hashCode({})", value)),
            ty if compounds::contains_array_rendering(&ty) => {
                Ok(format!("UniffiDeepValue.hashCode({})", value))
            }
            _ => Ok(format!("java.util.Objects.hashCode({})", value)),
        }
    }

    /// As [`hash_code_expr`], for positions whose components are reference types.
    #[askama::filter_fn]
    pub fn boxed_hash_code_expr<T: AsType, V: std::fmt::Display>(
        field: &T,
        _v: &dyn askama::Values,
        value: V,
    ) -> Result<String, askama::Error> {
        if compounds::contains_array_rendering(&field.as_type()) {
            Ok(format!("UniffiDeepValue.hashCode({})", value))
        } else {
            Ok(format!("java.util.Objects.hashCode({})", value))
        }
    }

    /// As [`equals_expr`], for positions whose components are reference types (enum variant
    /// records box their primitives, so `==` would compare boxed identities).
    #[askama::filter_fn]
    pub fn boxed_equals_expr<T: AsType, L: std::fmt::Display, R: std::fmt::Display>(
        field: &T,
        _v: &dyn askama::Values,
        left: L,
        right: R,
    ) -> Result<String, askama::Error> {
        if compounds::contains_array_rendering(&field.as_type()) {
            Ok(format!("UniffiDeepValue.equals({}, {})", left, right))
        } else {
            Ok(format!("java.util.Objects.equals({}, {})", left, right))
        }
    }

    /// See [`compounds::contains_array_rendering`].
    #[askama::filter_fn]
    pub fn contains_array_rendering(
        as_type: &impl AsType,
        _v: &dyn askama::Values,
    ) -> Result<bool, askama::Error> {
        Ok(compounds::contains_array_rendering(&as_type.as_type()))
    }

    /// Whether any field's rendering needs `UniffiDeepValue` equality. See
    /// [`compounds::contains_array_rendering`].
    #[askama::filter_fn]
    pub fn has_array_rendered_field(
        fields: &[Field],
        _v: &dyn askama::Values,
    ) -> Result<bool, askama::Error> {
        Ok(fields
            .iter()
            .any(|f| compounds::contains_array_rendering(&f.as_type())))
    }

    /// The Java name of a field: `v{index}` for a tuple variant's positional fields. Mirrors the
    /// `field_name` template macro for use in expression positions.
    #[askama::filter_fn]
    pub fn field_java_name(
        field: &Field,
        _v: &dyn askama::Values,
        index: &usize,
    ) -> Result<String, askama::Error> {
        if field.name().is_empty() {
            Ok(format!("v{index}"))
        } else {
            Ok(JavaCodeOracle.var_name(field.name()))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use uniffi_bindgen::interface::ComponentInterface;
    use uniffi_meta::{
        CallbackInterfaceMetadata, CustomTypeMetadata, EnumMetadata, EnumShape, FieldMetadata,
        FnMetadata, FnParamMetadata, LiteralMetadata, Metadata, MetadataGroup, MethodMetadata,
        NamespaceMetadata, ObjectImpl, ObjectMetadata, ObjectTraitImplMetadata, Radix,
        RecordMetadata, TraitKind, TraitMethodMetadata, Type, VariantMetadata,
    };

    #[test]
    fn error_variant_holding_an_object_is_closeable() {
        let mut group = test_group();
        group.add_item(Metadata::Object(ObjectMetadata {
            module_path: "test".to_string(),
            name: "Thing".to_string(),
            orig_name: None,
            remote: false,
            imp: ObjectImpl::Struct,
            docstring: None,
        }));
        group.add_item(Metadata::Enum(EnumMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "BoomError".to_string(),
            shape: EnumShape::Error { flat: false },
            remote: false,
            variants: vec![VariantMetadata {
                orig_name: None,
                name: "Boom".to_string(),
                discr: None,
                fields: vec![field(
                    "thing",
                    Type::Object {
                        module_path: "test".to_string(),
                        name: "Thing".to_string(),
                        imp: ObjectImpl::Struct,
                    },
                )],
                docstring: None,
            }],
            discr_type: None,
            non_exhaustive: false,
            docstring: None,
        }));
        group.add_item(Metadata::Func(FnMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "boom".to_string(),
            is_async: false,
            inputs: vec![],
            return_type: None,
            throws: Some(Type::Enum {
                module_path: "test".to_string(),
                name: "BoomError".to_string(),
            }),
            checksum: None,
            docstring: None,
        }));
        let mut ci = ComponentInterface::from_metadata(group).unwrap();
        ci.derive_ffi_funcs().unwrap();
        let bindings = generate_bindings(&Config::default(), &ci).unwrap();
        assert!(
            bindings.contains(
                "public class BoomException extends java.lang.Exception implements AutoCloseable"
            ),
            "callers catch the base type, so try-with-resources must work there:\n{}",
            error_variant_lines(&bindings)
        );
        assert!(
            bindings.contains("public static class Boom extends BoomException {"),
            "a class cannot `extends A, B`; the base provides AutoCloseable:\n{}",
            error_variant_lines(&bindings)
        );
        assert!(
            bindings.contains("public void close()"),
            "close() cannot narrow AutoCloseable's access:\n{}",
            error_variant_lines(&bindings)
        );
    }

    fn error_variant_lines(bindings: &str) -> String {
        bindings
            .lines()
            .filter(|l| l.contains("class Boom") || l.contains("close()"))
            .collect::<Vec<_>>()
            .join("\n")
    }

    #[test]
    fn preserves_error_type_named_error() {
        // create a metadata group with an error enum named only "Error" and a
        // function that always returns that error.
        let mut group = MetadataGroup {
            namespace: NamespaceMetadata {
                crate_name: "test".to_string(),
                name: "test".to_string(),
            },
            namespace_docstring: None,
            items: Default::default(),
        };
        group.add_item(Metadata::Enum(EnumMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "Error".to_string(),
            shape: EnumShape::Error { flat: true },
            remote: false,
            variants: vec![VariantMetadata {
                orig_name: None,
                name: "Oops".to_string(),
                discr: None,
                fields: vec![],
                docstring: None,
            }],
            discr_type: None,
            non_exhaustive: false,
            docstring: None,
        }));
        group.add_item(Metadata::Func(FnMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "always_fails".to_string(),
            is_async: false,
            inputs: vec![],
            return_type: None,
            throws: Some(Type::Enum {
                module_path: "test".to_string(),
                name: "Error".to_string(),
            }),
            checksum: None,
            docstring: None,
        }));
        let ci = ComponentInterface::from_metadata(group).unwrap();
        let bindings = generate_bindings(&Config::default(), &ci).unwrap();

        // show that the generated bindings preserve the name
        // Note: we use java.lang.Exception to avoid collisions with user types
        let relevant_lines = bindings
            .lines()
            .filter(|line| {
                line.contains("class Error extends java.lang.Exception")
                    || line.contains("class Exception extends java.lang.Exception")
                    || line.contains("throws Error")
                    || line.contains("throws Exception")
            })
            .collect::<Vec<_>>()
            .join("\n");

        assert!(
            bindings.contains("public class Error extends java.lang.Exception"),
            "expected generated bindings to preserve the `Error` type name:\n{relevant_lines}"
        );
        assert!(
            bindings.contains("public static void alwaysFails() throws Error"),
            "expected generated bindings to preserve `throws Error`:\n{relevant_lines}"
        );
    }

    #[test]
    fn converts_error_suffix_but_not_bare_error() {
        assert_eq!(
            JavaCodeOracle.convert_error_suffix("ExampleError"),
            "ExampleException"
        );
        assert_eq!(JavaCodeOracle.convert_error_suffix("Error"), "Error");
    }

    fn create_primitive_array_test_group() -> MetadataGroup {
        let mut group = MetadataGroup {
            namespace: NamespaceMetadata {
                crate_name: "test".to_string(),
                name: "test".to_string(),
            },
            namespace_docstring: None,
            items: Default::default(),
        };

        // Add functions for each primitive array type
        let primitive_types = [
            ("process_floats", Type::Float32),
            ("process_doubles", Type::Float64),
            ("process_shorts", Type::Int16),
            ("process_ints", Type::Int32),
            ("process_longs", Type::Int64),
            ("process_bools", Type::Boolean),
        ];

        for (name, inner_type) in primitive_types {
            group.add_item(Metadata::Func(FnMetadata {
                orig_name: None,
                module_path: "test".to_string(),
                name: name.to_string(),
                is_async: false,
                inputs: vec![FnParamMetadata {
                    name: "data".to_string(),
                    ty: Type::Sequence {
                        inner_type: Box::new(inner_type.clone()),
                    },
                    by_ref: false,
                    optional: false,
                    default: None,
                }],
                return_type: Some(Type::Sequence {
                    inner_type: Box::new(inner_type),
                }),
                throws: None,
                checksum: None,
                docstring: None,
            }));
        }

        group
    }

    #[test]
    fn generates_float32_primitive_array() {
        let group = create_primitive_array_test_group();
        let ci = ComponentInterface::from_metadata(group).unwrap();
        let bindings = generate_bindings(&Config::default(), &ci).unwrap();

        assert!(
            bindings.contains("float[]"),
            "expected float[] in generated bindings"
        );
        assert!(
            bindings.contains("FfiConverterFloat32Array"),
            "expected FfiConverterFloat32Array in generated bindings"
        );
        assert!(
            bindings.contains("public static float[] processFloats(float[] data)"),
            "expected processFloats method with float[] signature"
        );
    }

    #[test]
    fn generates_float64_primitive_array() {
        let group = create_primitive_array_test_group();
        let ci = ComponentInterface::from_metadata(group).unwrap();
        let bindings = generate_bindings(&Config::default(), &ci).unwrap();

        assert!(
            bindings.contains("double[]"),
            "expected double[] in generated bindings"
        );
        assert!(
            bindings.contains("FfiConverterFloat64Array"),
            "expected FfiConverterFloat64Array in generated bindings"
        );
        assert!(
            bindings.contains("public static double[] processDoubles(double[] data)"),
            "expected processDoubles method with double[] signature"
        );
    }

    #[test]
    fn box_renders_as_its_inner_type() {
        // `Box<T>` exists only in scaffolding, so leaking it into a signature would name a Java
        // type that was never generated.
        let mut group = MetadataGroup {
            namespace: NamespaceMetadata {
                crate_name: "test".to_string(),
                name: "test".to_string(),
            },
            namespace_docstring: None,
            items: Default::default(),
        };
        group.add_item(Metadata::Func(FnMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "unwrap_box".to_string(),
            is_async: false,
            inputs: vec![FnParamMetadata {
                name: "data".to_string(),
                ty: Type::Box {
                    inner_type: Box::new(Type::String),
                },
                by_ref: false,
                optional: false,
                default: None,
            }],
            return_type: Some(Type::String),
            throws: None,
            checksum: None,
            docstring: None,
        }));

        let mut ci = ComponentInterface::from_metadata(group).unwrap();
        ci.derive_ffi_funcs().unwrap();
        let bindings = generate_bindings(&Config::default(), &ci).unwrap();

        assert!(
            bindings.contains("public static java.lang.String unwrapBox(java.lang.String data)"),
            "expected Box<String> to render as java.lang.String:\n{}",
            bindings
                .lines()
                .filter(|line| line.contains("unwrapBox"))
                .collect::<Vec<_>>()
                .join("\n")
        );
    }

    fn point_type() -> Type {
        Type::Record {
            module_path: "test".to_string(),
            name: "Point".to_string(),
        }
    }

    fn field(name: &str, ty: Type) -> FieldMetadata {
        FieldMetadata {
            orig_name: None,
            name: name.to_string(),
            ty,
            default: None,
            docstring: None,
        }
    }

    /// Renders `enum Shape { Point, Group { ..fields } }` alongside a `Point` record, and returns
    /// the `Group` variant's declaration on one line.
    ///
    /// The variant named `Point` shadows the top-level `Point` from inside the sealed interface,
    /// so any field type that is not package-qualified resolves to the wrong `Point` and fails to
    /// compile.
    fn group_variant_decl(fields: Vec<FieldMetadata>) -> String {
        let mut group = test_group();
        group.add_item(Metadata::Record(RecordMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "Point".to_string(),
            remote: false,
            fields: vec![field("x", Type::Int32)],
            docstring: None,
        }));
        group.add_item(Metadata::Enum(EnumMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "Shape".to_string(),
            shape: EnumShape::Enum,
            remote: false,
            variants: vec![
                VariantMetadata {
                    orig_name: None,
                    name: "Point".to_string(),
                    discr: None,
                    fields: vec![],
                    docstring: None,
                },
                VariantMetadata {
                    orig_name: None,
                    name: "Group".to_string(),
                    discr: None,
                    fields,
                    docstring: None,
                },
            ],
            discr_type: None,
            non_exhaustive: false,
            docstring: None,
        }));
        group.add_item(Metadata::Func(FnMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "get_shape".to_string(),
            is_async: false,
            inputs: vec![],
            return_type: Some(Type::Enum {
                module_path: "test".to_string(),
                name: "Shape".to_string(),
            }),
            throws: None,
            checksum: None,
            docstring: None,
        }));

        let mut ci = ComponentInterface::from_metadata(group).unwrap();
        ci.derive_ffi_funcs().unwrap();
        let bindings = generate_bindings(&Config::default(), &ci).unwrap();

        // The record header and its fields land on separate lines, so match the whole decl.
        let lines: Vec<&str> = bindings.lines().collect();
        let start = lines
            .iter()
            .position(|line| line.contains("record Group("))
            .unwrap_or_else(|| panic!("no Group variant in:\n{bindings}"));
        lines[start..]
            .iter()
            .take_while(|line| !line.contains("implements"))
            .chain(lines[start..].iter().find(|l| l.contains("implements")))
            .copied()
            .collect::<Vec<_>>()
            .join(" ")
    }

    #[test]
    fn set_field_on_an_enum_variant_is_package_qualified() {
        let decl = group_variant_decl(vec![
            field(
                "members",
                Type::Set {
                    inner_type: Box::new(point_type()),
                },
            ),
            field(
                "ordered",
                Type::Sequence {
                    inner_type: Box::new(point_type()),
                },
            ),
        ]);

        assert!(
            decl.contains("java.util.List<uniffi.Point>"),
            "Vec<Point> should be qualified, got: {decl}"
        );
        assert!(
            decl.contains("java.util.Set<uniffi.Point>"),
            "HashSet<Point> should be qualified too, got: {decl}"
        );
    }

    #[test]
    fn box_field_on_an_enum_variant_is_package_qualified() {
        let decl = group_variant_decl(vec![field(
            "boxed",
            Type::Box {
                inner_type: Box::new(point_type()),
            },
        )]);

        assert!(
            decl.contains("uniffi.Point boxed"),
            "Box<Point> should be qualified, got: {decl}"
        );
    }

    #[test]
    fn hashed_field_on_an_enum_variant_keeps_the_boxed_list() {
        let decl = group_variant_decl(vec![
            field(
                "members",
                Type::Set {
                    inner_type: Box::new(Type::Sequence {
                        inner_type: Box::new(Type::Int32),
                    }),
                },
            ),
            field(
                "keyed",
                Type::Map {
                    key_type: Box::new(Type::Sequence {
                        inner_type: Box::new(Type::Int32),
                    }),
                    value_type: Box::new(Type::Sequence {
                        inner_type: Box::new(Type::Int32),
                    }),
                },
            ),
        ]);

        assert!(
            decl.contains("java.util.Set<java.util.List<java.lang.Integer>>"),
            "Set element should stay boxed, got: {decl}"
        );
        assert!(
            decl.contains("java.util.Map<java.util.List<java.lang.Integer>, int[]>"),
            "only the Map key is hashed, got: {decl}"
        );
    }

    #[test]
    fn hashed_primitive_array_stays_boxed_in_a_signature() {
        let mut group = test_group();
        group.add_item(Metadata::Func(FnMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "hashed".to_string(),
            is_async: false,
            inputs: vec![
                FnParamMetadata {
                    name: "set".to_string(),
                    ty: Type::Set {
                        inner_type: Box::new(Type::Sequence {
                            inner_type: Box::new(Type::Int32),
                        }),
                    },
                    by_ref: false,
                    optional: false,
                    default: None,
                },
                FnParamMetadata {
                    name: "map".to_string(),
                    ty: Type::Map {
                        key_type: Box::new(Type::Sequence {
                            inner_type: Box::new(Type::Int32),
                        }),
                        value_type: Box::new(Type::Sequence {
                            inner_type: Box::new(Type::Float64),
                        }),
                    },
                    by_ref: false,
                    optional: false,
                    default: None,
                },
            ],
            return_type: None,
            throws: None,
            checksum: None,
            docstring: None,
        }));
        let mut ci = ComponentInterface::from_metadata(group).unwrap();
        ci.derive_ffi_funcs().unwrap();
        let bindings = generate_bindings(&Config::default(), &ci).unwrap();

        assert!(
            bindings.contains(
                "hashed(java.util.Set<java.util.List<java.lang.Integer>> set, \
                 java.util.Map<java.util.List<java.lang.Integer>, double[]> map)"
            ),
            "hashed positions should stay boxed, values should not:\n{}",
            bindings
                .lines()
                .filter(|l| l.contains("hashed("))
                .collect::<Vec<_>>()
                .join("\n")
        );
        // The boxed rendering needs a converter the array helper does not provide.
        assert!(
            bindings.contains("enum FfiConverterSequenceInteger"),
            "expected the generic sequence converter alongside FfiConverterInt32Array"
        );
        assert!(
            bindings.contains("enum FfiConverterInt32Array"),
            "expected the array helper to still be emitted"
        );
    }

    fn seq(inner: Type) -> Type {
        Type::Sequence {
            inner_type: Box::new(inner),
        }
    }

    fn param(name: &str, ty: Type) -> FnParamMetadata {
        FnParamMetadata {
            name: name.to_string(),
            ty,
            by_ref: false,
            optional: false,
            default: None,
        }
    }

    /// Bindings for an interface holding a single function of these parameters.
    fn bindings_for_fn(inputs: Vec<FnParamMetadata>, config: &Config) -> String {
        let mut group = test_group();
        group.add_item(Metadata::Func(FnMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "subject".to_string(),
            is_async: false,
            inputs,
            return_type: None,
            throws: None,
            checksum: None,
            docstring: None,
        }));
        let mut ci = ComponentInterface::from_metadata(group).unwrap();
        ci.derive_ffi_funcs().unwrap();
        generate_bindings(config, &ci).unwrap()
    }

    #[test]
    fn nested_hashed_sequences_stay_boxed_at_every_depth() {
        let bindings = bindings_for_fn(
            vec![param(
                "nested",
                Type::Set {
                    inner_type: Box::new(seq(seq(Type::Int32))),
                },
            )],
            &Config::default(),
        );

        assert!(
            bindings.contains(
                "java.util.Set<java.util.List<java.util.List<java.lang.Integer>>> nested"
            ),
            "the inner array must stay boxed too, or contains() breaks one level down:\n{}",
            signature_lines(&bindings)
        );
        assert!(
            bindings.contains("enum FfiConverterSequenceSequenceInteger"),
            "expected the hashed converter for the outer sequence"
        );
        assert!(
            bindings.contains("enum FfiConverterSequenceInteger"),
            "expected the hashed converter for the inner sequence"
        );
    }

    #[test]
    fn optional_wrapped_hashed_element_stays_boxed() {
        let bindings = bindings_for_fn(
            vec![param(
                "opt",
                Type::Set {
                    inner_type: Box::new(Type::Optional {
                        inner_type: Box::new(seq(Type::Int32)),
                    }),
                },
            )],
            &Config::default(),
        );

        assert!(
            bindings.contains("java.util.Set<java.util.List<java.lang.Integer>> opt"),
            "an optional element is invisibly nullable but must stay boxed:\n{}",
            signature_lines(&bindings)
        );
        assert!(
            bindings.contains("enum FfiConverterOptionalSequenceInteger"),
            "expected the hashed optional converter"
        );
        assert!(
            bindings.contains("enum FfiConverterSequenceInteger"),
            "expected the hashed converter for the wrapped sequence"
        );
    }

    #[test]
    fn bytes_map_key_stays_boxed() {
        let bindings = bindings_for_fn(
            vec![param(
                "keyed",
                Type::Map {
                    key_type: Box::new(Type::Bytes),
                    value_type: Box::new(Type::String),
                },
            )],
            &Config::default(),
        );

        assert!(
            bindings
                .contains("java.util.Map<java.util.List<java.lang.Byte>, java.lang.String> keyed"),
            "byte[] keys never match on lookup:\n{}",
            signature_lines(&bindings)
        );
        assert!(
            bindings.contains("enum FfiConverterSequenceByte"),
            "expected the byte sequence converter for the hashed key"
        );
    }

    #[test]
    fn hashed_bytes_reuses_an_existing_byte_sequence_converter() {
        let bindings = bindings_for_fn(
            vec![
                param(
                    "hashed",
                    Type::Set {
                        inner_type: Box::new(Type::Bytes),
                    },
                ),
                param("plain", seq(Type::Int8)),
            ],
            &Config::default(),
        );

        assert_eq!(
            bindings.matches("enum FfiConverterSequenceByte ").count(),
            1,
            "hashed bytes and Vec<i8> share a converter; two copies would not compile"
        );
    }

    fn signature_lines(bindings: &str) -> String {
        bindings
            .lines()
            .filter(|l| l.contains("subject("))
            .collect::<Vec<_>>()
            .join("\n")
    }

    fn holder_group() -> MetadataGroup {
        let mut group = test_group();
        group.add_item(Metadata::Record(RecordMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "Holder".to_string(),
            remote: false,
            fields: vec![
                field("label", Type::String),
                field("ratio", Type::Float64),
                field("data", seq(Type::Int32)),
                field("nested", seq(seq(Type::Int32))),
            ],
            docstring: None,
        }));
        group
    }

    #[test]
    fn record_with_array_fields_gets_value_equality() {
        let mut ci = ComponentInterface::from_metadata(holder_group()).unwrap();
        ci.derive_ffi_funcs().unwrap();
        let bindings = generate_bindings(&Config::default(), &ci).unwrap();

        assert!(
            bindings.contains("UniffiDeepValue.equals(data, t.data)"),
            "array fields must compare by value:\n{bindings}"
        );
        assert!(
            bindings.contains("java.lang.Double.compare(ratio, t.ratio) == 0"),
            "`==` on a double breaks reflexivity for NaN:\n{bindings}"
        );
        assert!(
            bindings.contains("31 * result + UniffiDeepValue.hashCode(data)"),
            "array fields must hash by value:\n{bindings}"
        );
        assert!(
            bindings.contains("31 * result + java.lang.Double.hashCode(ratio)"),
            "double fields must hash without boxing:\n{bindings}"
        );
    }

    #[test]
    fn immutable_record_with_array_fields_overrides_equality() {
        let mut ci = ComponentInterface::from_metadata(holder_group()).unwrap();
        ci.derive_ffi_funcs().unwrap();
        let config = Config {
            generate_immutable_records: Some(true),
            ..Config::default()
        };
        let bindings = generate_bindings(&config, &ci).unwrap();

        assert!(
            bindings.contains("public record Holder("),
            "expected an immutable record:\n{bindings}"
        );
        assert!(
            bindings.contains("UniffiDeepValue.equals(data, t.data)"),
            "the record-generated equals sees array components by identity:\n{bindings}"
        );
        assert!(
            bindings.contains("java.lang.Double.compare(ratio, t.ratio) == 0"),
            "the override must keep the record default's NaN reflexivity:\n{bindings}"
        );
    }

    #[test]
    fn custom_type_wrapper_over_arrays_gets_value_equality() {
        let mut group = test_group();
        group.add_item(Metadata::CustomType(CustomTypeMetadata {
            module_path: "test".to_string(),
            name: "IntsKey".to_string(),
            orig_name: None,
            builtin: seq(Type::Int32),
            docstring: None,
        }));
        let mut ci = ComponentInterface::from_metadata(group).unwrap();
        ci.derive_ffi_funcs().unwrap();
        let bindings = generate_bindings(&Config::default(), &ci).unwrap();

        assert!(
            bindings.contains("UniffiDeepValue.equals(value, t.value)"),
            "the wrapper record's array component must compare by value:\n{bindings}"
        );
        assert!(
            bindings.contains("UniffiDeepValue.hashCode(value)"),
            "the wrapper record's hashCode must match its equals:\n{bindings}"
        );
    }

    #[test]
    fn enum_variant_with_array_field_overrides_equality() {
        let mut group = test_group();
        group.add_item(Metadata::Enum(EnumMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "Payload".to_string(),
            shape: EnumShape::Enum,
            remote: false,
            variants: vec![VariantMetadata {
                orig_name: None,
                name: "Ints".to_string(),
                discr: None,
                // A tuple variant, so the positional v1 name has to thread through.
                fields: vec![field("", seq(Type::Int32))],
                docstring: None,
            }],
            discr_type: None,
            non_exhaustive: false,
            docstring: None,
        }));
        let mut ci = ComponentInterface::from_metadata(group).unwrap();
        ci.derive_ffi_funcs().unwrap();
        let bindings = generate_bindings(&Config::default(), &ci).unwrap();

        assert!(
            bindings.contains("UniffiDeepValue.equals(v1, t.v1)"),
            "the variant record's equals sees array components by identity:\n{bindings}"
        );
        assert!(
            bindings.contains("31 * result + UniffiDeepValue.hashCode(v1)"),
            "the variant record's hashCode must match its equals:\n{bindings}"
        );
    }

    #[test]
    fn u64_discriminant_above_signed_max_uses_the_hex_form() {
        let mut group = test_group();
        group.add_item(Metadata::Enum(EnumMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "Big".to_string(),
            shape: EnumShape::Enum,
            remote: false,
            variants: vec![VariantMetadata {
                orig_name: None,
                name: "Hi".to_string(),
                discr: Some(LiteralMetadata::UInt(
                    u64::MAX,
                    Radix::Decimal,
                    Type::UInt64,
                )),
                fields: vec![],
                docstring: None,
            }],
            discr_type: Some(Type::UInt64),
            non_exhaustive: false,
            docstring: None,
        }));
        let mut ci = ComponentInterface::from_metadata(group).unwrap();
        ci.derive_ffi_funcs().unwrap();
        let bindings = generate_bindings(&Config::default(), &ci).unwrap();

        assert!(
            bindings.contains("HI(0xFFFFFFFFFFFFFFFFL)"),
            "a decimal literal for u64::MAX does not compile:\n{}",
            bindings
                .lines()
                .filter(|l| l.contains("HI("))
                .collect::<Vec<_>>()
                .join("\n")
        );
    }

    #[test]
    fn generates_int32_primitive_array() {
        let group = create_primitive_array_test_group();
        let ci = ComponentInterface::from_metadata(group).unwrap();
        let bindings = generate_bindings(&Config::default(), &ci).unwrap();

        assert!(
            bindings.contains("int[]"),
            "expected int[] in generated bindings"
        );
        assert!(
            bindings.contains("FfiConverterInt32Array"),
            "expected FfiConverterInt32Array in generated bindings"
        );
        assert!(
            bindings.contains("public static int[] processInts(int[] data)"),
            "expected processInts method with int[] signature"
        );
    }

    #[test]
    fn generates_int64_primitive_array() {
        let group = create_primitive_array_test_group();
        let ci = ComponentInterface::from_metadata(group).unwrap();
        let bindings = generate_bindings(&Config::default(), &ci).unwrap();

        assert!(
            bindings.contains("long[]"),
            "expected long[] in generated bindings"
        );
        assert!(
            bindings.contains("FfiConverterInt64Array"),
            "expected FfiConverterInt64Array in generated bindings"
        );
        assert!(
            bindings.contains("public static long[] processLongs(long[] data)"),
            "expected processLongs method with long[] signature"
        );
    }

    #[test]
    fn generates_int16_primitive_array() {
        let group = create_primitive_array_test_group();
        let ci = ComponentInterface::from_metadata(group).unwrap();
        let bindings = generate_bindings(&Config::default(), &ci).unwrap();

        assert!(
            bindings.contains("short[]"),
            "expected short[] in generated bindings"
        );
        assert!(
            bindings.contains("FfiConverterInt16Array"),
            "expected FfiConverterInt16Array in generated bindings"
        );
        assert!(
            bindings.contains("public static short[] processShorts(short[] data)"),
            "expected processShorts method with short[] signature"
        );
    }

    #[test]
    fn generates_boolean_primitive_array() {
        let group = create_primitive_array_test_group();
        let ci = ComponentInterface::from_metadata(group).unwrap();
        let bindings = generate_bindings(&Config::default(), &ci).unwrap();

        assert!(
            bindings.contains("boolean[]"),
            "expected boolean[] in generated bindings"
        );
        assert!(
            bindings.contains("FfiConverterBooleanArray"),
            "expected FfiConverterBooleanArray in generated bindings"
        );
        assert!(
            bindings.contains("public static boolean[] processBools(boolean[] data)"),
            "expected processBools method with boolean[] signature"
        );
    }

    #[test]
    fn does_not_generate_list_for_primitive_sequences() {
        let group = create_primitive_array_test_group();
        let ci = ComponentInterface::from_metadata(group).unwrap();
        let bindings = generate_bindings(&Config::default(), &ci).unwrap();

        // Verify that we don't generate boxed List types for primitives
        assert!(
            !bindings.contains("List<java.lang.Float>"),
            "should not contain List<java.lang.Float>"
        );
        assert!(
            !bindings.contains("List<java.lang.Double>"),
            "should not contain List<java.lang.Double>"
        );
        assert!(
            !bindings.contains("List<java.lang.Integer>"),
            "should not contain List<java.lang.Integer>"
        );
        assert!(
            !bindings.contains("List<java.lang.Long>"),
            "should not contain List<java.lang.Long>"
        );
        assert!(
            !bindings.contains("List<java.lang.Short>"),
            "should not contain List<java.lang.Short>"
        );
        assert!(
            !bindings.contains("List<java.lang.Boolean>"),
            "should not contain List<java.lang.Boolean>"
        );
    }

    #[test]
    fn android_replaces_ffm_package() {
        let mut group = MetadataGroup {
            namespace: NamespaceMetadata {
                crate_name: "test".to_string(),
                name: "test".to_string(),
            },
            namespace_docstring: None,
            items: Default::default(),
        };
        group.add_item(Metadata::Func(FnMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "noop".to_string(),
            is_async: false,
            inputs: vec![],
            return_type: None,
            throws: None,
            checksum: None,
            docstring: None,
        }));

        let mut ci = ComponentInterface::from_metadata(group).unwrap();
        ci.derive_ffi_funcs().unwrap();

        let android_config: Config = toml::from_str("android = true").unwrap();

        let bindings = generate_bindings(&android_config, &ci).unwrap();

        assert!(
            !bindings.contains("java.lang.foreign."),
            "android bindings should not contain java.lang.foreign"
        );
        assert!(
            bindings.contains("com.v7878.foreign."),
            "android bindings should contain com.v7878.foreign"
        );
        // MethodHandle/MethodHandles/MethodType should NOT be replaced
        assert!(
            bindings.contains("java.lang.invoke.MethodHandle"),
            "android bindings should preserve java.lang.invoke.MethodHandle"
        );
        // Standard java.lang types should NOT be replaced
        assert!(
            bindings.contains("java.lang.Exception"),
            "android bindings should preserve java.lang.Exception"
        );
    }

    #[test]
    fn trait_impl_with_submodule_path() {
        // Regression test: when a crate has multiple modules, module_path is
        // "crate_name::submodule". component_interface_for_module_path() handles
        // this by checking the local CI's crate_name first before falling back
        // to find_component_interface() for external crates.
        let submodule_path = "mycrate::inner";
        let mut group = MetadataGroup {
            namespace: NamespaceMetadata {
                crate_name: "mycrate".to_string(),
                name: "mycrate".to_string(),
            },
            namespace_docstring: None,
            items: Default::default(),
        };

        // A trait object defined in a submodule
        group.add_item(Metadata::Object(ObjectMetadata {
            orig_name: None,
            module_path: submodule_path.to_string(),
            name: "MyTrait".to_string(),
            remote: false,
            imp: ObjectImpl::Trait(TraitKind::ForeignOnly),
            docstring: None,
        }));

        // A concrete object that implements the trait, also in the submodule
        group.add_item(Metadata::Object(ObjectMetadata {
            orig_name: None,
            module_path: submodule_path.to_string(),
            name: "MyObj".to_string(),
            remote: false,
            imp: ObjectImpl::Struct,
            docstring: None,
        }));

        group.add_item(Metadata::ObjectTraitImpl(ObjectTraitImplMetadata {
            ty: Type::Object {
                module_path: submodule_path.to_string(),
                name: "MyObj".to_string(),
                imp: ObjectImpl::Struct,
            },
            trait_ty: Type::Object {
                module_path: submodule_path.to_string(),
                name: "MyTrait".to_string(),
                imp: ObjectImpl::Trait(TraitKind::ForeignOnly),
            },
        }));

        let mut ci = ComponentInterface::from_metadata(group).unwrap();
        ci.derive_ffi_funcs().unwrap();
        let bindings = generate_bindings(&Config::default(), &ci).unwrap();

        // The object should implement the trait interface
        assert!(
            bindings.contains("implements AutoCloseable, MyObjInterface, MyTrait"),
            "MyObj should implement MyTrait via trait_interface_name even with submodule path:\n{}",
            bindings
                .lines()
                .filter(|l| l.contains("MyObj") || l.contains("MyTrait"))
                .collect::<Vec<_>>()
                .join("\n")
        );
    }

    #[test]
    fn local_trait_impls_accept_submodule_module_paths() {
        let mut group = MetadataGroup {
            namespace: NamespaceMetadata {
                crate_name: "test".to_string(),
                name: "test".to_string(),
            },
            namespace_docstring: None,
            items: Default::default(),
        };
        group.add_item(Metadata::Object(ObjectMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "DefaultMetricsRecorder".to_string(),
            remote: false,
            imp: ObjectImpl::Struct,
            docstring: None,
        }));
        group.add_item(Metadata::CallbackInterface(CallbackInterfaceMetadata {
            module_path: "test::metrics".to_string(),
            name: "MetricsRecorder".to_string(),
            docstring: None,
        }));
        group.add_item(Metadata::ObjectTraitImpl(ObjectTraitImplMetadata {
            ty: Type::Object {
                module_path: "test".to_string(),
                name: "DefaultMetricsRecorder".to_string(),
                imp: ObjectImpl::Struct,
            },
            trait_ty: Type::CallbackInterface {
                module_path: "test::metrics".to_string(),
                name: "MetricsRecorder".to_string(),
            },
        }));

        let mut ci = ComponentInterface::from_metadata(group).unwrap();
        ci.derive_ffi_funcs().unwrap();

        let interface_name = super::filters::trait_interface_name_for(
            &Type::CallbackInterface {
                module_path: "test::metrics".to_string(),
                name: "MetricsRecorder".to_string(),
            },
            &ci,
        )
        .unwrap();
        assert_eq!(interface_name, "MetricsRecorder");

        let bindings = generate_bindings(&Config::default(), &ci).unwrap();
        assert!(
            bindings.contains("DefaultMetricsRecorderInterface, MetricsRecorder"),
            "expected local callback trait impls with submodule paths to render successfully:\n{}",
            bindings
                .lines()
                .filter(|line| line.contains("class DefaultMetricsRecorder"))
                .collect::<Vec<_>>()
                .join("\n")
        );
    }

    fn nullness_config() -> Config {
        toml::from_str("nullness_annotations = true").unwrap()
    }

    #[test]
    fn nullable_type_label_fully_qualified() {
        assert_eq!(
            super::nullable_type_label("java.lang.String"),
            "java.lang.@org.jspecify.annotations.Nullable String"
        );
    }

    #[test]
    fn nullable_type_label_unqualified() {
        assert_eq!(
            super::nullable_type_label("String"),
            "@org.jspecify.annotations.Nullable String"
        );
    }

    #[test]
    fn nullable_type_label_nested_class() {
        assert_eq!(
            super::nullable_type_label("UniffiCleaner.Cleanable"),
            "UniffiCleaner.@org.jspecify.annotations.Nullable Cleanable"
        );
    }

    #[test]
    fn nullable_type_label_generic_type() {
        assert_eq!(
            super::nullable_type_label("java.util.Map<java.lang.String, java.lang.Integer>"),
            "java.util.@org.jspecify.annotations.Nullable Map<java.lang.String, java.lang.Integer>"
        );
    }

    #[test]
    fn nullable_type_label_generic_with_nullable_inner() {
        // Simulates Optional<Map<String, Optional<Int32>>>: the inner Optional
        // is already annotated, then the outer Optional annotates the Map itself.
        assert_eq!(
            super::nullable_type_label(
                "java.util.Map<java.lang.String, java.lang.@org.jspecify.annotations.Nullable Integer>"
            ),
            "java.util.@org.jspecify.annotations.Nullable Map<java.lang.String, java.lang.@org.jspecify.annotations.Nullable Integer>"
        );
    }

    #[test]
    fn nullable_type_label_generic_unqualified() {
        assert_eq!(
            super::nullable_type_label("CompletableFuture<java.lang.String>"),
            "@org.jspecify.annotations.Nullable CompletableFuture<java.lang.String>"
        );
    }

    fn test_group() -> MetadataGroup {
        MetadataGroup {
            namespace: NamespaceMetadata {
                crate_name: "test".to_string(),
                name: "test".to_string(),
            },
            namespace_docstring: None,
            items: Default::default(),
        }
    }

    #[test]
    fn nullness_annotations_disabled_by_default() {
        let mut group = test_group();
        group.add_item(Metadata::Func(FnMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "maybe_string".to_string(),
            is_async: false,
            inputs: vec![FnParamMetadata {
                name: "input".to_string(),
                ty: Type::String,
                by_ref: false,
                optional: false,
                default: None,
            }],
            return_type: Some(Type::Optional {
                inner_type: Box::new(Type::String),
            }),
            throws: None,
            checksum: None,
            docstring: None,
        }));
        let ci = ComponentInterface::from_metadata(group).unwrap();
        let bindings = generate_bindings(&Config::default(), &ci).unwrap();
        assert!(
            !bindings.contains("@org.jspecify.annotations.NullMarked"),
            "should not contain @NullMarked when disabled"
        );
        assert!(
            !bindings.contains("@org.jspecify.annotations.Nullable"),
            "should not contain @Nullable when disabled"
        );
    }

    #[test]
    fn nullness_function_with_optional_param_and_return() {
        let mut group = test_group();
        group.add_item(Metadata::Func(FnMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "foo".to_string(),
            is_async: false,
            inputs: vec![
                FnParamMetadata {
                    name: "required".to_string(),
                    ty: Type::String,
                    by_ref: false,
                    optional: false,
                    default: None,
                },
                FnParamMetadata {
                    name: "optional".to_string(),
                    ty: Type::Optional {
                        inner_type: Box::new(Type::String),
                    },
                    by_ref: false,
                    optional: false,
                    default: None,
                },
            ],
            return_type: Some(Type::Optional {
                inner_type: Box::new(Type::Int32),
            }),
            throws: None,
            checksum: None,
            docstring: None,
        }));
        let ci = ComponentInterface::from_metadata(group).unwrap();
        let bindings = generate_bindings(&nullness_config(), &ci).unwrap();
        assert!(
            bindings.contains("java.lang.@org.jspecify.annotations.Nullable Integer"),
            "return type should be @Nullable Integer"
        );
        assert!(
            bindings.contains("java.lang.@org.jspecify.annotations.Nullable String optional"),
            "optional param should be @Nullable String"
        );
        // The required param should NOT have @Nullable
        assert!(
            bindings.contains(
                "java.lang.String required, java.lang.@org.jspecify.annotations.Nullable"
            ),
            "required param should not have @Nullable"
        );
    }

    #[test]
    fn nullness_record_with_optional_field() {
        let mut group = test_group();
        group.add_item(Metadata::Record(RecordMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "Person".to_string(),
            remote: false,
            fields: vec![
                FieldMetadata {
                    orig_name: None,
                    name: "name".to_string(),
                    ty: Type::String,
                    default: None,
                    docstring: None,
                },
                FieldMetadata {
                    orig_name: None,
                    name: "nickname".to_string(),
                    ty: Type::Optional {
                        inner_type: Box::new(Type::String),
                    },
                    default: None,
                    docstring: None,
                },
            ],
            docstring: None,
        }));
        // Need a function to make the record reachable
        group.add_item(Metadata::Func(FnMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "get_person".to_string(),
            is_async: false,
            inputs: vec![],
            return_type: Some(Type::Record {
                module_path: "test".to_string(),
                name: "Person".to_string(),
            }),
            throws: None,
            checksum: None,
            docstring: None,
        }));
        let ci = ComponentInterface::from_metadata(group).unwrap();
        let bindings = generate_bindings(&nullness_config(), &ci).unwrap();
        assert!(
            bindings
                .contains("private java.lang.@org.jspecify.annotations.Nullable String nickname"),
            "optional field should have @Nullable:\n{}",
            bindings
                .lines()
                .filter(|l| l.contains("nickname"))
                .collect::<Vec<_>>()
                .join("\n")
        );
        // Non-optional field should NOT have @Nullable
        assert!(
            !bindings.contains("java.lang.@org.jspecify.annotations.Nullable String name"),
            "non-optional field should not have @Nullable"
        );
    }

    #[test]
    fn nullness_immutable_record_with_optional_field() {
        let mut group = test_group();
        group.add_item(Metadata::Record(RecordMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "Person".to_string(),
            remote: false,
            fields: vec![
                FieldMetadata {
                    orig_name: None,
                    name: "name".to_string(),
                    ty: Type::String,
                    default: None,
                    docstring: None,
                },
                FieldMetadata {
                    orig_name: None,
                    name: "nickname".to_string(),
                    ty: Type::Optional {
                        inner_type: Box::new(Type::String),
                    },
                    default: None,
                    docstring: None,
                },
            ],
            docstring: None,
        }));
        group.add_item(Metadata::Func(FnMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "get_person".to_string(),
            is_async: false,
            inputs: vec![],
            return_type: Some(Type::Record {
                module_path: "test".to_string(),
                name: "Person".to_string(),
            }),
            throws: None,
            checksum: None,
            docstring: None,
        }));
        let ci = ComponentInterface::from_metadata(group).unwrap();
        let config: Config =
            toml::from_str("nullness_annotations = true\ngenerate_immutable_records = true")
                .unwrap();
        let bindings = generate_bindings(&config, &ci).unwrap();
        assert!(
            bindings.contains("java.lang.@org.jspecify.annotations.Nullable String nickname"),
            "immutable record should have @Nullable on optional component:\n{}",
            bindings
                .lines()
                .filter(|l| l.contains("nickname"))
                .collect::<Vec<_>>()
                .join("\n")
        );
        assert!(
            !bindings.contains("java.lang.@org.jspecify.annotations.Nullable String name"),
            "non-optional component should not have @Nullable"
        );
    }

    #[test]
    fn nullness_object_method_with_optional_param() {
        let mut group = test_group();
        group.add_item(Metadata::Object(ObjectMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "MyObj".to_string(),
            remote: false,
            imp: ObjectImpl::Struct,
            docstring: None,
        }));
        group.add_item(Metadata::Method(MethodMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            self_name: "MyObj".to_string(),
            name: "do_thing".to_string(),
            is_async: false,
            inputs: vec![FnParamMetadata {
                name: "input".to_string(),
                ty: Type::Optional {
                    inner_type: Box::new(Type::String),
                },
                by_ref: false,
                optional: false,
                default: None,
            }],
            return_type: None,
            throws: None,
            takes_self_by_arc: false,
            checksum: None,
            docstring: None,
        }));
        let mut ci = ComponentInterface::from_metadata(group).unwrap();
        ci.derive_ffi_funcs().unwrap();
        let bindings = generate_bindings(&nullness_config(), &ci).unwrap();
        assert!(
            bindings.contains("java.lang.@org.jspecify.annotations.Nullable String input"),
            "object method param should have @Nullable:\n{}",
            bindings
                .lines()
                .filter(|l| l.contains("doThing"))
                .collect::<Vec<_>>()
                .join("\n")
        );
    }

    #[test]
    fn nullness_object_cleanable_field_annotated() {
        let mut group = test_group();
        group.add_item(Metadata::Object(ObjectMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "MyObj".to_string(),
            remote: false,
            imp: ObjectImpl::Struct,
            docstring: None,
        }));
        let mut ci = ComponentInterface::from_metadata(group).unwrap();
        ci.derive_ffi_funcs().unwrap();
        let bindings = generate_bindings(&nullness_config(), &ci).unwrap();
        assert!(
            bindings
                .contains("UniffiCleaner.@org.jspecify.annotations.Nullable Cleanable cleanable"),
            "cleanable field should have @Nullable when annotations enabled:\n{}",
            bindings
                .lines()
                .filter(|l| l.contains("cleanable"))
                .collect::<Vec<_>>()
                .join("\n")
        );
    }

    #[test]
    fn nullness_object_cleanable_field_not_annotated_by_default() {
        let mut group = test_group();
        group.add_item(Metadata::Object(ObjectMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "MyObj".to_string(),
            remote: false,
            imp: ObjectImpl::Struct,
            docstring: None,
        }));
        let mut ci = ComponentInterface::from_metadata(group).unwrap();
        ci.derive_ffi_funcs().unwrap();
        let bindings = generate_bindings(&Config::default(), &ci).unwrap();
        assert!(
            bindings.contains("UniffiCleaner.Cleanable cleanable"),
            "cleanable field should not have @Nullable by default"
        );
        assert!(
            !bindings.contains("UniffiCleaner.@org.jspecify.annotations.Nullable Cleanable"),
            "cleanable field should not have @Nullable when annotations disabled"
        );
    }

    #[test]
    fn nullness_enum_variant_with_optional_field() {
        let mut group = test_group();
        group.add_item(Metadata::Enum(EnumMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "MyEnum".to_string(),
            shape: EnumShape::Enum,
            remote: false,
            variants: vec![VariantMetadata {
                orig_name: None,
                name: "WithOptional".to_string(),
                discr: None,
                fields: vec![FieldMetadata {
                    orig_name: None,
                    name: "value".to_string(),
                    ty: Type::Optional {
                        inner_type: Box::new(Type::String),
                    },
                    default: None,
                    docstring: None,
                }],
                docstring: None,
            }],
            discr_type: None,
            non_exhaustive: false,
            docstring: None,
        }));
        group.add_item(Metadata::Func(FnMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "get_enum".to_string(),
            is_async: false,
            inputs: vec![],
            return_type: Some(Type::Enum {
                module_path: "test".to_string(),
                name: "MyEnum".to_string(),
            }),
            throws: None,
            checksum: None,
            docstring: None,
        }));
        let ci = ComponentInterface::from_metadata(group).unwrap();
        let bindings = generate_bindings(&nullness_config(), &ci).unwrap();
        assert!(
            bindings.contains("java.lang.@org.jspecify.annotations.Nullable String value"),
            "enum variant optional field should have @Nullable on the field declaration:\n{}",
            bindings
                .lines()
                .filter(|l| l.contains("value"))
                .collect::<Vec<_>>()
                .join("\n")
        );
    }

    #[test]
    fn nullness_error_variant_with_optional_field() {
        let mut group = test_group();
        group.add_item(Metadata::Enum(EnumMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "MyError".to_string(),
            shape: EnumShape::Error { flat: false },
            remote: false,
            variants: vec![VariantMetadata {
                orig_name: None,
                name: "BadInput".to_string(),
                discr: None,
                fields: vec![FieldMetadata {
                    orig_name: None,
                    name: "detail".to_string(),
                    ty: Type::Optional {
                        inner_type: Box::new(Type::String),
                    },
                    default: None,
                    docstring: None,
                }],
                docstring: None,
            }],
            discr_type: None,
            non_exhaustive: false,
            docstring: None,
        }));
        group.add_item(Metadata::Func(FnMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "do_stuff".to_string(),
            is_async: false,
            inputs: vec![],
            return_type: None,
            throws: Some(Type::Enum {
                module_path: "test".to_string(),
                name: "MyError".to_string(),
            }),
            checksum: None,
            docstring: None,
        }));
        let ci = ComponentInterface::from_metadata(group).unwrap();
        let bindings = generate_bindings(&nullness_config(), &ci).unwrap();
        assert!(
            bindings.contains("java.lang.@org.jspecify.annotations.Nullable String detail"),
            "error variant optional field should have @Nullable on the field declaration:\n{}",
            bindings
                .lines()
                .filter(|l| l.contains("detail"))
                .collect::<Vec<_>>()
                .join("\n")
        );
    }

    #[test]
    fn nullness_async_function_with_optional_return() {
        let mut group = test_group();
        group.add_item(Metadata::Func(FnMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "fetch".to_string(),
            is_async: true,
            inputs: vec![],
            return_type: Some(Type::Optional {
                inner_type: Box::new(Type::String),
            }),
            throws: None,
            checksum: None,
            docstring: None,
        }));
        let ci = ComponentInterface::from_metadata(group).unwrap();
        let bindings = generate_bindings(&nullness_config(), &ci).unwrap();
        assert!(
            bindings
                .contains("CompletableFuture<java.lang.@org.jspecify.annotations.Nullable String>"),
            "async optional return should be CompletableFuture<@Nullable String>:\n{}",
            bindings
                .lines()
                .filter(|l| l.contains("fetch"))
                .collect::<Vec<_>>()
                .join("\n")
        );
    }

    #[test]
    fn nullness_non_optional_types_never_nullable() {
        let mut group = test_group();
        group.add_item(Metadata::Func(FnMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "identity".to_string(),
            is_async: false,
            inputs: vec![
                FnParamMetadata {
                    name: "s".to_string(),
                    ty: Type::String,
                    by_ref: false,
                    optional: false,
                    default: None,
                },
                FnParamMetadata {
                    name: "i".to_string(),
                    ty: Type::Int32,
                    by_ref: false,
                    optional: false,
                    default: None,
                },
                FnParamMetadata {
                    name: "b".to_string(),
                    ty: Type::Boolean,
                    by_ref: false,
                    optional: false,
                    default: None,
                },
            ],
            return_type: Some(Type::String),
            throws: None,
            checksum: None,
            docstring: None,
        }));
        let ci = ComponentInterface::from_metadata(group).unwrap();
        let bindings = generate_bindings(&nullness_config(), &ci).unwrap();
        assert!(
            !bindings.contains("@org.jspecify.annotations.Nullable"),
            "non-optional types should never have @Nullable"
        );
    }

    #[test]
    fn nullness_nested_optional_in_map_value() {
        let mut group = test_group();
        group.add_item(Metadata::Func(FnMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "process_map".to_string(),
            is_async: false,
            inputs: vec![FnParamMetadata {
                name: "data".to_string(),
                ty: Type::Map {
                    key_type: Box::new(Type::String),
                    value_type: Box::new(Type::Optional {
                        inner_type: Box::new(Type::Int32),
                    }),
                },
                by_ref: false,
                optional: false,
                default: None,
            }],
            return_type: None,
            throws: None,
            checksum: None,
            docstring: None,
        }));
        let ci = ComponentInterface::from_metadata(group).unwrap();
        let bindings = generate_bindings(&nullness_config(), &ci).unwrap();
        assert!(
            bindings.contains("java.util.Map<java.lang.String, java.lang.@org.jspecify.annotations.Nullable Integer>"),
            "map with optional value should have @Nullable on value type:\n{}",
            bindings.lines().filter(|l| l.contains("processMap")).collect::<Vec<_>>().join("\n")
        );
    }

    #[test]
    fn nullness_nested_optional_in_list() {
        let mut group = test_group();
        group.add_item(Metadata::Func(FnMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            name: "process_list".to_string(),
            is_async: false,
            inputs: vec![FnParamMetadata {
                name: "data".to_string(),
                ty: Type::Sequence {
                    inner_type: Box::new(Type::Optional {
                        inner_type: Box::new(Type::String),
                    }),
                },
                by_ref: false,
                optional: false,
                default: None,
            }],
            return_type: None,
            throws: None,
            checksum: None,
            docstring: None,
        }));
        let ci = ComponentInterface::from_metadata(group).unwrap();
        let bindings = generate_bindings(&nullness_config(), &ci).unwrap();
        assert!(
            bindings
                .contains("java.util.List<java.lang.@org.jspecify.annotations.Nullable String>"),
            "list with optional element should have @Nullable on element type:\n{}",
            bindings
                .lines()
                .filter(|l| l.contains("processList"))
                .collect::<Vec<_>>()
                .join("\n")
        );
    }

    #[test]
    fn borrowed_bytes_on_a_callback_method_is_rejected() {
        // Without this the vtable carries a ForeignBytes that Java has no way to lift, and the
        // generated bindings read a pointer they never owned.
        let mut group = MetadataGroup {
            namespace: NamespaceMetadata {
                crate_name: "test".to_string(),
                name: "test".to_string(),
            },
            namespace_docstring: None,
            items: Default::default(),
        };
        group.add_item(Metadata::CallbackInterface(CallbackInterfaceMetadata {
            module_path: "test".to_string(),
            name: "Sink".to_string(),
            docstring: None,
        }));
        group.add_item(Metadata::TraitMethod(TraitMethodMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            trait_name: "Sink".to_string(),
            index: 0,
            name: "write".to_string(),
            is_async: false,
            inputs: vec![FnParamMetadata {
                name: "data".to_string(),
                ty: Type::Bytes,
                by_ref: true,
                optional: false,
                default: None,
            }],
            return_type: None,
            throws: None,
            takes_self_by_arc: false,
            checksum: None,
            docstring: None,
        }));

        let mut ci = ComponentInterface::from_metadata(group).unwrap();
        ci.derive_ffi_funcs().unwrap();

        let err = generate_bindings(&Config::default(), &ci)
            .expect_err("borrowed bytes on a callback method should not generate");
        let msg = err.to_string();
        assert!(msg.contains("Sink.write"), "should name the method: {msg}");
        assert!(msg.contains("data"), "should name the argument: {msg}");
    }

    #[test]
    fn callback_interface_helpers_use_class_style_names() {
        let mut group = MetadataGroup {
            namespace: NamespaceMetadata {
                crate_name: "test".to_string(),
                name: "test".to_string(),
            },
            namespace_docstring: None,
            items: Default::default(),
        };
        group.add_item(Metadata::CallbackInterface(CallbackInterfaceMetadata {
            module_path: "test".to_string(),
            name: "Histogram".to_string(),
            docstring: None,
        }));
        group.add_item(Metadata::TraitMethod(TraitMethodMetadata {
            orig_name: None,
            module_path: "test".to_string(),
            trait_name: "Histogram".to_string(),
            index: 0,
            name: "record".to_string(),
            is_async: false,
            inputs: vec![FnParamMetadata {
                name: "value".to_string(),
                ty: Type::Float64,
                by_ref: false,
                optional: false,
                default: None,
            }],
            return_type: None,
            throws: None,
            takes_self_by_arc: false,
            checksum: None,
            docstring: None,
        }));

        let mut ci = ComponentInterface::from_metadata(group).unwrap();
        ci.derive_ffi_funcs().unwrap();

        let bindings = generate_bindings(&Config::default(), &ci).unwrap();

        assert!(
            bindings.contains("public void record(double value);"),
            "expected callback interface API to preserve the Rust method name:\n{}",
            bindings
                .lines()
                .filter(|l| l.contains("double value"))
                .collect::<Vec<_>>()
                .join("\n")
        );
        assert!(
            bindings.contains("public static final class RecordCallback implements UniffiCallbackInterfaceHistogramMethod0.Fn"),
            "expected callback helper class to use a Java class-style name:\n{}",
            bindings
                .lines()
                .filter(|l| l.contains("implements UniffiCallbackInterfaceHistogramMethod0.Fn"))
                .collect::<Vec<_>>()
                .join("\n")
        );
        assert!(
            bindings.contains("RecordCallback.INSTANCE"),
            "expected generated callback helper references to use the renamed helper class:\n{}",
            bindings
                .lines()
                .filter(|l| l.contains(".INSTANCE"))
                .collect::<Vec<_>>()
                .join("\n")
        );
        assert!(
            !bindings.contains("public static class record implements"),
            "unexpected lowercase helper class leaked into generated bindings:\n{}",
            bindings
                .lines()
                .filter(|l| l.contains("class record"))
                .collect::<Vec<_>>()
                .join("\n")
        );
    }
}