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
//! Stacks.
//!
//! * Label and lazy stacks

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

// ── Stacks ──

#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum StackKind {
    V,
    H,
    Z,
}

/// `VStack` from children.
pub fn vstack(children: &[ViewHandle]) -> ViewHandle {
    stack_impl(children, StackKind::V)
}

/// `HStack` from children.
pub fn hstack(children: &[ViewHandle]) -> ViewHandle {
    stack_impl(children, StackKind::H)
}

/// `ZStack` from children, centred.
pub fn zstack(children: &[ViewHandle]) -> ViewHandle {
    stack_impl(children, StackKind::Z)
}

/// `ZStack(alignment:)` from children.
pub fn zstack_aligned(children: &[ViewHandle], alignment: super::Alignment) -> ViewHandle {
    match children.len() {
        0 => empty_view(),
        _ => unsafe { build_stack_aligned(children, StackKind::Z, None, alignment) },
    }
}

pub(crate) fn stack_impl(children: &[ViewHandle], axis: StackKind) -> ViewHandle {
    stack_spaced(children, axis, None)
}

pub(crate) fn stack_spaced(children: &[ViewHandle], axis: StackKind, spacing: Option<f64>) -> ViewHandle {
    match children.len() {
        0 => empty_view(),
        // A lone child is passed through rather than wrapped. Note this is not
        // identical to Swift's `VStack { x }`: a `ForEach` that is the *only*
        // child needs a real stack around it, or its rows overlay each other.
        // Give such a stack a second child (a `spacer`, say).
        1 if spacing.is_none() => children[0].clone(),
        _ => unsafe { build_stack(children, axis, spacing) },
    }
}

/// `VStack(alignment:)` from children.
pub fn vstack_aligned(
    children: &[ViewHandle],
    alignment: super::HorizontalAlignment,
) -> ViewHandle {
    vstack_aligned_spacing(children, alignment, None)
}

/// `VStack(alignment:spacing:)` from children.
pub fn vstack_aligned_spacing(
    children: &[ViewHandle],
    alignment: super::HorizontalAlignment,
    spacing: Option<f64>,
) -> ViewHandle {
    unsafe {
        build_stack_aligned_h(
            children,
            StackKind::V,
            spacing,
            super::Alignment::Center,
            Some(alignment),
            None,
        )
    }
}

/// `HStack(alignment:)` from children.
pub fn hstack_aligned(
    children: &[ViewHandle],
    alignment: super::VerticalAlignment,
) -> ViewHandle {
    hstack_aligned_spacing(children, alignment, None)
}

/// `HStack(alignment:spacing:)` from children.
pub fn hstack_aligned_spacing(
    children: &[ViewHandle],
    alignment: super::VerticalAlignment,
    spacing: Option<f64>,
) -> ViewHandle {
    unsafe {
        build_stack_aligned_h(
            children,
            StackKind::H,
            spacing,
            super::Alignment::Center,
            None,
            Some(alignment),
        )
    }
}

/// `VStack(spacing:)` from children.
pub fn vstack_spacing(children: &[ViewHandle], spacing: f64) -> ViewHandle {
    stack_spaced(children, StackKind::V, Some(spacing))
}

/// `HStack(spacing:)` from children.
pub fn hstack_spacing(children: &[ViewHandle], spacing: f64) -> ViewHandle {
    stack_spaced(children, StackKind::H, Some(spacing))
}

/// One child of a `@ViewBuilder` body: its bytes, its type, and where in the
/// tuple the runtime decided to put it.
#[repr(C)]
pub(crate) struct TupleChild {
    pub(crate) value: *const c_void,
    pub(crate) meta: *const c_void,
    pub(crate) offset: usize,
}

/// What the content closure needs to emit the tuple.
#[repr(C)]
pub(crate) struct TuplePayload {
    pub(crate) children: *const TupleChild,
    pub(crate) count: usize,
}

/// `@ViewBuilder content` body — writes `TupleView<(A, B, ...)>` to `out`.
///
/// One `initialize_with_copy` per child, at the offset the tuple's own metadata
/// gives. That is the general form of the `swift_retain`-per-word this used to
/// do: a child is a value of its own type now, not a reference to an `AnyView`
/// box, so copying it means asking its value witness rather than assuming one
/// word and one reference count.
///
/// The stack takes ownership of what the closure returns, so each child is
/// copied on the way out and the caller keeps its own.
pub(crate) unsafe extern "C" fn emit_tuple(out: *mut u8, payload: *mut c_void) {
    let p = unsafe { &*(payload as *const TuplePayload) };
    for i in 0..p.count {
        let c = unsafe { &*p.children.add(i) };
        let vwt = unsafe { &*swift_runtime_sys::SwiftABI::get_value_witness_table(c.meta) };
        if vwt.size > 0 {
            unsafe {
                (vwt.initialize_with_copy)(
                    out.add(c.offset) as *mut c_void,
                    c.value as *mut c_void,
                    c.meta,
                );
            }
        }
    }
}

/// How a container names the type of its content.
///
/// This is not a style choice — it follows from how the container's own type is
/// obtained. A container composed from its content's metadata (`VStack`,
/// `ScrollView`, the content-carrying modifiers) can hold the child at its own
/// type. One named by a fixed mangled string — `Grid<AnyView>`, `Menu<AnyView>`
/// — has `AnyView` written into that name, so the child has to be boxed to
/// match it. Passing a concrete child to such a container describes a value the
/// callee was never given, and it reads whatever is there.
///
/// Choosing wrongly is not a compile error, so the two cases are named here
/// rather than left to whoever is reading the call site.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum Content {
    /// The container composes its type from the child's; keep the child's type.
    Concrete,
    /// The container's type names `AnyView`; box the child to match.
    Erased,
}

/// One child of a `@ViewBuilder` body, held for as long as the closure needs it.
///
/// A non-escaping `content:` — the kind an initialiser calls before it returns —
/// could borrow, but an escaping one is called long after the binding returned.
/// Holding the value here covers both, and the boxed word for [`Content::Erased`]
/// needs an owner regardless.
pub(crate) struct Child {
    /// Kept alive for `Concrete`: the closure copies out of these bytes.
    handle: ViewHandle,
    /// Kept alive for `Erased`: the `AnyView` the closure copies.
    word: u64,
    kind: Content,
}

impl Child {
    pub(crate) fn new(view: &ViewHandle, kind: Content) -> Self {
        Child {
            handle: view.clone(),
            word: if kind == Content::Erased { view.to_anyview_word() } else { 0 },
            kind,
        }
    }

    /// The tuple element describing this child.
    pub(crate) fn element(&self) -> [TupleChild; 1] {
        match self.kind {
            Content::Concrete => [TupleChild {
                value: self.handle.value_ptr(),
                meta: self.handle.meta,
                offset: 0,
            }],
            Content::Erased => [TupleChild {
                value: &self.word as *const u64 as *const c_void,
                meta: resolve::anyview_meta(),
                offset: 0,
            }],
        }
    }

    /// Leak a payload for a closure SwiftUI stores, and return the pointer a
    /// `ClosureCtx` wants.
    pub(crate) fn leak(view: &ViewHandle, kind: Content) -> *mut c_void {
        let kept: &'static Child = Box::leak(Box::new(Child::new(view, kind)));
        let kids = Box::leak(Box::new(kept.element()));
        let payload = Box::leak(Box::new(TuplePayload { children: kids.as_ptr(), count: 1 }));
        payload as *mut TuplePayload as *mut c_void
    }
}

/// Read a Swift static property getter that returns a `Double` (in d0).
pub(crate) unsafe fn static_getter_f64(getter: *const c_void, meta: *const c_void) -> f64 {
    unsafe { abi::call_f64(getter, [0; 8], [0.0; 4], meta as u64) }
}

/// Read a Swift static property getter that returns up to two words.
pub(crate) unsafe fn static_getter(getter: *const c_void, meta: *const c_void) -> (u64, u64) {
    let r = unsafe { abi::static_regs(getter, meta) };
    (r[0], r[1])
}

/// What a `@ViewBuilder` body of `children` *is*, as a type.
///
/// `ViewBuilder` collapses a single element to the element itself, and two or
/// more to a `TupleView` of them — so `VStack { Text("a") }` is a
/// `VStack<Text>` and `VStack { Text("a"); Text("b") }` a
/// `VStack<TupleView<(Text, Text)>>`. Returns the content's metadata, its `View`
/// conformance, and where in a tuple value each child goes.
///
/// The elements are the children's own types. Spelling them `AnyView` here built
/// a real tuple of real boxes — it rendered, but it described a
/// `TupleView<(AnyView, AnyView)>` where the same Swift source builds
/// `TupleView<(Text, Image)>`, and no amount of care further up recovers a type
/// thrown away at the leaves.
///
/// The offsets are asked for rather than packed by hand: the runtime orders and
/// pads tuple elements by alignment, and children of their own types are not
/// uniformly one word.
///
/// # Panics
/// With no children at all — an empty `@ViewBuilder` body is `EmptyView` and has
/// no tuple, which is a different construction and a caller's decision.
pub(crate) unsafe fn tuple_content(
    children: &[ViewHandle],
) -> (*const c_void, *const c_void, Vec<usize>) {
    assert!(!children.is_empty(), "a `@ViewBuilder` body with no children is `EmptyView`");
    if children.len() == 1 {
        return (children[0].meta, children[0].wt, vec![0usize]);
    }
    unsafe {
        let elements: Vec<*const c_void> = children.iter().map(|c| c.meta).collect();
        let tuple_meta = abi::tuple_metadata(&elements);
        assert!(!tuple_meta.is_null(), "tuple metadata instantiation failed");
        let offsets = abi::tuple_element_offsets(tuple_meta, children.len());
        let m = abi::generic_metadata1(resolve::tupleview_ma(), tuple_meta);
        assert!(!m.is_null(), "TupleView metadata instantiation failed");
        let w = abi::get_view_wt(m);
        assert!(!w.is_null(), "{} !: View", crate::diag::type_name(m));
        (m, w, offsets)
    }
}

/// The tuple elements describing `children`, laid out at `offsets`.
///
/// Borrowed rather than leaked, so the caller must keep the children alive until
/// the closure that reads this has run. For a non-escaping `content:` — the kind
/// an initialiser calls before it returns — that is the enclosing scope.
pub(crate) fn tuple_children(children: &[ViewHandle], offsets: &[usize]) -> Vec<TupleChild> {
    children
        .iter()
        .zip(offsets)
        .map(|(c, &offset)| TupleChild { value: c.value_ptr(), meta: c.meta, offset })
        .collect()
}

/// Build a real `VStack`/`HStack`/`ZStack` over N children.
///
/// The content is a genuine `TupleView` with one element per child, so the stack
/// is flat — not a chain of nested two-child stacks.
pub(crate) unsafe fn build_stack(
    children: &[ViewHandle],
    axis: StackKind,
    spacing: Option<f64>,
) -> ViewHandle {
    unsafe { build_stack_aligned(children, axis, spacing, super::Alignment::Center) }
}

/// As [`build_stack`], with the alignment spelled out.
///
/// Only `ZStack` reads it: `VStack` and `HStack` take a `HorizontalAlignment`
/// and a `VerticalAlignment` respectively, which is a different argument from
/// the two-word `Alignment` a `ZStack` wants.
pub(crate) unsafe fn build_stack_aligned(
    children: &[ViewHandle],
    axis: StackKind,
    spacing: Option<f64>,
    alignment: super::Alignment,
) -> ViewHandle {
    unsafe { build_stack_aligned_h(children, axis, spacing, alignment, None, None) }
}

/// As [`build_stack_aligned`], and for a `VStack` also its `HorizontalAlignment`.
///
/// A `VStack` takes a `HorizontalAlignment` and an `HStack` a
/// `VerticalAlignment` — one word each, and a different argument from the
/// two-word `Alignment` a `ZStack` wants, which is why this is separate.
pub(crate) unsafe fn build_stack_aligned_h(
    children: &[ViewHandle],
    axis: StackKind,
    spacing: Option<f64>,
    alignment: super::Alignment,
    horizontal: Option<super::HorizontalAlignment>,
    vertical: Option<super::VerticalAlignment>,
) -> ViewHandle {
    let (content_meta, content_wt, offsets) = unsafe { tuple_content(children) };

    // Stack type: VStack<Content> — needs both Content.Type and Content: View.
    let stack_ma = match axis {
        StackKind::V => resolve::vstack_ma(),
        StackKind::H => resolve::hstack_ma(),
        StackKind::Z => resolve::zstack_ma(),
    };
    let stack_meta = unsafe { abi::generic_metadata2(stack_ma, content_meta, content_wt) };
    assert!(!stack_meta.is_null(), "stack metadata instantiation failed");
    let stack_wt = unsafe { abi::get_view_wt(stack_meta) };
    assert!(!stack_wt.is_null(), "{} !: View", crate::diag::type_name(stack_meta));

    // Borrowed, not leaked: a stack's `content` closure is called by the
    // initialiser before it returns, so the children outlive the call.
    let kids = tuple_children(children, &offsets);
    let payload = TuplePayload { children: kids.as_ptr(), count: kids.len() };
    let mut ctx = abi::ClosureCtx::new(emit_tuple, &payload as *const TuplePayload as *mut c_void);
    let thunk = abi::swift_closure_thunk as *const c_void;

    let mut result = vec![0u8; unsafe { abi::type_bytes(stack_meta) }];

    match axis {
        StackKind::V | StackKind::H => {
            // init(alignment:spacing:content:)
            //   x0 = alignment, x1 = spacing payload, x2 = spacing tag (1 = nil),
            //   x3 = closure fn, x4 = closure ctx,
            //   x5 = Content.Type, x6 = Content: View WT, x8 = @out
            let (align, _) = unsafe {
                match axis {
                    StackKind::V => static_getter(
                        horizontal.map_or_else(resolve::halign_center, |h| h.resolved()),
                        resolve::halign_meta(),
                    ),
                    _ => static_getter(
                        vertical.map_or_else(resolve::valign_center, |v| v.resolved()),
                        resolve::valign_meta(),
                    ),
                }
            };
            let init = if axis == StackKind::V { resolve::vstack_init() } else { resolve::hstack_init() };
            // Optional<CGFloat>: raw bits in one word, tag in the next (1 == nil).
            let (spacing_bits, spacing_tag) = match spacing {
                Some(v) => (v.to_bits(), 0u64),
                None => (0u64, 1u64),
            };
            unsafe {
                core::arch::asm!("blr {f}", f = in(reg) init,
                    in("x0") align,
                    in("x1") spacing_bits,
                    in("x2") spacing_tag,
                    in("x3") thunk,
                    in("x4") &mut ctx as *mut abi::ClosureCtx,
                    in("x5") content_meta,
                    in("x6") content_wt,
                    in("x8") result.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"),
                );
            }
        }
        StackKind::Z => {
            // init(alignment:content:)
            //   x0 = alignment.horizontal, x1 = alignment.vertical,
            //   x2 = closure fn, x3 = closure ctx,
            //   x4 = Content.Type, x5 = Content: View WT, x8 = @out
            let [h, v] = unsafe { alignment.words() };
            unsafe {
                core::arch::asm!("blr {f}", f = in(reg) resolve::zstack_init(),
                    in("x0") h,
                    in("x1") v,
                    in("x2") thunk,
                    in("x3") &mut ctx as *mut abi::ClosureCtx,
                    in("x4") content_meta,
                    in("x5") content_wt,
                    in("x8") result.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("x20") _, lateout("x21") _,
                    clobber_abi("C"),
                );
            }
        }
    }

    unsafe { wrap_owned(result, stack_meta, stack_wt) }
}

// ── Label and lazy stacks ──

mangle::result_types! {
    /// `SwiftUI.Label<SwiftUI.Text, SwiftUI.Image>`
    /// `Label<Text, Image>`
    pub(crate) LABEL_T = ty("Label").of(vec![ty("Text"), ty("Image")]);
}

/// Create a `Label(_:systemImage:)`.
pub fn label(title: &str, system_image: &str) -> ViewHandle {
    unsafe {
        let ss = abi::swift_string(title);
        let s0 = u64::from_le_bytes(ss[..8].try_into().unwrap());
        let s1 = u64::from_le_bytes(ss[8..].try_into().unwrap());
        let (k0, k1, k2, k3) = localized_string_key(s0, s1);

        let img = abi::swift_string(system_image);
        let i0 = u64::from_le_bytes(img[..8].try_into().unwrap());
        let i1 = u64::from_le_bytes(img[8..].try_into().unwrap());

        let (meta, wt, size) = result_type(&LABEL_T);
        let mut result = vec![0u8; size];
        // Label.init(_: LocalizedStringKey, systemImage: String)
        //   x0-x3 = key, x4/x5 = image name, x8 = @out
        core::arch::asm!("blr {f}", f = in(reg) resolve::label_init(),
            in("x0") k0, in("x1") k1, in("x2") k2, in("x3") k3,
            in("x4") i0, in("x5") i1,
            in("x8") result.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("x20") _, lateout("x21") _,
            clobber_abi("C"),
        );
        wrap_owned(result, meta, wt)
    }
}

/// Build a `LazyVStack` or `LazyHStack` over N children.
pub(crate) fn lazy_stack_impl(children: &[ViewHandle], vertical: bool) -> ViewHandle {
    lazy_stack_aligned_impl(children, vertical, None, None)
}

/// As [`lazy_stack_impl`], with the cross-axis alignment named. Only the one
/// matching the stack's axis is read; the other is ignored.
pub(crate) fn lazy_stack_aligned_impl(
    children: &[ViewHandle],
    vertical: bool,
    halign: Option<super::HorizontalAlignment>,
    valign: Option<super::VerticalAlignment>,
) -> ViewHandle {
    if children.is_empty() {
        return empty_view();
    }
    unsafe {
        // Same rule as `build_stack_aligned_h`: the children's own types, and a
        // single child is the content rather than a one-element tuple.
        let (content_meta, content_wt, offsets) = if children.len() == 1 {
            (children[0].meta, children[0].wt, vec![0usize])
        } else {
            let elements: Vec<*const c_void> = children.iter().map(|c| c.meta).collect();
            let tuple_meta = abi::tuple_metadata(&elements);
            let offsets = abi::tuple_element_offsets(tuple_meta, children.len());
            let m = abi::generic_metadata1(resolve::tupleview_ma(), tuple_meta);
            let w = abi::get_view_wt(m);
            assert!(!w.is_null(), "TupleView !: View");
            (m, w, offsets)
        };

        let ma = if vertical { resolve::lazy_vstack_ma() } else { resolve::lazy_hstack_ma() };
        let stack_meta = abi::generic_metadata2(ma, content_meta, content_wt);
        let stack_wt = abi::get_view_wt(stack_meta);
        assert!(!stack_wt.is_null(), "lazy stack !: View");

        let kids: Vec<TupleChild> = children
            .iter()
            .zip(&offsets)
            .map(|(c, &offset)| TupleChild { value: c.value_ptr(), meta: c.meta, offset })
            .collect();
        let payload = TuplePayload { children: kids.as_ptr(), count: kids.len() };
        let mut ctx =
            abi::ClosureCtx::new(emit_tuple, &payload as *const TuplePayload as *mut c_void);

        let (align, _) = if vertical {
            static_getter(
                halign.map_or_else(resolve::halign_center, |h| h.resolved()),
                resolve::halign_meta(),
            )
        } else {
            static_getter(
                valign.map_or_else(resolve::valign_center, |v| v.resolved()),
                resolve::valign_meta(),
            )
        };
        let init = if vertical { resolve::lazy_vstack_init() } else { resolve::lazy_hstack_init() };

        // `PinnedScrollableViews` is a resilient OptionSet, so it is
        // address-only and passed by pointer; all-zero bytes mean "empty".
        let pinned_meta = crate::type_by_name!(swift_type!(SwiftUI.PinnedScrollableViews).as_bytes());
        assert!(!pinned_meta.is_null(), "PinnedScrollableViews metadata");
        let mut pinned = vec![0u8; abi::type_bytes(pinned_meta)];

        let mut result = vec![0u8; abi::type_bytes(stack_meta)];
        // init(alignment:spacing:pinnedViews:content:)
        //   x0 = alignment, x1 = spacing payload, x2 = spacing tag (1 = nil),
        //   x3 = @in pinnedViews, x4 = closure fn, x5 = closure ctx,
        //   x6 = Content.Type, x7 = Content: View WT, x8 = @out
        core::arch::asm!("blr {f}", f = in(reg) init,
            in("x0") align,
            in("x1") 0u64,
            in("x2") 1u64,
            in("x3") pinned.as_mut_ptr(),
            in("x4") abi::swift_closure_thunk as *const c_void,
            in("x5") &mut ctx as *mut abi::ClosureCtx,
            in("x6") content_meta,
            in("x7") content_wt,
            in("x8") result.as_mut_ptr(),
            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, stack_meta, stack_wt)
    }
}

/// `LazyVStack` from children.
pub fn lazy_vstack(children: &[ViewHandle]) -> ViewHandle {
    lazy_stack_impl(children, true)
}

/// `LazyVStack(alignment:)` from children.
pub fn lazy_vstack_aligned(
    children: &[ViewHandle],
    alignment: super::HorizontalAlignment,
) -> ViewHandle {
    lazy_stack_aligned_impl(children, true, Some(alignment), None)
}

/// `LazyHStack` from children.
pub fn lazy_hstack(children: &[ViewHandle]) -> ViewHandle {
    lazy_stack_impl(children, false)
}

/// `LazyHStack(alignment:)` from children.
pub fn lazy_hstack_aligned(
    children: &[ViewHandle],
    alignment: super::VerticalAlignment,
) -> ViewHandle {
    lazy_stack_aligned_impl(children, false, None, Some(alignment))
}

/// `TupleView<(A, B, …)>` — what a `@ViewBuilder` makes of several views, with
/// no container around them.
///
/// A `List` renders each element of its content as a row, so
/// `List { Text("a"); Text("b") }` is two rows. Without this the nearest the
/// bindings could get was `list(&vstack(&[a, b]))` — one row holding a stack —
/// and the parity corpus records that: its `List` case spells the *Swift* as
/// `List { AnyView(VStack { … }) }` so the two sides agree. They agreed about
/// the wrong thing.
///
/// A single child collapses to itself, as `ViewBuilder` does: `TupleView` of one
/// is not a type Swift ever builds.
pub fn tuple_view(children: &[ViewHandle]) -> ViewHandle {
    assert!(!children.is_empty(), "a TupleView needs at least one child");
    if children.len() == 1 {
        return children[0].clone();
    }
    unsafe {
        let elements: Vec<*const c_void> = children.iter().map(|c| c.meta).collect();
        let tuple_meta = abi::tuple_metadata(&elements);
        assert!(!tuple_meta.is_null(), "tuple metadata instantiation failed");
        let offsets = abi::tuple_element_offsets(tuple_meta, children.len());
        let meta = abi::generic_metadata1(resolve::tupleview_ma(), tuple_meta);
        assert!(!meta.is_null(), "TupleView metadata instantiation failed");
        let wt = abi::get_view_wt(meta);
        assert!(!wt.is_null(), "{} !: View", crate::diag::type_name(meta));

        let kids: Vec<TupleChild> = children
            .iter()
            .zip(&offsets)
            .map(|(c, &offset)| TupleChild { value: c.value_ptr(), meta: c.meta, offset })
            .collect();
        let payload = TuplePayload { children: kids.as_ptr(), count: kids.len() };
        // `emit_tuple` copies each child through its own value witness, so the
        // caller keeps its originals and the tuple owns copies.
        let mut out = vec![0u8; abi::type_bytes(meta)];
        emit_tuple(out.as_mut_ptr(), &payload as *const TuplePayload as *mut c_void);
        super::wrap_owned(out, meta, wt)
    }
}

/// One track of a `LazyVGrid`'s columns or a `LazyHGrid`'s rows.
///
/// Only `.fixed` is here. `.flexible` and `.adaptive` are the other two cases
/// of `GridItem.Size`, and each takes a *pair* of `CGFloat`s with defaults
/// that Swift supplies at the call site rather than in the enum — so a binding
/// for them is a different shape, not another arm of this one.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GridTrack {
    /// A track exactly this many points across.
    Fixed(f64),
}

/// Build one `GridItem`, with SwiftUI's own defaults for spacing and alignment.
///
/// # Safety
/// Calls into SwiftUI.
unsafe fn grid_item(track: GridTrack) -> Vec<u8> {
    unsafe {
        let size_meta = abi::metadata0(resolve::grid_item_size_ma());
        assert!(!size_meta.is_null(), "GridItem.Size metadata");
        let mut size = vec![0u8; abi::type_bytes(size_meta)];
        let GridTrack::Fixed(points) = track;
        size[..8].copy_from_slice(&points.to_le_bytes());
        // The tag is read, not written down: `GridItem.Size` is resilient, so
        // its case numbering is not something a caller may assume. SwiftUI
        // exports the tag as an i32 global (`…FWC`), and reflection agrees —
        // this asks reflection, which needs no extra symbol.
        let tag = abi::enum_case_index(size_meta, "fixed")
            .expect("GridItem.Size has a `fixed` case");
        abi::inject_enum_tag(&mut size, size_meta, tag as u32);

        let item_meta = abi::metadata0(resolve::grid_item_ma());
        assert!(!item_meta.is_null(), "GridItem metadata");
        let mut item = vec![0u8; abi::type_bytes(item_meta)];
        // `init(_:spacing:alignment:)`: x0 = @in Size, x1/x2 = `CGFloat?`
        // (payload, tag 1 = nil), x3/x4/x5 = `Alignment?` (two words and a
        // tag), x8 = @out. Both optionals are left nil, which is what Swift's
        // defaulted arguments pass.
        core::arch::asm!("blr {f}", f = in(reg) resolve::grid_item_init(),
            in("x0") size.as_mut_ptr(),
            in("x1") 0u64, in("x2") 1u64,
            in("x3") 0u64, in("x4") 0u64, in("x5") 1u64,
            in("x8") item.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("x20") _, lateout("x21") _,
            clobber_abi("C"),
        );
        item
    }
}

/// A Swift `Array<GridItem>` from the tracks.
///
/// # Safety
/// Calls into SwiftUI.
unsafe fn grid_item_array(tracks: &[GridTrack]) -> u64 {
    unsafe {
        let item_meta = abi::metadata0(resolve::grid_item_ma());
        let stride = abi::type_bytes(item_meta);
        let (array, buf): (u64, u64);
        core::arch::asm!("blr {f}", f = in(reg) resolve::array_alloc_uninit(),
            in("x0") tracks.len() as u64,
            in("x1") item_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"),
        );
        // By stride, not by size: the buffer is an array, so each element
        // starts a whole stride along even when the type's size is smaller.
        for (i, t) in tracks.iter().enumerate() {
            let item = grid_item(*t);
            core::ptr::copy_nonoverlapping(
                item.as_ptr(),
                (buf as *mut u8).add(i * stride),
                item.len(),
            );
        }
        array
    }
}

/// `LazyVGrid(columns:) { … }` — children flowed down the named columns.
pub fn lazy_vgrid(tracks: &[GridTrack], children: &[ViewHandle]) -> ViewHandle {
    unsafe { lazy_grid(tracks, children, true) }
}

/// `LazyHGrid(rows:) { … }` — children flowed across the named rows.
pub fn lazy_hgrid(tracks: &[GridTrack], children: &[ViewHandle]) -> ViewHandle {
    unsafe { lazy_grid(tracks, children, false) }
}

/// Shared body. The two initialisers differ only in the alignment's axis and
/// the name of their first argument.
///
/// # Safety
/// Calls into SwiftUI.
unsafe fn lazy_grid(tracks: &[GridTrack], children: &[ViewHandle], vertical: bool) -> ViewHandle {
    unsafe {
        // The children's own types, as everywhere else in this file: a grid of
        // `AnyView` would render but would describe a different Swift type,
        // and with one `AnyView` child the grid would have nothing to flow.
        let (content_meta, content_wt, offsets) = if children.len() == 1 {
            (children[0].meta, children[0].wt, vec![0usize])
        } else {
            let elements: Vec<*const c_void> = children.iter().map(|c| c.meta).collect();
            let tuple_meta = abi::tuple_metadata(&elements);
            assert!(!tuple_meta.is_null(), "tuple metadata instantiation failed");
            let offsets = abi::tuple_element_offsets(tuple_meta, children.len());
            let m = abi::generic_metadata1(resolve::tupleview_ma(), tuple_meta);
            assert!(!m.is_null(), "TupleView metadata instantiation failed");
            let w = abi::get_view_wt(m);
            assert!(!w.is_null(), "{} !: View", crate::diag::type_name(m));
            (m, w, offsets)
        };

        let ma = if vertical { resolve::lazy_vgrid_ma() } else { resolve::lazy_hgrid_ma() };
        let meta = abi::generic_metadata2(ma, content_meta, content_wt);
        assert!(!meta.is_null(), "lazy grid metadata");
        let wt = abi::get_view_wt(meta);
        assert!(!wt.is_null(), "lazy grid !: View");

        let array = grid_item_array(tracks);
        let (align, _) = if vertical {
            static_getter(resolve::halign_center(), resolve::halign_meta())
        } else {
            static_getter(resolve::valign_center(), resolve::valign_meta())
        };

        // The content closure is called before the initialiser returns, so the
        // children may be borrowed rather than leaked.
        let kids: Vec<TupleChild> = children
            .iter()
            .zip(&offsets)
            .map(|(c, &offset)| TupleChild { value: c.value_ptr(), meta: c.meta, offset })
            .collect();
        let payload = TuplePayload { children: kids.as_ptr(), count: kids.len() };
        let mut ctx =
            abi::ClosureCtx::new(emit_tuple, &payload as *const TuplePayload as *mut c_void);

        let pinned_meta = crate::type_by_name!(swift_type!(SwiftUI.PinnedScrollableViews).as_bytes());
        assert!(!pinned_meta.is_null(), "PinnedScrollableViews metadata");
        let mut pinned = vec![0u8; abi::type_bytes(pinned_meta)];

        let mut result = vec![0u8; abi::type_bytes(meta)];
        // init(columns:alignment:spacing:pinnedViews:content:)
        //   x0 = Array<GridItem>, x1 = alignment, x2/x3 = `CGFloat?`,
        //   x4 = @in pinnedViews, x5 = content fn, x6 = content ctx,
        //   x7 = Content.Type, [sp] = Content: View WT, x8 = @out.
        //
        // Nine arguments after the indirect result, so the last one spills.
        core::arch::asm!(
            "sub sp, sp, #16",
            "str {vw}, [sp]",
            "blr {f}",
            "add sp, sp, #16",
            f = in(reg) if vertical { resolve::lazy_vgrid_init() } else { resolve::lazy_hgrid_init() },
            vw = in(reg) content_wt,
            in("x0") array,
            in("x1") align,
            in("x2") 0u64, in("x3") 1u64,
            in("x4") pinned.as_mut_ptr(),
            in("x5") abi::swift_closure_thunk as *const c_void,
            in("x6") &mut ctx as *mut abi::ClosureCtx,
            in("x7") content_meta,
            in("x8") result.as_mut_ptr(),
            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)
    }
}