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
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
//! Builder API for [`JniGenBuilder`].
//!
//! [`JniGenBuilder::new`] starts from defaults; global settings are applied with
//! the `set_*` methods (`config.rs`) and declarations are *accepted* as
//! pre-built objects (`decl.rs`) via [`JniGenBuilder::package`], [`JniGenBuilder::expand`],
//! and [`JniGenBuilder::convert`] — there is no fluent typestate cursor. Carved from the former monolithic
//! JNI module; shares the `jni` namespace via `use super::*`.

// `flat` as a module, not `flat::TypeKind` directly: the bare `TypeKind` in this
// file is jnigen's OWN classifier (`classify.rs`, reached through `use super::*`
// above), and an explicit import beats a glob — importing the model's would
// silently retarget the `TypeKind::Sum` / `TypeKind::DataStruct` matches below.
// One qualifier keeps both names short and says which of the two it is.
use kotlin_codegen::KtType;
use prebindgen_registry::{
    flat::{self, TypeRef},
    Conversions,
};

use super::*;

impl DeclaredKind {
    /// The declaring macro's name, for the conflict message.
    pub(crate) fn macro_name(&self) -> &'static str {
        match self {
            DeclaredKind::Ptr(_) => "ptr_class",
            DeclaredKind::Enum(_) => "enum_class",
            DeclaredKind::Sealed(_) => "sealed_class",
            DeclaredKind::Data => "data_class",
        }
    }

    /// Fold a **reopened** declaration of the same kind into this one, or
    /// reject a *different* kind. Both halves of "a type gets exactly one
    /// class declarator" live here, once, for every kind:
    ///
    /// * a different variant is rejected — two declarators would emit two
    ///   Kotlin declarations for the same FQN and leave the type table
    ///   ambiguous about the kind. The check is one discriminant comparison,
    ///   kind-agnostic and symmetric in declaration order, so a new kind is
    ///   covered by it without touching this function;
    /// * the same variant merges that kind's own payload, each rule written
    ///   next to the payload it merges.
    ///
    /// `type_name` is the short Rust name of the type being declared, for the
    /// message.
    fn merge(&mut self, incoming: DeclaredKind, type_name: &str) {
        assert!(
            std::mem::discriminant(&*self) == std::mem::discriminant(&incoming),
            "`{}` is already declared with `{}!(...)`; it cannot also be declared with \
             `{}!(...)` — a type gets exactly one class declarator",
            type_name,
            self.macro_name(),
            incoming.macro_name(),
        );
        match (self, incoming) {
            // `.gc_managed()` is sticky-OR: once any declaration asks for
            // Cleaner-backed release, the handle keeps it.
            (DeclaredKind::Ptr(have), DeclaredKind::Ptr(add)) => {
                have.gc_managed |= add.gc_managed;
            }
            // Per-variant last-wins: a second `sealed_class!(E)` adding one
            // `.variant(...)` must not drop the renames the first one set.
            (DeclaredKind::Sealed(have), DeclaredKind::Sealed(add)) => {
                have.variant_names.extend(add.variant_names);
            }
            // Kinds with no payload of their own: nothing to merge.
            (DeclaredKind::Enum(_), _) | (DeclaredKind::Data, _) => {}
            // The discriminants were just checked equal, so no mixed pair
            // reaches this arm — landing here means a kind carrying options
            // was added above without a merge rule.
            (existing, _) => unreachable!(
                "`{}!(...)` has no merge rule for a reopened declaration",
                existing.macro_name()
            ),
        }
    }
}

impl Declarations {
    /// The module path a generated call to `#[prebindgen]` fn `ident` must be
    /// qualified with: the fn's **origin crate** as recorded from its
    /// stream's `SourceLocation` stamp (multi-source bindings — helper
    /// crates layered on the flat crate), else the registry's default
    /// module (first-seen stream origin), else `crate`.
    pub(crate) fn fn_module(
        &self,
        registry: &impl Conversions<KotlinMeta>,
        ident: &syn::Ident,
    ) -> syn::Path {
        registry
            .origin_module(ident)
            .or_else(|| registry.default_module())
            .unwrap_or_else(|| syn::parse_quote!(crate))
    }

    /// The module for source references with no per-item origin (declared
    /// types with no `#[prebindgen]` item, glob imports): the registry's
    /// default module (first source), `crate` for an origin-less registry.
    pub(crate) fn default_module(&self, registry: &Registry<KotlinMeta>) -> syn::Path {
        registry
            .default_module()
            .unwrap_or_else(|| syn::parse_quote!(crate))
    }

    /// Whether `ty` was registered via an `EnumClassDecl` — used by the
    /// Kotlin wrapper generator to decide if a parameter needs a `.value`
    /// projection between the typed enum (Kotlin signature) and the `Int`
    /// wire (JNI `external fun`).
    ///
    /// Keyed on the canonical **spelling**, so it answers about the wrapper for
    /// a transparently-wrapped type: `Box<Priority>` is `false` here.
    /// [`is_kotlin_enum_reading`](Self::is_kotlin_enum_reading) is the same
    /// question asked of the model, and is what a caller holding a reading
    /// should use.
    pub(crate) fn is_kotlin_enum(&self, ty: &syn::Type) -> bool {
        self.is_kotlin_enum_key(&TypeKey::from_type(ty))
    }

    /// [`Self::is_kotlin_enum`] off the **identity** — the whole type's, not a
    /// probe through its layers. See [`Self::is_kotlin_enum_reading`] for the
    /// question that does peel, and why the two are not interchangeable.
    pub(crate) fn is_kotlin_enum_key(&self, key: &TypeKey) -> bool {
        self.types.get(key).is_some_and(|c| c.is_enum_class())
    }

    /// Whether this value's core is a type registered via an `EnumClassDecl`,
    /// asked of the **reading**: [`enum_probe`] peels the borrow/optional
    /// layers off the model, and the name comes off the classification.
    ///
    /// The name off `TypeKind::Named` rather than the spelling is the whole
    /// difference from [`is_kotlin_enum`](Self::is_kotlin_enum). A declaration
    /// names a type (`enum_class!(Priority)` keys `Priority`), and the model
    /// erases the wrappers no destination language can see — so
    /// `Box<Option<&Priority>>` reaches the same declaration `Priority` does,
    /// where taking the spelling apart finds `Box` and answers about it.
    pub(crate) fn is_kotlin_enum_reading(&self, reading: &TypeRef) -> bool {
        let flat::TypeKind::Named { id, .. } = enum_probe(reading).unwrapped().kind() else {
            return false;
        };
        id.ident()
            .and_then(|i| self.types.get(&TypeKey::from_ident(&i)))
            .is_some_and(|c| c.is_enum_class())
    }
}

impl Default for Declarations {
    fn default() -> Self {
        Self {
            package: String::new(),
            fun_name_mangle: None,
            ptr_class_name_mangle: None,
            data_class_name_mangle: None,
            enum_name_mangle: None,
            method_name_mangle: None,
            harness_name_mangle: None,
            interface_name_mangle: None,
            types: HashMap::new(),
            packages: BTreeMap::new(),
            emit_handle_locks: true,
            jni_native_init: None,
            convert_decls: Vec::new(),
            param_expand_decls: Vec::new(),
            return_expand_decls: Vec::new(),
            fn_param_expands: Vec::new(),
            fn_return_expands: Vec::new(),
            fn_split_params: Vec::new(),
            class_members: HashMap::new(),
            ignored_fns: std::collections::HashSet::new(),
            ignored_name_predicates: Vec::new(),
            ignored_class_types: std::collections::HashSet::new(),
            ignored_const_idents: std::collections::HashSet::new(),
            local_fns: Vec::new(),
            iface_specs: Default::default(),
            fn_plans: Default::default(),
        }
    }
}

impl JniGenBuilder {
    /// Start a binding generator with default settings: empty base
    /// package, no `JNINative` init block, identity
    /// name-mangling, handle locks enabled. Adjust settings with the `set_*`
    /// methods, add declarations with [`package`](Self::package),
    /// [`expand`](Self::expand), [`convert`](Self::convert), etc., then run the
    /// result through [`build`](Self::build) → `JniGen::write_rust` /
    /// `write_kotlin`. Settings and
    /// declarations may be interleaved in any order — the builder stores
    /// only raw inputs, and every setting-derived name is computed at the
    /// point of use.
    pub fn new() -> Self {
        Self::default()
    }
}

impl Declarations {
    /// Apply the package-level function-name mangle closure to `name`.
    pub(crate) fn mangle_fun(&self, package: &str, name: &str) -> String {
        match &self.fun_name_mangle {
            Some(f) => f(package, name),
            None => mangle_kotlin_ident(name),
        }
    }
    /// Apply the method-name mangle closure to `name`, providing the package
    /// and final class name that contain the method.
    pub(crate) fn mangle_method(&self, package: &str, class: &str, name: &str) -> String {
        match &self.method_name_mangle {
            Some(f) => f(package, class, name),
            None => mangle_kotlin_ident(name),
        }
    }
    /// Apply the ptr-class mangle closure to `name`, returning the closure
    /// result or the sanitized `name` (issue #89) when unset.
    pub(crate) fn mangle_ptr_class(&self, package: &str, name: &str) -> String {
        match &self.ptr_class_name_mangle {
            Some(f) => f(package, name),
            None => mangle_kotlin_ident(name),
        }
    }
    /// Apply the data-class mangle closure to `name`, returning the closure
    /// result or the sanitized `name` (issue #89) when unset.
    pub(crate) fn mangle_data_class(&self, package: &str, name: &str) -> String {
        match &self.data_class_name_mangle {
            Some(f) => f(package, name),
            None => mangle_kotlin_ident(name),
        }
    }
    /// Apply the enum mangle closure to `name`, returning the closure result
    /// or the sanitized `name` (issue #89) when unset.
    pub(crate) fn mangle_enum(&self, package: &str, name: &str) -> String {
        match &self.enum_name_mangle {
            Some(f) => f(package, name),
            None => mangle_kotlin_ident(name),
        }
    }
    /// Apply the harness mangle closure to `name`, returning the closure
    /// result or the sanitized `name` (issue #89) when unset.
    pub(crate) fn mangle_harness(&self, name: &str) -> String {
        match &self.harness_name_mangle {
            Some(f) => f(name),
            None => mangle_kotlin_ident(name),
        }
    }
    /// The name of the centralized Native object that hosts every JNI
    /// `external fun`: the explicit default value `"JNINative"` run through
    /// the harness mangle hook (identity when unset). Drives both the
    /// Kotlin class emission and the JNI extern symbol path on the Rust
    /// side.
    pub(crate) fn jni_native_class_name(&self) -> String {
        self.mangle_harness("JNINative")
    }

    /// Mangle a method emitted on the centralized JNI extern harness.
    pub(crate) fn mangle_jni_method(&self, name: &str) -> String {
        self.mangle_method(&self.package, &self.jni_native_class_name(), name)
    }

    /// Resolve a relative subpackage against the configured base package.
    pub(crate) fn package_name(&self, subpackage: &str) -> String {
        match (&self.package, subpackage) {
            (p, sub) if !sub.is_empty() && !p.is_empty() => format!("{p}.{sub}"),
            (_, sub) if !sub.is_empty() => sub.to_string(),
            (p, _) => p.clone(),
        }
    }

    /// Resolve a relative class name against [`Self::package`] +
    /// `subpackage` (dot-separated; empty `subpackage` = the base package).
    /// Panics if `name` contains a `.` (a check that catches accidental FQNs
    /// in the relative-name builders) — a binding crate owns one package and
    /// must not write classes into anyone else's namespace.
    pub(crate) fn resolve_class_fqn(&self, subpackage: &str, name: &str) -> String {
        assert!(
            !name.contains('.'),
            "Kotlin class name `{}` must be relative (no dots) — FQNs are derived from the base \
             package + subpackage",
            name
        );
        let base = self.package_name(subpackage);
        if base.is_empty() {
            name.to_string()
        } else {
            format!("{}.{}", base, name)
        }
    }
}

// ── Accepting a `PackageDecl` ────────────────────────────────────────────

/// The describing surface: everything that *adds* to [`Declarations`].
///
/// Every method here takes `self` or `&mut self`; not one of them exists on
/// `Declarations`, which is the whole point of the two types.
impl JniGenBuilder {
    /// Register a package's worth of classes, functions and consts (a
    /// [`PackageDecl`], built with [`package!`](crate::package)). Call it once
    /// per package, or several times for the same package name — the
    /// declarations merge, so you can split a large package across calls.
    /// Every `#[prebindgen]` item captured in `dir` — pass
    /// `<source_crate>::PREBINDGEN_OUT_DIR`.
    ///
    /// The same feeder [`FlatBuilder::source`](prebindgen_registry::flat::FlatBuilder::source)
    /// has, because it is that feeder: the binding says where its source is,
    /// and the model is built from it at [`Self::build`].
    pub fn source<P: AsRef<std::path::Path>>(mut self, dir: P) -> Self {
        self.sources = std::mem::take(&mut self.sources).source(dir);
        self
    }

    /// The same, for a dependency this crate **renames** in `Cargo.toml`.
    ///
    /// The origin recorded at capture time is the dependency's real package
    /// name, which will not resolve from a crate that refers to it by another
    /// name. `crate_name` is the name *this* crate uses. Per directory,
    /// deliberately: a binding may layer several sources.
    pub fn source_named<P: AsRef<std::path::Path>>(
        mut self,
        dir: P,
        crate_name: impl Into<String>,
    ) -> Self {
        self.sources = std::mem::take(&mut self.sources).source_named(dir, crate_name);
        self
    }

    /// Add a captured item stream — a group selection, an otherwise-configured
    /// [`Source`](prebindgen::Source), or synthetic items in a test.
    ///
    /// Accumulates, so it mixes freely with [`Self::source`].
    pub fn items<I>(mut self, items: I) -> Self
    where
        I: IntoIterator<Item = (syn::Item, prebindgen::SourceLocation)>,
    {
        self.sources = std::mem::take(&mut self.sources).items(items);
        self
    }

    pub fn package(mut self, decl: PackageDecl) -> Self {
        let PackageDecl {
            name,
            classes,
            functions,
            constants,
        } = decl;
        self.decls.packages.entry(name.clone()).or_default();
        for class in classes {
            self.accept_class(&name, class);
        }
        for func in functions {
            self.accept_function(&name, func);
        }
        // One acceptor, dispatched on the decl's value source. The `.with`
        // source was already lowered to an expression (`path()`) at decl
        // time, so only three storage kinds exist internally.
        for c in constants {
            let pkg = self.decls.packages.entry(name.clone()).or_default();
            match c.source {
                super::decl::ConstSource::Item => {
                    let mut entry = FunctionEntry::new(c.rust_ident);
                    entry.kotlin_name_override = c.kotlin_name_override;
                    pkg.constants.push(entry);
                }
                super::decl::ConstSource::Fun(ref fn_ident) => {
                    let mut entry = FunctionEntry::new(fn_ident.clone());
                    entry.kotlin_name_override = Some(c.val_name());
                    pkg.constant_functions.push(entry);
                }
                super::decl::ConstSource::Expr { ref ty, ref expr } => {
                    pkg.constant_exprs.push(super::decl::ConstExprDecl {
                        kotlin_name: c.val_name(),
                        ty: ty.clone(),
                        expr: expr.clone(),
                    });
                }
            }
        }
        self
    }

    /// Acknowledge a `#[prebindgen]` item this binding deliberately does
    /// NOT bind: nothing is emitted for it and the registry's per-item
    /// "skipping undeclared" warning is suppressed. Global — an ignored
    /// item belongs to no package. One acceptor, the kind carried by the
    /// decl (see [`IgnoreDecl`]): `fun!` / `ty!` / `constant!` for exact
    /// items, [`matching`] for a name-family
    /// predicate over ANY item kind.
    pub fn ignore(mut self, decl: impl Into<IgnoreDecl>) -> Self {
        match decl.into().0 {
            super::decl::IgnoreKind::Fun(ident) => {
                self.decls.ignored_fns.insert(ident);
            }
            super::decl::IgnoreKind::Type(key) => {
                self.decls.ignored_class_types.insert(key);
            }
            super::decl::IgnoreKind::Const(ident) => {
                self.decls.ignored_const_idents.insert(ident);
            }
            super::decl::IgnoreKind::Matching(pred) => {
                self.decls.ignored_name_predicates.push(pred);
            }
        }
        self
    }

    fn accept_class(&mut self, subpackage: &str, decl: ClassDecl) {
        match decl {
            ClassDecl::Ptr(d) => self.accept_ptr_class(subpackage, d),
            ClassDecl::Enum(d) => self.accept_enum_class(subpackage, d),
            ClassDecl::Sealed(d) => self.accept_sealed_class(subpackage, d),
            ClassDecl::Data(d) => self.accept_data_class(subpackage, d),
        }
    }

    /// Register one class declaration: its [`DeclaredKind`] (kind + that
    /// kind's own options) and its raw [`NameSpec`]. The single entry point
    /// into [`Self::types`] — every acceptor goes through it, so the
    /// one-declarator-per-type rule is enforced for all kinds by
    /// [`DeclaredKind::merge`] and cannot be forgotten by a new one.
    /// No FQN is derived here — names materialize at read time via
    /// [`JniGenBuilder::fqn_of`], against whatever the settings are then.
    ///
    /// Returns the stored config so the caller can fold in its cross-kind
    /// options (`jobject_input`, interfaces).
    ///
    /// `rust_type` is the declaration's own spelling; `key` is the identity
    /// derived from it. They cannot disagree — every `*ClassDecl::new` builds
    /// both from the one `syn::Type` it was handed.
    fn register_class(
        &mut self,
        key: &TypeKey,
        rust_type: Origin<syn::Type>,
        kind: DeclaredKind,
        spec: NameSpec,
    ) -> &mut TypeConfig {
        // Early failure for a bad per-decl `.name()`: the FQN itself is only
        // derived at write time, but a dotted relative name is a declaration
        // mistake and should surface in the declaring call (the same check
        // `resolve_class_fqn` repeats at derivation time).
        if let NameSpec {
            name_override: Some(n),
            ..
        } = &spec
        {
            assert!(
                !n.contains('.'),
                "Kotlin class name `{}` must be relative (no dots) — FQNs are derived from the \
                 base package + subpackage",
                n
            );
        }
        let short = rust_short_name(key);
        match self.decls.types.entry(key.clone()) {
            std::collections::hash_map::Entry::Occupied(e) => {
                // A reopened declarator keeps the first spelling: the two agree
                // on identity by construction, and the model indexes types
                // first-mention-wins for the same reason.
                let cfg = e.into_mut();
                cfg.kind.merge(kind, &short);
                cfg.name_spec = Some(spec);
                cfg
            }
            std::collections::hash_map::Entry::Vacant(e) => {
                e.insert(TypeConfig::new(kind, spec, rust_type))
            }
        }
    }

    /// Merge a decl's interface options into the type's [`TypeConfig`]
    /// (reopened decls merge; the `.interface()` switch and name override are
    /// sticky-OR / last-wins, a repeated `.implements` interface is
    /// idempotent).
    fn store_iface_opts(&mut self, key: &TypeKey, iface: IfaceOpts) {
        let cfg = self
            .decls
            .types
            .get_mut(key)
            .expect("register_class created the entry");
        cfg.interface_enabled |= iface.enabled;
        if iface.name_override.is_some() {
            cfg.interface_name_override = iface.name_override;
        }
        for i in iface.implements {
            if !cfg.interfaces.contains(&i) {
                cfg.interfaces.push(i);
            }
        }
    }

    fn accept_ptr_class(&mut self, subpackage: &str, decl: PtrClassDecl) {
        let short = rust_short_name(&decl.key);
        let key = decl.key;
        self.register_class(
            &key,
            decl.rust_type,
            DeclaredKind::Ptr(OpaqueConfig {
                gc_managed: decl.gc_managed,
            }),
            NameSpec {
                subpackage: subpackage.to_string(),
                short,
                name_override: decl.name_override,
                kind: NameKind::Ptr,
            },
        );
        self.store_iface_opts(&key, decl.iface);
        self.accept_members(&key, decl.members);
    }

    fn accept_enum_class(&mut self, subpackage: &str, decl: EnumClassDecl) {
        let short = rust_short_name(&decl.key);
        let key = decl.key;
        self.register_class(
            &key,
            decl.rust_type,
            DeclaredKind::Enum(EnumConfig::default()),
            NameSpec {
                subpackage: subpackage.to_string(),
                short,
                name_override: decl.name_override,
                kind: NameKind::Enum,
            },
        );
        self.store_iface_opts(&key, decl.iface);
    }

    /// A `sealed_class!` declaration. The Kotlin name routes through the
    /// **enum** mangle hook: a sum is a declared enum, and its interface is
    /// the Kotlin name of that enum — one hook per Rust item kind, not one
    /// per emitted shape.
    fn accept_sealed_class(&mut self, subpackage: &str, decl: SealedClassDecl) {
        let short = rust_short_name(&decl.key);
        let key = decl.key;
        let rust_type = decl.rust_type;
        // Reopened decls merge — `DeclaredKind::merge` owns that rule for
        // every kind, so this acceptor only builds its own payload.
        let mut sum = SumConfig::default();
        for v in decl.variants {
            if let Some(name) = v.name_override {
                sum.variant_names.insert(v.rust_ident, name);
            }
        }
        self.register_class(
            &key,
            rust_type,
            DeclaredKind::Sealed(sum),
            NameSpec {
                subpackage: subpackage.to_string(),
                short,
                name_override: decl.name_override,
                kind: NameKind::Enum,
            },
        );
        self.store_iface_opts(&key, decl.iface);
    }

    fn data_value_name_spec(
        subpackage: &str,
        short: String,
        name_override: Option<String>,
    ) -> NameSpec {
        NameSpec {
            subpackage: subpackage.to_string(),
            short,
            name_override,
            kind: NameKind::DataOrValue,
        }
    }

    fn accept_data_class(&mut self, subpackage: &str, decl: DataClassDecl) {
        let short = rust_short_name(&decl.key);
        let key = decl.key;
        let spec = Self::data_value_name_spec(subpackage, short, decl.name_override);
        self.register_class(&key, decl.rust_type, DeclaredKind::Data, spec)
            .jobject_input |= decl.jobject_input;
        self.store_iface_opts(&key, decl.iface);
        self.accept_members(&key, decl.members);
    }

    /// Shared tail of the member-bearing class kinds (`ptr` / `data` —
    /// every kind whose instance can re-enter Rust): each member's
    /// per-fn expand overrides apply exactly as a free function's would; a
    /// constructor member's return is additionally never output-flattened
    /// (it's a factory); then the members join the class's registered set.
    fn accept_members(&mut self, key: &TypeKey, members: Vec<(FunctionDecl, MemberKind)>) {
        for (decl, kind) in members {
            let rust_ident = decl.rust_ident().clone();
            let kotlin_name_override = decl.kotlin_name_override().clone();
            self.accept_fn_expands(decl);
            // A constructor member's return is a factory, never
            // output-flattened — derived from `class_members` in
            // `build_deconstructors` (`skip_output`), not stored separately.
            self.decls
                .class_members
                .entry(key.clone())
                .or_default()
                .push(ClassMember {
                    rust_ident,
                    kotlin_name_override,
                    kind,
                });
        }
    }

    fn accept_function(&mut self, subpackage: &str, decl: FunctionDecl) {
        let mut entry = FunctionEntry::new(decl.rust_ident().clone());
        entry.kotlin_name_override = decl.kotlin_name_override().clone();
        self.decls
            .packages
            .entry(subpackage.to_string())
            .or_default()
            .functions
            .push(entry);
        self.accept_fn_expands(decl);
    }

    /// Move a [`FunctionDecl`]'s per-fn expand overrides
    /// (`.expand_param(name, …)` / `.expand_return(…)`) into raw storage.
    /// Shared by [`Self::accept_function`] (free package fns) and
    /// [`Self::accept_members`] (class members) — the overrides mean the same
    /// thing in both positions. Nothing is lowered here: variant/field lists
    /// are interpreted at the point of use ([`Self::build_expansions`] /
    /// [`Self::build_deconstructors`]) so field-name inheritance and the
    /// rust-side-only checks see the complete declaration set.
    fn accept_fn_expands(&mut self, decl: FunctionDecl) {
        let (
            rust_ident,
            _kotlin_name_override,
            param_expands,
            return_expand,
            split_on_params,
            local,
        ) = decl.into_parts();
        // A path-built decl (`fun!(crate::f)`) declares a BINDING-LOCAL fn:
        // record its stated signature for the synthesis pre-pass
        // ([`Self::local_functions`]). The signature is mandatory — a path
        // carries nothing to read.
        if let Some((path, sig)) = local {
            let Some(sig) = sig else {
                panic!(
                    "fun!({p}): a binding-local fn states its signature — chain \
                     .sig(sig!((params) -> Ret))",
                    p = quote::quote!(#path)
                );
            };
            self.decls.local_fns.push((rust_ident.clone(), path, sig));
        }
        for (param, pdecl) in param_expands {
            self.decls
                .fn_param_expands
                .push((rust_ident.clone(), param, pdecl));
        }
        if let Some(rdecl) = return_expand {
            self.decls
                .fn_return_expands
                .push((rust_ident.clone(), rdecl));
        }
        for param in split_on_params {
            self.decls.fn_split_params.push((rust_ident.clone(), param));
        }
    }
}

// ── Accepting boundary decls ─────────────────────────────────────────────

impl JniGenBuilder {
    /// Declare a type's **default boundary behavior** — either of the two
    /// [`ExpandDecl`] directions, the direction carried by the decl object
    /// (the boundary-decl peer of [`PackageDecl::class`]):
    ///
    /// * [`expand_param!`](prebindgen_registry::expand_param) — the input side: how a
    ///   parameter of the type may be supplied, as an OR-list of build
    ///   variants.
    /// * [`expand_return!`](prebindgen_registry::expand_return) — the output side: the
    ///   AND-set of fields a returned / callback-delivered / `Result`-error
    ///   value of the type decomposes into.
    ///
    /// Applies to every function mentioning the type, in any package; a
    /// single function overrides via the [`FunctionDecl`] `param_expand*` /
    /// `return_expand*` methods.
    pub fn expand(mut self, decl: impl Into<ExpandDecl>) -> Self {
        match decl.into() {
            ExpandDecl::Param(decl) => {
                assert!(
                    !decl.variants().is_empty(),
                    "expand_param!({}) declares no variants — add .variant(fun!(...)) and/or \
                     .variant_self()",
                    decl.key().as_str()
                );
                self.decls.param_expand_decls.push(decl);
            }
            ExpandDecl::Return(decl) => {
                assert!(
                    !decl.field_list().is_empty(),
                    "expand_return!({}) declares no fields — add .field(fun!(...)) and/or \
                     .field_self()",
                    decl.key().as_str()
                );
                self.decls.return_expand_decls.push(decl);
            }
        }
        self
    }
}

impl Declarations {
    /// The Kotlin name of `func` as a declared member (`.method`/`.constructor`)
    /// of the class keyed by `key`, if it is one — the name-inheritance
    /// source for [`ExpandReturnDecl::field`].
    fn class_method_kotlin_name(&self, key: &TypeKey, func: &syn::Ident) -> Option<String> {
        self.class_members
            .get(key)?
            .iter()
            .find(|m| &m.rust_ident == func)
            .map(|m| self.effective_method_name(key, m))
    }

    /// The effective Kotlin name of a class method/factory, derived at point
    /// of use: a per-method `.name()` override verbatim, else the method
    /// hook over the full camelCase Rust identifier with its final package
    /// and class context. Consumers can therefore remove flat namespace
    /// prefixes without the generator guessing their source convention.
    pub(crate) fn effective_method_name(&self, key: &TypeKey, m: &ClassMember) -> String {
        if let Some(name) = &m.kotlin_name_override {
            return name.clone();
        }
        let spec = self
            .types
            .get(key)
            .and_then(|cfg| cfg.name_spec.as_ref())
            .unwrap_or_else(|| panic!("class member `{}` has no class name", m.rust_ident));
        let fqn = self.fqn_of(spec);
        let (package, class) = fqn.rsplit_once('.').unwrap_or(("", fqn.as_str()));
        self.mangle_method(package, class, &snake_to_camel(&m.rust_ident.to_string()))
    }

    /// The effective Kotlin name of a package-level function. Explicit
    /// `.name()` wins; otherwise the package-aware function hook receives
    /// the full camelCase Rust identifier.
    pub(crate) fn effective_function_name(
        &self,
        subpackage: &str,
        entry: &FunctionEntry,
    ) -> String {
        entry.kotlin_name_override.clone().unwrap_or_else(|| {
            self.mangle_fun(
                &self.package_name(subpackage),
                &snake_to_camel(&entry.rust_ident.to_string()),
            )
        })
    }

    /// Whether `key` was declared as a class in some package (any
    /// [`DeclaredKind`]). Presence in [`Self::types`] *is* the answer —
    /// [`Self::register_class`] is the table's only writer. A boundary decl on
    /// a type without a class declaration makes it **rust-side-only**: the
    /// value is always built from ingredients / decomposed into fields at the
    /// boundary and never materializes in Kotlin — so the `_self` arms are
    /// structurally impossible for it.
    fn is_class_declared(&self, key: &TypeKey) -> bool {
        self.types.contains_key(key)
    }

    /// Lower the raw [`ExpandParamDecl`]s into the core's immutable
    /// [`Expansions`] record set at the point of use — a pure declaration →
    /// record mapping. Building on demand keeps declarations
    /// order-independent — a `param_expand` may precede or follow the
    /// `package` that declares its constructors (which is also why the
    /// rust-side-only `_self` check lives here and not at accept time).
    /// Duplicate targets pass through unmerged; core `apply` diagnoses them.
    pub(crate) fn build_expansions(&self) -> prebindgen_registry::expand::Expansions {
        use prebindgen_registry::expand::{ExpandDecl, ExpandSel, Expansions, Variant};
        let lower = |v: &LocalVariant| match v {
            LocalVariant::Ctor(f) => Variant::Ctor(f.clone()),
            LocalVariant::SelfIdentity => Variant::Identity,
        };
        let mut exp = Expansions::default();
        for decl in &self.param_expand_decls {
            assert!(
                self.is_class_declared(decl.key())
                    || !decl
                        .variants()
                        .iter()
                        .any(|v| matches!(v, LocalVariant::SelfIdentity)),
                "expand_param!({k}).variant_self(): `{k}` has no class declaration, so there is \
                 no Kotlin object to pass — drop .variant_self() (the type is rust-side-only) \
                 or declare the type in a package",
                k = decl.key().as_str()
            );
            // Identity-only normalization: `.variant_self()` alone declares
            // the plain-handle form — exactly the default when nothing is
            // declared, so registering it would only add a degenerate
            // 1-variant selector to every param of this type.
            if matches!(decl.variants(), [LocalVariant::SelfIdentity]) {
                continue;
            }
            exp.constructors
                .push(prebindgen_registry::expand::ConstructorDecl {
                    target: decl.rust_type().key(),
                    variants: decl.variants().iter().map(lower).collect(),
                    default: true,
                });
        }
        // Per-fn overrides: same decl shape, complete-set semantics; the
        // param-name/type cross-check and the identity-only lowering happen
        // in `core/expand.rs`'s `apply` (which sees the fn signatures).
        for (func, param, decl) in &self.fn_param_expands {
            assert!(
                self.is_class_declared(decl.key())
                    || !decl
                        .variants()
                        .iter()
                        .any(|v| matches!(v, LocalVariant::SelfIdentity)),
                "fun!({func}).expand_param(\"{param}\", expand_param!({k}).variant_self()): `{k}` \
                 has no class declaration, so there is no Kotlin object to pass — drop \
                 .variant_self() (the type is rust-side-only) or declare the type in a package",
                k = decl.key().as_str()
            );
            exp.expands.push(ExpandDecl {
                func: func.clone(),
                param: syn::Ident::new(param, Span::call_site()),
                declared_target: Some(decl.rust_type().key()),
                sel: ExpandSel::Subset(decl.variants().iter().map(lower).collect()),
            });
        }
        exp
    }

    /// Lower one raw [`LocalField`] list into core [`DeconRecord`]s with the
    /// UNIFORM field-name precedence resolved against the complete
    /// declaration set: explicit `.name()` first, then the class member's
    /// Kotlin name (a getter that is both a method and a field is named
    /// once, on the member), else the camel-cased Rust name.
    fn lower_fields(
        &self,
        registry: &impl Conversions<KotlinMeta>,
        key: &TypeKey,
        fields: &[LocalField],
    ) -> Vec<prebindgen_registry::unfold::DeconRecord> {
        use prebindgen_registry::unfold::DeconRecord;
        fields
            .iter()
            .map(|f| match f {
                LocalField::Fields(decl) => DeconRecord::Fields {
                    func: decl.func().clone(),
                    consuming: decl.is_consuming(),
                    fields: self.lower_value_form(registry, key, decl),
                },
                LocalField::Named(func, name_override) => {
                    let name = name_override
                        .clone()
                        .or_else(|| self.class_method_kotlin_name(key, func))
                        .unwrap_or_else(|| snake_to_camel(&func.to_string()));
                    DeconRecord::Acc {
                        func: func.clone(),
                        name,
                    }
                }
                LocalField::SelfField => DeconRecord::Identity,
                LocalField::Local {
                    path,
                    sig,
                    name_override,
                } => {
                    let name = self.local_field_name(key, path, name_override);
                    self.check_local_field_ty(key, &name, sig);
                    DeconRecord::LocalAcc {
                        path: path.clone(),
                        name,
                    }
                }
            })
            .collect()
    }

    /// Expand a `.fields(fields!(f))` declaration into one
    /// [`FieldRecord`](prebindgen_registry::unfold::FieldRecord) per field of the
    /// struct `f` returns — the value form.
    ///
    /// The walk is the adapter's job because only it knows which structs are
    /// declared `data_class!`es: a **non-optional** nested one is inlined (its
    /// own fields become records with `__`-joined names), matching what
    /// `synth_value_struct_leaves` does for a by-value data class; everything
    /// else is one record and core decides whether that record's type splices
    /// its own `expand_return!`.
    ///
    /// Per-field `.field(...)` overrides and `.name(...)` renames key on the
    /// **Rust field ident**, and both are checked against the struct: naming a
    /// field the value form doesn't have is a hard error, which is the point —
    /// a field renamed upstream must not silently lose its adjustment.
    fn lower_value_form(
        &self,
        registry: &impl Conversions<KotlinMeta>,
        key: &TypeKey,
        decl: &FieldsDecl,
    ) -> Vec<prebindgen_registry::unfold::FieldRecord> {
        let func = decl.func();
        let accessor = registry.flat().function(&func).unwrap_or_else(|| {
            panic!(
                "expand_return!({}).fields(fields!({func})): no `#[prebindgen]` function \
                 `{func}` — a value form is an accessor `fn {func}(v: &{}) -> {}Struct`",
                key.as_str(),
                key.as_str(),
                key.as_str(),
            )
        });
        // The accessor's return as the model read it, peeled of a leading `&`.
        // An elided return and a written `-> ()` are one thing here, because the
        // model already normalized them.
        let ret = accessor.ret.borrow_target().unwrap_or(&accessor.ret);
        assert!(
            !matches!(ret.unwrapped().kind(), flat::TypeKind::Unit),
            "expand_return!({}).fields(fields!({func})): `{func}` returns nothing — a \
             value form returns the struct holding this type's fields",
            key.as_str(),
        );
        let TypeKind::DataStruct { st, .. } = self.type_kind(registry, &ret.key()) else {
            panic!(
                "expand_return!({}).fields(fields!({func})): `{func}` returns `{}`, which is \
                 not a struct — a value form returns a struct whose fields become the leaves",
                key.as_str(),
                ret,
            )
        };
        let st = st.clone();

        let mut out = Vec::new();
        self.walk_value_form(registry, key, decl, &st, &[], "", 0, &mut out);

        // Every adjustment must have found its field. An unknown name is the
        // drift this whole declarator exists to catch, so it is an error rather
        // than a no-op.
        let named: std::collections::HashSet<String> = out
            .iter()
            .map(|r: &prebindgen_registry::unfold::FieldRecord| {
                r.members
                    .iter()
                    .map(|m| m.to_string())
                    .collect::<Vec<_>>()
                    .join(".")
            })
            .collect();
        for (field, _) in decl.overrides().iter() {
            assert!(
                named.contains(field),
                "fields!({func}).field(\"{field}\", ...): `{}` has no field `{field}` \
                 (fields: {})",
                st.name,
                named.iter().cloned().collect::<Vec<_>>().join(", "),
            );
        }
        for (field, _) in decl.names().iter() {
            assert!(
                named.contains(field),
                "fields!({func}).name(\"{field}\", ...): `{}` has no field `{field}` \
                 (fields: {})",
                st.name,
                named.iter().cloned().collect::<Vec<_>>().join(", "),
            );
        }
        out
    }

    /// One level of [`Self::lower_value_form`]'s struct walk. `members` /
    /// `name_prefix` accumulate through inlined nested data classes; an
    /// override or rename keys on the dotted member path, so a nested field is
    /// addressed as `"outer.inner"`.
    #[allow(clippy::too_many_arguments)]
    fn walk_value_form(
        &self,
        registry: &impl Conversions<KotlinMeta>,
        key: &TypeKey,
        decl: &FieldsDecl,
        st: &flat::Struct,
        members: &[syn::Ident],
        name_prefix: &str,
        depth: usize,
        out: &mut Vec<prebindgen_registry::unfold::FieldRecord>,
    ) {
        use prebindgen_registry::unfold::{FieldDecon, FieldRecord};
        // A value form holding itself would expand forever; the cycle rule for
        // everything reachable BELOW a field is core's `visited` check.
        assert!(
            depth <= 16,
            "expand_return!({}).fields(fields!({})): `{}` nests data classes more than 16 \
             deep — is a value form holding itself?",
            key.as_str(),
            decl.func(),
            st.name,
        );
        // A tuple struct is an `Extern` rather than a `Struct`, so it never
        // reaches here — `lower_value_form`'s "not a struct" diagnosis catches
        // it at the return type, which is where the author wrote it.
        for field in &st.fields {
            let Some(fname) = field.name.as_ref() else {
                continue;
            };
            let mut member_path = members.to_vec();
            member_path.push(fname.clone());
            let dotted = member_path
                .iter()
                .map(|m| m.to_string())
                .collect::<Vec<_>>()
                .join(".");
            let camel = mangle_kotlin_ident(&kt_snake_to_camel(&fname.to_string()));
            let name = decl
                .names()
                .iter()
                .find(|(f, _)| *f == dotted)
                .map(|(_, n)| n.clone())
                .unwrap_or(camel);
            let name = if name_prefix.is_empty() {
                name
            } else {
                format!("{name_prefix}__{name}")
            };

            // An explicit override replaces the field type's default
            // decomposition wholesale — including any nesting it would have had.
            if let Some((_, ovr)) = decl.overrides().iter().find(|(f, _)| *f == dotted) {
                // The override states the field's type, so it is cross-checked
                // against the field the same way a per-fn `.expand_param` /
                // `.expand_return` decl is checked against its parameter or
                // return. Without this an override outlives an upstream
                // field-type change — the very drift `.fields()` exists to
                // catch — and two same-shaped handle types silently swap.
                // Core applies override records to the whole field after
                // peeling only an outer `Option`: a `Vec<T>` remains `Vec<T>`.
                // Mirror that exact normalization here; peeling `Vec` would
                // accept `expand_return!(T)` and only fail later when core
                // applies its records to `Vec<T>`.
                let under_opt = field.ty.optional_inner().unwrap_or(&field.ty);
                let peeled = under_opt.borrow_target().unwrap_or(under_opt);
                let actual = peeled.key();
                assert!(
                    actual == *ovr.key(),
                    "fields!({}).field(\"{dotted}\", expand_return!({})): `{}.{dotted}` is \
                     `{}`, not `{}` — a per-field override names the field's own type",
                    decl.func(),
                    ovr.key().as_str(),
                    st.name,
                    actual.as_str(),
                    ovr.key().as_str(),
                );
                out.push(FieldRecord {
                    members: member_path,
                    name,
                    ty: field.ty.clone(),
                    decon: FieldDecon::Records(self.lower_fields(
                        registry,
                        ovr.key(),
                        ovr.field_list(),
                    )),
                });
                continue;
            }

            // A nested `data_class!` inlines when it is reached directly; behind
            // `Option` / `Vec` it stays one leaf, whose own converter builds the
            // object (the rule `synth_value_struct_leaves` already follows).
            // A `sealed_class!` field has no whole-value converter at all, so it
            // must decompose into its selector and groups wherever it appears.
            let bare = field.ty.optional_inner().unwrap_or(&field.ty);
            let probe = bare.sequence_elem().unwrap_or(bare);
            match self.type_kind(registry, &probe.key()) {
                TypeKind::DataStruct { st, cfg: Some(_) }
                    if field.ty.optional_inner().is_none()
                        && field.ty.sequence_elem().is_none() =>
                {
                    let child = st.clone();
                    self.walk_value_form(
                        registry,
                        key,
                        decl,
                        &child,
                        &member_path,
                        &name,
                        depth + 1,
                        out,
                    );
                    continue;
                }
                TypeKind::Sum => {
                    // A sum's leaves are a selector plus one group per
                    // alternative, laid out side by side at a FIXED position.
                    // A `Vec` of them has variable arity, so there is no fixed
                    // layout to lay out — that one stays refused.
                    //
                    // `Option<sum>` does NOT: absence is the selector leaf's own
                    // nullability, the same mechanism a sum under a conditional
                    // value form already crosses by (#220). The refusal that
                    // stood here predated it.
                    assert!(
                        bare.sequence_elem().is_none(),
                        "expand_return!({}).fields(fields!({})): field `{}.{}` is a \
                         `Vec<{}>` — a sequence of tag-gated groups has variable arity and \
                         cannot be laid out in a fixed leaf list",
                        key.as_str(),
                        decl.func(),
                        st.name,
                        dotted,
                        probe,
                    );
                    // The name is the reading's, not a path taken apart to
                    // re-derive one.
                    let flat::TypeKind::Named { id, .. } = probe.unwrapped().kind() else {
                        panic!("a sum type is a named type")
                    };
                    let flat::Type::Variant(sum) = registry
                        .flat()
                        .declared_type(&id.name)
                        .expect("TypeKind::Sum implies an indexed enum")
                    else {
                        panic!("TypeKind::Sum implies a payload-carrying enum")
                    };
                    let sum_cfg = self.types[&probe.key()]
                        .sum()
                        .expect("TypeKind::Sum implies a sealed-class config");
                    out.push(FieldRecord {
                        members: member_path,
                        name,
                        ty: field.ty.clone(),
                        decon: FieldDecon::Leaves(crate::jni::synth_sum_leaves(self, sum_cfg, sum)),
                    });
                    continue;
                }
                _ => {}
            }

            out.push(FieldRecord {
                members: member_path,
                name,
                ty: field.ty.clone(),
                decon: FieldDecon::Default,
            });
        }
    }

    /// Lower the raw [`ExpandReturnDecl`]s into the core's immutable
    /// [`Deconstructors`] record set — the output-side peer of
    /// [`Self::build_expansions`], a pure declaration → record mapping.
    /// Duplicate targets pass through unmerged; core `apply` diagnoses
    /// them. `skip_output` is derived from the class members: a
    /// `.constructor()` member's return is a factory, never
    /// output-flattened.
    pub(crate) fn build_deconstructors(
        &self,
        registry: &impl Conversions<KotlinMeta>,
    ) -> prebindgen_registry::unfold::Deconstructors {
        use prebindgen_registry::unfold::{
            DeconSel, DeconTarget, DeconstructorDecl, Deconstructors, Delivery, OutputDecl,
        };
        let mut dec = Deconstructors {
            skip_output: self
                .class_members
                .values()
                .flatten()
                .filter(|m| m.kind == MemberKind::Constructor)
                .map(|m| m.rust_ident.clone())
                .collect(),
            ..Deconstructors::default()
        };
        for decl in &self.return_expand_decls {
            assert!(
                self.is_class_declared(decl.key())
                    || !decl
                        .field_list()
                        .iter()
                        .any(|f| matches!(f, LocalField::SelfField)),
                "expand_return!({k}).field_self(): `{k}` has no class declaration, so there is \
                 no Kotlin object to deliver — drop .field_self() (the type is rust-side-only) \
                 or declare the type in a package",
                k = decl.key().as_str()
            );
            dec.deconstructors.push(DeconstructorDecl {
                target: decl.rust_type().key(),
                records: self.lower_fields(registry, decl.key(), decl.field_list()),
                default: Some((DeconTarget::Output, Delivery::Callback)),
            });
        }
        // Per-fn overrides: same decl shape and name inheritance; the
        // return-type cross-check and the identity-only lowering happen in
        // `core/unfold.rs`'s `apply` (which sees the fn signatures).
        for (func, decl) in &self.fn_return_expands {
            assert!(
                self.is_class_declared(decl.key())
                    || !decl
                        .field_list()
                        .iter()
                        .any(|f| matches!(f, LocalField::SelfField)),
                "fun!({func}).expand_return(expand_return!({k}).field_self()): `{k}` has no \
                 class declaration, so there is no Kotlin object to deliver — drop \
                 .field_self() (the type is rust-side-only) or declare the type in a package",
                k = decl.key().as_str()
            );
            dec.outputs.push(OutputDecl {
                func: func.clone(),
                sel: DeconSel::Inline(self.lower_fields(registry, decl.key(), decl.field_list())),
                target: DeconTarget::Output,
                delivery: Delivery::Callback,
                declared_source: Some(decl.rust_type().key()),
            });
        }
        dec
    }

    /// The resolved Kotlin name of a binding-local field — the UNIFORM
    /// field-name precedence over the path's LAST segment: explicit
    /// `.name()`; else the class member's Kotlin name if the same fn is a
    /// `.method()` of the type; else the camel-cased fn ident.
    fn local_field_name(
        &self,
        key: &TypeKey,
        path: &syn::Path,
        name_override: &Option<String>,
    ) -> String {
        let ident = &path.segments.last().expect("non-empty path").ident;
        name_override
            .clone()
            .or_else(|| self.class_method_kotlin_name(key, ident))
            .unwrap_or_else(|| snake_to_camel(&ident.to_string()))
    }

    /// Synthesize the registry items for every binding-local fn declared on
    /// this generator (see [`Prebindgen::local_functions`]): path-built
    /// `fun!(crate::f).sig(…)` decls contribute their full stated signature;
    /// `field!("name").with(ty, path)` output fields contribute
    /// `fn <ident>(v: &Target) -> Ty`. The item body is `unimplemented!()`
    /// — never emitted, only the signature is read; the origin is the path's
    /// module prefix, so generated calls qualify exactly as declared. One fn
    /// ident may back several declarations only with an IDENTICAL
    /// synthesized signature (panic otherwise — the emitted call could not
    /// distinguish them).
    pub(crate) fn collect_local_functions(&self) -> Vec<(syn::ItemFn, String)> {
        use quote::ToTokens;
        let mut out: Vec<(syn::ItemFn, String)> = Vec::new();
        let mut seen: HashMap<syn::Ident, String> = HashMap::new();
        let mut push = |item_fn: syn::ItemFn, origin: String, out: &mut Vec<_>| {
            let ident = item_fn.sig.ident.clone();
            let sig_str = format!("{origin}::{}", item_fn.sig.to_token_stream());
            match seen.get(&ident) {
                Some(prev) if *prev == sig_str => {} // same fn, same shape
                Some(_) => panic!(
                    "binding-local fn `{ident}` is declared with two different signatures — \
                     the emitted call is `<origin>::{ident}`, so one fn = one signature"
                ),
                None => {
                    seen.insert(ident, sig_str);
                    out.push((item_fn, origin));
                }
            }
        };
        // Path-built fun! decls: the stated signature, renamed to the ident.
        for (ident, path, sig) in &self.local_fns {
            let origin = local_path_prefix(path);
            let mut sig = sig.clone();
            sig.ident = ident.clone();
            let item_fn: syn::ItemFn = syn::parse_quote! {
                #sig {
                    unimplemented!()
                }
            };
            push(item_fn, origin, &mut out);
        }
        // field! output fields: `fn <ident>(v: &Target) -> Ty`.
        let type_level = self
            .return_expand_decls
            .iter()
            .map(|d| (d.key().clone(), d.field_list()));
        let per_fn = self
            .fn_return_expands
            .iter()
            .map(|(_, d)| (d.key().clone(), d.field_list()));
        for (_key, fields) in type_level.chain(per_fn) {
            for f in fields {
                let LocalField::Local { path, sig, .. } = f else {
                    continue;
                };
                let origin = local_path_prefix(path);
                let ident = path.segments.last().expect("non-empty path").ident.clone();
                let mut sig = sig.clone();
                sig.ident = ident;
                let item_fn: syn::ItemFn = syn::parse_quote! {
                    #sig {
                        unimplemented!()
                    }
                };
                push(item_fn, origin, &mut out);
            }
        }
        out
    }

    /// Guard for binding-local fields returning an OPTIONAL BORROW: the
    /// `Option<&T>` conditional-delivery leaf rides the opaque-handle
    /// projection (nullable typed handle / boxed `Long?` on the wire), so `T`
    /// must be a declared `ptr_class`. Owned returns — `Option<String>`,
    /// scalars, handles — carry their nullability in their own converters and
    /// pass through unchecked.
    fn check_local_field_ty(&self, decl_key: &TypeKey, name: &str, sig: &syn::Signature) {
        let syn::ReturnType::Type(_, ty) = &sig.output else {
            return;
        };
        let syn::Type::Path(p) = &**ty else { return };
        if p.path.segments.last().is_none_or(|s| s.ident != "Option") {
            return;
        }
        let Some(syn::PathArguments::AngleBracketed(args)) =
            p.path.segments.last().map(|s| &s.arguments)
        else {
            return;
        };
        let Some(syn::GenericArgument::Type(syn::Type::Reference(r))) = args.args.first() else {
            return;
        };
        let inner_key = TypeKey::from_type(&r.elem);
        assert!(
            self.types.get(&inner_key).is_some_and(|c| c.is_opaque()),
            "expand_return!({}).field(… .name(\"{name}\")): an `Option<&T>` binding-local field \
             delivers a nullable typed HANDLE, so `T` must be a declared ptr_class — `{}` is \
             not; return an owned `Option<{}>` instead",
            decl_key.as_str(),
            inner_key.as_str(),
            inner_key.as_str(),
        );
    }

    /// Type keys of boundary decls (`expand_param!` / `expand_return!`,
    /// type-level and per-fn) whose type has no class declaration — the
    /// **rust-side-only** types. Unioned into [`Prebindgen::ignored_types`]
    /// so the registry treats them as acknowledged (no "skipping undeclared"
    /// warning, no direct converter requirement, no Kotlin emission).
    ///
    /// Yields each decl's own `syn::Type` beside its key: these are types a
    /// build script wrote, and the scan diagnoses their spelling before
    /// anything has classified them (#291).
    pub(crate) fn rust_side_only_types(
        &self,
    ) -> impl Iterator<Item = (TypeKey, Origin<syn::Type>)> + '_ {
        self.param_expand_decls
            .iter()
            .map(|d| (d.key(), d.rust_type()))
            .chain(
                self.return_expand_decls
                    .iter()
                    .map(|d| (d.key(), d.rust_type())),
            )
            .chain(
                self.fn_param_expands
                    .iter()
                    .map(|(_, _, d)| (d.key(), d.rust_type())),
            )
            .chain(
                self.fn_return_expands
                    .iter()
                    .map(|(_, d)| (d.key(), d.rust_type())),
            )
            .filter(|(k, _)| !self.is_class_declared(k))
            .map(|(k, t)| (k.clone(), t.clone()))
    }

    /// Function idents referenced only inside boundary decls (type-level and
    /// per-fn) — `expand_return!` field accessors and `expand_param!` variant
    /// ctors. They are called Rust-side by the generated fold/unfold code and
    /// need no extern of their own; when not otherwise declared they are
    /// unioned into [`Prebindgen::ignored_functions`] so the registry's
    /// "skipping undeclared fn" warning stays quiet.
    pub(crate) fn boundary_referenced_fns(&self) -> impl Iterator<Item = syn::Ident> + '_ {
        let ctors = self
            .param_expand_decls
            .iter()
            .map(|d| d.variants())
            .chain(self.fn_param_expands.iter().map(|(_, _, d)| d.variants()))
            .flatten()
            .filter_map(|v| match v {
                LocalVariant::Ctor(f) => Some(f.clone()),
                LocalVariant::SelfIdentity => None,
            });
        // Includes a binding-local field's synthesized fn (called by the
        // generated code, never externed, so its synthesized registry entry
        // must not trip the warning) and a value form's accessor.
        let accessors = self.field_referenced_fns().into_iter();
        // Synthesized binding-local fns from every entry form (path-built
        // fun! at fun/method/constructor/convert sites): their registry
        // entries exist only for signature reads — helper-only unless also
        // declared (the declared set is subtracted by the caller).
        let locals = self.local_fns.iter().map(|(ident, _, _)| ident.clone());
        ctors.chain(accessors).chain(locals)
    }

    /// Every function referenced as a named field in any `expand_return!`
    /// decl (type-level or per-fn) — the accessor set. Backs
    /// [`Prebindgen::accessor_functions`]: `core/unfold.rs`'s deconstructor
    /// gate requires every named record's function to be in this set
    /// (`RecordNotAccessor` otherwise), and `core/expand.rs` excludes them
    /// from parameter composition. Derived from *usage* — a function need not
    /// also be a `.method()` class member to be referenced this way.
    pub(crate) fn field_accessor_fns(&self) -> std::collections::HashSet<syn::Ident> {
        self.field_referenced_fns().into_iter().collect()
    }

    /// Every function ident referenced as a field by any `expand_return!` decl
    /// (type-level or per-fn), recursing into a value form's per-field
    /// overrides. The one walk behind both [`Self::field_accessor_fns`] and the
    /// helper-only set in [`Self::boundary_referenced_fns`] — they ask the same
    /// question of the same declarations, so a new field kind is taught to both
    /// at once.
    fn field_referenced_fns(&self) -> Vec<syn::Ident> {
        fn walk(fields: &[LocalField], out: &mut Vec<syn::Ident>) {
            for f in fields {
                match f {
                    LocalField::Named(func, _) => out.push(func.clone()),
                    // A binding-local field's synthesized fn IS an accessor —
                    // excluded from parameter composition, and acknowledged so
                    // the registry's "skipping undeclared" warning stays quiet.
                    LocalField::Local { path, .. } => out.push(
                        path.segments
                            .last()
                            .expect("validated non-empty at decl time")
                            .ident
                            .clone(),
                    ),
                    LocalField::SelfField => {}
                    // The value form's own accessor, plus whatever its
                    // per-field overrides reference.
                    LocalField::Fields(d) => {
                        out.push(d.func().clone());
                        for (_, ovr) in d.overrides() {
                            walk(ovr.field_list(), out);
                        }
                    }
                }
            }
        }
        let mut out = Vec::new();
        for fields in self
            .return_expand_decls
            .iter()
            .map(|d| d.field_list())
            .chain(self.fn_return_expands.iter().map(|(_, d)| d.field_list()))
        {
            walk(fields, &mut out);
        }
        out
    }
}

// ── Accepting the convert decl ───────────────────────────────────────────

impl JniGenBuilder {
    /// Declare a type's **canonical single-value conversion** (a
    /// [`ConvertDecl`], built with [`convert!`](prebindgen_registry::convert)): a pair of
    /// `#[prebindgen]` functions carrying one value of the type across the
    /// boundary wherever a single value is needed (params, returns,
    /// `Option`/`Vec` elements, the `Result<T, E>` success position,
    /// `data_class` fields). Applies wherever the type appears; not tied to
    /// any package. See [`ConvertDecl`] for the relation to the
    /// [`expand`](Self::expand) boundary decls.
    pub fn convert(mut self, mut decl: ConvertDecl) -> Self {
        assert!(
            decl.input_spec().is_some() || decl.output_spec().is_some(),
            "convert!({}) declares no conversions — add .input(fun!(...)) and/or \
             .output(fun!(...))",
            decl.key().as_str()
        );
        // Binding-local fn sources (`fun!(crate::f).sig(…)`) join the same
        // synthesis list as fun/method/constructor sites — after the
        // pre-pass they lower exactly like `#[prebindgen]` fn sources.
        self.decls.local_fns.append(decl.locals_mut());
        self.decls.convert_decls.push(decl);
        self
    }
}

impl Declarations {
    /// Derive the rank-0 **input** converter body for a `convert!`-declared
    /// type: `(continue_ty, exc, body)` where `continue_ty` is the conversion
    /// fn's parameter type (by value) — the composed-converter machinery
    /// chains it through that type's own converter, so the wire and the
    /// Kotlin surface derive from it. It is what [`Self::lookup_input`]
    /// answers with; signatures are read from the registry at
    /// lookup time (order-independent, and multi-source qualification via
    /// [`Self::fn_module`]).
    pub(crate) fn convert_input_body(
        &self,
        key: &TypeKey,
        registry: &impl Conversions<KotlinMeta>,
        emit: &prebindgen_registry::Emit,
    ) -> Option<(syn::Type, Option<syn::Type>, syn::Expr)> {
        let decl = self.convert_decls.iter().find(|d| d.key() == key)?;
        // The `convert!` declaration's own spelling — the key is how the decl
        // was found, not a second source for what it says (#291).
        let target = decl.rust_type().declared_spelling();
        let result = match decl.input_spec().as_ref()? {
            ConvertSpec::PrebindgenFn(f) => {
                let item_fn = registry.flat().function(&f).unwrap_or_else(|| {
                    panic!(
                        "convert!({}).input({f}): function not found among #[prebindgen] items",
                        key.as_str()
                    )
                });
                let (param_reading, by_ref) = convert_single_param(key, f, item_fn, "input");
                let param_ty = emit.spell_ty(param_reading);
                // Return: `T` (infallible) or `Result<T, E>` (fallible — E
                // routes to the caller's error handler via the exc slot).
                // Off `TypeKind::Fallible`, where `result_ok_type` /
                // `result_err_type` each found the `Result` in a path.
                let (ok_ty, exc) = match item_fn.ret.fallible_parts() {
                    Some((ok, err)) => (emit.spell_ty(ok), Some(emit.spell_ty(err))),
                    None => (emit.spell_ty(&item_fn.ret), None),
                };
                assert!(
                    TypeKey::from_type(&ok_ty) == *key,
                    "convert!({k}).input({f}): the function produces `{got}`, not `{k}`",
                    k = key.as_str(),
                    got = TypeKey::from_type(&ok_ty).as_str()
                );
                let module = self.fn_module(registry, f);
                let body: syn::Expr = if by_ref {
                    syn::parse_quote!(#module::#f(&v))
                } else {
                    syn::parse_quote!(#module::#f(v))
                };
                Some((param_ty, exc, body))
            }
            // `Into`/`TryInto` impls: the repr is stated in the decl; the
            // fully-qualified call form pins both type parameters so the
            // right impl is selected regardless of what else is in scope.
            ConvertSpec::Trait { repr, fallible } => {
                if *fallible {
                    let exc: syn::Type = syn::parse_quote!(
                        <#repr as ::core::convert::TryInto<#target>>::Error
                    );
                    let body: syn::Expr = syn::parse_quote!(
                        <#repr as ::core::convert::TryInto<#target>>::try_into(v)
                    );
                    Some((repr.clone(), Some(exc), body))
                } else {
                    let body: syn::Expr = syn::parse_quote!(
                        <#repr as ::core::convert::Into<#target>>::into(v)
                    );
                    Some((repr.clone(), None, body))
                }
            } // Binding-local callable: emitted verbatim (multi-segment paths
              // pass the qualification visitor untouched). With a declared
              // error type the fn returns `Result<T, E>` — emitted as-is, `E`
              // riding the standard exc slot.
        };
        let (repr, exc, body) = result?;
        Some(self.apply_input_domain(decl, repr, exc, body))
    }

    /// Output-direction peer of [`Self::convert_input_body`]: the conversion
    /// fn takes `&T` (or `T`) and returns the continue type.
    pub(crate) fn convert_output_body(
        &self,
        key: &TypeKey,
        registry: &impl Conversions<KotlinMeta>,
        emit: &prebindgen_registry::Emit,
    ) -> Option<(syn::Type, Option<syn::Type>, syn::Expr)> {
        let decl = self.convert_decls.iter().find(|d| d.key() == key)?;
        // The `convert!` declaration's own spelling — the key is how the decl
        // was found, not a second source for what it says (#291).
        let target = decl.rust_type().declared_spelling();
        let result = match decl.output_spec().as_ref()? {
            ConvertSpec::PrebindgenFn(g) => {
                let item_fn = registry.flat().function(&g).unwrap_or_else(|| {
                    panic!(
                        "convert!({}).output({g}): function not found among #[prebindgen] items",
                        key.as_str()
                    )
                });
                let (param_reading, by_ref) = convert_single_param_any(g, item_fn);
                assert!(
                    param_reading.key() == *key,
                    "convert!({k}).output({g}): the function takes `{got}`, not `{k}`",
                    k = key.as_str(),
                    got = param_reading.key().as_str()
                );
                let (repr, exc) = match item_fn.ret.fallible_parts() {
                    Some((ok, err)) => (emit.spell_ty(ok), Some(emit.spell_ty(err))),
                    None => (emit.spell_ty(&item_fn.ret), None),
                };
                assert!(
                    TypeKey::from_type(&repr) != *key,
                    "convert!({k}).output({g}): the function must return the converted form, \
                     not `{k}`",
                    k = key.as_str()
                );
                let module = self.fn_module(registry, g);
                let body: syn::Expr = if by_ref {
                    syn::parse_quote!(#module::#g(&v))
                } else {
                    syn::parse_quote!(#module::#g(v))
                };
                Some((repr, exc, body))
            }
            ConvertSpec::Trait { repr, fallible } => {
                if *fallible {
                    let exc: syn::Type = syn::parse_quote!(
                        <#target as ::core::convert::TryInto<#repr>>::Error
                    );
                    let body: syn::Expr = syn::parse_quote!(
                        <#target as ::core::convert::TryInto<#repr>>::try_into(v)
                    );
                    Some((repr.clone(), Some(exc), body))
                } else {
                    let body: syn::Expr = syn::parse_quote!(
                        <#target as ::core::convert::Into<#repr>>::into(v)
                    );
                    Some((repr.clone(), None, body))
                }
            }
        };
        let (repr, exc, body) = result?;
        Some(self.apply_output_domain(decl, repr, exc, body))
    }

    /// Idents of every `#[prebindgen]`-fn conversion source — scanned as
    /// helper functions ([`Prebindgen::helper_functions`]) so their extern
    /// emission is suppressed. Trait/local-fn sources have no registry item.
    fn apply_input_domain(
        &self,
        decl: &ConvertDecl,
        repr: syn::Type,
        exc: Option<syn::Type>,
        body: syn::Expr,
    ) -> (syn::Type, Option<syn::Type>, syn::Expr) {
        let Some(domain) = decl.domain() else {
            return (repr, exc, body);
        };
        assert_eq!(
            TypeKey::from_type(domain.ty()),
            TypeKey::from_type(&repr),
            "convert!({}): domain type {} does not match input representation {}",
            decl.key().as_str(),
            TypeKey::from_type(domain.ty()),
            TypeKey::from_type(&repr),
        );
        let valid = domain.contains_expr(quote!(v));
        let key = decl.key().as_str();
        let converted = if exc.is_some() {
            quote!((#body).map_err(|__e| {
                <__JniErr as ::core::convert::From<String>>::from(__e.to_string())
            }))
        } else {
            quote!(::core::result::Result::Ok(#body))
        };
        let body = syn::parse_quote!({
            if #valid {
                #converted
            } else {
                ::core::result::Result::Err(
                    <__JniErr as ::core::convert::From<String>>::from(
                        format!("{} representation is outside its declared domain", #key)
                    )
                )
            }
        });
        (repr, Some(syn::parse_quote!(__JniErr)), body)
    }

    fn apply_output_domain(
        &self,
        decl: &ConvertDecl,
        repr: syn::Type,
        exc: Option<syn::Type>,
        body: syn::Expr,
    ) -> (syn::Type, Option<syn::Type>, syn::Expr) {
        let Some(domain) = decl.domain() else {
            return (repr, exc, body);
        };
        assert_eq!(
            TypeKey::from_type(domain.ty()),
            TypeKey::from_type(&repr),
            "convert!({}): domain type {} does not match output representation {}",
            decl.key().as_str(),
            TypeKey::from_type(domain.ty()),
            TypeKey::from_type(&repr),
        );
        let valid = domain.contains_expr(quote!(__repr));
        let key = decl.key().as_str();
        let converted = if exc.is_some() {
            quote!((#body).map_err(|__e| {
                <__JniErr as ::core::convert::From<String>>::from(__e.to_string())
            }))
        } else {
            quote!(::core::result::Result::Ok(#body))
        };
        let body = syn::parse_quote!({
            match #converted {
                ::core::result::Result::Ok(__repr) if #valid => {
                    ::core::result::Result::Ok(__repr)
                }
                ::core::result::Result::Ok(_) => {
                    ::core::result::Result::Err(
                        <__JniErr as ::core::convert::From<String>>::from(
                            format!("{} representation is outside its declared domain", #key)
                        )
                    )
                }
                ::core::result::Result::Err(__e) => {
                    ::core::result::Result::Err(__e)
                }
            }
        });
        (repr, Some(syn::parse_quote!(__JniErr)), body)
    }

    pub(crate) fn convert_fns(&self) -> impl Iterator<Item = syn::Ident> + '_ {
        self.convert_decls
            .iter()
            .flat_map(|d| d.input_spec().iter().chain(d.output_spec().iter()))
            .filter_map(|spec| match spec {
                ConvertSpec::PrebindgenFn(f) => Some(f.clone()),
                _ => None,
            })
    }
}

/// The single typed parameter of a conversion fn, peeled of a leading `&`;
/// asserts arity 1. Returns `(peeled_type, was_by_ref)`.
fn convert_single_param_any<'f>(
    f: &syn::Ident,
    item_fn: &'f prebindgen_registry::flat::Function,
) -> (&'f TypeRef, bool) {
    assert!(
        item_fn.params.len() == 1,
        "convert fn `{f}` must take exactly one parameter, it takes {}",
        item_fn.params.len()
    );
    let ty = &item_fn.params[0].ty;
    match ty.kind() {
        flat::TypeKind::Ref { inner, .. } => (inner, true),
        _ => (ty, false),
    }
}

/// [`convert_single_param_any`] + the direction-specific error context.
fn convert_single_param<'f>(
    key: &TypeKey,
    f: &syn::Ident,
    item_fn: &'f prebindgen_registry::flat::Function,
    dir: &str,
) -> (&'f TypeRef, bool) {
    let (ty, by_ref) = convert_single_param_any(f, item_fn);
    assert!(
        ty.key() != *key,
        "convert!({k}).{dir}({f}): the function must take the converted form, not `{k}` itself",
        k = key.as_str()
    );
    (ty, by_ref)
}

impl Declarations {
    /// Build a `KotlinMeta` carrying just the value-context Kotlin name.
    /// Used by every built-in converter (primitives, structs, `Option<_>`,
    /// `Vec<_>`, `impl Fn(...)` lambdas). Errors are routed uniformly to the
    /// per-call `signal_error` sink by the extern emitter, so no
    /// per-converter exception metadata is carried.
    pub(crate) fn framework_meta(&self, kotlin_name: Option<KtType>) -> KotlinMeta {
        KotlinMeta {
            kotlin_name,
            value_rust_type: None,
            projection: None,
        }
    }

    fn conversion_domain_niches(
        &self,
        key: &TypeKey,
        registry: &impl Conversions<KotlinMeta>,
        direction: Direction,
        wire: &syn::Type,
    ) -> (Niches, Vec<String>) {
        let Some(domain) = self
            .convert_decls
            .iter()
            .find(|d| d.key() == key)
            .and_then(|d| d.domain().as_ref())
        else {
            return (Niches::empty(), Vec::new());
        };
        if TypeKey::from_type(domain.ty()).as_str() != "u64"
            || prebindgen_registry::types_util::path_tail_ident(wire)
                .is_none_or(|ident| ident != "jlong")
        {
            return (Niches::empty(), Vec::new());
        }
        let demand = registry
            .crossing_keys(direction)
            .iter()
            .map(|candidate| {
                // How many `Option` layers this crossing puts over `key` — the
                // model's count, so a wrapped spelling contributes the same
                // demand a bare one does. Walking the reading also drops the
                // re-lookup the old loop did: it peeled a spelling and re-keyed
                // each result, where the layers are already right here (#273).
                let Some(mut reading) = registry.reading(candidate) else {
                    return 0;
                };
                let mut depth = 0;
                while let Some(inner) = reading.optional_inner().cloned() {
                    reading = inner;
                    depth += 1;
                }
                if reading.key() == *key {
                    depth
                } else {
                    0
                }
            })
            .max()
            .unwrap_or(0);
        let mut slots = Vec::new();
        let mut kotlin = Vec::new();
        for value in domain.niche_values(demand) {
            let ScalarValue::U64(value) = value else {
                continue;
            };
            let raw = value as i64;
            let literal = if raw == i64::MIN {
                "Long.MIN_VALUE".to_string()
            } else {
                format!("{raw}L")
            };
            slots.push(NicheSlot {
                value: syn::parse_quote!(#raw),
                matches: syn::parse_quote!(*v == #raw),
            });
            kotlin.push(literal);
        }
        (Niches::from_slots(slots), kotlin)
    }

    fn attach_domain_sentinels(metadata: &mut KotlinMeta, sentinels: Vec<String>) {
        if let Some(projection) = metadata.projection.as_mut() {
            projection.niche_sentinels = sentinels;
        }
    }

    // ── Converter lookups (used by the Prebindgen impl) ───────────

    /// The input converter a `convert!` declaration supplies for `outer`.
    ///
    /// The body triple's middle slot carries the bound exception — `None` ⇒
    /// framework `__JniErr` with an `Ok`-wrap, `Some(<Rust type>)` ⇒
    /// `Result<ty, <Rust type>>` emitted verbatim, decided in
    /// [`Self::build_input_fn`].
    ///
    /// The closure's returned type is classified by [`is_wire_type`]:
    /// * **wire** ⇒ terminal: a single converter `wire → outer`.
    /// * **rust type** ⇒ composed: that type's input converter runs
    ///   first (`wire → ty`), then this registration's body is a
    ///   value-inspecting stage `ty → outer` (built by-value via
    ///   [`Self::build_output_fn`]) prepended to the inner chain. Defer
    ///   (`None`) if the inner converter isn't resolved yet.
    ///
    /// The type a `convert!` declaration's conversion chains through, by
    /// **identity**.
    ///
    /// The declare-time probe: `declare_into` crosses this type and records an
    /// edge to it, and both are identity uses. It used to call
    /// `convert_{input,output}_body` and throw the body away — which now would
    /// mean handing the capability to declaration code, for a spelling it
    /// discards.
    ///
    /// The representation, per direction, is what those bodies return: the
    /// input fn's **parameter** (what the wire hands in), the output fn's
    /// **return** (what the wire gets back), and for a `Trait` spec the `repr`
    /// the declaration states outright.
    ///
    /// A `TypeKey` is a normalized type, so re-parsing one is exactly what
    /// `cross` canonicalizes to anyway.
    pub(crate) fn convert_target(
        &self,
        key: &TypeKey,
        registry: &impl Conversions<KotlinMeta>,
        dir: Direction,
    ) -> Option<syn::Type> {
        let decl = self.convert_decls.iter().find(|d| d.key() == key)?;
        let spec = match dir {
            Direction::Input => decl.input_spec().as_ref()?,
            Direction::Output => decl.output_spec().as_ref()?,
        };
        match spec {
            ConvertSpec::Trait { repr, .. } => Some(repr.clone()),
            ConvertSpec::PrebindgenFn(f) => {
                let item_fn = registry.flat().function(f)?;
                let reading = match dir {
                    Direction::Input => convert_single_param_any(f, item_fn).0,
                    Direction::Output => item_fn
                        .ret
                        .fallible_parts()
                        .map_or(&item_fn.ret, |(ok, _)| ok),
                };
                syn::parse_str(reading.key().as_str()).ok()
            }
        }
    }

    pub(crate) fn lookup_input(
        &self,
        outer: &prebindgen_registry::flat::TypeRef,
        registry: &impl Conversions<KotlinMeta>,
        emit: &prebindgen_registry::Emit,
    ) -> Option<ConverterImpl<KotlinMeta>> {
        // A `convert!`-declared conversion is the only thing that answers here.
        // There was a wildcard-pattern table beside it; nothing ever wrote to
        // the input half, so every lookup through it returned `None`.
        let key = outer.key();
        let (ty, exc_ty, body) = self.convert_input_body(&key, registry, emit)?;
        // The closure's middle slot carries the `Result`'s raw Rust error
        // type (or `None` for the framework `__JniErr`); it feeds the
        // converter signature `Result<_, E>` directly — no registration.
        let exc = exc_ty.as_ref();
        // Terminal vs composed: `ty` is composed iff it's a *distinct*
        // rust type with its own input converter. The self-check guards
        // the void/identity case, and the registered-converter probe
        // distinguishes a rust continue-type (compose) from a wire
        // (terminal) without forcing `()` either way. A non-wire `ty` that
        // isn't yet resolved defers.
        let outer_node: syn::Type = {
            let spelled = emit.spell(outer);
            syn::parse_quote!(#spelled)
        };
        let is_self = TypeKey::from_type(&ty) == outer.key();
        let inner = if is_self {
            None
        } else {
            registry
                .reading_of(&ty)
                .and_then(|tr| registry.input_entry(&tr))
        };
        match inner {
            None if is_self || is_wire_type(&ty) => {
                // Terminal: `ty` is the wire; the body produces `outer`.
                let kotlin_name = self
                    .types
                    .get(&key)
                    .and_then(|c| c.name_spec.as_ref())
                    .map(|s| KtType::cls(self.fqn_of(s)))
                    .or_else(|| kotlin_for_wire(&ty));
                let niches = Niches::empty();
                Some(ConverterImpl {
                    subs: vec![],
                    pre_stages: vec![],
                    function: self.build_input_fn_of(outer, &ty, &body, exc, emit),
                    destination: ty,
                    niches,
                    metadata: KotlinMeta {
                        kotlin_name,
                        value_rust_type: None,
                        // Terminal: body produces the wire directly, no inner
                        // converter composed, so no handle to carry.
                        projection: None,
                    },
                })
            }
            // Non-wire `ty` whose converter isn't resolved yet — defer.
            None => None,
            Some(inner) => {
                // Composed: `ty` is the inner source rust type. Its input
                // converter (`wire → ty`) is the wire-facing function;
                // this body is a stage `ty → outer` that runs after it.
                // The stage takes the inner-produced value BY VALUE and
                // yields `outer`, i.e. the same shape an output converter
                // has — so it's built with `build_output_fn`.
                let stage = Stage {
                    // `outer` sits in the WIRE slot here: the stage yields it
                    // from `ty`, so it is spelled into the signature rather
                    // than classified.
                    function: self.build_output_fn(&ty, &outer_node, &body, exc),
                    metadata: KotlinMeta::default(),
                };
                let mut pre_stages = vec![stage];
                pre_stages.extend(inner.pre_stages.iter().cloned());
                let kotlin_name = inner.metadata.kotlin_name.clone();
                let value_rust_type = None;
                let (niches, sentinels) = self.conversion_domain_niches(
                    &key,
                    registry,
                    Direction::Input,
                    &inner.destination,
                );
                let mut metadata = KotlinMeta {
                    kotlin_name,
                    value_rust_type,
                    projection: inner.metadata.projection.clone(),
                };
                Self::attach_domain_sentinels(&mut metadata, sentinels);
                Some(ConverterImpl {
                    subs: vec![],
                    function: inner.function.clone(),
                    destination: inner.destination.clone(),
                    pre_stages,
                    niches,
                    metadata,
                })
            }
        }
    }

    /// Look up a registered output converter for `pat` with `args`
    /// substituted into its `_` slots. Mirror of [`Self::lookup_input`].
    ///
    /// The closure's returned type is classified by [`is_wire_type`]:
    /// * **wire** ⇒ terminal: a single converter `outer → wire`,
    ///   returning `Result<wire, err>` (throwing iff exc is set).
    /// * **rust type** ⇒ composed: this body is a value-inspecting stage
    ///   `outer → ty` prepended to `ty`'s own output converter chain
    ///   (e.g. `ZResult<T>` returns rust `T`, so the peel stage raises
    ///   its exception and `T`'s converter marshals the wire). Defer
    ///   (`None`) if `ty`'s converter isn't resolved yet.
    pub(crate) fn lookup_output(
        &self,
        outer: &prebindgen_registry::flat::TypeRef,
        registry: &impl Conversions<KotlinMeta>,
        emit: &prebindgen_registry::Emit,
    ) -> Option<ConverterImpl<KotlinMeta>> {
        let key = outer.key();
        let (ty, exc_ty, body) = self.convert_output_body(&key, registry, emit)?;
        self.build_output_converter(outer, None, ty, exc_ty, body, registry, emit)
    }

    /// The `Result<T, E>` output peel: the value succeeds as `T`, and `E` routes
    /// to the error sink on `Err`.
    ///
    /// This was the sole entry in a four-rank wildcard-pattern table, reached
    /// through a general unification engine. The model already calls this shape
    /// [`TypeKind::Fallible`](prebindgen_registry::flat::TypeKind::Fallible), so the
    /// engine expressed one fact the frontend states outright.
    pub(crate) fn result_peel(
        &self,
        outer: &prebindgen_registry::flat::TypeRef,
        ok: &syn::Type,
        err: &syn::Type,
        registry: &impl Conversions<KotlinMeta>,
        emit: &prebindgen_registry::Emit,
    ) -> Option<ConverterImpl<KotlinMeta>> {
        self.build_output_converter(
            outer,
            Some(ok),
            ok.clone(),
            Some(err.clone()),
            syn::parse_quote!(v),
            registry,
            emit,
        )
    }

    /// Assemble the output `ConverterImpl` from a body triple.
    ///
    /// `arg0` is the peeled inner type for a shape peel, `None` for a
    /// `convert!`-declared conversion — which is what the old `rank == 0`
    /// tested.
    #[allow(clippy::too_many_arguments)]
    fn build_output_converter(
        &self,
        outer: &prebindgen_registry::flat::TypeRef,
        arg0: Option<&syn::Type>,
        ty: syn::Type,
        exc_ty: Option<syn::Type>,
        body: syn::Expr,
        registry: &impl Conversions<KotlinMeta>,
        emit: &prebindgen_registry::Emit,
    ) -> Option<ConverterImpl<KotlinMeta>> {
        let key = outer.key();
        // The middle slot carries the `Result`'s raw Rust error type (or `None`
        // for the framework `__JniErr`).
        let exc = exc_ty.as_ref();
        // Terminal vs composed — see [`Self::lookup_input`] for the rule.
        let is_self = TypeKey::from_type(&ty) == key;
        let inner = if is_self {
            None
        } else {
            registry
                .reading_of(&ty)
                .and_then(|tr| registry.output_entry(&tr))
        };
        match inner {
            None if is_self || is_wire_type(&ty) => {
                // Terminal: `ty` is the wire; the body produces it from `outer`.
                let (kotlin_name, value_rust_type) = if let Some(a0) = arg0 {
                    registry
                        .reading_of(a0)
                        .and_then(|tr| registry.output_entry(&tr))
                        .map(|e| {
                            (
                                e.metadata.kotlin_name.clone(),
                                Some(prebindgen_registry::flat::canonical_type(a0)),
                            )
                        })
                        .unwrap_or((None, None))
                } else {
                    let kn = self
                        .types
                        .get(&key)
                        .and_then(|c| c.name_spec.as_ref())
                        .map(|s| KtType::cls(self.fqn_of(s)))
                        .or_else(|| kotlin_for_wire(&ty));
                    (kn, None)
                };
                let niches = match arg0 {
                    None => Niches::empty(),
                    Some(_) => default_niches_for_wire(&ty),
                };
                Some(ConverterImpl {
                    subs: vec![],
                    pre_stages: vec![],
                    function: self.build_output_fn_of(outer, &ty, &body, exc, emit),
                    destination: ty,
                    niches,
                    metadata: KotlinMeta {
                        kotlin_name,
                        value_rust_type,
                        // Terminal: body produces the wire directly, no inner
                        // converter composed, so no handle to carry.
                        projection: None,
                    },
                })
            }
            // Non-wire `ty` whose converter isn't resolved yet — defer.
            None => None,
            Some(inner) => {
                // Composed: `ty` is the continue rust type; chain its converter.
                let stage = Stage {
                    function: self.build_output_fn_of(outer, &ty, &body, exc, emit),
                    metadata: KotlinMeta::default(),
                };
                let mut pre_stages = vec![stage];
                pre_stages.extend(inner.pre_stages.iter().cloned());
                let kotlin_name = inner.metadata.kotlin_name.clone();
                let value_rust_type = arg0.map(prebindgen_registry::flat::canonical_type);
                let (niches, sentinels) = match arg0 {
                    None => self.conversion_domain_niches(
                        &key,
                        registry,
                        Direction::Output,
                        &inner.destination,
                    ),
                    Some(_) => (default_niches_for_wire(&inner.destination), Vec::new()),
                };
                let mut metadata = KotlinMeta {
                    kotlin_name,
                    value_rust_type,
                    projection: inner.metadata.projection.clone(),
                };
                Self::attach_domain_sentinels(&mut metadata, sentinels);
                Some(ConverterImpl {
                    subs: vec![],
                    function: inner.function.clone(),
                    destination: inner.destination.clone(),
                    pre_stages,
                    niches,
                    metadata,
                })
            }
        }
    }
}

/// Recognise the JNI **wire** shapes a converter body may return as a
/// terminal destination. Reuses the back-end's existing wire knowledge:
/// every `jni::sys::*` / `jni::objects::*` wire is recognised by
/// [`kotlin_for_wire`] (returns `Some`), plus
/// raw pointers structurally — so there is no separate wire-type
/// allowlist to keep in sync.
///
/// `()` is deliberately **not** treated as a wire here: it is ambiguous
/// (the void wire of a self-converter *and* the unit continue-type of
/// `ZResult<()>`). The terminal-vs-composed decision in
/// [`JniGenBuilder::lookup_input`] / [`JniGenBuilder::lookup_output`] resolves that
/// ambiguity via the self-check + registered-converter probe, so `()`
/// flows correctly without being force-classified here.
pub(crate) fn is_wire_type(ty: &syn::Type) -> bool {
    matches!(ty, syn::Type::Ptr(_)) || kotlin_for_wire(ty).is_some()
}

pub(crate) fn default_err_type() -> syn::Type {
    syn::parse_quote!(__JniErr)
}

/// The actual framework error type the `__JniErr` alias resolves to: the
/// E-agnostic `JniBindingError<()>` whose failures are always `JniError`
/// (binding-layer). A `Result<T, E>` return carries its own raw `E`, surfaced
/// as `UserError` at the extern's error site.
pub(crate) fn framework_error_type() -> syn::Type {
    syn::parse_quote!(::prebindgen_jni_runtime::JniBindingError<()>)
}

/// The body expression to splice into a converter `fn` returning
/// `Result<_, E>`: with `exc = None` the `body` is a bare value, so wrap
/// it `Ok(body)`; with `exc = Some(E)` the `body` already evaluates to
/// the `Result`, so emit it verbatim.
pub(crate) fn body_for_exc(body: &syn::Expr, exc: Option<&syn::Type>) -> syn::Expr {
    if exc.is_some() {
        body.clone()
    } else {
        syn::parse_quote!(Ok(#body))
    }
}