swiftui-native 0.0.1

SwiftUI from pure Rust — no Swift bridge, no shim, only swift-runtime calls
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
//! Bindings and modifiers generic over a protocol.
//!
//! * Generic modifiers: `Hashable`, `Shape`, and focus bindings

use super::*;
use crate::abi;
use crate::resolve;
use core::ffi::c_void;
use crate::mangle::{self, swift_type};

// ── Bindings and modifiers generic over a protocol ──

//
// A `Binding` is three registers wide and two-way: SwiftUI reads it to decide
// what to show and writes back when the user acts, and both ends land in the
// Rust state it was built from.

/// The concrete types conforming to `SwiftUI.InsettableShape`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum InsettableShape {
    Circle,
    Ellipse,
    Rectangle,
    ContainerRelativeShape,
}

impl InsettableShape {
    /// The shape's own name, mangled, for spelling a type it appears in.
    pub(crate) fn type_mangling(self) -> &'static str {
        match self {
            Self::Circle => "7SwiftUI6CircleV",
            Self::Ellipse => "7SwiftUI7EllipseV",
            Self::Rectangle => "7SwiftUI9RectangleV",
            Self::ContainerRelativeShape => "7SwiftUI22ContainerRelativeShapeV",
        }
    }

    /// The shape's metadata accessor, its `InsettableShape` witness table, and
    /// its `init()`.
    pub(crate) fn parts(self) -> (*const c_void, *const c_void, *const c_void) {
        match self {
            Self::Circle => (
                resolve::circle_ma(),
                resolve::circle_insettable_wt(),
                resolve::circle_init(),
            ),
            Self::Ellipse => (
                resolve::ellipse_ma(),
                resolve::ellipse_insettable_wt(),
                resolve::ellipse_init(),
            ),
            Self::Rectangle => (
                resolve::rectangle_ma(),
                resolve::rectangle_insettable_wt(),
                resolve::rectangle_init(),
            ),
            Self::ContainerRelativeShape => (
                resolve::container_relative_shape_ma(),
                resolve::container_relative_shape_insettable_wt(),
                resolve::container_relative_shape_init(),
            ),
        }
    }
}

/// Apply `.findNavigator(isPresented:)`.
///
/// The binding is two-way: SwiftUI reads it to decide whether to show the find
/// bar and writes back when the user dismisses it, so `state` sees both.
pub fn find_navigator(view: &ViewHandle, state: &BoundState<bool>) -> ViewHandle {
    unsafe {
        let mut b = bool_binding(state);
        let w = binding_words(&mut b);
        opaque_modifier(
            resolve::find_navigator_fn(),
            resolve::find_navigator_oret(),
            view,
            &w,
            [0.0; 4],
        )
    }
}

/// Apply `.dialogSuppressionToggle(isSuppressed:)`.
pub fn dialog_suppression_toggle(view: &ViewHandle, state: &BoundState<bool>) -> ViewHandle {
    unsafe {
        let mut b = bool_binding(state);
        let w = binding_words(&mut b);
        opaque_modifier(
            resolve::dialog_suppression_toggle_fn(),
            resolve::dialog_suppression_toggle_oret(),
            view,
            &w,
            [0.0; 4],
        )
    }
}

/// Apply `.dialogSuppressionToggle(_:isSuppressed:)` with a label.
///
/// Seven integer arguments — four for the key, three for the binding — so
/// `Self.Type` and the witness table travel on the stack rather than in
/// registers.
pub fn dialog_suppression_toggle_labelled(
    view: &ViewHandle,
    label: &str,
    state: &BoundState<bool>,
) -> ViewHandle {
    unsafe {
        let ss = abi::swift_string(label);
        let k = localized_string_key(
            u64::from_le_bytes(ss[..8].try_into().expect("lo")),
            u64::from_le_bytes(ss[8..].try_into().expect("hi")),
        );
        let mut b = bool_binding(state);
        let w = binding_words(&mut b);
        opaque_modifier(
            resolve::dialog_suppression_toggle_labelled_fn(),
            resolve::dialog_suppression_toggle_labelled_oret(),
            view,
            &[k.0, k.1, k.2, k.3, w[0], w[1], w[2]],
            [0.0; 4],
        )
    }
}

/// Apply `.highPriorityGesture(_:including:)` with a `DragGesture`.
///
/// Generic over `Gesture`, so the call carries the gesture's metadata and its
/// conformance alongside `Self`'s — the same shape as a style modifier, with a
/// `GestureMask` on the end.
pub fn high_priority_gesture(view: &ViewHandle, minimum_distance: f64, action: impl Fn() + 'static) -> ViewHandle {
    unsafe {
        gesture_variant(
            resolve::high_priority_gesture_fn(),
            resolve::high_priority_gesture_oret(),
            view,
            minimum_distance,
            action,
        )
    }
}

/// Apply `.simultaneousGesture(_:including:)` with a `DragGesture`.
///
/// Generic over `Gesture`, so the call carries the gesture's metadata and its
/// conformance alongside `Self`'s — the same shape as a style modifier, with a
/// `GestureMask` on the end.
pub fn simultaneous_gesture(view: &ViewHandle, minimum_distance: f64, action: impl Fn() + 'static) -> ViewHandle {
    unsafe {
        gesture_variant(
            resolve::simultaneous_gesture_fn(),
            resolve::simultaneous_gesture_oret(),
            view,
            minimum_distance,
            action,
        )
    }
}

/// Apply `.containerShape(_:)`.
///
/// Three overloads share this name, differing only by extra constraints; this
/// is the one taking a plain `InsettableShape`. A shape that also conforms to
/// `RoundedRectangularShape` — `Circle`, `Rectangle`, `Capsule` — resolves to a
/// different overload in Swift source than the symbol bound here, and so
/// produces a different modifier.
pub fn container_shape(view: &ViewHandle, shape: InsettableShape) -> ViewHandle {
    unsafe {
        let (meta, wt, init) = shape.parts();
        style_modifier(
            resolve::container_shape_fn(),
            resolve::container_shape_oret(),
            view,
            meta,
            wt,
            init,
        )
    }
}

// ── Generic modifiers: `Hashable`, `Shape`, and focus bindings ──

/// Apply a modifier with one generic parameter beyond `Self`.
///
/// [`opaque_modifier`] cannot express these. It appends `Self.Type` and the
/// `Self: View` witness table to the arguments, which is the whole tail for an
/// ordinary modifier; a generic one takes a second metadata argument and a
/// second witness table, and the value arguments come first. So the sequence is
/// value, then any further arguments, then both types, then both conformances.
///
/// # Safety
/// `arg` must be a valid value of the type `arg_meta` describes, and `arg_wt`
/// its conformance to whatever protocol the modifier constrains the parameter
/// to.
pub(crate) unsafe fn generic1_modifier(
    func: *const c_void,
    oret: *const c_void,
    view: &ViewHandle,
    arg_meta: *const c_void,
    arg_wt: *const c_void,
    arg: &[u8],
    extra: &[u64],
) -> ViewHandle {
    unsafe {
        let subst = [view.meta, arg_meta, view.wt, arg_wt];
        let (meta, wt, size) = opaque_result_type(oret, &subst);
        let mut ints = Vec::with_capacity(5 + extra.len());
        ints.push(arg.as_ptr() as u64);
        ints.extend_from_slice(extra);
        ints.push(view.meta as u64);
        ints.push(arg_meta as u64);
        ints.push(view.wt as u64);
        ints.push(arg_wt as u64);
        let r = abi::call_modifier_generic(func, view.value_ptr(), &ints, [0.0; 4], size);
        wrap_owned(r, meta, wt)
    }
}

/// A value to pass where SwiftUI asks for `some Hashable`.
///
/// `id` and `tag` are generic over `Hashable` rather than over any SwiftUI
/// protocol, so the conformance comes from the standard library and the choice
/// of concrete type is the caller's.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HashableValue<'a> {
    Str(&'a str),
    Int(i64),
    Bool(bool),
    Double(f64),
}

impl HashableValue<'_> {
    /// The value's bytes, its metadata, and its `Hashable` witness table.
    pub(crate) unsafe fn parts(self) -> (Vec<u8>, *const c_void, *const c_void) {
        unsafe {
            match self {
                Self::Str(s) => (
                    abi::swift_string(s).to_vec(),
                    resolve::string_meta(),
                    resolve::string_hashable_wt(),
                ),
                Self::Int(i) => {
                    (i.to_le_bytes().to_vec(), resolve::int_meta(), resolve::int_hashable_wt())
                }
                Self::Bool(b) => {
                    (vec![u8::from(b)], resolve::bool_meta(), resolve::bool_hashable_wt())
                }
                Self::Double(d) => {
                    (d.to_le_bytes().to_vec(), resolve::double_meta(), resolve::double_hashable_wt())
                }
            }
        }
    }
}

/// Anything that can stand where SwiftUI wants `some Hashable`.
///
/// So that `.id(7)` and `.id("row")` are what a caller writes, rather than
/// `.id(HashableValue::Int(7))`. The enum stays as the carrier — it is what
/// crosses into the unsafe code — and this is the conversion into it.
///
/// Implemented per Rust type rather than blanket over `Hash`: the value has to
/// cross into Swift, so it needs a Swift type with a `Hashable` conformance to
/// cross *as*, and that mapping is a decision per type rather than something
/// derivable.
pub trait IntoHashable<'a> {
    /// This value as the carrier.
    fn into_hashable(self) -> HashableValue<'a>;
}

impl<'a> IntoHashable<'a> for HashableValue<'a> {
    fn into_hashable(self) -> HashableValue<'a> {
        self
    }
}

impl<'a> IntoHashable<'a> for &'a str {
    fn into_hashable(self) -> HashableValue<'a> {
        HashableValue::Str(self)
    }
}

impl<'a> IntoHashable<'a> for &'a String {
    fn into_hashable(self) -> HashableValue<'a> {
        HashableValue::Str(self)
    }
}

impl IntoHashable<'_> for i64 {
    fn into_hashable(self) -> HashableValue<'static> {
        HashableValue::Int(self)
    }
}

impl IntoHashable<'_> for i32 {
    fn into_hashable(self) -> HashableValue<'static> {
        // Swift's `Int` is 64-bit everywhere this runs, so a narrower Rust
        // integer widens rather than getting a `Hashable` of its own — an
        // `Int32` id would hash differently from the `Int` beside it.
        HashableValue::Int(i64::from(self))
    }
}

impl IntoHashable<'_> for usize {
    fn into_hashable(self) -> HashableValue<'static> {
        HashableValue::Int(self as i64)
    }
}

impl IntoHashable<'_> for bool {
    fn into_hashable(self) -> HashableValue<'static> {
        HashableValue::Bool(self)
    }
}

impl IntoHashable<'_> for f64 {
    fn into_hashable(self) -> HashableValue<'static> {
        HashableValue::Double(self)
    }
}

/// Apply `.id(_:)`.
pub fn id(view: &ViewHandle, value: HashableValue<'_>) -> ViewHandle {
    unsafe {
        let (bytes, meta, wt) = value.parts();
        generic1_modifier(resolve::id_fn(), resolve::id_oret(), view, meta, wt, &bytes, &[])
    }
}

/// Apply a `ViewModifier` *value* to a view.
///
/// The general case, and the way out of a corner: SwiftUI's convenience
/// spellings are increasingly `@_alwaysEmitIntoClient`, which means the
/// compiler inlines them into the caller and the framework exports no symbol to
/// call. `View.modifier(_:)` is exported, is generic over the modifier with no
/// constraint at all, and returns `ModifiedContent<Self, M>` concretely — so
/// building `M`'s value and handing it over reaches every one of them.
///
/// # Safety
/// `bytes` must be a valid value of the type `modifier_meta` describes, and
/// that type must conform to `ViewModifier`.
pub unsafe fn apply_modifier(
    view: &ViewHandle,
    modifier_meta: *const c_void,
    bytes: &[u8],
) -> ViewHandle {
    unsafe {
        // `ModifiedContent<Self, Modifier>` — `Self` being the receiver, not
        // `AnyView`. Composing against `AnyView` while handing the call a
        // concrete receiver described a result of the wrong size and shape, and
        // the callee wrote through it.
        let content = abi::generic_metadata2(
            resolve::modified_content_ma(),
            view.meta,
            modifier_meta,
        );
        let wt = abi::get_view_wt(content);
        assert!(!wt.is_null(), "{} !: View", crate::diag::type_name(content));
        let ints = [
            bytes.as_ptr() as u64,
            view.meta as u64,
            modifier_meta as u64,
            view.wt as u64,
        ];
        let r = abi::call_modifier_generic(resolve::view_modifier_fn(), view.value_ptr(),
            &ints,
            [0.0; 4],
            abi::type_bytes(content),
        );
        wrap_owned(r, content, wt)
    }
}

/// Apply `.tag(_:)`.
///
/// Not through the exported `View.tag` symbol, which is the pre-macOS 26
/// spelling and still builds `_TraitWritingModifier<TagValueTraitKey<V>>`. The
/// modifier Swift source produces today is `_TagTraitWritingModifier<V>`,
/// written by an `@_alwaysEmitIntoClient` function that exports nothing — so
/// the value is assembled here and applied with [`apply_modifier`]. The struct
/// is `@frozen`, which is what makes laying its two fields out by hand sound.
pub fn tag(view: &ViewHandle, value: HashableValue<'_>) -> ViewHandle {
    unsafe {
        let (bytes, meta, wt) = value.parts();
        let modifier = abi::generic_metadata2(resolve::tag_trait_writing_modifier_ma(), meta, wt);
        let size = abi::type_size(modifier);
        let at = abi::type_size(meta);
        assert_eq!(size, at + 1, "_TagTraitWritingModifier is not tag + Bool");
        let mut v = vec![0u8; abi::type_bytes(modifier)];
        v[..bytes.len()].copy_from_slice(&bytes);
        // `includeOptional` follows the tag, and defaults to true.
        v[at] = 1;
        apply_modifier(view, modifier, &v)
    }
}

impl InsettableShape {
    /// The same shapes seen as plain `Shape`s, for modifiers that ask only for
    /// that. A conformance is per protocol, not per type, so `contentShape`
    /// needs a different witness table from `containerShape` for the very same
    /// `Circle`.
    pub(crate) fn shape_parts(self) -> (*const c_void, *const c_void, *const c_void) {
        match self {
            Self::Circle => (resolve::circle_ma(), resolve::circle_shape_wt(), resolve::circle_init()),
            Self::Ellipse => (resolve::ellipse_ma(), resolve::ellipse_shape_wt(), resolve::ellipse_init()),
            Self::Rectangle => (resolve::rectangle_ma(), resolve::rectangle_shape_wt(), resolve::rectangle_init()),
            Self::ContainerRelativeShape => (
                resolve::container_relative_shape_ma(),
                resolve::container_relative_shape_shape_wt(),
                resolve::container_relative_shape_init(),
            ),
        }
    }
}

/// Apply `.contentShape(_:eoFill:)`.
pub fn content_shape(view: &ViewHandle, shape: InsettableShape, eo_fill: bool) -> ViewHandle {
    unsafe {
        let (ma, wt, init) = shape.shape_parts();
        let meta = abi::metadata0(ma);
        let mut value = vec![0u8; abi::type_bytes(meta)];
        abi::call_out(init, [0; 8], [0.0; 4], meta as u64, value.as_mut_ptr());
        generic1_modifier(
            resolve::content_shape_fn(),
            resolve::content_shape_oret(),
            view,
            meta,
            wt,
            &value,
            &[u64::from(eo_fill)],
        )
    }
}

/// Build a `FocusState<Bool>.Binding` by projecting a fresh `FocusState`.
///
/// `FocusState` is `@frozen`, so both it and its nested `Binding` are three
/// words that travel in registers rather than by address. The projection is a
/// method on a generic struct, which means the caller supplies `Value`'s
/// metadata and its `Hashable` conformance even though `Value` is pinned to
/// `Bool` here.
///
/// A binding made this way is not attached to a view graph, so nothing will
/// ever set it — which is exactly what `@FocusState var` produces before the
/// view it belongs to is installed, and what the modifier stores either way.
pub(crate) unsafe fn focus_binding(state_type: &[u8], init: *const c_void, projected: *const c_void) -> [u64; 3] {
    unsafe {
        let state_meta = abi::resolve_type_by_mangled_name(state_type);
        assert!(!state_meta.is_null(), "focus state metadata");
        // `init()` is spelled `<Value where Value == Bool>`, which still makes
        // it a generic function: `FocusState<Value>` is address-only in its own
        // body, so the new value is written through x8 rather than returned in
        // registers. Reading x0-x2 instead happens to yield zeroes for
        // `FocusState`, which is the right answer for the wrong reason and the
        // wrong one for `AccessibilityFocusState`.
        let mut this = [0u64; 3];
        core::arch::asm!("blr {f}", f = in(reg) init,
            in("x8") this.as_mut_ptr(), in("x20") state_meta,
            lateout("x0") _, lateout("x1") _, lateout("x2") _,
            lateout("x3") _, lateout("x4") _, lateout("x5") _, lateout("x6") _,
            lateout("x7") _, lateout("x9") _, lateout("x10") _,
            lateout("x11") _, lateout("x12") _, lateout("x13") _, lateout("x14") _,
            lateout("x15") _, lateout("x16") _, lateout("x17") _, lateout("lr") _,
            lateout("x21") _, clobber_abi("C"),
        );
        // `projectedValue` is generic in `Value`, so inside it both
        // `FocusState<Value>` and the `Binding` it returns are address-only:
        // the receiver arrives by pointer in x20 and the result is written
        // through x8. Only the *caller* of `.focused(_:)` knows `Value == Bool`
        // and can pass the binding's three words in registers.
        //
        // The metadata in x0 is the bound `FocusState<Bool>`, not `Bool`. That
        // is the one place this getter departs from the usual rule that a
        // generic function receives its type *parameters*: passing `Bool` there
        // faults inside the first value-witness call.
        let mut out = vec![0u64; 3];
        core::arch::asm!("blr {f}", f = in(reg) projected,
            in("x0") state_meta, in("x1") resolve::bool_hashable_wt(),
            in("x8") out.as_mut_ptr(), in("x20") this.as_mut_ptr(),
            lateout("x2") _, lateout("x3") _, lateout("x4") _, lateout("x5") _,
            lateout("x6") _, lateout("x7") _, lateout("x9") _,
            lateout("x10") _, lateout("x11") _, lateout("x12") _, lateout("x13") _,
            lateout("x14") _, lateout("x15") _, lateout("x16") _, lateout("x17") _,
            lateout("lr") _, lateout("x21") _, clobber_abi("C"),
        );
        [out[0], out[1], out[2]]
    }
}

/// Apply `.focused(_:)`.
pub fn focused(view: &ViewHandle) -> ViewHandle {
    unsafe {
        let b = focus_binding(
            mangle::bound(&swift_type!(SwiftUI.FocusState), &[mangle::BOOL]).as_bytes(),
            resolve::focus_state_bool_init(),
            resolve::focus_state_projected(),
        );
        opaque_modifier(resolve::focused_fn(), resolve::focused_oret(), view, &b, [0.0; 4])
    }
}

/// Apply `.focused(_:)` with a real, installed `@FocusState`.
///
/// [`focused`] applies the same modifier with a `FocusState` built on the spot,
/// which is what SwiftUI stores either way but leaves nothing to read or move.
/// This takes the projection of a property SwiftUI has installed, so
/// [`crate::state::ComposedView::focus`] reports whether the field has focus
/// and [`crate::state::ComposedView::set_focus`] puts it there.
pub fn focused_on(view: &ViewHandle, projection: [u64; 3]) -> ViewHandle {
    unsafe {
        opaque_modifier(
            resolve::focused_fn(),
            resolve::focused_oret(),
            view,
            &projection,
            [0.0; 4],
        )
    }
}

/// Apply `.searchFocused(_:)`.
pub fn search_focused(view: &ViewHandle) -> ViewHandle {
    unsafe {
        let b = focus_binding(
            mangle::bound(&swift_type!(SwiftUI.FocusState), &[mangle::BOOL]).as_bytes(),
            resolve::focus_state_bool_init(),
            resolve::focus_state_projected(),
        );
        opaque_modifier(
            resolve::search_focused_fn(),
            resolve::search_focused_oret(),
            view,
            &b,
            [0.0; 4],
        )
    }
}

/// Apply `.accessibilityFocused(_:)`.
pub fn accessibility_focused(view: &ViewHandle) -> ViewHandle {
    unsafe {
        let b = focus_binding(
            mangle::bound(&swift_type!(SwiftUI.AccessibilityFocusState), &[mangle::BOOL]).as_bytes(),
            resolve::a11y_focus_state_bool_init(),
            resolve::a11y_focus_state_projected(),
        );
        opaque_modifier(
            resolve::a11y_focused_fn(),
            resolve::a11y_focused_oret(),
            view,
            &b,
            [0.0; 4],
        )
    }
}

/// Apply `.coordinateSpace(name:)`.
pub fn coordinate_space(view: &ViewHandle, name: HashableValue<'_>) -> ViewHandle {
    unsafe {
        let (bytes, meta, wt) = name.parts();
        generic1_modifier(
            resolve::coordinate_space_name_fn(),
            resolve::coordinate_space_name_oret(),
            view,
            meta,
            wt,
            &bytes,
            &[],
        )
    }
}

/// A `Hashable` type, named rather than carried.
///
/// The metatype-keyed modifiers take `A.Type` rather than an `A`, so they need
/// the metadata and the conformance but no value.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum HashableKind {
    Str,
    Int,
}

/// Apply `.scrollPosition(id:anchor:)`.
///
/// The anchor is an optional `UnitPoint`, which travels as three integer
/// registers rather than two float ones and a tag.
pub fn scroll_position_id(
    view: &ViewHandle,
    state: &BoundState<String>,
    anchor: Option<(f64, f64)>,
) -> ViewHandle {
    unsafe {
        let g = state.clone();
        let st = state.clone();
        let value_meta = abi::resolve_type_by_mangled_name(mangle::optional(mangle::STRING).as_bytes());
        let binding = binding_get_set(
            value_meta,
            mangle::bound(&swift_type!(SwiftUI.Binding), &[&mangle::optional(mangle::STRING)]).as_bytes(),
            Box::new(move |out| {
                let s = abi::swift_string(&g.get());
                core::ptr::copy_nonoverlapping(s.as_ptr(), out, 16);
            }),
            Box::new(move |v| {
                let mut raw = [0u8; 16];
                core::ptr::copy_nonoverlapping(v, raw.as_mut_ptr(), 16);
                st.set(abi::read_swift_string(raw));
            }),
        );
        // `Binding<A?>` with `A` generic is address-only, so the binding goes
        // by pointer rather than in the three registers a concrete one uses.
        let mut ints = vec![binding.as_ptr() as u64];
        ints.extend(opt_unit_point_words(anchor));
        generic1_modifier_ints(
            resolve::scroll_position_id_fn(),
            resolve::scroll_position_id_oret(),
            view,
            resolve::string_meta(),
            resolve::string_hashable_wt(),
            &ints,
            [0.0; 4],
        )
    }
}

/// Apply `.preference(key:value:)` with a runtime-synthesized key.
///
/// The key type carries a `PreferenceKey` conformance built by
/// [`crate::conformance`] at run time, and its `Value` is `Int`. No Swift
/// source declares it, which is the whole point: this is the one family of
/// modifiers that expects the *client* to supply a conformance.
pub fn preference_int(view: &ViewHandle, value: i64) -> ViewHandle {
    unsafe {
        let wt = crate::conformance::preference_key().witness_table();
        let meta = resolve::spacer_meta();
        // `key: K.Type` is the metadata itself. `value: K.Value` is an
        // *associated* type, which the callee only knows abstractly, so it
        // travels by address however small the concrete type turns out to be.
        let mut boxed = value;
        generic1_modifier_ints(
            resolve::preference_fn(),
            resolve::preference_oret(),
            view,
            meta,
            wt,
            &[meta as u64, &mut boxed as *mut i64 as u64],
            [0.0; 4],
        )
    }
}

/// Apply a modifier with one generic parameter carrying *two* conformances.
unsafe fn generic2_modifier_ints(
    func: *const c_void,
    oret: *const c_void,
    view: &ViewHandle,
    arg_meta: *const c_void,
    wt_a: *const c_void,
    wt_b: *const c_void,
    leading: &[u64],
) -> ViewHandle {
    unsafe {
        let subst = [view.meta, arg_meta, view.wt, wt_a, wt_b];
        let (meta, wt, size) = opaque_result_type(oret, &subst);
        let mut ints = leading.to_vec();
        ints.push(view.meta as u64);
        ints.push(arg_meta as u64);
        ints.push(view.wt as u64);
        ints.push(wt_a as u64);
        ints.push(wt_b as u64);
        let r = abi::call_modifier_generic(func, view.value_ptr(), &ints, [0.0; 4], size);
        wrap_owned(r, meta, wt)
    }
}

/// Where [`on_preference_change_int`] records what SwiftUI handed it.
pub(crate) static OBSERVED_PREFERENCE: std::sync::atomic::AtomicI64 =
    std::sync::atomic::AtomicI64::new(i64::MIN);

pub(crate) unsafe extern "C" fn record_preference(
    a0: u64,
    _a1: u64,
    _a2: u64,
    _payload: *mut c_void,
) {
    // `K.Value` is an associated type, so it arrives by address.
    let v = unsafe { *(a0 as *const i64) };
    OBSERVED_PREFERENCE.store(v, std::sync::atomic::Ordering::SeqCst);
}

/// Apply `.onPreferenceChange(_:perform:)`, recording the value.
///
/// The value is read back through [`observed_preference`]. `K.Value` must also
/// be `Equatable` here, so the call carries two witness tables for the one
/// generic parameter.
pub fn on_preference_change_int(view: &ViewHandle) -> ViewHandle {
    unsafe {
        let wt = crate::conformance::preference_key().witness_table();
        let meta = resolve::spacer_meta();
        let c = wide_words(record_preference, core::ptr::null_mut());
        generic2_modifier_ints(
            resolve::on_preference_change_fn(),
            resolve::on_preference_change_oret(),
            view,
            meta,
            wt,
            resolve::int_equatable_wt(),
            &[meta as u64, c[0], c[1]],
        )
    }
}

/// The last preference value `onPreferenceChange` reported, if any.
pub fn observed_preference() -> Option<i64> {
    let v = OBSERVED_PREFERENCE.load(std::sync::atomic::Ordering::SeqCst);
    (v != i64::MIN).then_some(v)
}

pub(crate) unsafe extern "C" fn double_preference(
    a0: u64,
    _a1: u64,
    _a2: u64,
    _payload: *mut c_void,
) {
    // `inout K.Value`, so the pointer is writable.
    unsafe {
        let p = a0 as *mut i64;
        *p *= 2;
    }
}

/// Apply `.transformPreference(_:_:)`, doubling the value in place.
pub fn transform_preference_double(view: &ViewHandle) -> ViewHandle {
    unsafe {
        let wt = crate::conformance::preference_key().witness_table();
        let meta = resolve::spacer_meta();
        let c = wide_words(double_preference, core::ptr::null_mut());
        generic1_modifier_ints(
            resolve::transform_preference_fn(),
            resolve::transform_preference_oret(),
            view,
            meta,
            wt,
            &[meta as u64, c[0], c[1]],
            [0.0; 4],
        )
    }
}


/// `String`'s `Transferable` conformance, found at run time.
///
/// No synthesis needed: `String`, `URL`, `Data` and `Image` all conform
/// already, and the runtime hands the witness table over on request. What made
/// this look unreachable before was the protocol descriptor's mangled name —
/// `Transferable` inside `CoreTransferable` is word-substituted, so it is
/// `$s16CoreTransferable0B0Mp` and not the spelled-out form.
unsafe fn string_transferable() -> (*const c_void, *const c_void) {
    unsafe {
        let meta = resolve::string_meta();
        let wt = abi::get_view_wt_for_proto(meta, resolve::transferable_proto());
        assert!(!wt.is_null(), "String: Transferable");
        (meta, wt)
    }
}

/// A Swift `[String]`, built from Rust strings and kept alive.
pub(crate) unsafe fn swift_string_array(items: &[&str]) -> u64 {
    unsafe {
        let meta = resolve::string_meta();
        let stride = abi::type_bytes(meta);
        let mut bytes = vec![0u8; stride * items.len()];
        for (i, s) in items.iter().enumerate() {
            bytes[i * stride..i * stride + 16].copy_from_slice(&abi::swift_string(s));
        }
        abi::swift_array(meta, items.len(), &bytes)
    }
}

/// Read a Swift `[String]` back into Rust.
pub(crate) unsafe fn read_string_array(array: u64) -> Vec<String> {
    unsafe {
        if array == 0 {
            return Vec::new();
        }
        let stride = abi::type_bytes(resolve::string_meta());
        let (base, count) = abi::array_parts(array);
        (0..count)
            .map(|i| {
                let mut raw = [0u8; 16];
                core::ptr::copy_nonoverlapping(base.add(i * stride), raw.as_mut_ptr(), 16);
                abi::read_swift_string(raw)
            })
            .collect()
    }
}

/// Whether a drop of these strings should be accepted.
pub(crate) type StringsDecide = Box<dyn Fn(&[String]) -> bool>;

/// What a strings drop handler is told, with no answer expected.
pub(crate) type StringsObserve = Box<dyn Fn(&[String])>;

/// A payload the closures below carry: a prebuilt array, or a Rust callback.
pub(crate) struct StringsPayload {
    pub(crate) array: u64,
    pub(crate) decide: Option<StringsDecide>,
    pub(crate) observe: Option<StringsObserve>,
}

/// `() -> [String]` — hand back the array this closure was built with.
pub(crate) unsafe extern "C" fn emit_strings(payload: *mut c_void, _arg: u64) -> u64 {
    unsafe {
        let p = &*(payload as *const StringsPayload);
        // The caller takes ownership of what a closure returns.
        swift_runtime_sys::RuntimeRaw::swift_retain(p.array as *mut c_void);
        p.array
    }
}

/// `([String]) -> Bool` — decode the array and ask the Rust callback.
pub(crate) unsafe extern "C" fn decide_on_strings(payload: *mut c_void, arg: u64) -> u64 {
    unsafe {
        let p = &*(payload as *const StringsPayload);
        let items = read_string_array(arg);
        u64::from(p.decide.as_ref().map(|f| f(&items)).unwrap_or(false))
    }
}

/// `([String]) -> [String]` — let the callback see them, return them unchanged.
pub(crate) unsafe extern "C" fn observe_strings(payload: *mut c_void, arg: u64) -> u64 {
    unsafe {
        let p = &*(payload as *const StringsPayload);
        if let Some(f) = p.observe.as_ref() {
            f(&read_string_array(arg));
        }
        swift_runtime_sys::RuntimeRaw::swift_retain(arg as *mut c_void);
        arg
    }
}

fn strings_payload(array: u64) -> *mut c_void {
    Box::leak(Box::new(StringsPayload { array, decide: None, observe: None }))
        as *mut StringsPayload as *mut c_void
}

fn callback_payload(
    decide: Option<StringsDecide>,
    observe: Option<StringsObserve>,
) -> *mut c_void {
    Box::leak(Box::new(StringsPayload { array: 0, decide, observe }))
        as *mut StringsPayload as *mut c_void
}

/// Apply `.copyable(_:)` with the strings to offer.
pub fn copyable(view: &ViewHandle, items: &[&str]) -> ViewHandle {
    unsafe {
        let (meta, wt) = string_transferable();
        let c = word_closure(emit_strings, strings_payload(swift_string_array(items)));
        generic1_modifier_ints(
            resolve::copyable_fn(),
            resolve::copyable_oret(),
            view,
            meta,
            wt,
            &[c[0], c[1]],
            [0.0; 4],
        )
    }
}

/// Apply `.cuttable(for:action:)` with the strings to offer.
pub fn cuttable(view: &ViewHandle, items: &[&str]) -> ViewHandle {
    unsafe {
        let (meta, wt) = string_transferable();
        let c = word_closure(emit_strings, strings_payload(swift_string_array(items)));
        generic1_modifier_ints(
            resolve::cuttable_fn(),
            resolve::cuttable_oret(),
            view,
            meta,
            wt,
            &[meta as u64, c[0], c[1]],
            [0.0; 4],
        )
    }
}

/// Apply `.exportableToServices(_:)` with the strings to export.
pub fn exportable_to_services(view: &ViewHandle, items: &[&str]) -> ViewHandle {
    unsafe {
        let (meta, wt) = string_transferable();
        let c = word_closure(emit_strings, strings_payload(swift_string_array(items)));
        generic1_modifier_ints(
            resolve::exportable_to_services_fn(),
            resolve::exportable_to_services_oret(),
            view,
            meta,
            wt,
            &[c[0], c[1]],
            [0.0; 4],
        )
    }
}

/// Apply `.importableFromServices(for:action:)`.
///
/// `accept` sees the imported strings and answers whether it took them.
pub fn importable_from_services(view: &ViewHandle, accept: impl Fn(&[String]) -> bool + 'static) -> ViewHandle {
    unsafe {
        let (meta, wt) = string_transferable();
        let c = word_closure(decide_on_strings, callback_payload(Some(Box::new(accept)), None));
        generic1_modifier_ints(
            resolve::importable_from_services_fn(),
            resolve::importable_from_services_oret(),
            view,
            meta,
            wt,
            &[meta as u64, c[0], c[1]],
            [0.0; 4],
        )
    }
}

/// Apply `.dropDestination(for:action:isTargeted:)`.
///
/// `accept` sees the dropped strings and answers whether it took them;
/// `targeted` is told when the drop enters and leaves.
pub fn drop_destination(
    view: &ViewHandle,
    accept: impl Fn(&[String]) -> bool + 'static,
    targeted: impl Fn(bool) + 'static,
) -> ViewHandle {
    unsafe {
        let (meta, wt) = string_transferable();
        // `([A], CGPoint) -> Bool`: the array is in x0 and the point in d0/d1,
        // and the answer comes back in x0 — so the one-word closure serves.
        let action = word_closure(decide_on_strings, callback_payload(Some(Box::new(accept)), None));
        let is_targeted = bool_words(targeted);
        generic1_modifier_ints(
            resolve::drop_destination_fn(),
            resolve::drop_destination_oret(),
            view,
            meta,
            wt,
            &[meta as u64, action[0], action[1], is_targeted[0], is_targeted[1]],
            [0.0; 4],
        )
    }
}

/// Apply `.pasteDestination(for:action:validator:)`.
///
/// `paste` sees what was pasted; the validator passes every item through.
pub fn paste_destination(view: &ViewHandle, paste: impl Fn(&[String]) + 'static) -> ViewHandle {
    unsafe {
        let (meta, wt) = string_transferable();
        let action = wide_words(invoke_string_array, callback_payload(None, Some(Box::new(paste))));
        let validator = word_closure(observe_strings, callback_payload(None, None));
        generic1_modifier_ints(
            resolve::paste_destination_fn(),
            resolve::paste_destination_oret(),
            view,
            meta,
            wt,
            &[meta as u64, action[0], action[1], validator[0], validator[1]],
            [0.0; 4],
        )
    }
}

/// `([String]) -> ()` — decode and hand to the Rust callback.
pub(crate) unsafe extern "C" fn invoke_string_array(
    a0: u64,
    _a1: u64,
    _a2: u64,
    payload: *mut c_void,
) {
    unsafe {
        let p = &*(payload as *const StringsPayload);
        if let Some(f) = p.observe.as_ref() {
            f(&read_string_array(a0));
        }
    }
}

/// `.scrollPosition(_:anchor:)` — scroll to an edge, and stay bound to it.
///
/// [`scroll_position_id`] is the other overload, which scrolls to a row by its
/// identity. This one takes a whole `ScrollPosition`, which is what
/// "scrolled to the top" is: there is no row to name.
///
/// The position lives in the binding for the life of the view. SwiftUI writes
/// back as the user scrolls, so it has to be somewhere that outlives the call
/// that made it.
pub fn scroll_position_edge(view: &ViewHandle, edge: super::Edge) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::scroll_position_ma());
        assert!(!meta.is_null(), "ScrollPosition metadata");
        let mut initial = vec![0u8; abi::type_bytes(meta)];
        // `init(idType:edge:)`: x0 = the id metatype, x1 = the `Edge` tag,
        // x2 = T.Type and x3 = T: Hashable for the generic `some Hashable`.
        // `Never` is what Swift's own default argument passes.
        core::arch::asm!("blr {f}", f = in(reg) resolve::scroll_position_edge_init(),
            in("x0") resolve::never_meta(),
            in("x1") edge as u64,
            in("x2") resolve::never_meta(),
            in("x3") resolve::never_hashable_wt(),
            in("x8") initial.as_mut_ptr(),
            lateout("x4") _, lateout("x5") _, lateout("x6") _, lateout("x7") _,
            lateout("x9") _, lateout("x10") _, lateout("x11") _, lateout("x12") _,
            lateout("x13") _, lateout("x14") _, lateout("x15") _, lateout("x16") _,
            lateout("x17") _, lateout("lr") _, lateout("x20") _, lateout("x21") _,
            clobber_abi("C"),
        );

        let cell: &'static std::sync::Mutex<Vec<u8>> =
            Box::leak(Box::new(std::sync::Mutex::new(initial)));
        let get_cell = cell;
        let binding = super::binding_get_set(
            meta,
            b"7SwiftUI7BindingVyAA14ScrollPositionVG",
            Box::new(move |out| {
                let v = get_cell.lock().expect("scroll position");
                core::ptr::copy_nonoverlapping(v.as_ptr(), out, v.len());
            }),
            Box::new(move |inp| {
                let mut v = cell.lock().expect("scroll position");
                let n = v.len();
                core::ptr::copy_nonoverlapping(inp, v.as_mut_ptr(), n);
            }),
        );

        let subst = [view.meta, view.wt];
        let (out_meta, out_wt, size) =
            opaque_result_type(resolve::scroll_position_oret(), &subst);
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        // x0 = @in Binding, x1/x2 = the `UnitPoint` payload and x3 its tag
        // (1 = nil, which is the default anchor), x4 = Self.Type,
        // x5 = Self: View WT, x8 = @out, x20 = self.
        core::arch::asm!("blr {f}", f = in(reg) resolve::scroll_position_fn(),
            in("x0") binding.as_ptr(),
            in("x1") 0u64,
            in("x2") 0u64,
            in("x3") 1u64,
            in("x4") view.meta,
            in("x5") view.wt,
            in("x8") result.as_mut_ptr(),
            in("x20") this,
            lateout("x6") _, lateout("x7") _,
            lateout("x9") _, lateout("x10") _, lateout("x11") _, lateout("x12") _,
            lateout("x13") _, lateout("x14") _, lateout("x15") _, lateout("x16") _,
            lateout("x17") _, lateout("lr") _, lateout("x21") _, clobber_abi("C"),
        );
        wrap_owned(result, out_meta, out_wt)
    }
}

/// The text a `draggable` autoclosure hands back, and the closure that makes
/// a fresh `+1` copy of it on each call.
struct DragText {
    text: String,
}

/// The `() -> String` autoclosure body.
///
/// A new Swift string each time: the value is returned `+1`, and SwiftUI calls
/// this once per drag. Handing back the same two words twice would over-release
/// one allocation.
///
/// # Safety
/// `payload` must be a leaked [`DragText`].
unsafe extern "C" fn emit_drag_text(payload: *mut c_void) -> abi::Pair {
    unsafe {
        let d = &*(payload as *const DragText);
        let s = abi::swift_string(&d.text);
        abi::Pair(
            u64::from_le_bytes(s[..8].try_into().expect("lo")),
            u64::from_le_bytes(s[8..].try_into().expect("hi")),
        )
    }
}

/// Apply `.draggable(_:)` with a `String` payload.
///
/// The overload everything else calls `draggable`: drag this view and a piece
/// of text comes out, droppable anywhere that takes one. The
/// `containerItemID:` binding next door is a different modifier for a
/// different job — reordering within a container.
///
/// `String` because it is the `Transferable` conformer that needs no bridging:
/// its witness is exported from CoreTransferable, and its value is two loadable
/// words. A `Data` or a `URL` payload would each need their own.
pub fn draggable_text(view: &ViewHandle, text: &str) -> ViewHandle {
    unsafe {
        // SwiftUI keeps the autoclosure for as long as the view lives.
        let ctx = Box::leak(Box::new(abi::PairReturnClosureCtx::new(
            emit_drag_text,
            Box::into_raw(Box::new(DragText { text: text.to_string() })) as *mut c_void,
        ))) as *mut abi::PairReturnClosureCtx;
        generic1_modifier_ints(
            resolve::draggable_fn(),
            resolve::draggable_oret(),
            view,
            resolve::string_meta(),
            resolve::string_transferable_wt(),
            &[abi::pair_return_closure_thunk as *const () as u64, ctx as u64],
            [0.0; 4],
        )
    }
}

/// Apply `.draggable(containerItemID:containerNamespace:)`.
///
/// `Sendable` constrains the signature but emits no witness table, so the
/// `Hashable` one is the only conformance to pass.
pub fn draggable_container_item(view: &ViewHandle, id: HashableValue<'_>) -> ViewHandle {
    unsafe {
        let (bytes, meta, wt) = id.parts();
        // `Namespace.ID?` is two words: the id and a discriminator.
        let ns = crate::type_by_name!(swift_type!(SwiftUI.Namespace.ID).as_bytes());
        let opt = crate::type_by_name!(swift_type!(opt SwiftUI.Namespace.ID).as_bytes());
        let mut buf = vec![0u8; abi::type_bytes(opt)];
        abi::store_optional_tag(&mut buf, ns, false);
        let words: Vec<u64> = (0..abi::type_bytes(opt) / 8)
            .map(|i| u64::from_le_bytes(buf[i * 8..i * 8 + 8].try_into().expect("word")))
            .collect();
        let mut ints = vec![bytes.as_ptr() as u64];
        ints.extend(words);
        generic1_modifier_ints(
            resolve::draggable_container_fn(),
            resolve::draggable_container_oret(),
            view,
            meta,
            wt,
            &ints,
            [0.0; 4],
        )
    }
}

/// `(Proxy) -> Int` — measure the proxy, ask the Rust callback, and write the
/// answer through x8.
///
/// The proxy arrives in x0 and used to be ignored, which made the modifier
/// unable to do the one thing it is for: `measure` could return a constant or
/// read a global, and never the geometry it was being handed. `GeometryReader`
/// next door had read the proxy all along, so the accessor was already there.
pub(crate) unsafe extern "C" fn emit_measured_int(out: *mut u8, proxy: i64, payload: *mut c_void) {
    unsafe {
        let f = boxed_ref::<dyn Fn(f64, f64) -> i64>(payload);
        let (w, h) = crate::views::geometry_proxy_size(proxy as *const u8);
        *(out as *mut i64) = f(w, h);
    }
}

/// `(Proxy) -> Double` — the same as [`emit_measured_int`] for a `Double`.
///
/// `onGeometryChange<T>` returns `T` indirectly whatever `T` is, because it is
/// generic — so this differs from the integer one only in what it writes.
pub(crate) unsafe extern "C" fn emit_measured_f64(out: *mut u8, proxy: i64, payload: *mut c_void) {
    unsafe {
        let f = boxed_ref::<dyn Fn(f64, f64) -> f64>(payload);
        let (w, h) = crate::views::geometry_proxy_size(proxy as *const u8);
        *(out as *mut f64) = f(w, h);
    }
}

/// `(Double, Double) -> ()` — hand the old and new values over.
pub(crate) unsafe extern "C" fn invoke_f64_pair(
    a: *const u8,
    b: *const u8,
    payload: *mut c_void,
) {
    unsafe {
        let f = boxed_ref::<dyn Fn(f64, f64)>(payload);
        f(*(a as *const f64), *(b as *const f64));
    }
}

/// `(T, T) -> ()` — hand the old and new values to the Rust callback.
///
/// Both arrive by address because `T` is generic here. `Int` is what this
/// binding instantiates it with, so both are one word to load.
pub(crate) unsafe extern "C" fn invoke_int_pair(
    a: *const u8,
    b: *const u8,
    payload: *mut c_void,
) {
    unsafe {
        let f = boxed_ref::<dyn Fn(i64, i64)>(payload);
        f(*(a as *const i64), *(b as *const i64));
    }
}

/// Apply `.onGeometryChange(for:of:action:)`.
///
/// `measure` turns the proxy's size into the value to watch; `action` is called
/// with the old and the new one whenever it changes.
///
/// `measure` returns the generic `T`, so it returns *through x8*, with the
/// proxy in x0 — which is why it needs the index thunk rather than the plain
/// one.
pub fn on_geometry_change_int(
    view: &ViewHandle,
    measure: impl Fn(f64, f64) -> i64 + 'static,
    action: impl Fn(i64, i64) + 'static,
) -> ViewHandle {
    unsafe {
        let meta = resolve::int_meta();
        let wt = resolve::int_equatable_wt();
        let of = Box::leak(Box::new(abi::IndexClosureCtx::new(
            emit_measured_int,
            boxed_ctx(Box::new(measure) as Box<dyn Fn(f64, f64) -> i64>),
        ))) as *mut abi::IndexClosureCtx;
        let act = pair_words(invoke_int_pair, boxed_ctx(Box::new(action) as Box<dyn Fn(i64, i64)>));
        generic1_modifier_ints(
            resolve::on_geometry_change_fn(),
            resolve::on_geometry_change_oret(),
            view,
            meta,
            wt,
            &[
                meta as u64,
                abi::index_closure_thunk as *const () as u64,
                of as u64,
                act[0],
                act[1],
            ],
            [0.0; 4],
        )
    }
}

/// Apply `.onGeometryChange(for: Double.self, of:action:)`.
///
/// `for:` was `Int` and only `Int`, so a width — which is what the modifier is
/// nearly always used to watch — had to be rounded to be watched at all.
/// Swift's constraint on `T` is `Equatable`, and `Double` has a witness.
pub fn on_geometry_change_f64(
    view: &ViewHandle,
    measure: impl Fn(f64, f64) -> f64 + 'static,
    action: impl Fn(f64, f64) + 'static,
) -> ViewHandle {
    unsafe {
        let meta = resolve::double_meta();
        let wt = resolve::double_equatable_wt();
        let of = Box::leak(Box::new(abi::IndexClosureCtx::new(
            emit_measured_f64,
            boxed_ctx(Box::new(measure) as Box<dyn Fn(f64, f64) -> f64>),
        ))) as *mut abi::IndexClosureCtx;
        let act = pair_words(invoke_f64_pair, boxed_ctx(Box::new(action) as Box<dyn Fn(f64, f64)>));
        generic1_modifier_ints(
            resolve::on_geometry_change_fn(),
            resolve::on_geometry_change_oret(),
            view,
            meta,
            wt,
            &[
                meta as u64,
                abi::index_closure_thunk as *const () as u64,
                of as u64,
                act[0],
                act[1],
            ],
            [0.0; 4],
        )
    }
}

/// A `Foundation.JSONDecoder`, with the `ObservableObject` conformance this
/// crate synthesizes.
///
/// The object used to be `ImageRenderer<AnyView>` — the one SwiftUI class that
/// already conforms — which reached the modifiers but could never be checked
/// against anything: reflecting into a live `ImageRenderer` faults, so all
/// three object modifiers sat outside the parity suite. A `JSONDecoder` holds
/// nothing but its own options and dumps in two lines, and Swift can declare
/// the same conformance retroactively, so the reference builds the same value.
///
/// See [`crate::conformance::observable_object`] for the table.
unsafe fn observable_object() -> (u64, *const c_void, *const c_void) {
    unsafe {
        let conformance = crate::conformance::observable_object();
        let meta = abi::metadata0(resolve::json_decoder_ma());
        assert!(!meta.is_null(), "JSONDecoder metadata");
        // A class initialiser: the metatype in x20, the new instance in x0.
        let object = abi::call_regs(resolve::json_decoder_init(), abi::ints(&[]), [0.0; 4], meta as u64)[0];
        (object, meta, conformance.witness_table())
    }
}

/// Apply a modifier taking an `ObservableObject`.
unsafe fn object_modifier(
    func: *const c_void,
    oret: *const c_void,
    view: &ViewHandle,
) -> ViewHandle {
    unsafe {
        let (object, meta, wt) = observable_object();
        // `ObservableObject` refines `AnyObject`, so `B` is class-constrained
        // and loadable: the reference goes in a register, not by address.
        generic1_modifier_ints(func, oret, view, meta, wt, &[object], [0.0; 4])
    }
}

/// Apply `.environmentObject(_:)`.
pub fn environment_object(view: &ViewHandle) -> ViewHandle {
    unsafe {
        object_modifier(resolve::environment_object_fn(), resolve::environment_object_oret(), view)
    }
}

/// Apply `.focusedObject(_:)`.
pub fn focused_object(view: &ViewHandle) -> ViewHandle {
    unsafe {
        object_modifier(resolve::focused_object_fn(), resolve::focused_object_oret(), view)
    }
}

/// Apply `.focusedSceneObject(_:)`.
pub fn focused_scene_object(view: &ViewHandle) -> ViewHandle {
    unsafe {
        object_modifier(
            resolve::focused_scene_object_fn(),
            resolve::focused_scene_object_oret(),
            view,
        )
    }
}

/// Apply `.accessibilityDefaultFocus(_:_:)`.
///
/// The binding's `Value` is generic here, which makes `FocusState<A>.Binding`
/// address-only — unlike the concrete `focused(_:)`, where it travels in three
/// registers.
pub fn accessibility_default_focus(view: &ViewHandle, value: bool) -> ViewHandle {
    unsafe {
        let mut binding = accessibility_focus_binding();
        let mut v = u64::from(value);
        generic1_modifier_ints(
            resolve::a11y_default_focus_fn(),
            resolve::a11y_default_focus_oret(),
            view,
            resolve::bool_meta(),
            resolve::bool_hashable_wt(),
            &[binding.as_mut_ptr() as u64, &mut v as *mut u64 as u64],
            [0.0; 4],
        )
    }
}

/// The three words of a fresh `AccessibilityFocusState<Bool>.Binding`.
pub(crate) unsafe fn accessibility_focus_binding() -> [u64; 3] {
    unsafe {
        focus_binding(
            mangle::bound(&swift_type!(SwiftUI.AccessibilityFocusState), &[mangle::BOOL]).as_bytes(),
            resolve::a11y_focus_state_bool_init(),
            resolve::a11y_focus_state_projected(),
        )
    }
}


/// Apply `.layoutValue(key:value:)` with a runtime-synthesized key.
///
/// A second protocol through the same machinery as [`preference_int`], to show
/// nothing about it is specific to `PreferenceKey`.
pub fn layout_value_int(view: &ViewHandle, value: i64) -> ViewHandle {
    unsafe {
        let wt = crate::conformance::layout_value_key().witness_table();
        let meta = resolve::divider_meta();
        let mut boxed = value;
        generic1_modifier_ints(
            resolve::layout_value_fn(),
            resolve::layout_value_oret(),
            view,
            meta,
            wt,
            &[meta as u64, &mut boxed as *mut i64 as u64],
            [0.0; 4],
        )
    }
}

/// Apply a modifier taking a value of a protocol this crate conforms to at
/// run time, using `EmptyView` as the conforming type.
unsafe fn synthesized_value_modifier(
    func: *const c_void,
    oret: *const c_void,
    view: &ViewHandle,
    wt: *const c_void,
) -> ViewHandle {
    unsafe {
        // `EmptyView` has no stored properties, so the value is zero bytes —
        // but the callee still takes it by address, so it needs somewhere to
        // point.
        let mut empty = 0u64;
        generic1_modifier_ints(
            func,
            oret,
            view,
            resolve::empty_meta(),
            wt,
            &[&mut empty as *mut u64 as u64],
            [0.0; 4],
        )
    }
}

/// Apply `.presentationSizing(_:)`.
pub fn presentation_sizing(view: &ViewHandle) -> ViewHandle {
    unsafe {
        synthesized_value_modifier(
            resolve::presentation_sizing_fn(),
            resolve::presentation_sizing_oret(),
            view,
            crate::conformance::presentation_sizing().witness_table(),
        )
    }
}

/// Apply `.previewContext(_:)`.
pub fn preview_context(view: &ViewHandle) -> ViewHandle {
    unsafe {
        synthesized_value_modifier(
            resolve::preview_context_fn(),
            resolve::preview_context_oret(),
            view,
            crate::conformance::preview_context().witness_table(),
        )
    }
}

/// The `WritableKeyPath<EnvironmentValues, Image.Scale>` SwiftUI itself builds.
///
/// Constructing a key path from nothing means emitting a key path *pattern* and
/// handing it to `swift_getKeyPath` — a compact format describing each
/// component, which for a resilient computed property has to reference the
/// property descriptor. There is an easier way in, because SwiftUI already
/// builds the ones this crate needs: `.imageScale(_:)` returns
/// `_EnvironmentKeyWritingModifier<Image.Scale>`, whose first stored property
/// *is* that key path. So the modifier is applied once and the key path read
/// back out of the result.
///
/// The layout is `ModifiedContent<AnyView, _EnvironmentKeyWritingModifier<V>>`:
/// eight bytes of `AnyView`, then the key path, then the value.
unsafe fn image_scale_key_path() -> u64 {
    use std::sync::atomic::{AtomicU64, Ordering};
    static CACHE: AtomicU64 = AtomicU64::new(0);
    unsafe {
        let cached = CACHE.load(Ordering::Relaxed);
        if cached != 0 {
            return cached;
        }
        let meta = abi::metadata0(resolve::image_scale_ma());
        let mut arg = vec![0u8; abi::type_bytes(meta)];
        abi::inject_enum_tag(&mut arg, meta, 2);
        // `EmptyView`, not `Text`: the key path is read back out of the
        // modifier, which `ModifiedContent` lays out after the content. An
        // empty host puts it at offset 0 regardless of what the receiver's
        // type would otherwise contribute.
        let host = super::empty_view();
        let subst = [host.meta, host.wt];
        let (_, _, size) = opaque_result_type(resolve::image_scale_oret(), &subst);
        let r = abi::call_modifier(
            resolve::image_scale_fn(),
            host.value_ptr(),
            host.meta,
            host.wt,
            &[arg.as_ptr() as u64],
            [0.0; 4],
            size,
        );
        let kp = u64::from_le_bytes(r[0..8].try_into().expect("key path word"));
        // The result is dropped with this scope; the key path has to outlive it.
        swift_runtime_sys::RuntimeRaw::swift_retain(kp as *mut c_void);
        CACHE.store(kp, Ordering::Relaxed);
        kp
    }
}

/// The `\EnvironmentValues.symbolVariants` key path.
///
/// `EnvironmentValues` exports no properties, so there is no key path to build
/// — but SwiftUI stores one in every modifier that writes the environment, and
/// `.symbolVariant(_:)` is such a modifier. Calling it on a throwaway view and
/// reading the key path back out of the result is the same trick
/// [`image_scale_key_path`] uses; the only difference is that this one is a
/// *transform* modifier rather than a writing one, which changes what follows
/// the key path and not the key path's position.
unsafe fn symbol_variants_key_path() -> u64 {
    use std::sync::atomic::{AtomicU64, Ordering};
    static CACHE: AtomicU64 = AtomicU64::new(0);
    unsafe {
        let cached = CACHE.load(Ordering::Relaxed);
        if cached != 0 {
            return cached;
        }
        let meta = abi::metadata0(resolve::symbol_variants_ma());
        let mut arg = super::static_getter_indirect(
            resolve::require(super::SymbolVariants::Fill.getter()),
            meta,
            0,
        );
        // `EmptyView`, not `Text`: the key path is read back out of the
        // modifier, which `ModifiedContent` lays out after the content. An
        // empty host puts it at offset 0 regardless of what the receiver's
        // type would otherwise contribute.
        let host = super::empty_view();
        let subst = [host.meta, host.wt];
        let (_, _, size) = opaque_result_type(resolve::symbol_variant_oret(), &subst);
        let r = abi::call_modifier(
            resolve::symbol_variant_fn(),
            host.value_ptr(),
            host.meta,
            host.wt,
            &[arg.as_mut_ptr() as u64],
            [0.0; 4],
            size,
        );
        // `ModifiedContent`: an empty content, then the modifier, whose first
        // field is the key path.
        let kp = u64::from_le_bytes(r[0..8].try_into().expect("key path word"));
        swift_runtime_sys::RuntimeRaw::swift_retain(kp as *mut c_void);
        CACHE.store(kp, Ordering::Relaxed);
        kp
    }
}

/// Apply `.environment(\.symbolVariants, _)`.
pub fn environment_symbol_variants(view: &ViewHandle, value: super::SymbolVariants) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::symbol_variants_ma());
        let arg = super::static_getter_indirect(value.resolved(), meta, 0);
        generic1_modifier_ints(
            resolve::environment_fn(),
            resolve::environment_oret(),
            view,
            meta,
            core::ptr::null(),
            &[symbol_variants_key_path(), arg.as_ptr() as u64],
            [0.0; 4],
        )
    }
}

/// Apply `.environment(_:_:)` for `\EnvironmentValues.imageScale`.
///
/// The value is a generic `V` from the callee's side, so it travels by address
/// however small `Image.Scale` turns out to be.
pub fn environment_image_scale(view: &ViewHandle, scale: ImageScale) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::image_scale_ma());
        let mut value = vec![0u8; abi::type_bytes(meta)];
        abi::inject_enum_tag(&mut value, meta, scale.tag());
        generic1_modifier_ints(
            resolve::environment_fn(),
            resolve::environment_oret(),
            view,
            meta,
            core::ptr::null(),
            &[image_scale_key_path(), value.as_ptr() as u64],
            [0.0; 4],
        )
    }
}

/// `(inout ImageScale) -> ()` — read the current scale, ask Rust, write it back.
///
/// The whole point of `transformEnvironment` is that the value is `inout`: the
/// closure is handed the environment's current setting and replaces it. The
/// binding dropped the argument, so it could observe that the transform ran and
/// never change anything — an `.environment` that could not set.
pub(crate) unsafe extern "C" fn transform_image_scale(
    a0: u64,
    _a1: u64,
    _a2: u64,
    payload: *mut c_void,
) {
    unsafe {
        let f = boxed_ref::<dyn Fn(ImageScale) -> ImageScale>(payload);
        let meta = abi::metadata0(resolve::image_scale_ma());
        let p = a0 as *mut u8;
        let current = match abi::read_enum_tag(p, meta) {
            0 => ImageScale::Small,
            1 => ImageScale::Medium,
            _ => ImageScale::Large,
        };
        let next = f(current);
        let size = abi::type_bytes(meta).max(1);
        abi::inject_enum_tag(core::slice::from_raw_parts_mut(p, size), meta, next as u32);
    }
}

/// Apply `.transformEnvironment(_:_:)` for `\EnvironmentValues.imageScale`.
pub fn transform_environment_image_scale(
    view: &ViewHandle,
    action: impl Fn(ImageScale) -> ImageScale + 'static,
) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::image_scale_ma());
        let c = wide_words(
            transform_image_scale,
            boxed_ctx(Box::new(action) as Box<dyn Fn(ImageScale) -> ImageScale>),
        );
        generic1_modifier_ints(
            resolve::transform_environment_fn(),
            resolve::transform_environment_oret(),
            view,
            meta,
            core::ptr::null(),
            &[image_scale_key_path(), c[0], c[1]],
            [0.0; 4],
        )
    }
}

/// What a `transform_environment` handler needs, erased of its key type.
struct TransformCtx {
    /// Decode the byte the enum is stored as, run the handler, encode again.
    step: Box<dyn Fn(u8) -> u8>,
}

/// The `(inout V) -> ()` body SwiftUI calls.
///
/// Every environment property this crate has a key for stores one byte — an
/// enum tag or a `Bool` — so the whole transform is byte in, byte out, with
/// the key's own `decode`/`encode` on either side. A property whose value is
/// wider would need its own path; `buffer_bytes` is what would say so.
///
/// # Safety
/// `payload` must be a leaked [`TransformCtx`], and `a0` a pointer to a live
/// value of the property's type.
unsafe extern "C" fn transform_env_byte(a0: u64, _a1: u64, _a2: u64, payload: *mut c_void) {
    unsafe {
        let ctx = &*(payload as *const TransformCtx);
        let p = a0 as *mut u8;
        *p = (ctx.step)(*p);
    }
}

/// `.transformEnvironment(_:transform:)` for any property this crate has a
/// key for.
///
/// [`transform_environment_image_scale`] does this for one property, with the
/// key path recovered from a modifier SwiftUI built. Every `EnvKey` already
/// carries its own key path for `@Environment` to read through, so the same
/// modifier works for all of them — the only thing that was missing was a way
/// to write the value back, which is what [`crate::state::EnvKey::encode`] is.
///
/// ```no_run
/// # use swiftui_native::{state::ControlSizeKey, views::{self, ControlSize}};
/// // One size larger than whatever is in scope.
/// views::transform_environment::<ControlSizeKey>(&views::text("x"), |s| match s {
///     ControlSize::Mini => ControlSize::Small,
///     other => other,
/// });
/// ```
pub fn transform_environment<K: crate::state::EnvKey>(
    view: &ViewHandle,
    action: impl Fn(K::Value) -> K::Value + 'static,
) -> ViewHandle {
    unsafe {
        assert_eq!(
            K::buffer_bytes(),
            1,
            "transform_environment handles one-byte values; this key's is wider"
        );
        let meta = abi::resolve_type_by_mangled_name(K::value_type());
        assert!(!meta.is_null(), "environment value metadata");
        let ctx = Box::leak(Box::new(TransformCtx {
            step: Box::new(move |b| K::encode(&action(K::decode(&[b])))),
        })) as *mut TransformCtx;
        let c = wide_words(transform_env_byte, ctx as *mut c_void);
        generic1_modifier_ints(
            resolve::transform_environment_fn(),
            resolve::transform_environment_oret(),
            view,
            meta,
            core::ptr::null(),
            &[K::key_path(), c[0], c[1]],
            [0.0; 4],
        )
    }
}

/// Apply `.dragContainerSelection(_:containerNamespace:)` with the selection.
pub fn drag_container_selection(view: &ViewHandle, selected: &[&str]) -> ViewHandle {
    unsafe {
        let meta = resolve::string_meta();
        let wt = resolve::string_hashable_wt();
        let selection = word_closure(emit_strings, strings_payload(swift_string_array(selected)));
        let ns = crate::type_by_name!(swift_type!(SwiftUI.Namespace.ID).as_bytes());
        let opt = crate::type_by_name!(swift_type!(opt SwiftUI.Namespace.ID).as_bytes());
        let mut buf = vec![0u8; abi::type_bytes(opt)];
        abi::store_optional_tag(&mut buf, ns, false);
        let mut ints = vec![selection[0], selection[1]];
        ints.extend((0..abi::type_bytes(opt) / 8).map(|i| {
            u64::from_le_bytes(buf[i * 8..i * 8 + 8].try_into().expect("word"))
        }));
        generic1_modifier_ints(
            resolve::drag_container_selection_fn(),
            resolve::drag_container_selection_oret(),
            view,
            meta,
            wt,
            &ints,
            [0.0; 4],
        )
    }
}

/// What a scroll view's geometry looks like when it changes.
///
/// `ScrollGeometry` exports no accessors, but it does not need to: the fields
/// are stored, and the metadata says where.
///
/// ```text
///   +0   contentOffset  CGPoint
///   +16  contentSize    CGSize
///   +32  contentInsets  EdgeInsets  (top, leading, bottom, trailing)
///   +64  containerSize  CGSize
///   +80  visibleRect    CGRect      (origin then size)
/// ```
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ScrollGeometry {
    /// How far the content has been scrolled.
    pub content_offset: (f64, f64),
    /// How large the scrollable content is.
    pub content_size: (f64, f64),
    /// The insets around it, as `(top, leading, bottom, trailing)`.
    pub content_insets: (f64, f64, f64, f64),
    /// How large the scroll view itself is.
    pub container_size: (f64, f64),
    /// What part of the content is on screen, as `(x, y, width, height)`.
    pub visible_rect: (f64, f64, f64, f64),
}

/// The offsets of `ScrollGeometry`'s stored fields, from its metadata.
fn scroll_geometry_offsets() -> Option<&'static [usize; 5]> {
    static CACHE: std::sync::OnceLock<Option<[usize; 5]>> = std::sync::OnceLock::new();
    CACHE
        .get_or_init(|| unsafe {
            let offs = abi::struct_field_offsets(abi::metadata0(resolve::scroll_geometry_ma()))?;
            (offs.len() == 5).then(|| [offs[0], offs[1], offs[2], offs[3], offs[4]])
        })
        .as_ref()
}

/// Read the geometry at `p`, which SwiftUI passed by address.
///
/// # Safety
/// `p` must point at a live `ScrollGeometry`.
pub(crate) unsafe fn read_scroll_geometry(p: *const u8) -> ScrollGeometry {
    let Some(&[offset, size, insets, container, visible]) = scroll_geometry_offsets() else {
        return ScrollGeometry::default();
    };
    unsafe {
        let at = |o: usize| *(p.add(o) as *const f64);
        let pair = |o: usize| (at(o), at(o + 8));
        ScrollGeometry {
            content_offset: pair(offset),
            content_size: pair(size),
            content_insets: (at(insets), at(insets + 8), at(insets + 16), at(insets + 24)),
            container_size: pair(container),
            visible_rect: (at(visible), at(visible + 8), at(visible + 16), at(visible + 24)),
        }
    }
}

/// `(ScrollGeometry) -> Int` — measure the geometry and write through x8.
///
/// The geometry arrives in x0 by address, because it is a 112-byte resilient
/// struct. It used to be ignored, which left the modifier able to notice that
/// *something* had scrolled and nothing more.
pub(crate) unsafe extern "C" fn emit_scroll_measure(out: *mut u8, geometry: i64, payload: *mut c_void) {
    unsafe {
        let f = boxed_ref::<dyn Fn(ScrollGeometry) -> i64>(payload);
        *(out as *mut i64) = f(read_scroll_geometry(geometry as *const u8));
    }
}

/// Apply `.onScrollGeometryChange(for:prefersLast:of:action:)`.
pub fn on_scroll_geometry_change(
    view: &ViewHandle,
    measure: impl Fn(ScrollGeometry) -> i64 + 'static,
    action: impl Fn(i64, i64) + 'static,
) -> ViewHandle {
    unsafe {
        let meta = resolve::int_meta();
        let wt = resolve::int_equatable_wt();
        let of = Box::leak(Box::new(abi::IndexClosureCtx::new(
            emit_scroll_measure,
            boxed_ctx(Box::new(measure) as Box<dyn Fn(ScrollGeometry) -> i64>),
        ))) as *mut abi::IndexClosureCtx;
        let act = pair_words(invoke_int_pair, boxed_ctx(Box::new(action) as Box<dyn Fn(i64, i64)>));
        generic1_modifier_ints(
            resolve::on_scroll_geometry_change_fn(),
            resolve::on_scroll_geometry_change_oret(),
            view,
            meta,
            wt,
            &[
                meta as u64,
                abi::index_closure_thunk as *const () as u64,
                of as u64,
                act[0],
                act[1],
            ],
            [0.0; 4],
        )
    }
}

/// Apply `.onScrollGeometryChange(for: Double.self, prefersLast:of:action:)`.
pub fn on_scroll_geometry_change_f64(
    view: &ViewHandle,
    measure: impl Fn(ScrollGeometry) -> f64 + 'static,
    action: impl Fn(f64, f64) + 'static,
) -> ViewHandle {
    unsafe {
        let meta = resolve::double_meta();
        let wt = resolve::double_equatable_wt();
        let of = Box::leak(Box::new(abi::IndexClosureCtx::new(
            emit_scroll_measure_f64,
            boxed_ctx(Box::new(measure) as Box<dyn Fn(ScrollGeometry) -> f64>),
        ))) as *mut abi::IndexClosureCtx;
        let act = pair_words(invoke_f64_pair, boxed_ctx(Box::new(action) as Box<dyn Fn(f64, f64)>));
        generic1_modifier_ints(
            resolve::on_scroll_geometry_change_fn(),
            resolve::on_scroll_geometry_change_oret(),
            view,
            meta,
            wt,
            &[
                meta as u64,
                abi::index_closure_thunk as *const () as u64,
                of as u64,
                act[0],
                act[1],
            ],
            [0.0; 4],
        )
    }
}

/// `(ScrollGeometry) -> Double` — the same as [`emit_scroll_measure`] for a
/// `Double`.
pub(crate) unsafe extern "C" fn emit_scroll_measure_f64(
    out: *mut u8,
    geometry: i64,
    payload: *mut c_void,
) {
    unsafe {
        let f = boxed_ref::<dyn Fn(ScrollGeometry) -> f64>(payload);
        *(out as *mut f64) = f(read_scroll_geometry(geometry as *const u8));
    }
}

/// How big the view being aligned is.
///
/// SwiftUI hands an alignment guide a `ViewDimensions`, and the guide is
/// expected to answer *in terms of it* — `d.width / 2` centres, `d.width`
/// puts the edge at the far side. The binding ignored it, so a guide could
/// only return a constant, which is the one kind of guide that does not need
/// the modifier at all.
///
/// `width` and `height` are read through SwiftUI's own getters. The two
/// remaining accessors — the `[HorizontalAlignment]` and `[VerticalAlignment]`
/// subscripts, which is how Swift writes `d[.leading]` — are `@inlinable` and
/// export no symbol, so they are not here.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct ViewDimensions {
    /// The view's width.
    pub width: f64,
    /// The view's height.
    pub height: f64,
}

/// Read the dimensions at `p`, which SwiftUI passed by address.
///
/// # Safety
/// `p` must point at a live `ViewDimensions`.
pub(crate) unsafe fn read_view_dimensions(p: *const u8) -> ViewDimensions {
    unsafe {
        let get = |f: *const c_void| {
            let out: f64;
            // A getter on a 48-byte struct: self is `@in_guaranteed` in x20 and
            // the `CGFloat` comes back in d0.
            core::arch::asm!("blr {f}", f = in(reg) f,
                in("x20") p,
                lateout("d0") out,
                lateout("x0") _, lateout("x1") _, lateout("x2") _, lateout("x3") _,
                lateout("x4") _, lateout("x5") _, lateout("x6") _, lateout("x7") _,
                lateout("x8") _, lateout("x9") _, lateout("x10") _, lateout("x11") _,
                lateout("x12") _, lateout("x13") _, lateout("x14") _, lateout("x15") _,
                lateout("x16") _, lateout("x17") _, lateout("lr") _, lateout("x21") _,
                clobber_abi("C"),
            );
            out
        };
        let d = ViewDimensions {
            width: get(resolve::view_dimensions_width()),
            height: get(resolve::view_dimensions_height()),
        };
        // The getters should agree with the stored layout — `size` is a
        // `ViewSize` whose first field is the `CGSize`. Checked in debug
        // builds, because if they ever disagree it means one of the two reads
        // is looking at the wrong thing.
        debug_assert_eq!(Some((d.width, d.height)), stored_view_size(p));
        d
    }
}

/// `ViewDimensions.size.value`, read straight out of the struct.
///
/// Only for the crosscheck in [`read_view_dimensions`] — the getters are what
/// the value is actually read with.
///
/// # Safety
/// `p` must point at a live `ViewDimensions`.
unsafe fn stored_view_size(p: *const u8) -> Option<(f64, f64)> {
    unsafe {
        let offs = abi::struct_field_offsets(abi::metadata0(resolve::view_dimensions_ma()))?;
        // guideComputer, size.
        let &[_, size] = offs.as_slice() else { return None };
        let at = p.add(size) as *const f64;
        Some((*at, *at.add(1)))
    }
}

/// `(ViewDimensions) -> CGFloat` — measure, then ask the Rust callback.
pub(crate) unsafe extern "C" fn compute_length(arg: u64, payload: *mut c_void) -> f64 {
    unsafe {
        let f = boxed_ref::<dyn Fn(ViewDimensions) -> f64>(payload);
        f(read_view_dimensions(arg as *const u8))
    }
}

/// Apply `.alignmentGuide(_:computeValue:)`.
///
/// `computeValue` returns a `CGFloat`, which comes back in d0 — so it needs a
/// thunk of its own; the integer-returning one cannot carry it.
pub fn alignment_guide(
    view: &ViewHandle,
    alignment: HorizontalAlignment,
    compute: impl Fn(ViewDimensions) -> f64 + 'static,
) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::horizontal_alignment_ma());
        let a = frozen_static(meta, alignment.getter());
        let ctx = Box::leak(Box::new(abi::FloatClosureCtx::new(
            compute_length,
            boxed_ctx(Box::new(compute) as Box<dyn Fn(ViewDimensions) -> f64>),
        ))) as *mut abi::FloatClosureCtx;
        opaque_modifier(
            resolve::alignment_guide_fn(),
            resolve::alignment_guide_oret(),
            view,
            &[a, abi::float_closure_thunk as *const () as u64, ctx as u64],
            [0.0; 4],
        )
    }
}

/// Apply a modifier generic over *two* parameters.
///
/// The substitution buffer lists every metadata argument before every witness
/// table, so a second parameter is not simply appended — it goes between the
/// first parameter's metadata and the first conformance.
unsafe fn generic_pair_modifier(
    func: *const c_void,
    oret: *const c_void,
    view: &ViewHandle,
    first: (*const c_void, *const c_void),
    second: (*const c_void, *const c_void),
    leading: &[u64],
) -> ViewHandle {
    unsafe {
        let subst = [
            view.meta,
            first.0,
            second.0,
            view.wt,
            first.1,
            second.1,
        ];
        let (meta, wt, size) = opaque_result_type(oret, &subst);
        let mut ints = leading.to_vec();
        ints.extend(subst.iter().map(|p| *p as u64));
        let r = abi::call_modifier_generic(func, view.value_ptr(), &ints, [0.0; 4], size);
        wrap_owned(r, meta, wt)
    }
}

/// Apply `.backgroundPreferenceValue(_:alignment:_:)` with fixed content.
pub fn background_preference_value(
    view: &ViewHandle,
    alignment: Alignment,
    content: &ViewHandle,
) -> ViewHandle {
    unsafe { preference_value_modifier(
        resolve::background_preference_value_fn(),
        resolve::background_preference_value_oret(),
        view, alignment, content,
    ) }
}

/// Apply `.overlayPreferenceValue(_:alignment:_:)` with fixed content.
pub fn overlay_preference_value(
    view: &ViewHandle,
    alignment: Alignment,
    content: &ViewHandle,
) -> ViewHandle {
    unsafe { preference_value_modifier(
        resolve::overlay_preference_value_fn(),
        resolve::overlay_preference_value_oret(),
        view, alignment, content,
    ) }
}

unsafe fn preference_value_modifier(
    func: *const c_void,
    oret: *const c_void,
    view: &ViewHandle,
    alignment: Alignment,
    content: &ViewHandle,
) -> ViewHandle {
    unsafe {
        let key_meta = resolve::spacer_meta();
        let key_wt = crate::conformance::preference_key().witness_table();
        let a = alignment.words();
        let c = view_words(content);
        generic_pair_modifier(
            func,
            oret,
            view,
            (key_meta, key_wt),
            (content.meta, content.wt),
            &[key_meta as u64, a[0], a[1], c[0], c[1]],
        )
    }
}

/// `(Array<A>) -> ()`.
///
/// `Array` is one word whatever its element, so it stays loadable inside a
/// generic function — x0 is the array itself and not a pointer to it, unlike
/// the bare generic parameter [`ask_about_int`] receives.
unsafe extern "C" fn saw_int_array(value: *const u8, payload: *mut c_void) {
    unsafe {
        let f = boxed_ref::<dyn Fn(&[i64])>(payload);
        let (base, count) = abi::array_parts(value as u64);
        f(core::slice::from_raw_parts(base as *const i64, count));
    }
}

/// Apply `.onScrollTargetVisibilityChange(for:threshold:_:)` with `A == Int`.
///
/// `visible` receives the identities of the scroll targets that are at least
/// `threshold` visible, every time that set changes.
pub fn on_scroll_target_visibility_change(
    view: &ViewHandle,
    threshold: f64,
    visible: impl Fn(&[i64]) + 'static,
) -> ViewHandle {
    unsafe {
        let meta = resolve::int_meta();
        let wt = resolve::int_hashable_wt();
        let ctx = Box::leak(Box::new(abi::ValueClosureCtx::new(
            saw_int_array,
            boxed_ctx(Box::new(visible) as Box<dyn Fn(&[i64])>),
        ))) as *mut abi::ValueClosureCtx;
        generic1_modifier_ints(
            resolve::scroll_target_visibility_fn(),
            resolve::scroll_target_visibility_oret(),
            view,
            meta,
            wt,
            &[meta as u64, abi::value_closure_thunk as *const () as u64, ctx as u64],
            [threshold, 0.0, 0.0, 0.0],
        )
    }
}

/// `(EmptyVisualEffect, GeometryProxy) -> A` — return the effect unchanged.
///
/// `EmptyVisualEffect` is empty, so there is nothing to copy and nothing to
/// write: the identity function on a zero-sized type initialises its result by
/// doing nothing at all.
unsafe extern "C" fn identity_effect(_out: *mut u8, _payload: *mut c_void) {}

/// Apply `.visualEffect(_:)`.
///
/// The closure must return `some VisualEffect`, and the smallest real one is
/// `EmptyVisualEffect` — which SwiftUI exports a `VisualEffect` witness table
/// for but no metadata accessor, so the metadata is demangled from its name.
pub fn visual_effect(view: &ViewHandle) -> ViewHandle {
    unsafe {
        let meta = crate::type_by_name!(swift_type!(SwiftUI.EmptyVisualEffect).as_bytes());
        let wt = resolve::empty_visual_effect_wt();
        let ctx = Box::leak(Box::new(abi::ClosureCtx::new(
            identity_effect,
            core::ptr::null_mut(),
        ))) as *mut abi::ClosureCtx;
        generic1_modifier_ints(
            resolve::visual_effect_fn(),
            resolve::visual_effect_oret(),
            view,
            meta,
            wt,
            &[abi::swift_closure_thunk as *const () as u64, ctx as u64],
            [0.0; 4],
        )
    }
}

/// A scroll or layout axis.
///
/// Two cases, neither with a payload, so the tags are the declaration order.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Axis {
    Horizontal = 0,
    Vertical = 1,
}

/// How a scroll transition interpolates.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ScrollTransitionConfiguration {
    /// Follows the scroll position directly.
    Interactive,
    /// Animates between the discrete phases.
    Animated,
    /// Applies nothing.
    Identity,
}

impl ScrollTransitionConfiguration {
    fn getter(self) -> *const c_void {
        match self {
            ScrollTransitionConfiguration::Interactive => resolve::scroll_transition_config_interactive(),
            ScrollTransitionConfiguration::Animated => resolve::scroll_transition_config_animated(),
            ScrollTransitionConfiguration::Identity => resolve::scroll_transition_config_identity(),
        }
    }
}

/// The parts of a `scrollTransition` call that do not depend on which overload
/// is being made: the axis, and the identity transition.
///
/// `axis` is `Optional<Axis>`, which is one byte because `Axis` has two cases
/// and room to spare, so it travels in a register rather than by address.
///
/// The transition is the identity on `EmptyVisualEffect`, as in [`visual_effect`]
/// — a closure that returns its argument is still a real closure, and it is the
/// only `VisualEffect` that can be built without a Swift type of one's own.
unsafe fn scroll_transition_tail(axis: Option<Axis>) -> (Vec<u64>, *const c_void, *const c_void) {
    unsafe {
        let axis_meta = abi::metadata0(resolve::axis_ma());
        let opt_axis = crate::type_by_name!(swift_type!(opt enum SwiftUI.Axis).as_bytes());
        let tag = axis.map(|a| a as u32);
        let mut payload = vec![0u8; abi::type_bytes(axis_meta).max(1)];
        if let Some(t) = tag {
            abi::inject_enum_tag(&mut payload, axis_meta, t);
        }
        let words = optional_words(axis_meta, opt_axis, &payload, tag.is_some());
        let meta = crate::type_by_name!(swift_type!(SwiftUI.EmptyVisualEffect).as_bytes());
        let wt = resolve::empty_visual_effect_wt();
        let ctx = Box::leak(Box::new(abi::ClosureCtx::new(
            identity_effect,
            core::ptr::null_mut(),
        ))) as *mut abi::ClosureCtx;
        let mut ints = words;
        ints.push(abi::swift_closure_thunk as *const () as u64);
        ints.push(ctx as u64);
        (ints, meta, wt)
    }
}

/// Apply `.scrollTransition(_:axis:transition:)`.
pub fn scroll_transition(
    view: &ViewHandle,
    config: ScrollTransitionConfiguration,
    axis: Option<Axis>,
) -> ViewHandle {
    unsafe {
        let cfg_meta = abi::metadata0(resolve::scroll_transition_config_ma());
        let cfg = abi::static_out(config.getter(), cfg_meta, abi::type_bytes(cfg_meta));
        let (tail, meta, wt) = scroll_transition_tail(axis);
        let mut ints = vec![cfg.as_ptr() as u64];
        ints.extend_from_slice(&tail);
        generic1_modifier_ints(
            resolve::scroll_transition_fn(),
            resolve::scroll_transition_oret(),
            view,
            meta,
            wt,
            &ints,
            [0.0; 4],
        )
    }
}

/// Apply `.scrollTransition(topLeading:bottomTrailing:axis:transition:)` — the
/// two ends of the scroll configured separately.
///
/// A view leaving the top of a scroll view and one leaving the bottom are the
/// same transition run in opposite directions, and this is what lets them
/// differ: `.animated` on the way in and `.identity` on the way out, say.
///
/// Both configurations are `@in`, so both travel by address — which is why the
/// two buffers have to outlive the call rather than being built inline.
pub fn scroll_transition_ends(
    view: &ViewHandle,
    top_leading: ScrollTransitionConfiguration,
    bottom_trailing: ScrollTransitionConfiguration,
    axis: Option<Axis>,
) -> ViewHandle {
    unsafe {
        let cfg_meta = abi::metadata0(resolve::scroll_transition_config_ma());
        let size = abi::type_bytes(cfg_meta);
        let lead = abi::static_out(top_leading.getter(), cfg_meta, size);
        let trail = abi::static_out(bottom_trailing.getter(), cfg_meta, size);
        let (tail, meta, wt) = scroll_transition_tail(axis);
        let mut ints = vec![lead.as_ptr() as u64, trail.as_ptr() as u64];
        ints.extend_from_slice(&tail);
        generic1_modifier_ints(
            resolve::scroll_transition_ends_fn(),
            resolve::scroll_transition_ends_oret(),
            view,
            meta,
            wt,
            &ints,
            [0.0; 4],
        )
    }
}

/// Apply `._trait(_:_:)` with a one-byte `Value`.
///
/// `Value` is an associated type, so the callee cannot know its layout and takes
/// it by address however small it is — a `Bool` is a pointer to one byte, not a
/// register.
unsafe fn bool_trait(
    key_ma: *const c_void,
    key_wt: *const c_void,
    view: &ViewHandle,
    value: bool,
) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(key_ma);
        let byte = Box::leak(Box::new(u8::from(value))) as *mut u8;
        generic1_modifier_ints(
            resolve::view_trait_fn(),
            resolve::view_trait_oret(),
            view,
            meta,
            key_wt,
            &[meta as u64, byte as u64],
            [0.0; 4],
        )
    }
}

/// Apply `.selectionDisabled(_:)`.
///
/// The public spelling is `@_alwaysEmitIntoClient`, so it has no symbol of its
/// own — the compiler emits `_trait(IsSelectionEnabledTraitKey.self, !isDisabled)`
/// at every call site, and that is exactly what this calls. The `for:_:` overload
/// that *does* export a symbol is SPI the compiler will not resolve, so binding
/// it would have produced something no Swift program can be written against.
pub fn selection_disabled(view: &ViewHandle, disabled: bool) -> ViewHandle {
    unsafe {
        bool_trait(
            resolve::is_selection_enabled_key_ma(),
            resolve::is_selection_enabled_key_wt(),
            view,
            !disabled,
        )
    }
}

/// `(Anchor<CGRect>) -> K.Value` — hand back the Rust callback's answer.
///
/// `K.Value` is an associated type, so it returns through x8 whatever the
/// concrete type is; the anchor arrives in x0 and is not read here, since
/// nothing outside SwiftUI can resolve one without a layout pass.
unsafe extern "C" fn emit_anchor_value(out: *mut u8, payload: *mut c_void) {
    unsafe {
        let f = boxed_ref::<dyn Fn() -> i64>(payload);
        *(out as *mut i64) = f();
    }
}

/// `(inout K.Value, Anchor<CGRect>) -> ()` — let the callback rewrite the value.
unsafe extern "C" fn fold_anchor_value(value: *const u8, _anchor: *const u8, payload: *mut c_void) {
    unsafe {
        let f = boxed_ref::<dyn Fn(i64) -> i64>(payload);
        let slot = value as *mut i64;
        *slot = f(*slot);
    }
}

/// The pieces `anchorPreference` and `transformAnchorPreference` share.
///
/// Two generic parameters: the anchor's value type, which carries no
/// constraint, and the key, which carries `PreferenceKey`. So the tail is three
/// metadata arguments and only *two* witness tables — an unconstrained generic
/// parameter contributes a type but no conformance.
unsafe fn anchor_preference_parts() -> (*const c_void, *const c_void, *const c_void, u64) {
    unsafe {
        let key_meta = resolve::spacer_meta();
        let key_wt = crate::conformance::preference_key().witness_table();
        let rect_meta = crate::type_by_name!(swift_type!(objc struct CGRect).as_bytes());
        assert!(!rect_meta.is_null(), "CGRect metadata");
        let source: u64;
        core::arch::asm!("blr {f}", f = in(reg) resolve::anchor_source_bounds(),
            lateout("x0") source,
            lateout("x1") _, lateout("x2") _, lateout("x3") _, lateout("x4") _,
            lateout("x5") _, lateout("x6") _, lateout("x7") _, lateout("x8") _,
            lateout("x9") _, lateout("x10") _, lateout("x11") _, lateout("x12") _,
            lateout("x13") _, lateout("x14") _, lateout("x15") _, lateout("x16") _,
            lateout("x17") _, lateout("lr") _, lateout("x20") _, lateout("x21") _,
            clobber_abi("C"),
        );
        (key_meta, key_wt, rect_meta, source)
    }
}

/// Call one of the two anchor-preference modifiers.
unsafe fn anchor_modifier(
    func: *const c_void,
    oret: *const c_void,
    view: &ViewHandle,
    closure: [u64; 2],
) -> ViewHandle {
    unsafe {
        let (key_meta, key_wt, rect_meta, source) = anchor_preference_parts();
        let av = view.meta;
        let aw = view.wt;
        let subst = [av, rect_meta, key_meta, aw, key_wt];
        let (meta, wt, size) = opaque_result_type(oret, &subst);
        let ints = [
            key_meta as u64,
            source,
            closure[0],
            closure[1],
            av as u64,
            rect_meta as u64,
            key_meta as u64,
            aw as u64,
            key_wt as u64,
        ];
        let r = abi::call_modifier_generic(func, view.value_ptr(), &ints, [0.0; 4], size);
        wrap_owned(r, meta, wt)
    }
}

/// Apply `.anchorPreference(key:value:transform:)` with a synthesized key.
///
/// The value is `Anchor<CGRect>.Source.bounds` and the key's `Value` is `Int`,
/// supplied by [`crate::conformance`] rather than by any Swift declaration.
pub fn anchor_preference(view: &ViewHandle, transform: impl Fn() -> i64 + 'static) -> ViewHandle {
    unsafe {
        let ctx = Box::leak(Box::new(abi::ClosureCtx::new(
            emit_anchor_value,
            boxed_ctx(Box::new(transform) as Box<dyn Fn() -> i64>),
        ))) as *mut abi::ClosureCtx;
        anchor_modifier(
            resolve::anchor_preference_fn(),
            resolve::anchor_preference_oret(),
            view,
            [abi::swift_closure_thunk as *const () as u64, ctx as u64],
        )
    }
}

/// Apply `.transformAnchorPreference(key:value:transform:)`.
///
/// The same shape, except the transform takes the running value `inout` — so
/// x0 is a pointer to write back through rather than a result to produce.
pub fn transform_anchor_preference(view: &ViewHandle, transform: impl Fn(i64) -> i64 + 'static) -> ViewHandle {
    unsafe {
        anchor_modifier(
            resolve::transform_anchor_preference_fn(),
            resolve::transform_anchor_preference_oret(),
            view,
            pair_words(fold_anchor_value, boxed_ctx(Box::new(transform) as Box<dyn Fn(i64) -> i64>)),
        )
    }
}

swift_statics! {
    /// How eagerly SwiftUI honours a default focus request.
    pub enum DefaultFocusPriority {
        Automatic = c"$s7SwiftUI30DefaultFocusEvaluationPriorityV9automaticACvgZ",
        UserInitiated = c"$s7SwiftUI30DefaultFocusEvaluationPriorityV13userInitiatedACvgZ",
    }
}

/// Apply `.defaultFocus(_:_:priority:)` with `A == Bool`.
///
/// Three arguments, all by address for the same reason: `FocusState<A>.Binding`
/// and the value are generic over `A`, and the priority is resilient. Where
/// [`focused`] can hand its concrete `FocusState<Bool>.Binding` over in three
/// registers, a generic one cannot travel that way at all.
pub fn default_focus(
    view: &ViewHandle,
    value: bool,
    priority: DefaultFocusPriority,
) -> ViewHandle {
    unsafe {
        let b = focus_binding(
            mangle::bound(&swift_type!(SwiftUI.FocusState), &[mangle::BOOL]).as_bytes(),
            resolve::focus_state_bool_init(),
            resolve::focus_state_projected(),
        );
        let mut binding = [0u8; 24];
        for (i, w) in b.iter().enumerate() {
            binding[i * 8..i * 8 + 8].copy_from_slice(&w.to_le_bytes());
        }
        let mut flag = u8::from(value);
        let pm = abi::metadata0(resolve::default_focus_priority_ma());
        let p = resilient_static(pm, priority.getter());
        generic1_modifier_ints(
            resolve::default_focus_fn(),
            resolve::default_focus_oret(),
            view,
            resolve::bool_meta(),
            resolve::bool_hashable_wt(),
            &[
                binding.as_ptr() as u64,
                &mut flag as *mut u8 as u64,
                p.as_ptr() as u64,
            ],
            [0.0; 4],
        )
    }
}

/// Apply `.textRenderer(_:)` with a runtime-synthesized renderer.
///
/// The public spelling is `@_alwaysEmitIntoClient` and inlines to
/// `modifier(_TextRendererViewModifier(renderer:))`, so that is what this
/// builds — the modifier value directly, with no symbol to call.
pub fn text_renderer(view: &ViewHandle) -> ViewHandle {
    unsafe {
        let renderer = abi::metadata0(resolve::edge_insets_ma());
        let wt = crate::conformance::text_renderer().witness_table();
        let modifier =
            abi::generic_metadata2(resolve::text_renderer_modifier_ma(), renderer, wt);
        // The modifier's one stored property is the renderer, and an all-zero
        // `EdgeInsets` is `EdgeInsets()`.
        let bytes = vec![0u8; abi::type_bytes(modifier)];
        apply_modifier(view, modifier, &bytes)
    }
}

/// Apply `.attributedTextFormattingDefinition(_:)` with `AttributeScopes.SwiftUIAttributes`.
///
/// The overload taking an `AttributeScope` *type* rather than a definition
/// value, so the whole argument is a metatype. The conformance has no exported
/// witness table and comes from a runtime lookup.
pub fn attributed_text_formatting_definition(view: &ViewHandle) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::swiftui_attributes_ma());
        let wt = abi::get_view_wt_for_proto(meta, resolve::attribute_scope_proto());
        assert!(!wt.is_null(), "SwiftUIAttributes: AttributeScope");
        generic1_modifier_ints(
            resolve::attributed_formatting_fn(),
            resolve::attributed_formatting_oret(),
            view,
            meta,
            wt,
            &[meta as u64],
            [0.0; 4],
        )
    }
}

swift_statics! {
    /// How a view's content changes when its value does.
    pub enum ContentTransition {
        Identity = c"$s7SwiftUI17ContentTransitionV8identityACvgZ",
        Opacity = c"$s7SwiftUI17ContentTransitionV7opacityACvgZ",
        Interpolate = c"$s7SwiftUI17ContentTransitionV11interpolateACvgZ",
    }
}

/// `\EnvironmentValues.contentTransition`, built once.
fn content_transition_key_path() -> u64 {
    use std::sync::atomic::{AtomicU64, Ordering};
    static CACHE: AtomicU64 = AtomicU64::new(0);
    static mut SLOT: crate::keypath::Slot = crate::keypath::Slot::new();
    let hit = CACHE.load(Ordering::Relaxed);
    if hit != 0 {
        return hit;
    }
    unsafe {
        let kp = crate::keypath::build(
            crate::static_mut(&raw mut SLOT),
            crate::keypath::Property {
                getter: resolve::env_content_transition_getter(),
                setter: resolve::env_content_transition_setter(),
                descriptor: resolve::env_content_transition_descriptor(),
                root: swift_type!(SwiftUI.EnvironmentValues).as_bytes(),
                value: swift_type!(SwiftUI.ContentTransition).as_bytes(),
            },
            crate::keypath::next_thunks(),
        );
        CACHE.store(kp, Ordering::Relaxed);
        kp
    }
}

/// Apply `.contentTransition(_:)`.
///
/// The public spelling is `@_alwaysEmitIntoClient` and inlines to
/// `environment(\.contentTransition, transition)`, so the key path is built at
/// run time — see [`crate::keypath`] — and handed to the exported
/// `environment(_:_:)`.
pub fn content_transition(view: &ViewHandle, transition: ContentTransition) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::content_transition_ma());
        let value = resilient_static(meta, transition.getter());
        generic1_modifier_ints(
            resolve::environment_fn(),
            resolve::environment_oret(),
            view,
            meta,
            core::ptr::null(),
            &[content_transition_key_path(), value.as_ptr() as u64],
            [0.0; 4],
        )
    }
}

/// `(A) -> Animation?` — hand back the caller's choice.
///
/// `Animation` is one word and so is `Animation?`, whose `nil` is a null
/// reference rather than a separate tag — so the result goes back in x0 and the
/// phase in x0 is simply not read.
///
/// A closure returns its result at `+1`, and `Animation` is a reference. Handing
/// back the borrowed one renders correctly and then dies later, when SwiftUI
/// releases a reference this never took.
unsafe extern "C" fn emit_phase_animation(payload: *mut c_void, _arg: u64) -> u64 {
    if !payload.is_null() {
        unsafe { swift_runtime_sys::RuntimeRaw::swift_retain(payload) };
    }
    payload as u64
}

/// Apply `.phaseAnimator(_:content:animation:)` with `Phase == Int`.
///
/// Three generic parameters beyond `Self`: the phase, the sequence of phases and
/// the content view. `Array<Int>` is the sequence, but the parameter is a bare
/// generic one, so even an array — normally a single loadable word — travels by
/// address here.
pub fn phase_animator(
    view: &ViewHandle,
    phases: &[i64],
    content: &ViewHandle,
    animated: bool,
) -> ViewHandle {
    unsafe {
        let int_meta = resolve::int_meta();
        let mut bytes = Vec::with_capacity(phases.len() * 8);
        for p in phases {
            bytes.extend_from_slice(&p.to_le_bytes());
        }
        let array = abi::swift_array(int_meta, phases.len(), &bytes);
        let array_meta = abi::resolve_type_by_mangled_name(mangle::array(mangle::INT).as_bytes());
        assert!(!array_meta.is_null(), "Array<Int> metadata");
        let seq_wt = abi::get_view_wt_for_proto(array_meta, resolve::sequence_proto());
        assert!(!seq_wt.is_null(), "Array<Int>: Sequence");
        let eq_wt = abi::get_view_wt_for_proto(int_meta, resolve::equatable_proto());
        assert!(!eq_wt.is_null(), "Int: Equatable");

        let anim = if animated {
            let meta = abi::metadata0(resolve::animation_ma());
            frozen_static(meta, c"$s7SwiftUI9AnimationV7defaultACvgZ")
        } else {
            0
        };
        let a = word_closure(emit_phase_animation, anim as *mut c_void);

        // `Self` is the receiver; the trailing `Content` is what the content
        // closure emits, and `view_words` emits an `AnyView`.
        let av = content.meta;
        let aw = content.wt;
        let subst = [view.meta, int_meta, array_meta, av, view.wt, eq_wt, seq_wt, aw];
        let (meta, wt, size) = opaque_result_type(resolve::phase_animator_oret(), &subst);
        let mut ints = vec![&array as *const u64 as u64];
        ints.extend_from_slice(&view_words(content));
        ints.extend_from_slice(&a);
        ints.extend_from_slice(&[view.meta as u64, int_meta as u64, array_meta as u64, av as u64]);
        ints.extend_from_slice(&[view.wt as u64, eq_wt as u64, seq_wt as u64, aw as u64]);
        let r = abi::call_modifier_generic(resolve::phase_animator_fn(), view.value_ptr(), &ints, [0.0; 4], size);
        wrap_owned(r, meta, wt)
    }
}

/// Apply `.textInputSuggestions(_:content:)` with `[EdgeInsets]`.
///
/// The element has to be `Identifiable`, which no public SwiftUI value type is —
/// so the conformance is synthesized onto `EdgeInsets` at run time. Four witness
/// tables follow the three metadata arguments: `Self: View`, the collection's
/// `RandomAccessCollection`, the content's `View`, and the *associated*
/// conformance `A.Element: Identifiable`.
pub fn text_input_suggestions(
    view: &ViewHandle,
    count: usize,
    content: &ViewHandle,
) -> ViewHandle {
    unsafe {
        let elem = abi::metadata0(resolve::edge_insets_ma());
        let stride = abi::type_bytes(elem);
        let bytes = vec![0u8; stride * count];
        let array = abi::swift_array(elem, count, &bytes);
        let array_meta =
            crate::type_by_name!(swift_type!([SwiftUI.EdgeInsets]).as_bytes());
        assert!(!array_meta.is_null(), "[EdgeInsets] metadata");
        let rac = abi::get_view_wt_for_proto(array_meta, resolve::random_access_collection_proto());
        assert!(!rac.is_null(), "[EdgeInsets]: RandomAccessCollection");
        let ident = crate::conformance::identifiable().witness_table();

        // `Self` is the concrete receiver; the trailing type is the content
        // the closure emits, which `view_words` erases to an `AnyView`.
        let av = content.meta;
        let aw = content.wt;
        let subst = [view.meta, array_meta, av, view.wt, rac, aw, ident];
        let (meta, wt, size) = opaque_result_type(resolve::text_input_suggestions_oret(), &subst);
        let mut ints = vec![&array as *const u64 as u64];
        ints.extend_from_slice(&view_words(content));
        ints.extend_from_slice(&[view.meta as u64, array_meta as u64, av as u64]);
        ints.extend_from_slice(&[view.wt as u64, rac as u64, aw as u64, ident as u64]);
        let r = abi::call_modifier_generic(resolve::text_input_suggestions_fn(), view.value_ptr(), &ints, [0.0; 4], size);
        wrap_owned(r, meta, wt)
    }
}

/// `([A.ID]) -> B` — hand back the container's items.
unsafe extern "C" fn emit_drag_items(out: *mut u8, payload: *mut c_void) {
    unsafe { *(out as *mut u64) = payload as u64 };
}

/// Apply `.dragContainer(for:in:_:)` with `Item == String`.
///
/// The item has to be `Transferable` *and* `Identifiable`. `String` has the
/// first already and the second is synthesized onto it — see
/// [`crate::conformance::string_identifiable`]. `A.ID: Sendable` adds no
/// argument: `Sendable` is a marker protocol, so it carries no witness table.
pub fn drag_container(view: &ViewHandle, items: &[&str]) -> ViewHandle {
    unsafe {
        let item = resolve::string_meta();
        let transferable = abi::get_view_wt_for_proto(item, resolve::transferable_proto());
        assert!(!transferable.is_null(), "String: Transferable");
        let identifiable = crate::conformance::string_identifiable().witness_table();
        let array = swift_string_array(items);
        let array_meta = abi::resolve_type_by_mangled_name(mangle::array(mangle::STRING).as_bytes());
        assert!(!array_meta.is_null(), "[String] metadata");
        let collection = abi::get_view_wt_for_proto(array_meta, resolve::collection_proto());
        assert!(!collection.is_null(), "[String]: Collection");

        // `Namespace.ID?` holding `.none`.
        let ns = abi::metadata0(resolve::namespace_id_ma());
        let opt = crate::type_by_name!(swift_type!(opt SwiftUI.Namespace.ID).as_bytes());
        assert!(!opt.is_null(), "Optional<Namespace.ID>");
        let mut none = vec![0u8; abi::type_bytes(opt)];
        abi::store_optional_tag(&mut none, ns, false);
        let none_words = optional_words(ns, opt, &[], false);

        let ctx = Box::leak(Box::new(abi::ClosureCtx::new(
            emit_drag_items,
            array as *mut c_void,
        ))) as *mut abi::ClosureCtx;

        let av = view.meta;
        let aw = view.wt;
        let subst = [av, item, array_meta, aw, transferable, identifiable, collection];
        let (meta, wt, size) = opaque_result_type(resolve::drag_container_oret(), &subst);
        let mut ints = vec![item as u64];
        ints.extend_from_slice(&none_words);
        ints.push(abi::swift_closure_thunk as *const () as u64);
        ints.push(ctx as u64);
        ints.extend_from_slice(&[av as u64, item as u64, array_meta as u64]);
        ints.extend_from_slice(&[aw as u64, transferable as u64, identifiable as u64, collection as u64]);
        let r = abi::call_modifier_generic(resolve::drag_container_fn(), view.value_ptr(), &ints, [0.0; 4], size);
        wrap_owned(r, meta, wt)
    }
}

/// `(P.Output) -> ()` — an associated type, so the value arrives by address.
pub(crate) unsafe extern "C" fn saw_published_int(value: *const u8, payload: *mut c_void) {
    unsafe {
        let f = boxed_ref::<dyn Fn(i64)>(payload);
        f(*(value as *const i64));
    }
}

/// Apply `.onReceive(_:perform:)` with a `Combine.Empty<Int, Never>`.
pub fn on_receive(view: &ViewHandle, complete_immediately: bool, perform: impl Fn(i64) + 'static) -> ViewHandle {
    unsafe {
        let publisher = abi::resolve_type_by_mangled_name(mangle::bound("7Combine5EmptyV", &[mangle::INT, mangle::NEVER]).as_bytes());
        assert!(!publisher.is_null(), "Empty<Int, Never> metadata");
        let wt = abi::get_view_wt_for_proto(publisher, resolve::publisher_proto());
        assert!(!wt.is_null(), "Empty<Int, Never>: Publisher");
        let value = vec![u8::from(complete_immediately); abi::type_bytes(publisher).max(1)];
        let ctx = Box::leak(Box::new(abi::ValueClosureCtx::new(
            saw_published_int,
            boxed_ctx(Box::new(perform) as Box<dyn Fn(i64)>),
        ))) as *mut abi::ValueClosureCtx;
        generic1_modifier_ints(
            resolve::on_receive_fn(),
            resolve::on_receive_oret(),
            view,
            publisher,
            wt,
            &[
                value.as_ptr() as u64,
                abi::value_closure_thunk as *const () as u64,
                ctx as u64,
            ],
            [0.0; 4],
        )
    }
}

/// [`apply_modifier`] for out-of-crate diagnostics.
#[doc(hidden)]
pub unsafe fn apply_modifier_for_test(
    view: &ViewHandle,
    modifier_meta: *const c_void,
    bytes: &[u8],
) -> ViewHandle {
    unsafe { apply_modifier(view, modifier_meta, bytes) }
}

/// Apply `.focusedValue(_:)` with an `Observable` object.
///
/// The overload taking a key path needs a property on `FocusedValues`, which
/// only a client declares — so this is the other one, generic over
/// `AnyObject & Observable`. `AnyObject` is a layout constraint and contributes
/// no witness table; only the `Observable` conformance does, and that is
/// synthesized, because `Observable` has no requirements to satisfy.
pub fn focused_value(view: &ViewHandle, present: bool) -> ViewHandle {
    unsafe {
        let meta = abi::resolve_type_by_mangled_name(
            mangle::Type::Nominal {
                module: "Foundation",
                path: vec!["JSONDecoder"],
                kind: mangle::Kind::Class,
            }
            .mangle()
            .as_bytes(),
        );
        assert!(!meta.is_null(), "Foundation.JSONDecoder metadata");
        let wt = crate::conformance::observable().witness_table();
        let object = if present {
            let o: u64;
            core::arch::asm!("blr {f}", f = in(reg) resolve::json_decoder_init(),
                inlateout("x0") meta => o, in("x20") meta,
                lateout("x1") _, lateout("x2") _, lateout("x3") _, lateout("x4") _,
                lateout("x5") _, lateout("x6") _, lateout("x7") _, lateout("x8") _,
                lateout("x9") _, lateout("x10") _, lateout("x11") _, lateout("x12") _,
                lateout("x13") _, lateout("x14") _, lateout("x15") _, lateout("x16") _,
                lateout("x17") _, lateout("lr") _, lateout("x21") _, clobber_abi("C"),
            );
            o
        } else {
            // `Optional` of a class reference needs no tag: `nil` is null.
            0
        };
        generic1_modifier_ints(
            resolve::focused_value_fn(),
            resolve::focused_value_oret(),
            view,
            meta,
            wt,
            &[object],
            [0.0; 4],
        )
    }
}

/// The one `MoveKeyframe` a track is built from, and the track itself.
///
/// Leaked into statics because the closures Swift keeps have nowhere to store
/// them: a `ClosureCtx` carries one payload word, and both of these are values
/// several words wide. There is one of each for the process.
static FRAME: std::sync::OnceLock<(Vec<u8>, usize)> = std::sync::OnceLock::new();
static TRACK: std::sync::OnceLock<(Vec<u8>, usize)> = std::sync::OnceLock::new();

/// `() -> MoveKeyframe<Double>` — a generic result, so it goes through x8.
unsafe extern "C" fn emit_frame(out: *mut u8, _payload: *mut c_void) {
    let (bytes, meta) = FRAME.get().expect("keyframe built before the closure runs");
    unsafe { abi::copy_value(out, bytes.as_ptr(), *meta as *const c_void) };
}

/// `(Double) -> KeyframeTrack<…>` — likewise, and the value in x0 is not read.
unsafe extern "C" fn emit_track(out: *mut u8, _payload: *mut c_void) {
    let (bytes, meta) = TRACK.get().expect("track built before the closure runs");
    unsafe { abi::copy_value(out, bytes.as_ptr(), *meta as *const c_void) };
}

/// Build `KeyframeTrack<Double, Double, MoveKeyframe<Double>>` holding one
/// keyframe at `to`, and return it with its `Keyframes` conformance.
///
/// Every metadata here comes from a mangled name rather than a `…Ma` accessor.
/// `MoveKeyframe` constrains its parameter, so its accessor takes the witness
/// table as well — and calling it with one argument does not fail, it poisons
/// the metadata cache and the *next* type that mentions `MoveKeyframe` dies
/// instead, somewhere unrelated.
unsafe fn keyframe_track(to: f64) -> (*const c_void, *const c_void) {
    unsafe {
        let double = resolve::double_meta();
        let frame = abi::resolve_type_by_mangled_name(
            mangle::ty("MoveKeyframe")
                .of(vec![mangle::Type::Verbatim("Sd".into())])
                .mangle()
                .as_bytes(),
        );
        assert!(!frame.is_null(), "MoveKeyframe<Double> metadata");
        let frame_wt =
            abi::get_view_wt_for_proto(frame, resolve::keyframe_track_content_proto());
        assert!(!frame_wt.is_null(), "MoveKeyframe<Double>: KeyframeTrackContent");

        let mut at = to;
        let mut one = vec![0u8; abi::type_bytes(frame)];
        abi::call_out(
            resolve::move_keyframe_init(),
            abi::ints(&[&mut at as *mut f64 as u64, double as u64]),
            [0.0; 4],
            frame as u64,
            one.as_mut_ptr(),
        );
        let _ = FRAME.set((one, frame as usize));

        let track = abi::resolve_type_by_mangled_name(
            mangle::ty("KeyframeTrack")
                .of(vec![
                    mangle::Type::Verbatim("Sd".into()),
                    mangle::Type::Verbatim("Sd".into()),
                    mangle::ty("MoveKeyframe").of(vec![mangle::Type::Verbatim("Sd".into())]),
                ])
                .mangle()
                .as_bytes(),
        );
        assert!(!track.is_null(), "KeyframeTrack metadata");
        let track_wt = abi::get_view_wt_for_proto(track, resolve::keyframes_proto());
        assert!(!track_wt.is_null(), "KeyframeTrack: Keyframes");

        let ctx = Box::leak(Box::new(abi::ClosureCtx::new(emit_frame, core::ptr::null_mut())))
            as *mut abi::ClosureCtx;
        let mut bytes = vec![0u8; abi::type_bytes(track)];
        abi::call_spilled(
            resolve::keyframe_track_init(),
            &[
                abi::swift_closure_thunk as *const () as u64,
                ctx as u64,
                double as u64,
                frame as u64,
                frame_wt as u64,
            ],
            [0.0; 4],
            track as u64,
            bytes.as_mut_ptr(),
        );
        let _ = TRACK.set((bytes, track as usize));
        (track, track_wt)
    }
}

/// Apply `.keyframeAnimator(initialValue:repeating:content:keyframes:)`.
///
/// Three generic parameters beyond `Self`: the animated value, the content
/// view, and the keyframes. Nothing public conforms to `Keyframes` by itself —
/// the conformance belongs to `KeyframeTrack`, which is built here around a
/// single `MoveKeyframe`.
pub fn keyframe_animator(
    view: &ViewHandle,
    initial: f64,
    to: f64,
    repeating: bool,
    content: &ViewHandle,
) -> ViewHandle {
    unsafe {
        let (track, track_wt) = keyframe_track(to);
        let double = resolve::double_meta();
        // `Self` is the concrete receiver; `Content` is whatever the content
        // closure emits, and `view_words` emits an `AnyView`. They were the
        // same type only while every receiver was erased.
        let av = content.meta;
        let aw = content.wt;
        let subst = [view.meta, double, av, track, view.wt, aw, track_wt];
        let (meta, wt, size) = opaque_result_type(resolve::keyframe_animator_oret(), &subst);

        let keyframes = Box::leak(Box::new(abi::ClosureCtx::new(
            emit_track,
            core::ptr::null_mut(),
        ))) as *mut abi::ClosureCtx;

        let mut start = initial;
        let mut ints = vec![&mut start as *mut f64 as u64, u64::from(repeating)];
        ints.extend_from_slice(&view_words(content));
        ints.extend_from_slice(&[
            abi::swift_closure_thunk as *const () as u64,
            keyframes as u64,
        ]);
        ints.extend_from_slice(&[view.meta as u64, double as u64, av as u64, track as u64]);
        ints.extend_from_slice(&[view.wt as u64, aw as u64, track_wt as u64]);
        let r = abi::call_modifier_generic(resolve::keyframe_animator_fn(), view.value_ptr(), &ints, [0.0; 4], size);
        wrap_owned(r, meta, wt)
    }
}

// ── Reading the environment ─────────────────────────────────────────────────

/// A borrowed `SwiftUI.EnvironmentValues`, live for the body call that got it.
///
/// The pointer is SwiftUI's, valid only while the closure that received it is
/// running, which is why this borrows rather than owns.
#[derive(Clone, Copy)]
pub struct EnvironmentValues(*const c_void);

impl EnvironmentValues {
    /// Read a `Bool` property by its getter symbol.
    ///
    /// `EnvironmentValues` is resilient, so `self` travels by address in x20
    /// and the answer comes back in x0. Every `Bool` property on it has the
    /// same shape, so one function covers all of them.
    ///
    /// # Safety
    /// `getter` must name a `(EnvironmentValues) -> Bool` property getter.
    pub unsafe fn bool_at(self, getter: *const c_void) -> bool {
        unsafe { abi::call_regs(getter, abi::ints(&[]), [0.0; 4], self.0 as u64)[0] & 1 != 0 }
    }

    /// `\\.accessibilityVoiceOverEnabled`
    pub fn voice_over_enabled(self) -> bool {
        unsafe { self.bool_at(resolve::env_accessibility_voice_over()) }
    }

    /// `\\.accessibilitySwitchControlEnabled`
    pub fn switch_control_enabled(self) -> bool {
        unsafe { self.bool_at(resolve::env_accessibility_switch_control()) }
    }

    /// Read a key defined here — `env[myKey]`, through the key path.
    ///
    /// `swift_getAtKeyPath(sret Value, @in Root, KeyPath)`: the result is `sret`
    /// so it goes through x8 while the root is in x0. Whatever nothing above has
    /// written, this returns the key's `defaultValue` — which SwiftUI gets from
    /// the synthesised witness, so the default really is the caller's.
    ///
    /// The type comes from the key, so this cannot read a `String` key as an
    /// `Int`: the buffer is sized by `T`'s metadata and `+1`-owned on return,
    /// which is why it is destroyed after the copy out.
    pub fn value_for<T: super::KeyValue>(self, key: &super::CustomEnvKey<T>) -> T {
        unsafe {
            static GET: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
            let f = *GET.get_or_init(|| {
                libc::dlsym((-2isize) as *mut c_void, c"swift_getAtKeyPath".as_ptr()) as usize
            });
            assert!(f != 0, "swift_getAtKeyPath");
            let mut out = vec![0u8; abi::type_bytes(T::metadata())];
            core::arch::asm!("blr {f}", f = in(reg) f,
                in("x0") self.0,
                in("x1") key.key_path_for_test(),
                in("x8") out.as_mut_ptr(),
                lateout("x2") _, lateout("x3") _, lateout("x4") _, lateout("x5") _,
                lateout("x6") _, lateout("x7") _,
                lateout("x9") _, lateout("x10") _, lateout("x11") _, lateout("x12") _,
                lateout("x13") _, lateout("x14") _, lateout("x15") _, lateout("x16") _,
                lateout("x17") _, lateout("lr") _, lateout("x20") _, lateout("x21") _,
                clobber_abi("C"),
            );
            let value = T::read(out.as_ptr());
            abi::type_destroy(T::metadata(), out.as_mut_ptr());
            value
        }
    }
}

type EnvBuilder = Box<dyn Fn(EnvironmentValues) -> ViewHandle>;

/// The body SwiftUI calls: the environment arrives as an address, the result
/// goes back through the out pointer as an `AnyView`.
unsafe extern "C" fn emit_environment_view(out: *mut u8, env: i64, payload: *mut c_void) {
    unsafe {
        let build = &*(payload as *const EnvBuilder);
        let view = build(EnvironmentValues(env as *const c_void));
        (out as *mut u64).write(leak_retained(&view));
    }
}

/// A view whose content is a function of the environment.
///
/// This is what `@Environment` is for, without needing to be a view *type*.
/// A Swift view declares stored `Environment<V>` properties and SwiftUI finds
/// them by reflecting over the type's field descriptors, populates them, and
/// then calls `body` — machinery that only exists for types the compiler
/// emitted. `EnvironmentReader` takes the closure instead, so a view built out
/// of values can still depend on the environment:
///
/// ```ignore
/// environment_reader(|env| {
///     if env.voice_over_enabled() { button() } else { empty() }
/// })
/// ```
///
/// The closure is called during layout, every time the environment changes, so
/// it is leaked rather than borrowed from the frame that built it.
pub fn environment_reader(
    builder: impl Fn(EnvironmentValues) -> ViewHandle + 'static,
) -> ViewHandle {
    unsafe {
        let boxed: EnvBuilder = Box::new(builder);
        let payload = Box::into_raw(Box::new(boxed)) as *mut c_void;
        let ctx = Box::leak(Box::new(abi::IndexClosureCtx::new(emit_environment_view, payload)))
            as *mut abi::IndexClosureCtx;

        let ty = mangle::ty("EnvironmentReader").of(vec![mangle::ty("AnyView")]).mangle();
        let meta = abi::resolve_type_by_mangled_name(ty.as_bytes());
        assert!(!meta.is_null(), "EnvironmentReader<AnyView> metadata");

        // Through x8, not in registers. `EnvironmentReader<AnyView>` is two
        // words and loadable — but the *initialiser* is generic over `A`, and
        // from inside it `EnvironmentReader<A>` has unknown layout, so the
        // result is address-only however small it turns out to be.
        let mut value = vec![0u8; abi::type_bytes(meta)];
        abi::call_out(
            resolve::environment_reader_init(),
            abi::ints(&[abi::index_closure_thunk as *const c_void as u64, ctx as u64]),
            [0.0; 4],
            meta as u64,
            value.as_mut_ptr().cast(),
        );
        let wt = abi::get_view_wt(meta);
        assert!(!wt.is_null(), "EnvironmentReader !: View");
        ViewHandle::wrap(value.as_ptr() as *const c_void, meta, wt)
    }
}

#[cfg(test)]
mod geometry_tests {
    use super::*;

    /// The scroll-geometry reader agrees with the live layout.
    ///
    /// Same shape of check as the pinch readers': a buffer with a distinct
    /// value at each offset the metadata reports, and the reader has to return
    /// them in the right places. `EdgeInsets` is the one that would go unnoticed
    /// if it were wrong, because all four of its fields are plain `CGFloat` —
    /// so they get four different numbers.
    #[test]
    fn scroll_geometry_reader_matches_the_live_layout() {
        let &[offset, size, insets, container, visible] =
            scroll_geometry_offsets().expect("five stored fields");
        let bytes = unsafe { abi::type_bytes(abi::metadata0(resolve::scroll_geometry_ma())) };
        let mut buf = vec![0u8; bytes];
        let mut put = |at: usize, v: f64| buf[at..at + 8].copy_from_slice(&v.to_le_bytes());
        for (base, n) in [(offset, 2), (size, 2), (insets, 4), (container, 2), (visible, 4)] {
            for i in 0..n {
                put(base + i * 8, (base + i * 8) as f64);
            }
        }

        let g = unsafe { read_scroll_geometry(buf.as_ptr()) };
        let f = |o: usize| o as f64;
        assert_eq!(g.content_offset, (f(offset), f(offset + 8)));
        assert_eq!(g.content_size, (f(size), f(size + 8)));
        assert_eq!(
            g.content_insets,
            (f(insets), f(insets + 8), f(insets + 16), f(insets + 24)),
            "top, leading, bottom, trailing — in that order"
        );
        assert_eq!(g.container_size, (f(container), f(container + 8)));
        assert_eq!(
            g.visible_rect,
            (f(visible), f(visible + 8), f(visible + 16), f(visible + 24)),
            "CGRect is origin then size, so x, y, width, height"
        );
    }
}