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
//! Shapes.
//!
//! * Gradients

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

// ── Shapes ──

/// Wrap a shape value as a view. Shapes conform to `View` and fill themselves
/// with the current foreground style, so `foreground_style_color` acts as `.fill(_:)`.
pub(crate) unsafe fn shape_view(bytes: &[u8], mangled: &[u8]) -> ViewHandle {
    let meta = unsafe { abi::resolve_type_by_mangled_name(mangled) };
    assert!(!meta.is_null(), "shape metadata: {}", crate::diag::demangle_type(mangled));
    let wt = unsafe { abi::get_view_wt(meta) };
    assert!(!wt.is_null(), "{} !: View", crate::diag::demangle_type(mangled));
    unsafe { wrap_buf(bytes, meta, wt) }
}

/// `Rectangle()`
pub fn rectangle() -> ViewHandle {
    unsafe { shape_view(&[], swift_type!(SwiftUI.Rectangle).as_bytes()) }
}

/// `Circle()`
pub fn circle() -> ViewHandle {
    unsafe { shape_view(&[], swift_type!(SwiftUI.Circle).as_bytes()) }
}

/// `Ellipse()`
pub fn ellipse() -> ViewHandle {
    unsafe { shape_view(&[], swift_type!(SwiftUI.Ellipse).as_bytes()) }
}

/// `Capsule()` — `RoundedCornerStyle.circular` is case 0.
pub fn capsule() -> ViewHandle {
    unsafe { shape_view(&[0u8], swift_type!(SwiftUI.Capsule).as_bytes()) }
}

/// `RoundedRectangle(cornerRadius:style:)`.
///
/// The layout is a `CGSize` of corner radii followed by the corner style, so
/// the radius is written into both the width and height slots.
///
/// The style is not optional here the way it reads as optional in Swift. Source
/// that writes `RoundedRectangle(cornerRadius: 10)` gets `.continuous`, not
/// `.circular` — the two round the corners differently enough to disagree on a
/// couple of hundred pixels — so a binding that always wrote case 0 quietly
/// built the other shape. Callers say which one they mean.
pub fn rounded_rectangle_styled(radius: f64, continuous: bool) -> ViewHandle {
    let mut buf = [0u8; 17];
    buf[..8].copy_from_slice(&radius.to_le_bytes());
    buf[8..16].copy_from_slice(&radius.to_le_bytes());
    buf[16] = u8::from(continuous);
    unsafe { shape_view(&buf, swift_type!(SwiftUI.RoundedRectangle).as_bytes()) }
}

/// `RoundedRectangle(cornerRadius:)`, with the `.continuous` style Swift
/// source gets when it leaves the style out.
pub fn rounded_rectangle(radius: f64) -> ViewHandle {
    rounded_rectangle_styled(radius, true)
}

// ── Gradients ──

mangle::modifier_types! {
    /// `.background(_: LinearGradient)`
    /// `ModifiedContent<AnyView, _BackgroundStyleModifier<LinearGradient>>`
    pub(crate) LINEAR_GRADIENT_BG_T = ty("_BackgroundStyleModifier").of(vec![ty("LinearGradient")]);
    /// `.background(_: RadialGradient)`
    /// `ModifiedContent<AnyView, _BackgroundStyleModifier<RadialGradient>>`
    pub(crate) RADIAL_GRADIENT_BG_T = ty("_BackgroundStyleModifier").of(vec![ty("RadialGradient")]);
}


/// Build a Swift `Array<Color>` from raw `Color` references.
///
/// `Array._allocateUninitialized(_:)` hands back the array value together with a
/// pointer to its uninitialised buffer, which is the only practical way to build
/// a Swift array from outside Swift.
pub(crate) unsafe fn color_array(colors: &[u64]) -> u64 {
    let (array, buf): (u64, u64);
    unsafe {
        // `_allocateUninitializedArray<Element>(_ count:)` is what an array
        // literal compiles down to: x0 = count, x1 = Element.Type, returning
        // (Array, buffer) in x0/x1. The element metadata is a normal argument,
        // not the `self` register.
        core::arch::asm!("blr {f}", f = in(reg) resolve::array_alloc_uninit(),
            in("x0") colors.len() as u64,
            in("x1") resolve::color_meta(),
            lateout("x0") array, lateout("x1") buf,
            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"),
        );
        let dst = buf as *mut u64;
        for (i, c) in colors.iter().enumerate() {
            *dst.add(i) = *c;
        }
    }
    array
}

/// Build a `Gradient` from a list of colours.
pub(crate) unsafe fn gradient(colors: &[crate::Color]) -> u64 {
    let raw: Vec<u64> =
        colors.iter().map(|c| unsafe { color_value(c.r, c.g, c.b, c.a) }).collect();
    unsafe { gradient_of(&raw) }
}

/// Build a `Gradient` from `Color` values that are already built.
///
/// The components form cannot express `.yellow` or `.blue`: SwiftUI's named
/// colours are semantic and a literal triple is a visibly different colour —
/// 1371 of 1377 drawn pixels different, in the case that found this.
pub(crate) unsafe fn gradient_of(raw: &[u64]) -> u64 {
    let array = unsafe { color_array(raw) };
    let g: u64;
    unsafe {
        core::arch::asm!("blr {f}", f = in(reg) resolve::gradient_init(),
            in("x0") array,
            in("x20") resolve::gradient_meta(),
            lateout("x0") g,
            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"),
        );
    }
    g
}

/// `Color`'s metadata and `ShapeStyle` witness, for a call taking a style.
pub fn color_meta_for_style() -> *const c_void {
    resolve::color_meta()
}

/// See [`color_meta_for_style`].
pub fn color_shapestyle_wt_for_style() -> *const c_void {
    resolve::color_shapestyle_wt()
}

/// Which of the five hierarchical levels a style names.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Hierarchical {
    Primary,
    Secondary,
    Tertiary,
    Quaternary,
    Quinary,
}

/// `HierarchicalShapeStyle.primary` and friends, as a `ShapeStyle`.
///
/// `.primary` in a `ShapeStyle` position is *not* `Color.primary`: it is one of
/// these, four bytes wide, and the two render differently against a tinted
/// foreground. The shorthand that reaches them from `ShapeStyle` is inlinable;
/// these concrete statics are exported.
pub fn hierarchical_style(level: Hierarchical) -> (Vec<u8>, *const c_void, *const c_void) {
    unsafe {
        let getter = match level {
            Hierarchical::Primary => resolve::hierarchical_primary(),
            Hierarchical::Secondary => resolve::hierarchical_secondary(),
            Hierarchical::Tertiary => resolve::hierarchical_tertiary(),
            Hierarchical::Quaternary => resolve::hierarchical_quaternary(),
            Hierarchical::Quinary => resolve::hierarchical_quinary(),
        };
        let meta = abi::metadata0(resolve::hierarchical_ma());
        assert!(!meta.is_null(), "HierarchicalShapeStyle metadata");
        let r = abi::static_regs(getter, meta);
        let mut bytes = vec![0u8; abi::type_bytes(meta)];
        let n = bytes.len().min(8);
        bytes[..n].copy_from_slice(&r[0].to_le_bytes()[..n]);
        // Looked up rather than named: the witness table's own mangling
        // compresses `ShapeStyle` against the words in
        // `HierarchicalShapeStyle`, and guessing the substitution letters is
        // how this file has gone wrong before.
        let wt = abi::get_view_wt_for_proto(meta, resolve::shape_style_proto());
        assert!(!wt.is_null(), "HierarchicalShapeStyle !: ShapeStyle");
        (bytes, meta, wt)
    }
}

/// `.opacity(_:)` applied to a style that is already built.
///
/// `_OpacityShapeStyle<Base>` stores the base then the `Float`, so unlike the
/// `_ImplicitShapeStyle` case the base's bytes have to go in first.
pub fn opacity_of_style(
    base: &[u8],
    base_ty: mangle::Type,
    opacity: f64,
) -> (Vec<u8>, *const c_void, *const c_void) {
    unsafe {
        let ty = mangle::ty("_OpacityShapeStyle").of(vec![base_ty]).mangle();
        let meta = abi::resolve_type_by_mangled_name(ty.as_bytes());
        assert!(!meta.is_null(), "_OpacityShapeStyle metadata: {ty}");
        let wt = abi::get_view_wt_for_proto(meta, resolve::shape_style_proto());
        assert!(!wt.is_null(), "_OpacityShapeStyle !: ShapeStyle");
        let mut bytes = vec![0u8; abi::type_bytes(meta)];
        bytes[..base.len()].copy_from_slice(base);
        let at = base.len().next_multiple_of(4);
        bytes[at..at + 4].copy_from_slice(&(opacity as f32).to_le_bytes());
        (bytes, meta, wt)
    }
}

/// `ShapeStyle.opacity(_:)` — the current foreground style, faded.
///
/// `.opacity(0.5)` where a `ShapeStyle` is expected is a static on a protocol
/// extension, `@inlinable`, with no symbol. Its body builds one struct:
///
/// ```text
/// %6 = struct $_ImplicitShapeStyle ()
/// %7 = struct $_OpacityShapeStyle<_ImplicitShapeStyle> (%6, %5)
/// ```
///
/// `_ImplicitShapeStyle` has no stored properties, so the whole value is the
/// `Float` — which means it can be built here without calling anything.
pub fn implicit_opacity_style(opacity: f64) -> (Vec<u8>, *const c_void, *const c_void) {
    unsafe {
        let ty = mangle::ty("_OpacityShapeStyle")
            .of(vec![mangle::ty("_ImplicitShapeStyle")])
            .mangle();
        let meta = abi::resolve_type_by_mangled_name(ty.as_bytes());
        assert!(!meta.is_null(), "_OpacityShapeStyle<_ImplicitShapeStyle> metadata");
        let wt = abi::get_view_wt_for_proto(meta, resolve::shape_style_proto());
        assert!(!wt.is_null(), "_OpacityShapeStyle !: ShapeStyle");
        let mut bytes = vec![0u8; abi::type_bytes(meta)];
        bytes[..4].copy_from_slice(&(opacity as f32).to_le_bytes());
        (bytes, meta, wt)
    }
}

/// A `ShadowStyle` — `.drop(...)` or `.inner(...)`.
///
/// Both are exported statics: a `Color`, three `CGFloat`s and the metatype in,
/// the style out through x8. Only the *shorthand* that drops the receiver is
/// inlinable, and only the default arguments live in generator thunks — which
/// is why a search for what the SIL references reports these as missing when
/// they are not.
///
/// `color` defaults to `Color(.sRGBLinear, white: 0, opacity: _)` in Swift —
/// and the two are *not* the same default: a drop shadow gets 0.33 and an
/// inner one 0.55. Pass `None` to take whichever applies.
pub fn shadow_style(
    drop: bool,
    color: Option<u64>,
    radius: f64,
    x: f64,
    y: f64,
) -> Vec<u8> {
    unsafe {
        let meta = abi::metadata0(resolve::shadow_style_ma());
        assert!(!meta.is_null(), "ShadowStyle metadata");
        let colour = color.unwrap_or_else(|| default_shadow_colour(if drop { 0.33 } else { 0.55 }));
        let mut out = vec![0u8; abi::type_bytes(meta)];
        let f = if drop { resolve::shadow_style_drop() } else { resolve::shadow_style_inner() };
        core::arch::asm!("blr {f}", f = in(reg) f,
            in("x0") colour,
            in("d0") radius, in("d1") x, in("d2") y,
            in("x8") out.as_mut_ptr(),
            in("x20") meta,
            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"),
        );
        out
    }
}

/// `Color(.sRGBLinear, white: 0, opacity: _)` — Swift's default shadow colour.
///
/// `RGBColorSpace` is a frozen enum passed by address; `.sRGBLinear` is case 1.
fn default_shadow_colour(opacity: f64) -> u64 {
    unsafe {
        let mut space: u8 = 1;
        let out: u64;
        core::arch::asm!("blr {f}", f = in(reg) resolve::color_white_init(),
            in("x0") &mut space as *mut u8,
            in("d0") 0.0f64, in("d1") opacity,
            in("x20") resolve::color_meta(),
            lateout("x0") out,
            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
    }
}

/// `.shadow(_:)` applied to the *implicit* foreground style.
///
/// `_ShadowShapeStyle<_ImplicitShapeStyle>` again stores an empty base and the
/// argument, so the whole value is the `ShadowStyle`.
pub fn implicit_shadow_style(shadow: &[u8]) -> (Vec<u8>, *const c_void, *const c_void) {
    unsafe {
        let ty = mangle::ty("_ShadowShapeStyle")
            .of(vec![mangle::ty("_ImplicitShapeStyle")])
            .mangle();
        let meta = abi::resolve_type_by_mangled_name(ty.as_bytes());
        assert!(!meta.is_null(), "_ShadowShapeStyle<_ImplicitShapeStyle> metadata");
        let wt = abi::get_view_wt_for_proto(meta, resolve::shape_style_proto());
        assert!(!wt.is_null(), "_ShadowShapeStyle !: ShapeStyle");
        let mut bytes = vec![0u8; abi::type_bytes(meta)];
        let n = shadow.len().min(bytes.len());
        bytes[..n].copy_from_slice(&shadow[..n]);
        (bytes, meta, wt)
    }
}

/// `Color.shadow(_:)` — the generic `ShapeStyle.shadow`, with `Self == Color`.
pub fn color_shadow_style(color: u64, shadow: &[u8]) -> (Vec<u8>, *const c_void, *const c_void) {
    unsafe {
        let subst = [resolve::color_meta(), resolve::color_shapestyle_wt()];
        let (meta, _, size) =
            super::opaque_result_type(resolve::shape_style_shadow_oret(), &subst);
        let wt = abi::get_view_wt_for_proto(meta, resolve::shape_style_proto());
        assert!(!wt.is_null(), "shadowed style !: ShapeStyle");

        let mut out = vec![0u8; size];
        let mut arg = shadow.to_vec();
        let mut receiver = color;
        core::arch::asm!("blr {f}", f = in(reg) resolve::shape_style_shadow_fn(),
            in("x0") arg.as_mut_ptr(),
            in("x1") subst[0], in("x2") subst[1],
            in("x8") out.as_mut_ptr(),
            in("x20") &mut receiver as *mut u64,
            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, meta, wt)
    }
}

/// `ShapeStyle.blendMode(_:)` — the current foreground style, blended.
///
/// The same shape as [`implicit_opacity_style`]: an inlinable static whose body
/// stores an empty `_ImplicitShapeStyle` and the mode into a
/// `_BlendModeShapeStyle<_ImplicitShapeStyle>`. `BlendMode` is frozen, so the
/// case number is the whole of it.
pub fn implicit_blend_mode_style(mode: u8) -> (Vec<u8>, *const c_void, *const c_void) {
    unsafe {
        let ty = mangle::ty("_BlendModeShapeStyle")
            .of(vec![mangle::ty("_ImplicitShapeStyle")])
            .mangle();
        let meta = abi::resolve_type_by_mangled_name(ty.as_bytes());
        assert!(!meta.is_null(), "_BlendModeShapeStyle<_ImplicitShapeStyle> metadata");
        let wt = abi::get_view_wt_for_proto(meta, resolve::shape_style_proto());
        assert!(!wt.is_null(), "_BlendModeShapeStyle !: ShapeStyle");
        let mut bytes = vec![0u8; abi::type_bytes(meta)];
        bytes[0] = mode;
        (bytes, meta, wt)
    }
}

swift_statics! {
    /// `SwiftUI.Gradient.ColorSpace` — which space a gradient interpolates in.
    ///
    /// `Device` walks the colour components as stored, which is what most
    /// systems do and what makes a red-to-green ramp pass through a muddy
    /// brown; `Perceptual` interpolates so that equal steps look equal, which
    /// is Swift's default wherever this is a defaulted argument.
    pub enum GradientColorSpace {
        Device = c"$s7SwiftUI8GradientV10ColorSpaceV6deviceAEvgZ",
        Perceptual = c"$s7SwiftUI8GradientV10ColorSpaceV10perceptualAEvgZ",
    }
}

/// `Gradient.colorSpace(_:)` — the gradient interpolated in another space.
///
/// Returns an `AnyGradient`, which is the `ShapeStyle` [`Shape::fill_style`]
/// wants. `Gradient.ColorSpace` is resilient, so `.perceptual` arrives through
/// x8 and is then handed over by address, with the gradient itself in x1.
pub fn gradient_color_space_perceptual(
    colors: &[u64],
) -> (Vec<u8>, *const c_void, *const c_void) {
    gradient_color_space(colors, GradientColorSpace::Perceptual)
}

/// The same, in whichever space is named.
pub fn gradient_color_space(
    colors: &[u64],
    space: GradientColorSpace,
) -> (Vec<u8>, *const c_void, *const c_void) {
    unsafe {
        let g = gradient_of(colors);
        let space_meta = abi::metadata0(resolve::gradient_color_space_ma());
        assert!(!space_meta.is_null(), "Gradient.ColorSpace metadata");
        let mut space = super::static_getter_indirect(
            space.resolved(),
            space_meta,
            abi::type_bytes(space_meta),
        );
        let out: u64;
        core::arch::asm!("blr {f}", f = in(reg) resolve::gradient_color_space_fn(),
            in("x0") space.as_mut_ptr(),
            in("x1") g,
            lateout("x0") out,
            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"),
        );
        (out.to_le_bytes().to_vec(), resolve::any_gradient_meta(), resolve::any_gradient_wt())
    }
}

/// Build a `LinearGradient` value, with its metadata and `ShapeStyle` witness.
///
/// What [`Shape::fill_style`] wants: `.fill(.linearGradient(...))` is the same
/// call as `.fill(Color.red)` with a different style, so the style is passed as
/// bytes rather than as one of a fixed set.
pub fn linear_gradient_style(
    colors: &[crate::Color],
    start: (f64, f64),
    end: (f64, f64),
) -> (Vec<u8>, *const c_void, *const c_void) {
    let raw: Vec<u64> = colors.iter().map(|c| super::color_value_of(*c)).collect();
    linear_gradient_style_of(&raw, start, end)
}

/// `AngularGradient(gradient:center:angle:)` — a sweep around a point.
///
/// The angle is where the sweep starts, in degrees; SwiftUI's default is zero,
/// which is what Swift's own defaulted argument passes.
pub fn angular_gradient_style(
    colors: &[crate::Color],
    center: (f64, f64),
    start_degrees: f64,
) -> (Vec<u8>, *const c_void, *const c_void) {
    let raw: Vec<u64> = colors.iter().map(|c| super::color_value_of(*c)).collect();
    unsafe {
        let g = gradient_of(&raw);
        let meta = crate::type_by_name!(swift_type!(SwiftUI.AngularGradient).as_bytes());
        assert!(!meta.is_null(), "AngularGradient metadata");
        let mut value = vec![0u8; abi::type_bytes(meta)];
        // `(sret, gradient, cx, cy, angle)` — the `Angle` is one `Double` of
        // radians, so degrees are converted here as they are for `rotate`.
        core::arch::asm!("blr {f}", f = in(reg) resolve::angular_gradient_init(),
            in("x0") g,
            in("d0") center.0, in("d1") center.1,
            in("d2") start_degrees * core::f64::consts::PI / 180.0,
            in("x8") value.as_mut_ptr(),
            in("x20") meta,
            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"),
        );
        (value, meta, resolve::angular_gradient_wt())
    }
}

/// `EllipticalGradient(colors:center:startRadiusFraction:endRadiusFraction:)`.
///
/// Takes the colours directly rather than a built `Gradient` — a different
/// initialiser shape from the three gradients beside it, so there is no
/// `gradient_of` call here.
pub fn elliptical_gradient_style(
    colors: &[crate::Color],
    center: (f64, f64),
    start_fraction: f64,
    end_fraction: f64,
) -> (Vec<u8>, *const c_void, *const c_void) {
    let raw: Vec<u64> = colors.iter().map(|c| super::color_value_of(*c)).collect();
    unsafe {
        let array = color_array(&raw);
        let meta = crate::type_by_name!(swift_type!(SwiftUI.EllipticalGradient).as_bytes());
        assert!(!meta.is_null(), "EllipticalGradient metadata");
        let mut value = vec![0u8; abi::type_bytes(meta)];
        core::arch::asm!("blr {f}", f = in(reg) resolve::elliptical_gradient_init(),
            in("x0") array,
            in("d0") center.0, in("d1") center.1,
            in("d2") start_fraction, in("d3") end_fraction,
            in("x8") value.as_mut_ptr(),
            in("x20") meta,
            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"),
        );
        (value, meta, resolve::elliptical_gradient_wt())
    }
}

/// As [`linear_gradient_style`], from `Color` values that are already built.
pub fn linear_gradient_style_of(
    colors: &[u64],
    start: (f64, f64),
    end: (f64, f64),
) -> (Vec<u8>, *const c_void, *const c_void) {
    unsafe {
        let g = gradient_of(colors);
        let meta = crate::type_by_name!(swift_type!(SwiftUI.LinearGradient).as_bytes());
        assert!(!meta.is_null(), "LinearGradient metadata");
        let mut value = vec![0u8; abi::type_bytes(meta)];
        core::arch::asm!("blr {f}", f = in(reg) resolve::linear_gradient_init(),
            in("x0") g,
            in("d0") start.0, in("d1") start.1, in("d2") end.0, in("d3") end.1,
            in("x8") value.as_mut_ptr(),
            in("x20") meta,
            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"),
        );
        (value, meta, resolve::linear_gradient_wt())
    }
}

/// Apply `.background(LinearGradient(colors:startPoint:endPoint:))`.
pub fn background_linear_gradient(
    view: &ViewHandle,
    colors: &[crate::Color],
    start: (f64, f64),
    end: (f64, f64),
) -> ViewHandle {
    unsafe {
        let g = gradient(colors);
        let meta = crate::type_by_name!(swift_type!(SwiftUI.LinearGradient).as_bytes());
        assert!(!meta.is_null(), "LinearGradient metadata");
        let mut value = vec![0u8; abi::type_bytes(meta)];
        // init(gradient:startPoint:endPoint:) — x0 = Gradient, UnitPoints in d0-d3
        core::arch::asm!("blr {f}", f = in(reg) resolve::linear_gradient_init(),
            in("x0") g,
            in("d0") start.0, in("d1") start.1, in("d2") end.0, in("d3") end.1,
            in("x8") value.as_mut_ptr(),
            in("x20") meta,
            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"),
        );
        background_style(
            view,
            value.as_mut_ptr(),
            meta,
            resolve::linear_gradient_wt(),
            &LINEAR_GRADIENT_BG_T,
        )
    }
}

/// Apply `.background(RadialGradient(colors:center:startRadius:endRadius:))`.
pub fn background_radial_gradient(
    view: &ViewHandle,
    colors: &[crate::Color],
    center: (f64, f64),
    start_radius: f64,
    end_radius: f64,
) -> ViewHandle {
    unsafe {
        let g = gradient(colors);
        let meta = crate::type_by_name!(swift_type!(SwiftUI.RadialGradient).as_bytes());
        assert!(!meta.is_null(), "RadialGradient metadata");
        let mut value = vec![0u8; abi::type_bytes(meta)];
        core::arch::asm!("blr {f}", f = in(reg) resolve::radial_gradient_init(),
            in("x0") g,
            in("d0") center.0, in("d1") center.1, in("d2") start_radius, in("d3") end_radius,
            in("x8") value.as_mut_ptr(),
            in("x20") meta,
            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"),
        );
        background_style(
            view,
            value.as_mut_ptr(),
            meta,
            resolve::radial_gradient_wt(),
            &RADIAL_GRADIENT_BG_T,
        )
    }
}

// ── Shapes kept as shapes ───────────────────────────────────────────────────

/// A shape value, not yet erased to a view.
///
/// [`circle`] and its neighbours hand back a `ViewHandle`, because a shape
/// conforms to `View` and that is all most callers want. `Shape.fill(_:style:)`
/// and `.stroke(_:lineWidth:)` are not view modifiers, though — they are
/// extension methods on `Shape` whose receiver is `@in_guaranteed Self` with
/// `Self: Shape`, and an `AnyView` satisfies neither. So reaching them needs
/// the value, its metadata and its `Shape` witness table kept together, which
/// is what this is.
///
/// The bytes are the shape's own storage: empty for `Circle`, `Rectangle` and
/// `Ellipse`, which have no stored properties at all.
pub struct Shape {
    bytes: Vec<u8>,
    meta: *const c_void,
    wt: *const c_void,
    /// What this shape *is*, so a wrapping shape can name itself.
    ///
    /// `.offset(x:y:)` on a `Circle` gives an `OffsetShape<Circle>` — still a
    /// `Shape`, and still fillable — so each transform has to spell a type one
    /// level deeper than the last. Keeping the `mangle::Type` rather than the
    /// finished string is what makes that possible: the mangling of
    /// `OffsetShape<Circle>` is not the mangling of `Circle` with something
    /// glued on, because the substitution table depends on the whole.
    ty: mangle::Type,
}

impl Shape {
    /// A shape whose metadata and conformance are already in hand.
    ///
    /// For [`crate::views::custom_shape_value`], whose type was *minted at run
    /// time*: there is no name for it that `swift_getTypeByMangledName` can
    /// resolve, because a synthesised nominal descriptor is in no image's
    /// metadata section. The `ty` is carried anyway so the error message from a
    /// method that composes names says which shape it was — those methods cannot
    /// work for a synthesised type, and failing with its name beats failing with
    /// a null.
    ///
    /// # Safety
    /// `bytes` must hold a value of `meta`'s type, and `wt` must be that type's
    /// `Shape` conformance.
    pub(crate) unsafe fn of_metadata(
        bytes: Vec<u8>,
        meta: *const c_void,
        wt: *const c_void,
        ty: mangle::Type,
    ) -> Self {
        Self { bytes, meta, wt, ty }
    }

    unsafe fn of(bytes: Vec<u8>, ty: mangle::Type) -> Self {
        unsafe {
            let mangled = ty.mangle();
            let meta = abi::resolve_type_by_mangled_name(mangled.as_bytes());
            assert!(!meta.is_null(), "shape metadata: {}", mangle::demangle(&mangled));
            let wt = abi::get_view_wt_for_proto(meta, resolve::shape_proto());
            assert!(!wt.is_null(), "{} !: Shape", mangle::demangle(&mangled));
            Self { bytes, meta, wt, ty }
        }
    }

    /// `Circle()`
    pub fn circle() -> Self {
        unsafe { Self::empty(mangle::ty("Circle"), resolve::circle_init()) }
    }

    /// `Rectangle()`
    pub fn rectangle() -> Self {
        unsafe { Self::empty(mangle::ty("Rectangle"), resolve::rectangle_init()) }
    }

    /// `Ellipse()`
    pub fn ellipse() -> Self {
        unsafe { Self::empty(mangle::ty("Ellipse"), resolve::ellipse_init()) }
    }

    /// A shape with no stored properties, built by calling its initialiser.
    ///
    /// These three used to be an empty `Vec`, which is right for as long as
    /// they stay empty and says nothing if they stop. Calling the initialiser
    /// is what source does — the IR has one `Rectangle()` call per rectangle —
    /// and it writes whatever the type actually holds.
    ///
    /// # Safety
    /// `init` must be `ty`'s zero-argument initialiser.
    unsafe fn empty(ty: mangle::Type, init: *const c_void) -> Self {
        unsafe {
            let mut me = Self::of(Vec::new(), ty);
            let size = abi::type_bytes(me.meta);
            let mut bytes = vec![0u8; size.max(1)];
            core::arch::asm!("blr {f}", f = in(reg) init,
                in("x8") bytes.as_mut_ptr(),
                in("x20") me.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"),
            );
            bytes.truncate(size);
            me.bytes = bytes;
            me
        }
    }

    /// `Capsule()` — one byte of `RoundedCornerStyle`.
    ///
    /// Case **1**, `.continuous`, which is what `Capsule()` with no argument
    /// means. This said case 0 and called it `.circular` until a listing needed
    /// a capsule's corner style to match; nothing had compared one before, and
    /// [`Self::rounded_rectangle`] next door had the numbering right all along.
    pub fn capsule() -> Self {
        unsafe { Self::of(vec![1u8], mangle::ty("Capsule")) }
    }

    /// `RoundedRectangle(cornerRadius:style:)` — a `CGSize` then the style.
    ///
    /// `style` is `RoundedCornerStyle`: `.circular` is case 0 and
    /// `.continuous` is case 1. The one-argument spelling in Swift source does
    /// *not* mean circular — the declared default is `.continuous`, and the two
    /// differ by about two hundred pixels around the corners of a 200x50 box.
    pub fn rounded_rectangle(radius: f64, continuous: bool) -> Self {
        let mut bytes = Vec::with_capacity(24);
        bytes.extend_from_slice(&radius.to_le_bytes());
        bytes.extend_from_slice(&radius.to_le_bytes());
        bytes.push(u8::from(continuous));
        unsafe { Self::of(bytes, mangle::ty("RoundedRectangle")) }
    }

    /// The shape on its own, as a view.
    /// The shape's own type, for spelling a type it appears inside.
    ///
    /// `fill_then_stroke` names its result `StrokeShapeView<Shape, Color,
    /// _ShapeView<Shape, Color>>`, which cannot be written without knowing what
    /// the shape is — and after `.inset` or `.rotation` that is no longer the
    /// shape it started as.
    pub(crate) fn ty(&self) -> &mangle::Type {
        &self.ty
    }

    pub fn view(&self) -> ViewHandle {
        unsafe {
            let wt = abi::get_view_wt(self.meta);
            ViewHandle::wrap(self.bytes.as_ptr() as _, self.meta, wt)
        }
    }

    /// A `Path`, built by the four mutating methods below.
    ///
    /// `Path` is 33 bytes — a reference plus a discriminator — so it is neither
    /// one word nor a neat multiple of one, and every method takes it as
    /// `inout` through x20 while the points travel in d0 onwards.
    pub fn path() -> PathBuilder {
        let mut bytes = vec![0u8; 40]; // stride, not size: the callee may write padding
        unsafe {
            core::arch::asm!("blr {f}", f = in(reg) resolve::path_init(),
                in("x8") bytes.as_mut_ptr(),
                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("x20") _, lateout("x21") _,
                clobber_abi("C"),
            );
        }
        PathBuilder { bytes }
    }

    /// The shape's own name, when it is a plain nominal type.
    fn base_name(&self) -> Option<&'static str> {
        match &self.ty {
            mangle::Type::Nominal { path, .. } => path.last().copied(),
            _ => None,
        }
    }

    /// `.inset(by:)` — the shape drawn inside its own bounds.
    ///
    /// `inset(by:)` is an `InsettableShape` *requirement*, so it is exported
    /// once per conforming type rather than once on the protocol: there is a
    /// `Circle.inset`, a `Rectangle.inset` and so on, and no
    /// `InsettableShape.inset` at all. The result is `some InsettableShape`,
    /// whose first conformance is `InsettableShape` — so the `Shape` witness
    /// comes from the concrete metadata, as with `stroke(lineWidth:)`.
    pub fn inset(&self, amount: f64) -> Self {
        let name = self.base_name().expect("inset needs a plain shape");
        let symbol: &core::ffi::CStr = match name {
            "Circle" => c"$s7SwiftUI6CircleV5inset2byQr12CoreGraphics7CGFloatV_tF",
            "Capsule" => c"$s7SwiftUI7CapsuleV5inset2byQr12CoreGraphics7CGFloatV_tF",
            "Ellipse" => c"$s7SwiftUI7EllipseV5inset2byQr12CoreGraphics7CGFloatV_tF",
            "Rectangle" => c"$s7SwiftUI9RectangleV5inset2byQr12CoreGraphics7CGFloatV_tF",
            "RoundedRectangle" => c"$s7SwiftUI16RoundedRectangleV5inset2byQr12CoreGraphics7CGFloatV_tF",
            other => panic!("no exported inset(by:) for {other}"),
        };
        let oret: &core::ffi::CStr = match name {
            "Circle" => c"$s7SwiftUI6CircleV5inset2byQr12CoreGraphics7CGFloatV_tFQOMQ",
            "Capsule" => c"$s7SwiftUI7CapsuleV5inset2byQr12CoreGraphics7CGFloatV_tFQOMQ",
            "Ellipse" => c"$s7SwiftUI7EllipseV5inset2byQr12CoreGraphics7CGFloatV_tFQOMQ",
            "RoundedRectangle" => c"$s7SwiftUI16RoundedRectangleV5inset2byQr12CoreGraphics7CGFloatV_tFQOMQ",
            _ => c"$s7SwiftUI9RectangleV5inset2byQr12CoreGraphics7CGFloatV_tFQOMQ",
        };
        unsafe {
            let (meta, _, size) = super::opaque_result_type(resolve::sym(oret), &[]);
            let wt = abi::get_view_wt_for_proto(meta, resolve::shape_proto());
            assert!(!wt.is_null(), "inset shape !: Shape");
            let mut bytes = vec![0u8; size.max(1)];
            let mut receiver = self.receiver();
            core::arch::asm!("blr {f}", f = in(reg) resolve::sym(symbol),
                in("d0") amount,
                in("x8") bytes.as_mut_ptr(),
                in("x20") receiver.as_mut_ptr(),
                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"),
            );
            // `inset(by:)` returns `some InsettableShape`, so the call site has
            // no name — but the type behind it is always `<Shape>._Inset`, and
            // keeping the shape this started as is what made `fill_then_stroke`
            // spell `StrokeShapeView<Circle, …>` for an inset circle: a type
            // that exists, is the wrong one, and is laid out differently, which
            // is what its field-offset assertion was catching.
            //
            // Spelled as a nested path rather than pasted in as a verbatim
            // name: this crate's mangler numbers its own substitutions, and a
            // full `7SwiftUI6CircleV6_InsetV` dropped into the middle shifts
            // every `AA` after it, so the composed name resolves to nothing.
            //
            // The runtime knows the real name, so the guess is checked against
            // it rather than trusted.
            let ty = mangle::Type::Nominal {
                module: "SwiftUI",
                path: vec![name, "_Inset"],
                kind: mangle::Kind::Struct,
            };
            debug_assert_eq!(
                abi::mangled_type_name(meta).as_deref(),
                Some(ty.mangle().as_bytes()),
                "{name}.inset(by:) does not return {name}._Inset",
            );
            Self { bytes, meta, wt, ty }
        }
    }

    /// `.offset(x:y:)` — an `OffsetShape` around this one.
    ///
    /// A concrete wrapper, not an opaque return, so there is no substitution
    /// list to build: the result's size comes from its own metadata and the
    /// call writes it through x8.
    pub fn offset(&self, x: f64, y: f64) -> Self {
        let ty = mangle::ty("OffsetShape").of(vec![self.ty.clone()]);
        unsafe { self.wrapped(resolve::shape_offset_fn(), ty, [x, y, 0.0, 0.0]) }
    }

    /// `.rotation(_:anchor:)` — a `RotatedShape` around this one.
    ///
    /// `Angle` stores radians, and `.center` is `UnitPoint(0.5, 0.5)`.
    pub fn rotation(&self, degrees: f64) -> Self {
        let ty = mangle::ty("RotatedShape").of(vec![self.ty.clone()]);
        let radians = degrees * std::f64::consts::PI / 180.0;
        unsafe { self.wrapped(resolve::shape_rotation_fn(), ty, [radians, 0.5, 0.5, 0.0]) }
    }

    /// Call a `Shape` extension method that returns a concrete wrapper.
    ///
    /// The floats go in d0 onwards, the receiver is `@in_guaranteed` in x20,
    /// and the two generic words — `Self` and its `Shape` witness — follow in
    /// x0 and x1 because no formal argument occupies an integer register.
    unsafe fn wrapped(&self, func: *const c_void, ty: mangle::Type, floats: [f64; 4]) -> Self {
        unsafe {
            let mangled = ty.mangle();
            let meta = abi::resolve_type_by_mangled_name(mangled.as_bytes());
            assert!(!meta.is_null(), "shape metadata: {}", mangle::demangle(&mangled));
            let wt = abi::get_view_wt_for_proto(meta, resolve::shape_proto());
            assert!(!wt.is_null(), "{} !: Shape", mangle::demangle(&mangled));

            let mut bytes = vec![0u8; abi::type_bytes(meta).max(1)];
            let mut receiver = self.receiver();
            core::arch::asm!("blr {f}", f = in(reg) func,
                in("x0") self.meta,
                in("x1") self.wt,
                in("d0") floats[0], in("d1") floats[1],
                in("d2") floats[2], in("d3") floats[3],
                in("x8") bytes.as_mut_ptr(),
                in("x20") receiver.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"),
            );
            Self { bytes, meta, wt, ty }
        }
    }

    /// `.fill(_:style:)` with any `ShapeStyle` — its value, metadata and
    /// witness table.
    /// # Safety
    /// `style` must hold an initialised value of the type `meta` describes, and
    /// `wt` must be that type's `ShapeStyle` conformance.
    pub unsafe fn fill_style(&self, style: &[u8], meta: *const c_void, wt: *const c_void) -> ViewHandle {
        unsafe { self.filled(style, meta, wt) }
    }

    /// `.fill(_:style:)`, by building the `_ShapeView` it reduces to.
    ///
    /// `Shape.fill` has two overloads — one returning `some View`, one
    /// returning `_ShapeView<Self, S>` — and source picks the second. Neither
    /// helps directly: the concrete one is `@inlinable` and not exported, and
    /// the opaque one needs its result type resolved through a descriptor.
    /// What the inlined body does is call `_ShapeView.init`, which *is*
    /// exported, so that is what this calls.
    ///
    /// The `style:` default stays a constant here. SwiftUI's own generator for
    /// it — `…FfA0_` in the IR — is emitted into the client rather than
    /// exported, so there is nothing to call: `FillStyle()` is
    /// `(eoFill: false, antialiased: true)`, two bytes, and `0x0100` is them.
    ///
    /// # Safety
    /// `style` must be a live value of `meta` conforming through `wt`.
    unsafe fn filled(
        &self,
        style: &[u8],
        style_meta: *const c_void,
        style_wt: *const c_void,
    ) -> ViewHandle {
        unsafe {
            let meta = abi::generic_metadata_from_descriptor(
                resolve::shape_view_desc(),
                &[self.meta, style_meta, self.wt, style_wt],
            );
            assert!(!meta.is_null(), "_ShapeView metadata");
            let wt = abi::get_view_wt(meta);
            assert!(!wt.is_null(), "_ShapeView !: View");

            let mut arg = style.to_vec();
            arg.resize(abi::type_bytes(style_meta).max(style.len()).max(1), 0);
            let mut receiver = self.receiver();
            let mut result = vec![0u8; abi::type_bytes(meta)];
            // `(sret, @in shape, @in style, i16 fillStyle, Self.Type, S.Type,
            //   Self: Shape WT, S: ShapeStyle WT)` — an initialiser, so the
            // shape is an ordinary argument rather than `self` in x20.
            core::arch::asm!("blr {f}", f = in(reg) resolve::shape_view_init(),
                in("x0") receiver.as_mut_ptr(),
                in("x1") arg.as_mut_ptr(),
                in("x2") FILL_STYLE_DEFAULT,
                in("x3") self.meta,
                in("x4") style_meta,
                in("x5") self.wt,
                in("x6") style_wt,
                in("x8") result.as_mut_ptr(),
                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"),
            );
            wrap_owned(result, meta, wt)
        }
    }

    /// `.fill(_:)`'s value as raw bytes plus its type, for composing into a
    /// larger one rather than erasing it to a view.
    ///
    /// `ShapeView.stroke(_:lineWidth:)` needs this: it is
    /// `@_alwaysEmitIntoClient`, and what it builds is a `StrokeShapeView`
    /// holding *two* filled shape views — the stroke in front, the original fill
    /// behind it as a background — so both have to survive as values.
    pub(crate) fn fill_parts(
        &self,
        style: &[u8],
        meta: *const c_void,
        wt: *const c_void,
    ) -> (Vec<u8>, *const c_void) {
        unsafe {
            let subst = [self.meta, meta, self.wt, wt];
            let (ty, _, size) = super::opaque_result_type(resolve::shape_fill_oret(), &subst);
            let mut result = vec![0u8; size];
            let mut arg = style.to_vec();
            arg.resize(abi::type_bytes(meta).max(style.len()).max(1), 0);
            let mut receiver = self.receiver();
            core::arch::asm!("blr {f}", f = in(reg) resolve::shape_fill_fn(),
                in("x0") arg.as_mut_ptr(),
                in("x1") FILL_STYLE_DEFAULT as *const c_void,
                in("x2") subst[0], in("x3") subst[1], in("x4") subst[2], in("x5") subst[3],
                in("d0") 0.0f64,
                in("x8") result.as_mut_ptr(),
                in("x20") receiver.as_mut_ptr(),
                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"),
            );
            (result, ty)
        }
    }

    /// `.stroke(_:lineWidth:)` with any `ShapeStyle`.
    /// # Safety
    /// `style` must hold an initialised value of the type `meta` describes, and
    /// `wt` must be that type's `ShapeStyle` conformance.
    pub unsafe fn stroke_style(
        &self,
        style: &[u8],
        meta: *const c_void,
        wt: *const c_void,
        line_width: f64,
    ) -> ViewHandle {
        unsafe {
            let inner = self.styled(
                resolve::shape_stroke_fn(),
                resolve::shape_stroke_oret(),
                style,
                meta,
                wt,
                false,
                line_width,
            );
            // Every stroke, not just the colour-taking one: Swift's
            // `.stroke(_:lineWidth:)` returns a `StrokeShapeView` whatever the
            // style is.
            self.as_stroke_shape_view(inner, meta, wt)
        }
    }

    /// `.fill(_:style:)` with a `Color`.
    pub fn fill(&self, color: u64) -> ViewHandle {
        let bytes = color.to_le_bytes();
        // SAFETY: a `Color` word with `Color`'s metadata and conformance.
        unsafe { self.fill_style(&bytes, resolve::color_meta(), resolve::color_shapestyle_wt()) }
    }

    /// `.stroke(lineWidth:)`, kept as a `Shape` rather than erased to a view.
    ///
    /// What `overlay(_:in:)` wants: its `in:` argument is a `Shape`, and a
    /// stroked shape still is one.
    pub fn stroked(&self, line_width: f64) -> Self {
        unsafe {
            let subst = [self.meta, self.wt];
            let (meta, _, size) =
                super::opaque_result_type(resolve::shape_stroke_plain_oret(), &subst);
            let wt = abi::get_view_wt_for_proto(meta, resolve::shape_proto());
            assert!(!wt.is_null(), "stroked shape !: Shape");
            let mut bytes = vec![0u8; size.max(1)];
            let mut receiver = self.receiver();
            core::arch::asm!("blr {f}", f = in(reg) resolve::shape_stroke_plain_fn(),
                in("x0") subst[0], in("x1") subst[1],
                in("d0") line_width,
                in("x8") bytes.as_mut_ptr(),
                in("x20") receiver.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"),
            );
            Self { bytes, meta, wt, ty: self.ty.clone() }
        }
    }

    /// The value, metadata and `Shape` witness, for a call that takes a shape.
    pub fn parts(&self) -> (Vec<u8>, *const c_void, *const c_void) {
        (self.bytes.clone(), self.meta, self.wt)
    }

    /// `.stroke(lineWidth:)` — no style, so it strokes with the foreground.
    ///
    /// One generic parameter rather than two, so the substitution list is just
    /// `Self` and its `Shape` witness, and the line width is the only formal
    /// argument.
    pub fn stroke_default(&self, line_width: f64) -> ViewHandle {
        unsafe {
            let subst = [self.meta, self.wt];
            // `-> some Shape`, not `-> some View`. The opaque type carries one
            // conformance and it is `Shape`, so asking for the second one hands
            // back whatever follows it in memory; the value builds, reports the
            // right type, and faults when something tries to draw it. The
            // `View` witness comes from the concrete metadata instead.
            let (meta, _, size) =
                super::opaque_result_type(resolve::shape_stroke_plain_oret(), &subst);
            let wt = abi::get_view_wt(meta);
            assert!(!wt.is_null(), "stroked shape !: View");
            let mut result = vec![0u8; size];
            let mut receiver = self.receiver();
            core::arch::asm!("blr {f}", f = in(reg) resolve::shape_stroke_plain_fn(),
                in("x0") subst[0], in("x1") subst[1],
                in("d0") line_width,
                in("x8") result.as_mut_ptr(),
                in("x20") receiver.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"),
            );
            wrap_owned(result, meta, wt)
        }
    }

    /// `.stroke(_:lineWidth:)` with a `Color`.
    pub fn stroke(&self, color: u64, line_width: f64) -> ViewHandle {
        let bytes = color.to_le_bytes();
        // SAFETY: as [`Shape::fill`].
        unsafe {
            self.stroke_style(&bytes, resolve::color_meta(), resolve::color_shapestyle_wt(), line_width)
        }
    }

    /// Present a stroked shape as the `StrokeShapeView` Swift builds.
    ///
    /// `Circle().stroke(.blue, lineWidth: 4)` in Swift is a
    /// `StrokeShapeView<Circle, Color, EmptyView>`, and dumping one shows what
    /// that is: a newtype over
    /// `ModifiedContent<_ShapeView<_StrokedShape<Circle>, Color>,
    /// _BackgroundModifier<EmptyView>>` — one stored property, so identical in
    /// layout to what it wraps. The bindings built the inner `_ShapeView` and
    /// stopped there, which rendered the same and typed differently.
    ///
    /// `.stroke` is `@inlinable`, so there is no initialiser to call and no
    /// instantiation to read a descriptor off; the descriptor itself is exported
    /// and is what this instantiates from. A wrong argument vector would build
    /// some *other* type rather than fail, so the result is checked and anything
    /// unexpected keeps the inner view, which is what this always returned.
    ///
    /// # Safety
    /// `inner` must be the `_ShapeView` this shape's stroke produced.
    unsafe fn as_stroke_shape_view(
        &self,
        inner: ViewHandle,
        style_meta: *const c_void,
        style_wt: *const c_void,
    ) -> ViewHandle {
        unsafe {
            let empty = super::empty_view();
            let bg = super::background_content(&inner, &empty, super::Alignment::Center);

            let desc = resolve::stroke_shape_view_desc();
            if desc.is_null() {
                return inner;
            }
            // Parameters first — Content, Style, Background — then their
            // conformances: Shape, ShapeStyle, View.
            let args = [
                self.meta,
                style_meta,
                resolve::emptyview_meta(),
                self.wt,
                style_wt,
                resolve::emptyview_view_wt(),
            ];
            let meta = abi::generic_metadata_from_descriptor(desc, &args);
            if meta.is_null() {
                return inner;
            }
            // `StrokeShapeView` is a newtype over the `ModifiedContent` below
            // it: one stored property at offset zero, which is what lets the
            // bytes carry over unchanged. Read that from the metadata rather
            // than inferring it from the sizes agreeing.
            if abi::struct_field_offsets(meta).as_deref() != Some(&[0][..])
                || abi::type_bytes(meta) != abi::type_bytes(bg.meta)
            {
                return inner;
            }
            if !crate::diag::type_name(meta).starts_with("SwiftUI.StrokeShapeView<") {
                return inner;
            }
            let wt = abi::get_view_wt(meta);
            if wt.is_null() {
                return inner;
            }
            // Same layout, so the bytes carry over as they are — copied through
            // the value witness so anything refcounted inside is retained.
            let vwt = &*swift_runtime_sys::SwiftABI::get_value_witness_table(bg.meta);
            let mut out = vec![0u8; abi::type_bytes(meta)];
            if vwt.size > 0 {
                (vwt.initialize_with_copy)(
                    out.as_mut_ptr() as *mut c_void,
                    bg.value_ptr() as *mut c_void,
                    bg.meta,
                );
            }
            super::wrap_owned(out, meta, wt)
        }
    }

    /// Both calls have the same shape and differ by one register.
    ///
    /// `fill(_ content: S, style: FillStyle)` puts the `FillStyle` — two
    /// `Bool`s, so loadable — in x1, which pushes the four generic words to
    /// x2. `stroke(_ content: S, lineWidth: CGFloat)` sends its second
    /// argument in d0 instead, so nothing occupies x1 and the generic words
    /// start there. Reading the style metadata out of a line width faults
    /// inside the runtime.
    #[allow(clippy::too_many_arguments)]
    unsafe fn styled(
        &self,
        func: *const c_void,
        oret: *const c_void,
        style: &[u8],
        style_meta: *const c_void,
        style_wt: *const c_void,
        filling: bool,
        line_width: f64,
    ) -> ViewHandle {
        unsafe {
            // The substitution list an opaque return wants is every generic
            // argument and then every witness table: `Self`, the style,
            // `Self: Shape`, and the style's `ShapeStyle`.
            let subst = [self.meta, style_meta, self.wt, style_wt];
            let (meta, wt, size) = super::opaque_result_type(oret, &subst);

            let mut result = vec![0u8; size];
            let mut arg = style.to_vec();
            arg.resize(abi::type_bytes(style_meta).max(style.len()).max(1), 0);
            let mut receiver = self.receiver();
            let (x1, x2, x3, x4, x5) = if filling {
                (FILL_STYLE_DEFAULT as *const c_void, subst[0], subst[1], subst[2], subst[3])
            } else {
                (subst[0], subst[1], subst[2], subst[3], core::ptr::null())
            };
            core::arch::asm!("blr {f}", f = in(reg) func,
                in("x0") arg.as_mut_ptr(),
                in("x1") x1, in("x2") x2, in("x3") x3, in("x4") x4, in("x5") x5,
                in("d0") line_width,
                in("x8") result.as_mut_ptr(),
                in("x20") receiver.as_mut_ptr(),
                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, meta, wt)
        }
    }

    /// The shape's storage, with a byte to spare.
    ///
    /// `Circle` and `Rectangle` have no stored properties, and an empty `Vec`
    /// has a dangling pointer — fine where nothing reads it, but not worth
    /// relying on across a call whose layout is only inferred.
    fn receiver(&self) -> Vec<u8> {
        let mut v = self.bytes.clone();
        v.push(0);
        v
    }
}

/// A `Path` under construction.
///
/// Every method is `mutating` in Swift, so each takes the path through x20 and
/// writes back in place; there is no value to thread through. Finish with
/// [`PathBuilder::shape`].
pub struct PathBuilder {
    bytes: Vec<u8>,
}

impl PathBuilder {
    /// Move the `Path` into an `@out` slot and give up ownership.
    ///
    /// For a `Shape.path(in:)` witness, whose result slot SwiftUI supplies:
    /// copying and then dropping the builder would release the path's storage
    /// while SwiftUI still holds it.
    ///
    /// # Safety
    /// `out` must have room for a `Path` — the builder's own buffer is sized for
    /// one, and `bytes.len()` is that size.
    pub(crate) unsafe fn move_into(self, out: *mut u8) {
        let me = core::mem::ManuallyDrop::new(self);
        unsafe { core::ptr::copy_nonoverlapping(me.bytes.as_ptr(), out, me.bytes.len()) };
    }

    /// `move(to:)`
    pub fn move_to(&mut self, x: f64, y: f64) -> &mut Self {
        unsafe { self.point(resolve::path_move_to(), x, y, 0.0, 0.0) }
    }

    /// `addLine(to:)`
    pub fn line_to(&mut self, x: f64, y: f64) -> &mut Self {
        unsafe { self.point(resolve::path_add_line(), x, y, 0.0, 0.0) }
    }

    /// `addQuadCurve(to:control:)` — the destination in d0/d1, the control
    /// point in d2/d3.
    pub fn quad_curve_to(&mut self, x: f64, y: f64, cx: f64, cy: f64) -> &mut Self {
        unsafe { self.point(resolve::path_add_quad_curve(), x, y, cx, cy) }
    }

    /// `closeSubpath()`
    pub fn close(&mut self) -> &mut Self {
        unsafe { self.point(resolve::path_close_subpath(), 0.0, 0.0, 0.0, 0.0) }
    }

    unsafe fn point(&mut self, f: *const c_void, a: f64, b: f64, c: f64, d: f64) -> &mut Self {
        unsafe {
            core::arch::asm!("blr {f}", f = in(reg) f,
                in("d0") a, in("d1") b, in("d2") c, in("d3") d,
                in("x20") self.bytes.as_mut_ptr(),
                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"),
            );
        }
        self
    }

    /// The finished path, as a `Shape`.
    pub fn shape(&self) -> Shape {
        unsafe { Shape::of(self.bytes.clone(), mangle::ty("Path")) }
    }
}

/// `FillStyle()` — two `Bool`s in one register: `isEOFilled` false in byte 0,
/// `isAntialiased` true in byte 1.
const FILL_STYLE_DEFAULT: u64 = 0x0100;

/// `.strokeBorder(_:lineWidth:antialiased:)` on an `InsettableShape`.
///
/// Not `.stroke`: a stroke straddles the shape's edge, a border is inset so it
/// falls entirely inside. The difference is half the line width everywhere.
///
/// Two overloads share the name. The older returns `some View` and is exported;
/// the newer returns a concrete `StrokeBorderShapeView` and is
/// `@_alwaysEmitIntoClient`, and it is the one Swift picks — so matching what a
/// reference builds means building that type's value rather than calling either.
pub fn stroke_border(
    shape: super::InsettableShape,
    color: u64,
    line_width: f64,
) -> ViewHandle {
    unsafe {
        let (ma, _insettable_wt, init) = shape.parts();
        let shape_meta = abi::metadata0(ma);
        let mut receiver = vec![0u8; abi::type_bytes(shape_meta).max(1)];
        core::arch::asm!("blr {f}", f = in(reg) init,
            in("x8") receiver.as_mut_ptr(),
            in("x20") shape_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"),
        );

        let subst = [shape_meta, resolve::color_meta(), _insettable_wt, resolve::color_shapestyle_wt()];
        let (meta, wt, size) =
            super::opaque_result_type(resolve::stroke_border_oret(), &subst);
        let style = color.to_le_bytes();
        let mut result = vec![0u8; size.max(1)];
        core::arch::asm!("blr {f}", f = in(reg) resolve::stroke_border_fn(),
            in("x0") style.as_ptr(),
            in("d0") line_width,
            in("x1") 1u64,
            in("x2") subst[0], in("x3") subst[1], in("x4") subst[2], in("x5") subst[3],
            in("x8") result.as_mut_ptr(),
            in("x20") receiver.as_mut_ptr(),
            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"),
        );
        // The exported call produced the *inner* view. Swift's overload wraps it:
        //   StrokeBorderShapeView<Shape, Style, EmptyView> {
        //       shape, view: ModifiedContent<that, _BackgroundModifier<EmptyView>>
        //   }
        // `Circle` and `EmptyView` are both zero bytes, so the whole wrapper adds
        // only the background modifier's `Alignment` — which is `.center`.
        let outer_mangled = format!(
            "7SwiftUI21StrokeBorderShapeViewVy{}7SwiftUI5ColorV7SwiftUI9EmptyViewVG",
            shape.type_mangling()
        );
        let outer = abi::resolve_type_by_mangled_name(outer_mangled.as_bytes());
        assert!(!outer.is_null(), "{}", crate::diag::demangle_type(outer_mangled.as_bytes()));
        let outer_wt = abi::get_view_wt(outer);
        assert!(!outer_wt.is_null(), "StrokeBorderShapeView !: View");

        // `Alignment` is two `AlignmentKey`s and comes back in x0/x1, not
        // through x8 — reading it as an indirect return left both keys zero,
        // which renders the same (centre *is* what an empty background aligns
        // to) and only the value comparison saw.
        let (ah, av) = super::static_getter(resolve::alignment_center(), resolve::alignment_meta());

        let mut bytes = vec![0u8; abi::type_bytes(outer)];
        let inner = abi::type_size(meta);
        bytes[..inner].copy_from_slice(&result[..inner]);
        // Where the alignment sits is read from the metadata, by the same walk
        // [`stroke_view_offsets`] does — it is not a field of the outer type at
        // all, but of the `_BackgroundModifier` two levels in. The arithmetic
        // that used to stand in here padded the inner view to eight, and
        // writing at its unpadded 58 instead straddled the two alignment keys
        // and read back as one `AlignmentKey(bits: 0x50002)` — which still
        // rendered centred, because an empty background has nothing to
        // misalign.
        let align_at = border_view_offsets(outer)
            .map(|(_, _, _, align)| align)
            .unwrap_or_else(|| inner.next_multiple_of(8));
        bytes[align_at..align_at + 8].copy_from_slice(&ah.to_le_bytes());
        bytes[align_at + 8..align_at + 16].copy_from_slice(&av.to_le_bytes());
        let _ = wt;
        wrap_buf(&bytes, outer, outer_wt)
    }
}

/// `.fill(_:).stroke(_:lineWidth:)` — a shape filled, then outlined.
///
/// `ShapeView.stroke(_:lineWidth:antialiased:)` is `@_alwaysEmitIntoClient`, so
/// there is nothing to call. What it builds is
/// `StrokeShapeView<Content, S, Self>`, whose single field is a
/// `ModifiedContent` putting the *stroke* in front and the original *fill*
/// behind it as a `_BackgroundModifier` — so the fill is drawn as a background
/// rather than composited, and both filled shape views have to be built.
pub fn fill_then_stroke(
    shape: &Shape,
    fill: u64,
    stroke: u64,
    line_width: f64,
    result_mangled: &[u8],
) -> ViewHandle {
    unsafe {
        let color_meta = resolve::color_meta();
        let color_wt = resolve::color_shapestyle_wt();
        let (background, bg_ty) = shape.fill_parts(&fill.to_le_bytes(), color_meta, color_wt);
        let (content, content_ty) =
            shape.stroked(line_width).fill_parts(&stroke.to_le_bytes(), color_meta, color_wt);

        let meta = abi::resolve_type_by_mangled_name(result_mangled);
        assert!(!meta.is_null(), "{}", crate::diag::demangle_type(result_mangled));
        let wt = abi::get_view_wt(meta);
        assert!(!wt.is_null(), "StrokeShapeView !: View");

        let (ah, av) = super::static_getter(resolve::alignment_center(), resolve::alignment_meta());
        let content_size = abi::type_size(content_ty);
        let bg_size = abi::type_size(bg_ty);
        let (content_at, bg_at, align_at) =
            stroke_view_offsets(meta)
                .unwrap_or_else(|| {
                    // Every offset padded to eight — right for a bare shape,
                    // and an assumption rather than a fact. Only reached if one
                    // of the three nested types does not resolve.
                    let bg_at = content_size.next_multiple_of(8);
                    (0, bg_at, (bg_at + bg_size).next_multiple_of(8))
                });

        let mut bytes = vec![0u8; abi::type_bytes(meta)];
        assert!(
            align_at + 16 <= bytes.len() && bg_at + bg_size <= bytes.len(),
            "{} lays out its fields differently than expected: content at {content_at} \
             ({content_size} bytes), background at {bg_at} ({bg_size}), alignment at \
             {align_at} — but the type is only {} bytes.",
            crate::diag::type_name(meta),
            bytes.len(),
        );
        bytes[content_at..content_at + content_size].copy_from_slice(&content[..content_size]);
        bytes[bg_at..bg_at + bg_size].copy_from_slice(&background[..bg_size]);
        bytes[align_at..align_at + 8].copy_from_slice(&ah.to_le_bytes());
        bytes[align_at + 8..align_at + 16].copy_from_slice(&av.to_le_bytes());
        wrap_buf(&bytes, meta, wt)
    }
}

/// Where a `StrokeShapeView`'s three written fields actually sit.
///
/// They are not its own fields: it has exactly one, a `ModifiedContent`, whose
/// two fields are the stroked shape and a `_BackgroundModifier`, whose two are
/// the fill and the alignment. So each offset is a sum down three levels, and
/// every level is read from that level's metadata — reached with
/// [`abi::field_type_metadata`], since `_BackgroundModifier` exports no
/// accessor to ask for by name.
///
/// Returns `None` if any level does not look as expected, which leaves the
/// caller on its padded-to-eight estimate — right for a bare shape, and what
/// this replaces.
///
/// # Safety
/// `meta` must be `StrokeShapeView` metadata.
unsafe fn stroke_view_offsets(meta: *const c_void) -> Option<(usize, usize, usize)> {
    unsafe {
        let &[view_at] = abi::struct_field_offsets(meta)?.as_slice() else { return None };
        let modified = abi::field_type_metadata(meta, 0);
        if modified.is_null() {
            return None;
        }
        let &[content_at, modifier_at] = abi::struct_field_offsets(modified)?.as_slice() else {
            return None;
        };
        let background = abi::field_type_metadata(modified, 1);
        if background.is_null() {
            return None;
        }
        let &[bg_at, align_at] = abi::struct_field_offsets(background)?.as_slice() else {
            return None;
        };
        Some((
            view_at + content_at,
            view_at + modifier_at + bg_at,
            view_at + modifier_at + align_at,
        ))
    }
}

/// Where a `StrokeBorderShapeView`'s four written fields sit.
///
/// The same walk as [`stroke_view_offsets`], with the type's own `shape` field
/// in front of the `ModifiedContent`.
///
/// # Safety
/// `meta` must be `StrokeBorderShapeView` metadata.
unsafe fn border_view_offsets(meta: *const c_void) -> Option<(usize, usize, usize, usize)> {
    unsafe {
        let &[shape_at, view_at] = abi::struct_field_offsets(meta)?.as_slice() else {
            return None;
        };
        let modified = abi::field_type_metadata(meta, 1);
        if modified.is_null() {
            return None;
        }
        let &[content_at, modifier_at] = abi::struct_field_offsets(modified)?.as_slice() else {
            return None;
        };
        let background = abi::field_type_metadata(modified, 1);
        if background.is_null() {
            return None;
        }
        let &[bg_at, align_at] = abi::struct_field_offsets(background)?.as_slice() else {
            return None;
        };
        Some((
            shape_at,
            view_at + content_at,
            view_at + modifier_at + bg_at,
            view_at + modifier_at + align_at,
        ))
    }
}

/// `.fill(_:).strokeBorder(_:style:)` — a shape filled, then bordered inside its
/// own edge.
///
/// The `ShapeView` spelling of `strokeBorder`, and like the `Shape` one it is
/// `@_alwaysEmitIntoClient`. What it builds is a `StrokeBorderShapeView` whose
/// `shape` field is the original shape and whose `view` field is the same
/// stroke-over-fill `ModifiedContent` [`fill_then_stroke`] builds — except the
/// stroked shape is first `inset(by:)` half the line width, which is the whole
/// difference between a stroke and a border.
pub fn fill_then_stroke_border(
    shape: &Shape,
    fill: u64,
    border: u64,
    line_width: f64,
    result_mangled: &[u8],
) -> ViewHandle {
    unsafe {
        let color_meta = resolve::color_meta();
        let color_wt = resolve::color_shapestyle_wt();
        let (background, bg_ty) = shape.fill_parts(&fill.to_le_bytes(), color_meta, color_wt);
        let (content, content_ty) = shape
            .inset(line_width / 2.0)
            .stroked(line_width)
            .fill_parts(&border.to_le_bytes(), color_meta, color_wt);

        let meta = abi::resolve_type_by_mangled_name(result_mangled);
        assert!(!meta.is_null(), "{}", crate::diag::demangle_type(result_mangled));
        let wt = abi::get_view_wt(meta);
        assert!(!wt.is_null(), "StrokeBorderShapeView !: View");

        let (ah, av) = super::static_getter(resolve::alignment_center(), resolve::alignment_meta());
        let shape_size = abi::type_size(shape.meta);
        let content_size = abi::type_size(content_ty);
        let bg_size = abi::type_size(bg_ty);
        // `StrokeBorderShapeView` has a `shape` of its own in front of the same
        // nested `ModifiedContent` the stroke case has, so its offsets are read
        // the same way — one level further in.
        let (shape_at, content_at, bg_at, align_at) = border_view_offsets(meta)
            .unwrap_or_else(|| {
                let content_at = shape_size.next_multiple_of(8);
                let bg_at = (content_at + content_size).next_multiple_of(8);
                (0, content_at, bg_at, (bg_at + bg_size).next_multiple_of(8))
            });

        let mut bytes = vec![0u8; abi::type_bytes(meta)];
        assert!(
            align_at + 16 <= bytes.len(),
            "{} lays out its fields differently than expected",
            crate::diag::type_name(meta),
        );
        bytes[shape_at..shape_at + shape_size].copy_from_slice(&shape.bytes[..shape_size]);
        bytes[content_at..content_at + content_size].copy_from_slice(&content[..content_size]);
        bytes[bg_at..bg_at + bg_size].copy_from_slice(&background[..bg_size]);
        bytes[align_at..align_at + 8].copy_from_slice(&ah.to_le_bytes());
        bytes[align_at + 8..align_at + 16].copy_from_slice(&av.to_le_bytes());
        wrap_buf(&bytes, meta, wt)
    }
}

/// A `LinearGradient` built from explicit `Gradient.Stop`s.
///
/// Not the same as the `colors:` spelling next door: that one spaces its colours
/// evenly, this one places each at a location the caller gives. A mask built
/// from stops — which is what both of the tvOS Media Catalog's hero views use —
/// cannot be expressed as evenly-spaced colours.
pub fn linear_gradient_stops(
    stops: &[(u64, f64)],
    start: (f64, f64),
    end: (f64, f64),
) -> (Vec<u8>, *const c_void, *const c_void) {
    unsafe {
        let stop_meta = abi::metadata0(resolve::gradient_stop_ma());
        let stride = abi::type_stride(stop_meta);
        let mut bytes = vec![0u8; stride * stops.len()];
        for (i, (color, location)) in stops.iter().enumerate() {
            // Gradient.Stop.init(color:location:) — the Color in x0 and the
            // location in d0, and the result comes *back* the same way: a Stop
            // is one reference and one CGFloat, so it is returned in x0/d0
            // rather than through x8. Handing it an x8 left the buffer zeroed
            // and the array of stops full of null Colors, which faulted on the
            // first draw.
            let (word, loc): (u64, f64);
            core::arch::asm!("blr {f}", f = in(reg) resolve::gradient_stop_init(),
                inout("x0") *color => word,
                inout("d0") *location => loc,
                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"),
            );
            bytes[i * stride..i * stride + 8].copy_from_slice(&word.to_le_bytes());
            bytes[i * stride + 8..i * stride + 16].copy_from_slice(&loc.to_le_bytes());
        }
        let array = abi::swift_array(stop_meta, stops.len(), &bytes);

        let g: u64;
        core::arch::asm!("blr {f}", f = in(reg) resolve::gradient_stops_init(),
            in("x0") array,
            in("x20") resolve::gradient_meta(),
            lateout("x0") g,
            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"),
        );

        let meta = crate::type_by_name!(swift_type!(SwiftUI.LinearGradient).as_bytes());
        assert!(!meta.is_null(), "LinearGradient metadata");
        let mut value = vec![0u8; abi::type_bytes(meta)];
        core::arch::asm!("blr {f}", f = in(reg) resolve::linear_gradient_init(),
            in("x0") g,
            in("d0") start.0, in("d1") start.1, in("d2") end.0, in("d3") end.1,
            in("x8") value.as_mut_ptr(),
            in("x20") meta,
            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"),
        );
        (value, meta, resolve::linear_gradient_wt())
    }
}

/// A `LinearGradient` as a view, for `.mask { … }` and friends.
pub fn linear_gradient_stops_view(
    stops: &[(u64, f64)],
    start: (f64, f64),
    end: (f64, f64),
) -> ViewHandle {
    let (bytes, meta, _) = linear_gradient_stops(stops, start, end);
    unsafe {
        let wt = abi::get_view_wt(meta);
        assert!(!wt.is_null(), "LinearGradient !: View");
        wrap_buf(&bytes, meta, wt)
    }
}

/// `.shadow(_:)` applied to any `ShapeStyle` — `_ShadowShapeStyle<Base>`.
///
/// [`implicit_shadow_style`] is the special case where `Base` is
/// `_ImplicitShapeStyle` and so contributes no bytes. A real base — a
/// `Material`, say — sits in front of the `ShadowStyle`, which is why this takes
/// its bytes and its type rather than assuming both are empty.
pub fn shadow_over_style(
    base: &[u8],
    base_ty: &str,
    shadow: &[u8],
) -> (Vec<u8>, *const c_void, *const c_void) {
    unsafe {
        let ty = mangle::ty("_ShadowShapeStyle")
            .of(vec![mangle::Type::Verbatim(base_ty.into())])
            .mangle();
        let meta = abi::resolve_type_by_mangled_name(ty.as_bytes());
        assert!(!meta.is_null(), "{}", mangle::demangle(&ty));
        let wt = abi::get_view_wt_for_proto(meta, resolve::shape_style_proto());
        assert!(!wt.is_null(), "_ShadowShapeStyle !: ShapeStyle");
        let mut bytes = vec![0u8; abi::type_bytes(meta)];
        // Where the two fields sit comes from the metadata: `Base` is whatever
        // style this wraps, so padding the first to eight is a guess about a
        // type chosen by the caller.
        let offsets = abi::struct_field_offsets(meta).expect("two stored fields");
        let &[base_at, shadow_at] = offsets.as_slice() else {
            panic!("_ShadowShapeStyle is {} fields, not 2", offsets.len());
        };
        bytes[base_at..base_at + base.len()].copy_from_slice(base);
        let n = shadow.len().min(bytes.len() - shadow_at);
        bytes[shadow_at..shadow_at + n].copy_from_slice(&shadow[..n]);
        (bytes, meta, wt)
    }
}

/// `.opacity(_:)` applied to any `ShapeStyle` — `_OpacityShapeStyle<Base>`.
///
/// [`implicit_opacity_style`] is the case where `Base` is `_ImplicitShapeStyle`
/// and contributes nothing; a real base — `.red.gradient`, say — sits in front
/// of the `Float`.
pub fn opacity_over_style(
    base: &[u8],
    base_ty: &str,
    opacity: f64,
) -> (Vec<u8>, *const c_void, *const c_void) {
    unsafe {
        let ty = mangle::ty("_OpacityShapeStyle")
            .of(vec![mangle::Type::Verbatim(base_ty.into())])
            .mangle();
        let meta = abi::resolve_type_by_mangled_name(ty.as_bytes());
        assert!(!meta.is_null(), "{}", mangle::demangle(&ty));
        let wt = abi::get_view_wt_for_proto(meta, resolve::shape_style_proto());
        assert!(!wt.is_null(), "_OpacityShapeStyle !: ShapeStyle");
        let mut bytes = vec![0u8; abi::type_bytes(meta)];
        bytes[..base.len()].copy_from_slice(base);
        let at = base.len().next_multiple_of(4);
        bytes[at..at + 4].copy_from_slice(&(opacity as f32).to_le_bytes());
        (bytes, meta, wt)
    }
}

impl Shape {
    /// `.trim(from:to:)` — keep a fraction of the shape's path.
    ///
    /// How a progress ring is drawn: a stroked circle trimmed to the fraction
    /// complete. Without it a "ring showing 70%" is a full circle.
    ///
    /// `.trim` is `@inlinable`, so SwiftUI exports no function for it — but
    /// `_TrimmedShape<S>` is just the shape and two `CGFloat`s, its descriptor
    /// is exported, and the field offsets come from the metadata rather than
    /// being assumed.
    pub fn trim(&self, from: f64, to: f64) -> Self {
        unsafe {
            let desc = resolve::trimmed_shape_desc();
            let meta = if desc.is_null() {
                core::ptr::null()
            } else {
                abi::generic_metadata_from_descriptor(desc, &[self.meta, self.wt])
            };
            let offsets = if meta.is_null() {
                None
            } else {
                abi::struct_field_offsets(meta)
            };
            // Shape, then the two fractions — anything else is not the type
            // this was taken for, and writing into it would be a guess.
            let same = || Self {
                bytes: self.bytes.clone(),
                meta: self.meta,
                wt: self.wt,
                ty: self.ty.clone(),
            };
            let Some(offs) = offsets.filter(|o| o.len() == 3) else {
                return same();
            };
            let wt = abi::get_view_wt_for_proto(meta, resolve::shape_proto());
            if wt.is_null() {
                return same();
            }

            let mut bytes = vec![0u8; abi::type_bytes(meta)];
            let vwt = &*swift_runtime_sys::SwiftABI::get_value_witness_table(self.meta);
            if vwt.size > 0 {
                (vwt.initialize_with_copy)(
                    bytes.as_mut_ptr().add(offs[0]) as *mut c_void,
                    self.bytes.as_ptr() as *mut c_void,
                    self.meta,
                );
            }
            bytes[offs[1]..offs[1] + 8].copy_from_slice(&from.to_le_bytes());
            bytes[offs[2]..offs[2] + 8].copy_from_slice(&to.to_le_bytes());

            Self {
                bytes,
                meta,
                wt,
                ty: mangle::ty("_TrimmedShape").of(vec![self.ty.clone()]),
            }
        }
    }
}