rustcall_julia_core 0.6.0

Shared Rust core for RustCall.jl: FFI manifest model, syn-based extraction, wrapper codegen, generic specialization
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
//! Wrapper code generation.
//!
//! Two flavours share this module:
//!
//! * **crate** codegen, used by the `rustcall_julia_macros` proc-macro for
//!   `@rust_crate` (`transform_function`, `transform_struct_crate`,
//!   `transform_impl_crate`);
//! * **inline** codegen, used by the extractor CLI's `expand` command for
//!   `rust"""` blocks (`inline_struct_wrappers`, `inline_generic_wrappers`).
//!
//! Every `extern "C"` entry point — inline function, crate function,
//! specialized generic instantiation, inline method, crate method — is
//! produced by the one generator
//! [`generate_wrapper`]; the public `transform_*` functions are thin adapters
//! that fill in a [`WrapperSpec`]. Adding a flavour therefore cannot lose the
//! string ABI, the `#[cfg]` propagation or the receiver handling again (#279).
//!
//! # `#[julia]` is additive (#279)
//!
//! The annotated item is kept **byte-for-byte**, minus the `#[julia]`
//! attribute itself, and the FFI entry point is emitted *next to it* under a
//! distinct symbol. Every in-crate caller, `#[test]`, `pub use` re-export and
//! other proc-macro (notably `#[pyfunction]`) therefore still sees the Rust
//! signature that was written.
//!
//! # Export-symbol scheme
//!
//! Every exported symbol hangs off the item's **FFI name** ([`symbol_stem`]):
//! the item's own name at the crate root, and its module path folded in
//! otherwise (`a::run` -> `a__run`, see [`symbol_stem`] for the escaping).
//! The manifest carries it as `Function.ffi_name` / `Struct.ffi_name`
//! (schema 7, #300); `<f>` and `<Struct>` below stand for that name.
//!
//! | generated item | symbol |
//! |---|---|
//! | free function `f` | `rustcall_<f>` |
//! | method / constructor `Struct::m` | `rustcall_<Struct>_m` |
//! | specialized generic instantiation `f_i32` | `rustcall_<f_i32>` |
//! | struct destructor | `<Struct>_free` |
//! | field accessors | `<Struct>_get_x` / `<Struct>_set_x` |
//! | clone | `<Struct>_clone` |
//! | `Result` / `Option` payload | `CResult_<f>` / `COption_<f>` |
//! | owned string buffer / release | `<owner>_RustCallOwnedString` / `<owner>_free_rust_string` |
//! | borrowed string view | `<owner>_RustCallBorrowedString` |
//! | panic channel of a wrapper | `<wrapper symbol>_take_panic` |
//! | generic inline struct's wrappers (not exported, #462) | `<Struct>_<method>`, `<Struct>_get_x`, `<Struct>_free` |
//!
//! Only the first three wrap a user-written item and so must step aside from
//! its name; `<owner>` is the free function, `<Struct>_<method>` or `<Struct>`
//! the buffer belongs to.
//!
//! The scheme is stable and part of artifact identity: the manifest carries it
//! in `Function.symbol` / `Method.symbol` (schema 3) and every Julia-side
//! `ccall` / `dlsym` goes through those fields, never through the Rust name.
//! Inline expansion additionally refuses a block in which a user item already
//! owns a generated symbol (see `crate::expand::symbol_collisions`); the
//! proc-macro sees one item at a time and cannot make that check.
//!
//! # Where the module path comes from (#300)
//!
//! * Inline expansion (`rust"""`) walks the block's inline modules itself and
//!   qualifies every item by the path it finds.
//! * In a crate the proc-macro cannot see its enclosing module, so the path is
//!   spelled by `#[julia]` **on the module**: `#[julia] pub mod a { #[julia] pub
//!   fn run() }` expands the nested items with `["a"]` ([`transform_module`]),
//!   and nested marked modules accumulate. A `#[julia]` item inside an inline
//!   module that is *not* marked would be exported under the crate-root symbol,
//!   which is why crate extraction refuses it (`crate::extract`). File modules
//!   (`mod a;`) cannot carry an attribute macro and are transparent: their
//!   items keep root symbols.
//! * PyO3-scanned items (#275) carry the real module path of the crate's tree
//!   walk and are qualified by it, so two `#[pyclass] C` in different modules
//!   no longer collide.

use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::{
    Attribute, File, FnArg, Ident, Item, ItemFn, ItemImpl, ItemMod, ItemStruct, Pat, ReturnType,
    Type, Visibility,
};

use crate::cfg::cfg_attrs;
use crate::manifest::{GenericWrapper, Mode};
use crate::model::{ImplHost, MethodModel, StructModel};
use crate::receiver::Receiver;
use crate::refusal::Refusal;
use crate::types::{
    extract_option_type, extract_result_type, field_has_accessors, generic_field_has_accessors,
    is_self_type, is_str_ref_type, is_string_type, is_vec_type, last_ident, unparen,
};

// ============================================================================
// Export-symbol scheme (#279, #300)
// ============================================================================

/// Prefix of every exported symbol that stands in for a user-written item.
pub const SYMBOL_PREFIX: &str = "rustcall_";

/// Separator between the segments of a module-qualified FFI name.
pub const MODULE_SEPARATOR: &str = "__";

/// Replacement for an underscore inside a segment of a module-qualified FFI
/// name.
pub const ESCAPED_UNDERSCORE: &str = "_0";

/// The **FFI name** of an item: the stem every generated symbol of the item is
/// derived from (`rustcall_<stem>`, `<stem>_free`, `<stem>_get_<field>`, ...).
///
/// * At the crate root (`module_path` empty) it is the item's own name,
///   unchanged: `run` -> `run`, `my_fn` -> `my_fn`.
/// * Inside modules every segment — the modules and the item name — has each
///   `_` replaced by [`ESCAPED_UNDERSCORE`] (`_0`), and the segments are joined
///   with [`MODULE_SEPARATOR`] (`__`): `a::run` -> `a__run`,
///   `geometry::shapes::Circle` -> `geometry__shapes__Circle`,
///   `my_mod::my_fn` -> `my_0mod__my_0fn`.
///
/// The encoding is prefix-free: in a qualified stem every `_` is followed by
/// either `0` (an escaped underscore) or `_` (a separator), so it decodes
/// unambiguously and two different paths never share a stem — `a_b::c` is
/// `a_0b__c`, `a::b_c` is `a__b_0c`. A raw-identifier prefix (`r#mod`) is
/// dropped, since `#` cannot appear in a symbol. Only identifier characters
/// are used, so the stem is valid as a Rust item name and as a linker symbol
/// on every platform.
///
/// A crate-root item whose *name* happens to spell an encoding (`fn a__run`
/// next to `a::run`) is the one coincidence the encoding cannot exclude; crate
/// extraction reports such a duplicate symbol instead of describing it.
/// A Rust item's name without a raw identifier's `r#` (`r#match` -> `match`):
/// the one spelling every symbol, helper identifier and Python attribute is
/// built from (#514). `r#match` and `match` are one Rust name, `#` cannot occur
/// in a symbol, and `format_ident!` panics on an `r#` that is not at the start.
/// The manifest keeps the item's own spelling for the source paths the
/// wrappers call (`<Buf>::r#match`); nothing else reads it.
pub fn unraw(name: &str) -> &str {
    name.strip_prefix("r#").unwrap_or(name)
}

/// The identifier that spells a Rust item's name in source, as the item wrote
/// it: `r#type` is a raw identifier, anything else a plain one. The one place a
/// manifest name becomes a source `Ident` (#514); a symbol or helper name is
/// built from [`unraw`] instead.
pub fn source_ident(name: &str, span: proc_macro2::Span) -> Ident {
    match name.strip_prefix("r#") {
        Some(bare) => Ident::new_raw(bare, span),
        None => Ident::new(name, span),
    }
}

pub fn symbol_stem(module_path: &[String], name: &str) -> String {
    let name = unraw(name);
    if module_path.is_empty() {
        return name.to_string();
    }
    module_path
        .iter()
        .map(|segment| segment.as_str())
        .chain(std::iter::once(name))
        .map(|segment| unraw(segment).replace('_', ESCAPED_UNDERSCORE))
        .collect::<Vec<_>>()
        .join(MODULE_SEPARATOR)
}

/// Exported symbol of the `extern "C"` wrapper of the free function `name`
/// living under `module_path`: `rustcall_<stem>`.
pub fn function_symbol(module_path: &[String], name: &str) -> String {
    format!("{SYMBOL_PREFIX}{}", symbol_stem(module_path, name))
}

/// Exported symbol of the `extern "C"` wrapper of `Struct::method`, the struct
/// living under `module_path`: `rustcall_<stem>_<method>`. The method part is
/// [`method_stem`], so a raw method name (`r#match`) is spelled as the symbol
/// the wrapper exports (`rustcall_S_match`, PR #517 review).
pub fn method_symbol(module_path: &[String], struct_name: &str, method: &str) -> String {
    method_symbol_of(
        &symbol_stem(module_path, struct_name),
        &method_stem(None, method),
    )
}

/// The part of every per-method name after the struct stem (#506): the
/// method's own name for an inherent method; for a method of a trait impl,
/// the trait's name, length-prefixed, ahead of it — `3Far_m` for `Far::m`.
///
/// The exported symbol (`rustcall_<stem>_<method stem>`), the string buffers
/// a crate wrapper declares (`<stem>_<method stem>_…`) and the `CResult_` /
/// `COption_` aggregate all hang off it, so a struct with an inherent `m` and
/// the `m` of two traits exports `rustcall_Buf_m`, `rustcall_Buf_3Far_m` and
/// `rustcall_Buf_4Near_m`. An identifier cannot start with a digit, so no
/// inherent method's name is a trait method's stem, and the length prefix
/// keeps every `(trait, method)` pair apart. The trait is named by the last
/// segment of its path as the header writes it (`tr::Far<u8>` → `Far`): two
/// impls whose traits end in the same name and that both wrap a method of the
/// same name get one symbol, which the crate scan's duplicate-symbol check
/// refuses (`crate::claims`).
pub fn method_stem(trait_name: Option<&str>, method: &str) -> String {
    let method = unraw(method);
    match trait_name.map(unraw) {
        None => method.to_string(),
        Some(trait_name) => format!("{}{trait_name}_{method}", trait_name.len()),
    }
}

/// The name a trait path ends in, `Far` for `tr::Far<u8>`: the trait part of
/// [`method_stem`] and of a qualified Julia name. A raw identifier loses its
/// `r#` (`r#type` → `type`), which is no part of the name and cannot appear
/// in a symbol or a Julia identifier. `None` for an empty (inherent) path.
pub fn trait_name_of(trait_path: &syn::Path) -> Option<String> {
    use syn::ext::IdentExt;
    trait_path
        .segments
        .last()
        .map(|s| s.ident.unraw().to_string())
}

/// [`method_symbol`] from an already computed struct stem and method stem.
/// Like every public symbol helper it is total over a raw name: an `r#` handed
/// in where a stem belongs is dropped, never spelled into a symbol (#514).
pub fn method_symbol_of(struct_stem: &str, method: &str) -> String {
    format!("{SYMBOL_PREFIX}{}_{}", unraw(struct_stem), unraw(method))
}

/// The destructor of a struct with FFI name `struct_stem`: `<stem>_free`.
pub fn struct_free_symbol(struct_stem: &str) -> String {
    format!("{}_free", unraw(struct_stem))
}

/// The stem a method's string buffers hang off when the wrapper **declares**
/// them itself: `<struct stem>_<method>`, giving
/// `<owner>_RustCallOwnedString`, `<owner>_free_rust_string` and
/// `<owner>_RustCallBorrowedString`.
///
/// That is every crate-flavour method — the proc-macro sees one impl block at
/// a time and cannot share a buffer per struct — and, since #342, an inline
/// method whose `#[julia] impl` block sits in another module than its struct,
/// whose wrapper is emitted at the block. An inline method emitted next to its
/// struct shares the struct's buffers, whose owner is the struct stem itself.
/// The manifest states which of the two a method uses (`Method.string_owner`)
/// rather than leaving Julia to infer it from the flavour.
pub fn method_string_owner(struct_stem: &str, method: &str) -> String {
    format!("{}_{}", unraw(struct_stem), unraw(method))
}

/// The field accessors of a struct with FFI name `struct_stem`:
/// `<stem>_get_<field>` and `<stem>_set_<field>`. A raw field name (`r#let`)
/// loses its `r#`, as the accessor the proc macro exports does
/// (`format_ident!` unraws an identifier argument, #514).
pub fn field_getter_symbol(struct_stem: &str, field: &str) -> String {
    format!("{}_get_{}", unraw(struct_stem), unraw(field))
}

pub fn field_setter_symbol(struct_stem: &str, field: &str) -> String {
    format!("{}_set_{}", unraw(struct_stem), unraw(field))
}

// ============================================================================
// Signature predicates (shared)
// ============================================================================

pub fn function_returns_string(sig: &syn::Signature) -> bool {
    matches!(&sig.output, ReturnType::Type(_, ty) if is_string_type(ty))
}

pub fn function_returns_str_ref(sig: &syn::Signature) -> bool {
    matches!(&sig.output, ReturnType::Type(_, ty) if is_str_ref_type(ty))
}

/// Whether any argument is passed as a `(ptr, len)` byte pair.
pub fn has_string_args(sig: &syn::Signature) -> bool {
    sig.inputs.iter().any(|a| match a {
        FnArg::Typed(pt) => is_string_type(&pt.ty) || is_str_ref_type(&pt.ty),
        FnArg::Receiver(_) => false,
    })
}

/// A `&str` return may only be handed to Julia as a borrowed view when it
/// cannot point into a temporary the wrapper itself created: the `(ptr, len)`
/// argument conversions build owned values (`String::from_utf8_lossy`) that
/// die with the call, so a function that both takes and returns strings
/// returns an owned copy instead (#242).
pub fn returns_borrowed_str(sig: &syn::Signature) -> bool {
    function_returns_str_ref(sig) && !has_string_args(sig)
}

/// A `&str`-returning signature whose result must be copied into an owned
/// buffer (see [`returns_borrowed_str`]).
pub fn returns_copied_str(sig: &syn::Signature) -> bool {
    function_returns_str_ref(sig) && has_string_args(sig)
}

/// The manifest `return_abi` of a signature: `"string"` (owned buffer),
/// `"str"` (borrowed view) or `""`.
pub fn return_abi(sig: &syn::Signature) -> &'static str {
    if function_returns_string(sig) || returns_copied_str(sig) {
        "string"
    } else if returns_borrowed_str(sig) {
        "str"
    } else {
        ""
    }
}

/// The manifest `abi` of a struct field: `"string"` when the generated getter
/// returns an owned `<Struct>_RustCallOwnedString` buffer (released through
/// `<Struct>_free_rust_string`), `""` when it returns the field as written.
///
/// Both wrapper flavours lower a `String` field the same way, so this depends
/// on the field type alone (#276).
pub fn field_abi(ty: &Type) -> &'static str {
    if is_string_type(ty) {
        "string"
    } else {
        ""
    }
}

/// An identifier the generated wrapper introduces (`s_ptr`, `s_len`, `s_bytes`,
/// `s_cow`, the receiver `ptr`, `self_obj`), chosen so that it never coincides
/// with one of the function's own argument names (`taken`): a trailing
/// underscore is appended until the name is free. `fn f(s: String, s_ptr:
/// usize)` therefore gets `s_ptr_` / `s_len` and keeps the user's `s_ptr`.
fn fresh_ident(base: &str, taken: &[String]) -> Ident {
    let mut name = base.to_string();
    while taken.iter().any(|t| t == &name) {
        name.push('_');
    }
    format_ident!("{}", name)
}

/// Names of every typed argument of a signature. A destructuring pattern
/// (`fn f((a, b): (i32, i32))`) has no name of its own, so the wrapper calls
/// its argument `argN`; the annotated item keeps the pattern, because the
/// wrapper passes the arguments on positionally.
fn typed_arg_names(sig: &syn::Signature) -> Vec<Ident> {
    sig.inputs
        .iter()
        .enumerate()
        .filter_map(|(i, arg)| match arg {
            FnArg::Typed(pat_type) => Some(match pat_type.pat.as_ref() {
                Pat::Ident(pi) => pi.ident.clone(),
                _ => format_ident!("arg{}", i),
            }),
            FnArg::Receiver(_) => None,
        })
        .collect()
}

/// `(name, type)` of every typed argument, in declaration order.
fn arg_pairs(sig: &syn::Signature) -> Vec<(Ident, Type)> {
    sig.inputs
        .iter()
        .filter_map(|a| match a {
            FnArg::Typed(pt) => Some((*pt.ty).clone()),
            FnArg::Receiver(_) => None,
        })
        .zip(typed_arg_names(sig))
        .map(|(ty, name)| (name, ty))
        .collect()
}

/// Wrapper-side view of one argument: `String` / `&str` become a
/// `(ptr, len)` byte pair (`conversion` rebuilds the Rust value under the
/// argument's own name, lossily for invalid UTF-8, never through
/// `from_utf8_unchecked`); everything else is passed through.
fn string_arg_conversion(
    name: &Ident,
    ty: &Type,
    taken: &[String],
) -> (Vec<TokenStream2>, Option<TokenStream2>) {
    if is_string_type(ty) {
        let p = fresh_ident(&format!("{name}_ptr"), taken);
        let l = fresh_ident(&format!("{name}_len"), taken);
        (
            vec![quote! { #p: *const u8 }, quote! { #l: usize }],
            Some(quote! {
                let #name = unsafe {
                    let slice = std::slice::from_raw_parts(#p, #l);
                    String::from_utf8_lossy(slice).into_owned()
                };
            }),
        )
    } else if is_str_ref_type(ty) {
        let p = fresh_ident(&format!("{name}_ptr"), taken);
        let l = fresh_ident(&format!("{name}_len"), taken);
        let b = fresh_ident(&format!("{name}_bytes"), taken);
        let c = fresh_ident(&format!("{name}_cow"), taken);
        (
            vec![quote! { #p: *const u8 }, quote! { #l: usize }],
            Some(quote! {
                let #b = unsafe { std::slice::from_raw_parts(#p, #l) };
                let #c = String::from_utf8_lossy(#b);
                let #name: &str = &#c;
            }),
        )
    } else {
        (vec![quote! { #name: #ty }], None)
    }
}

// ============================================================================
// The one wrapper generator (#279)
// ============================================================================

/// The receiver of a method wrapper: the wrapper takes `*const` / `*mut Struct`
/// and dereferences it into `self_obj`.
pub(crate) struct WrapperReceiver {
    /// Path of the receiver type. An in-crate flavour passes the bare struct
    /// name; the PyO3 wrapper crate of #275 passes `user_crate::module::Class`,
    /// because the type lives in a dependency.
    pub ty: syn::Path,
    /// The method's receiver (#509): the pointer the wrapper takes
    /// (`*mut` for a mutable one), how `self_obj` is bound, and the first
    /// argument of the call. Never [`Receiver::Static`] or unreadable — a
    /// static method has no `WrapperReceiver`, and an unreadable receiver is
    /// refused before a spec is built (`refusal::receiver_refusal`).
    pub shape: Receiver,
    /// The item's receiver as lifetime elision sees it (#484): the lifetime
    /// an elided output lifetime of the method takes. The wrapper's own
    /// receiver is a raw pointer, which has none.
    pub borrow: crate::environment::SelfBorrow,
}

/// The item the wrapper calls. Always the original, under its own name.
pub(crate) enum CallTarget {
    /// `f(args)` — a path, so the PyO3 wrapper crate of #275 can name
    /// `user_crate::module::f` while the in-crate flavours pass a bare name.
    Free(syn::Path),
    /// A method, called by path with the spec's receiver as its first
    /// argument, if it has one (#497, #509): `<Buf>::m` for an inherent
    /// method, `<Buf as tr::Far>::m` for a trait impl's. A path call reaches
    /// exactly this item — method-call syntax would need a trait in scope
    /// where the wrapper is emitted and would reach an inherent method of the
    /// same name first — and applies no receiver adjustment, so the argument
    /// is built from the receiver's declared shape. `ty` is the type as the
    /// wrapper spells it, for the panic message.
    Method { ty: syn::Path, path: syn::TypePath },
}

/// The last segment of a path, which is the name a human reads: the panic
/// message of a wrapper for `user_crate::geometry::Point::area` says
/// `Point::area`, not the whole path.
fn path_tail(path: &syn::Path) -> String {
    path.segments
        .last()
        .map(|s| s.ident.to_string())
        .unwrap_or_default()
}

/// How the wrapper hands the value back across the C ABI.
///
/// `syn::Type` is a large enum; the variants carry it by value because a
/// wrapper spec is built once per generated item and immediately consumed.
#[allow(clippy::large_enum_variant)]
pub(crate) enum WrapperReturn {
    /// No return value.
    Unit,
    /// Returned as written.
    Plain(Type),
    /// The value is boxed and returned as `*mut Struct` (constructors and
    /// anything returning `Self`). A path, see [`CallTarget::Free`].
    Boxed(syn::Path),
    /// `<helper> { ptr, len, cap }`, released through `<free>`.
    OwnedString {
        helper: Ident,
        free: Ident,
        /// Whether this wrapper declares the buffer type and its release
        /// function (false when a struct-level helper is shared).
        declare: bool,
    },
    /// `<helper> { ptr, len }` borrowed from the callee.
    BorrowedStr { helper: Ident, declare: bool },
    /// `CResult_<owner> { is_ok, ok_value, err_value }`.
    CResult {
        name: Ident,
        ok: WrapperPayload,
        err: WrapperPayload,
    },
    /// `COption_<owner> { is_some, value }`.
    COption { name: Ident, inner: WrapperPayload },
}

/// How one `Result` / `Option` payload is stored in the `#[repr(C)]` aggregate
/// the wrapper returns (#268).
///
/// A `String` / `&str` payload cannot be a field of that aggregate — it is not
/// FFI-safe and Julia could neither read nor release it — so it is lowered to
/// the very buffer a `String`-returning wrapper already hands back:
/// `<owner>_RustCallOwnedString { ptr, len, cap }`, released through
/// `<owner>_free_rust_string`. The `Result` / `Option` lowering and the string
/// lowering therefore compose, rather than one excluding the other.
///
/// A `&str` payload is **copied** into that buffer rather than borrowed: unlike
/// a bare `&str` return, a payload sits inside an aggregate that outlives the
/// call's temporaries in Julia's hands, and the borrowed-view optimisation
/// (`returns_borrowed_str`) would make its validity depend on where the `&str`
/// came from. One owned shape for every string payload is what keeps the
/// release rule "free exactly the active payload, through the owner's
/// `free_rust_string`" true in all cases.
#[allow(clippy::large_enum_variant)]
pub(crate) enum WrapperPayload {
    /// Stored as written.
    Plain(Type),
    /// A class value stored as an owning raw pointer. Julia reconstructs its
    /// opaque handle with the destructor from the same library generation.
    Boxed(syn::Path),
    /// A boxed `Result<Self, E>` payload, which also exports the producer's ABI
    /// marker ([`boxed_result_marker`]).
    BoxedVerified(syn::Path),
    /// `String` / `&str`, stored as `<helper> { ptr, len, cap }`.
    OwnedString {
        helper: Ident,
        free: Ident,
        /// Whether this wrapper declares the buffer type and its release
        /// function (false when a struct-level helper is shared).
        declare: bool,
    },
}

impl WrapperReturn {
    /// The item's types the wrapper hands back as written: a plain return, a
    /// boxed constructor's type, a `Result` / `Option` payload stored as is.
    /// A string is copied or viewed and is not one of them.
    fn passed_types(&self) -> Vec<TokenStream2> {
        let payload = |p: &WrapperPayload| match p {
            WrapperPayload::Plain(ty) => Some(quote! { #ty }),
            WrapperPayload::Boxed(path) | WrapperPayload::BoxedVerified(path) => {
                Some(quote! { #path })
            }
            WrapperPayload::OwnedString { .. } => None,
        };
        match self {
            WrapperReturn::Plain(ty) => vec![quote! { #ty }],
            WrapperReturn::Boxed(path) => vec![quote! { #path }],
            WrapperReturn::CResult { ok, err, .. } => {
                [ok, err].into_iter().filter_map(payload).collect()
            }
            WrapperReturn::COption { inner, .. } => payload(inner).into_iter().collect(),
            WrapperReturn::Unit
            | WrapperReturn::OwnedString { .. }
            | WrapperReturn::BorrowedStr { .. } => Vec::new(),
        }
    }

    /// The types of [`WrapperReturn::passed_types`] spelled from the item's
    /// signature, for `Self` to be spelled as the impl's type (#482). A boxed
    /// constructor's path is the caller's spelling of the struct already.
    fn types_mut(&mut self) -> Vec<&mut Type> {
        fn payload(p: &mut WrapperPayload) -> Option<&mut Type> {
            match p {
                WrapperPayload::Plain(ty) => Some(ty),
                _ => None,
            }
        }
        match self {
            WrapperReturn::Plain(ty) => vec![ty],
            WrapperReturn::CResult { ok, err, .. } => {
                [ok, err].into_iter().filter_map(payload).collect()
            }
            WrapperReturn::COption { inner, .. } => payload(inner).into_iter().collect(),
            _ => Vec::new(),
        }
    }
}

impl WrapperPayload {
    /// Whether the payload is stored exactly as the Rust signature wrote it.
    fn is_plain(&self) -> bool {
        matches!(self, WrapperPayload::Plain(_))
    }

    /// The type the payload occupies in the aggregate.
    fn stored_type(&self) -> Type {
        match self {
            WrapperPayload::Plain(ty) => ty.clone(),
            WrapperPayload::Boxed(ty) | WrapperPayload::BoxedVerified(ty) => {
                syn::parse_quote!(*mut #ty)
            }
            WrapperPayload::OwnedString { helper, .. } => syn::parse_quote!(#helper),
        }
    }

    /// The expression that turns the value bound to `value` into the stored
    /// form.
    fn store_expr(&self, value: &Ident) -> TokenStream2 {
        match self {
            WrapperPayload::Plain(_) => quote! { #value },
            WrapperPayload::Boxed(_) | WrapperPayload::BoxedVerified(_) => {
                quote! { Box::into_raw(Box::new(#value)) }
            }
            WrapperPayload::OwnedString { helper, .. } => quote! {{
                // `ToString` covers both `String` and a `&str` payload, which
                // is always copied (see the type docs).
                let mut rustcall_bytes = ToString::to_string(&#value).into_bytes();
                let rustcall_buf = #helper {
                    ptr: rustcall_bytes.as_mut_ptr(),
                    len: rustcall_bytes.len(),
                    cap: rustcall_bytes.capacity(),
                };
                ::std::mem::forget(rustcall_bytes);
                rustcall_buf
            }},
        }
    }

    /// The `(helper, free)` pair this payload wants declared, if it declares one.
    fn declaration(&self) -> Option<(&Ident, &Ident)> {
        match self {
            WrapperPayload::OwnedString {
                helper,
                free,
                declare: true,
            } => Some((helper, free)),
            _ => None,
        }
    }
}

/// Everything [`generate_wrapper`] needs: a signature model plus the call
/// target. Every flavour of `#[julia]` codegen fills this in and so gets
/// identical lowering by construction (#279).
pub(crate) struct WrapperSpec {
    /// Exported symbol, see the module docs.
    pub symbol: Ident,
    /// `#[cfg]` / `#[cfg_attr]` attributes replicated onto every generated item.
    pub cfg_attrs: Vec<Attribute>,
    pub receiver: Option<WrapperReceiver>,
    pub args: Vec<(Ident, Type)>,
    /// The wrapped item's generics as written (`fn f<'a>(..) where ..`). The
    /// wrapper declares its lifetime parameters and `where` clause after those
    /// of `host` ([`crate::environment`], #477, #482): an argument passed
    /// through as written (`other: &'a Buf`) names them, and a predicate can
    /// be the only proof the call is valid. Type and const parameters never
    /// reach a wrapper — a generic item is refused or monomorphized first.
    /// Empty where the arguments are spelled from a manifest.
    pub generics: syn::Generics,
    /// The impl block a method was written in: its generics join the
    /// wrapper's, and `Self` in the method's signature is spelled as its
    /// header's type (#482). `None` for a free function and for a wrapper
    /// whose types are spelled from a manifest.
    pub host: Option<ImplHost>,
    pub ret: WrapperReturn,
    pub target: CallTarget,
    /// Whether this wrapper may take a boundary guard from the file-level
    /// quiet-panic items (#304); see [`PanicHook`].
    pub panic_hook: PanicHook,
    /// Tokens appended to the call expression before the return lowering sees
    /// its value. Empty for every in-crate flavour; the PyO3 wrapper crate of
    /// #275 uses it to turn a `PyResult<T>` into a `Result<T, i32>` by
    /// **dropping** the `PyErr` — rendering one panics inside pyo3 without an
    /// interpreter, and that panic crossing `extern "C"` aborts the process.
    pub call_suffix: TokenStream2,
}

/// Whether a generated wrapper may use the file-level quiet-panic items (#304).
///
/// Rust runs the panic *hook* before the unwind `catch_unwind` catches, so a
/// panic RustCall handles correctly still prints `thread '<unnamed>' panicked
/// at ...` first. Silencing it needs a replacement hook that can tell "inside a
/// wrapper boundary" from "anywhere else", which in turn needs a thread-local
/// depth counter **shared by every wrapper in the image**: the one installed
/// hook can only see the counter it captured.
///
/// That sharing is what decides where the items live.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum PanicHook {
    /// The generator emits the whole file and puts [`panic_hook_items`] at its
    /// root, so every wrapper in it — including wrappers in submodules, which
    /// reach the items as `crate::__RustCallBoundary` — takes a boundary guard.
    /// The inline `rust"""` path and monomorphized generics are of this kind:
    /// they are compiled by `rustc` directly, with no dependency to reach.
    FileOwned,
    /// The items live in the [`RUNTIME_CRATE`] rlib the wrapper's crate already
    /// depends on, and the guard is taken through its path.
    ///
    /// This is what `#[julia]` uses. An attribute proc macro is handed one item
    /// and may only replace that item: it cannot see the crate's other
    /// `#[julia]` items, and has no reliable place to remember whether it
    /// already emitted the shared state, so it can never emit
    /// [`panic_hook_items`] itself. It does not have to. The crate already
    /// depends on `rustcall_julia_macros` — that is where `#[julia]` comes from
    /// — so the items can sit *there*, compiled once, and the wrapper names the
    /// guard by a Rust path like any other dependency. `#[no_mangle]` items of a
    /// dependency rlib are exported from the `cdylib` that links it, so Julia
    /// still finds [`INSTALL_PANIC_HOOK_SYMBOL`] on the image (#304).
    ///
    /// The generated PyO3 wrapper crate uses this too, even though it is a whole
    /// file RustCall writes: it links the same rlib, so emitting
    /// [`panic_hook_items`] as well would define `#[no_mangle]`
    /// [`INSTALL_PANIC_HOOK_SYMBOL`] twice in one `cdylib`. One image, one hook,
    /// one depth counter — shared with the `#[julia]` wrappers of the crate it
    /// wraps, which is exactly what makes both quiet.
    Runtime,
    /// No boundary guard at all: the default hook stays. Nothing RustCall
    /// generates chooses this today; it is the conservative default of
    /// [`FreeFnOptions`], because a wrapper that takes no guard merely keeps the
    /// default hook while one that takes a guard it cannot name does not
    /// compile.
    External,
}

/// Suffix of the panic-channel reader a wrapper exports next to itself.
pub const PANIC_SYMBOL_SUFFIX: &str = "_take_panic";

/// The crate that carries [`panic_hook_items`] for [`PanicHook::Runtime`].
///
/// Every crate that uses `#[julia]` depends on it already — it is where the
/// attribute comes from — and every `Cargo.toml` RustCall writes for a crate
/// with generated wrappers declares it too (`rustcall_runtime_crate_path`, used
/// by `generate_wrapper_cargo_toml` in `src/crate_bindings/crate_bindings.jl`
/// and `generate_pyo3_wrapper_cargo_toml` in `src/pyo3/pyo3.jl`), all pointing at the one
/// directory — two copies in one `cdylib` would each define
/// [`INSTALL_PANIC_HOOK_SYMBOL`]. The path is spelled `::rustcall_julia_macros`,
/// so a module of any depth reaches it and no local item can shadow it; the one
/// thing that breaks is renaming the dependency in `Cargo.toml`, which
/// `docs/src/panics.md` records.
pub const RUNTIME_CRATE: &str = "rustcall_julia_macros";

/// The symbol a file-owned artifact exports to install its quiet panic hook.
/// Julia resolves it once per image, at load time (`src/loading/loadpolicy.jl`).
///
/// # Why the `__rustcall_` prefix
///
/// Julia calls whatever it finds under this name as `extern "C" fn()`, so the
/// name must be one the symbol scheme can never produce for a user's item. A
/// wrapper is `rustcall_<stem>` — so `#[julia] fn install_panic_hook` would have
/// exported `rustcall_install_panic_hook`, and calling *that* through a
/// zero-argument signature crosses the boundary wrongly (#388 review). Every
/// name the scheme derives is `rustcall_<stem>` or `<stem>_<known suffix>`
/// (`_free`, `_clone`, `_get_<field>`, `_set_<field>`, `_free_rust_string`,
/// `_take_panic`), and `_hook` is not among the suffixes, so a doubled prefix is
/// unreachable from any Rust identifier. `__rustcall_` is reserved for RustCall;
/// `docs/src/panics.md` says so.
pub const INSTALL_PANIC_HOOK_SYMBOL: &str = "__rustcall_install_panic_hook";

/// The symbol that removes the hook again, called before `dlclose`. Named like
/// [`INSTALL_PANIC_HOOK_SYMBOL`], for the same reason.
pub const UNINSTALL_PANIC_HOOK_SYMBOL: &str = "__rustcall_uninstall_panic_hook";

/// The panic-channel reader of the wrapper exported as `symbol`.
pub fn panic_symbol(symbol: &str) -> String {
    format!("{}{PANIC_SYMBOL_SUFFIX}", unraw(symbol))
}

/// The per-wrapper panic channel: a thread-local message slot and the
/// `extern "C"` reader Julia polls after every call (#244).
///
/// # Why one channel per wrapper rather than one per crate
///
/// The obvious design — a single `rustcall_take_last_panic` per library —
/// cannot be emitted reliably by a proc macro. `#[julia]` expands one item at a
/// time and has no crate-wide state it may depend on, so "emit these three
/// items exactly once per crate" is either a mutable static in the macro
/// (fragile, and silently produces duplicate symbols when it is wrong) or a
/// convention the user has to follow. Worse, wherever the shared items landed,
/// a wrapper in a *different module* could not name them: a `#[no_mangle]`
/// symbol is not a Rust path, and reaching it would need an `extern "C"`
/// block, which edition 2024 requires to be written `unsafe extern` — so the
/// generated code would depend on the user crate's edition.
///
/// A channel per wrapper has none of those problems: the slot and its reader
/// sit in the same module as the wrapper that writes them, are named after a
/// symbol that is already unique, need no crate-wide coordination and no
/// `extern` block, and make every library self-contained (a generated `cdylib`
/// does not link `rustcall_helpers`). The cost is one thread-local and one exported
/// symbol per `#[julia]` item.
///
/// # Protocol
///
/// `<symbol>_take_panic(out, cap) -> usize` returns the byte length of the
/// pending message, or 0 when there is none. The slot is cleared **only** when
/// the whole message fitted in `cap`, so a caller that guessed too small a
/// buffer can simply call again with the length it was told. Nothing is
/// allocated across the boundary and there is nothing to free.
fn panic_channel(cfg_attrs: &[Attribute], slot: &Ident, reader: &Ident) -> TokenStream2 {
    quote! {
        #(#cfg_attrs)*
        thread_local! {
            static #slot: ::std::cell::RefCell<::std::option::Option<::std::string::String>> =
                ::std::cell::RefCell::new(::std::option::Option::None);
        }

        #(#cfg_attrs)*
        #[no_mangle]
        pub extern "C" fn #reader(out: *mut u8, cap: usize) -> usize {
            #slot.with(|rustcall_slot| {
                let mut rustcall_slot = rustcall_slot.borrow_mut();
                // Finalizers only need a failure count, not its text. This
                // reserved request consumes the channel without allocating a
                // Julia message buffer or leaving a stale panic for a later
                // call. Ordinary null/zero length queries still retain it.
                if out.is_null() && cap == usize::MAX {
                    return rustcall_slot.take().map_or(0, |message| message.len());
                }
                let rustcall_len = match rustcall_slot.as_ref() {
                    ::std::option::Option::Some(message) => {
                        let bytes = message.as_bytes();
                        if bytes.len() <= cap && !out.is_null() {
                            unsafe {
                                ::std::ptr::copy_nonoverlapping(bytes.as_ptr(), out, bytes.len());
                            }
                            Some(bytes.len())
                        } else {
                            // Too small a buffer: report the length and keep
                            // the message so the caller can ask again.
                            return bytes.len();
                        }
                    }
                    ::std::option::Option::None => ::std::option::Option::None,
                };
                match rustcall_len {
                    ::std::option::Option::Some(n) => {
                        *rustcall_slot = ::std::option::Option::None;
                        n
                    }
                    ::std::option::Option::None => 0,
                }
            })
        }
    }
}

/// Whether `items` already declares the quiet-panic hook.
///
/// `specialize` is handed a source that is sometimes the *expanded* form of a
/// block — a generic struct registers the expansion, wrappers and all — so
/// adding the items unconditionally would define them twice. Asking first makes
/// the insertion idempotent for any input that is already a generated file.
pub fn panic_hook_items_present(items: &[Item]) -> bool {
    items.iter().any(|item| match item {
        Item::Struct(s) => s.ident == "__RustCallBoundary",
        Item::Fn(f) => f.sig.ident == INSTALL_PANIC_HOOK_SYMBOL,
        _ => false,
    })
}

/// The four items a file-owned artifact keeps at its root so that a panic
/// RustCall catches leaves no `panicked at` line on stderr (#304).
///
/// * a thread-local **depth counter**, raised while a thread is inside any
///   wrapper's boundary;
/// * the **hook**: silent while the depth is non-zero, delegating to the hook
///   it replaced otherwise, so a panic *outside* a boundary — on a thread the
///   artifact's own code spawned, say — still prints exactly as before;
/// * `__rustcall_install_panic_hook`, which Julia calls once per image right
///   after `dlopen`, before any wrapper can run. Installing from Julia rather
///   than lazily from the first wrapper call is what removes the race #302's
///   attempt had: there is no first call to lose it;
/// * `__rustcall_uninstall_panic_hook`, called before `dlclose` so the closure is
///   out of the registry before its code is unmapped.
///
/// Install and uninstall are **repeatable**, guarded by one mutex rather than a
/// `Once`: an image can be reopened while it is still mapped — a `dlopen` of the
/// same path racing the last `dlclose` — and a `Once` would leave that reopened
/// image without a hook for the rest of the process (#388 review).
///
/// The uninstaller restores std's **default** hook rather than the exact hook
/// that was replaced: naming the hook's argument type (`PanicHookInfo`, renamed
/// from `PanicInfo` in 1.81) to store it would pin a minimum Rust version on
/// every generated artifact. The two differ only if the artifact's own code
/// installed a hook before RustCall's load-time install, which runs before any
/// of that code does; what matters for safety is that *our* closure leaves the
/// registry, and `take_hook` does that.
/// No item here carries an `allow` attribute, and none needs one: every
/// artifact these items land in is a `cdylib`, where a `pub` item at the crate
/// root is externally reachable and never reported as dead. Attributes and doc
/// text emitted here also land in the generated source, where the `#[cfg_attr]`
/// tests count what a user's own attribute did (`tests/cfg_pruning.rs`).
pub fn panic_hook_items() -> TokenStream2 {
    let install = format_ident!("{}", INSTALL_PANIC_HOOK_SYMBOL);
    let uninstall = format_ident!("{}", UNINSTALL_PANIC_HOOK_SYMBOL);
    // `__RUSTCALL_PANIC_*` is the panic-channel slot namespace — the slot of a
    // wrapper named `hook_once` would be `__RUSTCALL_PANIC_HOOK_ONCE` — so these
    // statics take a namespace of their own (#338).
    quote! {
        thread_local! {
            // `const`-initialised: the runtime crate is real source that CI
            // runs clippy over, and `thread_local_initializer_can_be_made_const`
            // fires otherwise. It is also the faster access path.
            static __RUSTCALL_QUIET_DEPTH: ::std::cell::Cell<usize> =
                const { ::std::cell::Cell::new(0) };
        }

        /// `true` while this image's hook is the one std will call. A mutex, not a
        /// `Once`: installing again after an uninstall has to work.
        static __RUSTCALL_QUIET_HOOK_LIVE: ::std::sync::Mutex<bool> =
            ::std::sync::Mutex::new(false);

        /// Raises the boundary depth for as long as a wrapper body runs, so the
        /// hook above knows the panic it is about to print is one Julia will
        /// raise as `RustCall.RustPanicError` instead.
        pub struct __RustCallBoundary;

        impl __RustCallBoundary {
            pub fn enter() -> Self {
                // `try_with`, not `with`: a wrapper may run while this thread's
                // TLS is being torn down, and a boundary that cannot count is
                // better than a panic inside the panic machinery.
                let _ = __RUSTCALL_QUIET_DEPTH.try_with(|depth| depth.set(depth.get() + 1));
                Self
            }
        }

        impl ::std::ops::Drop for __RustCallBoundary {
            fn drop(&mut self) {
                let _ = __RUSTCALL_QUIET_DEPTH
                    .try_with(|depth| depth.set(depth.get().saturating_sub(1)));
            }
        }

        #[no_mangle]
        pub extern "C" fn #install() {
            // A poisoned lock means a panic inside this function, which cannot
            // happen; leaving the default hook in place is the safe answer.
            if let ::std::result::Result::Ok(mut rustcall_live) =
                __RUSTCALL_QUIET_HOOK_LIVE.lock()
            {
                if !*rustcall_live {
                    let rustcall_previous = ::std::panic::take_hook();
                    ::std::panic::set_hook(::std::boxed::Box::new(move |rustcall_info| {
                        if __RUSTCALL_QUIET_DEPTH.try_with(|depth| depth.get()).unwrap_or(0) == 0 {
                            rustcall_previous(rustcall_info);
                        }
                    }));
                    *rustcall_live = true;
                }
            }
        }

        #[no_mangle]
        pub extern "C" fn #uninstall() {
            if let ::std::result::Result::Ok(mut rustcall_live) =
                __RUSTCALL_QUIET_HOOK_LIVE.lock()
            {
                if *rustcall_live {
                    let _ = ::std::panic::take_hook();
                    *rustcall_live = false;
                }
            }
        }
    }
}

/// The source of the [`RUNTIME_CRATE`]'s runtime module: exactly the items
/// [`panic_hook_items`] emits, formatted.
///
/// `deps/rustcall_julia_macros/src/rt.rs` is this string run through `rustfmt`,
/// checked in, and compared against the generator by `tests/runtime_crate.rs` —
/// as syntax trees, since the two formatters disagree about layout and nothing
/// else (regenerate with `UPDATE_GOLDEN=1 cargo test`, then `cargo fmt`). It is
/// a checked-in file rather than a
/// `build.rs` output because the crate is compiled into every user `cdylib`
/// and must stay readable, buildable and diffable without running a generator —
/// but it is generated from the one definition, so the hook a `#[julia]` crate
/// gets and the hook an inline block gets cannot drift apart.
pub fn runtime_module_source() -> String {
    let file: File =
        syn::parse2(panic_hook_items()).expect("the quiet-hook items are not a valid Rust file");
    format!(
        "// GENERATED by `rustcall_julia_core::codegen::runtime_module_source`. DO NOT EDIT.\n\
         // Regenerate with `UPDATE_GOLDEN=1 cargo test` in `deps/rustcall_julia_core`,\n\
         // then `cargo fmt` here;\n\
         // `tests/runtime_crate.rs` fails if this file and the generator disagree.\n\
         //\n\
         // These are the same items `panic_hook_items()` puts at the root of a file\n\
         // RustCall writes whole (#304). Here they are compiled once, into the crate\n\
         // every `#[julia]` crate already depends on, so a `#[julia]` wrapper can take\n\
         // the boundary guard by path and the `cdylib` still exports\n\
         // `__rustcall_install_panic_hook` for Julia to call.\n\
         \n{}",
        prettyplease::unparse(&file)
    )
}

/// The body of a generated wrapper, with the user's code inside
/// `catch_unwind`.
///
/// A panic no longer crosses `extern "C"` at all: it is caught, its message is
/// recorded in this wrapper's channel, and a sentinel of the right shape is
/// returned. Julia reads the channel after the call and raises
/// `RustCall.RustPanicError` — the process survives and the failure is
/// catchable, which is what #244 asks for.
///
/// The prologue (string argument conversion, receiver binding) runs *inside*
/// the closure: converting a `(ptr, len)` pair can itself panic, and that panic
/// must be contained too.
///
/// `AssertUnwindSafe` is required because the closure captures raw pointers and
/// `&mut` receivers. The assertion is sound for the use RustCall makes of it:
/// on the unwind path the sentinel is returned to Julia, which raises
/// immediately, so no Rust code observes a value the panic may have left
/// half-updated. What the *user's* `&mut self` looks like afterwards is their
/// business — the object is still theirs, and the exception says so.
fn guarded_body(
    julia_name: &str,
    slot: &Ident,
    prologue: &TokenStream2,
    body: TokenStream2,
    sentinel: TokenStream2,
    returns_unit: bool,
    hook: PanicHook,
) -> TokenStream2 {
    // A unit-returning wrapper must not *evaluate* to `()`: clippy's
    // `unused_unit` fires on the generated `Ok(v) => v` arm, and the match is a
    // statement there anyway.
    let ok_arm = if returns_unit {
        quote! { ::std::result::Result::Ok(_) => {} }
    } else {
        quote! { ::std::result::Result::Ok(rustcall_value) => rustcall_value, }
    };
    // The guard is taken *outside* `catch_unwind`, so the prologue — string
    // conversions, receiver binding — is inside the boundary too, and it is
    // dropped after the message has been recorded.
    let boundary = match hook {
        PanicHook::FileOwned => quote! {
            let _rustcall_boundary = crate::__RustCallBoundary::enter();
        },
        PanicHook::Runtime => {
            let krate = format_ident!("{}", RUNTIME_CRATE);
            quote! {
                let _rustcall_boundary = ::#krate::__RustCallBoundary::enter();
            }
        }
        PanicHook::External => TokenStream2::new(),
    };
    quote! {
        #boundary
        match ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| {
            #prologue
            #body
        })) {
            #ok_arm
            ::std::result::Result::Err(rustcall_payload) => {
                // `panic!("...")` with a literal gives `&'static str`; with
                // arguments, `String`. Anything else came from
                // `panic_any` and has no text.
                let rustcall_message: ::std::string::String =
                    if let ::std::option::Option::Some(s) =
                        rustcall_payload.downcast_ref::<&'static str>()
                    {
                        ::std::string::ToString::to_string(s)
                    } else if let ::std::option::Option::Some(s) =
                        rustcall_payload.downcast_ref::<::std::string::String>()
                    {
                        s.clone()
                    } else {
                        ::std::string::ToString::to_string("Box<dyn Any>")
                    };
                let rustcall_message = ::std::format!(
                    "{} panicked: {}", #julia_name, rustcall_message);
                #slot.with(|rustcall_slot| {
                    *rustcall_slot.borrow_mut() =
                        ::std::option::Option::Some(rustcall_message);
                });
                #sentinel
            }
        }
    }
}

/// The single `extern "C"` wrapper generator: every entry point of this module
/// goes through it, so the string ABI, the `#[cfg]` propagation, the receiver
/// handling and the panic boundary cannot diverge between flavours.
///
/// A signature the wrapper cannot express is refused (#482, #484) — decided
/// by [`wrapper_tokens`], and asked for ahead of generation by
/// [`crate::refusal`] so the manifest records it (#503). Every caller in
/// this module asks first, so the refusal emitted here is reached only by a
/// wrapper spelled from a manifest (`crate::wrap`) or an instantiation
/// (`crate::specialize`).
pub(crate) fn generate_wrapper(spec: WrapperSpec) -> TokenStream2 {
    let cfgs = spec.cfg_attrs.clone();
    match wrapper_tokens(spec) {
        Ok(tokens) => tokens,
        Err(refusal) => refusal.compile_error(&cfgs),
    }
}

/// The refusal [`generate_wrapper`] would emit for `spec`, if any: the
/// wrapper-level half of [`crate::refusal`] (#503).
fn wrapper_refusal(spec: WrapperSpec) -> Option<Refusal> {
    wrapper_tokens(spec).err()
}

/// [`generate_wrapper`]'s body: the wrapper, or why it cannot be written.
fn wrapper_tokens(spec: WrapperSpec) -> Result<TokenStream2, Refusal> {
    let WrapperSpec {
        symbol,
        cfg_attrs,
        receiver,
        mut args,
        generics,
        host,
        mut ret,
        target,
        call_suffix,
        panic_hook,
    } = spec;

    // The Julia-facing name this wrapper stands for, used in the panic
    // message. Derived from the call target rather than from the symbol, so
    // the message reads `Point::area panicked: ...` and not
    // `rustcall_Point_area panicked: ...`.
    let julia_name = match &target {
        CallTarget::Free(name) => path_tail(name),
        CallTarget::Method { ty, path } => {
            format!("{}::{}", path_tail(ty), path_tail(&path.path))
        }
    };

    // The wrapper's environment is the item's, verbatim, with `Self` spelled
    // as the impl header's type (#482, `crate::environment`).
    let mut environment = crate::environment::wrapper_environment(host.as_ref(), &generics);
    if let Some(host) = &host {
        let mut out_of_scope = crate::environment::expand_self(host, &mut environment);
        for (_, ty) in args.iter_mut() {
            out_of_scope = out_of_scope.or(crate::environment::expand_self_in_type(host, ty));
        }
        for ty in ret.types_mut() {
            out_of_scope = out_of_scope.or(crate::environment::expand_self_in_type(host, ty));
        }
        if let Some(span) = out_of_scope {
            return Err(crate::environment::out_of_scope_error(
                span,
                host,
                &julia_name,
            ));
        }
    }
    let spelled_types = {
        let arg_types = args.iter().map(|(_, ty)| ty);
        let returned = ret.passed_types();
        // `Generics` prints its parameters only; the `where` clause is apart.
        let predicates = &environment.where_clause;
        quote! { #environment #predicates #(#arg_types)* #(#returned)* }
    };
    if let Some((span, in_macro)) = crate::environment::leftover_self(spelled_types) {
        return Err(crate::environment::leftover_self_error(
            span,
            in_macro.as_deref(),
            &julia_name,
        ));
    }
    // An elided output lifetime takes the one Rust's elision rules pick on
    // the item's signature, spelled out: the wrapper's own inputs are raw
    // pointers and byte pairs, from which elision would pick nothing (#484).
    let borrow = receiver
        .as_ref()
        .map(|r| r.borrow.clone())
        .unwrap_or(crate::environment::SelfBorrow::None);
    match crate::environment::name_elided_return(
        &mut environment,
        &borrow,
        &mut args,
        ret.types_mut(),
        &julia_name,
    ) {
        crate::environment::ElidedReturn::Named => {}
        crate::environment::ElidedReturn::Undecidable => return Ok(TokenStream2::new()),
        crate::environment::ElidedReturn::Refused(refusal) => return Err(refusal),
    }
    if let Some(refusal) = crate::environment::lowered_lifetime_error(
        &environment,
        &args,
        &ret.passed_types(),
        &julia_name,
    ) {
        return Err(refusal);
    }

    let taken: Vec<String> = args.iter().map(|(n, _)| n.to_string()).collect();
    let ptr = fresh_ident("ptr", &taken);
    let self_obj = fresh_ident("self_obj", &taken);

    let mut wrapper_args: Vec<TokenStream2> = Vec::new();
    let mut conversions: Vec<TokenStream2> = Vec::new();
    let mut call_args: Vec<TokenStream2> = Vec::new();

    if let Some(r) = &receiver {
        let ty = &r.ty;
        wrapper_args.push(if r.shape.is_mutable() {
            quote! { #ptr: *mut #ty }
        } else {
            quote! { #ptr: *const #ty }
        });
    }
    for (name, ty) in &args {
        let (a, conversion) = string_arg_conversion(name, ty, &taken);
        wrapper_args.extend(a);
        conversions.extend(conversion);
        call_args.push(quote! { #name });
    }
    // A lifetime the wrapper's signature and predicates name nowhere — one
    // only a lowered string named, say — is left out (#482).
    let signature = {
        let returned = ret.passed_types();
        quote! { #(#wrapper_args)* #(#returned)* }
    };
    let environment = crate::environment::prune_unused_lifetimes(environment, signature);
    let (lifetimes, _, lifetime_where) = environment.split_for_impl();

    let self_binding = receiver
        .as_ref()
        .map(|r| r.shape.binding(&self_obj, &ptr))
        .unwrap_or_default();
    let call = match &target {
        CallTarget::Free(name) => quote! { #name(#(#call_args),*) },
        CallTarget::Method { path, .. } => {
            let self_arg = receiver.as_ref().and_then(|r| r.shape.argument(&self_obj));
            let args = self_arg.into_iter().chain(call_args.iter().cloned());
            quote! { #path(#(#args),*) }
        }
    };
    let call = quote! { #call #call_suffix };
    let prologue = quote! { #(#conversions)* #self_binding };

    let slot = format_ident!("__RUSTCALL_PANIC_{}", symbol.to_string().to_uppercase());
    let reader = format_ident!("{}", panic_symbol(&symbol.to_string()));

    let mut out = TokenStream2::new();
    out.extend(panic_channel(&cfg_attrs, &slot, &reader));

    let wrapper = match ret {
        WrapperReturn::Unit => {
            let guarded = guarded_body(
                &julia_name,
                &slot,
                &prologue,
                quote! { #call },
                quote! {},
                true,
                panic_hook,
            );
            quote! {
                #(#cfg_attrs)*
                #[no_mangle]
                pub extern "C" fn #symbol #lifetimes (#(#wrapper_args),*) #lifetime_where {
                    #guarded
                }
            }
        }
        WrapperReturn::Plain(ty) => {
            // The value leaves as `MaybeUninit<T>` (#462). Nothing checks that
            // a plain return type is valid all-zero — `&T`, `Box<T>`,
            // `NonZero*`, a fn pointer, a user `#[repr(C)]` struct holding one
            // all reach this arm — so a `mem::zeroed::<T>()` sentinel hit
            // rustc's non-unwinding "attempted to zero-initialize" check and
            // aborted the process on the very panic the boundary exists to
            // contain. `MaybeUninit::zeroed()` has no validity requirement,
            // and `MaybeUninit<T>` is guaranteed the size, alignment and
            // **ABI** of `T`, so the C signature Julia calls is unchanged
            // (and `improper_ctypes_definitions` still judges `T` itself).
            // Julia reads the panic channel and raises before it looks at the
            // sentinel.
            let sentinel = quote! { ::std::mem::MaybeUninit::zeroed() };
            let guarded = guarded_body(
                &julia_name,
                &slot,
                &prologue,
                quote! { ::std::mem::MaybeUninit::new(#call) },
                sentinel,
                false,
                panic_hook,
            );
            quote! {
                #(#cfg_attrs)*
                #[no_mangle]
                pub extern "C" fn #symbol #lifetimes (#(#wrapper_args),*) -> ::std::mem::MaybeUninit<#ty> #lifetime_where {
                    #guarded
                }
            }
        }
        WrapperReturn::Boxed(ty) => {
            let body = quote! {
                let obj = #call;
                Box::into_raw(Box::new(obj))
            };
            let guarded = guarded_body(
                &julia_name,
                &slot,
                &prologue,
                body,
                quote! { ::std::ptr::null_mut() },
                false,
                panic_hook,
            );
            quote! {
                #(#cfg_attrs)*
                #[no_mangle]
                pub extern "C" fn #symbol #lifetimes (#(#wrapper_args),*) -> *mut #ty #lifetime_where {
                    #guarded
                }
            }
        }
        WrapperReturn::OwnedString {
            helper,
            free,
            declare,
        } => {
            if declare {
                out.extend(owned_string_helper(&cfg_attrs, &helper, &free));
            }
            let body = quote! {
                let rustcall_value = #call;
                // `ToString` covers both `String` and a `&str` result that
                // must be copied because it may borrow from a converted
                // argument (see `returns_copied_str`).
                let mut rustcall_bytes = ToString::to_string(&rustcall_value).into_bytes();
                let rustcall_ret = #helper {
                    ptr: rustcall_bytes.as_mut_ptr(),
                    len: rustcall_bytes.len(),
                    cap: rustcall_bytes.capacity(),
                };
                std::mem::forget(rustcall_bytes);
                rustcall_ret
            };
            // An empty buffer: `ptr` is null and `cap == 0`, so the release
            // function is a no-op on it.
            let sentinel = quote! {
                #helper { ptr: ::std::ptr::null_mut(), len: 0, cap: 0 }
            };
            let guarded = guarded_body(
                &julia_name,
                &slot,
                &prologue,
                body,
                sentinel,
                false,
                panic_hook,
            );
            quote! {
                #(#cfg_attrs)*
                #[no_mangle]
                pub extern "C" fn #symbol #lifetimes (#(#wrapper_args),*) -> #helper #lifetime_where {
                    #guarded
                }
            }
        }
        WrapperReturn::BorrowedStr { helper, declare } => {
            if declare {
                out.extend(borrowed_string_helper(&cfg_attrs, &helper));
            }
            let body = quote! {
                let rustcall_value = #call;
                #helper {
                    ptr: rustcall_value.as_ptr(),
                    len: rustcall_value.len(),
                }
            };
            let sentinel = quote! {
                #helper { ptr: ::std::ptr::null(), len: 0 }
            };
            let guarded = guarded_body(
                &julia_name,
                &slot,
                &prologue,
                body,
                sentinel,
                false,
                panic_hook,
            );
            quote! {
                #(#cfg_attrs)*
                #[no_mangle]
                pub extern "C" fn #symbol #lifetimes (#(#wrapper_args),*) -> #helper #lifetime_where {
                    #guarded
                }
            }
        }
        WrapperReturn::CResult { name, ok, err } => {
            if matches!(ok, WrapperPayload::BoxedVerified(_)) {
                // Fail closed if a newer extractor sees a crate built with an
                // older macro whose Result<Self, E> ABI returned Self by value.
                let marker = format_ident!("{}", boxed_result_marker(&symbol.to_string()));
                out.extend(quote! {
                    #(#cfg_attrs)*
                    #[no_mangle]
                    pub extern "C" fn #marker() -> u8 { 1 }
                });
            }
            out.extend(payload_helpers(&cfg_attrs, &[&ok, &err]));
            out.extend(generate_c_result_type(
                &name,
                &ok.stored_type(),
                &err.stored_type(),
                &cfg_attrs,
            ));
            // `is_ok = 0` with an uninitialized payload: the `Err` branch, and
            // Julia raises before it decodes either payload.
            let sentinel = quote! { #name::panicked() };
            // With no payload to lower the `Result` goes straight in; the
            // re-wrapping match exists only to convert a string payload.
            let body = if ok.is_plain() && err.is_plain() {
                quote! { #name::new(#call) }
            } else {
                let ok_binding = fresh_ident("rustcall_ok", &taken);
                let err_binding = fresh_ident("rustcall_err", &taken);
                let ok_store = ok.store_expr(&ok_binding);
                let err_store = err.store_expr(&err_binding);
                quote! {
                    #name::new(match #call {
                        ::std::result::Result::Ok(#ok_binding) =>
                            ::std::result::Result::Ok(#ok_store),
                        ::std::result::Result::Err(#err_binding) =>
                            ::std::result::Result::Err(#err_store),
                    })
                }
            };
            let guarded = guarded_body(
                &julia_name,
                &slot,
                &prologue,
                body,
                sentinel,
                false,
                panic_hook,
            );
            quote! {
                #(#cfg_attrs)*
                #[no_mangle]
                pub extern "C" fn #symbol #lifetimes (#(#wrapper_args),*) -> #name #lifetime_where {
                    #guarded
                }
            }
        }
        WrapperReturn::COption { name, inner } => {
            out.extend(payload_helpers(&cfg_attrs, &[&inner]));
            out.extend(generate_c_option_type(
                &name,
                &inner.stored_type(),
                &cfg_attrs,
            ));
            let sentinel = quote! { #name::panicked() };
            let body = if inner.is_plain() {
                quote! { #name::new(#call) }
            } else {
                let binding = fresh_ident("rustcall_some", &taken);
                let store = inner.store_expr(&binding);
                quote! {
                    #name::new(match #call {
                        ::std::option::Option::Some(#binding) =>
                            ::std::option::Option::Some(#store),
                        ::std::option::Option::None => ::std::option::Option::None,
                    })
                }
            };
            let guarded = guarded_body(
                &julia_name,
                &slot,
                &prologue,
                body,
                sentinel,
                false,
                panic_hook,
            );
            quote! {
                #(#cfg_attrs)*
                #[no_mangle]
                pub extern "C" fn #symbol #lifetimes (#(#wrapper_args),*) -> #name #lifetime_where {
                    #guarded
                }
            }
        }
    };
    out.extend(wrapper);
    Ok(out)
}

/// [`owned_string_helper`] with no `#[cfg]` attributes, for a generator that
/// emits the buffer next to a struct rather than next to a function: the PyO3
/// wrapper crate of #275 shares one buffer type per `#[pyclass]`.
pub(crate) fn owned_string_helper_items(helper: &Ident, free: &Ident) -> TokenStream2 {
    owned_string_helper(&[], helper, free)
}

/// The string buffer types the payloads of one `Result` / `Option` wrapper
/// need declared. Both payloads of a `Result<String, String>` share the owner's
/// single buffer type, so it is emitted once (#268).
fn payload_helpers(cfg_attrs: &[Attribute], payloads: &[&WrapperPayload]) -> TokenStream2 {
    let mut out = TokenStream2::new();
    let mut declared: Vec<String> = Vec::new();
    for p in payloads {
        if let Some((helper, free)) = p.declaration() {
            if declared.contains(&helper.to_string()) {
                continue;
            }
            declared.push(helper.to_string());
            out.extend(owned_string_helper(cfg_attrs, helper, free));
        }
    }
    out
}

/// The owned string buffer `<name> { ptr, len, cap }` and the `extern "C"`
/// function that releases it (the Rust `Vec` is reconstructed and dropped).
fn owned_string_helper(cfg_attrs: &[Attribute], helper: &Ident, free: &Ident) -> TokenStream2 {
    quote! {
        #(#cfg_attrs)*
        #[repr(C)]
        pub struct #helper {
            pub ptr: *mut u8,
            pub len: usize,
            pub cap: usize,
        }

        #(#cfg_attrs)*
        #[no_mangle]
        pub extern "C" fn #free(ptr: *mut u8, len: usize, cap: usize) {
            if !ptr.is_null() {
                unsafe { drop(Vec::from_raw_parts(ptr, len, cap)); }
            }
        }
    }
}

/// The borrowed string view `<name> { ptr, len }`.
fn borrowed_string_helper(cfg_attrs: &[Attribute], helper: &Ident) -> TokenStream2 {
    quote! {
        #(#cfg_attrs)*
        #[repr(C)]
        pub struct #helper {
            pub ptr: *const u8,
            pub len: usize,
        }
    }
}

fn generate_c_result_type(
    name: &Ident,
    ok_type: &Type,
    err_type: &Type,
    cfg_attrs: &[Attribute],
) -> TokenStream2 {
    quote! {
        #(#cfg_attrs)*
        #[repr(C)]
        pub struct #name {
            // Private: the discriminant and the payloads must stay consistent,
            // or `ok()` / `err()` would read uninitialized memory. The C layout
            // (u8 followed by both payloads) is unchanged.
            is_ok: u8,
            /// Only initialized when `is_ok == 1`. `MaybeUninit` keeps the
            /// inactive field free of validity invariants (e.g. `NonZeroU32`).
            ok_value: ::std::mem::MaybeUninit<#ok_type>,
            /// Only initialized when `is_ok == 0`.
            err_value: ::std::mem::MaybeUninit<#err_type>,
        }

        #(#cfg_attrs)*
        impl #name {
            /// Wrap a `Result` in the C-compatible representation.
            pub fn new(value: Result<#ok_type, #err_type>) -> Self {
                match value {
                    Ok(v) => Self {
                        is_ok: 1,
                        ok_value: ::std::mem::MaybeUninit::new(v),
                        err_value: ::std::mem::MaybeUninit::zeroed(),
                    },
                    Err(e) => Self {
                        is_ok: 0,
                        ok_value: ::std::mem::MaybeUninit::zeroed(),
                        err_value: ::std::mem::MaybeUninit::new(e),
                    },
                }
            }
            /// Whether the call succeeded.
            pub fn is_ok(&self) -> bool {
                self.is_ok == 1
            }
            /// The `Ok` value, if any.
            pub fn ok(&self) -> Option<&#ok_type> {
                if self.is_ok == 1 { Some(unsafe { self.ok_value.assume_init_ref() }) } else { None }
            }
            /// The `Err` value, if any.
            pub fn err(&self) -> Option<&#err_type> {
                if self.is_ok == 0 { Some(unsafe { self.err_value.assume_init_ref() }) } else { None }
            }
            /// The value returned after a caught panic (#244): the `Err`
            /// discriminant with **no** payload initialized.
            ///
            /// Julia reads this wrapper's panic channel before it decodes
            /// anything, and raises `RustPanicError`, so neither payload is
            /// ever observed. Both stay `MaybeUninit::zeroed()`, which is what
            /// `new` already writes for the inactive side.
            pub fn panicked() -> Self {
                Self {
                    is_ok: 0,
                    ok_value: ::std::mem::MaybeUninit::zeroed(),
                    err_value: ::std::mem::MaybeUninit::zeroed(),
                }
            }
        }
    }
}

fn generate_c_option_type(
    name: &Ident,
    inner_type: &Type,
    cfg_attrs: &[Attribute],
) -> TokenStream2 {
    quote! {
        #(#cfg_attrs)*
        #[repr(C)]
        pub struct #name {
            // Private, see the CResult type: the discriminant guards a
            // `MaybeUninit` payload. The C layout is unchanged.
            is_some: u8,
            /// Only initialized when `is_some == 1`.
            value: ::std::mem::MaybeUninit<#inner_type>,
        }

        #(#cfg_attrs)*
        impl #name {
            /// Wrap an `Option` in the C-compatible representation.
            pub fn new(value: Option<#inner_type>) -> Self {
                match value {
                    Some(v) => Self {
                        is_some: 1,
                        value: ::std::mem::MaybeUninit::new(v),
                    },
                    None => Self {
                        is_some: 0,
                        value: ::std::mem::MaybeUninit::zeroed(),
                    },
                }
            }
            /// Whether a value is present.
            pub fn is_some(&self) -> bool {
                self.is_some == 1
            }
            /// The `Some` value, if any.
            pub fn some(&self) -> Option<&#inner_type> {
                if self.is_some == 1 { Some(unsafe { self.value.assume_init_ref() }) } else { None }
            }
            /// The value returned after a caught panic (#244): the `None`
            /// discriminant with an uninitialized payload. Julia raises
            /// `RustPanicError` before it looks at either field.
            pub fn panicked() -> Self {
                Self {
                    is_some: 0,
                    value: ::std::mem::MaybeUninit::zeroed(),
                }
            }
        }
    }
}

// ============================================================================
// Free functions: thin adapters over the generator
// ============================================================================

/// How a free function is lowered.
struct FreeFnOptions {
    /// Wrap a `Result` / `Option` return into `CResult_<fn>` / `COption_<fn>`.
    wrap_result: bool,
    /// See [`PanicHook`]: whether the wrapper may take a boundary guard.
    panic_hook: PanicHook,
}

impl Default for FreeFnOptions {
    fn default() -> Self {
        FreeFnOptions {
            wrap_result: true,
            // The conservative half of the pair: a wrapper that takes no guard
            // merely keeps the default hook, while one that takes a guard the
            // file does not define will not compile.
            panic_hook: PanicHook::External,
        }
    }
}

/// The wrapper (and its helpers) of a free function. The function itself is
/// **not** part of the output: the caller emits the original item next to it.
fn free_function_wrapper(
    func: &ItemFn,
    module_path: &[String],
    options: &FreeFnOptions,
) -> TokenStream2 {
    generate_wrapper(free_function_spec(func, module_path, options))
}

/// What [`generate_wrapper`] refuses for the wrapper [`transform_function`]
/// gives `func` (#503); see [`crate::refusal::function_refusal`].
pub(crate) fn free_function_wrapper_refusal(
    func: &ItemFn,
    module_path: &[String],
) -> Option<Refusal> {
    wrapper_refusal(free_function_spec(
        func,
        module_path,
        &FreeFnOptions::default(),
    ))
}

/// The [`WrapperSpec`] of a free function.
fn free_function_spec(
    func: &ItemFn,
    module_path: &[String],
    options: &FreeFnOptions,
) -> WrapperSpec {
    let name = func.sig.ident.clone();
    // Every generated name of the function hangs off its FFI name (#300).
    let stem = format_ident!("{}", symbol_stem(module_path, &name.to_string()));
    let symbol = format_ident!("{}{}", SYMBOL_PREFIX, stem);
    let cfgs = cfg_attrs(&func.attrs);

    let ret = free_fn_return(func, &stem, options);
    WrapperSpec {
        symbol,
        cfg_attrs: cfgs,
        receiver: None,
        generics: func.sig.generics.clone(),
        host: None,
        args: arg_pairs(&func.sig),
        ret,
        target: CallTarget::Free(name.into()),
        call_suffix: TokenStream2::new(),
        panic_hook: options.panic_hook,
    }
}

/// The [`WrapperPayload`] of one `Result` / `Option` component: a `String` /
/// `&str` becomes the owner's owned-string buffer, everything else is stored as
/// written (#268).
fn payload_of(ty: &Type, helper: &Ident, free: &Ident, declare: bool) -> WrapperPayload {
    if is_string_type(ty) || is_str_ref_type(ty) {
        WrapperPayload::OwnedString {
            helper: helper.clone(),
            free: free.clone(),
            declare,
        }
    } else {
        WrapperPayload::Plain(ty.clone())
    }
}

pub use crate::refusal::payload_is_representable;

/// Whether a method wrapper lowers this return type into `CResult_*` — i.e.
/// it is a `Result` whose payloads the aggregate can carry. A `Result` with a
/// payload it cannot carry keeps the pre-#268 behaviour (returned as written,
/// reported as `Plain`), rather than turning existing code into a compile
/// error.
pub fn method_wraps_result(ty: &Type) -> bool {
    extract_result_type(ty)
        .map(|r| payload_is_representable(&r.ok_type) && payload_is_representable(&r.err_type))
        .unwrap_or(false)
}

/// The `Option` counterpart of [`method_wraps_result`].
pub fn method_wraps_option(ty: &Type) -> bool {
    extract_option_type(ty)
        .map(|o| payload_is_representable(&o.inner_type))
        .unwrap_or(false)
}

/// Whether a `Result` / `Option` payload travels as an owned string buffer,
/// i.e. what the manifest reports as `ok_abi` / `err_abi` / `inner_abi`
/// (#268). `&str` is included: a payload is always copied, never borrowed.
pub fn payload_abi(ty: &Type) -> &'static str {
    if is_string_type(ty) || is_str_ref_type(ty) {
        "string"
    } else {
        ""
    }
}

fn free_fn_return(func: &ItemFn, name: &Ident, options: &FreeFnOptions) -> WrapperReturn {
    let ReturnType::Type(_, ty) = &func.sig.output else {
        return WrapperReturn::Unit;
    };
    if options.wrap_result {
        // A `String` payload is lowered to the function's own owned-string
        // buffer, which this wrapper declares (#268).
        let helper = format_ident!("{}_RustCallOwnedString", name);
        let free = format_ident!("{}_free_rust_string", name);
        let payload = |ty: &Type| payload_of(ty, &helper, &free, true);
        if let Some(r) = extract_result_type(ty) {
            return WrapperReturn::CResult {
                name: format_ident!("CResult_{}", name),
                ok: payload(&r.ok_type),
                err: payload(&r.err_type),
            };
        }
        if let Some(o) = extract_option_type(ty) {
            return WrapperReturn::COption {
                name: format_ident!("COption_{}", name),
                inner: payload(&o.inner_type),
            };
        }
    }
    if function_returns_string(&func.sig) || returns_copied_str(&func.sig) {
        return WrapperReturn::OwnedString {
            helper: format_ident!("{}_RustCallOwnedString", name),
            free: format_ident!("{}_free_rust_string", name),
            declare: true,
        };
    }
    if returns_borrowed_str(&func.sig) {
        return WrapperReturn::BorrowedStr {
            helper: format_ident!("{}_RustCallBorrowedString", name),
            declare: true,
        };
    }
    WrapperReturn::Plain((**ty).clone())
}

/// Transform a `#[julia]` function: the annotated item is kept as written (the
/// attribute itself is already gone) and the `extern "C"` entry point is
/// emitted next to it under `rustcall_<fn>` (#279).
///
/// The rules are the crate flavour's ([`crate::refusal::function_refusal`] with
/// [`Mode::Crate`]); the `rust"""` expander calls this only for a function
/// that is not generic, for which the two flavours' rules agree. A refused
/// function is kept as written too, with the refusal's `compile_error!` beside
/// it, gated by the item's `#[cfg]` (PR #470 review): inside a `#[julia]
/// mod`, and for a `#[cfg]` written after `#[julia]`, the macro runs before
/// rustc evaluates the predicate, so an ungated `compile_error!` broke builds
/// where the item does not exist. Keeping the item means the one diagnostic is
/// not followed by a cascade about a missing item.
pub fn transform_function(
    func: ItemFn,
    module_path: &[String],
    panic_hook: PanicHook,
) -> TokenStream2 {
    if let Some(refusal) = crate::refusal::function_refusal(&func, module_path, Mode::Crate) {
        let error = refusal.compile_error(&cfg_attrs(&func.attrs));
        return quote! { #error #func };
    }

    let wrapper = free_function_wrapper(
        &func,
        module_path,
        &FreeFnOptions {
            panic_hook,
            ..FreeFnOptions::default()
        },
    );
    quote! {
        #func
        #wrapper
    }
}

/// Whether an inline method gets an `extern "C"` wrapper next to its struct —
/// that is, whether [`crate::refusal::method_refusal`] lets it through (#503).
fn inline_method_is_wrapped(site: crate::refusal::MethodSite<'_>, m: &MethodModel) -> bool {
    crate::refusal::method_refusal(site, m).is_none()
}

/// What [`generate_wrapper`] refuses for the wrapper of the method `m` of the
/// struct `struct_name`, spelled `self_ty` where the wrapper is emitted
/// (#503); see [`crate::refusal::method_refusal`]. The symbol and the string
/// buffers the wrapper would use decide nothing a refusal depends on.
pub(crate) fn method_wrapper_refusal(
    self_ty: &Type,
    struct_name: &Ident,
    m: &MethodModel,
) -> Option<Refusal> {
    let Type::Path(self_path) = unparen(self_ty) else {
        return None;
    };
    // A raw struct name (`r#for`) is no part of a symbol (#514).
    let stem = struct_stem(&[], struct_name);
    let owned_helper = format_ident!("{}_RustCallOwnedString", stem);
    let owned_free = format_ident!("{}_free_rust_string", stem);
    let borrowed_helper = format_ident!("{}_RustCallBorrowedString", stem);
    wrapper_refusal(method_spec(
        &self_path.path,
        struct_name,
        &stem,
        m,
        &owned_helper,
        &owned_free,
        &borrowed_helper,
        true,
        PanicHook::External,
    ))
}

/// The wrapper of a function exported with the signature as written: `Result` /
/// `Option` are not wrapped. Used by [`crate::specialize`] for the
/// instantiation of a generic function, whose fixed `String` / `&str`
/// parameters still get the byte-pair ABI (#242).
pub fn plain_function_wrapper(func: &ItemFn, module_path: &[String]) -> TokenStream2 {
    free_function_wrapper(
        func,
        module_path,
        &FreeFnOptions {
            // `specialize` re-emits the whole block with the instantiation
            // inserted and puts `panic_hook_items()` at its root (#304).
            panic_hook: PanicHook::FileOwned,
            wrap_result: false,
        },
    )
}

// ============================================================================
// Crate flavour: structs and impl blocks (proc-macro)
// ============================================================================

/// Whether the crate flavour emits the `<Struct>_RustCallOwnedString` /
/// `<Struct>_free_rust_string` helpers for this struct: it does exactly when a
/// field getter has to hand an owned `String` back (#276).
pub fn crate_struct_needs_owned_string_helper(item_struct: &ItemStruct) -> bool {
    let syn::Fields::Named(ref fields) = item_struct.fields else {
        return false;
    };
    fields
        .named
        .iter()
        .any(|f| f.ident.is_some() && field_has_accessors(&f.ty) && is_string_type(&f.ty))
}

/// Apply the common boundary to generated field/clone helpers.
///
/// A `Vec` result (never across `extern "C"`) takes an empty vector as its
/// sentinel. Any other value leaves as `MaybeUninit<T>`, `MaybeUninit::zeroed()`
/// after a panic, exactly as a plain function return does in
/// [`generate_wrapper`] (#462): the sentinel is then sound whatever `T` is,
/// rather than only while every caller keeps to types that are valid
/// all-zero, and the C signature is unchanged because `MaybeUninit<T>` has the
/// ABI of `T`.
pub(crate) fn guard_struct_helper(tokens: TokenStream2, hook: PanicHook) -> TokenStream2 {
    let mut function: ItemFn = syn::parse2(tokens).expect("generated struct helper is a function");
    let symbol = &function.sig.ident;
    let suffix: String = symbol
        .to_string()
        .bytes()
        .map(|b| format!("{b:02X}"))
        .collect();
    let slot = format_ident!("__RUSTCALL_HELPER_PANIC_{}", suffix);
    let reader = format_ident!("{}", panic_symbol(&symbol.to_string()));
    let channel = panic_channel(&cfg_attrs(&function.attrs), &slot, &reader);
    let original = function.block.clone();
    let (sentinel, unit, body) = match function.sig.output.clone() {
        ReturnType::Default => (quote! {}, true, quote! { #original }),
        ReturnType::Type(_, ty) if matches!(unparen(&ty), Type::Tuple(t) if t.elems.is_empty()) => {
            (quote! {}, true, quote! { #original })
        }
        ReturnType::Type(_, ty) if is_vec_type(&ty) => (
            quote! { ::std::vec::Vec::new() },
            false,
            quote! { #original },
        ),
        ReturnType::Type(arrow, ty) => {
            function.sig.output =
                ReturnType::Type(arrow, syn::parse_quote!(::std::mem::MaybeUninit<#ty>));
            (
                quote! { ::std::mem::MaybeUninit::zeroed() },
                false,
                quote! { ::std::mem::MaybeUninit::new(#original) },
            )
        }
    };
    let body = guarded_body(
        &symbol.to_string(),
        &slot,
        &quote! {},
        body,
        sentinel,
        unit,
        hook,
    );
    function.block = syn::parse_quote!({ #body });
    quote! { #channel #function }
}

/// Copy the struct's cfg onto every accessor and its channel, including when
/// a module macro expands the struct before rustc evaluates the predicate.
fn crate_field_accessors(
    item_struct: &ItemStruct,
    stem: &Ident,
    cfgs: &[Attribute],
) -> TokenStream2 {
    // `#[julia]` on a struct expands inside a crate RustCall does not write,
    // so its accessors take the boundary guard from the runtime crate (#304).
    let hook = PanicHook::Runtime;
    let struct_name = &item_struct.ident;
    let owned_helper = format_ident!("{}_RustCallOwnedString", stem);
    let owned_free = format_ident!("{}_free_rust_string", stem);
    let mut ffi_functions = TokenStream2::new();
    if crate_struct_needs_owned_string_helper(item_struct) {
        ffi_functions.extend(owned_string_helper(cfgs, &owned_helper, &owned_free));
    }
    if let syn::Fields::Named(ref fields) = item_struct.fields {
        for field in &fields.named {
            let Some(ref field_name) = field.ident else {
                continue;
            };
            let field_ty = &field.ty;
            if !field_has_accessors(field_ty) {
                continue;
            }
            // A field's own `#[cfg]` gates its accessors on top of the
            // struct's (#462): a `#[cfg(target_os = "linux")]` field does not
            // exist elsewhere, and neither may a getter that reads it.
            let mut field_cfgs = cfgs.to_vec();
            field_cfgs.extend(cfg_attrs(&field.attrs));
            let cfgs = field_cfgs.as_slice();
            let getter_name = format_ident!("{}_get_{}", stem, field_name);
            if is_string_type(field_ty) {
                // A `String` cannot cross `extern "C"` by value: it leaves as an
                // owned `(ptr, len, cap)` buffer the caller hands back to
                // `<Struct>_free_rust_string`, exactly as the inline flavour
                // and the string-returning method wrappers do (#246).
                ffi_functions.extend(guard_struct_helper(quote! {
                    #(#cfgs)*
                    #[no_mangle]
                    pub extern "C" fn #getter_name(ptr: *const #struct_name) -> #owned_helper {
                        let mut rustcall_bytes = unsafe { (*ptr).#field_name.clone().into_bytes() };
                        let rustcall_ret = #owned_helper {
                            ptr: rustcall_bytes.as_mut_ptr(),
                            len: rustcall_bytes.len(),
                            cap: rustcall_bytes.capacity(),
                        };
                        std::mem::forget(rustcall_bytes);
                        rustcall_ret
                    }
                }, hook));
            } else {
                ffi_functions.extend(guard_struct_helper(
                    quote! {
                        #(#cfgs)*
                        #[no_mangle]
                        pub extern "C" fn #getter_name(ptr: *const #struct_name) -> #field_ty {
                            unsafe { (*ptr).#field_name }
                        }
                    },
                    hook,
                ));
            }
            let setter_name = format_ident!("{}_set_{}", stem, field_name);
            ffi_functions.extend(struct_field_setter(
                struct_name,
                field_name,
                field_ty,
                &setter_name,
                cfgs,
                hook,
            ));
        }
    }
    ffi_functions
}

pub(crate) fn struct_field_setter(
    owner: &impl quote::ToTokens,
    field: &Ident,
    ty: &Type,
    setter: &Ident,
    cfgs: &[Attribute],
    hook: PanicHook,
) -> TokenStream2 {
    let value = format_ident!("value");
    let (args, conversion) = if is_string_type(ty) {
        string_arg_conversion(&value, ty, &["ptr".into()])
    } else {
        (vec![quote! { value: #ty }], None)
    };
    guard_struct_helper(
        quote! {
            #(#cfgs)*
            #[no_mangle]
            pub extern "C" fn #setter(ptr: *mut #owner, #(#args),*) {
                #conversion
                unsafe { (*ptr).#field = value; }
            }
        },
        hook,
    )
}

pub(crate) fn struct_free_wrapper(
    struct_type: &syn::Path,
    stem: &Ident,
    cfgs: &[Attribute],
    hook: PanicHook,
) -> TokenStream2 {
    let free_fn_name = format_ident!("{}_free", stem);
    // Unlike case folding, byte encoding keeps distinct struct names such as
    // `C` and `c` distinct in the private TLS namespace as well.
    let slot_suffix: String = free_fn_name
        .to_string()
        .bytes()
        .map(|byte| format!("{byte:02X}"))
        .collect();
    let slot = format_ident!("__RUSTCALL_DROP_PANIC_{}", slot_suffix);
    let reader = format_ident!("{}", panic_symbol(&free_fn_name.to_string()));
    let channel = panic_channel(cfgs, &slot, &reader);
    let body = guarded_body(
        &format!("{}::drop", path_tail(struct_type)),
        &slot,
        &quote! {},
        quote! {
            if !ptr.is_null() {
                unsafe { drop(Box::from_raw(ptr)); }
            }
        },
        quote! {},
        true,
        hook,
    );
    quote! {
        #channel
        #(#cfgs)*
        #[no_mangle]
        pub extern "C" fn #free_fn_name(ptr: *mut #struct_type) {
            #body
        }
    }
}

/// The FFI name of a struct as an identifier (see [`symbol_stem`]).
fn struct_stem(module_path: &[String], struct_name: &Ident) -> Ident {
    format_ident!("{}", symbol_stem(module_path, &struct_name.to_string()))
}

/// Transform a `#[julia]` struct (crate flavour): `#[repr(C)]`, `pub`, free + accessors.
pub fn transform_struct_crate(mut item_struct: ItemStruct, module_path: &[String]) -> TokenStream2 {
    if let Some(refusal) = crate::refusal::struct_refusal(&item_struct, Mode::Crate) {
        let error = refusal.compile_error(&cfg_attrs(&item_struct.attrs));
        return quote! { #error #item_struct };
    }
    let repr_c: Attribute = syn::parse_quote!(#[repr(C)]);
    item_struct.attrs.insert(0, repr_c);
    item_struct.vis = Visibility::Public(syn::token::Pub::default());

    let stem = struct_stem(module_path, &item_struct.ident);
    // The struct's `#[cfg]` gates its helpers too (#300 review).
    let cfgs = cfg_attrs(&item_struct.attrs);
    let struct_name = &item_struct.ident;
    let free = struct_free_wrapper(
        &syn::parse_quote!(#struct_name),
        &stem,
        &cfgs,
        PanicHook::Runtime,
    );
    let accessors = crate_field_accessors(&item_struct, &stem, &cfgs);

    quote! {
        #item_struct
        #free
        #accessors
    }
}

/// The module path the proc-macro takes the struct of `#[julia] impl <self_ty>`
/// to live at, given the `#[julia]` modules `module_path` around the block:
/// the header read literally (`crate::a::C` is `a::C`, `super::C` one level up,
/// a bare `C` the block's own path), see
/// `PathQualifier::macro_target_path` (#315). Every symbol of the block's
/// methods hangs off this path, and crate extraction refuses a block whose
/// header names a struct that lives somewhere else.
pub fn impl_target_module_path(module_path: &[String], self_ty: &Type) -> Vec<String> {
    crate::paths::type_path_qualifier(self_ty).macro_target_path(module_path)
}

/// Transform a `#[julia]` impl block (crate flavour): wrap `#[julia]` methods.
///
/// The block may sit in another module than its struct (`impl crate::Gauge`
/// from `ops.rs`, `impl super::Gauge` from a child module, #315); the method
/// symbols follow the struct the header names, [`impl_target_module_path`].
pub fn transform_impl_crate(mut item_impl: ItemImpl, module_path: &[String]) -> TokenStream2 {
    // A header that is not a type path, or a generic block (`impl<T>
    // Wrapper<T>`), which has no concrete receiver type to wrap: refuse it at
    // the header, and keep the block as written (#462).
    if let Some(refusal) = crate::refusal::impl_refusal(&item_impl) {
        let error = refusal.compile_error(&cfg_attrs(&item_impl.attrs));
        for item in &mut item_impl.items {
            if let syn::ImplItem::Fn(method) = item {
                method.attrs.retain(|attr| !attr.path().is_ident("julia"));
            }
        }
        return quote! { #error #item_impl };
    }
    let struct_path = impl_target_module_path(module_path, &item_impl.self_ty);
    // The wrappers are emitted next to the block, in *its* module, so they
    // name the struct the way the header does (`super::Gauge`): a bare
    // `Gauge` need not be in scope there. The block's generics and `where`
    // clause join every wrapper's, and `Self` in a method's signature is
    // spelled as the header (#482).
    let host = ImplHost::of(&item_impl);

    // The block's own `#[cfg]` gates every wrapper it produces: inside a
    // `#[julia] mod` the module macro expands a gated impl before rustc
    // evaluates the predicate (#300 review).
    let block_cfgs = cfg_attrs(&item_impl.attrs);
    let mut ffi_wrappers = TokenStream2::new();
    for item in &mut item_impl.items {
        if let syn::ImplItem::Fn(method) = item {
            let has_julia_attr = method
                .attrs
                .iter()
                .any(|attr| attr.path().is_ident("julia"));
            if has_julia_attr {
                method.attrs.retain(|attr| !attr.path().is_ident("julia"));
                // The generator reads the method's `#[cfg]` set and puts it on
                // every item it emits; the block's predicates join that set
                // for the wrapper only, the method itself is left as written.
                let mut gated = method.clone();
                gated.attrs.splice(0..0, block_cfgs.iter().cloned());
                ffi_wrappers.extend(method_wrapper_in_block(&host, &struct_path, &gated));
            }
        }
    }

    quote! {
        #item_impl
        #ffi_wrappers
    }
}

/// Transform a `#[julia]` **module** (crate flavour, #300).
///
/// The proc-macro cannot see the module an item sits in, so the module itself
/// carries the marker and expands its own `#[julia]` items with the module
/// path — `module_path` is the path of the enclosing marked modules, and this
/// module's name is appended to it. Each nested `#[julia]` function, struct and
/// impl block is expanded exactly as [`transform_function`],
/// [`transform_struct_crate`] and [`transform_impl_crate`] would, its own
/// `#[julia]` attribute removed so the item-level macro does not run on it a
/// second time; a nested `#[julia] mod` recurses with the accumulated path;
/// everything else is kept as written.
///
/// A file module (`mod a;`) has no body to expand: the attribute is refused
/// with a `compile_error!` naming the alternative (an inline module block).
pub fn transform_module(item_mod: ItemMod, module_path: &[String]) -> TokenStream2 {
    if let Some(refusal) = crate::refusal::module_refusal(&item_mod) {
        return refusal.compile_error(&cfg_attrs(&item_mod.attrs));
    }
    let Some((_, items)) = item_mod.content else {
        return TokenStream2::new();
    };
    let mut path = module_path.to_vec();
    path.push(item_mod.ident.to_string());

    let mut body = TokenStream2::new();
    for item in items {
        body.extend(expand_marked_item(item, &path));
    }

    let attrs = &item_mod.attrs;
    let vis = &item_mod.vis;
    let unsafety = &item_mod.unsafety;
    let ident = &item_mod.ident;
    quote! { #(#attrs)* #vis #unsafety mod #ident { #body } }
}

/// One item of a `#[julia]` module body: a `#[julia]` function, struct, impl
/// block or module is expanded with `module_path`; anything else is unchanged.
fn expand_marked_item(item: Item, module_path: &[String]) -> TokenStream2 {
    fn take_julia(attrs: &mut Vec<Attribute>) -> bool {
        let before = attrs.len();
        attrs.retain(|attr| !crate::attrs::is_julia_attr(attr));
        attrs.len() != before
    }
    match item {
        Item::Fn(mut f) => {
            if take_julia(&mut f.attrs) {
                transform_function(f, module_path, PanicHook::Runtime)
            } else {
                quote! { #f }
            }
        }
        Item::Struct(mut s) => {
            if take_julia(&mut s.attrs) {
                transform_struct_crate(s, module_path)
            } else {
                quote! { #s }
            }
        }
        Item::Impl(mut i) => {
            if take_julia(&mut i.attrs) {
                transform_impl_crate(i, module_path)
            } else {
                quote! { #i }
            }
        }
        Item::Mod(mut m) => {
            if take_julia(&mut m.attrs) {
                transform_module(m, module_path)
            } else {
                quote! { #m }
            }
        }
        // Any other kind carrying `#[julia]` is refused here, as the
        // item-level macro would refuse it (#503 review).
        other => match crate::refusal::julia_item_refusal(&other) {
            Some(refusal) => {
                let error = refusal.compile_error(&cfg_attrs(&crate::refusal::item_attrs(&other)));
                let kept = crate::refusal::without_julia_attr(other);
                quote! { #error #kept }
            }
            None => quote! { #other },
        },
    }
}

/// `#[julia]` on an item that is none of a function, a struct, an impl block
/// or an inline module: the item as written, with the refusal
/// ([`crate::refusal::attribute_target_refusal`], the decision the scans take
/// through [`crate::refusal::julia_item_refusal`]) before it.
pub fn transform_unsupported_item(item: TokenStream2) -> TokenStream2 {
    let error = crate::refusal::attribute_target_refusal(&item).compile_error(&[]);
    quote! {
        #error
        #item
    }
}

/// Whether an inline module is marked `#[julia]`, i.e. contributes its name
/// to the symbols of the items it contains (#300).
pub fn is_marked_module(item_mod: &ItemMod) -> bool {
    item_mod.attrs.iter().any(crate::attrs::is_julia_attr)
}

/// Exported ABI proof for a wrapper whose `Result<Self, E>` stores a boxed
/// `Ok` payload — a fallible constructor (#559) or any other method returning
/// the struct in a `Result` (#564). Julia refuses to decode the aggregate when
/// the image lacks it: an older macro returned such a `Self` by value.
pub(crate) fn boxed_result_marker(symbol: &str) -> String {
    format!("{symbol}_boxed_result_v1")
}

/// Whether the wrapper of a method returns a boxed `*mut Struct`: `new`, or any
/// method (static or instance) returning `Self` / the struct type. This is what
/// Julia needs to know; both codegen flavours box these cases.
pub fn returns_boxed_struct(struct_name: &Ident, method: &syn::ImplItemFn) -> bool {
    returns_own_type(&method.sig.output, struct_name, None)
}

/// Whether a method's declared return type **is spelled as** the implementing
/// type, so its wrapper hands Julia an owning `*mut Struct`
/// (`WrapperReturn::Boxed`): `Self`, or the impl header's own type spelled
/// token for token as the header spells it (`own_ty`: `Meter` in `use
/// super::Gauge as Meter; impl Meter`, `super::Gauge` in `impl super::Gauge`).
/// With no header (a lone method), the bare struct name. The one rule for the
/// manifest's `returns_boxed_struct` / `is_constructor` and the codegen's
/// boxed return, in both flavours (PR #513 review).
///
/// The header and the signature are written in one scope, so one spelling
/// names one type there. A path that merely **ends** in the header's name is
/// not the implementing type as far as the syntax says — `other::Meter` may
/// be `type Meter = f64` — and boxing it as `*mut Meter` does not compile
/// (#518). A path spelled otherwise that does name the struct
/// (`crate::Gauge` in `impl Gauge`) is recognised only by resolution, which
/// the inline expander does ([`crate::model::MethodModel::returns_own_type_resolved`],
/// through [`crate::paths::names_struct`]); the proc macro sees one block
/// and cannot resolve a name, so to it only this spelling counts, and the
/// crate scan, which must describe what the macro emits, uses no more.
///
/// Decided by the return type alone, never by the method's name: a `fn new()
/// -> i32` (a trait's, or an inherent helper) returns an `i32`, and boxing it
/// as a `*mut Struct` does not compile.
pub fn returns_own_type(output: &ReturnType, struct_name: &Ident, own_ty: Option<&Type>) -> bool {
    let ReturnType::Type(_, ty) = output else {
        return false;
    };
    let ty = unparen(ty);
    let is_self = matches!(ty, Type::Path(tp) if tp.qself.is_none() && tp.path.is_ident("Self"));
    is_self
        || match own_ty {
            Some(own) => {
                matches!(ty, Type::Path(_)) && crate::receiver::same_spelling(ty, unparen(own))
            }
            None => is_self_type(ty, struct_name),
        }
}

/// Generate the FFI wrapper for a method (crate flavour).
///
/// Same generator as the inline flavour ([`inline_method_wrapper`]): `String` /
/// `&str` arguments arrive as `(ptr, len)` pairs, a string result leaves as an
/// owned or borrowed buffer. The proc-macro transforms one impl block at a time
/// and cannot see the struct or sibling impl blocks, so the buffer types are
/// per method rather than per struct:
/// `<Struct>_<method>_RustCallOwnedString` released through
/// `<Struct>_<method>_free_rust_string`, and
/// `<Struct>_<method>_RustCallBorrowedString`. The method itself is left in the
/// impl block untouched; the wrapper calls it (#279).
pub fn generate_method_wrapper_crate(
    self_ty: &Type,
    module_path: &[String],
    method: &syn::ImplItemFn,
) -> TokenStream2 {
    method_wrapper_in_block(
        &ImplHost {
            generics: syn::Generics::default(),
            self_ty: self_ty.clone(),
            trait_: None,
        },
        module_path,
        method,
    )
}

/// [`generate_method_wrapper_crate`] for a method of the block `host`, whose
/// generics join the wrapper's and whose type `Self` stands for (#482).
fn method_wrapper_in_block(
    host: &ImplHost,
    module_path: &[String],
    method: &syn::ImplItemFn,
) -> TokenStream2 {
    let self_ty = &host.self_ty;
    // The origin is a manifest column; the wrapper's shape does not depend
    // on it.
    let mut model = MethodModel::from_fn(method, crate::manifest::Attribute::Julia);
    model.host = Some(host.clone());
    // The proc-macro sees one block and cannot resolve a name: the header's
    // last segment *is* the struct as far as it knows. Crate extraction
    // refuses a header the macro would read differently from the struct it
    // resolves to — a renamed import among them (#315).
    let Some(struct_name) = last_ident(self_ty) else {
        return crate::refusal::impl_header_refusal(self_ty)
            .map(|refusal| refusal.compile_error(&cfg_attrs(&method.attrs)))
            .unwrap_or_default();
    };
    method_wrapper_at_impl_site(
        self_ty,
        struct_name,
        module_path,
        &model,
        PanicHook::Runtime,
    )
}

/// The FFI wrapper of a method emitted **at its impl block** rather than next
/// to its struct: `self_ty` is the impl header as written (`super::Gauge`), so
/// the struct need not be in scope under its bare name, and the string buffers
/// are declared per method ([`method_string_owner`]) so two blocks of one
/// struct cannot both claim the struct-level `#[no_mangle]` helpers.
///
/// `struct_name` is the struct's **own** identifier and `struct_module_path`
/// the module it lives in: every exported symbol hangs off those, wherever the
/// wrapper is emitted and however the header spells the type. The two are not
/// the same thing — `use super::Gauge as Meter; impl Meter` must still export
/// `rustcall_Gauge_<method>`, which is what the manifest advertises, while the
/// wrapper's own code says `Meter` because that is the name in scope there
/// (#342 review).
///
/// Used by the proc-macro for every `#[julia] impl` block
/// ([`generate_method_wrapper_crate`]) and by the inline expander for a block
/// that sits in another module than its struct (#342).
pub fn method_wrapper_at_impl_site(
    self_ty: &Type,
    struct_name: &Ident,
    struct_module_path: &[String],
    m: &MethodModel,
    panic_hook: PanicHook,
) -> TokenStream2 {
    let Type::Path(self_path) = unparen(self_ty) else {
        return crate::refusal::impl_header_refusal(self_ty)
            .map(|refusal| refusal.compile_error(&cfg_attrs(&m.func.attrs)))
            .unwrap_or_default();
    };
    // Both flavours reach Rust through here for a block's method: the
    // proc-macro's `#[julia] impl`, and an inline block beside another
    // module's struct (#491). The refusal is the one the manifest records
    // (#503); the hook says which flavour's rules apply.
    let site = match panic_hook {
        PanicHook::Runtime => crate::refusal::MethodSite::Crate { self_ty },
        _ => crate::refusal::MethodSite::Inline {
            self_ty,
            struct_name,
        },
    };
    if let Some(refusal) = crate::refusal::method_refusal(site, m) {
        return refusal.compile_error(&cfg_attrs(&m.func.attrs));
    }
    let stem = struct_stem(struct_module_path, struct_name);
    let owner = format_ident!(
        "{}",
        method_string_owner(&stem.to_string(), &m.method_stem())
    );
    let owned_helper = format_ident!("{}_RustCallOwnedString", owner);
    let owned_free = format_ident!("{}_free_rust_string", owner);
    let borrowed_helper = format_ident!("{}_RustCallBorrowedString", owner);
    generate_wrapper(method_spec(
        &self_path.path,
        struct_name,
        &stem,
        m,
        &owned_helper,
        &owned_free,
        &borrowed_helper,
        true,
        panic_hook,
    ))
}

/// The wrapper of an **inline** method whose `#[julia] impl` block sits in
/// another module than its struct (#342), emitted into the block's module.
///
/// The expander resolves the header itself, so `struct_name` /
/// `struct_module_path` are the struct the block was married to — not the
/// header's last segment, which a `use ... as` may have renamed — while
/// `self_ty` stays the header as written, the only spelling in scope where the
/// wrapper is emitted (#342 review).
///
/// The block's own `#[cfg]` — and that of the modules around it — gates the
/// wrapper as much as the method's own does, exactly as
/// [`transform_impl_crate`] splices the block's predicates onto the crate
/// flavour's wrapper.
pub fn inline_foreign_method_wrapper(
    self_ty: &Type,
    struct_name: &Ident,
    struct_module_path: &[String],
    m: &MethodModel,
) -> TokenStream2 {
    let mut gated = m.clone();
    gated
        .func
        .attrs
        .splice(0..0, m.enclosing_cfg.iter().cloned());
    method_wrapper_at_impl_site(
        self_ty,
        struct_name,
        struct_module_path,
        &gated,
        PanicHook::FileOwned,
    )
}

// ============================================================================
// Inline flavour: struct wrappers for rust"""...""" blocks
// ============================================================================

/// What the inline struct wrapper generator produced, for the manifest.
#[derive(Debug, Default, Clone)]
pub struct InlineStructMeta {
    pub has_clone: bool,
    pub has_owned_string_helper: bool,
    pub has_borrowed_string_helper: bool,
    /// `(field, getter symbol, setter symbol)` for every accessible field. When a
    /// method wrapper already owns the `<Struct>_get_<field>` symbol, that wrapper
    /// serves as the getter and no setter is generated.
    pub accessors: Vec<(String, String, String)>,
}

/// The `Result<T, E>` a method wrapper lowers into `CResult_<Struct>_<method>`,
/// if it is one (#268). A constructor is excluded by the caller.
fn method_result_return(m: &MethodModel) -> Option<crate::types::ResultTypeInfo> {
    match &m.func.sig.output {
        ReturnType::Type(_, ty) if method_wraps_result(ty) => extract_result_type(ty),
        _ => None,
    }
}

/// The `Option<T>` counterpart of [`method_result_return`].
fn method_option_return(m: &MethodModel) -> Option<crate::types::OptionTypeInfo> {
    match &m.func.sig.output {
        ReturnType::Type(_, ty) if method_wraps_option(ty) => extract_option_type(ty),
        _ => None,
    }
}

/// Whether an inline method's wrapper needs the struct's owned-string buffer:
/// a `String` / copied `&str` return, or a `Result` / `Option` with a string
/// payload (#268).
fn method_needs_owned_string(m: &MethodModel) -> bool {
    if method_returns_string(m) || method_copies_str(m) {
        return true;
    }
    if let Some(r) = method_result_return(m) {
        return !payload_abi(&r.ok_type).is_empty() || !payload_abi(&r.err_type).is_empty();
    }
    if let Some(o) = method_option_return(m) {
        return !payload_abi(&o.inner_type).is_empty();
    }
    false
}

fn method_returns_string(m: &MethodModel) -> bool {
    matches!(&m.func.sig.output, ReturnType::Type(_, ty) if is_string_type(ty))
}

/// A method returning `&str` that also takes string arguments: the result may
/// borrow from a converted argument, so it is copied (see [`returns_borrowed_str`]).
fn method_copies_str(m: &MethodModel) -> bool {
    returns_copied_str(&m.func.sig)
}

fn method_returns_borrowed_str(m: &MethodModel) -> bool {
    returns_borrowed_str(&m.func.sig)
}

fn inline_method_is_ctor(struct_name: &Ident, m: &MethodModel) -> bool {
    // A method returning `Self` / the struct type (static or not) hands Julia
    // a boxed struct; the name decides nothing (PR #513 review).
    m.returns_boxed_struct(struct_name)
}

/// Generate the `extern "C"` wrappers for a non-generic inline struct: the
/// destructor, the field accessors, the shared string buffers and the wrappers
/// of the methods whose `#[julia] impl` block sits in `module_path` — the
/// struct's own module.
///
/// A method from a block in *another* module is not wrapped here: its wrapper
/// is emitted at the block by `expand::expand_items` through
/// [`inline_foreign_method_wrapper`], because its signature is written in the
/// block's scope (#342).
pub fn inline_struct_wrappers(
    model: &StructModel,
    module_path: &[String],
) -> (TokenStream2, InlineStructMeta) {
    let struct_name = &model.item.ident;
    let stem = struct_stem(module_path, struct_name);
    let mut out = TokenStream2::new();
    let mut meta = InlineStructMeta::default();
    // The struct's `#[cfg]` gates every item generated for it, and a field's
    // own `#[cfg]` its accessors on top, exactly as in the crate flavour
    // (`transform_struct_crate`, #462): without them a `#[cfg(unix)] struct`
    // got an ungated `<Struct>_free` that names a type which does not exist
    // off unix. The enclosing modules need nothing: the wrappers are emitted
    // inside them.
    let cfgs = cfg_attrs(&model.item.attrs);

    out.extend(struct_free_wrapper(
        &syn::parse_quote!(#struct_name),
        &stem,
        &cfgs,
        PanicHook::FileOwned,
    ));

    let fields = model.named_fields();
    let accessible: Vec<&(Ident, Type)> = fields
        .iter()
        .filter(|(_, ty)| field_has_accessors(ty))
        .collect();

    // Only the methods whose `#[julia] impl` block sits beside the struct are
    // wrapped here. One in another module has its wrapper emitted at the block
    // (`inline_foreign_method_wrapper`, #342), where the types its signature
    // names are in scope, with string buffers of its own — so it neither needs
    // nor may use the struct-level helpers, and does not make them exist.
    let local: Vec<&MethodModel> = model
        .methods
        .iter()
        .filter(|m| m.is_local_to(module_path))
        .collect();

    // A refused method — generic (#471), `unsafe` (#491), or one whose wrapper
    // cannot be written (#482, #484) — gets no wrapper, so it makes no buffer
    // exist either (#503).
    let self_ty: Type = syn::parse_quote!(#struct_name);
    let site = crate::refusal::MethodSite::Inline {
        self_ty: &self_ty,
        struct_name,
    };
    let wrapped = || local.iter().filter(|m| inline_method_is_wrapped(site, m));
    let needs_owned = accessible.iter().any(|(_, ty)| is_string_type(ty))
        || wrapped()
            .any(|m| method_needs_owned_string(m) && !inline_method_is_ctor(struct_name, m));
    let needs_borrowed =
        wrapped().any(|m| method_returns_borrowed_str(m) && !inline_method_is_ctor(struct_name, m));

    let owned_helper = format_ident!("{}_RustCallOwnedString", stem);
    let borrowed_helper = format_ident!("{}_RustCallBorrowedString", stem);
    let owned_free = format_ident!("{}_free_rust_string", stem);

    if needs_owned {
        meta.has_owned_string_helper = true;
        out.extend(owned_string_helper(&cfgs, &owned_helper, &owned_free));
    }
    if needs_borrowed {
        meta.has_borrowed_string_helper = true;
        out.extend(borrowed_string_helper(&cfgs, &borrowed_helper));
    }

    // Field accessors. A method wrapper cannot take an accessor's symbol:
    // since #279 it is `rustcall_<stem>_<method>`, and `rustcall_` followed by
    // `<stem>` never continues with the `_get_` / `_set_` an accessor
    // `<stem>_get_<field>` has at that position.
    for (field_name, field_ty) in &accessible {
        let getter = format_ident!("{}_get_{}", stem, field_name);
        let setter = format_ident!("{}_set_{}", stem, field_name);
        meta.accessors.push((
            field_name.to_string(),
            getter.to_string(),
            setter.to_string(),
        ));
        let mut field_cfgs = cfgs.clone();
        field_cfgs.extend(model.field_cfg_attrs(field_name));
        if is_string_type(field_ty) {
            out.extend(guard_struct_helper(
                quote! {
                    #(#field_cfgs)*
                    #[no_mangle]
                    pub extern "C" fn #getter(ptr: *const #struct_name) -> #owned_helper {
                        let mut rustcall_bytes = unsafe { (*ptr).#field_name.clone().into_bytes() };
                        let rustcall_ret = #owned_helper {
                            ptr: rustcall_bytes.as_mut_ptr(),
                            len: rustcall_bytes.len(),
                            cap: rustcall_bytes.capacity(),
                        };
                        std::mem::forget(rustcall_bytes);
                        rustcall_ret
                    }
                },
                PanicHook::FileOwned,
            ));
        } else {
            out.extend(guard_struct_helper(
                quote! {
                    #(#field_cfgs)*
                    #[no_mangle]
                    pub extern "C" fn #getter(ptr: *const #struct_name) -> #field_ty {
                        unsafe { (*ptr).#field_name }
                    }
                },
                PanicHook::FileOwned,
            ));
        }
        out.extend(struct_field_setter(
            struct_name,
            field_name,
            field_ty,
            &setter,
            &field_cfgs,
            PanicHook::FileOwned,
        ));
    }

    if model.derives.iter().any(|d| d == "Clone") {
        meta.has_clone = true;
        let clone_name = format_ident!("{}_clone", stem);
        out.extend(guard_struct_helper(
            quote! {
                #(#cfgs)*
                #[no_mangle]
                pub extern "C" fn #clone_name(ptr: *const #struct_name) -> *mut #struct_name {
                    unsafe { Box::into_raw(Box::new((*ptr).clone())) }
                }
            },
            PanicHook::FileOwned,
        ));
    }

    for m in &local {
        // A method exists only where its struct and its impl block do: the
        // generator reads the method's own `#[cfg]` set, so those predicates
        // join it for the wrapper only — as `transform_impl_crate` and
        // `inline_foreign_method_wrapper` do.
        let mut gated = (*m).clone();
        gated
            .func
            .attrs
            .splice(0..0, cfgs.iter().chain(m.enclosing_cfg.iter()).cloned());
        if let Some(refusal) = crate::refusal::method_refusal(site, m) {
            out.extend(refusal.compile_error(&cfg_attrs(&gated.func.attrs)));
            continue;
        }
        out.extend(inline_method_wrapper(
            struct_name,
            &stem,
            &gated,
            &owned_helper,
            &owned_free,
            &borrowed_helper,
        ));
    }

    (out, meta)
}

/// The [`WrapperSpec`] of a struct method, shared by the inline and the crate
/// flavour: `declare` says whether the string buffer helpers are emitted by
/// this wrapper (crate flavour, per method) or already exist next to the struct
/// (inline flavour, per struct). `self_path` is how the wrapper spells the
/// struct where it is emitted — the bare name next to the struct (inline), the
/// impl header's own path (`super::Gauge`) next to the block (crate, #315) —
/// and `struct_name` the struct's identifier. Whether a method returns the
/// struct is [`MethodModel::returns_boxed_struct`] (#518).
#[allow(clippy::too_many_arguments)]
fn method_spec(
    self_path: &syn::Path,
    struct_name: &Ident,
    stem: &Ident,
    m: &MethodModel,
    owned_helper: &Ident,
    owned_free: &Ident,
    borrowed_helper: &Ident,
    declare: bool,
    panic_hook: PanicHook,
) -> WrapperSpec {
    let method_name = m.func.sig.ident.clone();
    // Every per-method name hangs off the method stem, which tells an
    // inherent method from each trait's of the same name (#506).
    let method_stem = m.method_stem();
    let symbol = format_ident!("{}", method_symbol_of(&stem.to_string(), &method_stem));
    let shape = m.receiver();
    let receiver = (!shape.is_static()).then(|| WrapperReceiver {
        ty: self_path.clone(),
        shape: shape.clone(),
        borrow: m
            .func
            .sig
            .receiver()
            .map(crate::environment::SelfBorrow::of)
            .unwrap_or(crate::environment::SelfBorrow::None),
    });
    // Every method is called by path (#509): a trait impl's through the
    // trait, spelled as the header spells it — the wrapper is emitted in the
    // block's module (#497) — and an inherent one as `<Buf>::m`.
    let target = CallTarget::Method {
        ty: self_path.clone(),
        path: crate::environment::method_item_path(m.host.as_ref(), self_path, &method_name),
    };
    let ret = if let Some(result) = m.boxed_self_result(struct_name) {
        WrapperReturn::CResult {
            name: format_ident!("CResult_{}_{}", stem, method_stem),
            ok: WrapperPayload::BoxedVerified(self_path.clone()),
            err: payload_of(&result.err_type, owned_helper, owned_free, declare),
        }
    } else if inline_method_is_ctor(struct_name, m) {
        // `new`, or any method returning `Self` / the struct type, hands Julia
        // an owning pointer. The string helpers are not involved.
        WrapperReturn::Boxed(self_path.clone())
    } else if let Some(r) = method_result_return(m) {
        // A `Result` method is lowered exactly like a free function (#268):
        // `CResult_<Struct>_<method>`, with a `String` payload composed onto
        // the owner's owned-string buffer.
        WrapperReturn::CResult {
            name: format_ident!("CResult_{}_{}", stem, method_stem),
            ok: payload_of(&r.ok_type, owned_helper, owned_free, declare),
            err: payload_of(&r.err_type, owned_helper, owned_free, declare),
        }
    } else if let Some(o) = method_option_return(m) {
        WrapperReturn::COption {
            name: format_ident!("COption_{}_{}", stem, method_stem),
            inner: payload_of(&o.inner_type, owned_helper, owned_free, declare),
        }
    } else if method_returns_string(m) || method_copies_str(m) {
        WrapperReturn::OwnedString {
            helper: owned_helper.clone(),
            free: owned_free.clone(),
            declare,
        }
    } else if method_returns_borrowed_str(m) {
        WrapperReturn::BorrowedStr {
            helper: borrowed_helper.clone(),
            declare,
        }
    } else {
        match &m.func.sig.output {
            ReturnType::Default => WrapperReturn::Unit,
            ReturnType::Type(_, ty) => WrapperReturn::Plain((**ty).clone()),
        }
    };
    WrapperSpec {
        symbol,
        cfg_attrs: cfg_attrs(&m.func.attrs),
        receiver,
        generics: m.func.sig.generics.clone(),
        // A lone method has no block: `Self` is the struct as the wrapper
        // spells it, and no block generics join the method's.
        host: Some(m.host.clone().unwrap_or_else(|| ImplHost {
            generics: syn::Generics::default(),
            self_ty: Type::Path(syn::TypePath {
                qself: None,
                path: self_path.clone(),
            }),
            trait_: None,
        })),
        args: arg_pairs(&m.func.sig),
        ret,
        target,
        call_suffix: TokenStream2::new(),
        panic_hook,
    }
}

/// The `extern "C"` wrapper of an inline struct method. The string buffer types
/// are shared per struct, so the wrapper only refers to them.
fn inline_method_wrapper(
    struct_name: &Ident,
    stem: &Ident,
    m: &MethodModel,
    owned_helper: &Ident,
    owned_free: &Ident,
    borrowed_helper: &Ident,
) -> TokenStream2 {
    generate_wrapper(method_spec(
        &syn::Path::from(struct_name.clone()),
        struct_name,
        stem,
        m,
        owned_helper,
        owned_free,
        borrowed_helper,
        false,
        PanicHook::FileOwned,
    ))
}

/// Type parameter names of a wrapper in the struct's parameter order: for
/// `struct S<T>` and `impl<U> S<U>`, the name bound at the struct's `T` position
/// is `U`. Remaining impl/method parameters follow.
fn wrapper_param_names(decl: &syn::Generics, self_ty: &Type) -> Vec<String> {
    let declared: Vec<String> = decl
        .params
        .iter()
        .filter_map(|p| match p {
            syn::GenericParam::Type(tp) => Some(tp.ident.to_string()),
            _ => None,
        })
        .collect();
    let mut ordered: Vec<String> = Vec::new();
    if let Type::Path(tp) = self_ty {
        if let Some(seg) = tp.path.segments.last() {
            if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
                for a in &args.args {
                    if let syn::GenericArgument::Type(Type::Path(p)) = a {
                        if p.qself.is_none() && p.path.segments.len() == 1 {
                            let n = p.path.segments[0].ident.to_string();
                            if declared.contains(&n) && !ordered.contains(&n) {
                                ordered.push(n);
                            }
                        }
                    }
                }
            }
        }
    }
    for n in declared {
        if !ordered.contains(&n) {
            ordered.push(n);
        }
    }
    ordered
}

/// Generics for a generic-struct method wrapper: the enclosing impl block's
/// parameters and `where` predicates, plus the method's own. Falls back to the
/// struct's parameters when no impl block declares the method.
fn wrapper_generics(
    model: &StructModel,
    m: &MethodModel,
) -> (syn::Generics, Option<syn::WhereClause>, Type) {
    let owner = model.impls.iter().find(|imp| {
        imp.items
            .iter()
            .any(|ii| matches!(ii, syn::ImplItem::Fn(f) if f.sig.ident == m.func.sig.ident))
    });
    // The receiver / constructor type must be spelled with the impl block's own
    // parameter names (`impl<U> Wrapper<U>`), not the struct declaration's.
    let self_ty: Type = match owner {
        Some(imp) => (*imp.self_ty).clone(),
        None => {
            let name = &model.item.ident;
            let (_, ty_generics, _) = model.item.generics.split_for_impl();
            syn::parse_quote!(#name #ty_generics)
        }
    };
    let mut merged = owner
        .map(|imp| imp.generics.clone())
        .unwrap_or_else(|| model.item.generics.clone());
    for p in &m.func.sig.generics.params {
        merged.params.push(p.clone());
    }
    let mut predicates: Vec<syn::WherePredicate> = merged
        .where_clause
        .take()
        .map(|w| w.predicates.into_iter().collect())
        .unwrap_or_default();
    if let Some(w) = &m.func.sig.generics.where_clause {
        predicates.extend(w.predicates.iter().cloned());
    }
    if !merged.params.is_empty() {
        merged.lt_token = Some(Default::default());
        merged.gt_token = Some(Default::default());
    }
    let where_clause = if predicates.is_empty() {
        None
    } else {
        Some(syn::WhereClause {
            where_token: Default::default(),
            predicates: predicates.into_iter().collect(),
        })
    };
    (merged, where_clause, self_ty)
}

fn fn_source(func: ItemFn) -> String {
    let file = syn::File {
        shebang: None,
        attrs: Vec::new(),
        items: vec![syn::Item::Fn(func)],
    };
    prettyplease::unparse(&file)
}

/// The name of the generic wrapper of `Struct::method` for a generic inline
/// struct with FFI name `struct_stem`: `<stem>_<method>`. Like every other
/// name of the struct it hangs off [`symbol_stem`], so two same-named generic
/// structs in different modules register different wrappers (#462); the
/// manifest carries it as `Method.generic_wrapper_name`. The method part is
/// [`method_stem`], so a raw method name (`r#match`) loses its `r#` exactly
/// as it does in a concrete struct's symbol (#514).
pub fn generic_method_wrapper_name(struct_stem: &str, method: &str) -> String {
    format!("{}_{}", unraw(struct_stem), method_stem(None, method))
}

/// The refusals of a generic inline struct's methods that are generic in their
/// own right (`impl<T> W<T> { pub fn f<U>(..) }`, #477), which
/// [`inline_generic_wrappers`] leaves unwrapped. Each is gated like the wrapper
/// it replaces — by the struct's `#[cfg]`, the method's block's and its own —
/// so it fires only where the method exists. The expander emits them next to
/// the struct.
pub fn inline_generic_method_refusals(model: &StructModel) -> TokenStream2 {
    let struct_name = &model.item.ident;
    let mut out = TokenStream2::new();
    for m in &model.methods {
        let Some(refusal) = crate::refusal::method_refusal(
            crate::refusal::MethodSite::InlineGeneric { struct_name },
            m,
        ) else {
            continue;
        };
        let mut cfgs = cfg_attrs(&model.item.attrs);
        cfgs.extend(m.enclosing_cfg.iter().cloned());
        cfgs.extend(cfg_attrs(&m.func.attrs));
        out.extend(refusal.compile_error(&cfgs));
    }
    out
}

/// Generate the generic wrapper functions of a generic inline struct living
/// under `module_path`. They are not compiled into the main library; Julia
/// registers them for on-demand monomorphization through `specialize`.
///
/// Every wrapper is named off the struct's FFI name ([`symbol_stem`]):
/// `<stem>_<method>`, `<stem>_get_<field>` / `<stem>_set_<field>` and
/// `<stem>_free`, exactly as a concrete struct's symbols are (#300, #462).
pub fn inline_generic_wrappers(model: &StructModel, module_path: &[String]) -> Vec<GenericWrapper> {
    let struct_name = &model.item.ident;
    let stem = symbol_stem(module_path, &struct_name.to_string());
    let generics = &model.item.generics;
    // The wrappers are emitted into the expanded source next to the struct, so
    // they exist only where it does: the struct's `#[cfg]` goes on each, a
    // method's block and own predicates on its wrapper, a field's on its
    // accessors — as `inline_struct_wrappers` does for a concrete struct
    // (#462, PR #470 review).
    let cfgs = cfg_attrs(&model.item.attrs);
    let gated = |mut func: ItemFn, extra: &[Attribute]| -> ItemFn {
        func.attrs
            .splice(0..0, cfgs.iter().chain(extra.iter()).cloned());
        func
    };
    let (_, ty_generics, _) = generics.split_for_impl();
    let decl_generics = {
        let mut g = generics.clone();
        g.where_clause = None;
        g
    };
    let mut wrappers = Vec::new();

    // A method generic in its own right gets no wrapper: instantiating the
    // struct binds only the struct's parameters (#477). Nor does an `unsafe`
    // one (#491). The expander emits [`inline_generic_method_refusals`] for
    // them instead.
    let site = crate::refusal::MethodSite::InlineGeneric { struct_name };
    for m in model
        .methods
        .iter()
        .filter(|m| inline_method_is_wrapped(site, m))
    {
        let method_name = &m.func.sig.ident;
        let wrapper_name = format_ident!(
            "{}",
            generic_method_wrapper_name(&stem, &method_name.to_string())
        );
        // The wrapper must satisfy the bounds the impl block and the method
        // themselves declare (`impl<T: Copy>`, `where T: Copy`, `fn f<U>`).
        let (decl_generics, where_clause, self_ty) = wrapper_generics(model, m);
        let where_clause = where_clause.map(|w| quote! { #w }).unwrap_or_default();
        let mut wrapper_args: Vec<TokenStream2> = Vec::new();
        let mut call_args: Vec<TokenStream2> = Vec::new();
        // The one receiver model of the concrete wrappers (#509): the
        // pointer, the binding and the first argument of the path call.
        let receiver = m.receiver();
        if !receiver.is_static() {
            if receiver.is_mutable() {
                wrapper_args.push(quote! { ptr: *mut #self_ty });
            } else {
                wrapper_args.push(quote! { ptr: *const #self_ty });
            }
        }
        for (i, arg) in m.func.sig.inputs.iter().enumerate() {
            let FnArg::Typed(pat_type) = arg else {
                continue;
            };
            let ty = &pat_type.ty;
            let name: Ident = match pat_type.pat.as_ref() {
                Pat::Ident(pi) => pi.ident.clone(),
                _ => format_ident!("arg{}", i),
            };
            wrapper_args.push(quote! { #name: #ty });
            call_args.push(quote! { #name });
        }
        let is_ctor = inline_method_is_ctor(struct_name, m);
        // An elided return lifetime (`-> &str`, `-> &T`) borrows from a
        // reference receiver, which the wrapper receives as a raw pointer;
        // name the lifetime so the wrapper itself is valid Rust (`&*ptr` is
        // unbounded and coerces to it, #484). A static method's arguments
        // are passed through as written, so elision on the wrapper picks
        // what it picks on the method; a lowered string among them is
        // refused when the instance is wrapped (`name_elided_return`).
        let borrow = m
            .func
            .sig
            .receiver()
            .map(crate::environment::SelfBorrow::of)
            .unwrap_or(crate::environment::SelfBorrow::None);
        let (decl_generics, ret) = match (&m.func.sig.output, &borrow) {
            (ReturnType::Type(_, ty), crate::environment::SelfBorrow::Ref(named))
                if crate::environment::has_elided_lifetime(ty) =>
            {
                let mut g = decl_generics.clone();
                let lifetime: syn::Lifetime = match named {
                    Some(named) => named.clone(),
                    None => {
                        // A name the method's own lifetimes do not already
                        // use, by the rule concrete wrappers follow.
                        let fresh = {
                            let predicates = &where_clause;
                            crate::environment::fresh_lifetime(
                                quote! { #g #predicates #(#wrapper_args)* #ty },
                            )
                        };
                        // `&'fresh Self<T>` requires every type parameter to
                        // outlive it.
                        for param in g.params.iter_mut() {
                            if let syn::GenericParam::Type(tp) = param {
                                tp.bounds.push(syn::TypeParamBound::Lifetime(fresh.clone()));
                            }
                        }
                        g.params.insert(
                            0,
                            syn::GenericParam::Lifetime(syn::LifetimeParam::new(fresh.clone())),
                        );
                        fresh
                    }
                };
                let mut ty = (**ty).clone();
                crate::environment::name_elided_lifetimes(&mut ty, &lifetime);
                (g, quote! { -> #ty })
            }
            (other, _) => (decl_generics.clone(), quote! { #other }),
        };
        let ret = &ret;
        let func: ItemFn = if is_ctor {
            syn::parse_quote! {
                pub fn #wrapper_name #decl_generics (#(#wrapper_args),*) -> *mut #self_ty #where_clause {
                    let obj = #struct_name::#method_name(#(#call_args),*);
                    Box::into_raw(Box::new(obj))
                }
            }
        } else {
            let self_obj = format_ident!("self_obj");
            let binding = receiver.binding(&self_obj, &format_ident!("ptr"));
            let args = receiver
                .argument(&self_obj)
                .into_iter()
                .chain(call_args.iter().cloned());
            syn::parse_quote! {
                pub fn #wrapper_name #decl_generics (#(#wrapper_args),*) #ret #where_clause {
                    #binding
                    <#self_ty>::#method_name(#(#args),*)
                }
            }
        };
        // `Self` in the method's signature and predicates is the block's
        // type, which the wrapper, a free function, has to spell (#482).
        let mut func = func;
        crate::environment::expand_self_in_signature(
            &ImplHost {
                generics: decl_generics.clone(),
                self_ty: self_ty.clone(),
                trait_: None,
            },
            &mut func.sig,
        );
        let mut method_cfgs = m.enclosing_cfg.clone();
        method_cfgs.extend(cfg_attrs(&m.func.attrs));
        wrappers.push(GenericWrapper {
            name: wrapper_name.to_string(),
            source: fn_source(gated(func, &method_cfgs)),
            type_params: wrapper_param_names(&decl_generics, &self_ty),
        });
    }

    // Accessor and free wrappers are emitted generically into the expanded
    // source, so they must type-check for every `T`: carry the struct's own
    // `where` predicates and state what the getter body needs (`Copy` to read
    // the field out through the raw pointer, `Clone` for a String).
    let struct_predicates: Vec<syn::WherePredicate> = generics
        .where_clause
        .as_ref()
        .map(|w| w.predicates.iter().cloned().collect())
        .unwrap_or_default();
    let where_of = |extra: Option<syn::WherePredicate>| -> TokenStream2 {
        let mut preds = struct_predicates.clone();
        preds.extend(extra);
        if preds.is_empty() {
            quote! {}
        } else {
            quote! { where #(#preds),* }
        }
    };
    let struct_where = where_of(None);

    let struct_param_names = model.type_param_names();
    let method_symbols: Vec<String> = wrappers.iter().map(|w| w.name.clone()).collect();
    for (field_name, field_ty) in model.named_fields() {
        if !generic_field_has_accessors(&field_ty, &struct_param_names) {
            continue;
        }
        let getter = format_ident!("{}", field_getter_symbol(&stem, &field_name.to_string()));
        if method_symbols.contains(&getter.to_string()) {
            continue;
        }
        let setter = format_ident!("{}", field_setter_symbol(&stem, &field_name.to_string()));
        let (body, getter_where) = if is_string_type(&field_ty) {
            (
                quote! { unsafe { (*ptr).#field_name.clone() } },
                where_of(Some(syn::parse_quote!(#field_ty: Clone))),
            )
        } else {
            (
                quote! { unsafe { (*ptr).#field_name } },
                where_of(Some(syn::parse_quote!(#field_ty: Copy))),
            )
        };
        let g: ItemFn = syn::parse_quote! {
            pub fn #getter #decl_generics (ptr: *const #struct_name #ty_generics) -> #field_ty #getter_where { #body }
        };
        let s: ItemFn = syn::parse_quote! {
            pub fn #setter #decl_generics (ptr: *mut #struct_name #ty_generics, value: #field_ty) #struct_where {
                unsafe { (*ptr).#field_name = value; }
            }
        };
        let field_cfgs = model.field_cfg_attrs(&field_name);
        let g = gated(g, &field_cfgs);
        let s = gated(s, &field_cfgs);
        wrappers.push(GenericWrapper {
            name: getter.to_string(),
            source: fn_source(g),
            type_params: struct_param_names.clone(),
        });
        wrappers.push(GenericWrapper {
            name: setter.to_string(),
            source: fn_source(s),
            type_params: struct_param_names.clone(),
        });
    }

    let free_name = format_ident!("{}", struct_free_symbol(&stem));
    let f: ItemFn = syn::parse_quote! {
        pub fn #free_name #decl_generics (ptr: *mut #struct_name #ty_generics) #struct_where {
            if !ptr.is_null() {
                unsafe { drop(Box::from_raw(ptr)); }
            }
        }
    };
    wrappers.push(GenericWrapper {
        name: free_name.to_string(),
        source: fn_source(gated(f, &[])),
        type_params: struct_param_names,
    });

    wrappers
}