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

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

// ── Typography ──

/// Build a `SwiftUI.Font` from `Font.system(size:weight:design:)`.
///
/// `design` is `Optional<Font.Design>`, which is passed indirectly; its `nil`
/// representation is produced through the value witness table rather than
/// assumed, since it depends on how many cases the enum has.
pub(crate) unsafe fn system_font(size: f64, bold: bool) -> u64 {
    let design_meta = unsafe { crate::type_by_name!(swift_type!(opt enum SwiftUI.Font.Design).as_bytes()) };
    assert!(!design_meta.is_null(), "Optional<Font.Design> metadata");
    let mut design = vec![0u8; unsafe { abi::type_bytes(design_meta) }];
    unsafe {
        abi::store_optional_tag(&mut design, design_payload_meta(), false);
    }

    // Optional<Font.Weight>: payload in x0 (Font.Weight is a Double), tag in x1.
    // `Font.Weight` wraps a Double, so its static getters return in d0 — reading
    // x0 instead yields a stale register and the weight is silently ignored.
    let (weight_payload, weight_tag) = if bold {
        let w = unsafe { static_getter_f64(resolve::font_weight_bold(), resolve::font_weight_meta()) };
        (w.to_bits(), 0u64)
    } else {
        (0u64, 1u64)
    };

    let font: u64;
    unsafe {
        core::arch::asm!("blr {f}", f = in(reg) resolve::font_system(),
            in("d0") size,
            in("x0") weight_payload,
            in("x1") weight_tag,
            in("x2") design.as_mut_ptr(),
            in("x20") resolve::font_meta(),
            lateout("x0") font,
            lateout("x1") _, 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"),
        );
    }
    font
}

/// Apply `.font(.system(size:weight:))`.
pub fn font(view: &ViewHandle, size: f64, bold: bool) -> ViewHandle {
    unsafe {
        let f = system_font(size, bold);
        let (_, _, out_size) = FONT_T.applied_to(view.meta);
        let mut result = vec![0u8; out_size];
        let self_storage = view.value_ptr();
        // font(_: Font?) — x0 = Font? (8 bytes, nil == 0)
        core::arch::asm!("blr {fun}", fun = in(reg) resolve::font_fn(),
            in("x0") f,
            in("x1") view.meta,
            in("x2") view.wt,
            in("x8") result.as_mut_ptr(),
            in("x20") self_storage,
            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_modified(result, &FONT_T, view)
    }
}

/// Apply `.font(.system(size:))`.
pub fn font_size(view: &ViewHandle, size: f64) -> ViewHandle {
    font(view, size, false)
}

/// Apply `.bold()`.
pub fn bold(view: &ViewHandle) -> ViewHandle {
    unsafe {
        let (_, _, size) = BOLD_T.applied_to(view.meta);
        let mut result = vec![0u8; size];
        let self_storage = view.value_ptr();
        core::arch::asm!("blr {f}", f = in(reg) resolve::bold_fn(),
            in("x0") 1u64,
            in("x1") view.meta,
            in("x2") view.wt,
            in("x8") result.as_mut_ptr(),
            in("x20") self_storage,
            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_modified(result, &BOLD_T, view)
    }
}

/// Apply `.foregroundStyle(_:)` with a colour.
///
/// Named for what it does, not for `.foregroundColor(_:)` — which is deprecated
/// and a different thing: it writes an environment key, producing
/// `_EnvironmentKeyWritingModifier<Color?>` where this produces
/// `_ForegroundStyleModifier<Color>`. The two render alike, so only a
/// type-level comparison tells them apart. See [`foreground_color`] for the
/// other one.
pub fn foreground_style_color(view: &ViewHandle, r: f64, g: f64, b: f64, a: f64) -> ViewHandle {
    unsafe { foreground_style_value(view, color_value(r, g, b, a)) }
}

/// Apply `.foregroundStyle(_:_:)` — a primary and a secondary style.
///
/// What `symbolRenderingMode(.palette)` needs: a palette symbol takes its
/// layers from successive styles, and with only one it renders as monochrome.
pub fn foreground_style_pair(view: &ViewHandle, primary: u64, secondary: u64) -> ViewHandle {
    unsafe {
        let (_, _, size) = FOREGROUND2_T.applied_to(view.meta);
        let mut result = vec![0u8; size];
        let self_storage = view.value_ptr();
        let mut a: u64 = primary;
        let mut b: u64 = secondary;
        // foregroundStyle<S1: ShapeStyle, S2: ShapeStyle>(_:_:)
        //   x0/x1 = the two styles by address, then Self.Type, S1.Type,
        //   S2.Type, and the three witness tables. Eight words exactly, so
        //   nothing spills.
        core::arch::asm!("blr {f}", f = in(reg) resolve::foreground_style2_fn(),
            in("x0") &mut a as *mut u64,
            in("x1") &mut b as *mut u64,
            in("x2") view.meta,
            in("x3") resolve::color_meta(),
            in("x4") resolve::color_meta(),
            in("x5") view.wt,
            in("x6") resolve::color_shapestyle_wt(),
            in("x7") resolve::color_shapestyle_wt(),
            in("x8") result.as_mut_ptr(),
            in("x20") self_storage,
            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_modified(result, &FOREGROUND2_T, view)
    }
}

/// Apply `.foregroundStyle(_:_:_:)` — three styles.
///
/// A palette symbol takes its layers from successive styles.
/// [`foreground_style_pair`] covers the two-layer symbols; the three-layer
/// ones — and there are plenty in SF Symbols — rendered their third layer in
/// the secondary colour, because there was no way to say what it should be.
///
/// Eleven words of arguments, so three spill: the three style addresses and
/// `Self.Type` fill x0–x3, the three style types and the `Self: View` witness
/// take x4–x7, and all *three* `ShapeStyle` witnesses go to the stack.
///
/// Spilling only two of them — which is easy to do, since the pair version next
/// door fits in eight words exactly and spills none — left the callee reading a
/// stale word as a witness table. It did not fault there: it faulted much later
/// inside `swift::MetadataCacheKey::operator==`, recursing on a type built from
/// the garbage, which is what an argument-count mistake looks like from the
/// outside.
pub fn foreground_style_triple(
    view: &ViewHandle,
    primary: u64,
    secondary: u64,
    tertiary: u64,
) -> ViewHandle {
    unsafe {
        let (_, _, size) = FOREGROUND3_T.applied_to(view.meta);
        let mut result = vec![0u8; size];
        let self_storage = view.value_ptr();
        let mut a: u64 = primary;
        let mut b: u64 = secondary;
        let mut c: u64 = tertiary;
        let color = resolve::color_meta();
        let style_wt = resolve::color_shapestyle_wt();
        core::arch::asm!(
            "sub sp, sp, #32",
            "stp {w1}, {w2}, [sp]",
            "str {w3}, [sp, #16]",
            "blr {f}",
            "add sp, sp, #32",
            f = in(reg) resolve::foreground_style3_fn(),
            w1 = in(reg) style_wt,
            w2 = in(reg) style_wt,
            w3 = in(reg) style_wt,
            in("x0") &mut a as *mut u64,
            in("x1") &mut b as *mut u64,
            in("x2") &mut c as *mut u64,
            in("x3") view.meta,
            in("x4") color,
            in("x5") color,
            in("x6") color,
            in("x7") view.wt,
            in("x8") result.as_mut_ptr(),
            in("x20") self_storage,
            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_modified(result, &FOREGROUND3_T, view)
    }
}

/// Apply `.foregroundStyle(_:)` to a `Color` that is already built.
///
/// The components overload above cannot express `Color.blue`: SwiftUI's named
/// colours are semantic, not literal, and resolve per appearance — the aqua
/// `Color.blue` is nowhere near `(0, 0, 1)`. This takes the value a static
/// getter handed back instead. See [`super::system_color`].
pub fn foreground_style_value(view: &ViewHandle, color: u64) -> ViewHandle {
    let bytes = color.to_le_bytes();
    unsafe {
        foreground_style_of(
            view,
            &bytes,
            resolve::color_meta(),
            resolve::color_shapestyle_wt(),
            &FOREGROUND_T,
        )
    }
}

/// Apply `.foregroundStyle(.linearGradient(colors:startPoint:endPoint:))`.
///
/// The shorthand in Swift source is a protocol-extension static marked
/// `@inlinable`, so it has no symbol; the `LinearGradient` it builds does.
/// Apply `.foregroundStyle(_:)` with one of the hierarchical levels —
/// `.secondary` and friends.
pub fn foreground_style_hierarchical(
    view: &ViewHandle,
    level: super::Hierarchical,
) -> ViewHandle {
    let (style, meta, wt) = super::hierarchical_style(level);
    unsafe { foreground_style_of(view, &style, meta, wt, &FOREGROUND_HIERARCHICAL_T) }
}

pub fn foreground_style_linear_gradient(
    view: &ViewHandle,
    colors: &[u64],
    start: (f64, f64),
    end: (f64, f64),
) -> ViewHandle {
    let (style, meta, wt) = super::linear_gradient_style_of(colors, start, end);
    unsafe { foreground_style_of(view, &style, meta, wt, &FOREGROUND_GRADIENT_T) }
}

/// Apply `.foregroundStyle(_:)` with any `ShapeStyle`.
///
/// `.linearGradient(colors:startPoint:endPoint:)` and its neighbours are
/// protocol-extension statics marked `@inlinable`, so none of them has a
/// symbol — but the concrete type each one builds does. Passing a
/// `LinearGradient` here is the same call the shorthand would have made.
///
/// `result` names the `ModifiedContent<AnyView, _ForegroundStyleModifier<S>>`
/// the call produces, which depends on `S` and so cannot be fixed here.
/// # Safety
/// `style` must hold an initialised value of the type `style_meta` describes,
/// `style_wt` must be that type's `ShapeStyle` conformance, and `result` must
/// name the `ModifiedContent` the call actually produces.
pub unsafe fn foreground_style_of(
    view: &ViewHandle,
    style: &[u8],
    style_meta: *const c_void,
    style_wt: *const c_void,
    modifier: &ModifierType,
) -> ViewHandle {
    unsafe {
        let (_, _, size) = modifier.applied_to(view.meta);
        let mut result = vec![0u8; size];
        let self_storage = view.value_ptr();
        let mut arg = style.to_vec();
        arg.resize(abi::type_bytes(style_meta).max(style.len()).max(1), 0);
        // foregroundStyle<S: ShapeStyle>(_:)
        //   x0 = @in style, x1 = Self.Type, x2 = S.Type,
        //   x3 = Self: View WT, x4 = S: ShapeStyle WT, x8 = @out, x20 = self
        core::arch::asm!("blr {f}", f = in(reg) resolve::foreground_style_fn(),
            in("x0") arg.as_mut_ptr(),
            in("x1") view.meta,
            in("x2") style_meta,
            in("x3") view.wt,
            in("x4") style_wt,
            in("x8") result.as_mut_ptr(),
            in("x20") self_storage,
            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_modified(result, modifier, view)
    }
}

// ── Typography ──

// `.font(_:)` writes `Font?` into the environment; `.italic()`, `.bold()`,
// `.fontWeight()`, `.fontDesign()` and `.monospaced()` all funnel through the
// same environment-transform modifier.
mangle::modifier_types! {
    /// `.kerning(_:)`, `.tracking(_:)` and `.lineSpacing(_:)` share a result type.
    /// `ModifiedContent<AnyView, _EnvironmentKeyWritingModifier<CoreGraphics.CGFloat>>`
    pub(crate) CGFLOAT_ENV_T = ty("_EnvironmentKeyWritingModifier").of(vec![Type::Nominal { module: "CoreGraphics", path: vec!["CGFloat"], kind: Kind::Struct }]);
    /// `.lineLimit(_:)`
    /// `ModifiedContent<AnyView, _EnvironmentKeyWritingModifier<Int?>>`
    pub(crate) LINE_LIMIT_T = ty("_EnvironmentKeyWritingModifier").of(vec![opt(Type::Verbatim("Si".into()))]);
    /// `.multilineTextAlignment(_:)`
    /// `ModifiedContent<AnyView, _EnvironmentKeyWritingModifier<TextAlignment>>`
    pub(crate) TEXT_ALIGN_T = ty("_EnvironmentKeyWritingModifier").of(vec![ty_enum("TextAlignment")]);
}



/// `SwiftUI.Font.Weight`. The values are Doubles behind the scenes; these are
/// the named steps SwiftUI exposes.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Weight {
    UltraLight,
    Thin,
    Light,
    Regular,
    Medium,
    Semibold,
    Bold,
    Heavy,
    Black,
}

impl Weight {
    pub(crate) fn getter(self) -> &'static core::ffi::CStr {
        match self {
            Weight::UltraLight => c"$s7SwiftUI4FontV6WeightV10ultraLightAEvgZ",
            Weight::Thin => c"$s7SwiftUI4FontV6WeightV4thinAEvgZ",
            Weight::Light => c"$s7SwiftUI4FontV6WeightV5lightAEvgZ",
            Weight::Regular => c"$s7SwiftUI4FontV6WeightV7regularAEvgZ",
            Weight::Medium => c"$s7SwiftUI4FontV6WeightV6mediumAEvgZ",
            Weight::Semibold => c"$s7SwiftUI4FontV6WeightV8semiboldAEvgZ",
            Weight::Bold => c"$s7SwiftUI4FontV6WeightV4boldAEvgZ",
            Weight::Heavy => c"$s7SwiftUI4FontV6WeightV5heavyAEvgZ",
            Weight::Black => c"$s7SwiftUI4FontV6WeightV5blackAEvgZ",
        }
    }

    /// The raw `Font.Weight` payload (a Double, returned in d0).
    pub fn value(self) -> f64 {
        unsafe { static_getter_f64(resolve::require(self.getter()), resolve::font_weight_meta()) }
    }
}

/// `SwiftUI.Font.Design`, in declaration order.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(u8)]
pub enum Design {
    Default = 0,
    Serif = 1,
    Rounded = 2,
    Monospaced = 3,
}

/// `SwiftUI.Font.TextStyle` presets, reached through their static getters.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum TextStyle {
    LargeTitle,
    Title,
    Title2,
    Title3,
    Headline,
    Subheadline,
    Body,
    Callout,
    Footnote,
    Caption,
    Caption2,
}

impl TextStyle {
    pub(crate) fn getter(self) -> &'static core::ffi::CStr {
        match self {
            TextStyle::LargeTitle => c"$s7SwiftUI4FontV10largeTitleACvgZ",
            TextStyle::Title => c"$s7SwiftUI4FontV5titleACvgZ",
            TextStyle::Title2 => c"$s7SwiftUI4FontV6title2ACvgZ",
            TextStyle::Title3 => c"$s7SwiftUI4FontV6title3ACvgZ",
            TextStyle::Headline => c"$s7SwiftUI4FontV8headlineACvgZ",
            TextStyle::Subheadline => c"$s7SwiftUI4FontV11subheadlineACvgZ",
            TextStyle::Body => c"$s7SwiftUI4FontV4bodyACvgZ",
            TextStyle::Callout => c"$s7SwiftUI4FontV7calloutACvgZ",
            TextStyle::Footnote => c"$s7SwiftUI4FontV8footnoteACvgZ",
            TextStyle::Caption => c"$s7SwiftUI4FontV7captionACvgZ",
            TextStyle::Caption2 => c"$s7SwiftUI4FontV8caption2ACvgZ",
        }
    }
}

/// Build `Font.system(size:weight:design:)`.
///
/// `design` is `Optional<Font.Design>`, passed indirectly; its `nil`
/// representation comes from the value witness table rather than being assumed,
/// since it depends on how many cases the enum has.
/// # Safety
/// SwiftUI must be loaded. The returned word is a `+1` `Font`.
pub unsafe fn system_font_full(size: f64, weight: Option<Weight>, design: Option<Design>) -> u64 {
    let mut design_buf = unsafe { optional_design(design) };

    // Optional<Font.Weight>: payload in x0 (Font.Weight wraps a Double), tag in x1.
    let (payload, tag) = match weight {
        Some(w) => (w.value().to_bits(), 0u64),
        None => (0u64, 1u64),
    };

    let font: u64;
    unsafe {
        core::arch::asm!("blr {f}", f = in(reg) resolve::font_system(),
            in("d0") size,
            in("x0") payload,
            in("x1") tag,
            in("x2") design_buf.as_mut_ptr(),
            in("x20") resolve::font_meta(),
            lateout("x0") font,
            lateout("x1") _, 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"),
        );
    }
    font
}

/// Build `Font.custom(_:size:)`.
/// # Safety
/// As [`system_font_full`].
pub unsafe fn custom_font(name: &str, size: f64) -> u64 {
    let ss = unsafe { abi::swift_string(name) };
    let s0 = u64::from_le_bytes(ss[..8].try_into().unwrap());
    let s1 = u64::from_le_bytes(ss[8..].try_into().unwrap());
    let font: u64;
    unsafe {
        core::arch::asm!("blr {f}", f = in(reg) resolve::font_custom(),
            in("x0") s0, in("x1") s1, in("d0") size,
            in("x20") resolve::font_meta(),
            lateout("x0") font,
            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"),
        );
    }
    font
}

/// A reusable `SwiftUI.Font`.
///
/// Building a font is expensive — SwiftUI resolves it through the text system,
/// which costs tens of microseconds — while *applying* one costs a few hundred
/// nanoseconds. Building it once and reusing the handle is the difference
/// between roughly 66 µs and 0.4 µs per view.
///
/// ```ignore
/// let title = Font::system(28.0, Some(Weight::Bold), None);
/// let ui = vstack![
///     text("Heading").font_ref(&title),
///     text("Another").font_ref(&title),
/// ];
/// ```
pub struct Font(u64);

impl Font {
    /// `Font.system(size:weight:design:)`
    pub fn system(size: f64, weight: Option<Weight>, design: Option<Design>) -> Self {
        Self(unsafe { system_font_full(size, weight, design) })
    }

    /// `Font.custom(_:size:)`
    pub fn custom(name: &str, size: f64) -> Self {
        Self(unsafe { custom_font(name, size) })
    }

    /// One of the built-in text styles.
    pub fn text_style(style: TextStyle) -> Self {
        Self(unsafe {
            let (f, _) = static_getter(resolve::require(style.getter()), resolve::font_meta());
            f
        })
    }

    /// The raw `Font` word, for the `font_apply` form that takes one.
    pub fn raw(&self) -> u64 {
        self.0
    }

}

impl Clone for Font {
    fn clone(&self) -> Self {
        unsafe { swift_runtime_sys::RuntimeRaw::swift_retain(self.0 as *mut c_void) };
        Self(self.0)
    }
}

impl Drop for Font {
    fn drop(&mut self) {
        unsafe { swift_runtime_sys::RuntimeRaw::swift_release(self.0 as *mut c_void) };
    }
}

/// Apply a prebuilt [`Font`] with `.font(_:)`.
pub fn font_ref(view: &ViewHandle, font: &Font) -> ViewHandle {
    unsafe { apply_font(view, font.raw()) }
}

/// Apply an already-built raw `Font` value with `.font(_:)`.
pub fn font_apply(view: &ViewHandle, font: u64) -> ViewHandle {
    unsafe { apply_font(view, font) }
}

/// Apply an already-built `Font` value with `.font(_:)`.
pub(crate) unsafe fn apply_font(view: &ViewHandle, font: u64) -> ViewHandle {
    unsafe {
        let (_, _, size) = FONT_T.applied_to(view.meta);
        let r = abi::call_modifier(resolve::font_fn(), view.value_ptr(), view.meta, view.wt, &[font], [0.0; 4], size);
        wrap_modified(r, &FONT_T, view)
    }
}

/// Apply `.font(.system(size:weight:design:))`.
pub fn font_system(
    view: &ViewHandle,
    size: f64,
    weight: Option<Weight>,
    design: Option<Design>,
) -> ViewHandle {
    unsafe { apply_font(view, system_font_full(size, weight, design)) }
}

/// Apply `.font(.custom(_:size:))`.
pub fn font_custom(view: &ViewHandle, name: &str, size: f64) -> ViewHandle {
    unsafe { apply_font(view, custom_font(name, size)) }
}

/// Apply `.font(_:)` with one of the built-in text styles.
pub fn font_text_style(view: &ViewHandle, style: TextStyle) -> ViewHandle {
    unsafe {
        let (f, _) = static_getter(resolve::require(style.getter()), resolve::font_meta());
        apply_font(view, f)
    }
}

/// Apply `.italic()`.
pub fn italic(view: &ViewHandle) -> ViewHandle {
    unsafe {
        let (_, _, size) = BOLD_T.applied_to(view.meta);
        let r = abi::call_modifier(resolve::italic_fn(), view.value_ptr(), view.meta, view.wt, &[1], [0.0; 4], size);
        wrap_modified(r, &BOLD_T, view)
    }
}

/// Apply `.monospaced()`.
pub fn monospaced(view: &ViewHandle) -> ViewHandle {
    unsafe {
        let (_, _, size) = BOLD_T.applied_to(view.meta);
        let r = abi::call_modifier(resolve::monospaced_fn(), view.value_ptr(), view.meta, view.wt, &[1], [0.0; 4], size);
        wrap_modified(r, &BOLD_T, view)
    }
}

/// Apply `.fontWeight(_:)`.
pub fn font_weight(view: &ViewHandle, weight: Weight) -> ViewHandle {
    unsafe {
        let (_, _, size) = BOLD_T.applied_to(view.meta);
        // Optional<Font.Weight>: payload then tag (0 == some).
        let r = abi::call_modifier(resolve::font_weight_fn(), view.value_ptr(), view.meta, view.wt,
            &[weight.value().to_bits(), 0],
            [0.0; 4],
            size,
        );
        wrap_modified(r, &BOLD_T, view)
    }
}

/// Build an `Optional<Font.Design>` buffer.
///
/// `Font.Design` is a resilient enum from another module, so it is address-only
/// — every API that takes one takes it *indirectly*, by pointer.
pub(crate) unsafe fn optional_design(design: Option<Design>) -> Vec<u8> {
    let meta = unsafe { crate::type_by_name!(swift_type!(opt enum SwiftUI.Font.Design).as_bytes()) };
    assert!(!meta.is_null(), "Optional<Font.Design> metadata");
    let mut buf = vec![0u8; unsafe { abi::type_bytes(meta) }];
    match design {
        Some(d) => buf[0] = d as u8,
        None => unsafe { abi::store_optional_tag(&mut buf, design_payload_meta(), false) },
    }
    buf
}

/// `Font.Design`'s own metadata — the payload of `Optional<Font.Design>`.
pub(crate) fn design_payload_meta() -> *const c_void {
    let meta = unsafe { crate::type_by_name!(swift_type!(enum SwiftUI.Font.Design).as_bytes()) };
    assert!(!meta.is_null(), "Font.Design metadata");
    meta
}

/// Apply `.fontDesign(_:)`.
pub fn font_design(view: &ViewHandle, design: Design) -> ViewHandle {
    unsafe {
        let (_, _, size) = BOLD_T.applied_to(view.meta);
        let mut buf = optional_design(Some(design));
        let r = abi::call_modifier(resolve::font_design_fn(), view.value_ptr(), view.meta, view.wt,
            &[buf.as_mut_ptr() as u64],
            [0.0; 4],
            size,
        );
        wrap_modified(r, &BOLD_T, view)
    }
}

/// Apply `.kerning(_:)`.
pub fn kerning(view: &ViewHandle, amount: f64) -> ViewHandle {
    unsafe {
        let (_, _, size) = CGFLOAT_ENV_T.applied_to(view.meta);
        let r = abi::call_modifier(resolve::kerning_fn(), view.value_ptr(), view.meta, view.wt, &[], [amount, 0.0, 0.0, 0.0], size);
        wrap_modified(r, &CGFLOAT_ENV_T, view)
    }
}

/// Apply `.tracking(_:)`.
pub fn tracking(view: &ViewHandle, amount: f64) -> ViewHandle {
    unsafe {
        let (_, _, size) = CGFLOAT_ENV_T.applied_to(view.meta);
        let r = abi::call_modifier(resolve::tracking_fn(), view.value_ptr(), view.meta, view.wt, &[], [amount, 0.0, 0.0, 0.0], size);
        wrap_modified(r, &CGFLOAT_ENV_T, view)
    }
}

/// Apply `.lineSpacing(_:)`.
pub fn line_spacing(view: &ViewHandle, amount: f64) -> ViewHandle {
    unsafe {
        let (_, _, size) = CGFLOAT_ENV_T.applied_to(view.meta);
        let r =
            abi::call_modifier(resolve::line_spacing_fn(), view.value_ptr(), view.meta, view.wt, &[], [amount, 0.0, 0.0, 0.0], size);
        wrap_modified(r, &CGFLOAT_ENV_T, view)
    }
}

/// Apply `.lineLimit(_:)`.
pub fn line_limit(view: &ViewHandle, limit: Option<i64>) -> ViewHandle {
    unsafe {
        let (_, _, size) = LINE_LIMIT_T.applied_to(view.meta);
        // Optional<Int>: payload then tag (0 == some).
        let ints = match limit {
            Some(n) => [n as u64, 0],
            None => [0, 1],
        };
        let r = abi::call_modifier(resolve::line_limit_fn(), view.value_ptr(), view.meta, view.wt, &ints, [0.0; 4], size);
        wrap_modified(r, &LINE_LIMIT_T, view)
    }
}

/// `SwiftUI.TextAlignment`, in declaration order.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[repr(u8)]
pub enum TextAlign {
    Leading = 0,
    Center = 1,
    Trailing = 2,
}

/// Apply `.multilineTextAlignment(_:)`.
pub fn multiline_alignment(view: &ViewHandle, align: TextAlign) -> ViewHandle {
    unsafe {
        let (_, _, size) = TEXT_ALIGN_T.applied_to(view.meta);
        let r = abi::call_modifier(resolve::multiline_align_fn(), view.value_ptr(), view.meta, view.wt,
            &[align as u64],
            [0.0; 4],
            size,
        );
        wrap_modified(r, &TEXT_ALIGN_T, view)
    }
}

/// `Locale.Language(languageCode: .thai)`.
///
/// `Locale.LanguageCode.thai` has no symbol — it is `@inlinable`, and so is the
/// `init(stringLiteral:)` it reduces to. But the value it produces is plain:
/// dumping `.thai` gives thirty-two bytes that are the small string `"th"`
/// twice over, so the code can be laid out here without calling anything. The
/// `Language` initialiser around it *is* exported, and takes all three of its
/// optionals by address.
pub fn locale_language_thai() -> Vec<u8> {
    unsafe {
        let code_meta = abi::metadata0(resolve::language_code_ma());
        assert!(!code_meta.is_null(), "Locale.LanguageCode metadata");
        let opt_code = abi::resolve_type_by_mangled_name(b"10Foundation6LocaleV12LanguageCodeVSg");
        assert!(!opt_code.is_null(), "Optional<Locale.LanguageCode>");

        let th = abi::swift_string("th");
        let mut code = vec![0u8; abi::type_bytes(opt_code)];
        code[..16].copy_from_slice(&th);
        code[16..32].copy_from_slice(&th);

        let mut script = nil_of(b"10Foundation6LocaleV6ScriptVSg");
        let mut region = nil_of(b"10Foundation6LocaleV6RegionVSg");

        let lang_meta = abi::metadata0(resolve::locale_language_ma());
        assert!(!lang_meta.is_null(), "Locale.Language metadata");
        let mut out = vec![0u8; abi::type_bytes(lang_meta)];
        core::arch::asm!("blr {f}", f = in(reg) resolve::locale_language_init(),
            in("x0") code.as_mut_ptr(),
            in("x1") script.as_mut_ptr(),
            in("x2") region.as_mut_ptr(),
            in("x8") out.as_mut_ptr(),
            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"),
        );
        out
    }
}

/// A `nil` of the optional named by `mangled`, using its own enum witness.
unsafe fn nil_of(mangled: &[u8]) -> Vec<u8> {
    unsafe {
        let meta = abi::resolve_type_by_mangled_name(mangled);
        assert!(!meta.is_null(), "{}", crate::mangle::demangle(&String::from_utf8_lossy(mangled)));
        let mut buf = vec![0u8; abi::type_bytes(meta)];
        abi::inject_enum_tag(&mut buf, meta, 1);
        buf
    }
}

/// `Text(verbatim:)` — the string as written, with no localisation lookup.
pub fn text_verbatim(s: &str) -> ViewHandle {
    unsafe { wrap_text(text_verbatim_words(s)) }
}

/// The four words a verbatim `Text` occupies.
/// # Safety
/// SwiftUI must be loaded. The four words are a `+1` `Text` and must be given
/// to something that takes ownership, or released.
pub unsafe fn text_verbatim_words(s: &str) -> [u64; 4] {
    unsafe {
        let ss = abi::swift_string(s);
        let s0 = u64::from_le_bytes(ss[..8].try_into().expect("lo"));
        let s1 = u64::from_le_bytes(ss[8..].try_into().expect("hi"));
        // A `Text` is `{ i64, i64, i8, ptr }` — four registers out, which is
        // one more than `call_regs` reports.
        let (t0, t1, t2, t3): (u64, u64, u64, u64);
        core::arch::asm!("blr {f}", f = in(reg) resolve::text_verbatim_init(),
            inout("x0") s0 => t0, inout("x1") s1 => t1,
            lateout("x2") t2, lateout("x3") t3,
            in("x20") resolve::text_meta(),
            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"),
        );
        [t0, t1, t2, t3]
    }
}

/// `Text.typesettingLanguage(_:isEnabled:)` with a `Locale.Language`.
///
/// The language goes by address in x0, `isEnabled` in x1, and the receiving
/// `Text`'s four words follow in x2 through x5 — a `Text` is not `self` in x20
/// here, because this is a method on a struct that returns a new one and the
/// compiler passes it like any other argument.
pub fn text_typesetting_language(words: [u64; 4], language: &[u8], enabled: bool) -> ViewHandle {
    unsafe { wrap_text(typesetting_call(resolve::text_typesetting_language_fn(), words, language, enabled)) }
}

/// `Text.typesettingLanguage(_:isEnabled:)` with `.explicit(_:)`.
pub fn text_typesetting_explicit(words: [u64; 4], language: &[u8], enabled: bool) -> ViewHandle {
    unsafe {
        let meta = abi::metadata0(resolve::typesetting_language_ma());
        assert!(!meta.is_null(), "TypesettingLanguage metadata");
        let mut lang = language.to_vec();
        let mut explicit = vec![0u8; abi::type_bytes(meta)];
        core::arch::asm!("blr {f}", f = in(reg) resolve::typesetting_explicit_of(),
            in("x0") lang.as_mut_ptr(),
            in("x8") explicit.as_mut_ptr(),
            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"),
        );
        wrap_text(typesetting_call(
            resolve::text_typesetting_explicit_fn(),
            words,
            &explicit,
            enabled,
        ))
    }
}

unsafe fn typesetting_call(
    func: *const c_void,
    words: [u64; 4],
    value: &[u8],
    enabled: bool,
) -> [u64; 4] {
    unsafe {
        let mut arg = value.to_vec();
        let (t0, t1, t2, t3): (u64, u64, u64, u64);
        core::arch::asm!("blr {f}", f = in(reg) func,
            inout("x0") arg.as_mut_ptr() => t0,
            inout("x1") u64::from(enabled) => t1,
            inout("x2") words[0] => t2,
            inout("x3") words[1] => t3,
            in("x4") words[2], in("x5") words[3],
            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"),
        );
        [t0, t1, t2, t3]
    }
}

/// A `Text`'s four words, as a view.
pub(crate) unsafe fn wrap_text(words: [u64; 4]) -> ViewHandle {
    unsafe {
        ViewHandle::wrap(
            words.as_ptr() as *const c_void,
            resolve::text_meta(),
            resolve::text_wt(),
        )
    }
}

// ── `Text`'s own modifiers ───────────────────────────────────────────────────
//
// SwiftUI declares `bold`, `italic`, `font` and their neighbours twice: once on
// `Text`, returning `Text`, and once as a `View` extension that writes the
// environment for everything below it. The two are not interchangeable — the
// Swift in Apple's own documentation reaches the first and produces `Text`,
// while going through the second produces
// `ModifiedContent<Text, _EnvironmentKeyTransformModifier<…>>`. Same pixels,
// different type, and type identity is the check that notices.
//
// `Text` lowers to `{ i64, i64, i8, ptr }` and travels in registers rather than
// indirectly, so these are register-in/register-out calls with the arguments
// first and `self` last — read off the IR rather than assumed.

/// The four words of a `Text` value.
///
/// # Safety
/// `view` must hold a `SwiftUI.Text`.
unsafe fn text_words(view: &ViewHandle) -> (u64, u64, u64, u64) {
    unsafe {
        let p = view.value_ptr() as *const u8;
        (
            (p as *const u64).read_unaligned(),
            (p.add(8) as *const u64).read_unaligned(),
            u64::from(p.add(16).read()),
            (p.add(24) as *const u64).read_unaligned(),
        )
    }
}

/// Put four returned words back into a `Text`-shaped buffer.
///
/// # Safety
/// `view` must be the `Text` the call was made on, so its metadata describes the
/// result too — every one of these returns `Text`.
unsafe fn text_from_words(view: &ViewHandle, w: (u64, u64, u64, u64)) -> ViewHandle {
    unsafe {
        let mut out = vec![0u8; abi::type_bytes(view.meta)];
        let p: *mut u8 = out.as_mut_ptr();
        (p as *mut u64).write_unaligned(w.0);
        (p.add(8) as *mut u64).write_unaligned(w.1);
        p.add(16).write(w.2 as u8);
        (p.add(24) as *mut u64).write_unaligned(w.3);
        super::wrap_owned(out, view.meta, view.wt)
    }
}

/// Is this handle a `SwiftUI.Text`?
///
/// Every function below reinterprets the handle's bytes as `Text`'s four fields,
/// so handing one anything else would read whatever happened to be there.
fn is_text(view: &ViewHandle) -> bool {
    crate::diag::type_name(view.meta) == "SwiftUI.Text"
}

/// Call a `Text` method that takes no arguments.
///
/// `self` is the four fields in x0-x3 and the result comes back the same way.
///
/// # Safety
/// `f` must be a `Text` method of this shape and `view` must hold a `Text`.
unsafe fn text_call0(view: &ViewHandle, f: *const c_void) -> ViewHandle {
    unsafe {
        let (a, b, c, d) = text_words(view);
        let (r0, r1, r2, r3): (u64, u64, u64, u64);
        core::arch::asm!("blr {f}", f = in(reg) f,
            inout("x0") a => r0, inout("x1") b => r1,
            inout("x2") c => r2, inout("x3") d => r3,
            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"),
        );
        text_from_words(view, (r0, r1, r2, r3))
    }
}

/// Call a `Text` method taking one word, which lands ahead of `self`.
///
/// # Safety
/// As [`text_call0`], and `w` must be the argument that method expects.
unsafe fn text_call1(view: &ViewHandle, f: *const c_void, w: u64) -> ViewHandle {
    unsafe {
        let (a, b, c, d) = text_words(view);
        let (r0, r1, r2, r3): (u64, u64, u64, u64);
        core::arch::asm!("blr {f}", f = in(reg) f,
            inout("x0") w => r0, inout("x1") a => r1,
            inout("x2") b => r2, inout("x3") c => r3,
            inout("x4") d => _,
            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"),
        );
        text_from_words(view, (r0, r1, r2, r3))
    }
}

/// Call a `Text` method taking one `CGFloat`, which travels in d0 while `self`
/// stays in x0-x3.
///
/// # Safety
/// As [`text_call0`].
unsafe fn text_call_f64(view: &ViewHandle, f: *const c_void, x: f64) -> ViewHandle {
    unsafe {
        let (a, b, c, d) = text_words(view);
        let (r0, r1, r2, r3): (u64, u64, u64, u64);
        core::arch::asm!("blr {f}", f = in(reg) f,
            in("d0") x,
            inout("x0") a => r0, inout("x1") b => r1,
            inout("x2") c => r2, inout("x3") d => r3,
            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"),
        );
        text_from_words(view, (r0, r1, r2, r3))
    }
}

/// `Text.bold()` — the one that returns `Text`.
///
/// Returns the `View` extension's result if this is not a `Text`: that is what a
/// caller wants there, and it is what every one of these used to do.
pub fn text_bold(view: &ViewHandle) -> ViewHandle {
    if !is_text(view) {
        return super::bold(view);
    }
    unsafe { text_call0(view, resolve::text_bold()) }
}

/// `Text.italic()`
pub fn text_italic(view: &ViewHandle) -> ViewHandle {
    if !is_text(view) {
        return super::italic(view);
    }
    unsafe { text_call0(view, resolve::text_italic()) }
}

/// `Text.monospaced(_:)`
pub fn text_monospaced(view: &ViewHandle) -> ViewHandle {
    if !is_text(view) {
        return super::monospaced(view);
    }
    unsafe { text_call1(view, resolve::text_monospaced(), 1) }
}

/// `Text.foregroundColor(_:)` — the overload that returns `Text`.
pub fn text_foreground_color(view: &ViewHandle, color: crate::Color) -> ViewHandle {
    if !is_text(view) {
        return super::foreground_style_color(view, color.r, color.g, color.b, color.a);
    }
    unsafe { text_call1(view, resolve::text_fg_color(), super::color_value_of(color)) }
}

/// `Text.kerning(_:)` — space added between every pair of characters.
pub fn text_kerning(view: &ViewHandle, amount: f64) -> ViewHandle {
    if !is_text(view) {
        return super::kerning(view, amount);
    }
    unsafe { text_call_f64(view, resolve::text_kerning(), amount) }
}

/// `Text.tracking(_:)` — like kerning, but not suppressed between the pairs the
/// font has a ligature for.
pub fn text_tracking(view: &ViewHandle, amount: f64) -> ViewHandle {
    if !is_text(view) {
        return super::tracking(view, amount);
    }
    unsafe { text_call_f64(view, resolve::text_tracking(), amount) }
}

/// `Text.baselineOffset(_:)`
pub fn text_baseline_offset(view: &ViewHandle, amount: f64) -> ViewHandle {
    if !is_text(view) {
        return view.clone();
    }
    unsafe { text_call_f64(view, resolve::text_baseline(), amount) }
}
/// `Text.font(_:)` — the overload that returns `Text`.
///
/// `Text("x").font(.body).bold()` stays a `Text` all the way through in Swift
/// precisely because this returns one; going through the `View` extension for
/// the font is what made the rest of the chain fall back to the environment
/// forms. `None` clears the font.
pub fn text_font(view: &ViewHandle, font: Option<&super::Font>) -> ViewHandle {
    if !is_text(view) {
        return match font {
            Some(f) => super::font_ref(view, f),
            None => view.clone(),
        };
    }
    unsafe { text_call1(view, resolve::text_font(), font.map_or(0, super::Font::raw)) }
}

/// `Text.fontWeight(_:)` — the overload that returns `Text`.
///
/// `Font.Weight?` lowers to two words, a payload and a tag, which land ahead of
/// `self` — so this is the one shape the single-word helper cannot serve.
/// `None` clears the weight.
pub fn text_font_weight(view: &ViewHandle, weight: Option<super::Weight>) -> ViewHandle {
    if !is_text(view) {
        return match weight {
            Some(w) => super::font_weight(view, w),
            None => view.clone(),
        };
    }
    unsafe {
        let (a, b, c, d) = text_words(view);
        // The payload is the weight's own value; the tag is 0 for `some` and 1
        // for `none`, which is how a single-payload optional of a non-pointer
        // type is spelled.
        let (w0, w1) = match weight {
            // `Font.Weight` is a wrapper around a `CGFloat`, which is what the
            // `View` extension next door passes too.
            Some(w) => (w.value().to_bits(), 0u64),
            None => (0, 1),
        };
        let (r0, r1, r2, r3): (u64, u64, u64, u64);
        core::arch::asm!("blr {f}", f = in(reg) resolve::text_font_weight(),
            inout("x0") w0 => r0, inout("x1") w1 => r1,
            inout("x2") a => r2, inout("x3") b => r3,
            inout("x4") c => _, inout("x5") d => _,
            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"),
        );
        text_from_words(view, (r0, r1, r2, r3))
    }
}

/// `Text.foregroundStyle(_:)` — the overload that returns `Text`.
///
/// Generic over `ShapeStyle`, so the style travels `@in` with its metadata and
/// witness after `self`: `(@in S, self…, S.Type, S: ShapeStyle)` — read off the
/// IR. This is what a gradient-filled `Text` needs; the `View` extension next
/// door wraps it in a `_ForegroundStyleModifier` instead.
///
/// # Safety
/// `style` must be a value of the type `style_meta` describes, and `style_wt`
/// its `ShapeStyle` conformance.
pub unsafe fn text_foreground_style(
    view: &ViewHandle,
    style: &[u8],
    style_meta: *const c_void,
    style_wt: *const c_void,
) -> ViewHandle {
    if !is_text(view) {
        return unsafe { foreground_style_of(view, style, style_meta, style_wt, &FOREGROUND_GRADIENT_T) };
    }
    unsafe {
        let (a, b, c, d) = text_words(view);
        let mut buf = style.to_vec();
        let (r0, r1, r2, r3): (u64, u64, u64, u64);
        core::arch::asm!("blr {f}", f = in(reg) resolve::text_fg_style(),
            inout("x0") buf.as_mut_ptr() as u64 => r0,
            inout("x1") a => r1, inout("x2") b => r2, inout("x3") c => r3,
            inout("x4") d => _,
            in("x5") style_meta, in("x6") style_wt,
            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"),
        );
        text_from_words(view, (r0, r1, r2, r3))
    }
}

/// `Text.foregroundStyle(LinearGradient(...))`.
pub fn text_foreground_linear_gradient(
    view: &ViewHandle,
    colors: &[u64],
    start: (f64, f64),
    end: (f64, f64),
) -> ViewHandle {
    let (style, meta, wt) = super::linear_gradient_style_of(colors, start, end);
    unsafe { text_foreground_style(view, &style, meta, wt) }
}

/// `Text.foregroundStyle(_:)` with one of the hierarchical styles.
pub fn text_foreground_hierarchical(
    view: &ViewHandle,
    level: super::Hierarchical,
) -> ViewHandle {
    let (style, meta, wt) = super::hierarchical_style(level);
    unsafe { text_foreground_style(view, &style, meta, wt) }
}