prebindgen-c 0.5.0

Experimental C / cbindgen 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
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
use prebindgen_registry::{Building, Conversions, Crossing, RegistryBuilder};

use super::{builder::callback_fn_type, *};

/// Per-category **input** terminal converter builders. Each returns
/// `Some(ConverterImpl)` only for the type category it claims (and `None`
/// otherwise); [`Prebindgen::on_input_type`] chains them in priority order
/// before the wrapper shapes. The categories are mutually exclusive, so the
/// chain's fall-through is equivalent to a sequential `if … return` block.
impl CbindgenBuilder {
    /// Opaque handle, by-value consume: `*Box::from_raw(v)` — fallible (null
    /// handle → message). The wire is the bare handle pointer `*mut #c_struct`.
    pub(crate) fn in_opaque_handle(&self, ty: &TypeRef) -> Option<ConverterImpl<()>> {
        let key = ty.key();
        if !self.opaque.contains_key(&key) {
            return None;
        }
        let name = Self::in_name_of(&ty.key());
        let c_struct = self.c_type_ident(&ty.key());
        let src = self.src_ty_of(&ty.key());
        let short = type_short(&ty.key());
        let null_msg = format!("null {short} handle passed by value");
        let function: syn::ItemFn = syn::parse_quote!(
            #[allow(non_snake_case, unused_variables, dead_code)]
            pub(crate) unsafe fn #name(
                v: *mut #c_struct,
            ) -> ::core::result::Result<#src, ::std::string::String> {
                if v.is_null() {
                    return ::core::result::Result::Err(
                        ::std::string::String::from(#null_msg),
                    );
                }
                ::core::result::Result::Ok(*::std::boxed::Box::from_raw(v as *mut #src))
            }
        );
        Some(ConverterImpl {
            subs: vec![],
            destination: syn::parse_quote!(*mut #c_struct),
            function,
            pre_stages: vec![],
            niches: Niches::empty(),
            metadata: (),
        })
    }

    /// Data struct: decode each field from its C wire — infallible.
    pub(crate) fn in_data_struct(
        &self,
        ty: &TypeRef,
        r: &impl Conversions<()>,
    ) -> Option<ConverterImpl<()>> {
        let key = ty.key();
        if !self.data.contains_key(&key) {
            return None;
        }
        let fields = self.struct_fields(r, &ty.key())?;
        let name = Self::in_name_of(&ty.key());
        let c_struct = self.c_type_ident(&ty.key());
        let src = self.src_ty_of(&ty.key());
        let mut inits: Vec<TokenStream> = Vec::new();
        let mut subs: Vec<TypeKey> = Vec::new();
        let mut fallible = false;
        for (fname, fty) in &fields {
            if r_is_string(fty) {
                inits.push(quote!(#fname: if v.#fname.is_null() {
                    ::std::string::String::new()
                } else {
                    ::std::ffi::CStr::from_ptr(v.#fname).to_string_lossy().into_owned()
                }));
            } else if self.tagged_unions.contains_key(&fty.key()) {
                // A sum field crosses by value as its mirror; its own converter
                // validates the tag and rebuilds the live arm, which is what
                // makes this whole decode fallible.
                let conv = Self::in_name_of(&fty.key());
                subs.push(fty.key());
                fallible = true;
                inits.push(quote!(#fname: #conv(v.#fname)?));
            } else if r_is_bool(fty) {
                // #170 instance 2: the field's wire is `MaybeUninit<bool>`, so
                // the byte C wrote is normalised here — a Rust `bool` never
                // holds it unchecked.
                let read = bool_in_expr(quote!(v.#fname));
                inits.push(quote!(#fname: #read));
            } else {
                inits.push(quote!(#fname: v.#fname));
            }
        }
        // Only a union field can fail; a struct of strings and scalars keeps
        // its infallible signature (and its callers keep theirs).
        let function: syn::ItemFn = if fallible {
            syn::parse_quote!(
                #[allow(non_snake_case, unused_variables, dead_code)]
                pub(crate) unsafe fn #name(
                    v: #c_struct,
                ) -> ::core::result::Result<#src, ::std::string::String> {
                    ::core::result::Result::Ok(#src { #(#inits),* })
                }
            )
        } else {
            syn::parse_quote!(
                #[allow(non_snake_case, unused_variables, dead_code)]
                pub(crate) unsafe fn #name(v: #c_struct) -> #src {
                    #src { #(#inits),* }
                }
            )
        };
        Some(ConverterImpl {
            subs,
            destination: syn::parse_quote!(#c_struct),
            function,
            pre_stages: vec![],
            niches: Niches::empty(),
            metadata: (),
        })
    }

    /// The mirror field idents to null in a by-value consume's gravestone write-back,
    /// for a `repr_c_struct` (`generate_mirror`) whose owned-pointer fields are all
    /// **nullable** (`Option<Box<T>>`). `Some(idents)` (possibly empty — a pure
    /// scalar/enum mirror needs no write-back) enables the cheap field-nulling path;
    /// `None` (not a generate_mirror, or a bare `Box<T>` field whose NULL would be an
    /// invalid `Box`) forces the full `gravestone()` write.
    fn nullable_owned_ptr_fields(
        &self,
        registry: &impl Conversions<()>,
        key: &TypeKey,
    ) -> Option<Vec<syn::Ident>> {
        let cfg = self.value_opaque.get(key)?;
        if !cfg.generate_mirror {
            return None;
        }
        let mut idents = Vec::new();
        for (fname, fty) in self.struct_fields(registry, key)? {
            // An owned-pointer field is one whose mirror wire is a raw pointer
            // (`Option<Box<T>>` / `Box<T>` → `*mut t_t`); scalars/enums are not.
            if matches!(self.mirror_field_wire(fty), Some(syn::Type::Ptr(_))) {
                // Bare `Box<T>`: cannot be nulled (an invalid `Box`).
                fty.optional_inner()?;
                idents.push(fname);
            }
        }
        Some(idents)
    }

    /// The gravestone write-back statements for a by-value **consume** / `_take` of a
    /// value-opaque type, writing into the slot pointed to by `slot` (a `*mut #opaque`).
    /// `None` ⇒ no write-back needed (plain data — the moved-from bitwise copy drops
    /// harmlessly). Owned-ness is **inferred** for a `repr_c_struct` mirror (the
    /// generator knows the fields): nullable owned-pointer fields are nulled in place
    /// (cheap, no `Default`); a bare `Box<T>` field falls back to the full `gravestone()`
    /// write. A non-mirror (`opaque_data_struct`/`opaque_owned_struct`) uses its explicit
    /// declared `kind` (its fields are an opaque blob the generator can't introspect).
    fn value_opaque_writeback(
        &self,
        registry: &impl Conversions<()>,
        key: &TypeKey,
        slot: &syn::Ident,
    ) -> Option<TokenStream> {
        let cfg = self.value_opaque.get(key)?;
        let opaque = &cfg.opaque;
        if cfg.generate_mirror {
            match self.nullable_owned_ptr_fields(registry, key) {
                // No owned-pointer fields ⇒ plain data, nothing to clean up.
                Some(fields) if fields.is_empty() => None,
                // All owned-pointer fields nullable ⇒ null them in place (drop-safe).
                Some(fields) => Some(quote!(#( (*#slot).#fields = ::core::ptr::null_mut(); )*)),
                // Bare `Box<T>` field ⇒ a NULL would be an invalid `Box`; full gravestone.
                None => Some(
                    quote!(::core::ptr::write(#slot, <#opaque as ::prebindgen_c_runtime::Gravestone>::gravestone());),
                ),
            }
        } else {
            // Non-mirror opaque: the consumer chose the kind explicitly.
            match cfg.kind {
                OpaqueKind::Owned => Some(
                    quote!(::core::ptr::write(#slot, <#opaque as ::prebindgen_c_runtime::Gravestone>::gravestone());),
                ),
                OpaqueKind::Data => None,
            }
        }
    }

    /// Whether the auto-generated `Gravestone` impl is needed for a `repr_c_struct`
    /// mirror: only when its consume/`_take` write-back uses `gravestone()` — i.e. it
    /// has a bare `Box<T>` owned-pointer field (a null `Box` is invalid). Nullable
    /// (`Option<Box<T>>`) mirrors null in place and need no `Gravestone`/`Default`;
    /// non-mirror owned types get their `Gravestone` impl from the consumer.
    fn mirror_needs_gravestone_impl(&self, registry: &Registry<()>, key: &TypeKey) -> bool {
        match self.value_opaque.get(key) {
            Some(cfg) if cfg.generate_mirror => {
                self.nullable_owned_ptr_fields(registry, key).is_none()
            }
            _ => false,
        }
    }

    /// Inline-opaque, by-`*mut` consume: read the live Rust value out by
    /// transmute (move). For an `opaque_owned_struct` type, write a gravestone back so a
    /// later `_drop` is a no-op (safe drop-after-move); an `opaque_data_struct` type
    /// owns no external resource, so the moved-from bitwise duplicate is
    /// harmlessly droppable and no write-back is needed. Only the C pointer is
    /// null-checked — NULL ⇒ Err, and the `Option<_>` wrapper maps a NULL pointer
    /// wire → None. (We do NOT reject gravestone values: for types whose
    /// gravestone coincides with a legitimate value — e.g. an *empty* `ZBytes` —
    /// that would wrongly reject valid inputs; the move + write-back is safe.)
    ///
    /// **Write-back optimization for a `repr_c_struct` mirror:** the generator knows
    /// the mirror's fields, so when all its owned-pointer fields are nullable
    /// (`Option<Box<T>>`) it nulls just those fields (`(*v).label = null`) instead of
    /// rebuilding+writing the whole `Default` gravestone — drop-safe (scalars are
    /// `Copy`; nulling the owned pointers prevents the double-free) and far cheaper.
    /// Non-mirror types (`opaque_owned_struct` blobs) and mirrors with a bare `Box<T>`
    /// field (NULL would be an invalid `Box`) keep the full `gravestone()` write.
    pub(crate) fn in_value_opaque(
        &self,
        ty: &TypeRef,
        registry: &impl Conversions<()>,
    ) -> Option<ConverterImpl<()>> {
        let opaque = self.value_opaque_ty_of(&ty.key())?.clone();
        let name = Self::in_name_of(&ty.key());
        let src = self.src_ty_of(&ty.key());
        let short = type_short(&ty.key());
        let null_msg = format!("null {short} value passed by value");
        // Owned-ness (whether to clean up the moved-from slot) is inferred from the
        // mirror's fields for a `repr_c_struct`, or the explicit kind for a non-mirror.
        let writeback = self.value_opaque_writeback(registry, &ty.key(), &format_ident!("v"));
        let function: syn::ItemFn = syn::parse_quote!(
            #[allow(non_snake_case, unused_variables, dead_code)]
            pub(crate) unsafe fn #name(
                v: *mut #opaque,
            ) -> ::core::result::Result<#src, ::std::string::String> {
                if v.is_null() {
                    return ::core::result::Result::Err(
                        ::std::string::String::from(#null_msg),
                    );
                }
                let __live = <#opaque as ::prebindgen_c_runtime::Transmute>::into_rust(
                    ::core::ptr::read(v),
                );
                #writeback
                ::core::result::Result::Ok(__live)
            }
        );
        Some(ConverterImpl {
            subs: vec![],
            destination: syn::parse_quote!(*mut #opaque),
            function,
            pre_stages: vec![],
            niches: Niches::empty(),
            metadata: (),
        })
    }

    /// Enum input: read the C-supplied discriminant as a plain integer,
    /// **validate** it, then build the source enum — fallible.
    ///
    /// A C `enum` is an `int` at the ABI, so nothing stops a caller passing a
    /// value no variant has. Taking the mirror `#[repr(C)]` enum by value would
    /// **materialise** that invalid discriminant at the boundary — undefined
    /// behaviour *before* any `match` in this converter could inspect it, which
    /// is why validating an already-materialised enum is not a fix (#158).
    ///
    /// So the wire is `::core::mem::MaybeUninit<mirror>`, which is
    /// `#[repr(transparent)]` over the mirror (identical ABI, identical C
    /// spelling — cbindgen renders `MaybeUninit<T>` as `T`) and, unlike the
    /// mirror itself, may legally hold **any** bit pattern. The discriminant is
    /// then read out as `c_int` — the representation a `#[repr(C)]` fieldless
    /// enum has by definition, asserted below — and compared against the
    /// mirror's own variants, so a `const`- or `cfg`-driven discriminant needs
    /// no generator-side evaluation. An unmatched value is a binding error
    /// through the wrapper's error channel; no Rust enum is ever constructed
    /// from it.
    pub(crate) fn in_enum(
        &self,
        ty: &TypeRef,
        r: &impl Conversions<()>,
    ) -> Option<ConverterImpl<()>> {
        let key = ty.key();
        if !self.enums.contains_key(&key) {
            return None;
        }
        let e = unit_enum(r, &ty.key())?;
        let name = Self::in_name_of(&ty.key());
        let cname = self.c_type_ident(&ty.key());
        let src = self.src_ty_of(&ty.key());
        let cname_str = cname.to_string();
        let arms = e.values.iter().map(|v| {
            let id = &v.name;
            quote!(
                if __raw == #cname::#id as ::core::ffi::c_int {
                    return ::core::result::Result::Ok(#src::#id);
                }
            )
        });
        let bad_msg = format!("invalid discriminant {{}} for `{cname_str}`");
        let size_msg = format!("`{cname_str}`: a #[repr(C)] enum must have the size of a C `int`");
        let align_msg =
            format!("`{cname_str}`: a #[repr(C)] enum must have the alignment of a C `int`");
        let function: syn::ItemFn = syn::parse_quote!(
            #[allow(non_snake_case, unused_variables, dead_code)]
            pub(crate) unsafe fn #name(
                v: ::core::mem::MaybeUninit<#cname>,
            ) -> ::core::result::Result<#src, ::std::string::String> {
                const _: () = {
                    assert!(
                        ::core::mem::size_of::<#cname>()
                            == ::core::mem::size_of::<::core::ffi::c_int>(),
                        #size_msg
                    );
                    assert!(
                        ::core::mem::align_of::<#cname>()
                            == ::core::mem::align_of::<::core::ffi::c_int>(),
                        #align_msg
                    );
                };
                let __raw: ::core::ffi::c_int =
                    ::core::ptr::read(v.as_ptr() as *const ::core::ffi::c_int);
                #(#arms)*
                ::core::result::Result::Err(::std::format!(#bad_msg, __raw))
            }
        );
        Some(ConverterImpl {
            subs: vec![],
            destination: syn::parse_quote!(::core::mem::MaybeUninit<#cname>),
            function,
            pre_stages: vec![],
            niches: Niches::empty(),
            metadata: (),
        })
    }

    /// `String` input: `*const c_char` → owned `String` — fallible.
    pub(crate) fn in_string(&self, ty: &TypeRef) -> Option<ConverterImpl<()>> {
        if !r_is_string(ty) {
            return None;
        }
        let name = Self::in_name_of(&ty.key());
        let function: syn::ItemFn = syn::parse_quote!(
            #[allow(non_snake_case, unused_variables, dead_code)]
            pub(crate) unsafe fn #name(
                v: *const ::core::ffi::c_char,
            ) -> ::core::result::Result<::std::string::String, ::std::string::String> {
                if v.is_null() {
                    return ::core::result::Result::Err(
                        ::std::string::String::from("null pointer passed for String argument"),
                    );
                }
                match ::std::ffi::CStr::from_ptr(v).to_str() {
                    ::core::result::Result::Ok(s) => {
                        ::core::result::Result::Ok(s.to_owned())
                    }
                    ::core::result::Result::Err(_) => {
                        ::core::result::Result::Err(
                            ::std::string::String::from("invalid UTF-8 in String argument"),
                        )
                    }
                }
            }
        );
        Some(ConverterImpl {
            subs: vec![],
            destination: syn::parse_quote!(*const ::core::ffi::c_char),
            function,
            pre_stages: vec![],
            niches: Niches::empty(),
            metadata: (),
        })
    }

    /// Bare `str` never crosses the C ABI directly, but resolving `&str`
    /// inputs requires its inner node to have a filled rank-0 cell.
    pub(crate) fn in_str(&self, ty: &TypeRef) -> Option<ConverterImpl<()>> {
        if !r_is_str(ty) {
            return None;
        }
        let name = Self::in_name_of(&ty.key());
        let function: syn::ItemFn = syn::parse_quote!(
            #[allow(non_snake_case, dead_code, unused_variables)]
            pub(crate) fn #name() {}
        );
        Some(ConverterImpl {
            subs: vec![],
            destination: syn::parse_quote!(*const ::core::ffi::c_char),
            function,
            pre_stages: vec![],
            niches: Niches::empty(),
            metadata: (),
        })
    }

    /// `bool` input: the one scalar that is **not** a pass-through (#170).
    ///
    /// A `bool` parameter is the broadest place C hands over a byte that no
    /// Rust `bool` may hold, so it crosses as [`bool_wire`] and is normalised
    /// by [`bool_in_expr`] before a `bool` exists. The C prototype is
    /// unchanged — cbindgen simplifies `MaybeUninit<T>` to `T`.
    pub(crate) fn in_bool(&self, ty: &TypeRef) -> Option<ConverterImpl<()>> {
        if !r_is_bool(ty) {
            return None;
        }
        let name = Self::in_name_of(&ty.key());
        let wire = bool_wire();
        let read = bool_in_expr(quote!(v));
        let function: syn::ItemFn = syn::parse_quote!(
            #[allow(non_snake_case, unused_variables, dead_code)]
            pub(crate) unsafe fn #name(v: #wire) -> bool {
                #read
            }
        );
        Some(ConverterImpl {
            subs: vec![],
            destination: wire,
            function,
            pre_stages: vec![],
            niches: Niches::empty(),
            metadata: (),
        })
    }

    /// FFI-safe scalar (integers, floats): identity pass-through. `bool` is
    /// claimed earlier by [`Self::in_bool`] and never reaches here.
    pub(crate) fn in_scalar(&self, ty: &TypeRef) -> Option<ConverterImpl<()>> {
        if !r_is_scalar(ty) || r_is_bool(ty) {
            return None;
        }
        let name = Self::in_name_of(&ty.key());
        // A scalar's spelling is its name, so this needs no captured syntax.
        let spelled = scalar_ty(ty)?;
        let function: syn::ItemFn = syn::parse_quote!(
            #[allow(non_snake_case, unused_variables, dead_code)]
            pub(crate) fn #name(v: #spelled) -> #spelled {
                v
            }
        );
        Some(ConverterImpl {
            subs: vec![],
            destination: spelled.clone(),
            function,
            pre_stages: vec![],
            niches: Niches::empty(),
            metadata: (),
        })
    }
}

/// Per-section [`CbindgenBuilder::prerequisites`] emitters. Each returns the runtime-
/// support items for one concern; the trait method concatenates them in order,
/// so the emitted preamble is identical to the former single function.
impl CbindgenBuilder {
    /// C allocator extern + raw C-string allocator + the universal memory freer.
    /// Emitted when the layer hands `char*`/array memory to C. Panics if such
    /// memory is produced but no `.free_memory_function` is declared.
    fn prereq_alloc_free(&self, registry: &Registry<()>, produces_array: bool) -> Vec<syn::Item> {
        let mut items: Vec<syn::Item> = Vec::new();
        if !(self.needs_free(registry) || produces_array) {
            return items;
        }
        let free_ident = match &self.free_fn {
            Some(name) => format_ident!("{}", name),
            None => panic!(
                "Cbindgen: the generated layer hands `char*` string memory to C \
                 (a `String` return or a `String` data-struct field) but no \
                 memory-freeing function is declared — add \
                 `.free_memory_function(\"z_free\")`"
            ),
        };
        // C allocator (linked from the C runtime; no crate dependency).
        items.push(syn::parse_quote!(
            extern "C" {
                fn malloc(size: usize) -> *mut ::core::ffi::c_void;
                fn free(ptr: *mut ::core::ffi::c_void);
            }
        ));
        // Raw, destructor-free C-string block. `CString::new` drops interior
        // NULs so the terminator marks the true end for C consumers.
        items.push(syn::parse_quote!(
            #[allow(non_snake_case, dead_code)]
            pub(crate) fn __cbg_alloc_cstr(s: ::std::string::String) -> *mut ::core::ffi::c_char {
                let c = ::std::ffi::CString::new(s).unwrap_or_default();
                let bytes = c.as_bytes_with_nul();
                unsafe {
                    let p = malloc(bytes.len()) as *mut u8;
                    if p.is_null() {
                        return ::core::ptr::null_mut();
                    }
                    ::core::ptr::copy_nonoverlapping(bytes.as_ptr(), p, bytes.len());
                    p as *mut ::core::ffi::c_char
                }
            }
        ));
        // Universal raw memory freer: type-agnostic C `free`, no length, no
        // destructor (NULL-safe via C `free`).
        items.push(syn::parse_quote!(
            #[no_mangle]
            #[allow(non_snake_case, unused_variables)]
            pub unsafe extern "C" fn #free_ident(p: *mut ::core::ffi::c_void) {
                free(p);
            }
        ));
        items
    }

    /// Array builder: copy a `Vec<W>` into a C-`malloc`'d block of `W` and
    /// return `(ptr, len)` (empty ⇒ `(NULL, 0)`). The block is freed C-side
    /// via the `z_free_array` macro (per-element drop + the universal freer).
    fn prereq_array_builder(&self, produces_array: bool) -> Vec<syn::Item> {
        let mut items: Vec<syn::Item> = Vec::new();
        if !produces_array {
            return items;
        }
        items.push(syn::parse_quote!(
            #[allow(non_snake_case, dead_code)]
            pub(crate) unsafe fn __cbg_alloc_array<W>(v: ::std::vec::Vec<W>) -> (*mut W, usize) {
                let n = v.len();
                if n == 0 {
                    return (::core::ptr::null_mut(), 0);
                }
                let p = malloc(n.wrapping_mul(::core::mem::size_of::<W>())) as *mut W;
                if p.is_null() {
                    return (::core::ptr::null_mut(), 0);
                }
                for (i, e) in v.into_iter().enumerate() {
                    ::core::ptr::write(p.add(i), e);
                }
                (p, n)
            }
        ));
        items
    }

    /// Opaque handles: bare-pointer C type (`z_*_t*` = `Box::into_raw`) + typed
    /// `_drop`. The C type is an opaque/incomplete struct.
    fn prereq_opaque_handles(&self, registry: &Registry<()>) -> Vec<syn::Item> {
        let mut items: Vec<syn::Item> = Vec::new();
        for (key, _cfg) in sorted_by_key(&self.opaque) {
            // Keyed directly: this used to spell the key into tokens purely so
            // `reading_of` could re-key them, twice (#291).
            let Some(reading) = registry.reading(key) else {
                continue;
            };
            if registry.input_entry(&reading).is_none() && registry.output_entry(&reading).is_none()
            {
                continue;
            }
            let c_struct = self.c_type_ident(&reading.key());
            // Opaque/incomplete C type: the handle is `#c_struct *`, which IS the
            // `Box::into_raw` pointer to the source value.
            items.push(syn::parse_quote!(
                #[repr(C)]
                #[allow(non_camel_case_types)]
                pub struct #c_struct {
                    _private: [u8; 0],
                }
            ));
            let src = self.src_ty_of(&reading.key());
            let drop_ident = self.destructor_symbol(&reading.key());
            items.push(syn::parse_quote!(
                #[no_mangle]
                #[allow(non_snake_case, unused_variables)]
                pub unsafe extern "C" fn #drop_ident(this_: *mut #c_struct) {
                    if !this_.is_null() {
                        drop(::std::boxed::Box::from_raw(this_ as *mut #src));
                    }
                }
            ));
        }
        items
    }

    /// Data structs: `#[repr(C)]` mirror only. Heap (`String`) fields are
    /// `char*` raw blocks the C user releases individually via the
    /// `free_memory_function` — no per-struct destructor.
    fn prereq_data_structs(&self, registry: &Registry<()>) -> Vec<syn::Item> {
        let mut items: Vec<syn::Item> = Vec::new();
        for (key, _cfg) in sorted_by_key(&self.data) {
            let Some(reading) = registry.reading(key) else {
                continue;
            };
            if registry.input_entry(&reading).is_none() && registry.output_entry(&reading).is_none()
            {
                continue;
            }
            let Some(fields) = self.struct_fields(registry, &reading.key()) else {
                continue;
            };
            let c_struct = self.c_type_ident(&reading.key());
            let mut field_defs: Vec<TokenStream> = Vec::new();
            for (fname, fty) in &fields {
                let wire = self.data_field_wire(fty).unwrap_or_else(|| {
                    panic!(
                        "Cbindgen: field `{}` of data struct `{}` has unsupported type `{}`",
                        fname,
                        type_short(&reading.key()),
                        fty
                    )
                });
                field_defs.push(quote!(pub #fname: #wire));
            }
            items.push(syn::parse_quote!(
                #[repr(C)]
                #[allow(non_camel_case_types)]
                pub struct #c_struct {
                    #(#field_defs,)*
                }
            ));
        }
        items
    }

    /// Value-opaque types: the opaque `#[repr(C, align(_))]` counterpart is
    /// defined elsewhere (e.g. a size/align probe generator). Here we emit only
    /// the fail-closed size+align equality asserts and the typed `_drop` (drops
    /// the live Rust value in place; NULL/gravestone ⇒ no-op), plus a `_take`
    /// for types delivered as takeable callback params.
    fn prereq_value_opaque(&self, registry: &Registry<()>) -> Vec<syn::Item> {
        let mut items: Vec<syn::Item> = Vec::new();
        let takeable_keys = self.takeable_type_keys();
        let mut vo: Vec<(&TypeKey, &ValueOpaqueCfg)> = self.value_opaque.iter().collect();
        vo.sort_by(|a, b| a.0.as_str().cmp(b.0.as_str()));
        for (key, cfg) in vo {
            let Some(reading) = registry.reading(key) else {
                continue;
            };
            if registry.input_entry(&reading).is_none() && registry.output_entry(&reading).is_none()
            {
                continue;
            }
            let src = self.src_ty_of(&reading.key());
            let opaque = &cfg.opaque;
            // `repr_c_struct`: the opaque counterpart is an auto-generated
            // **visible-field** `#[repr(C)]` mirror (so C reads the fields directly),
            // not an externally-provided blob. Each field is lowered by
            // `mirror_field_wire` (scalar / enum / opaque pointer). The size/align
            // assert below then proves the whole-struct reinterpret sound.
            if cfg.generate_mirror {
                let mirror_ident = self.c_type_ident(&reading.key());
                let fields = self
                    .struct_fields(registry, &reading.key())
                    .unwrap_or_else(|| {
                        panic!(
                            "Cbindgen::repr_c_struct: `{}` is not a named struct",
                            type_short(&reading.key())
                        )
                    });
                // Restricted-validity audit (#170 instance 3, #158 instance 3):
                // a mirror is reinterpreted whole, so a field whose Rust type
                // rejects some bit patterns is UB the moment C writes one and
                // hands the struct back.
                //
                // Not narrowed to inbound mirrors, though only those are
                // reachable: converter reachability is not derived from use
                // today (a declared type resolves BOTH directions whether or
                // not either is called — the accounting #194/#196 replace), so
                // "does it cross in" has no truthful answer here. Over-
                // reporting is the safe direction, and the acknowledgement
                // below is the escape for a genuinely write-only mirror.
                let restricted = self.restricted_validity_fields(registry, &reading.key());
                if !restricted.is_empty() && !cfg.assume_c_field_validity {
                    let listed: Vec<String> = restricted
                        .iter()
                        .map(|(fname, reason)| format!("  `{fname}`: {reason}"))
                        .collect();
                    panic!(
                        "Cbindgen::repr_c_struct: `{}` crosses C's memory by whole-struct \
                         reinterpret, but these fields have restricted-validity Rust types:\n\
                         {}\n\
                         A C caller can write a byte outside those domains, and the reinterpret \
                         materialises it with no hook to normalise or validate it first (#170, \
                         #158). Move the field to a `data_struct` (per-field wires), pass it as \
                         a separate parameter, or widen it to an integer. If this binding's C \
                         side is trusted to write only in-domain bytes — or never hands the \
                         mirror back at all — acknowledge it with `.assume_c_field_validity()`.",
                        type_short(&reading.key()),
                        listed.join("\n"),
                    );
                }
                let field_defs: Vec<TokenStream> = fields
                    .iter()
                    .map(|(fname, fty)| {
                        let wire = self.mirror_field_wire(fty).unwrap_or_else(|| {
                            panic!(
                                "Cbindgen::repr_c_struct: field `{}` of `{}` has unsupported \
                                 type `{}` (expected a scalar, a declared `enum_type`, or an \
                                 opaque pointer `Option<Box<T>>`/`Box<T>` with `T` an `opaque_ptr`)",
                                fname,
                                type_short(&reading.key()),
                                fty
                            )
                        });
                        quote!(pub #fname: #wire)
                    })
                    .collect();
                items.push(syn::parse_quote!(
                    #[repr(C)]
                    #[allow(non_camel_case_types)]
                    pub struct #mirror_ident {
                        #(#field_defs,)*
                    }
                ));
                // A mirror that needs `gravestone()` (only the bare-`Box<T>` fallback —
                // nullable owned-pointer fields are nulled in place) gets an
                // auto-generated `Gravestone` from the source type's `Default`. Nullable
                // mirrors emit nothing here, so they impose no `Default` requirement.
                if self.mirror_needs_gravestone_impl(registry, &reading.key()) {
                    items.push(syn::parse_quote!(
                        impl ::prebindgen_c_runtime::Gravestone for #mirror_ident {
                            #[inline]
                            fn rust_gravestone() -> #src {
                                <#src as ::core::default::Default>::default()
                            }
                        }
                    ));
                }
            }
            // Fail-closed size/align equality guard (proves the transmute sound).
            items.push(syn::parse_quote!(
                const _: () = {
                    assert!(
                        ::core::mem::size_of::<#src>() == ::core::mem::size_of::<#opaque>(),
                        "value_opaque: Rust type and opaque counterpart differ in size"
                    );
                    assert!(
                        ::core::mem::align_of::<#src>() == ::core::mem::align_of::<#opaque>(),
                        "value_opaque: Rust type and opaque counterpart differ in alignment"
                    );
                };
            ));
            // Autogenerated transmute glue: the single place that owns the
            // unsafe rust<->opaque reinterpretation. `Gravestone` (user logic)
            // and the converters below are all expressed via these methods.
            items.push(syn::parse_quote!(
                impl ::prebindgen_c_runtime::Transmute for #opaque {
                    type Rust = #src;
                    #[inline]
                    fn from_rust(value: Self::Rust) -> Self {
                        let __v = ::core::mem::ManuallyDrop::new(value);
                        unsafe {
                            ::core::ptr::read(&*__v as *const Self::Rust as *const Self)
                        }
                    }
                    #[inline]
                    fn into_rust(self) -> Self::Rust {
                        let __v = ::core::mem::ManuallyDrop::new(self);
                        unsafe {
                            ::core::ptr::read(&*__v as *const Self as *const Self::Rust)
                        }
                    }
                    #[inline]
                    fn as_rust(&self) -> &Self::Rust {
                        unsafe { &*(self as *const Self as *const Self::Rust) }
                    }
                    #[inline]
                    fn as_rust_mut(&mut self) -> &mut Self::Rust {
                        unsafe { &mut *(self as *mut Self as *mut Self::Rust) }
                    }
                }
            ));
            let drop_ident = self.destructor_symbol(&reading.key());
            // Unconditional drop: safe because a moved-from slot holds a
            // gravestone (a valid, safely-droppable empty value), so dropping
            // it is a harmless no-op; a live slot drops normally.
            items.push(syn::parse_quote!(
                #[no_mangle]
                #[allow(non_snake_case, unused_variables)]
                pub unsafe extern "C" fn #drop_ident(this_: *mut #opaque) {
                    if !this_.is_null() {
                        ::core::ptr::drop_in_place(
                            <#opaque as ::prebindgen_c_runtime::Transmute>::as_rust_mut(&mut *this_),
                        );
                    }
                }
            ));
            // For a type delivered as a takeable callback param, also emit a
            // public `<base>_take(dst, src)`: move `src`'s value into `dst`. For
            // an `opaque_owned_struct` type, leave `src` a gravestone (so the
            // trampoline's post-call drop is a no-op); an `opaque_data_struct` type owns
            // nothing, so the leftover bitwise copy in `src` drops harmlessly and
            // no write-back is needed. This is the C user's "take" operation.
            if takeable_keys.contains(key) {
                let take_ident = self.take_symbol(&reading.key());
                // Same inferred write-back as a consume (field-null for a nullable
                // mirror, `gravestone()` for a bare-`Box` mirror / non-mirror owned).
                let writeback =
                    self.value_opaque_writeback(registry, &reading.key(), &format_ident!("src"));
                items.push(syn::parse_quote!(
                    #[no_mangle]
                    #[allow(non_snake_case, unused_variables)]
                    pub unsafe extern "C" fn #take_ident(
                        dst: *mut #opaque,
                        src: *mut #opaque,
                    ) {
                        if dst.is_null() || src.is_null() {
                            return;
                        }
                        ::core::ptr::write(dst, ::core::ptr::read(src));
                        #writeback
                    }
                ));
            }
        }
        items
    }

    /// Enums: `#[repr(C)]` mirror — variant idents with each discriminant
    /// **re-emitted verbatim**, exactly as the source wrote it.
    ///
    /// Deliberately NOT routed through the shared
    /// [`enum_discriminant_values`](prebindgen_registry::types_util::enum_discriminant_values).
    /// That helper resolves each variant to a concrete `i64`, which is what an
    /// adapter needs when it must *know the number* — JniGenBuilder's `jint` decode
    /// and the Kotlin `value(N)` constants. This mirror needs no number: it is
    /// Rust source that cbindgen re-reads, so passing the expression through
    /// keeps every discriminant C already accepted — a `const` or `cfg`-driven
    /// expression, and any value the source's own `repr` admits, including
    /// ones outside `i64`. Resolving here would narrow that domain to what
    /// `i64` and a literal can express, for no gain.
    ///
    /// The two adapters therefore agree on the *rule* (Rust's own assignment
    /// order, which the shared helper encodes) while differing on what they
    /// need from it — a number versus a spelling.
    fn prereq_enums(
        &self,
        registry: &Registry<()>,
        emit: &prebindgen_registry::Emit,
    ) -> Vec<syn::Item> {
        let mut items: Vec<syn::Item> = Vec::new();
        for (key, _cfg) in sorted_by_key(&self.enums) {
            let Some(reading) = registry.reading(key) else {
                continue;
            };
            if registry.input_entry(&reading).is_none() && registry.output_entry(&reading).is_none()
            {
                continue;
            }
            let Some(e) = unit_enum(registry, &reading.key()) else {
                continue;
            };
            let cname = self.c_type_ident(&reading.key());
            // The C mirror re-states the discriminant **as written** — `= 0x07`
            // stays `0x07` — which is the one consumer `EnumValue`'s retained
            // syntax exists for, and the model's own docs name it.
            let variants = e.values.iter().map(|v| {
                let id = &v.name;
                match emit.discriminant(v) {
                    Some(expr) => quote!(#id = #expr),
                    None => quote!(#id),
                }
            });
            items.push(syn::parse_quote!(
                #[repr(C)]
                #[derive(Copy, Clone, Debug, Eq, PartialEq)]
                #[allow(non_camel_case_types)]
                pub enum #cname {
                    #(#variants),*
                }
            ));
        }
        items
    }

    /// Tagged unions: the `#[repr(C)]` mirror with payload variants, which
    /// cbindgen renders as a tag enum plus a `union` of the variant bodies —
    /// the idiomatic C tagged union, with no hand-written header fragment.
    /// Variant shape is mirrored faithfully (named stays named, tuple stays
    /// tuple, unit stays unit); each payload field takes the wire chosen by
    /// [`CbindgenBuilder::payload_field_wire`].
    ///
    /// A union whose payload wires own memory also gets a typed
    /// `<base>_drop(t_t *)` that frees the **active arm** and nulls the freed
    /// slots, so a second drop is a no-op. A union of plain data owns nothing
    /// and gets no drop.
    fn prereq_tagged_unions(
        &self,
        registry: &Registry<()>,
        emit: &prebindgen_registry::Emit,
    ) -> Vec<syn::Item> {
        let mut items: Vec<syn::Item> = Vec::new();
        for (key, _cfg) in sorted_by_key(&self.tagged_unions) {
            let Some(reading) = registry.reading(key) else {
                continue;
            };
            if registry.input_entry(&reading).is_none() && registry.output_entry(&reading).is_none()
            {
                continue;
            }
            let Some(e) = payload_enum(registry, &reading.key()) else {
                continue;
            };
            let cname = self.c_type_ident(&reading.key());

            let mut variant_defs: Vec<TokenStream> = Vec::new();
            // Per-variant drop arm, collected only for variants that own
            // something; the rest fall to a single wildcard arm.
            let mut drop_arms: Vec<TokenStream> = Vec::new();
            for a in &e.alternatives {
                let vident = &a.name;
                let wires: Vec<syn::Type> = a
                    .fields
                    .iter()
                    .map(|f| self.payload_wire_of(&reading.key(), vident, f, registry))
                    .collect();
                // `Alternative::spell` writes the delimiters the source wrote,
                // which is what the three-armed `syn::Fields` match was doing —
                // and `Field::bind` decides `name: wire` or `wire` per field.
                let defs: Vec<TokenStream> = a
                    .fields
                    .iter()
                    .zip(&wires)
                    .map(|(f, w)| f.bind(w))
                    .collect();
                variant_defs.push(emit.shape(a, quote!(#vident), &defs));

                // Drop arm: bind every field, free the owning ones.
                let owning: Vec<(usize, &Field, &syn::Type)> = a
                    .fields
                    .iter()
                    .zip(&wires)
                    .enumerate()
                    .filter(|(_, (f, w))| self.payload_wire_owns(&f.ty, w, registry))
                    .map(|(i, (f, w))| (i, f, w))
                    .collect();
                if owning.is_empty() {
                    continue;
                }
                let binds: Vec<syn::Ident> = (0..a.fields.len())
                    .map(|i| format_ident!("__f{}", i))
                    .collect();
                let parts: Vec<TokenStream> = a
                    .fields
                    .iter()
                    .zip(&binds)
                    .map(|(f, b)| f.bind(b))
                    .collect();
                let pattern = emit.shape(a, quote!(#cname::#vident), &parts);
                let frees = owning.iter().map(|(i, f, _)| {
                    let b = &binds[*i];
                    self.payload_free_stmt(&f.ty, b, registry)
                });
                drop_arms.push(quote!(#pattern => { #(#frees)* }));
            }

            items.push(syn::parse_quote!(
                #[repr(C)]
                #[allow(non_camel_case_types)]
                pub enum #cname {
                    #(#variant_defs),*
                }
            ));

            // The same predicate a CONTAINING struct uses to decide whether to
            // call this drop, so a nested union can never be freed through a
            // symbol that was not emitted.
            if self.tagged_union_has_drop(&reading, registry) {
                debug_assert!(!drop_arms.is_empty(), "has_drop implies an owning arm");
                let drop_ident = self.destructor_symbol(&reading.key());
                // The drop is a second C entry point into the same bytes, so it
                // owes the same tag check as the input converter — `&mut *this_`
                // on an out-of-range tag would be the very UB that check exists
                // to prevent. It emits that check from the same place, and,
                // having nowhere to report to, ignores the value (there is no
                // live arm to release), which keeps `_drop` the always-safe
                // no-op it is everywhere else.
                let tag_guard = self.tag_guard(
                    &cname,
                    e.alternatives.len(),
                    quote!((*this_)),
                    quote!(return;),
                );
                items.push(syn::parse_quote!(
                    #[no_mangle]
                    #[allow(non_snake_case, unused_variables)]
                    pub unsafe extern "C" fn #drop_ident(
                        this_: *mut ::core::mem::MaybeUninit<#cname>,
                    ) {
                        if this_.is_null() {
                            return;
                        }
                        #tag_guard
                        match (*this_).assume_init_mut() {
                            #(#drop_arms)*
                            _ => {}
                        }
                    }
                ));
            }
        }
        items
    }

    /// The wire of one payload field, or a generation error naming the
    /// offending variant field and the supported set.
    fn payload_wire_of(
        &self,
        key: &TypeKey,
        variant: &syn::Ident,
        field: &Field,
        registry: &Registry<()>,
    ) -> syn::Type {
        self.payload_field_wire(&field.ty, registry)
            .unwrap_or_else(|reason| {
                panic!(
                    "Cbindgen::tagged_union: payload `{}::{}{}` of type `{}` cannot cross: {}",
                    type_short(key),
                    variant,
                    match &field.name {
                        Some(n) => format!(".{n}"),
                        None => String::new(),
                    },
                    field.ty,
                    reason,
                )
            })
    }

    /// Release one owning payload slot held behind `binding` (a `&mut` to the
    /// wire, from a `match &mut *this_` arm) and null it, so a second drop of
    /// the same union is a no-op. A `char *` block goes back to the C
    /// allocator; an opaque pointer is re-boxed and dropped, running the Rust
    /// destructor.
    fn payload_free_stmt(
        &self,
        fty: &TypeRef,
        binding: &syn::Ident,
        registry: &Registry<()>,
    ) -> TokenStream {
        if r_is_string(fty) {
            return quote!(
                free(*#binding as *mut ::core::ffi::c_void);
                *#binding = ::core::ptr::null_mut();
            );
        }
        // A nested `data_struct` payload crosses BY VALUE, so the arm binds the
        // mirror itself and what has to be released is each of its OWNING
        // fields — reached through the binding and nulled in place, exactly as
        // a directly-owning payload is. This is the shape zenoh-flat#30 needs
        // (`ReplyResult`'s alternatives are structs whose fields are handles),
        // and without it those fields would leak silently.
        let owning = self.owning_data_struct_fields(fty, registry);
        if !owning.is_empty() {
            let frees = owning.iter().map(|(fname, fty)| {
                if r_is_string(fty) {
                    quote!(
                        free((*#binding).#fname as *mut ::core::ffi::c_void);
                        (*#binding).#fname = ::core::ptr::null_mut();
                    )
                } else if self.tagged_union_has_drop(fty, registry) {
                    // The field is ANOTHER union, crossing by value. Its own
                    // typed drop releases whichever arm is live and nulls the
                    // slot, so this stays idempotent like every other arm here
                    // — and the owning pointer is reached even though it is two
                    // levels down. Nothing else can reach it: a union arm is not
                    // a top-level struct field the C caller releases by hand.
                    let drop_ident = self.destructor_symbol(&fty.key());
                    quote!(#drop_ident(&mut (*#binding).#fname);)
                } else {
                    // `owning_data_struct_fields` yields exactly the two shapes
                    // above (`data_field_owns`), so this is unreachable — and a
                    // silent fall-through here would be a leak, which is the
                    // defect this whole path exists to prevent.
                    panic!(
                        "Cbindgen: data-struct field `{}` of type `{}` is owning but has no \
                         release form (expected a `String` or a declared `tagged_union`)",
                        fname, fty,
                    )
                }
            });
            return quote!(#(#frees)*);
        }
        let src_inner = self.src_ty_of(&r_boxed_inner(fty).unwrap_or(fty).key());
        quote!(
            if !(*#binding).is_null() {
                drop(::std::boxed::Box::from_raw(*#binding as *mut #src_inner));
                *#binding = ::core::ptr::null_mut();
            }
        )
    }

    /// Tagged-union **input**: **validate the tag**, then `match` the C union
    /// back to the source enum, converting each arm's payload through the
    /// per-field policy. The generalization of [`Self::in_enum`] from "match
    /// idents" to "match idents and convert each arm's fields" — fallible for
    /// the same reason, and by the same rule (#158): a Rust `enum` must never
    /// be *materialised* from C-supplied bytes without checking first, because
    /// an undeclared discriminant is UB at the boundary, before any `match`.
    ///
    /// So the wire is [`::core::mem::MaybeUninit`] over the mirror. A
    /// `#[repr(C)]` enum with payload variants is laid out as a leading
    /// discriminant of a C `int` followed by the variant union, so the tag is
    /// read from the front as a plain `c_int` and range-checked against the
    /// variants (the mirror carries no explicit discriminants, so its tags are
    /// declaration order `0..N`). Only then is the value `assume_init`ed —
    /// which is sound because [`CbindgenBuilder::payload_field_wire`] makes every
    /// payload wire bit-pattern-agnostic, leaving the tag as the sole
    /// obligation.
    pub(crate) fn in_tagged_union(
        &self,
        ty: &TypeRef,
        r: &impl Conversions<()>,
        emit: &prebindgen_registry::Emit,
    ) -> Option<ConverterImpl<()>> {
        let key = ty.key();
        if !self.tagged_unions.contains_key(&key) {
            return None;
        }
        let e = payload_enum(r, &key)?;
        let name = Self::in_name_of(&ty.key());
        let cname = self.c_type_ident(&ty.key());
        let src = self.src_ty_of(&ty.key());
        // A payload that crosses through its own converter needs that converter
        // to exist before this one can call it. `subs` only drives the
        // post-resolution propagation pass, so it cannot order the build —
        // returning `None` here is the resolver's DEFERRAL protocol, and it
        // retries at the next fixed point. Without this the payload silently
        // degrades to a passthrough and the generated code does not compile.
        for a in &e.alternatives {
            for f in &a.fields {
                if self.payload_needs_converter(&f.ty) && r.input_entry(&f.ty).is_none() {
                    return None;
                }
            }
        }
        let mut subs: Vec<TypeKey> = Vec::new();
        let arms: Vec<TokenStream> = e
            .alternatives
            .iter()
            .map(|a| {
                let vident = &a.name;
                let binds: Vec<syn::Ident> = (0..a.fields.len())
                    .map(|i| format_ident!("__f{}", i))
                    .collect();
                let parts: Vec<TokenStream> = a
                    .fields
                    .iter()
                    .zip(&binds)
                    .map(|(f, b)| f.bind(b))
                    .collect();
                let from = emit.shape(a, quote!(#cname::#vident), &parts);
                let exprs: Vec<TokenStream> = a
                    .fields
                    .iter()
                    .zip(&binds)
                    .map(|(f, b)| {
                        // Every payload that crosses through a converter of its
                        // own — a declared `enum_type`, a nested `data_struct`,
                        // an opaque handle, a converted leaf — is a resolver
                        // dependency, so its converter exists before this one is
                        // emitted. Without it the payload silently falls back to
                        // a passthrough and the generated code does not compile.
                        if self.payload_needs_converter(&f.ty) {
                            subs.push(f.ty.key());
                        }
                        self.payload_in_expr(&f.ty, b, r)
                    })
                    .collect();
                let inits: Vec<TokenStream> = a
                    .fields
                    .iter()
                    .zip(&exprs)
                    .map(|(f, e)| f.bind(e))
                    .collect();
                let to = emit.shape(a, quote!(#src::#vident), &inits);
                quote!(#from => #to,)
            })
            .collect();
        let bad_msg = format!(
            "invalid tag {{}} for `{cname}` (expected 0..{})",
            e.alternatives.len()
        );
        let tag_guard = self.tag_guard(
            &cname,
            e.alternatives.len(),
            quote!(v),
            quote!(return ::core::result::Result::Err(::std::format!(#bad_msg, __tag));),
        );
        let function: syn::ItemFn = syn::parse_quote!(
            #[allow(non_snake_case, unused_variables, dead_code)]
            pub(crate) unsafe fn #name(
                v: ::core::mem::MaybeUninit<#cname>,
            ) -> ::core::result::Result<#src, ::std::string::String> {
                #tag_guard
                let v = v.assume_init();
                ::core::result::Result::Ok(match v { #(#arms)* })
            }
        );
        Some(ConverterImpl {
            subs,
            destination: syn::parse_quote!(::core::mem::MaybeUninit<#cname>),
            function,
            pre_stages: vec![],
            niches: Niches::empty(),
            metadata: (),
        })
    }

    /// The statements that make a C-supplied `MaybeUninit<mirror>` safe to
    /// `assume_init`: read the leading discriminant as a plain `c_int` and
    /// reject anything outside `0..variants`.
    ///
    /// `slot` is an expression for the `MaybeUninit` in scope and `on_bad` is
    /// what to do with an out-of-range tag — the **only** thing the two C entry
    /// points into these bytes differ in (the input converter returns `Err`,
    /// the typed drop returns `()` and so just bails). Passing that difference
    /// in, rather than letting the drop repeat the check inline, is what keeps
    /// the two from drifting apart.
    fn tag_guard(
        &self,
        cname: &syn::Ident,
        variants: usize,
        slot: TokenStream,
        on_bad: TokenStream,
    ) -> TokenStream {
        let n = variants as i64;
        let bounds_msg = format!(
            "`{cname}`: a #[repr(C)] enum with payload variants must be at least as large as \
             its C `int` discriminant"
        );
        quote!(
            const _: () = {
                assert!(
                    ::core::mem::size_of::<#cname>()
                        >= ::core::mem::size_of::<::core::ffi::c_int>(),
                    #bounds_msg
                );
            };
            let __tag: ::core::ffi::c_int =
                ::core::ptr::read(#slot.as_ptr() as *const ::core::ffi::c_int);
            if !((__tag as i64) >= 0 && (__tag as i64) < #n) {
                #on_bad
            }
        )
    }

    /// Tagged-union **output**: `match` the source enum to the C union,
    /// converting each arm's payload. The counterpart of
    /// [`Self::in_tagged_union`]; a `String` payload is allocated here and
    /// released by the union's typed drop.
    pub(crate) fn out_tagged_union(
        &self,
        ty: &TypeRef,
        r: &impl Conversions<()>,
        emit: &prebindgen_registry::Emit,
    ) -> Option<ConverterImpl<()>> {
        let key = ty.key();
        if !self.tagged_unions.contains_key(&key) {
            return None;
        }
        let e = payload_enum(r, &key)?;
        let name = Self::out_name_of(&ty.key());
        let cname = self.c_type_ident(&ty.key());
        let src = self.src_ty_of(&ty.key());
        // Deferral, as in `in_tagged_union` — the output counterpart.
        for a in &e.alternatives {
            for f in &a.fields {
                if self.payload_needs_converter(&f.ty) && r.output_entry(&f.ty).is_none() {
                    return None;
                }
            }
        }
        let mut subs: Vec<TypeKey> = Vec::new();
        let arms: Vec<TokenStream> = e
            .alternatives
            .iter()
            .map(|a| {
                let vident = &a.name;
                let binds: Vec<syn::Ident> = (0..a.fields.len())
                    .map(|i| format_ident!("__f{}", i))
                    .collect();
                let parts: Vec<TokenStream> = a
                    .fields
                    .iter()
                    .zip(&binds)
                    .map(|(f, b)| f.bind(b))
                    .collect();
                let from = emit.shape(a, quote!(#src::#vident), &parts);
                let exprs: Vec<TokenStream> = a
                    .fields
                    .iter()
                    .zip(&binds)
                    .map(|(f, b)| {
                        if self.payload_needs_converter(&f.ty) {
                            subs.push(f.ty.key());
                        }
                        self.payload_out_expr(&f.ty, b, r)
                    })
                    .collect();
                let inits: Vec<TokenStream> = a
                    .fields
                    .iter()
                    .zip(&exprs)
                    .map(|(f, e)| f.bind(e))
                    .collect();
                let to = emit.shape(a, quote!(#cname::#vident), &inits);
                quote!(#from => #to,)
            })
            .collect();
        // Same wire as the input direction — one mirror type serves both, and a
        // union carried through a `data_struct` field has only one field type
        // to be. Rust always writes a live arm, so nothing is validated here.
        let function: syn::ItemFn = syn::parse_quote!(
            #[allow(non_snake_case, unused_variables, dead_code)]
            pub(crate) fn #name(v: #src) -> ::core::mem::MaybeUninit<#cname> {
                ::core::mem::MaybeUninit::new(match v { #(#arms)* })
            }
        );
        Some(ConverterImpl {
            subs,
            destination: syn::parse_quote!(::core::mem::MaybeUninit<#cname>),
            function,
            pre_stages: vec![],
            niches: Niches::empty(),
            metadata: (),
        })
    }

    /// One payload field, C wire → Rust value. Mirrors the `data_struct`
    /// input policy, plus the opaque-pointer and declared-enum cases the
    /// mirror wire allows.
    fn payload_in_expr(
        &self,
        fty: &TypeRef,
        b: &syn::Ident,
        registry: &impl Conversions<()>,
    ) -> TokenStream {
        if r_is_string(fty) {
            return quote!(if #b.is_null() {
                ::std::string::String::new()
            } else {
                ::std::ffi::CStr::from_ptr(#b).to_string_lossy().into_owned()
            });
        }
        if self.enums.contains_key(&fty.key()) {
            // The payload rides as `MaybeUninit<enum mirror>` and goes through
            // the same validating decode a top-level enum parameter does; an
            // out-of-range one propagates out of the union's own converter.
            let conv = Self::in_name_of(&fty.key());
            return quote!(#conv(#b)?);
        }
        // The same opaque-pointer arm the wire took, for a spelling with no
        // `Box` in it: the C caller still hands over a `*mut handle_t` it gave
        // up ownership of, so the pointer is reclaimed the same way — the value
        // is just moved out of the box instead of kept in one. Conversion
        // follows the SYNTAX; the C type followed `kind` + the declaration.
        if let Some(inner) = self.declared_opaque_payload_inner(fty) {
            let src_inner = self.src_ty_of(&inner);
            let owned = quote!(*::std::boxed::Box::from_raw(#b as *mut #src_inner));
            let null_msg = format!(
                "null payload for `{}` (a non-optional handle payload cannot be NULL — the \
                 union may already have been dropped)",
                type_short(&inner)
            );
            return if fty.optional_inner().is_some() {
                quote!(if #b.is_null() {
                    ::core::option::Option::None
                } else {
                    ::core::option::Option::Some(#owned)
                })
            } else {
                quote!({
                    if #b.is_null() {
                        return ::core::result::Result::Err(
                            ::std::string::String::from(#null_msg),
                        );
                    }
                    #owned
                })
            };
        }
        if let Some(inner) = r_boxed_inner(fty) {
            let src_inner = self.src_ty_of(&inner.key());
            let boxed = quote!(::std::boxed::Box::from_raw(#b as *mut #src_inner));
            return if fty.optional_inner().is_some() {
                quote!(if #b.is_null() {
                    ::core::option::Option::None
                } else {
                    ::core::option::Option::Some(#boxed)
                })
            } else {
                // A bare `Box<T>` has no null representation, so a NULL slot
                // cannot be decoded — and it is reachable, not hypothetical:
                // the typed drop nulls the arm it frees, so a union passed back
                // in after being dropped arrives here NULL. Same rule as the
                // tag: report it, never materialise it.
                let null_msg = format!(
                    "null payload for `{}` (a non-optional `Box` payload cannot be NULL — the \
                     union may already have been dropped)",
                    type_short(&inner.key())
                );
                quote!({
                    if #b.is_null() {
                        return ::core::result::Result::Err(
                            ::std::string::String::from(#null_msg),
                        );
                    }
                    #boxed
                })
            };
        }
        // A `bool` payload rides as `MaybeUninit<bool>` (see `bool_wire`), so
        // the byte C wrote is normalised rather than materialised.
        if r_is_bool(fty) {
            return bool_in_expr(quote!(#b));
        }
        // A scalar is its own wire and needs no call.
        if r_is_scalar(fty) {
            return quote!(#b);
        }
        // Everything else rides its own resolved input converter — the wire
        // came from that converter's destination, so the two cannot disagree.
        // A fallible one propagates with `?`, which the union's own `Result`
        // already provides.
        match registry.input_entry(fty) {
            Some(entry) => {
                let conv = &entry.function.sig.ident;
                if returns_result(&entry.function.sig.output) {
                    quote!(#conv(#b)?)
                } else {
                    quote!(#conv(#b))
                }
            }
            None => quote!(#b),
        }
    }

    /// One payload field, Rust value → C wire. The `String` arm allocates the
    /// `char *` block the union's typed drop later frees.
    fn payload_out_expr(
        &self,
        fty: &TypeRef,
        b: &syn::Ident,
        registry: &impl Conversions<()>,
    ) -> TokenStream {
        if r_is_string(fty) {
            return quote!(__cbg_alloc_cstr(#b));
        }
        if self.enums.contains_key(&fty.key()) {
            let conv = Self::out_name_of(&fty.key());
            return quote!(::core::mem::MaybeUninit::new(#conv(#b)));
        }
        // The peer of the input arm above: an owned value the C side must later
        // release, so it is boxed HERE rather than having arrived boxed.
        if let Some(inner) = self.declared_opaque_payload_inner(fty) {
            let c = self.c_type_ident(&inner);
            return if fty.optional_inner().is_some() {
                quote!(match #b {
                    ::core::option::Option::Some(__v) => {
                        ::std::boxed::Box::into_raw(::std::boxed::Box::new(__v)) as *mut #c
                    }
                    ::core::option::Option::None => ::core::ptr::null_mut(),
                })
            } else {
                quote!(::std::boxed::Box::into_raw(::std::boxed::Box::new(#b)) as *mut #c)
            };
        }
        if let Some(inner) = r_boxed_inner(fty) {
            let c = self.c_type_ident(&inner.key());
            return if fty.optional_inner().is_some() {
                quote!(match #b {
                    ::core::option::Option::Some(__b) => {
                        ::std::boxed::Box::into_raw(__b) as *mut #c
                    }
                    ::core::option::Option::None => ::core::ptr::null_mut(),
                })
            } else {
                quote!(::std::boxed::Box::into_raw(#b) as *mut #c)
            };
        }
        // The counterpart of the normalising read above: Rust always writes a
        // valid `0`/`1`, so this only wraps.
        if r_is_bool(fty) {
            return bool_out_expr(quote!(#b));
        }
        if r_is_scalar(fty) {
            return quote!(#b);
        }
        // The output counterpart of the input dispatch above. Acceptance —
        // including the refusal of a FALLIBLE output converter, which a union
        // cannot report through — is decided once in `payload_field_wire`, so
        // this site only emits the call.
        match registry.output_entry(fty) {
            Some(entry) => {
                let conv = entry.function.sig.ident.clone();
                quote!(#conv(#b))
            }
            None => quote!(#b),
        }
    }

    /// Callback closure structs: one `#[repr(C)]` `{ context, call, drop }`
    /// per declared signature actually used (its `impl Fn(...)` input
    /// resolved). `call` takes each arg's output wire (the owned handle the
    /// C callback must drop) plus the `void *context`; `drop` releases the
    /// context. Deterministic order by emitted name.
    fn prereq_callback_structs(&self, registry: &Registry<()>) -> Vec<syn::Item> {
        let mut items: Vec<syn::Item> = Vec::new();
        // The declaration's own argument types. `CallbackKey` is a list of
        // identities — what the map is keyed by — and the arguments it was
        // declared with are beside it, so neither is rebuilt from the other
        // (#291).
        let mut cb_keys: Vec<(&CallbackKey, &CbCfg)> = self.callbacks.iter().collect();
        cb_keys.sort_by_key(|(k, _)| self.callback_c_name(k));
        for (key, cfg) in cb_keys {
            let args: Vec<syn::Type> = cfg.args.clone();
            // Emit only if the callback is required (its input resolved); skip a
            // declared-but-unused signature.
            if registry
                .reading_of(&callback_fn_type(&args))
                .and_then(|tr| registry.input_entry(&tr))
                .is_none()
            {
                continue;
            }
            let takeable = &self.callbacks.get(key).expect("callback cfg").takeable;
            let mut arg_wires: Vec<syn::Type> = Vec::new();
            for (i, a) in args.iter().enumerate() {
                // `&[E]` slice arg → TWO C `call` params: `const E_wire *` + `size_t`
                // (the slice delivered by reference, zero-copy).
                if let Some((_src, elem_wire)) = self.callback_slice_elem_wire(a) {
                    arg_wires.push(syn::parse_quote!(*const #elem_wire));
                    arg_wires.push(syn::parse_quote!(usize));
                    continue;
                }
                let wire = registry
                    .reading_of(a)
                    .and_then(|tr| registry.output_entry(&tr))
                    .unwrap_or_else(|| {
                        panic!(
                            "Cbindgen: callback arg `{}` has no output converter (declare it \
                             as a opaque_ptr/data_struct/enum_type)",
                            a.to_token_stream()
                        )
                    })
                    .destination
                    .clone();
                // Takeable params are delivered as an owned pointer.
                if takeable.contains(&i) {
                    arg_wires.push(syn::parse_quote!(*mut #wire));
                } else {
                    arg_wires.push(wire);
                }
            }
            let c_struct = self.callback_c_ident(key);
            items.push(syn::parse_quote!(
                #[repr(C)]
                #[allow(non_camel_case_types)]
                pub struct #c_struct {
                    pub context: *mut ::core::ffi::c_void,
                    pub call: ::core::option::Option<
                        unsafe extern "C" fn(#(#arg_wires,)* *mut ::core::ffi::c_void),
                    >,
                    pub drop: ::core::option::Option<
                        unsafe extern "C" fn(*mut ::core::ffi::c_void),
                    >,
                }
            ));
        }
        items
    }
}

impl CbindgenBuilder {
    /// State this binding into `registry` — see `JniGenBuilder::declare_into`.
    ///
    /// Push, not pull: the build script calls this, and the registry never
    /// calls back. cbindgen declares no consts (it has no const mechanism, so
    /// every captured const re-emits verbatim) and no decompositions.
    /// Binding-local fns declared by `convert!(..).local(..)`.
    fn collect_local_functions(&self) -> Vec<(syn::ItemFn, String)> {
        let mut result = Vec::new();
        let mut seen = HashMap::<syn::Ident, String>::new();
        for (ident, path, sig) in self.convert_decls.iter().flat_map(|decl| decl.locals()) {
            let origin = prebindgen_registry::decl::local_path_prefix(path);
            let mut sig = sig.clone();
            sig.ident = ident.clone();
            let signature = quote!(#origin #sig).to_string();
            match seen.get(ident) {
                Some(previous) if previous == &signature => continue,
                Some(_) => panic!(
                    "binding-local conversion fn `{ident}` is declared with two different signatures"
                ),
                None => {
                    seen.insert(ident.clone(), signature);
                }
            }
            let item: syn::ItemFn = syn::parse_quote!(#sig { unimplemented!() });
            result.push((item, origin));
        }
        result
    }

    /// State this binding into `registry`, then resolve it — see
    /// `JniGenBuilder::build`.
    /// Read the source, resolve every crossing, and hand back the binding —
    /// see `JniGenBuilder::build`.
    pub fn build(self) -> Result<Cbindgen, prebindgen_registry::WriteRustError> {
        let flat = self
            .sources
            .clone()
            .build()
            .map_err(prebindgen_registry::ScanError::from)?;
        let registry = prebindgen_registry::Registry::builder(flat)?;
        self.build_with(registry)
    }

    /// [`Self::build`] over a registry described elsewhere — the test seam.
    pub(crate) fn build_with(
        self,
        registry: prebindgen_registry::RegistryBuilder<()>,
    ) -> Result<Cbindgen, prebindgen_registry::WriteRustError> {
        let registry = self
            .declare_into(registry)?
            .validate_with(&self)?
            .convert_with(|crossing, built, emit| self.convert_crossing(crossing, built, emit))?
            .build()?;
        self.validate_resolved(&registry)
            .map_err(|message| prebindgen_registry::ScanError::AdapterInvariant { message })?;
        Ok(Cbindgen {
            gen: self,
            registry,
        })
    }

    /// Build the conversion for one crossing — see `JniGenBuilder::convert_crossing`.
    fn convert_crossing(
        &self,
        crossing: &Crossing,
        built: &Building<'_, ()>,
        emit: &prebindgen_registry::Emit,
    ) -> Option<ConverterImpl<()>> {
        let (dir, key) = crossing;
        // The reading the scan already took for this crossing, fetched by the
        // key the crossing IS — the same migration the JNI adapter's twin made in #284,
        // in place of `key -> to_type() -> spelling` (#291). Every crossing
        // `convert_with` hands out comes from a type table, so it has a cell.
        // The selectors take the reading now, so nothing here spells it.
        let ty = built.reading(key)?;
        match dir {
            Direction::Input => self.select_input_type(&ty, built, emit).or_else(|| {
                // The callback's arguments off the model's own `Callback` kind,
                // where `extract_fn_trait_args` re-read the parameter's bounds.
                let args = ty.callback_args()?;
                self.dispatch_fn_input(args, built)
            }),
            Direction::Output => self.select_output_type(&ty, built, emit),
        }
    }

    pub fn declare_into(
        &self,
        mut registry: RegistryBuilder<()>,
    ) -> Result<RegistryBuilder<()>, prebindgen_registry::ScanError> {
        for (item_fn, origin) in self.collect_local_functions() {
            registry = registry.local_function(item_fn, origin)?;
        }
        for ident in self.declared_functions() {
            registry = registry.export(&ident);
        }
        for ident in self.helper_functions() {
            registry = registry.reference(&ident);
        }
        for ty in self.declared_types().into_values() {
            registry = registry.export_type(ty);
        }
        Ok(registry)
    }
}

impl CbindgenBuilder {
    fn dispatch_fn_input(
        &self,
        args: &[TypeRef],
        registry: &impl Conversions<()>,
    ) -> Option<ConverterImpl<()>> {
        let key: CallbackKey = args.iter().map(|a| a.key()).collect();
        if !self.callbacks.contains_key(&key) {
            // Undeclared callback signature: leave unresolved so the registry
            // reports it (the consumer must `.callback(...)`-declare it).
            return None;
        }
        let c_struct = self.callback_c_ident(&key);

        // Per-arg: closure parameter (`__aN: <src>`) + encode statement
        // (`let __wN = <output_conv>(__aN);`, panicking if the converter is
        // fallible — a firing callback has no error channel). A non-takeable arg
        // is passed to the C `call` by value (the C side owns + drops it); a
        // **takeable** arg is passed as `&mut __wN` (`*mut z_x_t`) and dropped here
        // after the call (no-op if the C side took it, leaving a gravestone).
        let takeable = &self.callbacks.get(&key).expect("callback cfg").takeable;
        let mut closure_params: Vec<TokenStream> = Vec::new();
        let mut encode_stmts: Vec<TokenStream> = Vec::new();
        let mut call_args: Vec<TokenStream> = Vec::new();
        let mut post_drops: Vec<TokenStream> = Vec::new();
        for (i, arg) in args.iter().enumerate() {
            // `&[E]` slice arg: deliver the slice to the C `call` **by reference** —
            // `(*const E_wire, size_t)`, zero-copy (the closure borrows the slice for
            // the call). The element wire is layout-identical to `E`, so the pointer
            // cast is sound; no per-element encode and no post-call drop.
            if let Some((src_elem, elem_wire)) = self.callback_slice_elem_wire_of(arg) {
                let ai = format_ident!("__a{}", i);
                closure_params.push(quote!(#ai: &[#src_elem]));
                call_args.push(quote!(#ai.as_ptr() as *const #elem_wire));
                call_args.push(quote!(#ai.len()));
                continue;
            }
            let entry = registry.output_entry(arg)?;
            let conv = entry.function.sig.ident.clone();
            let opaque = entry.destination.clone();
            let fallible = matches!(
                &entry.function.sig.output,
                syn::ReturnType::Type(_, ty) if is_result(ty)
            );
            let src = self.src_ty_deep_of(arg);
            let ai = format_ident!("__a{}", i);
            let wi = format_ident!("__w{}", i);
            closure_params.push(quote!(#ai: #src));
            let is_takeable = takeable.contains(&i);
            let mut_kw = if is_takeable { quote!(mut) } else { quote!() };
            if fallible {
                encode_stmts.push(quote!(
                    let #mut_kw #wi = match #conv(#ai) {
                        ::core::result::Result::Ok(__v) => __v,
                        ::core::result::Result::Err(__e) => {
                            ::core::panic!("cbindgen: callback argument conversion failed: {}", __e)
                        }
                    };
                ));
            } else {
                encode_stmts.push(quote!(let #mut_kw #wi = #conv(#ai);));
            }
            if is_takeable {
                call_args.push(quote!(&mut #wi as *mut #opaque));
                // Always drop after the call (leak-safe): live value if untaken,
                // gravestone (no-op) if the C side took it via `z_x_take`.
                post_drops.push(
                    quote!(let _ = <#opaque as ::prebindgen_c_runtime::Transmute>::into_rust(#wi);),
                );
            } else {
                call_args.push(quote!(#wi));
            }
        }

        let fn_ty = callback_fn_type(
            &args
                .iter()
                .map(|a| self.src_ty_deep_of(a))
                .collect::<Vec<_>>(),
        );
        let name = format_ident!("__cbg_in_{}", self.callback_c_name(&key));
        let function: syn::ItemFn = syn::parse_quote!(
            #[allow(non_snake_case, unused_variables, dead_code)]
            pub(crate) unsafe fn #name(c: #c_struct) -> #fn_ty {
                struct __Ctx {
                    context: *mut ::core::ffi::c_void,
                    drop: ::core::option::Option<unsafe extern "C" fn(*mut ::core::ffi::c_void)>,
                }
                unsafe impl ::core::marker::Send for __Ctx {}
                unsafe impl ::core::marker::Sync for __Ctx {}
                impl ::core::ops::Drop for __Ctx {
                    fn drop(&mut self) {
                        if let ::core::option::Option::Some(__d) = self.drop {
                            unsafe { __d(self.context) }
                        }
                    }
                }
                let __call = c.call;
                let __ctx = ::std::sync::Arc::new(__Ctx { context: c.context, drop: c.drop });
                move |#(#closure_params),*| {
                    #(#encode_stmts)*
                    if let ::core::option::Option::Some(__f) = __call {
                        unsafe { __f(#(#call_args,)* __ctx.context) }
                    }
                    #(#post_drops)*
                }
            }
        );
        Some(ConverterImpl {
            subs: vec![],
            destination: syn::parse_quote!(#c_struct),
            function,
            pre_stages: vec![],
            niches: Niches::empty(),
            metadata: (),
        })
    }
}

impl Prebindgen for CbindgenBuilder {
    /// Report what this binding left unclaimed. Here because it is the
    /// earliest generator-owned hook that sees the model, and it runs exactly
    /// where the registry used to print these itself. Moves into
    /// `CbindgenBuilder::generate` once that exists (prebindgen#251 phase E).
    ///
    /// `consts: None` — cbindgen has no const declaration mechanism, so every
    /// captured const is re-emitted verbatim and none is ever a skip.
    fn validate(&self, binding: &Building<'_, Self::Metadata>) -> Result<(), String> {
        let mut functions = self.declared_functions();
        functions.extend(self.helper_functions());
        prebindgen_registry::warn_unclaimed(
            binding.flat(),
            &prebindgen_registry::Claimed {
                functions,
                // The report asks what was *claimed*, which is a set of
                // identities — the declarations' spellings are the scan's
                // business, not this one's.
                types: self.declared_types().into_keys().collect(),
                consts: None,
                ignored_functions: self.ignored_functions(),
                ignored_types: self.ignored_types(),
                ..Default::default()
            },
        );
        Ok(())
    }

    type Metadata = ();

    // Consts have no declaration mechanism here (`declared_consts` stays
    // `None`), so every indexed const re-emits through the default
    // `on_const` — a path-alias against this source module, keeping consts
    // with non-portable initializers valid in the generated file. (cbindgen
    // cannot evaluate a path initializer, so aliased consts don't surface
    // as `#define`s in the C header.)
    fn source_module(&self) -> Option<&syn::Path> {
        self.source_module.as_ref()
    }

    // ── Structural type resolution ──────────────────────────────────────
    // The adapter peels `ty` itself: a rank-0 terminal category, else a
    // wrapper shape (`Option<_>`, `&`/`&mut`/`&[_]`/`&str`). See `in_wrappers`
    // / `out_wrappers`.

    fn prerequisites(
        &self,
        registry: &Registry<()>,
        emit: &prebindgen_registry::Emit,
    ) -> Vec<syn::Item> {
        // C-string data memory (string returns + `String` fields of data structs)
        // is malloc'd raw and freed by the single universal `free_memory_function`.
        // Array returns (`Vec<T>`) also hand out a malloc'd block freed via the
        // same function (per element through the `z_free_array` macro), so the
        // allocator/freer prelude is needed for them too. Each section's emitter
        // lives in the `impl CbindgenBuilder` block above; order is significant.
        let produces_array = self.produces_array(registry);
        let mut items: Vec<syn::Item> = Vec::new();
        items.extend(self.prereq_alloc_free(registry, produces_array));
        items.extend(self.prereq_array_builder(produces_array));
        items.extend(self.prereq_opaque_handles(registry));
        items.extend(self.prereq_data_structs(registry));
        items.extend(self.prereq_value_opaque(registry));
        items.extend(self.prereq_enums(registry, emit));
        items.extend(self.prereq_tagged_unions(registry, emit));
        items.extend(self.prereq_callback_structs(registry));
        items.extend(self.prereq_domain_constants(registry));
        items
    }

    // ── Item emission ──────────────────────────────────────────────────

    fn on_function(
        &self,
        f: &prebindgen_registry::flat::Function,
        registry: &Registry<()>,
        emit: &prebindgen_registry::Emit,
    ) -> TokenStream {
        self.emit_function_wrapper(f, registry, emit)
    }

    fn on_struct(
        &self,
        _s: &prebindgen_registry::flat::Struct,
        _registry: &Registry<()>,
        _emit: &prebindgen_registry::Emit,
    ) -> TokenStream {
        // The `#[repr(C)]` mirror + converters come from prerequisites /
        // on_output_type; the original (non-FFI-safe) struct is dropped.
        TokenStream::new()
    }

    fn on_variant(
        &self,
        _v: &prebindgen_registry::flat::Variant,
        _registry: &Registry<()>,
        _emit: &prebindgen_registry::Emit,
    ) -> TokenStream {
        TokenStream::new()
    }

    fn on_enum(
        &self,
        _e: &prebindgen_registry::flat::Enum,
        _registry: &Registry<()>,
        _emit: &prebindgen_registry::Emit,
    ) -> TokenStream {
        TokenStream::new()
    }
}

/// Output-direction terminal categories — the rank-0 chain, now an inherent
/// helper called by [`CbindgenBuilder::select_output_type`].
impl CbindgenBuilder {
    pub(crate) fn out_terminal(
        &self,
        ty: &TypeRef,
        _r: &impl Conversions<()>,
        emit: &prebindgen_registry::Emit,
    ) -> Option<ConverterImpl<()>> {
        // Unit return: trivial converter so `()` (and `Result<(), _>`) resolves.
        // Never actually called — void-returning wrappers ignore it, and
        // `emit_fallible_wrapper` special-cases `Result<(), E>` to drop the
        // out-param entirely (it exists only to satisfy the resolver).
        if matches!(ty.kind(), TypeKind::Unit) {
            let function: syn::ItemFn = syn::parse_quote!(
                #[allow(non_snake_case, dead_code, unused_variables)]
                pub(crate) fn __cbg_out_unit(v: ()) {}
            );
            return Some(ConverterImpl {
                subs: vec![],
                destination: syn::parse_quote!(()),
                function,
                pre_stages: vec![],
                niches: Niches::empty(),
                metadata: (),
            });
        }

        // `String` output: a `malloc`'d `char*` raw block freed via the
        // `free_memory_function`. A `String` explicitly declared `opaque_ptr`
        // (held by C as `string_t *`) opts out — the opaque-handle branch below
        // owns it then (mirroring the input side, where `in_opaque_handle` wins).
        if r_is_string(ty) && !self.opaque.contains_key(&ty.key()) {
            let name = Self::out_name_of(&ty.key());
            let function: syn::ItemFn = syn::parse_quote!(
                #[allow(non_snake_case, unused_variables, dead_code)]
                pub(crate) fn #name(v: ::std::string::String) -> *mut ::core::ffi::c_char {
                    __cbg_alloc_cstr(v)
                }
            );
            return Some(ConverterImpl {
                subs: vec![],
                destination: syn::parse_quote!(*mut ::core::ffi::c_char),
                function,
                pre_stages: vec![],
                niches: Niches::empty(),
                metadata: (),
            });
        }

        // FFI-safe scalar (`bool`, integers, floats): identity pass-through.
        if r_is_scalar(ty) {
            let name = Self::out_name_of(&ty.key());
            let spelled = scalar_ty(ty)?;
            let function: syn::ItemFn = syn::parse_quote!(
                #[allow(non_snake_case, unused_variables, dead_code)]
                pub(crate) fn #name(v: #spelled) -> #spelled {
                    v
                }
            );
            return Some(ConverterImpl {
                subs: vec![],
                destination: spelled.clone(),
                function,
                pre_stages: vec![],
                niches: Niches::empty(),
                metadata: (),
            });
        }

        let key = ty.key();

        // Opaque handle output: `Box::into_raw` → the bare `*mut #c_struct` handle.
        if self.opaque.contains_key(&key) {
            let name = Self::out_name_of(&ty.key());
            let c_struct = self.c_type_ident(&ty.key());
            let src = self.src_ty_of(&ty.key());
            let function: syn::ItemFn = syn::parse_quote!(
                #[allow(non_snake_case, unused_variables, dead_code)]
                pub(crate) fn #name(v: #src) -> *mut #c_struct {
                    ::std::boxed::Box::into_raw(::std::boxed::Box::new(v)) as *mut #c_struct
                }
            );
            return Some(ConverterImpl {
                subs: vec![],
                destination: syn::parse_quote!(*mut #c_struct),
                function,
                pre_stages: vec![],
                niches: Niches::empty(),
                metadata: (),
            });
        }

        // Opaque error output (e.g. `ZError`): not a by-value struct — marshal it
        // to a malloc'd `char*` message via the recorded accessor `fn(&E) ->
        // String`. The error out-param of a `Result<_, E>` wrapper is thus
        // `char **e`. Freed by the universal `free_memory_function`.
        if let Some(msg_fn) = self.opaque_errors.get(&key) {
            let name = Self::out_name_of(&ty.key());
            let src = self.src_ty_of(&ty.key());
            let msg_path = self.src_fn(msg_fn);
            let function: syn::ItemFn = syn::parse_quote!(
                #[allow(non_snake_case, unused_variables, dead_code)]
                pub(crate) fn #name(v: #src) -> *mut ::core::ffi::c_char {
                    __cbg_alloc_cstr(#msg_path(&v))
                }
            );
            return Some(ConverterImpl {
                subs: vec![],
                destination: syn::parse_quote!(*mut ::core::ffi::c_char),
                function,
                pre_stages: vec![],
                niches: Niches::empty(),
                metadata: (),
            });
        }

        // Data struct output: encode each field into its C wire (`String` →
        // malloc'd `char*` raw block, freed by the `free_memory_function`).
        if self.data.contains_key(&key) {
            let fields = self.struct_fields(_r, &ty.key())?;
            let name = Self::out_name_of(&ty.key());
            let c_struct = self.c_type_ident(&ty.key());
            let src = self.src_ty_of(&ty.key());
            let mut inits: Vec<TokenStream> = Vec::new();
            let mut subs: Vec<TypeKey> = Vec::new();
            for (fname, fty) in &fields {
                if r_is_string(fty) {
                    inits.push(quote!(#fname: __cbg_alloc_cstr(v.#fname)));
                } else if self.tagged_unions.contains_key(&fty.key()) {
                    let conv = Self::out_name_of(&fty.key());
                    subs.push(fty.key());
                    inits.push(quote!(#fname: #conv(v.#fname)));
                } else if r_is_bool(fty) {
                    let wrap = bool_out_expr(quote!(v.#fname));
                    inits.push(quote!(#fname: #wrap));
                } else {
                    inits.push(quote!(#fname: v.#fname));
                }
            }
            let function: syn::ItemFn = syn::parse_quote!(
                #[allow(non_snake_case, unused_variables, dead_code)]
                pub(crate) fn #name(v: #src) -> #c_struct {
                    #c_struct { #(#inits),* }
                }
            );
            return Some(ConverterImpl {
                subs,
                destination: syn::parse_quote!(#c_struct),
                function,
                pre_stages: vec![],
                niches: Niches::empty(),
                metadata: (),
            });
        }

        // Value-opaque output: move the Rust value's bytes into the opaque
        // counterpart, by value (no Box). Size/align equality is asserted at the
        // type's emission site (fail-closed).
        if let Some(opaque) = self.value_opaque_ty_of(&ty.key()) {
            let opaque = opaque.clone();
            let name = Self::out_name_of(&ty.key());
            let src = self.src_ty_of(&ty.key());
            let function: syn::ItemFn = syn::parse_quote!(
                #[allow(non_snake_case, unused_variables, dead_code)]
                pub(crate) fn #name(v: #src) -> #opaque {
                    <#opaque as ::prebindgen_c_runtime::Transmute>::from_rust(v)
                }
            );
            return Some(ConverterImpl {
                subs: vec![],
                destination: opaque,
                function,
                pre_stages: vec![],
                niches: Niches::empty(),
                metadata: (),
            });
        }

        // Enum output: `match` the source enum to the C enum.
        if self.enums.contains_key(&key) {
            let e = unit_enum(_r, &ty.key())?;
            let name = Self::out_name_of(&ty.key());
            let cname = self.c_type_ident(&ty.key());
            let src = self.src_ty_of(&ty.key());
            let arms = e.values.iter().map(|v| {
                let id = &v.name;
                quote!(#src::#id => #cname::#id,)
            });
            let function: syn::ItemFn = syn::parse_quote!(
                #[allow(non_snake_case, unused_variables, dead_code)]
                pub(crate) fn #name(v: #src) -> #cname {
                    match v { #(#arms)* }
                }
            );
            return Some(ConverterImpl {
                subs: vec![],
                destination: syn::parse_quote!(#cname),
                function,
                pre_stages: vec![],
                niches: Niches::empty(),
                metadata: (),
            });
        }

        // Tagged-union output: `match` the source enum to the C union,
        // converting each arm's payload.
        if let Some(c) = self.out_tagged_union(ty, _r, emit) {
            return Some(c);
        }

        None
    }
}

/// Structural wrapper-shape resolvers (the post-rank-machinery surface). Each
/// peels `ty`'s outermost layer and composes the inner's converter; `subs`
/// lists the immediate inner(s) it looked up.
impl CbindgenBuilder {
    /// `Option<X>` and reference (`&`/`&mut`/`&[E]`/`&str`) **input** shapes.
    pub(crate) fn in_wrappers(
        &self,
        ty: &TypeRef,
        r: &impl Conversions<()>,
    ) -> Option<ConverterImpl<()>> {
        // `Option<X>` input: a single nullable C param, NULL = `None`. The inner
        // `X` is reused wholesale (its own converter — e.g. an `&T` borrow — does
        // the non-null decode), so `Option<&ZConfig>` binds the *reference*
        // converter, never the owned one.
        if let Some(inner) = ty.optional_inner() {
            let entry = r.input_entry(inner)?;
            let inner_wire = entry.destination.clone();
            let inner_conv = entry.function.sig.ident.clone();
            let (inner_ok, fallible): (syn::Type, bool) = match &entry.function.sig.output {
                syn::ReturnType::Type(_, t) if is_result(t) => {
                    let (ok, _e) = result_parts(t).expect("is_result ⇒ result_parts");
                    (ok, true)
                }
                syn::ReturnType::Type(_, t) => ((**t).clone(), false),
                syn::ReturnType::Default => (syn::parse_quote!(()), false),
            };
            if let Some((slot, rest)) = entry.niches.clone().carve() {
                let pred = &slot.matches;
                let name = format_ident!("__cbg_in_option_{}", sanitize(&inner.key()));
                let function: syn::ItemFn = if fallible {
                    syn::parse_quote!(
                        #[allow(non_snake_case, unused_variables, dead_code)]
                        pub(crate) unsafe fn #name(
                            v: #inner_wire,
                        ) -> ::core::result::Result<
                            ::core::option::Option<#inner_ok>,
                            ::std::string::String
                        > {
                            if #pred {
                                ::core::result::Result::Ok(::core::option::Option::None)
                            } else {
                                #inner_conv(v).map(::core::option::Option::Some)
                            }
                        }
                    )
                } else {
                    syn::parse_quote!(
                        #[allow(non_snake_case, unused_variables, dead_code)]
                        pub(crate) unsafe fn #name(
                            v: #inner_wire,
                        ) -> ::core::option::Option<#inner_ok> {
                            if #pred {
                                ::core::option::Option::None
                            } else {
                                ::core::option::Option::Some(#inner_conv(v))
                            }
                        }
                    )
                };
                return Some(ConverterImpl {
                    subs: vec![inner.key()],
                    destination: inner_wire,
                    function,
                    pre_stages: vec![],
                    niches: rest,
                    metadata: (),
                });
            }
            let is_ptr = matches!(inner_wire, syn::Type::Ptr(_));
            let wire: syn::Type = if is_ptr {
                inner_wire.clone()
            } else {
                syn::parse_quote!(*const #inner_wire)
            };
            let read = if is_ptr { quote!(v) } else { quote!(*v) };
            let name = format_ident!("__cbg_in_option_{}", sanitize(&inner.key()));
            let lt: TokenStream = if inner.borrow_target().is_some() {
                quote!(<'a>)
            } else {
                quote!()
            };
            let function: syn::ItemFn = if fallible {
                syn::parse_quote!(
                    #[allow(non_snake_case, unused_variables, dead_code)]
                    pub(crate) unsafe fn #name #lt(
                        v: #wire,
                    ) -> ::core::result::Result<::core::option::Option<#inner_ok>, ::std::string::String> {
                        if v.is_null() {
                            return ::core::result::Result::Ok(::core::option::Option::None);
                        }
                        match #inner_conv(#read) {
                            ::core::result::Result::Ok(__x) => {
                                ::core::result::Result::Ok(::core::option::Option::Some(__x))
                            }
                            ::core::result::Result::Err(__e) => ::core::result::Result::Err(__e),
                        }
                    }
                )
            } else {
                syn::parse_quote!(
                    #[allow(non_snake_case, unused_variables, dead_code)]
                    pub(crate) unsafe fn #name #lt(
                        v: #wire,
                    ) -> ::core::option::Option<#inner_ok> {
                        if v.is_null() {
                            ::core::option::Option::None
                        } else {
                            ::core::option::Option::Some(#inner_conv(#read))
                        }
                    }
                )
            };
            return Some(ConverterImpl {
                subs: vec![inner.key()],
                destination: wire,
                function,
                pre_stages: vec![],
                niches: Niches::empty(),
                metadata: (),
            });
        }

        // `mutable` off the `Ref` itself, NOT `is_exclusive_borrow`: that
        // reading deliberately answers `false` for `&mut MaybeUninit<_>` — an
        // out-param slot is not an exclusive borrow OF A VALUE — and these arms
        // ask the syntactic question, "did the source write `&mut`".
        let TypeKind::Ref {
            mutable: rf_mut,
            inner: rf_inner,
            ..
        } = ty.kind()
        else {
            return None;
        };
        // The borrow's target, as a reading — every use below is its identity
        // or its source path, both of which the model answers.
        let elem = rf_inner;

        // `&[E]` slice: marker only — the two-param (`*const E_wire`, `usize`)
        // lowering is done structurally in `emit_inputs`. A scalar `E` crosses as
        // itself (`*const E`); a declared inline-opaque by-value `E` (e.g. a
        // `repr_c_struct`) crosses as `*const E_counterpart` reinterpreted to
        // `&[E]` zero-copy. `subs` marks `E`'s input required so its mirror /
        // prerequisites are emitted.
        if !*rf_mut {
            if let Some(e) = r_shared_slice_elem(ty) {
                // #170, the slice instance. The two-param lowering builds the
                // `&[E]` zero-copy from C's own block, so there is nowhere to
                // normalise the bytes: `&[bool]` would materialise every
                // element's restricted domain at once. `MaybeUninit<bool>` is
                // not a fix here — the callee wants `&[bool]`, and rebuilding
                // the block would silently drop the zero-copy contract this
                // path exists for. Rejected until a raw-wire lowering exists.
                if r_is_bool(e) {
                    panic!(
                        "Cbindgen: `&[bool]` cannot cross IN from C. A `bool` slice is \
                         reinterpreted zero-copy from the caller's block, so a byte outside \
                         `{{0, 1}}` would become a Rust `bool` with no chance to normalise it \
                         (#170). Take the flags as an integer slice, or wrap them in a declared \
                         `opaque_ptr` handle."
                    );
                }
                if let Some(e_ty) = scalar_ty(e) {
                    let name = format_ident!("__cbg_inmark_slice_{}", sanitize(&e.key()));
                    let function: syn::ItemFn = syn::parse_quote!(
                        #[allow(non_snake_case, dead_code, unused)]
                        pub(crate) fn #name() {}
                    );
                    return Some(ConverterImpl {
                        subs: vec![e.key()],
                        destination: syn::parse_quote!(*const #e_ty),
                        function,
                        pre_stages: vec![],
                        niches: Niches::empty(),
                        metadata: (),
                    });
                }
                if let Some(counterpart) = self.value_opaque_ty_of(&e.key()) {
                    let counterpart = counterpart.clone();
                    let name = format_ident!("__cbg_inmark_slice_{}", sanitize(&e.key()));
                    let function: syn::ItemFn = syn::parse_quote!(
                        #[allow(non_snake_case, dead_code, unused)]
                        pub(crate) fn #name() {}
                    );
                    return Some(ConverterImpl {
                        subs: vec![e.key()],
                        destination: syn::parse_quote!(*const #counterpart),
                        function,
                        pre_stages: vec![],
                        niches: Niches::empty(),
                        metadata: (),
                    });
                }
            }
        }
        // `&str`: borrow a UTF-8 C string directly from the caller.
        if !*rf_mut && r_is_str(rf_inner) {
            let name = Self::in_name_of(&ty.key());
            let function: syn::ItemFn = syn::parse_quote!(
                #[allow(non_snake_case, unused_variables, dead_code)]
                pub(crate) unsafe fn #name<'a>(
                    v: *const ::core::ffi::c_char,
                ) -> ::core::result::Result<&'a str, ::std::string::String> {
                    if v.is_null() {
                        return ::core::result::Result::Err(
                            ::std::string::String::from("null pointer passed for str argument"),
                        );
                    }
                    match ::std::ffi::CStr::from_ptr(v).to_str() {
                        ::core::result::Result::Ok(s) => ::core::result::Result::Ok(s),
                        ::core::result::Result::Err(_) => ::core::result::Result::Err(
                            ::std::string::String::from("invalid UTF-8 in str argument"),
                        ),
                    }
                }
            );
            return Some(ConverterImpl {
                subs: vec![elem.key()],
                destination: syn::parse_quote!(*const ::core::ffi::c_char),
                function,
                pre_stages: vec![],
                niches: Niches::empty(),
                metadata: (),
            });
        }
        // `&mut T` (mutable borrow). Three sub-cases, all wiring to a `*mut` of the
        // wire (the C memory IS the Rust value for a value-opaque mirror — asserted
        // layout-identical — so the cast is sound; `&mut` is a borrow, no gravestone).
        if *rf_mut {
            // `&mut MaybeUninit<X>` (X value-opaque): out-param into uninitialized
            // memory. Rust writes via the `MaybeUninit` (no drop of the garbage slot).
            // `TypeKind::Uninit` is the form `maybe_uninit_inner` matched by
            // reading a path's tail ident.
            if let prebindgen_registry::flat::TypeKind::Uninit(inner) = elem.kind() {
                let op = self.value_opaque_ty_of(&inner.key())?.clone();
                let name = Self::in_name_of(&ty.key());
                let src = self.src_ty_of(&inner.key());
                let short = type_short(&inner.key());
                let null_ptr_msg = format!("null {short} pointer");
                let function: syn::ItemFn = syn::parse_quote!(
                    #[allow(non_snake_case, unused_variables, dead_code)]
                    pub(crate) unsafe fn #name<'a>(
                        v: *mut #op,
                    ) -> ::core::result::Result<&'a mut ::core::mem::MaybeUninit<#src>, ::std::string::String> {
                        if v.is_null() {
                            return ::core::result::Result::Err(
                                ::std::string::String::from(#null_ptr_msg),
                            );
                        }
                        ::core::result::Result::Ok(&mut *(v as *mut ::core::mem::MaybeUninit<#src>))
                    }
                );
                return Some(ConverterImpl {
                    subs: vec![inner.key()],
                    destination: syn::parse_quote!(*mut #op),
                    function,
                    pre_stages: vec![],
                    niches: Niches::empty(),
                    metadata: (),
                });
            }
            // `&mut` opaque handle, or `&mut` value-opaque: both reinterpret the C
            // pointer as a mutable Rust reference. The wire is the handle's C struct
            // or the value-opaque mirror.
            let wire_ty: syn::Type = if self.opaque.contains_key(&elem.key()) {
                let c_struct = self.c_type_ident(&elem.key());
                syn::parse_quote!(#c_struct)
            } else {
                self.value_opaque_ty_of(&elem.key())?.clone()
            };
            let name = Self::in_name_of(&ty.key());
            let src = self.src_ty_of(&elem.key());
            let short = type_short(&elem.key());
            let null_ptr_msg = format!("null {short} pointer");
            let function: syn::ItemFn = syn::parse_quote!(
                #[allow(non_snake_case, unused_variables, dead_code)]
                pub(crate) unsafe fn #name<'a>(
                    v: *mut #wire_ty,
                ) -> ::core::result::Result<&'a mut #src, ::std::string::String> {
                    if v.is_null() {
                        return ::core::result::Result::Err(
                            ::std::string::String::from(#null_ptr_msg),
                        );
                    }
                    ::core::result::Result::Ok(&mut *(v as *mut #src))
                }
            );
            return Some(ConverterImpl {
                subs: vec![elem.key()],
                destination: syn::parse_quote!(*mut #wire_ty),
                function,
                pre_stages: vec![],
                niches: Niches::empty(),
                metadata: (),
            });
        }
        // `&T` (shared borrow) of an opaque handle or value-opaque type.
        let key1 = elem.key();
        let wire_ty: syn::Type = if self.opaque.contains_key(&key1) {
            let c_struct = self.c_type_ident(&elem.key());
            syn::parse_quote!(#c_struct)
        } else {
            self.value_opaque_ty_of(&elem.key())?.clone()
        };
        let name = Self::in_name_of(&ty.key());
        let src = self.src_ty_of(&elem.key());
        let short = type_short(&elem.key());
        let null_ptr_msg = format!("null {short} pointer");
        let function: syn::ItemFn = syn::parse_quote!(
            #[allow(non_snake_case, unused_variables, dead_code)]
            pub(crate) unsafe fn #name<'a>(
                v: *const #wire_ty,
            ) -> ::core::result::Result<&'a #src, ::std::string::String> {
                if v.is_null() {
                    return ::core::result::Result::Err(::std::string::String::from(#null_ptr_msg));
                }
                ::core::result::Result::Ok(&*(v as *const #src))
            }
        );
        Some(ConverterImpl {
            subs: vec![elem.key()],
            destination: syn::parse_quote!(*const #wire_ty),
            function,
            pre_stages: vec![],
            niches: Niches::empty(),
            metadata: (),
        })
    }

    /// `Option<X>`/`Vec<X>`/`&T`/`Result<T,E>` **output** shapes. The composite
    /// markers (`Option`/`Vec`/`Result`) carry a `()` destination — the real
    /// lowering is structural in `emit_function_wrapper` — and exist only to
    /// resolve the entry and make the inner(s) required.
    pub(crate) fn out_wrappers(
        &self,
        ty: &TypeRef,
        r: &impl Conversions<()>,
    ) -> Option<ConverterImpl<()>> {
        // `Option<T>` / `Vec<T>` marker.
        if let Some(inner) = ty.optional_inner().or_else(|| ty.sequence_elem()) {
            r.output_entry(inner)?;
            let kind = if ty.optional_inner().is_some() {
                "option"
            } else {
                "vec"
            };
            let name = format_ident!("__cbg_outmark_{}_{}", kind, sanitize(&inner.key()));
            let function: syn::ItemFn = syn::parse_quote!(
                #[allow(non_snake_case, dead_code, unused)]
                pub(crate) fn #name() {}
            );
            return Some(ConverterImpl {
                subs: vec![inner.key()],
                destination: syn::parse_quote!(()),
                function,
                pre_stages: vec![],
                niches: Niches::empty(),
                metadata: (),
            });
        }
        // `Cow<'_, [T]>` marker. The actual C ABI shape is structural in
        // `lower_shape`/`encode_value`, like `Vec<T>`.
        if let Some(inner) = r_cow_slice_elem(ty) {
            r.output_entry(inner)?;
            let name = format_ident!("__cbg_outmark_cow_slice_{}", sanitize(&inner.key()));
            let function: syn::ItemFn = syn::parse_quote!(
                #[allow(non_snake_case, dead_code, unused)]
                pub(crate) fn #name() {}
            );
            return Some(ConverterImpl {
                subs: vec![inner.key()],
                destination: syn::parse_quote!(()),
                function,
                pre_stages: vec![],
                niches: Niches::empty(),
                metadata: (),
            });
        }
        // `&[E]` shared slice borrow (a callback argument): marker only — the real
        // two-component `(*const E_wire, size_t)` lowering of the closure `call`
        // param is structural in `prereq_callback_structs` / `dispatch_fn_input`.
        // `subs: [E]` forces E's output (its `payload_t` mirror / scalar) so the
        // closure wire element type exists; `destination` is unused for the slice
        // (the callback emitter reads the element wire directly).
        if let Some(elem) = self
            .r_value_opaque_slice_elem(ty)
            .or_else(|| r_scalar_slice_elem(ty))
        {
            r.output_entry(elem)?;
            let name = format_ident!("__cbg_outmark_slice_{}", sanitize(&elem.key()));
            let function: syn::ItemFn = syn::parse_quote!(
                #[allow(non_snake_case, dead_code, unused)]
                pub(crate) fn #name() {}
            );
            return Some(ConverterImpl {
                subs: vec![elem.key()],
                destination: syn::parse_quote!(()),
                function,
                pre_stages: vec![],
                niches: Niches::empty(),
                metadata: (),
            });
        }
        // `&T` shared borrow of an opaque/value-opaque type → non-owning `*const`.
        if let TypeKind::Ref { mutable, inner, .. } = ty.kind() {
            if !*mutable {
                let key = inner.key();
                let wire_ty: syn::Type = if self.opaque.contains_key(&key) {
                    let c_struct = self.c_type_ident(&key);
                    syn::parse_quote!(#c_struct)
                } else {
                    self.value_opaque_ty_of(&key)?.clone()
                };
                let src = self.src_ty_of(&key);
                let name = format_ident!("__cbg_out_ref_{}", sanitize(&key));
                let function: syn::ItemFn = syn::parse_quote!(
                    #[allow(non_snake_case, dead_code, unused)]
                    pub(crate) unsafe fn #name(v: &#src) -> *const #wire_ty {
                        v as *const #src as *const #wire_ty
                    }
                );
                return Some(ConverterImpl {
                    subs: vec![key],
                    destination: syn::parse_quote!(*const #wire_ty),
                    function,
                    pre_stages: vec![],
                    niches: Niches::empty(),
                    metadata: (),
                });
            }
            return None;
        }
        // `Result<T, E>` marker — real lowering (bool + out-param + error-param)
        // is in `on_function`.
        if ty.fallible_parts().is_some() {
            let (ok, err) = ty.fallible_parts()?;
            let name = format_ident!("__cbg_result_{}", sanitize(&ty.key()));
            let function: syn::ItemFn = syn::parse_quote!(
                #[allow(non_snake_case, dead_code, unused)]
                pub(crate) fn #name() {}
            );
            return Some(ConverterImpl {
                subs: vec![ok.key(), err.key()],
                destination: syn::parse_quote!(()),
                function,
                pre_stages: vec![],
                niches: Niches::empty(),
                metadata: (),
            });
        }
        None
    }
}

/// The declaration surface, stated once.
///
/// These were trait methods the registry called back into the adapter from
/// inside `resolve`. They are the adapter's own business now, gathered into the
/// one value the registry is constructed from.
impl CbindgenBuilder {
    pub(crate) fn declared_functions(&self) -> HashSet<syn::Ident> {
        self.functions.keys().cloned().collect()
    }
    pub(crate) fn ignored_functions(&self) -> HashSet<syn::Ident> {
        self.ignored_functions.clone()
    }
    pub(crate) fn helper_functions(&self) -> HashSet<syn::Ident> {
        self.convert_decls
            .iter()
            .flat_map(|decl| decl.input_spec().iter().chain(decl.output_spec().iter()))
            .filter_map(|spec| match spec {
                ConvertSpec::PrebindgenFn(ident) => Some(ident.clone()),
                ConvertSpec::Trait { .. } => None,
            })
            .filter(|ident| !self.functions.contains_key(ident))
            .collect()
    }
    /// Each with the spelling its declarator was written with — the scan needs
    /// real tokens to intern a type that is in no table yet (#291).
    pub(crate) fn declared_types(&self) -> HashMap<TypeKey, Origin<syn::Type>> {
        self.opaque
            .iter()
            .chain(self.data.iter())
            .map(|(k, c)| (k, &c.rust_type))
            .chain(self.value_opaque.iter().map(|(k, c)| (k, &c.cfg.rust_type)))
            .chain(
                self.enums
                    .iter()
                    .chain(self.tagged_unions.iter())
                    .map(|(k, c)| (k, &c.rust_type)),
            )
            .map(|(k, t)| (k.clone(), t.clone()))
            .collect()
    }
    pub(crate) fn ignored_types(&self) -> HashSet<TypeKey> {
        self.ignored_types.clone()
    }
}