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
//! Key paths into SwiftUI's keyed value bags, built from scratch.
//!
//! Three of SwiftUI's protocols ask the *caller* to declare a key type and then
//! reach the value through a key path: `FocusedValueKey`, `EnvironmentKey` and
//! `ContainerValueKey`. All three need the same two things synthesised, and all
//! three draw from the same pool of thunks and pattern slots in
//! [`crate::keypath`], so they are here together.
//!
//! # Focused values — publishing a value the menu bar can read
//!
//! `.focusedSceneValue(\.someKey, value)` is how a window tells the commands
//! above it what is selected, and it is the last entry in Apple's catalogue this
//! crate could not build. Two things stood in the way, and both are interesting:
//!
//! 1. **The key.** `FocusedValues` is keyed by a type conforming to
//!    `FocusedValueKey`, and the conformance is the caller's to write. So one is
//!    synthesised at run time, the same way [`crate::conformance`] does for
//!    `PreferenceKey` and `Layout`: a carrier type is minted, a witness table
//!    holding its `Value` is built, and a conformance record is registered.
//!
//! 2. **The key path.** `WritableKeyPath<FocusedValues, T?>` is not a symbol,
//!    and unlike `EnvironmentValues` there is no SwiftUI modifier that stores one
//!    this crate could read back out — `FocusedValues` exports no properties at
//!    all. So the key path *pattern* is emitted, with a settable computed
//!    component whose getter and setter go through `FocusedValues`'s subscript.
//!    That is exactly what `swiftc` emits for a client's own computed property on
//!    `FocusedValues`, and the pattern here was read out of its IR rather than
//!    assembled from the bit definitions.
//!
//! ```no_run
//! # use swiftui_native::views;
//! let key = views::focus_key("selectedRow");
//! let v = views::focused_scene_value(&views::text("row"), &key, 7);
//! ```
//!
//! # What is bound and what is not
//!
//! Publishing. *Reading* a focused value needs `@FocusedValue`, which is a
//! `DynamicProperty` — a property wrapper SwiftUI instantiates itself, which is
//! a different mechanism from anything here. The key's value type is `Int`,
//! because that is what a key path's value type has to be fixed to at the moment
//! the pattern is emitted.

use super::{wrap_owned, ViewHandle};
use crate::conformance::{synthesize, Conformance, Protocol, Witness};
use crate::keypath;
use crate::mangle::{self, swift_type};
use crate::resolve;
use core::ffi::c_void;
use std::sync::{Mutex, OnceLock};

/// A Swift type a synthesised key can hold.
///
/// The three keyed bags — `EnvironmentKey`, `FocusedValueKey`,
/// `ContainerValueKey` — are generic over their value, and so are these. Each
/// implementation is four things: the type's mangled name (for the key path's
/// value type), its metadata (for the conformance's associated type), and the
/// two directions of moving a value across.
///
/// # Ownership
///
/// `write` produces a `+1` value, because that is what every use here needs: an
/// `@in` argument is *owned* by the callee, and a `defaultValue` witness is
/// called again each time SwiftUI wants the default and destroys what it got. A
/// `String` that handed back the same object twice without retaining would be
/// over-released, which is why the default is kept as a closure that writes a
/// fresh one rather than as bytes to copy.
///
/// `read` copies and takes nothing: it is reading a value somebody else owns.
pub trait KeyValue: Clone + Send + Sync + 'static {
    /// The mangled name of the Swift type, without the `$s`.
    fn mangled() -> &'static str;

    /// The type's metadata.
    fn metadata() -> *const c_void;

    /// Write a `+1` copy into a buffer of the type's stride.
    ///
    /// # Safety
    /// `out` must have room for the type's stride.
    unsafe fn write(&self, out: *mut u8);

    /// Read a copy back, leaving the source owned by whoever owns it.
    ///
    /// # Safety
    /// `from` must address an initialised value of this type.
    unsafe fn read(from: *const u8) -> Self;
}

/// What a key's default may be written as.
///
/// `env_key("depth", 3)` and `env_key("greeting", "hello")` should both work, and
/// `Into` cannot do it: `3.into()` with an `i64` target is ambiguous, because
/// every integer width has a `From` into `i64`. This has one impl per
/// destination, so the literal's type is decided by the key's.
pub trait IntoKeyValue<T: KeyValue> {
    /// The value itself.
    fn into_key_value(self) -> T;
}

impl<T: KeyValue> IntoKeyValue<T> for T {
    fn into_key_value(self) -> T {
        self
    }
}

impl IntoKeyValue<String> for &str {
    fn into_key_value(self) -> String {
        self.to_string()
    }
}

impl KeyValue for i64 {
    fn mangled() -> &'static str {
        crate::mangle::INT
    }
    fn metadata() -> *const c_void {
        resolve::int_meta()
    }
    unsafe fn write(&self, out: *mut u8) {
        unsafe { *(out as *mut i64) = *self };
    }
    unsafe fn read(from: *const u8) -> Self {
        unsafe { *(from as *const i64) }
    }
}

impl KeyValue for f64 {
    fn mangled() -> &'static str {
        crate::mangle::DOUBLE
    }
    fn metadata() -> *const c_void {
        resolve::double_meta()
    }
    unsafe fn write(&self, out: *mut u8) {
        unsafe { *(out as *mut f64) = *self };
    }
    unsafe fn read(from: *const u8) -> Self {
        unsafe { *(from as *const f64) }
    }
}

impl KeyValue for bool {
    fn mangled() -> &'static str {
        crate::mangle::BOOL
    }
    fn metadata() -> *const c_void {
        resolve::bool_meta()
    }
    unsafe fn write(&self, out: *mut u8) {
        unsafe { *out = u8::from(*self) };
    }
    unsafe fn read(from: *const u8) -> Self {
        unsafe { *from & 1 != 0 }
    }
}

impl KeyValue for String {
    fn mangled() -> &'static str {
        crate::mangle::STRING
    }
    fn metadata() -> *const c_void {
        resolve::string_meta()
    }
    unsafe fn write(&self, out: *mut u8) {
        // A fresh `+1` string every time: see the note on the trait.
        let bytes = unsafe { crate::abi::swift_string(self) };
        unsafe { core::ptr::copy_nonoverlapping(bytes.as_ptr(), out, 16) };
    }
    unsafe fn read(from: *const u8) -> Self {
        let mut bytes = [0u8; 16];
        unsafe { core::ptr::copy_nonoverlapping(from, bytes.as_mut_ptr(), 16) };
        unsafe { crate::abi::read_swift_string(bytes) }
    }
}

/// Call a synthesised `defaultValue` witness and read what it wrote.
///
/// Through the witness table rather than the Rust function behind it, so this
/// covers the whole path SwiftUI takes: the table slot, the thunk's `x8`/`x20`
/// shuffle, the registry lookup, and the generic writer. Calling the Rust
/// function directly would skip every part that has ever been wrong.
///
/// # Safety
/// `table` must be a synthesised conformance whose requirement `slot` is a
/// `static defaultValue` returning `T`, and `key_meta` the conforming type's
/// metadata.
unsafe fn read_default<T: KeyValue>(
    table: *const c_void,
    slot: usize,
    key_meta: *const c_void,
) -> T {
    unsafe {
        let witness = *(table as *const *const c_void).add(slot + 1);
        let mut out = vec![0u8; crate::abi::type_bytes(T::metadata())];
        core::arch::asm!("blr {f}", f = in(reg) witness,
            in("x8") out.as_mut_ptr(),
            in("x20") key_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 value = T::read(out.as_ptr());
        crate::abi::type_destroy(T::metadata(), out.as_mut_ptr());
        value
    }
}

/// A registered focused-value key: a synthesised `FocusedValueKey` conformance
/// and the `WritableKeyPath<FocusedValues, T?>` that reaches it.
pub struct FocusKey<T: KeyValue = i64> {
    /// Which of [`keypath::VALUE_SLOTS`] this key's pattern and thunks occupy.
    ///
    /// The thunks carry it as an immediate, so it is also how the accessors find
    /// their way back to the conformance — which is why the registry is indexed
    /// by *slot* rather than by registration order. Those were the same number
    /// for as long as focused keys were the only thing drawing from the pool.
    slot: usize,
    key_path: u64,
    value: core::marker::PhantomData<fn() -> T>,
}

impl<T: KeyValue> FocusKey<T> {
    /// The `WritableKeyPath<FocusedValues, T?>` object, for driving directly.
    ///
    /// Exposed for `tests/native_tests.rs`, which pushes a value through the key
    /// path and reads it back: whether the pattern *works* is not something a
    /// render or a type comparison can answer, and a key path that built but
    /// never ran would look identical from outside.
    #[doc(hidden)]
    pub fn key_path_for_test(&self) -> u64 {
        self.key_path
    }

    /// The key type's metadata and its `FocusedValueKey` witness table.
    #[doc(hidden)]
    pub fn parts_for_test(&self) -> (usize, usize) {
        let r = registry().lock().expect("focus key registry");
        let e = r[self.slot].as_ref().expect("a registered focus key");
        (e.key_meta, e.key_wt)
    }
}

/// One registered key's parts, as the thunks need them.
///
/// Held as `usize` rather than pointers so the registry can be a `static`:
/// metadata and witness tables are immortal, so a raw pointer across threads is
/// safe here, but `*const c_void` is not `Send` and saying so with a wrapper
/// would be more machinery than the two casts.
struct Registered {
    key_meta: usize,
    key_wt: usize,
    key_path: u64,
}

fn registry() -> &'static Mutex<Vec<Option<Registered>>> {
    static R: OnceLock<Mutex<Vec<Option<Registered>>>> = OnceLock::new();
    R.get_or_init(|| Mutex::new((0..keypath::VALUE_SLOTS).map(|_| None).collect()))
}

/// Names already registered, and the slot each took.
fn named() -> &'static Mutex<Vec<(String, usize)>> {
    static N: OnceLock<Mutex<Vec<(String, usize)>>> = OnceLock::new();
    N.get_or_init(|| Mutex::new(Vec::new()))
}

/// Register a focused-value key, or return the one already registered for `name`.
///
/// The name is not passed to SwiftUI — it identifies the key on the Rust side, so
/// that the publisher and any future reader agree on which of the slots they
/// mean. What SwiftUI sees is a type, minted once per name.
///
/// # Panics
/// Past [`keypath::VALUE_SLOTS`] distinct synthesised key paths — the pool is
/// shared with [`env_key`](super::env_key), [`container_key`](super::container_key)
/// and each named property of an observable model — since each needs its own
/// thunk pair, and those are declared rather than generated.
pub fn focus_key<T: KeyValue>(name: &str) -> FocusKey<T> {
    let mut names = named().lock().expect("focus key names");
    if let Some(&(_, slot)) = names.iter().find(|(n, _)| n == name) {
        let key_path = registry().lock().expect("focus key registry")[slot]
            .as_ref()
            .expect("a registered focus key")
            .key_path;
        return FocusKey { slot, key_path, value: core::marker::PhantomData };
    }

    let slot = keypath::next_value_slot();
    names.push((name.to_string(), slot));

    unsafe {
        // A distinct carrier type per key, because `FocusedValues` is keyed by
        // the *type*: one type conforming for every key would make them all the
        // same entry.
        let type_name: &'static [u8] = leak_cstr(&format!("RustFocusKey{slot}"));
        let mangled: &'static [u8] =
            leak_cstr(&format!("6rswift{}RustFocusKey{slot}V", 12 + digits(slot)));
        let (descriptor, key_meta) = crate::state::emit_int_carrier(type_name, mangled);

        let protocol = Protocol::from_symbol(c"$s7SwiftUI15FocusedValueKeyMp");
        assert_eq!(
            protocol.requirement_count(),
            1,
            "FocusedValueKey changed shape — it used to be one associated type",
        );
        // The one requirement is `associatedtype Value`, and it has to agree with
        // what the key path's value type is built as, below.
        let conformance: &'static Conformance = Box::leak(Box::new(synthesize(
            &protocol,
            descriptor,
            &[Witness::Metadata(T::metadata())],
        )));
        let key_wt = conformance.witness_table();

        let (get, set, get_target, set_target) = keypath::value_thunks(slot);
        *get_target = focus_get as *const c_void;
        *set_target = focus_set as *const c_void;
        // The conformance goes in *before* the pattern is built: instantiating a
        // key path can call its own getter, and the getter reads this.
        registry().lock().expect("focus key registry")[slot] = Some(Registered {
            key_meta: key_meta as usize,
            key_wt: key_wt as usize,
            key_path: 0,
        });
        let key_path = keypath::build_writable_computed(
            keypath::value_slot(slot),
            swift_type!(SwiftUI.FocusedValues).as_bytes(),
            mangle::optional(T::mangled()).as_bytes(),
            get,
            set,
        );
        // SwiftUI keeps the key path inside the modifier it is handed to, and
        // this one is handed over again on every rebuild.
        swift_runtime_sys::RuntimeRaw::swift_retain(key_path as *mut c_void);
        registry().lock().expect("focus key registry")[slot]
            .as_mut()
            .expect("just registered")
            .key_path = key_path;

        FocusKey { slot, key_path, value: core::marker::PhantomData }
    }
}

/// How many times the key path accessors have been entered.
///
/// The only thing about this mechanism a client can observe. Whether a value
/// *survives* a round trip through a `FocusedValues` is not testable from
/// outside SwiftUI: `FocusedValues()` is `internal`, so a client cannot make one
/// — Swift itself cannot write that test — and one built here by allocating the
/// stride is not the thing SwiftUI's focus machinery produces. What *is*
/// observable, and what these count, is that `swift_getKeyPath` accepted the
/// pattern and that both accessors are reached with the shuffles they expect.
static GETS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
static SETS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// `(getter calls, setter calls)` so far.
#[doc(hidden)]
pub fn focus_accessor_counts() -> (usize, usize) {
    use std::sync::atomic::Ordering::Relaxed;
    (GETS.load(Relaxed), SETS.load(Relaxed))
}

/// How many decimal digits `n` takes, for the mangled name's length prefix.
fn digits(n: usize) -> usize {
    if n < 10 {
        1
    } else if n < 100 {
        2
    } else {
        3
    }
}

/// A NUL-terminated copy of `s`, leaked.
///
/// The type name and mangled name go into a runtime-minted type descriptor,
/// which outlives every caller.
fn leak_cstr(s: &str) -> &'static [u8] {
    let mut bytes = s.as_bytes().to_vec();
    bytes.push(0);
    Box::leak(bytes.into_boxed_slice())
}

/// The key path's getter: read `values[Key.self]`.
///
/// # Safety
/// Reached through one of [`keypath::focus_thunks`]'s getter thunks, which
/// supplies the three arguments in order. `root` must address a live
/// `FocusedValues`.
unsafe extern "C" fn focus_get(out: *mut u8, root: *const c_void, index: u64) {
    GETS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let (meta, wt) = {
        let r = registry().lock().expect("focus key registry");
        let e = r[index as usize].as_ref().expect("a registered focus key");
        (e.key_meta as *const c_void, e.key_wt as *const c_void)
    };
    unsafe {
        // `FocusedValues.subscript(_:)`'s getter: x0 the metatype value — which
        // for a struct is its metadata — x1 the generic argument, x2 the
        // conformance, x8 the `Value?` result, x20 the values themselves.
        core::arch::asm!("blr {f}", f = in(reg) resolve::focused_values_get(),
            in("x0") meta,
            in("x1") meta,
            in("x2") wt,
            in("x8") out,
            in("x20") root,
            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"),
        );
    }
}

/// The key path's setter: write `values[Key.self] = value`.
///
/// # Safety
/// As [`focus_get`]; `root` must address a live, mutable `FocusedValues`.
unsafe extern "C" fn focus_set(value: *const u8, root: *mut c_void, index: u64) {
    SETS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let (meta, wt) = {
        let r = registry().lock().expect("focus key registry");
        let e = r[index as usize].as_ref().expect("a registered focus key");
        (e.key_meta as *const c_void, e.key_wt as *const c_void)
    };
    unsafe {
        // The setter takes the new `Value?` by address in x0, then the same three
        // arguments, and the values as an `inout` in x20.
        core::arch::asm!("blr {f}", f = in(reg) resolve::focused_values_set(),
            in("x0") value,
            in("x1") meta,
            in("x2") meta,
            in("x3") wt,
            in("x20") root,
            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"),
        );
    }
}

/// `.focusedSceneValue(keyPath, value)` — publish a value for the whole scene.
///
/// What a window tells the menu bar about its selection. The scene form is the
/// one commands read; [`focused_value_keyed`] is the same thing scoped to
/// whatever currently has focus.
pub fn focused_scene_value<T: KeyValue>(
    view: &ViewHandle,
    key: &FocusKey<T>,
    value: impl IntoKeyValue<T>,
) -> ViewHandle {
    unsafe {
        publish(
            view,
            key,
            value.into_key_value(),
            resolve::focused_scene_value_fn(),
            resolve::focused_scene_value_oret(),
        )
    }
}

/// `.focusedValue(keyPath, value)` — publish a value for the focused view.
pub fn focused_value_keyed<T: KeyValue>(
    view: &ViewHandle,
    key: &FocusKey<T>,
    value: impl IntoKeyValue<T>,
) -> ViewHandle {
    unsafe {
        publish(
            view,
            key,
            value.into_key_value(),
            resolve::focused_value_kp_fn(),
            resolve::focused_value_kp_oret(),
        )
    }
}

/// # Safety
/// `f`/`oret` must be a matching `focusedValue`-shaped modifier and descriptor.
unsafe fn publish<T: KeyValue>(
    view: &ViewHandle,
    key: &FocusKey<T>,
    value: T,
    f: *const c_void,
    oret: *const c_void,
) -> ViewHandle {
    unsafe {
        // `@in T`, consumed — so a `+1` copy, which is what `write` produces.
        let mut boxed = vec![0u8; crate::abi::type_bytes(T::metadata())];
        value.write(boxed.as_mut_ptr());
        // The key path is *consumed* by the initialiser, as `Environment.init`
        // and `ForEach.init(_:id:)` are — so a cached one needs a retain per
        // call or it is freed under SwiftUI a few rebuilds later.
        swift_runtime_sys::RuntimeRaw::swift_retain(key.key_path as *mut c_void);

        // Three substitutions, not two: the opaque type is a function of the
        // whole generic signature — `<Self: View, T>` — so `T`'s metadata sits
        // between the receiver's and its conformance. The *call* does not pass
        // `T.Type`, which is what made two look right; asking for the metadata
        // with it missing reads the conformance out of past the end of the array.
        let (meta, wt, size) =
            super::opaque_result_type(oret, &[view.meta, T::metadata(), view.wt]);
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        // x0 = the key path, x1 = @in the value, x2 = Self.Type,
        // x3 = Self: View, x8 = @out, x20 = self.
        //
        // No `T.Type`: SwiftUI recovers the value type from the key path, which
        // is why the argument list is shorter than the signature suggests.
        core::arch::asm!("blr {f}", f = in(reg) f,
            in("x0") key.key_path,
            in("x1") boxed.as_mut_ptr(),
            in("x2") view.meta,
            in("x3") view.wt,
            in("x8") result.as_mut_ptr(),
            in("x20") this,
            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)
    }
}

// ── Environment keys defined in Rust ──
//
// `.environment(\.myKey, value)` where `myKey` is the caller's own — the last
// thing `EnvironmentValues` could not do from here. The pieces are the same as a
// focused value's and reuse the same pool:
//
//   * an `EnvironmentKey` conformance, synthesised, whose `defaultValue` is a
//     Rust function;
//   * a `WritableKeyPath<EnvironmentValues, Int>` whose accessors go through
//     `EnvironmentValues`'s `EnvironmentKey` subscript.
//
// The value is not optional here. An `EnvironmentKey` *has* a default, so the
// subscript returns `Value`, and a reader always gets something — which is the
// whole difference between an environment value and a focused one.

/// A registered environment key: the conformance, the key path, and the default.
///
/// Generic over what it holds. The type is fixed when the key is made, which is
/// what lets [`environment_value`] and
/// [`EnvironmentValues::value_for`](crate::views::EnvironmentValues::value_for)
/// be checked rather than trusted — reading a `String` key as an `Int` is a
/// compile error here and a reinterpreted pointer in Swift.
pub struct CustomEnvKey<T: KeyValue = i64> {
    slot: usize,
    key_path: u64,
    value: core::marker::PhantomData<fn() -> T>,
}

impl<T: KeyValue> CustomEnvKey<T> {
    /// What the synthesised `defaultValue` witness produces, called as SwiftUI
    /// calls it.
    ///
    /// Reading it twice must give the same answer twice: the witness is called
    /// afresh on every access and its result is destroyed by the caller, so a
    /// default that handed back a shared object rather than a copy would be
    /// over-released here rather than somewhere inside SwiftUI later.
    #[doc(hidden)]
    pub fn default_for_test(&self) -> T {
        let (key_meta, key_wt) = {
            let r = env_registry().lock().expect("environment key registry");
            let e = r[self.slot].as_ref().expect("a registered environment key");
            (e.key_meta as *const c_void, e.key_wt as *const c_void)
        };
        // Requirement 1 of `EnvironmentKey` — `Value` is 0, `defaultValue` is 1.
        unsafe { read_default(key_wt, 1, key_meta) }
    }

    /// The `WritableKeyPath<EnvironmentValues, Int>` object.
    #[doc(hidden)]
    pub fn key_path_for_test(&self) -> u64 {
        self.key_path
    }
}

/// One registered environment key.
///
/// The default is a *writer* rather than bytes: `defaultValue` is called again
/// every time SwiftUI wants it and destroys what it gets, so a `String` default
/// has to be a fresh `+1` each time. Copying stored bytes would hand back the
/// same object twice and over-release it.
struct EnvRegistered {
    key_meta: usize,
    key_wt: usize,
    key_path: u64,
    write_default: Box<dyn Fn(*mut u8) + Send + Sync>,
}

fn env_registry() -> &'static Mutex<Vec<Option<EnvRegistered>>> {
    static R: OnceLock<Mutex<Vec<Option<EnvRegistered>>>> = OnceLock::new();
    R.get_or_init(|| Mutex::new((0..keypath::VALUE_SLOTS).map(|_| None).collect()))
}

/// Names already registered, and the slot each took.
fn env_named() -> &'static Mutex<Vec<(String, usize)>> {
    static N: OnceLock<Mutex<Vec<(String, usize)>>> = OnceLock::new();
    N.get_or_init(|| Mutex::new(Vec::new()))
}

/// Which key a `defaultValue` getter is being asked for.
///
/// Unlike the key path accessors, this one needs no per-key thunk: a static
/// property getter is handed `Self.Type` in x20, and `Self` *is* the key. So one
/// thunk serves every key and the metadata is the lookup.
fn env_slot_for(meta: *const c_void) -> usize {
    let r = env_registry().lock().expect("environment key registry");
    r.iter()
        .position(|e| e.as_ref().is_some_and(|e| e.key_meta == meta as usize))
        .unwrap_or_else(|| {
            panic!("no environment key registered for {}", crate::diag::type_name(meta))
        })
}

crate::thunk::runtime_thunk! {
    /// `static defaultValue` — result through x8, `Self.Type` in x20.
    fn env_default_thunk = "rswift_env_default" via RSWIFT_ENV_DEFAULT {
        prologue: ["mov x1, x20", "mov x0, x8"],
        branch: "br",
        epilogue: [],
    }
}

/// The `defaultValue` witness: write the registered default.
///
/// # Safety
/// Reached through [`env_default_thunk`]; `out` must have room for an `Int` and
/// `meta` must be a registered key's metadata.
unsafe extern "C" fn env_default(out: *mut u8, meta: *const c_void) {
    let slot = env_slot_for(meta);
    let r = env_registry().lock().expect("environment key registry");
    (r[slot].as_ref().expect("a registered environment key").write_default)(out);
}

/// The key path's getter: read `values[Key.self]`.
///
/// # Safety
/// As [`focus_get`], for an environment key.
unsafe extern "C" fn env_get(out: *mut u8, root: *const c_void, index: u64) {
    let (meta, wt) = {
        let r = env_registry().lock().expect("environment key registry");
        let e = r[index as usize].as_ref().expect("a registered environment key");
        (e.key_meta as *const c_void, e.key_wt as *const c_void)
    };
    unsafe {
        core::arch::asm!("blr {f}", f = in(reg) resolve::environment_values_get(),
            in("x0") meta,
            in("x1") meta,
            in("x2") wt,
            in("x8") out,
            in("x20") root,
            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"),
        );
    }
}

/// The key path's setter: write `values[Key.self] = value`.
///
/// # Safety
/// As [`env_get`].
unsafe extern "C" fn env_set(value: *const u8, root: *mut c_void, index: u64) {
    let (meta, wt) = {
        let r = env_registry().lock().expect("environment key registry");
        let e = r[index as usize].as_ref().expect("a registered environment key");
        (e.key_meta as *const c_void, e.key_wt as *const c_void)
    };
    unsafe {
        core::arch::asm!("blr {f}", f = in(reg) resolve::environment_values_set(),
            in("x0") value,
            in("x1") meta,
            in("x2") meta,
            in("x3") wt,
            in("x20") root,
            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"),
        );
    }
}

/// Define an environment key, or return the one already defined for `name`.
///
/// `default` is what a view reads when nothing above it has written the key —
/// SwiftUI asks for it through the synthesised `defaultValue` witness, so this is
/// the real default and not a value written into a root somewhere.
///
/// # Panics
/// Past [`keypath::VALUE_SLOTS`] synthesised key paths: the pool is shared with
/// focused keys, container keys and observable properties.
pub fn env_key<T: KeyValue>(name: &str, default: impl IntoKeyValue<T>) -> CustomEnvKey<T> {
    let default = default.into_key_value();
    let mut names = env_named().lock().expect("environment key names");
    if let Some(&(_, slot)) = names.iter().find(|(n, _)| n == name) {
        let key_path = env_registry().lock().expect("environment key registry")[slot]
            .as_ref()
            .expect("a registered environment key")
            .key_path;
        return CustomEnvKey { slot, key_path, value: core::marker::PhantomData };
    }

    let slot = keypath::next_value_slot();
    names.push((name.to_string(), slot));

    unsafe {
        let type_name: &'static [u8] = leak_cstr(&format!("RustEnvKey{slot}"));
        let mangled: &'static [u8] =
            leak_cstr(&format!("6rswift{}RustEnvKey{slot}V", 10 + digits(slot)));
        let (descriptor, key_meta) = crate::state::emit_int_carrier(type_name, mangled);

        let protocol = Protocol::from_symbol(c"$s7SwiftUI14EnvironmentKeyMp");
        assert_eq!(
            protocol.requirement_count(),
            3,
            "EnvironmentKey changed shape — it used to be Value, defaultValue and \
             one defaulted requirement",
        );
        let conformance: &'static Conformance = Box::leak(Box::new(synthesize(
            &protocol,
            descriptor,
            &[
                Witness::Metadata(T::metadata()),
                Witness::Function(env_default_thunk as *const c_void),
                Witness::Default,
            ],
        )));
        let key_wt = conformance.witness_table();

        let (get, set, get_target, set_target) = keypath::value_thunks(slot);
        *get_target = env_get as *const c_void;
        *set_target = env_set as *const c_void;
        RSWIFT_ENV_DEFAULT = env_default as *const c_void;
        // Registered before the pattern is built: instantiating a key path can
        // call its own getter, and the getter reads this.
        env_registry().lock().expect("environment key registry")[slot] = Some(EnvRegistered {
            key_meta: key_meta as usize,
            key_wt: key_wt as usize,
            key_path: 0,
            // SAFETY (the enclosing block's): `env_default` sizes `out` by this
            // key's own value type, which is the `T` captured here.
            write_default: Box::new(move |out| default.write(out)),
        });

        let key_path = keypath::build_writable_computed(
            keypath::value_slot(slot),
            swift_type!(SwiftUI.EnvironmentValues).as_bytes(),
            T::mangled().as_bytes(),
            get,
            set,
        );
        swift_runtime_sys::RuntimeRaw::swift_retain(key_path as *mut c_void);
        env_registry().lock().expect("environment key registry")[slot]
            .as_mut()
            .expect("just registered")
            .key_path = key_path;

        CustomEnvKey { slot, key_path, value: core::marker::PhantomData }
    }
}

/// `.environment(\.key, value)` for a key defined here.
pub fn environment_value<T: KeyValue>(
    view: &ViewHandle,
    key: &CustomEnvKey<T>,
    value: impl IntoKeyValue<T>,
) -> ViewHandle {
    let value = value.into_key_value();
    unsafe {
        let _ = key.slot;
        // `@in`, and owned by the callee — so a `+1` copy, which is what
        // `KeyValue::write` produces.
        let mut boxed = vec![0u8; crate::abi::type_bytes(T::metadata()).max(1)];
        value.write(boxed.as_mut_ptr());
        // Consumed by the modifier, as every key path argument in this crate is.
        swift_runtime_sys::RuntimeRaw::swift_retain(key.key_path as *mut c_void);

        let (meta, wt, size) = super::opaque_result_type(
            resolve::environment_oret(),
            &[view.meta, T::metadata(), view.wt],
        );
        let mut result = vec![0u8; size];
        let this = view.value_ptr();
        core::arch::asm!("blr {f}", f = in(reg) resolve::environment_fn(),
            in("x0") key.key_path,
            in("x1") boxed.as_mut_ptr(),
            in("x2") view.meta,
            in("x3") view.wt,
            in("x8") result.as_mut_ptr(),
            in("x20") this,
            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)
    }
}

// ── Container values defined in Rust ──
//
// `.containerValue(\.myKey, value)` — how a row tells the container it is in
// something about itself. The modifier is `@_alwaysEmitIntoClient`, so there is
// no symbol for it; its body is
// `modifier(_ContainerValueWritingModifier(keyPath:value:))`, and that
// initialiser is client-emitted too.
//
// The type is `@frozen`, though, and its two stored properties are the whole of
// it — so the value is built by writing the key path and the value into a buffer.
// `@frozen` is exactly the promise that makes that legitimate: it says the layout
// is API. Nothing else in this crate writes a layout down, and this is the one
// declaration that permits it.

/// A registered container-value key.
pub struct CustomContainerKey<T: KeyValue = i64> {
    slot: usize,
    key_path: u64,
    value: core::marker::PhantomData<fn() -> T>,
}

impl<T: KeyValue> CustomContainerKey<T> {
    /// What the synthesised `defaultValue` witness produces. As
    /// [`CustomEnvKey::default_for_test`].
    #[doc(hidden)]
    pub fn default_for_test(&self) -> T {
        let (key_meta, key_wt) = {
            let r = container_registry().lock().expect("container key registry");
            let e = r[self.slot].as_ref().expect("a registered container key");
            (e.key_meta as *const c_void, e.key_wt as *const c_void)
        };
        // Requirement 1 of `ContainerValueKey` — `Value`, then `defaultValue`.
        unsafe { read_default(key_wt, 1, key_meta) }
    }
}

/// One registered container-value key.
///
/// The default is a writer for the same reason [`EnvRegistered`]'s is.
struct ContainerRegistered {
    key_meta: usize,
    key_wt: usize,
    key_path: u64,
    write_default: Box<dyn Fn(*mut u8) + Send + Sync>,
}

fn container_registry() -> &'static Mutex<Vec<Option<ContainerRegistered>>> {
    static R: OnceLock<Mutex<Vec<Option<ContainerRegistered>>>> = OnceLock::new();
    R.get_or_init(|| Mutex::new((0..keypath::VALUE_SLOTS).map(|_| None).collect()))
}

fn container_named() -> &'static Mutex<Vec<(String, usize)>> {
    static N: OnceLock<Mutex<Vec<(String, usize)>>> = OnceLock::new();
    N.get_or_init(|| Mutex::new(Vec::new()))
}

crate::thunk::runtime_thunk! {
    /// `static defaultValue` for a container key — result in x8, `Self.Type` in x20.
    fn container_default_thunk = "rswift_container_default" via RSWIFT_CONTAINER_DEFAULT {
        prologue: ["mov x1, x20", "mov x0, x8"],
        branch: "br",
        epilogue: [],
    }
}

/// The `defaultValue` witness for a container key.
///
/// # Safety
/// Reached through [`container_default_thunk`].
unsafe extern "C" fn container_default(out: *mut u8, meta: *const c_void) {
    let r = container_registry().lock().expect("container key registry");
    let entry = r
        .iter()
        .flatten()
        .find(|e| e.key_meta == meta as usize)
        .unwrap_or_else(|| {
            panic!("no container key registered for {}", crate::diag::type_name(meta))
        });
    (entry.write_default)(out);
}

/// The key path's getter for a container key.
///
/// # Safety
/// As [`focus_get`].
unsafe extern "C" fn container_get(out: *mut u8, root: *const c_void, index: u64) {
    let (meta, wt) = {
        let r = container_registry().lock().expect("container key registry");
        let e = r[index as usize].as_ref().expect("a registered container key");
        (e.key_meta as *const c_void, e.key_wt as *const c_void)
    };
    unsafe {
        core::arch::asm!("blr {f}", f = in(reg) resolve::container_values_get(),
            in("x0") meta, in("x1") meta, in("x2") wt,
            in("x8") out, in("x20") root,
            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"),
        );
    }
}

/// The key path's setter for a container key.
///
/// # Safety
/// As [`container_get`].
unsafe extern "C" fn container_set(value: *const u8, root: *mut c_void, index: u64) {
    let (meta, wt) = {
        let r = container_registry().lock().expect("container key registry");
        let e = r[index as usize].as_ref().expect("a registered container key");
        (e.key_meta as *const c_void, e.key_wt as *const c_void)
    };
    unsafe {
        core::arch::asm!("blr {f}", f = in(reg) resolve::container_values_set(),
            in("x0") value, in("x1") meta, in("x2") meta, in("x3") wt,
            in("x20") root,
            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"),
        );
    }
}

/// Define a container-value key, or return the one already defined for `name`.
///
/// # Panics
/// Past [`keypath::VALUE_SLOTS`] synthesised key paths — the pool is shared with
/// [`focus_key`], [`env_key`] and each named property of an observable model.
pub fn container_key<T: KeyValue>(
    name: &str,
    default: impl IntoKeyValue<T>,
) -> CustomContainerKey<T> {
    let default = default.into_key_value();
    let mut names = container_named().lock().expect("container key names");
    if let Some(&(_, slot)) = names.iter().find(|(n, _)| n == name) {
        let key_path = container_registry().lock().expect("container key registry")[slot]
            .as_ref()
            .expect("a registered container key")
            .key_path;
        return CustomContainerKey { slot, key_path, value: core::marker::PhantomData };
    }

    let slot = keypath::next_value_slot();
    names.push((name.to_string(), slot));

    unsafe {
        let type_name: &'static [u8] = leak_cstr(&format!("RustContainerKey{slot}"));
        let mangled: &'static [u8] =
            leak_cstr(&format!("6rswift{}RustContainerKey{slot}V", 16 + digits(slot)));
        let (descriptor, key_meta) = crate::state::emit_int_carrier(type_name, mangled);

        let protocol = Protocol::from_symbol(c"$s7SwiftUI17ContainerValueKeyMp");
        assert_eq!(
            protocol.requirement_count(),
            2,
            "ContainerValueKey changed shape — it used to be Value and defaultValue",
        );
        let conformance: &'static Conformance = Box::leak(Box::new(synthesize(
            &protocol,
            descriptor,
            &[
                Witness::Metadata(T::metadata()),
                Witness::Function(container_default_thunk as *const c_void),
            ],
        )));
        let key_wt = conformance.witness_table();

        let (get, set, get_target, set_target) = keypath::value_thunks(slot);
        *get_target = container_get as *const c_void;
        *set_target = container_set as *const c_void;
        RSWIFT_CONTAINER_DEFAULT = container_default as *const c_void;
        container_registry().lock().expect("container key registry")[slot] =
            Some(ContainerRegistered {
                key_meta: key_meta as usize,
                key_wt: key_wt as usize,
                key_path: 0,
                // SAFETY (the enclosing block's): as `env_key`'s.
                write_default: Box::new(move |out| default.write(out)),
            });

        let key_path = keypath::build_writable_computed(
            keypath::value_slot(slot),
            swift_type!(SwiftUI.ContainerValues).as_bytes(),
            T::mangled().as_bytes(),
            get,
            set,
        );
        swift_runtime_sys::RuntimeRaw::swift_retain(key_path as *mut c_void);
        container_registry().lock().expect("container key registry")[slot]
            .as_mut()
            .expect("just registered")
            .key_path = key_path;

        CustomContainerKey { slot, key_path, value: core::marker::PhantomData }
    }
}

/// `.containerValue(\.key, value)` for a key defined here.
///
/// What the `@_alwaysEmitIntoClient` modifier's body does, since the modifier
/// itself exports no symbol: build a `_ContainerValueWritingModifier` and apply
/// it with `.modifier(_:)`.
pub fn container_value<T: KeyValue>(
    view: &ViewHandle,
    key: &CustomContainerKey<T>,
    value: impl IntoKeyValue<T>,
) -> ViewHandle {
    let value = value.into_key_value();
    unsafe {
        let _ = key.slot;
        let modifier_meta =
            crate::abi::generic_metadata1(resolve::container_write_ma(), T::metadata());
        assert!(
            !modifier_meta.is_null(),
            "_ContainerValueWritingModifier<{}> metadata",
            crate::diag::type_name(T::metadata()),
        );

        // `@frozen public struct _ContainerValueWritingModifier<Value> { keyPath,
        // value }`. `@frozen` is the promise that those two fields, in that order,
        // *are* the layout — so the value is written rather than initialised,
        // because the initialiser is `@_alwaysEmitIntoClient` and exports nothing.
        // The field offsets are still asked for rather than assumed.
        let offsets = crate::abi::struct_field_offsets(modifier_meta)
            .expect("_ContainerValueWritingModifier has reflection metadata");
        assert_eq!(offsets.len(), 2, "_ContainerValueWritingModifier changed shape");
        let mut modifier = vec![0u8; crate::abi::type_bytes(modifier_meta)];
        // The modifier owns the key path it stores.
        swift_runtime_sys::RuntimeRaw::swift_retain(key.key_path as *mut c_void);
        modifier[offsets[0]..offsets[0] + 8].copy_from_slice(&key.key_path.to_le_bytes());
        // The stored field is the second one; the modifier owns what is written
        // there, so this is the `+1` copy and not a borrow of the argument.
        value.write(modifier.as_mut_ptr().add(offsets[1]));

        let meta = crate::abi::generic_metadata2(
            resolve::modified_content_ma(),
            view.meta,
            modifier_meta,
        );
        assert!(!meta.is_null(), "ModifiedContent metadata");
        let wt = crate::abi::get_view_wt(meta);
        assert!(!wt.is_null(), "{} !: View", crate::diag::type_name(meta));

        let mut result = vec![0u8; crate::abi::type_bytes(meta)];
        let this = view.value_ptr();
        core::arch::asm!("blr {f}", f = in(reg) resolve::apply_view_modifier_fn(),
            in("x0") modifier.as_mut_ptr(),
            in("x1") view.meta,
            in("x2") modifier_meta,
            in("x3") view.wt,
            in("x8") result.as_mut_ptr(),
            in("x20") this,
            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)
    }
}