prebindgen-jni 0.5.0

JNI / Kotlin binding generator for prebindgen
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
use prebindgen_registry::{Conversions, RegistryBuilder};

use super::*;

/// Two fns returning the same type under different output decompositions:
/// the type-level `expand_return!` default and a per-fn `.return_expand(...)`
/// inline field list. Each gets its own builder interface.
#[test]
fn inline_output_gets_own_builder() {
    let loc = myflat_loc();
    let fns: &[&str] = &[
        "pub fn z_thing_name(t: &ZThing) -> String { unimplemented!() }",
        "pub fn z_thing_size(t: &ZThing) -> i64 { unimplemented!() }",
        "pub fn z_make_a() -> ZThing { unimplemented!() }",
        "pub fn z_make_b() -> ZThing { unimplemented!() }",
    ];
    let items: Vec<(syn::Item, SourceLocation)> = fns
        .iter()
        .map(|src| {
            let f: syn::ItemFn = syn::parse_str(src).expect("parse fn");
            (syn::Item::Fn(f), loc.clone())
        })
        .collect();
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");

    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("thing")
                .class(
                    crate::ptr_class!(ZThing)
                        .method(prebindgen_registry::fun!(z_thing_name).name("name"))
                        .method(prebindgen_registry::fun!(z_thing_size).name("size")),
                )
                .fun(prebindgen_registry::fun!(z_make_a))
                // Per-fn inline fields: name + size + name again (different shape). The
                // third field reuses the `z_thing_name` accessor but must carry a
                // distinct (literal) leaf name — duplicate names are a hard error.
                .fun(
                    prebindgen_registry::fun!(z_make_b).expand_return(
                        prebindgen_registry::expand_return!(ZThing)
                            .field(prebindgen_registry::fun!(z_thing_name).name("name"))
                            .field(prebindgen_registry::fun!(z_thing_size).name("size"))
                            .field(prebindgen_registry::fun!(z_thing_name).name("name2")),
                    ),
                ),
        )
        // Default output: name + size (2 leaves ⇒ builder callback). The
        // `name` field inherits its Kotlin name from the class member; `size`
        // sets it explicitly — both paths resolve to the member-equal names.
        .expand(
            prebindgen_registry::expand_return!(ZThing)
                .field(prebindgen_registry::fun!(z_thing_name))
                .field(prebindgen_registry::fun!(z_thing_size).name("size")),
        );

    let dir = unique_test_dir("jnigen_inline_out");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let gen = jni.build_with(registry).expect("resolve");
    let rust_path = gen.write_rust(dir.join("gen.rs")).expect("write_rust");
    let rust = std::fs::read_to_string(&rust_path).unwrap();
    let rc: String = rust.split_whitespace().collect();

    // Each extern names its own builder interface: the canonical
    // `ZThingBuilder` for z_make_a, the per-fn `ZThingZMakeBBuilder`.
    assert!(rc.contains("io/test/jni/thing/ZThingBuilder"), "{rust}");
    assert!(
        rc.contains("io/test/jni/thing/ZThingZMakeBBuilder"),
        "{rust}"
    );

    let kdir = dir.join("kotlin");
    let paths = gen.write_kotlin(&kdir).expect("write_kotlin");
    let all: String = paths
        .iter()
        .filter_map(|p| std::fs::read_to_string(p).ok())
        .collect::<Vec<_>>()
        .join("\n")
        .split_whitespace()
        .collect();
    // Canonical builder: (name, size); inline builder: (name, size, name2).
    assert!(
        all.contains("funinterfaceZThingBuilder<outR>{publicfunrun(name:String,size:Long):R"),
        "{all}"
    );
    assert!(
        all.contains(
            "funinterfaceZThingZMakeBBuilder<outR>{publicfunrun(name:String,size:Long,name2:String):R"
        ),
        "{all}"
    );
    // Wrappers take their own builder types.
    assert!(all.contains("build:ZThingBuilder<R>"), "{all}");
    assert!(all.contains("build:ZThingZMakeBBuilder<R>"), "{all}");
}

/// Domain-error decomposition is the OUTPUT decomposition (issue #45 split off
/// the binding channel, so there is no leading `je`): the same record kinds
/// work — an identity record (the error itself as an owned handle), plain
/// accessors, and accessors nested through `Option` (spliced child
/// decomposition, nullable leaves). The ze params are typed exactly like a
/// builder's; a binding/system failure goes to the separate `onBindingError`
/// (`JniErrorHandler`) channel, so there are no fabricated defaults.
#[test]
fn error_unwrap_universal_records() {
    let loc = myflat_loc();
    let fns: &[&str] = &[
        "pub fn z_err_message(e: &ZErr) -> String { unimplemented!() }",
        "pub fn z_err_detail(e: &ZErr) -> Option<&ZDetail> { unimplemented!() }",
        "pub fn z_detail_code(d: &ZDetail) -> i32 { unimplemented!() }",
        "pub fn z_fallible() -> Result<i64, ZErr> { unimplemented!() }",
    ];
    let items: Vec<(syn::Item, SourceLocation)> = fns
        .iter()
        .map(|src| {
            let f: syn::ItemFn = syn::parse_str(src).expect("parse fn");
            (syn::Item::Fn(f), loc.clone())
        })
        .collect();
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");

    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("errors")
                .class(
                    crate::ptr_class!(ZDetail)
                        .method(prebindgen_registry::fun!(z_detail_code).name("code")),
                )
                .class(
                    crate::ptr_class!(ZErr)
                        .method(prebindgen_registry::fun!(z_err_message).name("message"))
                        .method(prebindgen_registry::fun!(z_err_detail).name("detail")),
                )
                .fun(prebindgen_registry::fun!(z_fallible)),
        )
        .expand(
            prebindgen_registry::expand_return!(ZDetail)
                .field(prebindgen_registry::fun!(z_detail_code)),
        )
        // Canonical error decomposition: the owned error handle itself, its
        // message, and the Option-nested detail spliced to its code leaf.
        // Field names inherit from the class members.
        .expand(
            prebindgen_registry::expand_return!(ZErr)
                .field_self()
                .field(prebindgen_registry::fun!(z_err_message))
                .field(prebindgen_registry::fun!(z_err_detail)),
        );

    let dir = unique_test_dir("jnigen_err_universal");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let gen = jni.build_with(registry).expect("resolve");
    let rust_path = gen.write_rust(dir.join("gen.rs")).expect("write_rust");
    let rust = std::fs::read_to_string(&rust_path).unwrap();
    let rc: String = rust.split_whitespace().collect();

    // Domain handler descriptor (`__DSINK_DESCR`): typed handle jlong, non-null
    // String, BOXED nullable Integer for the Option-nested code — exactly the
    // builder typing, with NO leading `je` String (that is the binding channel).
    assert!(
        rc.contains("\"(JLjava/lang/String;Ljava/lang/Integer;)Ljava/lang/Object;\""),
        "{rust}"
    );
    // Binding channel descriptor (`__SINK_DESCR`): the base `JniErrorHandler`.
    assert!(
        rc.contains("\"(Ljava/lang/String;)Ljava/lang/Object;\""),
        "{rust}"
    );
    // Domain-error arm: the SAME shared leaf encoder — owned identity moves
    // the error into a boxed handle, the nested Option accessor unwraps via
    // a match — delivered through `signal_domain_error` (no `je`, no defaults).
    assert!(rc.contains("std::boxed::Box::new(__de)"), "{rust}");
    assert!(rc.contains("matchmyflat::z_err_detail(&__de)"), "{rust}");
    assert!(rc.contains("signal_domain_error("), "{rust}");
    // No fabricated-defaults machinery — the binding channel carries only a
    // message string, so there is no `__ze_defaults` closure.
    assert!(!rc.contains("__ze_defaults"), "{rust}");

    let kdir = dir.join("kotlin");
    let paths = gen.write_kotlin(&kdir).expect("write_kotlin");
    let all: String = paths
        .iter()
        .filter_map(|p| std::fs::read_to_string(p).ok())
        .collect::<Vec<_>>()
        .join("\n")
        .split_whitespace()
        .collect();
    // Builder-typed DOMAIN handler interface — no leading `je` (the binding
    // channel is the separate `JniErrorHandler`).
    assert!(
        all.contains(
            "funinterfaceZErrHandler<outR>{publicfunrun(handle:ZErr,message:String,detail__code:Int?):R"
        ),
        "{all}"
    );
    // Raw twin carries the jlong handle; the wrapper captures raw and wraps
    // on redispatch.
    assert!(
        all.contains(
            "funinterfaceZErrHandlerRaw<outR>{publicfunrun(handle:Long,message:String,detail__code:Int?):R"
        ),
        "{all}"
    );
    // The fallible wrapper takes BOTH channels; the domain redispatch wraps the
    // captured leaves (no `je`), the binding one forwards its single message.
    assert!(
        all.contains("returnonError.run(ZErr(__dcap.ze0!!),__dcap.ze1!!,__dcap.ze2)"),
        "{all}"
    );
    assert!(
        all.contains("if(__bcap.failed)returnonBindingError.run(__bcap.ze0)"),
        "{all}"
    );
    // Zero-alloc thread-local capture holders for BOTH channels (no per-call SAM
    // lambda / Ref-boxed vars); the wrapper uses acquire() on each.
    assert!(
        all.contains("internalclassZErrHandlerRawCapture:ZErrHandlerRaw<Unit>"),
        "{all}"
    );
    assert!(
        all.contains("val__dcap=ZErrHandlerRawCapture.acquire()"),
        "{all}"
    );
    assert!(
        all.contains("val__bcap=JniErrorHandlerCapture.acquire()"),
        "{all}"
    );
    assert!(all.contains("ThreadLocal.withInitial"), "{all}");
    // Wrapper: nullable capture slots, `!!` redispatch for the non-null ze,
    // pass-through for the nullable one — NO `?:` default coalescing.
    assert!(!all.contains("?:\"\""), "{all}");
}

/// `.method(f)` binds the `&Class` receiver to `this` (dropped from the
/// signature, its handle locked) while keeping the non-receiver params; the
/// fn delegates to the same `JNINative` extern. `.constructor(f)` emits a
/// companion-object factory returning the class. Per-fn
/// `.expand_return(...field_self()...)` emits the handle leaf.
#[test]
fn method_constructor_and_inline_field_self() {
    let loc = myflat_loc();
    let fns: &[&str] = &[
        "pub fn z_thing_name(t: &ZThing) -> String { unimplemented!() }",
        "pub fn z_thing_rename(t: &ZThing, name: String) -> bool { unimplemented!() }",
        "pub fn z_thing_make(name: String) -> ZThing { unimplemented!() }",
        "pub fn z_get() -> ZThing { unimplemented!() }",
    ];
    let items: Vec<(syn::Item, SourceLocation)> = fns
        .iter()
        .map(|src| {
            let f: syn::ItemFn = syn::parse_str(src).expect("parse fn");
            (syn::Item::Fn(f), loc.clone())
        })
        .collect();
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");

    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("thing")
                .class(
                    crate::ptr_class!(ZThing)
                        .method(prebindgen_registry::fun!(z_thing_name).name("name"))
                        // A method with extra params: `&ZThing` receiver + a `name: String` param.
                        .method(prebindgen_registry::fun!(z_thing_rename).name("rename"))
                        // A constructor: factory returning ZThing.
                        .constructor(prebindgen_registry::fun!(z_thing_make).name("make")),
                )
                // A free fn whose per-fn inline output decomposes to (handle, name).
                .fun(
                    prebindgen_registry::fun!(z_get).expand_return(
                        prebindgen_registry::expand_return!(ZThing)
                            .field_self()
                            .field(prebindgen_registry::fun!(z_thing_name).name("name")),
                    ),
                ),
        );

    let dir = unique_test_dir("jnigen_method_ctor");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let gen = jni.build_with(registry).expect("resolve");
    gen.write_rust(dir.join("gen.rs")).expect("write_rust");
    let kdir = dir.join("kotlin");
    let paths = gen.write_kotlin(&kdir).expect("write_kotlin");
    let all: String = paths
        .iter()
        .filter_map(|p| std::fs::read_to_string(p).ok())
        .collect::<Vec<_>>()
        .join("\n");
    let flat: String = all.split_whitespace().collect();

    // The method binds `this` and keeps the non-receiver `name` param (no `t`).
    assert!(flat.contains("publicfunrename(name:String"), "{all}");
    // The receiver is locked under `this`.
    assert!(all.contains("withSortedHandleLocks(this)"), "{all}");
    // The constructor is a companion-object factory returning ZThing.
    assert!(flat.contains("publiccompanionobject"), "{all}");
    assert!(flat.contains("publicfunmake(name:String"), "{all}");
    // Per-fn inline output: `z_get` decomposes to (handle, name) — a 2-leaf
    // builder (`handle: ZThing, name: String`) from the inline field list.
    assert!(
        flat.contains("publicfunrun(handle:ZThing,name:String)"),
        "{all}"
    );
}

/// A **rust-side-only** error type: `expand_return!` with NO class
/// declaration. The `Result<_, ZErr>` error channel decomposes the error into
/// its fields (here just the message), the `ZErrHandler` interface lands in
/// the BASE package (no type package exists), and no Kotlin class / `freePtr`
/// is emitted for `ZErr` — the value lives and dies in Rust.
#[test]
fn rust_side_only_error_type() {
    let loc = myflat_loc();
    let fns: &[&str] = &[
        "pub fn z_err_message(e: &ZErr) -> String { unimplemented!() }",
        "pub fn z_fallible() -> Result<i64, ZErr> { unimplemented!() }",
    ];
    let items: Vec<(syn::Item, SourceLocation)> = fns
        .iter()
        .map(|src| {
            let f: syn::ItemFn = syn::parse_str(src).expect("parse fn");
            (syn::Item::Fn(f), loc.clone())
        })
        .collect();
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");

    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(crate::package!("ops").fun(prebindgen_registry::fun!(z_fallible)))
        // No class declaration for ZErr anywhere — rust-side-only. The field
        // name is explicit (no class member to inherit from).
        .expand(
            prebindgen_registry::expand_return!(ZErr)
                .field(prebindgen_registry::fun!(z_err_message).name("message")),
        );

    let dir = unique_test_dir("jnigen_rust_side_only_err");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let gen = jni.build_with(registry).expect("resolve");
    let rust_path = gen.write_rust(dir.join("gen.rs")).expect("write_rust");
    let rust = std::fs::read_to_string(&rust_path).unwrap();
    let rc: String = rust.split_whitespace().collect();

    // The error decomposition calls the accessor Rust-side...
    assert!(rc.contains("myflat::z_err_message(&__de)"), "{rust}");
    // ...and no freePtr destructor exists for ZErr (no opaque handle).
    assert!(!rc.contains("ZErr_1freePtr"), "{rust}");

    let kdir = dir.join("kotlin");
    let paths = gen.write_kotlin(&kdir).expect("write_kotlin");
    let all: String = paths
        .iter()
        .filter_map(|p| std::fs::read_to_string(p).ok())
        .collect::<Vec<_>>()
        .join("\n")
        .split_whitespace()
        .collect();
    // Domain handler in the BASE package with the decomposed message field (no
    // leading `je`); no ZErr class anywhere.
    assert!(
        all.contains("funinterfaceZErrHandler<outR>{publicfunrun(message:String):R"),
        "{all}"
    );
    assert!(!all.contains("classZErr("), "{all}");
    // The handler file belongs to the base package (io/test/jni.kt), not a
    // type package.
    let base_file: String = paths
        .iter()
        .filter(|p| p.ends_with("io/test/jni.kt"))
        .filter_map(|p| std::fs::read_to_string(p).ok())
        .collect::<Vec<_>>()
        .join("\n")
        .split_whitespace()
        .collect();
    assert!(base_file.contains("funinterfaceZErrHandler"), "{all}");
}

/// A **rust-side-only** input type: `expand_param!` with NO class
/// declaration. Every param of the type is built from the ctor's ingredients
/// (no selector — single variant); the type never surfaces in Kotlin.
#[test]
fn rust_side_only_input_type() {
    let loc = myflat_loc();
    let fns: &[&str] = &[
        "pub fn z_opts_new(retries: i32, verbose: bool) -> ZOpts { unimplemented!() }",
        "pub fn z_run(opts: ZOpts) -> i64 { unimplemented!() }",
    ];
    let items: Vec<(syn::Item, SourceLocation)> = fns
        .iter()
        .map(|src| {
            let f: syn::ItemFn = syn::parse_str(src).expect("parse fn");
            (syn::Item::Fn(f), loc.clone())
        })
        .collect();
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");

    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(crate::package!("ops").fun(prebindgen_registry::fun!(z_run)))
        .expand(
            prebindgen_registry::expand_param!(ZOpts)
                .variant(prebindgen_registry::fun!(z_opts_new)),
        );

    let dir = unique_test_dir("jnigen_rust_side_only_in");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let gen = jni.build_with(registry).expect("resolve");
    let rust_path = gen.write_rust(dir.join("gen.rs")).expect("write_rust");
    let rust = std::fs::read_to_string(&rust_path).unwrap();
    let rc: String = rust.split_whitespace().collect();
    // The wrapper folds the ctor Rust-side.
    assert!(rc.contains("myflat::z_opts_new("), "{rust}");

    let kdir = dir.join("kotlin");
    let paths = gen.write_kotlin(&kdir).expect("write_kotlin");
    let all: String = paths
        .iter()
        .filter_map(|p| std::fs::read_to_string(p).ok())
        .collect::<Vec<_>>()
        .join("\n")
        .split_whitespace()
        .collect();
    // The Kotlin wrapper takes the ctor's flattened ingredients (prefixed by
    // the param name), not a ZOpts object; no ZOpts class exists.
    assert!(
        all.contains("funzRun(optsRetries:Int,optsVerbose:Boolean"),
        "{all}"
    );
    assert!(!all.contains("classZOpts("), "{all}");
}

/// `variant_self()` on a type with no class declaration is structurally
/// impossible (no Kotlin object to pass) — hard error at write time.
#[test]
#[should_panic(expected = "has no class declaration")]
fn rust_side_only_variant_self_rejected() {
    let loc = myflat_loc();
    let f: syn::ItemFn =
        syn::parse_str("pub fn z_run(opts: ZOpts) -> i64 { unimplemented!() }").unwrap();
    let registry =
        crate::test_util::reg_from_items(declare_referenced(vec![(syn::Item::Fn(f), loc)]))
            .expect("index items");
    let jni = JniGenBuilder::new()
        .package(crate::package!("ops").fun(prebindgen_registry::fun!(z_run)))
        .expand(prebindgen_registry::expand_param!(ZOpts).variant_self());
    let dir = unique_test_dir("jnigen_rso_self_in");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let _ = jni
        .build_with(registry)
        .and_then(|gen| gen.write_rust(dir.join("gen.rs")));
}

/// `field_self()` on a type with no class declaration is structurally
/// impossible (no Kotlin object to deliver) — hard error at write time.
#[test]
#[should_panic(expected = "has no class declaration")]
fn rust_side_only_field_self_rejected() {
    let loc = myflat_loc();
    let f: syn::ItemFn = syn::parse_str("pub fn z_make() -> ZThing { unimplemented!() }").unwrap();
    let registry =
        crate::test_util::reg_from_items(declare_referenced(vec![(syn::Item::Fn(f), loc)]))
            .expect("index items");
    let jni = JniGenBuilder::new()
        .package(crate::package!("ops").fun(prebindgen_registry::fun!(z_make)))
        .expand(prebindgen_registry::expand_return!(ZThing).field_self());
    let dir = unique_test_dir("jnigen_rso_self_out");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let _ = jni
        .build_with(registry)
        .and_then(|gen| gen.write_rust(dir.join("gen.rs")));
}

/// Per-fn `.expand_param(name, expand_param!(T))`: the decl's `T` must match
/// the named parameter's peeled type — a typo'd type is a hard error naming
/// both types.
#[test]
fn fn_expand_param_type_mismatch_rejected() {
    let loc = myflat_loc();
    let fns: &[&str] = &[
        "pub fn z_thing_make(name: String) -> ZThing { unimplemented!() }",
        "pub fn z_use(t: ZThing) -> i64 { unimplemented!() }",
    ];
    let items: Vec<(syn::Item, SourceLocation)> = fns
        .iter()
        .map(|src| {
            let f: syn::ItemFn = syn::parse_str(src).expect("parse fn");
            (syn::Item::Fn(f), loc.clone())
        })
        .collect();
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");
    let jni = JniGenBuilder::new().package(
        crate::package!("ops")
            .class(crate::ptr_class!(ZThing).constructor(prebindgen_registry::fun!(z_thing_make)))
            .class(crate::ptr_class!(ZOther))
            // Wrong type: the param `t` is a ZThing, not a ZOther.
            .fun(
                prebindgen_registry::fun!(z_use).expand_param(
                    "t",
                    prebindgen_registry::expand_param!(ZOther)
                        .variant(prebindgen_registry::fun!(z_thing_make)),
                ),
            ),
    );
    let dir = unique_test_dir("jnigen_fn_param_mismatch");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let err = jni
        .build_with(registry)
        .expect_err("type mismatch must fail");
    let msg = format!("{err}");
    assert!(msg.contains("ZOther") && msg.contains("ZThing"), "{msg}");
}

/// Per-fn `.expand_return(expand_return!(T))`: the decl's `T` must match the
/// function's peeled return type — a mismatch is a hard error.
#[test]
fn fn_expand_return_type_mismatch_rejected() {
    let loc = myflat_loc();
    let fns: &[&str] = &[
        "pub fn z_thing_name(t: &ZThing) -> String { unimplemented!() }",
        "pub fn z_make() -> ZThing { unimplemented!() }",
    ];
    let items: Vec<(syn::Item, SourceLocation)> = fns
        .iter()
        .map(|src| {
            let f: syn::ItemFn = syn::parse_str(src).expect("parse fn");
            (syn::Item::Fn(f), loc.clone())
        })
        .collect();
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");
    let jni = JniGenBuilder::new().package(
        crate::package!("ops")
            .class(
                crate::ptr_class!(ZThing)
                    .method(prebindgen_registry::fun!(z_thing_name).name("name")),
            )
            .class(crate::ptr_class!(ZOther))
            // Wrong type: z_make returns ZThing, not ZOther.
            .fun(
                prebindgen_registry::fun!(z_make)
                    .expand_return(prebindgen_registry::expand_return!(ZOther).field_self()),
            ),
    );
    let dir = unique_test_dir("jnigen_fn_return_mismatch");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let err = jni
        .build_with(registry)
        .expect_err("type mismatch must fail");
    let msg = format!("{err}");
    assert!(msg.contains("ZOther") && msg.contains("ZThing"), "{msg}");
}

/// `.expand_param` on a parameter name the function doesn't have is a hard
/// error (`UnknownParam`) — the second typo guard.
#[test]
fn fn_expand_param_unknown_param_rejected() {
    let loc = myflat_loc();
    let fns: &[&str] = &[
        "pub fn z_thing_make(name: String) -> ZThing { unimplemented!() }",
        "pub fn z_use(t: ZThing) -> i64 { unimplemented!() }",
    ];
    let items: Vec<(syn::Item, SourceLocation)> = fns
        .iter()
        .map(|src| {
            let f: syn::ItemFn = syn::parse_str(src).expect("parse fn");
            (syn::Item::Fn(f), loc.clone())
        })
        .collect();
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");
    let jni = JniGenBuilder::new().package(
        crate::package!("ops")
            .class(crate::ptr_class!(ZThing).constructor(prebindgen_registry::fun!(z_thing_make)))
            .fun(
                prebindgen_registry::fun!(z_use).expand_param(
                    "typo",
                    prebindgen_registry::expand_param!(ZThing)
                        .variant(prebindgen_registry::fun!(z_thing_make)),
                ),
            ),
    );
    let dir = unique_test_dir("jnigen_fn_param_unknown");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let err = jni
        .build_with(registry)
        .expect_err("unknown param must fail");
    assert!(format!("{err}").contains("typo"), "{err}");
}

/// Duplicate `.expand_return` on one function is a decl-time hard error —
/// the complete field set belongs in ONE decl.
#[test]
#[should_panic(expected = "already has a return expand override")]
fn fn_expand_return_duplicate_rejected() {
    let _ = prebindgen_registry::fun!(z_make)
        .expand_return(prebindgen_registry::expand_return!(ZThing).field_self())
        .expand_return(prebindgen_registry::expand_return!(ZThing).field_self());
}

/// A typo'd `fun!` inside a boundary decl is a HARD scan error (I7):
/// boundary-referenced fns ride the helper-function channel, and a declared
/// helper matching no `#[prebindgen]` item fails the scan — no silent
/// omission, no stale-ignore warning.
#[test]
fn typo_in_expand_decl_is_hard_error() {
    use prebindgen_registry::{ScanError, WriteRustError};
    let loc = myflat_loc();
    let f: syn::ItemFn =
        syn::parse_str("pub fn z_fallible() -> Result<i64, ZErr> { unimplemented!() }").unwrap();
    let registry =
        crate::test_util::reg_from_items(declare_referenced(vec![(syn::Item::Fn(f), loc)]))
            .expect("index items");
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(crate::package!("ops").fun(prebindgen_registry::fun!(z_fallible)))
        // `z_err_mesage` (sic) exists nowhere among the indexed items.
        .expand(
            prebindgen_registry::expand_return!(ZErr)
                .field(prebindgen_registry::fun!(z_err_mesage).name("message")),
        );
    let dir = unique_test_dir("jnigen_expand_typo_hard_error");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let err = jni
        .build_with(registry)
        .expect_err("typo'd expand accessor must fail the scan");
    match err {
        WriteRustError::Scan(ScanError::DeclaredNotFound { entries }) => {
            assert_eq!(
                entries,
                vec![("helper function", "z_err_mesage".to_string())]
            );
        }
        other => panic!("expected DeclaredNotFound, got {other:?}"),
    }
}

/// `.ignore(matching(…))` (C2/I4): one predicate acknowledges a whole
/// naming family — the matching undeclared items are skipped without
/// per-name lines, no extern is emitted for them, and the generation still
/// succeeds with only the declared surface. Also exercises the exact
/// type-ignore path (`.ignore(ty!(…))`).
#[test]
fn ignore_matching_acknowledges_naming_family() {
    let loc = myflat_loc();
    let fns: &[&str] = &[
        "pub fn z_len(v: i64) -> i64 { unimplemented!() }",
        "pub fn detail_const_a() -> i64 { unimplemented!() }",
        "pub fn detail_const_b() -> i64 { unimplemented!() }",
    ];
    let items: Vec<(syn::Item, SourceLocation)> = fns
        .iter()
        .map(|src| {
            let f: syn::ItemFn = syn::parse_str(src).expect("parse fn");
            (syn::Item::Fn(f), loc.clone())
        })
        .collect();
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(crate::package!("ops").fun(prebindgen_registry::fun!(z_len)))
        .ignore(crate::matching(|name| name.starts_with("detail_const_")))
        // The previously-untested type-ignore path: acknowledge a type by key.
        .ignore(prebindgen_registry::ty!(ZUnusedThing));
    // The predicate flows through the Prebindgen hook…
    {
        let preds = jni.decls.ignored_name_predicates();
        assert_eq!(preds.len(), 1);
        assert!(preds[0]("detail_const_a") && !preds[0]("z_len"));
        assert!(jni
            .decls
            .ignored_types()
            .contains(&TypeKey::parse("ZUnusedThing").expect("test type")));
    }
    // …and the full pipeline runs clean, emitting only the declared fn.
    let dir = unique_test_dir("jnigen_ignore_funs_where");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let gen = jni.build_with(registry).expect("resolve");
    let rust_path = gen.write_rust(dir.join("gen.rs")).expect("write_rust");
    let rust = std::fs::read_to_string(&rust_path).unwrap();
    assert!(rust.contains("Java_io_test_jni_JNINative_zLen"), "{rust}");
    assert!(!rust.contains("detailConstA"), "{rust}");
}

/// An ignore names a bare item — surface overrides are meaningless and
/// rejected at decl time.
#[test]
#[should_panic(expected = "expand overrides don't apply")]
fn ignore_fun_with_overrides_rejected() {
    let _ = crate::IgnoreDecl::from(prebindgen_registry::fun!(z_thing).name("thing"));
}

/// Same for constants: an ignore names a `#[prebindgen]` const, not a
/// value-sourced val.
#[test]
#[should_panic(expected = "value sources/.name() don't apply")]
fn ignore_const_with_source_rejected() {
    let _ = crate::IgnoreDecl::from(crate::constant!(X).expr(
        prebindgen_registry::ty!(i64),
        prebindgen_registry::expr!(1 + 1),
    ));
}

/// A `.variant()` arm only names its constructor — a `.name()` decoration
/// has no surface to land on and is rejected at decl time (was a silent
/// discard).
#[test]
#[should_panic(expected = ".name()/expand overrides don't apply")]
fn expand_param_variant_with_name_rejected() {
    let _ = prebindgen_registry::expand_param!(ZThing)
        .variant(prebindgen_registry::fun!(z_thing_new).name("thing"));
}

/// Same for expand overrides on a variant constructor.
#[test]
#[should_panic(expected = ".name()/expand overrides don't apply")]
fn expand_param_variant_with_expand_override_rejected() {
    let _ = prebindgen_registry::expand_param!(ZThing).variant(
        prebindgen_registry::fun!(z_thing_new)
            .expand_return(prebindgen_registry::expand_return!(ZName).field_self()),
    );
}

/// A `.field()` accessor honors `.name()` but nothing else — expand
/// overrides are rejected at decl time (was a silent discard).
#[test]
#[should_panic(expected = "only .name() is honored")]
fn expand_return_field_with_expand_override_rejected() {
    let _ = prebindgen_registry::expand_return!(ZThing).field(
        prebindgen_registry::fun!(z_thing_name).expand_param(
            "v",
            prebindgen_registry::expand_param!(ZName).variant_self(),
        ),
    );
}

/// Positive pin for the asymmetry: `.name()` on a `.field()` accessor is
/// the documented way to name the field — still accepted.
#[test]
fn expand_return_field_with_name_accepted() {
    let _ = prebindgen_registry::expand_return!(ZThing)
        .field(prebindgen_registry::fun!(z_thing_name).name("label"));
}

/// N5: a `.method()` whose target has no parameter of the class type
/// is a hard `AdapterInvariant` error at resolve — previously it silently
/// emitted a method that ignored `this`.
#[test]
fn method_without_receiver_rejected() {
    let loc = myflat_loc();
    let fns: &[&str] = &[
        "pub fn z_thing_free_standing(v: i64) -> i64 { unimplemented!() }",
        "pub fn z_make() -> ZThing { unimplemented!() }",
    ];
    let items: Vec<(syn::Item, SourceLocation)> = fns
        .iter()
        .map(|src| {
            let f: syn::ItemFn = syn::parse_str(src).expect("parse fn");
            (syn::Item::Fn(f), loc.clone())
        })
        .collect();
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("t").class(
                crate::ptr_class!(ZThing)
                    .method(prebindgen_registry::fun!(z_thing_free_standing))
                    .constructor(prebindgen_registry::fun!(z_make)),
            ),
        );
    let err = jni.build_with(registry).expect_err("receiver-less member");
    let msg = format!("{err}");
    assert!(
        msg.contains("method `z_thing_free_standing`") && msg.contains("`ZThing`"),
        "{msg}"
    );
}

/// N5: a `.constructor()` member must return `Self` or `Result<Self, E>`.
#[test]
fn constructor_with_wrong_return_rejected() {
    let loc = myflat_loc();
    let fns: &[&str] = &[
        "pub fn z_thing_len(t: &ZThing) -> i64 { unimplemented!() }",
        "pub fn z_make_number() -> i64 { unimplemented!() }",
    ];
    let items: Vec<(syn::Item, SourceLocation)> = fns
        .iter()
        .map(|src| {
            let f: syn::ItemFn = syn::parse_str(src).expect("parse fn");
            (syn::Item::Fn(f), loc.clone())
        })
        .collect();
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("t").class(
                crate::ptr_class!(ZThing)
                    .method(prebindgen_registry::fun!(z_thing_len))
                    .constructor(prebindgen_registry::fun!(z_make_number)),
            ),
        );
    let err = jni.build_with(registry).expect_err("wrong ctor return");
    let msg = format!("{err}");
    assert!(
        msg.contains("constructor `z_make_number`") && msg.contains("it returns `i64`"),
        "{msg}"
    );
}

/// Binding-local output field (`fun!(crate::…).sig(sig!(…)).name(…)`): the
/// accessor lives in the BINDING crate — the generated Rust calls it by its
/// declared path — and a self-typed `Option<&T>` return degrades to a
/// nullable typed handle leaf instead of a splice cycle: the
/// conditional-handle idiom ("deliver the handle only when the binding says
/// it's worth having").
#[test]
fn binding_local_field_conditional_handle() {
    let loc = myflat_loc();
    let fns: &[&str] = &[
        "pub fn z_enc_get_id(e: &ZEnc) -> i32 { unimplemented!() }",
        "pub fn z_enc_make() -> ZEnc { unimplemented!() }",
    ];
    let mut items: Vec<(syn::Item, SourceLocation)> = vec![(
        syn::Item::Struct(syn::parse_quote!(
            pub struct ZEnc {
                _p: u8,
            }
        )),
        loc.clone(),
    )];
    for src in fns {
        items.push((
            syn::Item::Fn(syn::parse_str(src).expect("parse fn")),
            loc.clone(),
        ));
    }
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("enc")
                .class(crate::ptr_class!(ZEnc).method(prebindgen_registry::fun!(z_enc_get_id)))
                .fun(prebindgen_registry::fun!(z_enc_make)),
        )
        .expand(
            prebindgen_registry::expand_return!(ZEnc)
                .field(prebindgen_registry::fun!(z_enc_get_id))
                .field(
                    prebindgen_registry::fun!(crate::enc_if_custom)
                        .sig(prebindgen_registry::sig!((e: &ZEnc) -> Option<&ZEnc>))
                        .name("handle"),
                ),
        );
    let dir = unique_test_dir("jnigen_local_field");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let gen = jni.build_with(registry).expect("resolve");
    let rust_path = gen.write_rust(dir.join("gen.rs")).expect("write_rust");
    let rust = std::fs::read_to_string(&rust_path).unwrap();
    let rc: String = rust.split_whitespace().collect();
    // The generated Rust calls the binding-local accessor by its DECLARED
    // path (the generated file compiles inside the binding crate).
    assert!(rc.contains("crate::enc_if_custom("), "{rust}");
    // The registry accessor stays source-qualified.
    assert!(rc.contains("myflat::z_enc_get_id("), "{rust}");
    // Wire shape: the conditional handle is an Option-unwrapped IDENTITY leaf
    // — present clones through the handle projection and BOXES the jlong
    // (matching the `Long?` slot of the raw interface), absent delivers JVM
    // null. A raw primitive `jvalue { j }` here would desync the descriptor.
    assert!(rc.contains("box_jlong"), "{rust}");
    assert!(
        rc.contains("Option::None=>jni::objects::JObject::null()"),
        "{rust}"
    );

    let paths = gen.write_kotlin(&dir.join("kotlin")).expect("write_kotlin");
    let raw = paths
        .iter()
        .filter_map(|p| std::fs::read_to_string(p).ok())
        .collect::<Vec<_>>()
        .join("\n");
    let all: String = raw.split_whitespace().collect();
    // Builder callback: the id leaf + the NULLABLE conditional handle leaf
    // (self-splice degraded to a plain converter leaf).
    assert!(all.contains("zEncGetId:Int,handle:ZEnc?"), "{raw}");
}

/// A binding-local callable must be crate-qualified: `fun!`'s ident arm
/// catches single segments (declaring a registry fn), and `new_local`
/// rejects a degenerate single-segment path outright.
#[test]
#[should_panic(expected = "crate::")]
fn binding_local_field_bare_path_rejected() {
    let _ = crate::FunctionDecl::new_local(syn::parse_quote!(enc_if_custom));
}

/// A binding-local fn name colliding with a `#[prebindgen]` item is a hard
/// error — the emitted call is `<prefix>::<name>`, so the name must denote
/// exactly the binding-local fn.
#[test]
fn binding_local_field_name_collision_rejected() {
    let loc = myflat_loc();
    let fns: &[&str] = &[
        "pub fn z_enc_get_id(e: &ZEnc) -> i32 { unimplemented!() }",
        "pub fn z_enc_make() -> ZEnc { unimplemented!() }",
    ];
    let mut items: Vec<(syn::Item, SourceLocation)> = vec![(
        syn::Item::Struct(syn::parse_quote!(
            pub struct ZEnc {
                _p: u8,
            }
        )),
        loc.clone(),
    )];
    for src in fns {
        items.push((
            syn::Item::Fn(syn::parse_str(src).expect("parse fn")),
            loc.clone(),
        ));
    }
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("enc")
                .class(crate::ptr_class!(ZEnc))
                .fun(prebindgen_registry::fun!(z_enc_make)),
        )
        .expand(
            // `z_enc_get_id` names a real #[prebindgen] fn — a binding-local
            // field may not shadow it.
            prebindgen_registry::expand_return!(ZEnc).field(
                prebindgen_registry::fun!(crate::z_enc_get_id)
                    .sig(prebindgen_registry::sig!((e: &ZEnc) -> i32))
                    .name("id"),
            ),
        );
    let err = jni
        .build_with(registry)
        .expect_err("collision must be rejected");
    let msg = format!("{err}");
    assert!(msg.contains("collides"), "{msg}");
}

/// A binding-local field spliced through a PARENT decomposition: the child's
/// conditional-handle leaf arrives prefixed (`enc__handle`) and nullable, and
/// the generated Rust composes the source accessor with the binding-local
/// one (`crate::enc_if_custom(myflat::z_msg_enc(&v))`).
#[test]
fn binding_local_field_splices_through_parent() {
    let loc = myflat_loc();
    let fns: &[&str] = &[
        "pub fn z_enc_get_id(e: &ZEnc) -> i32 { unimplemented!() }",
        "pub fn z_msg_enc(m: &ZMsg) -> &ZEnc { unimplemented!() }",
        "pub fn z_msg_len(m: &ZMsg) -> i64 { unimplemented!() }",
        "pub fn z_msg_make() -> ZMsg { unimplemented!() }",
    ];
    let mut items: Vec<(syn::Item, SourceLocation)> = vec![
        (
            syn::Item::Struct(syn::parse_quote!(
                pub struct ZEnc {
                    _p: u8,
                }
            )),
            loc.clone(),
        ),
        (
            syn::Item::Struct(syn::parse_quote!(
                pub struct ZMsg {
                    _p: u8,
                }
            )),
            loc.clone(),
        ),
    ];
    for src in fns {
        items.push((
            syn::Item::Fn(syn::parse_str(src).expect("parse fn")),
            loc.clone(),
        ));
    }
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("msg")
                .class(crate::ptr_class!(ZEnc).method(prebindgen_registry::fun!(z_enc_get_id)))
                .class(crate::ptr_class!(ZMsg))
                .fun(prebindgen_registry::fun!(z_msg_make)),
        )
        .expand(
            prebindgen_registry::expand_return!(ZEnc)
                .field(prebindgen_registry::fun!(z_enc_get_id))
                .field(
                    prebindgen_registry::fun!(crate::enc_if_custom)
                        .sig(prebindgen_registry::sig!((e: &ZEnc) -> Option<&ZEnc>))
                        .name("handle"),
                ),
        )
        .expand(
            prebindgen_registry::expand_return!(ZMsg)
                .field(prebindgen_registry::fun!(z_msg_len).name("len"))
                .field(prebindgen_registry::fun!(z_msg_enc).name("enc")),
        );
    let dir = unique_test_dir("jnigen_local_field_splice");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let gen = jni.build_with(registry).expect("resolve");
    let rust_path = gen.write_rust(dir.join("gen.rs")).expect("write_rust");
    let rust = std::fs::read_to_string(&rust_path).unwrap();
    let rc: String = rust.split_whitespace().collect();
    assert!(
        rc.contains("crate::enc_if_custom(myflat::z_msg_enc("),
        "{rust}"
    );

    let paths = gen.write_kotlin(&dir.join("kotlin")).expect("write_kotlin");
    let raw = paths
        .iter()
        .filter_map(|p| std::fs::read_to_string(p).ok())
        .collect::<Vec<_>>()
        .join("\n");
    let all: String = raw.split_whitespace().collect();
    // Spliced child leaves: prefixed id + prefixed NULLABLE handle.
    assert!(all.contains("enc__zEncGetId:Int"), "{raw}");
    assert!(all.contains("enc__handle:ZEnc?"), "{raw}");
}

/// Binding-local FUNCTIONS (`fun!(crate::f).sig(sig!(…))`): a fn defined in
/// the binding crate exported through the full `FunctionDecl` surface — free
/// package fn, instance method, companion constructor (also referenced by
/// ident as an `expand_param!` variant arm). After synthesis it IS a registry
/// fn: converters, receiver rule, name mangling, expansion defaults all apply;
/// the generated Rust calls it by its declared path.
#[test]
fn binding_local_functions_all_positions() {
    let loc = myflat_loc();
    let fns: &[&str] = &[
        "pub fn z_thing_len(t: &ZThing) -> i64 { unimplemented!() }",
        "pub fn z_use(primary: ZThing) -> bool { unimplemented!() }",
    ];
    let mut items: Vec<(syn::Item, SourceLocation)> = vec![(
        syn::Item::Struct(syn::parse_quote!(
            pub struct ZThing {
                _p: u8,
            }
        )),
        loc.clone(),
    )];
    for src in fns {
        items.push((
            syn::Item::Fn(syn::parse_str(src).expect("parse fn")),
            loc.clone(),
        ));
    }
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");
    let jni =
        JniGenBuilder::new()
            .set_package_prefix("io.test.jni")
            .package(
                crate::package!("t")
                    .class(
                        crate::ptr_class!(ZThing)
                            .method(prebindgen_registry::fun!(z_thing_len))
                            // binding-local INSTANCE METHOD (receiver &Self first)
                            .method(
                                prebindgen_registry::fun!(crate::z_thing_ratio)
                                    .sig(prebindgen_registry::sig!((t: &ZThing, scale: f64) -> f64)),
                            )
                            // binding-local COMPANION CONSTRUCTOR
                            .constructor(
                                prebindgen_registry::fun!(crate::z_thing_from_len)
                                    .sig(prebindgen_registry::sig!((len: i64) -> ZThing)),
                            ),
                    )
                    // binding-local FREE FUNCTION, fallible (Result -> onError)
                    .fun(prebindgen_registry::fun!(crate::z_thing_describe).sig(
                        prebindgen_registry::sig!((t: &ZThing, verbose: bool) -> Result<String, String>),
                    ))
                    .fun(prebindgen_registry::fun!(z_use)),
            )
            // The local constructor also serves as an expand_param! variant arm,
            // referenced by IDENT like any registry fn.
            .expand(
                prebindgen_registry::expand_param!(ZThing)
                    .variant(prebindgen_registry::fun!(z_thing_from_len))
                    .variant_self(),
            );
    let dir = unique_test_dir("jnigen_local_funs");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let gen = jni.build_with(registry).expect("resolve");
    let rust_path = gen.write_rust(dir.join("gen.rs")).expect("write_rust");
    let rust = std::fs::read_to_string(&rust_path).unwrap();
    let rc: String = rust.split_whitespace().collect();
    // Every binding-local call is qualified by its declared path; registry
    // fns keep their source qualification.
    assert!(rc.contains("crate::z_thing_ratio("), "{rust}");
    assert!(rc.contains("crate::z_thing_from_len("), "{rust}");
    assert!(rc.contains("crate::z_thing_describe("), "{rust}");
    assert!(rc.contains("myflat::z_thing_len("), "{rust}");

    let paths = gen.write_kotlin(&dir.join("kotlin")).expect("write_kotlin");
    let raw = paths
        .iter()
        .filter_map(|p| std::fs::read_to_string(p).ok())
        .collect::<Vec<_>>()
        .join("\n");
    let all: String = raw.split_whitespace().collect();
    // Method on the class (receiver dropped, stated param names surface).
    assert!(all.contains("funzThingRatio(scale:Double,"), "{raw}");
    // Companion factory returning the class.
    assert!(all.contains("funzThingFromLen(len:Long,"), "{raw}");
    // Free fn with the Result error routed to onError; its ZThing param
    // picked up the TYPE-LEVEL expand default (selector form) — expansion
    // defaults apply to binding-local fns exactly as to registry fns.
    assert!(all.contains("funzThingDescribe("), "{raw}");
    assert!(
        all.contains("tSel:Int,t0:Long?,t1:ZThing?,verbose:Boolean,"),
        "{raw}"
    );
    // The variant arm built from the local ctor: selector slot named after
    // its single param.
    assert!(all.contains("primarySel:Int"), "{raw}");
}

/// Naming rule for binding-local fns: `.name()` is NEVER obligatory — the
/// default derivation feeds the manglers the camel-cased LAST PATH SEGMENT
/// (`crate::sub::z_thing_ratio` → hook sees `zThingRatio`), with the same
/// package/class context as a registry fn, and the hook's output names the
/// Kotlin member. A local field without `.name()` defaults the same way.
#[test]
fn binding_local_fn_names_flow_through_manglers() {
    let loc = myflat_loc();
    let mut items: Vec<(syn::Item, SourceLocation)> = vec![(
        syn::Item::Struct(syn::parse_quote!(
            pub struct ZThing {
                _p: u8,
            }
        )),
        loc.clone(),
    )];
    for src in [
        "pub fn z_thing_make() -> ZThing { unimplemented!() }",
        // A PLAIN fn returning ZThing — the field decomposition applies here
        // (constructors are excluded from output decomposition by design).
        "pub fn z_thing_query() -> ZThing { unimplemented!() }",
    ] {
        items.push((syn::Item::Fn(syn::parse_str(src).unwrap()), loc.clone()));
    }
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        // Custom hooks: prefix every derived name — proof the hook RAN and
        // received the camel-cased last segment with its context.
        .set_fun_name_mangle(|pkg, name| {
            assert!(pkg.ends_with("t"), "fun hook package: {pkg}");
            format!("pkg_{name}")
        })
        .set_method_name_mangle(|_pkg, class, name| {
            if class == "ZThing" {
                format!("cls_{name}")
            } else {
                name.to_string()
            }
        })
        .package(
            crate::package!("t")
                .class(
                    crate::ptr_class!(ZThing)
                        .constructor(prebindgen_registry::fun!(z_thing_make))
                        // local METHOD, no .name(): hook sees `zThingRatio`.
                        .method(
                            prebindgen_registry::fun!(crate::sub::z_thing_ratio)
                                .sig(prebindgen_registry::sig!((t: &ZThing, scale: f64) -> f64)),
                        ),
                )
                // local FREE FN, no .name(): fun hook sees `zThingTag`.
                .fun(
                    prebindgen_registry::fun!(crate::sub::z_thing_tag)
                        .sig(prebindgen_registry::sig!((t: &ZThing) -> i64)),
                )
                .fun(prebindgen_registry::fun!(z_thing_query)),
        )
        // local FIELD, no .name(): defaults to camel(last segment). A second
        // field (the handle) keeps the decomposition on the builder path —
        // a single leaf would deliver by direct return, hiding the name.
        .expand(
            prebindgen_registry::expand_return!(ZThing)
                .field(
                    prebindgen_registry::fun!(crate::sub::z_thing_len)
                        .sig(prebindgen_registry::sig!((t: &ZThing) -> i64)),
                )
                .field_self(),
        );
    let raw = write_all(
        jni.build_with(registry).expect("resolve"),
        "jnigen_local_mangle",
    );
    let all: String = raw.split_whitespace().collect();
    // Method named by the class hook over the camel-cased last segment.
    assert!(all.contains("funcls_zThingRatio(scale:Double,"), "{raw}");
    // Free fn named by the package hook.
    assert!(all.contains("funpkg_zThingTag("), "{raw}");
    // Field leaf defaulted to camel(last segment) — builder param name.
    assert!(all.contains("zThingLen:Long"), "{raw}");
}

/// A path-built `fun!` without `.sig(…)` is a hard error at acceptance —
/// a path carries no signature to read.
#[test]
#[should_panic(expected = ".sig(sig!(")]
fn binding_local_fun_missing_sig_rejected() {
    let _ = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(crate::package!("t").fun(prebindgen_registry::fun!(crate::z_no_sig)));
}

/// `.sig(…)` on an ident-built (registry) `fun!` is a hard error — the
/// signature is read from the registry.
#[test]
#[should_panic(expected = "read from the")]
fn sig_on_registry_fun_rejected() {
    let _ =
        prebindgen_registry::fun!(z_thing_len).sig(prebindgen_registry::sig!((t: &ZThing) -> i64));
}

/// A binding-local fn name colliding with a `#[prebindgen]` item is a hard
/// resolve error — the emitted call would resolve the wrong fn.
#[test]
fn binding_local_fun_name_collision_rejected() {
    let loc = myflat_loc();
    let mut items: Vec<(syn::Item, SourceLocation)> = vec![(
        syn::Item::Struct(syn::parse_quote!(
            pub struct ZThing {
                _p: u8,
            }
        )),
        loc.clone(),
    )];
    items.push((
        syn::Item::Fn(
            syn::parse_str("pub fn z_thing_len(t: &ZThing) -> i64 { unimplemented!() }").unwrap(),
        ),
        loc.clone(),
    ));
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("t").class(crate::ptr_class!(ZThing)).fun(
                // shadows the #[prebindgen] fn of the same name
                prebindgen_registry::fun!(crate::z_thing_len)
                    .sig(prebindgen_registry::sig!((t: &ZThing) -> i64)),
            ),
        );
    let err = jni
        .build_with(registry)
        .expect_err("collision must be rejected");
    assert!(format!("{err}").contains("collides"), "{err}");
}

/// `.gc_managed()`: the typed handle extends `GcNativeHandle` (pointer in a
/// separate atomic cell), registers a Cleaner action capturing only the cell,
/// and every release path settles the once-only untagged→tagged CAS ticket —
/// `close()` frees eagerly, `take()` and by-value consumption void it, the GC
/// action frees only if it wins. A plain class keeps the field-backed
/// lifecycle; by-value consumption is routed through `markConsumed()` for
/// both.
#[test]
fn gc_managed_handle_lifecycle() {
    let loc = myflat_loc();
    let mut items: Vec<(syn::Item, SourceLocation)> = vec![
        (
            syn::Item::Struct(syn::parse_quote!(
                pub struct ZThing {
                    _p: u8,
                }
            )),
            loc.clone(),
        ),
        (
            syn::Item::Struct(syn::parse_quote!(
                pub struct ZOther {
                    _p: u8,
                }
            )),
            loc.clone(),
        ),
    ];
    let fns: &[&str] = &[
        "pub fn z_thing_new() -> ZThing { unimplemented!() }",
        "pub fn z_thing_use(t: ZThing) -> bool { unimplemented!() }",
        "pub fn z_other_new() -> ZOther { unimplemented!() }",
        "pub fn z_other_use(t: ZOther) -> bool { unimplemented!() }",
    ];
    for src in fns {
        items.push((
            syn::Item::Fn(syn::parse_str(src).expect("parse fn")),
            loc.clone(),
        ));
    }
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("t")
                .class(
                    crate::ptr_class!(ZThing)
                        .gc_managed()
                        .constructor(prebindgen_registry::fun!(z_thing_new)),
                )
                .class(
                    crate::ptr_class!(ZOther).constructor(prebindgen_registry::fun!(z_other_new)),
                )
                .fun(prebindgen_registry::fun!(z_thing_use))
                .fun(prebindgen_registry::fun!(z_other_use)),
        );
    let raw = write_all(
        jni.build_with(registry).expect("resolve"),
        "jnigen_gc_managed",
    );
    let all: String = raw.split_whitespace().collect();

    // Shared harness: cell-backed base, CAS helper, shared Cleaner, register fn.
    assert!(all.contains("abstractclassGcNativeHandle"), "{raw}");
    assert!(all.contains("internalfunreleaseCell"), "{raw}");
    assert!(all.contains("internalobjectNativeCleaner"), "{raw}");
    assert!(all.contains("internalfunregisterGcHandle"), "{raw}");

    // The gc class extends GcNativeHandle and self-registers via the cell.
    assert!(
        all.contains("classZThing(initialPtr:Long):GcNativeHandle(initialPtr)"),
        "{raw}"
    );
    assert!(
        all.contains("privateval__cleanable=registerGcHandle(this){freePtr(it)}"),
        "{raw}"
    );
    // close(): CAS ticket, eager free + eager deregistration.
    assert!(
        all.contains("valp=releaseCell(cell)if(p!=0L)freePtr(p)__cleanable?.clean()"),
        "{raw}"
    );
    // take(): ticket voided, ownership moves into the fresh wrapper.
    assert!(
        all.contains(
            "valp=releaseCell(cell)__cleanable?.clean()returnZThing(if(p!=0L)pelsecell.get())"
        ),
        "{raw}"
    );

    // The plain class keeps the field-backed lifecycle.
    assert!(
        all.contains("classZOther(initialPtr:Long):NativeHandle(initialPtr)"),
        "{raw}"
    );
    assert!(all.contains("ptr=por1L"), "{raw}");
    assert!(
        !all.contains("classZOther(initialPtr:Long):GcNativeHandle"),
        "{raw}"
    );

    // By-value consumption goes through markConsumed() for BOTH classes —
    // for the gc class that settles the ticket, for the plain one it is
    // exactly the old tag write.
    assert!(all.contains("t.markConsumed()"), "{raw}");
    assert!(!all.contains("t.ptr=t.ptror1L"), "{raw}");
}

/// #52 shared fixture: a `ZSummary` ptr class, its `(count, total)` builder, a
/// splittable 2-variant type-level `expand_param!`, and functions taking one or
/// two `ZSummary` params. `extra` fns are appended before indexing.
fn split_fixture(extra: &[&str]) -> RegistryBuilder<KotlinMeta> {
    let loc = myflat_loc();
    let base: &[&str] = &[
        "pub fn z_summary_new(count: i64, total: f64) -> ZSummary { unimplemented!() }",
        "pub fn z_store_expect(expected: ZSummary) -> bool { unimplemented!() }",
        "pub fn z_prefer(primary: ZSummary, fallback: ZSummary) -> i64 { unimplemented!() }",
    ];
    let mut items: Vec<(syn::Item, SourceLocation)> = vec![(
        syn::Item::Struct(syn::parse_quote!(
            pub struct ZSummary {
                _p: u8,
            }
        )),
        loc.clone(),
    )];
    for src in base.iter().chain(extra) {
        items.push((
            syn::Item::Fn(syn::parse_str(src).expect("parse fn")),
            loc.clone(),
        ));
    }
    crate::test_util::reg_from_items(declare_referenced(items)).expect("index items")
}

pub(super) fn write_all(gen: JniGen, tag: &str) -> String {
    let dir = unique_test_dir(tag);
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    gen.write_rust(dir.join("gen.rs")).expect("write_rust");
    let paths = gen.write_kotlin(&dir.join("kotlin")).expect("write_kotlin");
    paths
        .iter()
        .filter_map(|p| std::fs::read_to_string(p).ok())
        .collect::<Vec<_>>()
        .join("\n")
}

/// #52: `FunctionDecl::split_on_param` emits, alongside the retained selector
/// form, one idiomatic typed overload per variant — the build arm named after
/// the constructor's parameters, the `variant_self()` arm typed as the class —
/// each delegating to the selector wrapper.
#[test]
fn split_on_param_emits_typed_overloads() {
    let registry = split_fixture(&[]);
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("ops")
                .class(crate::ptr_class!(ZSummary))
                .fun(prebindgen_registry::fun!(z_store_expect).split_on_param("expected")),
        )
        .expand(
            prebindgen_registry::expand_param!(ZSummary)
                .variant(prebindgen_registry::fun!(z_summary_new))
                .variant_self(),
        );
    let raw = write_all(
        jni.build_with(registry).expect("resolve"),
        "jnigen_split_one",
    );
    let all: String = raw.split_whitespace().collect();
    assert!(all.contains("expectedSel:Int"), "{raw}"); // selector retained
    assert!(
        all.contains("funzStoreExpect(count:Long,total:Double,"),
        "{raw}"
    );
    assert!(all.contains("funzStoreExpect(expected:ZSummary,"), "{raw}");
    assert!(all.contains("zStoreExpect(0,count,total,null,"), "{raw}");
    assert!(all.contains("zStoreExpect(1,null,null,expected,"), "{raw}");
}

/// #52: two `.split_on_param` on one function emit the **cartesian product** of
/// the params' arms (2×2 = four overloads); build-arm params are prefixed with
/// their origin parameter name to stay unique.
#[test]
fn split_on_param_cartesian_product() {
    let registry = split_fixture(&[]);
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("ops")
                .class(crate::ptr_class!(ZSummary))
                .fun(
                    prebindgen_registry::fun!(z_prefer)
                        .split_on_param("primary")
                        .split_on_param("fallback"),
                ),
        )
        .expand(
            prebindgen_registry::expand_param!(ZSummary)
                .variant(prebindgen_registry::fun!(z_summary_new))
                .variant_self(),
        );
    let raw = write_all(
        jni.build_with(registry).expect("resolve"),
        "jnigen_split_prod",
    );
    let all: String = raw.split_whitespace().collect();
    // build / build
    assert!(
        all.contains(
            "funzPrefer(primaryCount:Long,primaryTotal:Double,fallbackCount:Long,fallbackTotal:Double,"
        ),
        "{raw}"
    );
    // build / handle, handle / build, handle / handle
    assert!(
        all.contains("funzPrefer(primaryCount:Long,primaryTotal:Double,fallback:ZSummary,"),
        "{raw}"
    );
    assert!(
        all.contains("funzPrefer(primary:ZSummary,fallbackCount:Long,fallbackTotal:Double,"),
        "{raw}"
    );
    assert!(
        all.contains("funzPrefer(primary:ZSummary,fallback:ZSummary,"),
        "{raw}"
    );
    // A product delegation fills BOTH selector blocks.
    assert!(
        all.contains(
            "zPrefer(0,primaryCount,primaryTotal,null,0,fallbackCount,fallbackTotal,null,"
        ),
        "{raw}"
    );
}

/// #87: a split parameter on a function whose return is **builder-delivered**
/// (decomposed `expand_return!` fields ⇒ generic `<R>` wrapper) keeps the
/// wrapper's generic declaration on every overload — including the full
/// cartesian product — instead of referencing an undeclared `R`.
#[test]
fn split_on_param_preserves_wrapper_generics() {
    let registry = split_fixture(&[
        "pub fn z_summary_count(s: &ZSummary) -> i64 { unimplemented!() }",
        "pub fn z_summary_total(s: &ZSummary) -> f64 { unimplemented!() }",
        "pub fn z_summarize(primary: ZSummary, fallback: ZSummary) -> ZSummary { unimplemented!() }",
    ]);
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("ops")
                .class(crate::ptr_class!(ZSummary))
                .fun(
                    prebindgen_registry::fun!(z_summarize)
                        .split_on_param("primary")
                        .split_on_param("fallback"),
                ),
        )
        .expand(
            prebindgen_registry::expand_param!(ZSummary)
                .variant(prebindgen_registry::fun!(z_summary_new))
                .variant_self(),
        )
        .expand(
            prebindgen_registry::expand_return!(ZSummary)
                .field(prebindgen_registry::fun!(z_summary_count))
                .field(prebindgen_registry::fun!(z_summary_total)),
        );
    let raw = write_all(
        jni.build_with(registry).expect("resolve"),
        "jnigen_split_generic",
    );
    let all: String = raw.split_whitespace().collect();
    // The selector wrapper is generic (builder-delivered return)…
    assert!(all.contains("fun<R>zSummarize(primarySel:Int"), "{raw}");
    // …and every cartesian overload re-declares `<R>`.
    assert!(
        all.contains(
            "fun<R>zSummarize(primaryCount:Long,primaryTotal:Double,fallbackCount:Long,fallbackTotal:Double,"
        ),
        "{raw}"
    );
    assert!(
        all.contains("fun<R>zSummarize(primaryCount:Long,primaryTotal:Double,fallback:ZSummary,"),
        "{raw}"
    );
    assert!(
        all.contains("fun<R>zSummarize(primary:ZSummary,fallbackCount:Long,fallbackTotal:Double,"),
        "{raw}"
    );
    assert!(
        all.contains("fun<R>zSummarize(primary:ZSummary,fallback:ZSummary,"),
        "{raw}"
    );
    // No wrapper form may reference `R` without declaring it (the only
    // non-generic `fun zSummarize` is the `external` JNINative extern).
    assert!(!all.contains("publicfunzSummarize("), "{raw}");
}

/// #52: a `.split_on_param` product whose two combinations erase to the same
/// JVM signature is a hard, per-function error. `from_one(Long)` /
/// `from_two(Long,Long)` on two params collide at (one,two) vs (two,one).
#[test]
#[should_panic(expected = "ambiguous")]
fn split_on_param_product_ambiguous_rejected() {
    let loc = myflat_loc();
    let srcs: &[&str] = &[
        "pub fn z_thing_one(a: i64) -> ZThing { unimplemented!() }",
        "pub fn z_thing_two(a: i64, b: i64) -> ZThing { unimplemented!() }",
        "pub fn z_combine(primary: ZThing, fallback: ZThing) -> bool { unimplemented!() }",
    ];
    let mut items: Vec<(syn::Item, SourceLocation)> = vec![(
        syn::Item::Struct(syn::parse_quote!(
            pub struct ZThing {
                _p: u8,
            }
        )),
        loc.clone(),
    )];
    for s in srcs {
        items.push((syn::Item::Fn(syn::parse_str(s).unwrap()), loc.clone()));
    }
    let registry = crate::test_util::reg_from_items(declare_referenced(items)).expect("index");
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("ops").class(crate::ptr_class!(ZThing)).fun(
                prebindgen_registry::fun!(z_combine)
                    .split_on_param("primary")
                    .split_on_param("fallback"),
            ),
        )
        .expand(
            prebindgen_registry::expand_param!(ZThing)
                .variant(prebindgen_registry::fun!(z_thing_one))
                .variant(prebindgen_registry::fun!(z_thing_two)),
        );
    let _ = write_all(
        jni.build_with(registry).expect("resolve"),
        "jnigen_split_ambig",
    );
}

/// #52 proactive: a multi-variant `expand_param!` whose arms share a JVM
/// signature is a hard error at the DECLARATION — no function need split it.
#[test]
#[should_panic(expected = "same JVM signature")]
fn split_declaration_colliding_variants_rejected() {
    let loc = myflat_loc();
    let srcs: &[&str] = &[
        "pub fn z_name_from_text(text: String) -> ZName { unimplemented!() }",
        "pub fn z_name_from_label(label: String) -> ZName { unimplemented!() }",
        "pub fn z_use_name(name: ZName) -> bool { unimplemented!() }",
    ];
    let mut items: Vec<(syn::Item, SourceLocation)> = vec![(
        syn::Item::Struct(syn::parse_quote!(
            pub struct ZName {
                _p: u8,
            }
        )),
        loc.clone(),
    )];
    for s in srcs {
        items.push((syn::Item::Fn(syn::parse_str(s).unwrap()), loc.clone()));
    }
    let registry = crate::test_util::reg_from_items(declare_referenced(items)).expect("index");
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("ops")
                .class(crate::ptr_class!(ZName))
                .fun(prebindgen_registry::fun!(z_use_name)), // NOT split — still errors
        )
        .expand(
            prebindgen_registry::expand_param!(ZName)
                .variant(prebindgen_registry::fun!(z_name_from_text))
                .variant(prebindgen_registry::fun!(z_name_from_label)),
        );
    let _ = write_all(
        jni.build_with(registry).expect("resolve"),
        "jnigen_split_decl",
    );
}

/// #90: the validation boundary is now in `resolve` — a colliding split
/// declaration (a Kotlin-side concern) fails `resolve` as a clean `Err`, so
/// no `JniGen` is produced and neither artifact can be written.
#[test]
fn split_declaration_collision_fails_resolve() {
    let loc = myflat_loc();
    let srcs: &[&str] = &[
        "pub fn z_name_from_text(text: String) -> ZName { unimplemented!() }",
        "pub fn z_name_from_label(label: String) -> ZName { unimplemented!() }",
        "pub fn z_use_name(name: ZName) -> bool { unimplemented!() }",
    ];
    let mut items: Vec<(syn::Item, SourceLocation)> = vec![(
        syn::Item::Struct(syn::parse_quote!(
            pub struct ZName {
                _p: u8,
            }
        )),
        loc.clone(),
    )];
    for s in srcs {
        items.push((syn::Item::Fn(syn::parse_str(s).unwrap()), loc.clone()));
    }
    let registry = crate::test_util::reg_from_items(declare_referenced(items)).expect("index");
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("ops")
                .class(crate::ptr_class!(ZName))
                .fun(prebindgen_registry::fun!(z_use_name)),
        )
        .expand(
            prebindgen_registry::expand_param!(ZName)
                .variant(prebindgen_registry::fun!(z_name_from_text))
                .variant(prebindgen_registry::fun!(z_name_from_label)),
        );
    let err = jni
        .build_with(registry)
        .expect_err("colliding split declaration must fail resolve");
    assert!(
        err.to_string().contains("same JVM signature"),
        "unexpected error: {err}"
    );
}

/// #52: `.no_split()` suppresses the proactive splittability check for a
/// genuinely non-splittable variant set (used only as the selector form).
#[test]
fn split_no_split_suppresses_check() {
    let loc = myflat_loc();
    let srcs: &[&str] = &[
        "pub fn z_name_from_text(text: String) -> ZName { unimplemented!() }",
        "pub fn z_name_from_label(label: String) -> ZName { unimplemented!() }",
        "pub fn z_use_name(name: ZName) -> bool { unimplemented!() }",
    ];
    let mut items: Vec<(syn::Item, SourceLocation)> = vec![(
        syn::Item::Struct(syn::parse_quote!(
            pub struct ZName {
                _p: u8,
            }
        )),
        loc.clone(),
    )];
    for s in srcs {
        items.push((syn::Item::Fn(syn::parse_str(s).unwrap()), loc.clone()));
    }
    let registry = crate::test_util::reg_from_items(declare_referenced(items)).expect("index");
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("ops")
                .class(crate::ptr_class!(ZName))
                .fun(prebindgen_registry::fun!(z_use_name)),
        )
        .expand(
            prebindgen_registry::expand_param!(ZName)
                .variant(prebindgen_registry::fun!(z_name_from_text))
                .variant(prebindgen_registry::fun!(z_name_from_label))
                .no_split(),
        );
    // No panic: the colliding variants are tolerated as selector-only.
    let raw = write_all(
        jni.build_with(registry).expect("resolve"),
        "jnigen_no_split",
    );
    let all: String = raw.split_whitespace().collect();
    assert!(all.contains("nameSel:Int"), "{raw}"); // selector form emitted
}

/// #52: `.split_on_param` naming a parameter that does not exist on the
/// function is a hard error (typo guard).
#[test]
#[should_panic(expected = "no parameter named")]
fn split_on_unknown_param_rejected() {
    let registry = split_fixture(&[]);
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("ops")
                .class(crate::ptr_class!(ZSummary))
                .fun(prebindgen_registry::fun!(z_store_expect).split_on_param("nope")),
        )
        .expand(
            prebindgen_registry::expand_param!(ZSummary)
                .variant(prebindgen_registry::fun!(z_summary_new))
                .variant_self(),
        );
    let _ = write_all(
        jni.build_with(registry).expect("resolve"),
        "jnigen_split_typo",
    );
}

/// Nullable-arm rule: `.split_on_param` on an `Option<T>` parameter emits
/// overloads for its **single-leaf** arms only — here the `variant_self()`
/// arm, typed nullable (`ZSummary?`) with `null` = absent, delegating a
/// conditional selector (`-1` when null). The multi-leaf `(count, total)`
/// build arm stays selector-only.
#[test]
fn split_on_option_param_emits_nullable_arm() {
    let registry =
        split_fixture(&["pub fn z_maybe(opt: Option<ZSummary>) -> bool { unimplemented!() }"]);
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("ops")
                .class(crate::ptr_class!(ZSummary))
                .fun(prebindgen_registry::fun!(z_maybe).split_on_param("opt")),
        )
        .expand(
            prebindgen_registry::expand_param!(ZSummary)
                .variant(prebindgen_registry::fun!(z_summary_new))
                .variant_self(),
        );
    let raw = write_all(
        jni.build_with(registry).expect("resolve"),
        "jnigen_split_opt",
    );
    let all: String = raw.split_whitespace().collect();
    // Selector form retained; single nullable overload for the identity arm.
    assert!(all.contains("optSel:Int"), "{raw}");
    assert!(all.contains("funzMaybe(opt:ZSummary?,"), "{raw}");
    assert!(
        all.contains("zMaybe(if(opt!=null)1else-1,null,null,opt,"),
        "{raw}"
    );
    // No overload for the multi-leaf build arm.
    assert!(!all.contains("funzMaybe(count:"), "{raw}");
}

/// Nullable-arm rule: an `Option<T>` parameter whose expansion has **no**
/// single-leaf arm (two multi-arg build arms, no identity) cannot be split —
/// hard error, keep the selector form.
#[test]
#[should_panic(expected = "none of its arms is a single leaf")]
fn split_on_option_param_without_single_leaf_arm_rejected() {
    let registry = split_fixture(&[
        "pub fn z_summary_scaled(units: String, factor: f64) -> ZSummary { unimplemented!() }",
        "pub fn z_maybe(opt: Option<ZSummary>) -> bool { unimplemented!() }",
    ]);
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("ops")
                .class(crate::ptr_class!(ZSummary))
                .fun(prebindgen_registry::fun!(z_maybe).split_on_param("opt")),
        )
        .expand(
            prebindgen_registry::expand_param!(ZSummary)
                .variant(prebindgen_registry::fun!(z_summary_new))
                .variant(prebindgen_registry::fun!(z_summary_scaled)),
        );
    let _ = write_all(
        jni.build_with(registry).expect("resolve"),
        "jnigen_split_opt_no_arm",
    );
}

/// Nullable-arm rule × cartesian product: a non-optional split param (all
/// arms) combines with an optional one (single-leaf arms only) — each combo
/// fills its own block, constant selector for the former, conditional for the
/// latter.
#[test]
fn split_on_param_optional_cartesian_with_plain() {
    let registry = split_fixture(&[
        "pub fn z_mixed(primary: ZSummary, fallback: Option<&ZSummary>) -> i64 { unimplemented!() }",
    ]);
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("ops")
                .class(crate::ptr_class!(ZSummary))
                .fun(
                    prebindgen_registry::fun!(z_mixed)
                        .split_on_param("primary")
                        .split_on_param("fallback"),
                ),
        )
        .expand(
            prebindgen_registry::expand_param!(ZSummary)
                .variant(prebindgen_registry::fun!(z_summary_new))
                .variant_self(),
        );
    let raw = write_all(
        jni.build_with(registry).expect("resolve"),
        "jnigen_split_opt_prod",
    );
    let all: String = raw.split_whitespace().collect();
    // 2 (primary arms) × 1 (fallback single-leaf arm) overloads.
    assert!(
        all.contains("funzMixed(primaryCount:Long,primaryTotal:Double,fallback:ZSummary?,"),
        "{raw}"
    );
    assert!(
        all.contains("funzMixed(primary:ZSummary,fallback:ZSummary?,"),
        "{raw}"
    );
    // Constant selector for the plain block, conditional for the optional one.
    assert!(
        all.contains(
            "zMixed(0,primaryCount,primaryTotal,null,if(fallback!=null)1else-1,null,null,fallback,"
        ),
        "{raw}"
    );
}

/// Optional combined-selector expansion: an `Option<&T>` param with a
/// build-from arm AND an identity arm crosses as a selector tuple whose
/// selector also encodes absence (`-1` = `None`). The ctor's own
/// `Option<String>` arg passes through un-double-wrapped, and the identity
/// arm is a nullable typed handle.
#[test]
fn optional_selector_dispatch_end_to_end() {
    let loc = myflat_loc();
    let items: Vec<(syn::Item, SourceLocation)> = vec![
        (
            syn::Item::Struct(syn::parse_quote!(
                pub struct ZEnc {
                    _p: u8,
                }
            )),
            loc.clone(),
        ),
        (
            syn::Item::Fn(syn::parse_quote!(
                pub fn z_enc_from_id(id: i32, schema: Option<String>) -> ZEnc {
                    unimplemented!()
                }
            )),
            loc.clone(),
        ),
        (
            syn::Item::Fn(syn::parse_quote!(
                pub fn z_put(encoding: Option<&ZEnc>) -> bool {
                    unimplemented!()
                }
            )),
            loc.clone(),
        ),
    ];
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("ops")
                .class(
                    crate::ptr_class!(ZEnc).constructor(prebindgen_registry::fun!(z_enc_from_id)),
                )
                .fun(prebindgen_registry::fun!(z_put)),
        )
        .expand(
            prebindgen_registry::expand_param!(ZEnc)
                .variant(prebindgen_registry::fun!(z_enc_from_id))
                .variant_self(),
        );
    let dir = unique_test_dir("jnigen_opt_selector");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let gen = jni.build_with(registry).expect("resolve");
    let rust_path = gen.write_rust(dir.join("gen.rs")).expect("write_rust");
    let rust = std::fs::read_to_string(&rust_path).unwrap();
    let rc: String = rust.split_whitespace().collect();
    // Rust side: the selector gates absence before the dispatch.
    assert!(rc.contains("<0"), "{rust}");
    assert!(rc.contains("Option::None"), "{rust}");
    assert!(rc.contains("z_enc_from_id"), "{rust}");

    let paths = gen.write_kotlin(&dir.join("kotlin")).expect("write_kotlin");
    let raw = paths
        .iter()
        .filter_map(|p| std::fs::read_to_string(p).ok())
        .collect::<Vec<_>>()
        .join("\n");
    let all: String = raw.split_whitespace().collect();
    // Selector Int + nullable build-arm leaves + nullable identity handle.
    assert!(all.contains("encodingSel:Int"), "{raw}");
    assert!(all.contains("encoding1:ZEnc?"), "{raw}");
    // The already-Option schema arg stays a single-level String?.
    assert!(all.contains("encoding01:String?"), "{raw}");
    assert!(!all.contains("String??"), "{raw}");
}

/// #96: a `.constructor()` member's return is a factory — it must be
/// excluded from the type-level `expand_return!` default auto-apply even
/// though its return type matches. Pins the `skip_output` derivation from
/// `class_members` (previously an eagerly-mutated accumulator).
#[test]
fn constructor_member_skips_default_output_expand() {
    let loc = myflat_loc();
    let fns: &[&str] = &[
        "pub fn z_thing_make() -> ZThing { unimplemented!() }",
        "pub fn z_thing_name(t: &ZThing) -> String { unimplemented!() }",
        "pub fn z_thing_get(s: i64) -> ZThing { unimplemented!() }",
    ];
    let items: Vec<(syn::Item, SourceLocation)> = fns
        .iter()
        .map(|src| {
            let f: syn::ItemFn = syn::parse_str(src).expect("parse fn");
            (syn::Item::Fn(f), loc.clone())
        })
        .collect();
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("ops")
                .class(
                    crate::ptr_class!(ZThing)
                        .constructor(prebindgen_registry::fun!(z_thing_make).name("make"))
                        .method(prebindgen_registry::fun!(z_thing_name).name("name")),
                )
                .fun(prebindgen_registry::fun!(z_thing_get)),
        )
        // Canonical output for ZThing: any ZThing-returning declared fn gets
        // callback delivery by default…
        .expand(
            prebindgen_registry::expand_return!(ZThing)
                .field_self()
                .field(prebindgen_registry::fun!(z_thing_name)),
        );
    let gen = jni.build_with(registry).expect("resolve");
    let registry = gen.registry();
    // …the free fn is decomposed…
    assert!(
        registry.unfold_plans().contains_key(&syn::Ident::new(
            "z_thing_get",
            proc_macro2::Span::call_site()
        )),
        "free fn gets the default output expansion"
    );
    // …but the constructor member is NOT (its return is the factory value).
    assert!(
        !registry.unfold_plans().contains_key(&syn::Ident::new(
            "z_thing_make",
            proc_macro2::Span::call_site()
        )),
        "constructor member must skip the default output expansion"
    );
}

// ── issue #95: qualified signature spellings + bare declarations ─────────

#[test]
fn qualified_signature_spelling_matches_bare_ptr_class() {
    // The source crate spells its own types with `myflat::`/`crate::` and a
    // std-prelude path; ingest normalizes them to the bare flat spelling,
    // so the bare `ptr_class!(ZThing)` declaration (and the whole
    // kotlin_fqn / leaf_key chain behind the wrapper) matches.
    let loc = myflat_loc();
    let items: Vec<(syn::Item, prebindgen::SourceLocation)> = vec![
        (
            syn::Item::Fn(syn::parse_quote!(
                pub fn z_thing_get() -> myflat::ZThing {
                    unimplemented!()
                }
            )),
            loc.clone(),
        ),
        (
            syn::Item::Fn(syn::parse_quote!(
                pub fn z_thing_name(this_: &crate::things::ZThing) -> std::string::String {
                    unimplemented!()
                }
            )),
            loc.clone(),
        ),
    ];
    let registry =
        crate::test_util::reg_from_items(declare_referenced(items)).expect("index items");
    let jni = JniGenBuilder::new()
        .set_package_prefix("io.test.jni")
        .package(
            crate::package!("thing")
                .class(
                    crate::ptr_class!(ZThing)
                        .method(prebindgen_registry::fun!(z_thing_name).name("name")),
                )
                .fun(prebindgen_registry::fun!(z_thing_get)),
        );
    let dir = unique_test_dir("jnigen_q95");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let gen = jni
        .build_with(registry)
        .expect("qualified spellings resolve");
    gen.write_rust(dir.join("gen.rs")).expect("write_rust");
    let paths = gen.write_kotlin(&dir.join("kotlin")).expect("write_kotlin");
    let all: String = paths
        .iter()
        .filter_map(|p| std::fs::read_to_string(p).ok())
        .collect();
    let ac: String = all.split_whitespace().collect();
    // The typed handle class with its instance method, and the typed factory
    // wrapper returning the class — the full declaration↔signature chain.
    assert!(ac.contains("classZThing(initialPtr:Long)"), "{all}");
    assert!(ac.contains("funname(onError:"), "{all}");
    assert!(
        ac.contains("funzThingGet(onError:JniErrorHandler<ZThing>):ZThing"),
        "{all}"
    );
}