tvm-ffi 0.1.16

tvm-ffi rust support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

//! Native Rust structural mutation and mapping.
//!
//! [`structural_mutate`] lets a mutator drive recursion, while
//! [`structural_map`](crate::structural_map) applies callbacks around engine-owned recursion.

// `_raw` functions move one owned `TVMFFIAny`: forward it once, or import it into `Any` before
// anything can unwind. Private `extern "C-unwind"` helpers return it in registers on AArch64.

use std::cell::{RefCell, UnsafeCell};
use std::collections::{HashMap, hash_map::Entry};
use std::ffi::c_void;
use std::marker::PhantomData;

use super::cold_init_lazy_lock::ColdInitLazyLock;
use super::dispatch::IntoDispatcher;
use std::borrow::BorrowMut;
use std::ops::ControlFlow;
use std::ptr::NonNull;
use std::rc::Rc;

use super::dispatch::Dispatcher;
use crate::any::{Any, AnyView, is_plain_inline};
use crate::error::{Error, Result, TYPE_ERROR};
use crate::function::Function;
use crate::object::{self, Object, ObjectArc};
use crate::reflection::TypeAttrColumn;
use crate::tvm_ffi_sys::{
    TVMFFIAny, TVMFFIAnyViewToOwnedAny, TVMFFIFieldInfo, TVMFFIFieldSetter, TVMFFIFunctionCall,
    TVMFFIGetTypeInfo, TVMFFIObject, TVMFFITypeIndex,
};
use crate::tvm_ffi_sys::{TVMFFIObjectHandle, TVMFFISEqHashKind};

use super::structural_common::{
    FLAG_SEQ_HASH_IGNORE, FLAG_SETTER_IS_FUNCTION, field_def_region, for_each_field_info,
    free_var_child_region, missing_field_getter_error, raw_ffi_any_into_result,
    raw_ffi_any_same_as, registered_type_index, reject_error_value, result_into_raw_ffi_any,
    runtime_error, seq_hash_kind, wrong_dispatcher,
};
use super::structural_visit::DefRegionKind;
use super::unchanged::is_unchanged;
use super::unchanged::{Unchanged, UnchangedOr};
use super::visit_error_context::{enrich_visit_error, update_visit_error_context};

const STRUCTURAL_MUTATE_ATTR: &str = "__s_mutate__";
const STRUCTURAL_MAYBE_INPLACE_MUTATE_ATTR: &str = "__s_maybe_inplace_mutate__";
const SHALLOW_COPY_ATTR: &str = "__ffi_shallow_copy__";

// -----------------------------------------------------------------------------
// Data structures and FFI layout
// -----------------------------------------------------------------------------

pub(super) type StructuralMutatorHandle = *mut StructuralMutatorObj;

type FStructuralMutate =
    unsafe extern "C" fn(StructuralMutatorHandle, AnyView<'static>) -> TVMFFIAny;

type FStructuralVarRemapGet =
    unsafe extern "C" fn(StructuralMutatorHandle, AnyView<'static>) -> TVMFFIAny;

type FStructuralVarRemapSet =
    unsafe extern "C" fn(StructuralMutatorHandle, AnyView<'static>, AnyView<'static>) -> TVMFFIAny;

#[repr(C)]
struct StructuralMutatorVTable {
    mutate: FStructuralMutate,
    maybe_inplace_mutate: FStructuralMutate,
    var_remap_get: FStructuralVarRemapGet,
    var_remap_set: FStructuralVarRemapSet,
}

/// The native mutator state, laid out as the prefix of the C++
/// `StructuralMutatorObj`, with no Rust traversal state.
#[repr(C)]
pub struct StructuralMutatorObj {
    base_: Object,
    vtable: *const StructuralMutatorVTable,
    def_region_mode: UnsafeCell<i32>,
}

// Scoped runtime prefixes are not independently allocatable ObjectCore values.
impl StructuralMutatorObj {
    const TYPE_KEY: &'static str = "ffi.StructuralMutator";
}

impl Default for StructuralMutatorObj {
    #[inline(always)]
    fn default() -> Self {
        Self {
            base_: Object::new(),
            vtable: std::ptr::null(),
            def_region_mode: UnsafeCell::new(DefRegionKind::None as i32),
        }
    }
}

const _: () = {
    assert!(
        std::mem::offset_of!(StructuralMutatorObj, vtable) == std::mem::size_of::<TVMFFIObject>()
    );
    assert!(
        std::mem::offset_of!(StructuralMutatorObj, def_region_mode)
            == std::mem::size_of::<TVMFFIObject>() + std::mem::size_of::<*const c_void>()
    );
};

/// Native state and default mutation for [`StructuralMutateEngine`].
/// The engine owns allocation, scoped dispatch, identity remaps and results.
///
/// # Safety
///
/// `Self` must have a complete initialized C layout with [`StructuralMutatorObj`]
/// at offset zero, matching its registered native type and every field hooks access.
/// Native-mutated fields require interior mutability; shared references must not
/// freeze them during recursion. Hooks must preserve the vtable and valid region state.
///
/// The base must not implement [`crate::ObjectCore`] or otherwise allow callers
/// to retain the runtime. Hooks may access the runtime and borrowed mutation
/// state only synchronously, on the calling thread.
///
/// `default_mutate_raw` returns one owning ABI replacement/Unchanged/Error and recurses
/// only through the installed vtable, preserving the input's in-place mode.
/// No whole-base mutable reference may span recursion. Failures use the result
/// carrier; panics must not cross native callbacks.
pub unsafe trait StructuralMutatorBase: Sized {
    /// Initialize the complete base before the engine installs its runtime header.
    fn new() -> Result<Self>;

    /// Native type registered for this complete base layout.
    fn type_index() -> i32;

    /// Descend from a borrowed view without dispatching that value again.
    ///
    /// # Safety
    /// `runtime` is the base of a live `StructuralMutateEngine<Self>` with its
    /// matching installed vtable.
    /// The input and runtime remain borrowed for this synchronous call. The
    /// caller has published the current exclusive dispatcher reborrow.
    unsafe fn default_mutate_raw(runtime: *mut Self, value: MutationView<'_>) -> TVMFFIAny;
}

// SAFETY: this prefix exactly matches the ordinary native mutator. Its mutable
// region is interior mutable, and it exposes no safe ownership conversion.
unsafe impl StructuralMutatorBase for StructuralMutatorObj {
    #[inline(always)]
    fn new() -> Result<Self> {
        Ok(Self::default())
    }

    fn type_index() -> i32 {
        static TYPE_INDEX: ColdInitLazyLock<i32> =
            ColdInitLazyLock::new(|| registered_type_index(StructuralMutatorObj::TYPE_KEY));
        *TYPE_INDEX
    }

    #[inline(always)]
    unsafe fn default_mutate_raw(runtime: *mut Self, value: MutationView<'_>) -> TVMFFIAny {
        // Prefix-only: remaps go through the vtable, so any base may reuse this.
        let raw = value.value;
        // Registered hooks own their remapping policy; reflection handles its own.
        // A hook that rewrites fields keeps the rebuilt object valid for the
        // refined references that point at it.
        if let Some(attr) = Self::structural_mutate_hook(raw, value.mode) {
            return unsafe { Self::call_structural_mutate_hook_raw(runtime, raw, attr) };
        }
        unsafe { Self::mutate_without_hook_raw(runtime, raw) }
    }
}

/// Scoped Rust mutator runtime with a statically selected native base.
///
/// Enter through [`StructuralMutateEngine::mutate_root`]. The engine owns the complete base,
/// dispatcher reborrow handle and identity remaps. The dispatcher stays in the
/// outer call; callbacks receive only a scoped [`StructuralMutatorView`].
#[repr(C)]
pub struct StructuralMutateEngine<Base = StructuralMutatorObj> {
    base: Base,
    dispatcher: *mut c_void,
    remap: RefCell<StructuralVarRemap>,
}

/// Identity substitutions for structural mutation within one invocation.
///
/// Internal to the engine: handlers reach the remap through
/// [`StructuralMutatorView::var_remap_get`] and [`StructuralMutatorView::var_remap_set`].
///
/// Each pointer key owns one strong reference to its original object, preventing
/// address reuse until removal. Values are owning replacements, including
/// [`Unchanged`] markers. Replacing a value does not acquire another key reference;
/// lookup clones the replacement, and dropping releases every owner.
// Perf note: Store only the replacement Any; raw identity keys avoid a second
// Any payload, but still own one retained reference per distinct key. Replacing
// a value does not retain the key again; Drop releases each key exactly once.
#[derive(Default)]
pub(crate) struct StructuralVarRemap {
    entries: HashMap<NonNull<TVMFFIObject>, Any>,
}

impl StructuralVarRemap {
    /// Look up an identity replacement previously stored for `var`.
    pub(crate) fn get(&self, var: AnyView<'_>) -> Result<Option<Any>> {
        let key = object_identity_key(*var.as_raw_ffi_any())?;
        Ok(self.entries.get(&key).cloned())
    }

    /// Store a descent result or an [`Unchanged`] marker for `var`.
    ///
    /// A new key acquires one strong reference; replacing its value preserves
    /// that reference. The replacement is cloned before modifying the table.
    pub(crate) fn set(&mut self, var: AnyView<'_>, mutated_value: &Any) -> Result<()> {
        let key = object_identity_key(*var.as_raw_ffi_any())?;
        let value = mutated_value.clone();
        match self.entries.entry(key) {
            Entry::Occupied(mut entry) => {
                entry.insert(value);
            }
            Entry::Vacant(entry) => {
                entry.insert(value);
                // Insertion may allocate, so retain only after it succeeds.
                // The borrowed var still keeps key live; IncRef cannot unwind.
                unsafe { object::unsafe_::inc_ref(key.as_ptr()) };
            }
        }
        Ok(())
    }
}

impl Drop for StructuralVarRemap {
    fn drop(&mut self) {
        // Release keys first: their C ABI deleters cannot unwind. Field Drop
        // then releases values and buckets without resetting capacity for reuse.
        // The remaining NonNull key bits are dropped without dereferencing them.
        for key in self.entries.keys() {
            unsafe { object::unsafe_::dec_ref(key.as_ptr()) };
        }
    }
}

/// Whether a [`MutationView`] may reuse its value's storage in place.
///
/// `Allow` is an upper bound: a value is reused in place only when it is also
/// uniquely owned. A view made from `&mut Any` starts as `Allow`, and a view
/// from [`MutationView::borrowed`] is always `Disallow`.
///
/// See also [`structural_mutate`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum InplaceMode {
    /// Use ordinary mutation, including for uniquely owned values.
    #[default]
    Disallow,
    /// Permit reuse when ownership and alias checks allow it.
    Allow,
}

impl InplaceMode {
    // The mode is only an upper bound; ownership must still be unique here.
    #[inline(always)]
    fn for_value(self, raw: TVMFFIAny) -> Self {
        if self == Self::Allow && object_is_unique(raw) {
            Self::Allow
        } else {
            Self::Disallow
        }
    }
}

/// A borrowed value that a structural mutation may rewrite in place.
///
/// Mutation handlers receive a `MutationView` instead of an owned value, so
/// matching a node does not retain it. Inspect the node through the view,
/// then pass the view to [`StructuralMutatorView::default_mutate`] to rewrite
/// its children, or rewrite one field with [`field`](MutationView::field).
/// When the node is uniquely owned and the view carries
/// [`InplaceMode::Allow`], its storage is reused instead of copied.
///
/// `T` is the matched type: `MutationView<'_, Array<Any>>` derefs to the
/// array's node, and the default `MutationView<'_>` matches every value. The
/// view is move-only: it cannot be copied or cloned, and consuming it passes
/// on the same mode. A view made from `&mut Any` may reuse storage;
/// one made with [`borrowed`](MutationView::borrowed) never does.
///
/// See also [`structural_mutate`].
pub struct MutationView<'a, T = Any> {
    value: TVMFFIAny,
    mode: InplaceMode,
    #[allow(clippy::type_complexity)]
    _marker: PhantomData<(AnyView<'a>, fn() -> T, Rc<()>)>,
}

impl<T> MutationView<'_, T> {
    /// The viewed cell, borrowed in place by `match_any!` reference patterns.
    #[inline(always)]
    pub(crate) fn cell(&self) -> &TVMFFIAny {
        &self.value
    }
}

impl<'a> MutationView<'a> {
    #[inline(always)]
    pub(super) fn new(value: AnyView<'a>, mode: InplaceMode) -> Self {
        Self::from_raw(*value.as_raw_ffi_any(), mode)
    }

    /// Create a view of a borrowed value that never reuses its storage.
    ///
    /// The mutation result is always a new value or [`Unchanged`]. To allow reuse,
    /// make the view from `&mut Any` instead.
    ///
    /// # Arguments
    ///
    /// * `value` - The value to view.
    ///
    /// # Returns
    ///
    /// A view with [`InplaceMode::Disallow`].
    #[inline(always)]
    pub fn borrowed(value: AnyView<'a>) -> Self {
        Self::new(value, InplaceMode::Disallow)
    }
}

impl<'a> From<&'a mut Any> for MutationView<'a> {
    /// Borrow an owner exclusively without acquiring a reference count.
    ///
    /// Reuse still requires the runtime's uniqueness and alias checks.
    #[inline(always)]
    fn from(value: &'a mut Any) -> Self {
        Self::new(AnyView::from(&*value), InplaceMode::Allow)
    }
}

impl<'a, T> MutationView<'a, T> {
    #[inline(always)]
    fn from_raw(value: TVMFFIAny, mode: InplaceMode) -> Self {
        Self {
            value,
            mode,
            _marker: PhantomData,
        }
    }

    /// # Safety
    /// The original must not be used while the alias lives.
    #[inline(always)]
    pub(crate) unsafe fn alias(&self) -> MutationView<'a, T> {
        MutationView::from_raw(self.value, self.mode)
    }

    // A chain may lend its view to one link at a time. The shorter lifetime
    // prevents a matched link from retaining a borrow across the next link.
    #[inline(always)]
    pub(crate) fn reborrow(&mut self) -> MutationView<'_, T> {
        MutationView::from_raw(self.value, self.mode)
    }

    /// Return the in-place mode this view carries.
    ///
    /// # Returns
    ///
    /// Whether this view may reuse its value's storage.
    #[inline(always)]
    pub fn inplace_mode(&self) -> InplaceMode {
        self.mode
    }

    /// Restrict the mode, without ever upgrading it.
    ///
    /// `Disallow` turns off reuse. `Allow` keeps the current mode, so it never
    /// grants reuse to a view that does not have it, such as a borrowed one.
    ///
    /// # Arguments
    ///
    /// * `requested` - The mode to restrict to.
    ///
    /// # Returns
    ///
    /// The view with the restricted mode.
    #[inline(always)]
    pub fn narrow_inplace_mode(mut self, requested: InplaceMode) -> Self {
        if requested == InplaceMode::Disallow {
            self.mode = InplaceMode::Disallow;
        }
        self
    }

    /// Borrow the current value.
    ///
    /// The view and its copies borrow this handle, so their last use must precede
    /// consuming it for default mutation.
    ///
    /// # Returns
    ///
    /// The value as an [`AnyView`].
    #[inline(always)]
    pub fn as_any_view(&self) -> AnyView<'_> {
        // SAFETY: the input owner, which a handler does not remove from a list
        // or dict it modifies (the callback contract), keeps this payload live
        // while the view is borrowed. The returned lifetime is bounded by self,
        // not by 'a.
        unsafe { AnyView::from_raw_ffi_any(self.value) }
    }

    /// Borrow the value as `U` without changing ownership or mode.
    ///
    /// `U` is anything [`AnyView::downcast_ref`] borrows: a managed reference such as
    /// `Array<i64>`, an object type such as `ArrayObj`, or [`Any`], borrowed in place
    /// without a reference-count bump. The check is strict, and the reference borrows
    /// this view and cannot survive its consumption.
    ///
    /// # Returns
    ///
    /// The borrowed value, or `None` when the value is not a `U`.
    #[inline(always)]
    pub fn downcast_ref<U: crate::type_traits::DowncastRefFromAny>(&self) -> Option<&U> {
        // SAFETY: the view holds a valid cell, borrowed for the returned lifetime,
        // and the input owner keeps its payload live.
        unsafe { U::downcast_ref_from_any(&self.value) }
    }

    /// Whether the value is a `U`, as [`Any::is`].
    #[inline(always)]
    pub fn is<U: crate::type_traits::AnyCompatible>(&self) -> bool {
        self.as_any_view().is::<U>()
    }

    /// Narrow the matched type without acquiring an owning reference.
    ///
    /// The check is the strict one of `match_any!`: only a value that fits `U` as
    /// is, elements included, matches. The view keeps its mode.
    ///
    /// # Returns
    ///
    /// The view typed as `MutationView<'_, U>`.
    ///
    /// # Errors
    ///
    /// Returns the view unchanged when the value is not a `U`, so another type can
    /// be tried.
    #[inline(always)]
    pub fn downcast<U: crate::type_traits::ContainerElement>(
        self,
    ) -> std::result::Result<MutationView<'a, U>, Self> {
        // SAFETY: the input owner keeps the borrowed value live for this handle's
        // lifetime. This only checks its type and does not acquire ownership.
        if unsafe {
            U::container_check_any_strict(&self.value)
                && U::container_match_constraints(&self.value)
        } {
            Ok(MutationView::from_raw(self.value, self.mode))
        } else {
            Err(self)
        }
    }

    /// Erase the matched type while preserving the carried mode.
    ///
    /// # Returns
    ///
    /// The view as `MutationView<'_>`.
    #[inline(always)]
    pub fn into_untyped(self) -> MutationView<'a> {
        MutationView::from_raw(self.value, self.mode)
    }
}

mod mutation_field {
    pub trait Sealed {}
    impl Sealed for crate::Any {}
    impl<T: crate::object::ObjectRefCore> Sealed for T {}
}

/// Owned storage supported by [`MutationView::field`].
/// Sealed to `Any` and owning object handles; borrowed conversion adapters do not qualify.
#[doc(hidden)]
pub trait MutationField: crate::type_traits::ContainerElement + mutation_field::Sealed {}

impl MutationField for Any {}

impl<T: object::ObjectRefCore> MutationField for T {}

impl<T: object::ObjectRefCore> std::ops::Deref for MutationView<'_, T> {
    type Target = T::ContainerType;

    #[inline(always)]
    fn deref(&self) -> &Self::Target {
        // SAFETY: typed view construction establishes T's object layout;
        // this shared borrow cannot outlive or survive consumption of the handle.
        unsafe { &*self.value.data_union.v_obj.cast::<T::ContainerType>() }
    }
}

impl<T: object::ObjectRefCore> MutationView<'_, T> {
    /// Borrow a direct owning field of the node as a view of its own, to rewrite it
    /// with [`StructuralMutatorView::mutate`].
    ///
    /// The field view exclusively borrows this view. It may reuse the field's
    /// storage only when this view may and the node remains uniquely owned. This
    /// does not write the result back into the node: keep the node [`Unchanged`] or
    /// rebuild it from the result.
    ///
    /// # Arguments
    ///
    /// * `selector` - Returns a reference to one of the node's own owning fields,
    ///   an [`Any`] or a managed reference.
    ///
    /// # Returns
    ///
    /// A view of the field.
    ///
    /// # Panics
    ///
    /// Panics if `selector` returns a reference outside the node.
    ///
    /// ```standalone_crate
    /// # use tvm_ffi::*;
    /// # use tvm_ffi::StructuralMutatorView;
    /// # #[rs_object(type_key = "my_ext.MyPair", final)]
    /// # pub struct MyPairObj { base_: Object, pub first: Array<i64>, pub second: Array<i64> }
    /// # #[derive(Clone, tvm_ffi::derive::ObjectRef)]
    /// # pub struct MyPair { data: ObjectArc<MyPairObj> }
    /// # struct Pass;
    /// # #[dispatch(mutate, (MutationView<'_>, &mut StructuralMutatorView<'_, Self>), Result<UnchangedOr<Any>>)]
    /// # impl Pass {
    /// #     fn mutate_pair(&mut self, mut pair: MutationView<'_, MyPair>, mutator: &mut StructuralMutatorView<'_, Self>) -> Result<UnchangedOr<Any>> {
    /// let second = mutator.mutate(self, pair.field(|pair| &pair.second))?;
    /// #         Ok(second)
    /// #     }
    /// # }
    /// # let pair = MyPairObj::new(Object::new(), Array::from_vec(vec![1_i64]), Array::from_vec(vec![2_i64]));
    /// # structural_mutate(MyPair::from_object(pair), Pass)?;
    /// # Ok::<(), tvm_ffi::Error>(())
    /// ```
    ///
    /// See also [`structural_mutate`].
    #[inline(always)]
    pub fn field<U: MutationField>(
        &mut self,
        selector: impl for<'node> FnOnce(&'node T::ContainerType) -> &'node U,
    ) -> MutationView<'_, U> {
        let node: &T::ContainerType = self;
        let child = selector(node);
        let offset = (child as *const U)
            .addr()
            .checked_sub((node as *const T::ContainerType).addr());
        assert!(
            offset.is_some_and(|offset| {
                offset <= std::mem::size_of::<T::ContainerType>()
                    && std::mem::size_of::<U>() > 0
                    && std::mem::size_of::<U>() <= std::mem::size_of::<T::ContainerType>() - offset
            }),
            "MutationView::field must select a direct owning field"
        );
        let mut value = TVMFFIAny::new();
        // SAFETY: child is a live owning field. Copying its view acquires no owner;
        // the returned view exclusively borrows the parent view.
        unsafe { U::container_copy_to_any_view(child, &mut value) };
        // Selection and conversion may retain aliases, so check the parent last.
        let mode = self.mode.for_value(self.value);
        MutationView::from_raw(value, mode)
    }
}

/// The running structural mutation, passed to each handler.
///
/// A handler that matches a node decides how its children are rewritten: call
/// [`default_mutate`](Self::default_mutate) to rewrite every child through the
/// dispatcher, [`mutate`](Self::mutate) to rewrite one value, or neither to
/// leave the children as they are. Pass the handler's own `self` as `dispatch`
/// to every method.
///
/// See also [`structural_mutate`].
pub struct StructuralMutatorView<'a, D, Base = StructuralMutatorObj> {
    runtime: StructuralMutatorHandle,
    #[allow(clippy::type_complexity)]
    _marker: PhantomData<(&'a mut (), fn(&mut D) -> Base, Rc<()>)>,
}

// -----------------------------------------------------------------------------
// Public mutation API and entrypoint
// -----------------------------------------------------------------------------

impl<D, Base: StructuralMutatorBase> StructuralMutatorView<'_, D, Base> {
    /// Inspect the base state without retaining the scoped mutator runtime.
    ///
    /// # Returns
    ///
    /// The base state, borrowed for the lifetime of this view.
    #[inline(always)]
    pub fn base(&self) -> &Base {
        // SAFETY: the unsafe base contract permits shared inspection, including
        // native mutation through interior-mutable fields during recursion.
        unsafe { &*self.runtime.cast::<Base>() }
    }

    #[inline(always)]
    fn reborrow(&self) -> StructuralMutatorView<'_, D, Base> {
        StructuralMutatorView {
            runtime: self.runtime,
            _marker: PhantomData,
        }
    }

    /// Return the definition region the current value is in.
    ///
    /// Reflected fields marked as definitions set it while their values are
    /// mutated; it is [`DefRegionKind::None`] elsewhere.
    ///
    /// # Returns
    ///
    /// The current definition region.
    #[inline(always)]
    pub fn def_region_kind(&self) -> DefRegionKind {
        // SAFETY: the view's runtime is live.
        unsafe { std::mem::transmute(*(*self.runtime).def_region_mode.get()) }
    }

    /// Run `callback` under a scoped definition region.
    ///
    /// An enclosing [`DefRegionKind::Pattern`] region keeps precedence, since a
    /// pattern applies to everything inside it. The previous region is restored
    /// afterwards.
    ///
    /// # Arguments
    ///
    /// * `kind` - The definition region to enter.
    /// * `callback` - Runs inside the region, with this view.
    ///
    /// # Returns
    ///
    /// The result of `callback`.
    #[inline(always)]
    pub fn with_def_region_kind<R>(
        &mut self,
        kind: DefRegionKind,
        callback: impl FnOnce(&mut StructuralMutatorView<'_, D, Base>) -> R,
    ) -> R {
        // SAFETY: the view's runtime outlives the callback.
        StructuralMutatorObj::with_def_region_kind(self.runtime, kind, |_| {
            callback(&mut self.reborrow())
        })
    }

    /// Mutate `value` through the dispatcher, as if the traversal had reached it.
    ///
    /// `value` keeps the mode it carries. Use it to rewrite a value other
    /// than the current node, such as a field selected with
    /// [`MutationView::field`].
    ///
    /// # Arguments
    ///
    /// * `dispatch` - The handler's own `self`.
    /// * `value` - The value to mutate.
    ///
    /// # Returns
    ///
    /// The replacement, or [`Unchanged`].
    ///
    /// # Errors
    ///
    /// Returns the error of the handler that `value` reaches.
    #[inline(always)]
    pub fn mutate<'input, T>(
        &mut self,
        dispatch: &mut D,
        value: impl Into<MutationView<'input, T>>,
    ) -> Result<UnchangedOr<Any>> {
        let value = value.into();
        unsafe {
            let context =
                StructuralMutateEngine::<Base>::checked_dispatcher(self.runtime, dispatch);
            (*StructuralMutateEngine::<Base>::from_handle(self.runtime)).dispatcher = context;
            StructuralMutatorObj::call_mutator(self.runtime, value.value, value.mode)
        }
        .and_then(UnchangedOr::from_carrier)
    }

    /// Rewrite the children of `value` through the dispatcher, without dispatching
    /// `value` itself again.
    ///
    /// Children are found by the type's registered mutation hook or its reflected
    /// fields. A hook uses the mutator only through its arguments, during the
    /// call, and must not keep it or call it outside them. The result is
    /// unchanged when no child changed; otherwise it is a node with the new
    /// children, made in place when `value` allows it and is uniquely owned.
    ///
    /// # Arguments
    ///
    /// * `dispatch` - The handler's own `self`.
    /// * `value` - The value whose children to mutate, usually the view the
    ///   handler received.
    ///
    /// # Returns
    ///
    /// The rewritten node, or [`Unchanged`].
    ///
    /// # Errors
    ///
    /// Returns the first error of a child's handler.
    #[inline(always)]
    pub fn default_mutate<'input, T>(
        &mut self,
        dispatch: &mut D,
        value: impl Into<MutationView<'input, T>>,
    ) -> Result<UnchangedOr<Any>> {
        let value = value.into();
        unsafe {
            let context =
                StructuralMutateEngine::<Base>::checked_dispatcher(self.runtime, dispatch);
            raw_ffi_any_into_result(StructuralMutateEngine::<Base>::publish_and_descend_raw(
                self.runtime,
                context,
                value.value,
                value.mode,
            ))
        }
        .and_then(UnchangedOr::from_carrier)
    }

    /// Look up the replacement recorded for a variable in this mutation.
    ///
    /// Default mutation records the result of every free variable and DAG node it
    /// rewrites, and replaces each later occurrence with it.
    ///
    /// # Arguments
    ///
    /// * `dispatch` - The handler's own `self`.
    /// * `var` - The variable, an object.
    ///
    /// # Returns
    ///
    /// The recorded replacement, or `None`.
    ///
    /// # Errors
    ///
    /// Returns a `TypeError` if `var` is not an object.
    #[inline(always)]
    pub fn var_remap_get(&mut self, dispatch: &mut D, var: AnyView<'_>) -> Result<Option<Any>> {
        unsafe {
            StructuralMutateEngine::<Base>::checked_dispatcher(self.runtime, dispatch);
            StructuralMutateEngine::<Base>::runtime_var_remap_get(
                self.runtime,
                *var.as_raw_ffi_any(),
            )
        }
    }

    /// Record a replacement for a variable for the rest of this mutation.
    ///
    /// Default mutation then replaces each later occurrence of `var`, a free
    /// variable or DAG node, with `value`.
    ///
    /// # Arguments
    ///
    /// * `dispatch` - The handler's own `self`.
    /// * `var` - The variable, an object.
    /// * `value` - The replacement.
    ///
    /// # Returns
    ///
    /// `Ok(())` once the replacement is recorded.
    ///
    /// # Errors
    ///
    /// Returns a `TypeError` if `var` is not an object.
    #[inline(always)]
    pub fn var_remap_set(&mut self, dispatch: &mut D, var: AnyView<'_>, value: &Any) -> Result<()> {
        unsafe {
            StructuralMutateEngine::<Base>::checked_dispatcher(self.runtime, dispatch);
            StructuralMutateEngine::<Base>::runtime_var_remap_set(
                self.runtime,
                *var.as_raw_ffi_any(),
                value,
            )
        }
    }
}

/// Mutate a structured value with an owned or borrowed [`Dispatcher`].
///
/// The root is consumed to establish the ownership boundary for optional
/// in-place mutation. A matching callback supplies the final value; unmatched
/// values use default mutation.
///
/// Callbacks must report failures through [`Result`] and must not panic: a panic
/// reaching the non-unwinding native callback boundary aborts the process.
///
/// A callback must not modify an `ffi.List` or `ffi.Dict` that holds the
/// value it receives or one of that value's ancestors: the traversal borrows
/// their cells while the callback runs. A callback that returns an `Error`
/// object as its value fails the traversal with a `TypeError`.
///
/// # Arguments
///
/// * `root` - Owned value to mutate, convertible into an [`Any`]. A uniquely
///   owned container may be reused in place; clone first to preserve the original.
/// * `dispatcher` - Owned or mutably borrowed dispatcher implementing [`IntoDispatcher`].
///   Matching handlers return replacements and control recursion through
///   [`StructuralMutatorView`]; unmatched values use default mutation. For closure
///   callbacks with automatic recursion, use [`structural_map`](crate::structural_map).
///
/// # Examples
///
/// Double the integers in nested arrays; default mutation descends into the
/// arrays:
///
/// ```
/// use tvm_ffi::{dispatch, structural_mutate, Any, Array, MutationView, Result, UnchangedOr};
/// use tvm_ffi::StructuralMutatorView;
///
/// struct Double;
///
/// #[dispatch(mutate, (MutationView<'_>, &mut StructuralMutatorView<'_, Self>), Result<UnchangedOr<Any>>)]
/// impl Double {
///     fn mutate_int(
///         &mut self,
///         value: i64,
///         _: &mut StructuralMutatorView<'_, Self>,
///     ) -> Result<UnchangedOr<Any>> {
///         Ok((value * 2).into())
///     }
/// }
///
/// let root = Array::from_vec(vec![Array::from_vec(vec![1_i64, 2]), Array::from_vec(vec![3_i64])]);
/// let result = Array::<Array<i64>>::try_from(structural_mutate(root, Double)?)?;
/// assert_eq!(result[0].iter().copied().collect::<Vec<_>>(), vec![2, 4]);
/// # Ok::<(), tvm_ffi::Error>(())
/// ```
pub fn structural_mutate<R, H, M, D, O>(root: R, dispatcher: H) -> Result<Any>
where
    R: Into<Any>,
    O: BorrowMut<D>,
    for<'v, 'c, 'r> H: IntoDispatcher<
            (
                MutationView<'v>,
                &'c mut StructuralMutatorView<'r, D, StructuralMutatorObj>,
            ),
            Option<Result<UnchangedOr<Any>>>,
            M,
            Target = D,
            Output = O,
        >,
    for<'s, 'v, 'c, 'r> &'s mut D: crate::Dispatcher<
            (
                MutationView<'v>,
                &'c mut StructuralMutatorView<'r, D, StructuralMutatorObj>,
            ),
            Option<Result<UnchangedOr<Any>>>,
        >,
{
    StructuralMutateEngine::mutate_root(root, dispatcher)
}

mod callback_result_sealed {
    use super::{Any, Result};

    pub trait Sealed {}

    impl<T: Into<Any>> Sealed for T {}
    impl<T: Into<Any>> Sealed for Result<T> {}
}

/// Convert an infallible or fallible map or mutation callback result into
/// [`Result<UnchangedOr<Any>>`].
///
/// A callback may return any value convertible into [`Any`], including
/// [`Unchanged`] and [`UnchangedOr`], or wrap it in [`Result`] to use `?`.
///
/// This trait is sealed and is not an extension point.
#[doc(hidden)]
pub trait IntoMutateResult: callback_result_sealed::Sealed {
    fn into_mutate_result(self) -> Result<UnchangedOr<Any>>;
}

impl<T: Into<Any>> IntoMutateResult for T {
    #[inline(always)]
    fn into_mutate_result(self) -> Result<UnchangedOr<Any>> {
        Ok(UnchangedOr::from_any(self.into()))
    }
}

impl<T: Into<Any>> IntoMutateResult for Result<T> {
    #[inline(always)]
    fn into_mutate_result(self) -> Result<UnchangedOr<Any>> {
        self.map(|value| UnchangedOr::from_any(value.into()))
    }
}

// -----------------------------------------------------------------------------
// StructuralMutateEngine implementation
// -----------------------------------------------------------------------------

// Perf note: Raw carriers avoid materializing an owning Any on the success path.
// Private C-unwind boundaries return this 16-byte carrier in x0/x1 on AArch64,
// avoiding the hidden result slot observed with the Rust ABI while allowing
// Rust cleanup to unwind. Native vtables remain extern "C".
// Raw bits provide no ownership guard: import an owning result into Any before
// fallible work or destruction of an observer; borrowed inputs must stay live.
impl<Base: StructuralMutatorBase> StructuralMutateEngine<Base> {
    /// Mutate `root` with `dispatcher` on the native base `Base`. See also [`structural_mutate`].
    #[inline(always)]
    pub fn mutate_root<R, H, M, D, O>(root: R, dispatcher: H) -> Result<Any>
    where
        R: Into<Any>,
        O: BorrowMut<D>,
        for<'v, 'c, 'r> H: IntoDispatcher<
                (MutationView<'v>, &'c mut StructuralMutatorView<'r, D, Base>),
                Option<Result<UnchangedOr<Any>>>,
                M,
                Target = D,
                Output = O,
            >,
        for<'s, 'v, 'c, 'r> &'s mut D: crate::Dispatcher<
                (MutationView<'v>, &'c mut StructuralMutatorView<'r, D, Base>),
                Option<Result<UnchangedOr<Any>>>,
            >,
    {
        // Normalize the input once. Named dispatchers keep their own recursive view
        // type; callback and tuple targets are their aggregate adapters.
        let mut storage = dispatcher.into_dispatcher();
        Self::run_mutator::<D, true>(root.into(), storage.borrow_mut())
    }

    /// The engine whose first field is the native prefix `runtime`.
    ///
    /// # Safety
    ///
    /// `runtime` is this live Rust engine, not an arbitrary native mutator; only raw
    /// projections of the result may cross recursion.
    #[inline(always)]
    unsafe fn from_handle(runtime: StructuralMutatorHandle) -> *mut Self {
        runtime.cast()
    }

    /// Validate a recursive caller and return its current exclusive reborrow.
    ///
    /// # Safety
    /// `runtime` must belong to the live invocation of `dispatch` with matching `D`.
    /// The identity check does not replace that lifetime/type contract; mismatch panics.
    #[inline(always)]
    unsafe fn checked_dispatcher<D>(
        runtime: StructuralMutatorHandle,
        dispatch: &mut D,
    ) -> *mut c_void {
        let context = std::ptr::from_mut(dispatch).cast();
        if context != unsafe { (*Self::from_handle(runtime)).dispatcher } {
            core::hint::cold_path();
            wrong_dispatcher();
        }
        context
    }

    /// Build native callbacks for dispatcher `D`. `CALLBACK_CONTEXT` selects
    /// whether direct callback failures receive input context; map adapters add their own.
    #[inline(always)]
    fn vtable<D, const CALLBACK_CONTEXT: bool>() -> &'static StructuralMutatorVTable
    where
        for<'s, 'v, 'c, 'r> &'s mut D: Dispatcher<
                (MutationView<'v>, &'c mut StructuralMutatorView<'r, D, Base>),
                Option<Result<UnchangedOr<Any>>>,
            >,
    {
        &StructuralMutatorVTable {
            mutate: Self::rust_vtable_mutate::<D, false, CALLBACK_CONTEXT>,
            maybe_inplace_mutate: Self::rust_vtable_mutate::<D, true, CALLBACK_CONTEXT>,
            var_remap_get: Self::rust_vtable_var_remap_get,
            var_remap_set: Self::rust_vtable_var_remap_set,
        }
    }

    /// Enter a native callback with borrowed `value` and return one owning raw result.
    /// `INPLACE` sets the mode only; uniqueness is checked before dispatch.
    ///
    /// # Safety
    /// `runtime` must have this `D` vtable and a live published exclusive reborrow.
    /// The ABI lifetime on `value` is erased: it remains valid only during this call.
    /// Callbacks report errors through results and must not unwind across this C boundary.
    unsafe extern "C" fn rust_vtable_mutate<D, const INPLACE: bool, const CALLBACK_CONTEXT: bool>(
        runtime: StructuralMutatorHandle,
        value: AnyView<'static>,
    ) -> TVMFFIAny
    where
        for<'s, 'v, 'c, 'r> &'s mut D: Dispatcher<
                (MutationView<'v>, &'c mut StructuralMutatorView<'r, D, Base>),
                Option<Result<UnchangedOr<Any>>>,
            >,
    {
        let context = unsafe { (*Self::from_handle(runtime)).dispatcher };
        let raw = *value.as_raw_ffi_any();
        let mode = if INPLACE {
            InplaceMode::Allow
        } else {
            InplaceMode::Disallow
        };
        let mode = mode.for_value(raw);
        let dispatch = unsafe { &mut *context.cast::<D>() };
        let mut mutator = StructuralMutatorView {
            runtime,
            _marker: PhantomData,
        };
        let result = match Dispatcher::dispatch_tuple(
            &mut *dispatch,
            (MutationView::new(value, mode), &mut mutator),
        ) {
            // Map adapters attribute errors to their possibly replaced value;
            // direct mutation attributes callback failures to this input.
            Some(result) => {
                let result = result.map(Any::from).and_then(reject_error_value);
                result_into_raw_ffi_any(if CALLBACK_CONTEXT {
                    result.map_err(|error| update_visit_error_context(error, raw))
                } else {
                    result
                })
            }
            None => unsafe {
                Self::publish_and_descend_raw(
                    runtime,
                    std::ptr::from_mut(dispatch).cast(),
                    raw,
                    mode,
                )
            },
        };
        // All callback reborrows have ended before restoring the caller's provenance.
        unsafe { (*Self::from_handle(runtime)).dispatcher = context };
        result
    }

    /// Publish `context`, then descend through hooks or reflection for borrowed `raw`.
    /// `mode` is an upper bound, not proof of uniqueness. Returns one owning token.
    ///
    /// # Safety
    /// `runtime` must be live; `context` must be its current exclusive dispatcher
    /// reborrow, and `raw` must remain valid throughout synchronous descent.
    #[inline(always)]
    unsafe fn publish_and_descend_raw(
        runtime: StructuralMutatorHandle,
        context: *mut c_void,
        raw: TVMFFIAny,
        mode: InplaceMode,
    ) -> TVMFFIAny {
        unsafe { (*Self::from_handle(runtime)).dispatcher = context };
        unsafe {
            <Base as StructuralMutatorBase>::default_mutate_raw(
                runtime.cast(),
                MutationView::new(AnyView::from_raw_ffi_any(raw), mode),
            )
        }
    }

    /// Look up borrowed identity `raw` in the invocation remap, cloning its value.
    ///
    /// # Safety
    /// `runtime` and the object represented by `raw` must remain live for this lookup.
    /// The RefCell borrow ends before the owning result reaches the caller.
    #[inline(always)]
    unsafe fn runtime_var_remap_get(
        runtime: StructuralMutatorHandle,
        raw: TVMFFIAny,
    ) -> Result<Option<Any>> {
        unsafe {
            (*Self::from_handle(runtime))
                .remap
                .borrow()
                .get(AnyView::from_raw_ffi_any(raw))
        }
    }

    /// Record borrowed identity `raw` and clone `value` into the invocation remap.
    ///
    /// # Safety
    /// `runtime`, `raw`, and `value` must remain live through insertion. The remap
    /// retains each new key once; no RefCell borrow escapes this call.
    #[inline(always)]
    unsafe fn runtime_var_remap_set(
        runtime: StructuralMutatorHandle,
        raw: TVMFFIAny,
        value: &Any,
    ) -> Result<()> {
        unsafe {
            (*Self::from_handle(runtime))
                .remap
                .borrow_mut()
                .set(AnyView::from_raw_ffi_any(raw), value)
        }
    }

    /// Native remap lookup: borrow `var`, return an owning value, None, or Error.
    ///
    /// # Safety
    /// `runtime` must be this live engine and `var` valid for the call despite its
    /// erased ABI lifetime. Rust panics cannot cross this native C boundary.
    unsafe extern "C" fn rust_vtable_var_remap_get(
        runtime: StructuralMutatorHandle,
        var: AnyView<'static>,
    ) -> TVMFFIAny {
        match unsafe { Self::runtime_var_remap_get(runtime, *var.as_raw_ffi_any()) } {
            Ok(Some(value)) => Any::into_raw_ffi_any(value),
            Ok(None) => TVMFFIAny::new(),
            Err(error) => result_into_raw_ffi_any(Err(error)),
        }
    }

    /// Native remap update borrowing `var` and `replacement`; return owning None/Error.
    ///
    /// # Safety
    /// Both views and this Rust `runtime` must remain live for the synchronous call.
    /// Replacement ownership is acquired before insertion; panics cannot cross C.
    unsafe extern "C" fn rust_vtable_var_remap_set(
        runtime: StructuralMutatorHandle,
        var: AnyView<'static>,
        replacement: AnyView<'static>,
    ) -> TVMFFIAny {
        // Finish replacement cleanup before constructing the ABI result.
        let result =
            raw_ffi_any_to_owned_any(*replacement.as_raw_ffi_any()).and_then(|value| unsafe {
                Self::runtime_var_remap_set(runtime, *var.as_raw_ffi_any(), &value)
            });
        result_into_raw_ffi_any(result.map(|()| Any::new()))
    }

    /// Run the public mutate/map adapter with owned `root` and borrowed `dispatch`.
    /// `CALLBACK_CONTEXT` distinguishes direct mutation from map error attribution.
    /// Keep the owning result and root live across engine/remap destruction, including
    /// unwind, then replace Unchanged with the original root. Hooks may not retain
    /// the scoped runtime or dispatcher after this call.
    pub(super) fn run_mutator<D, const CALLBACK_CONTEXT: bool>(
        root: Any,
        dispatch: &mut D,
    ) -> Result<Any>
    where
        for<'s, 'v, 'c, 'r> &'s mut D: Dispatcher<
                (MutationView<'v>, &'c mut StructuralMutatorView<'r, D, Base>),
                Option<Result<UnchangedOr<Any>>>,
            >,
    {
        let mut base = Base::new()?;
        let type_index = Base::type_index();
        // Initialize the native prefix before allocation, so the ordinary base's
        // default region value and this reset can be folded into one write.
        unsafe {
            let prefix = std::ptr::from_mut(&mut base).cast::<StructuralMutatorObj>();
            *(*prefix).def_region_mode.get() = DefRegionKind::None as i32;
        }
        let mut engine = unsafe {
            ObjectArc::<Object>::new_opaque_unchecked(
                Self {
                    base,
                    dispatcher: std::ptr::from_mut(dispatch).cast(),
                    remap: RefCell::new(StructuralVarRemap::default()),
                },
                type_index,
            )
        };
        let runtime = ObjectArc::as_mut_ptr(&mut engine).cast::<StructuralMutatorObj>();
        unsafe { (*runtime).vtable = Self::vtable::<D, CALLBACK_CONTEXT>() };
        let result =
            StructuralMutatorObj::call_mutator(runtime, *root.as_raw_ffi_any(), InplaceMode::Allow);
        // Native hooks release temporary runtime owners before this synchronous run ends.
        drop(engine);
        match result {
            Ok(value) => Ok(if is_unchanged(&value) { root } else { value }),
            // The public traversal boundary, as the C++ `StructuralMutateExpected`.
            Err(error) => Err(enrich_visit_error(error, *root.as_raw_ffi_any())),
        }
    }
}

// -----------------------------------------------------------------------------
// Prefix-only default traversal and native ABI operations
// -----------------------------------------------------------------------------

// Prefix operations use only the native layout and installed vtable.
impl StructuralMutatorObj {
    /// Consume a native hook's `result`, naming the borrowed `raw` in it when it is an Error.
    ///
    /// # Safety
    ///
    /// `result` owns one valid value and `raw` outlives the call.
    #[inline(always)]
    unsafe fn with_native_mutation_context_raw(result: TVMFFIAny, raw: TVMFFIAny) -> TVMFFIAny {
        if result.type_index != TVMFFITypeIndex::kTVMFFIError as i32 {
            result
        } else {
            core::hint::cold_path();
            unsafe { Self::with_mutation_context_raw(result, raw) }
        }
    }

    /// The cold arm of [`Self::with_native_mutation_context_raw`].
    ///
    /// # Safety
    ///
    /// `result` owns one Error, and `raw` is a live borrowed value.
    #[cold]
    #[inline(never)]
    unsafe extern "C-unwind" fn with_mutation_context_raw(
        result: TVMFFIAny,
        raw: TVMFFIAny,
    ) -> TVMFFIAny {
        unsafe {
            result_into_raw_ffi_any(
                raw_ffi_any_into_result(result)
                    .map_err(|error| update_visit_error_context(error, raw)),
            )
        }
    }

    /// Mutate the reflected fields of a shallow copy of borrowed `raw`; `Unchanged` when no
    /// field changed.
    fn map_reflected(
        runtime: StructuralMutatorHandle,
        raw: TVMFFIAny,
        def_region_kind: DefRegionKind,
        type_info: *const crate::tvm_ffi_sys::TVMFFITypeInfo,
    ) -> Result<Any> {
        let inherited_region =
            free_var_child_region(def_region_kind, unsafe { seq_hash_kind(type_info) });
        // Match the C++ reflected-mutation contract: resolve and invoke the
        // shallow-copy hook before inspecting any fields. Besides providing
        // isolated setter storage, this means a missing or failing hook is an
        // error even when no field eventually changes.
        let output = shallow_copy(raw)?;
        let output_raw = *output.as_raw_ffi_any();
        let output_object = unsafe { output_raw.data_union.v_obj.cast::<u8>() };
        if output_object.is_null() {
            return Err(runtime_error(
                "native structural mutate: shallow copy has a null object pointer",
            ));
        }

        let mut field_changed = false;
        let mut failure: Option<Error> = None;
        unsafe {
            for_each_field_info(type_info, &mut |field| {
                if field.flags & FLAG_SEQ_HASH_IGNORE != 0 {
                    return ControlFlow::Continue(());
                }
                match Self::map_reflected_field(
                    runtime,
                    output_object,
                    field,
                    inherited_region,
                    &mut field_changed,
                ) {
                    Ok(()) => ControlFlow::Continue(()),
                    Err(error) => {
                        failure = Some(error);
                        ControlFlow::Break(())
                    }
                }
            });
        }
        if let Some(error) = failure {
            return Err(error);
        }
        if field_changed {
            Ok(output)
        } else {
            Ok(Unchanged.into())
        }
    }

    /// Mutate one reflected `field` of `output_object`, setting `field_changed` on a
    /// replacement.
    ///
    /// # Safety
    ///
    /// `runtime` is live, and `field` describes `output_object`'s storage.
    unsafe fn map_reflected_field(
        runtime: StructuralMutatorHandle,
        output_object: *mut u8,
        field: &TVMFFIFieldInfo,
        inherited_region: DefRegionKind,
        field_changed: &mut bool,
    ) -> Result<()> {
        let Some(getter) = field.getter else {
            return Err(unsafe {
                missing_field_getter_error("structural mutate", field.name.as_str())
            });
        };
        // Read every field from the copy so earlier setters' side effects are
        // visible to later field mappings, exactly as in the C++ fallback.
        let field_offset = usize::try_from(field.offset)
            .map_err(|_| unsafe { invalid_field_offset_error(field.name.as_str()) })?;
        // SAFETY: registered reflection metadata guarantees that the field
        // offset lies within this object's allocation. The checked conversion
        // above also prevents truncation on 32-bit targets.
        let source_address = unsafe { output_object.add(field_offset).cast::<c_void>() };
        // Own the output slot before entering foreign code. A getter may
        // populate an owning result and still report an error.
        let mut child = Any::new();
        if unsafe { getter(source_address, Any::as_raw_ffi_any_mut(&mut child)) } != 0 {
            return Err(Error::from_raised());
        }
        // Reflection getters return owning values. Keep the child alive for
        // the complete recursive call, then let normal Drop release it.
        let child_raw = *child.as_raw_ffi_any();
        let child_region = field_def_region(field, inherited_region);
        let mapped = Self::with_def_region_kind(runtime, child_region, |_| {
            Self::call_mutator(runtime, child_raw, InplaceMode::Disallow)
        })?;
        if is_unchanged(&mapped) || raw_ffi_any_same_as(child_raw, *mapped.as_raw_ffi_any()) {
            return Ok(());
        }

        call_field_setter(field, source_address, mapped.as_raw_ffi_any())?;
        *field_changed = true;
        Ok(())
    }

    /// Dispatch borrowed `raw` through the runtime's vtable, in place when `mode` allows
    /// it and `raw` is unique.
    #[inline(always)]
    fn call_mutator(
        runtime: StructuralMutatorHandle,
        raw: TVMFFIAny,
        mode: InplaceMode,
    ) -> Result<Any> {
        let callback = unsafe {
            if mode.for_value(raw) == InplaceMode::Allow {
                (*(*runtime).vtable).maybe_inplace_mutate
            } else {
                (*(*runtime).vtable).mutate
            }
        };
        unsafe {
            let view = AnyView::from_raw_ffi_any(raw);
            raw_ffi_any_into_result(callback(runtime, view))
        }
    }

    /// The registered mutation hook of `raw`: the in-place one when `mode` allows it and
    /// `raw` is unique, otherwise the copying one.
    #[inline(always)]
    fn structural_mutate_hook(raw: TVMFFIAny, mode: InplaceMode) -> Option<TVMFFIAny> {
        if mode.for_value(raw) == InplaceMode::Allow
            && let Some(attr) = structural_mutate_column::<true>().get_raw_ffi_any(raw.type_index)
            && (attr.type_index == TVMFFITypeIndex::kTVMFFIOpaquePtr as i32
                || attr.type_index == TVMFFITypeIndex::kTVMFFIFunction as i32)
        {
            return Some(attr);
        }
        let attr = structural_mutate_column::<false>().get_raw_ffi_any(raw.type_index)?;
        (attr.type_index != TVMFFITypeIndex::kTVMFFINone as i32).then_some(attr)
    }

    /// Call the registered mutation `hook` (native pointer or packed function) on `value`.
    ///
    /// # Safety
    ///
    /// `runtime` is live with its dispatcher published, `value` and `hook` outlive the call,
    /// the caller's mode allows any in-place mutation the hook performs, and a native hook
    /// has the mutation ABI for this runtime's layout and obeys [`StructuralMutatorBase`]'s
    /// non-escaping contract.
    #[inline(always)]
    pub unsafe fn call_structural_mutate_hook_raw(
        runtime: *mut Self,
        value: TVMFFIAny,
        hook: TVMFFIAny,
    ) -> TVMFFIAny {
        unsafe {
            if hook.type_index == TVMFFITypeIndex::kTVMFFIOpaquePtr as i32 {
                let callback: FStructuralMutate = std::mem::transmute(hook.data_union.v_ptr);
                Self::with_native_mutation_context_raw(
                    callback(runtime, AnyView::from_raw_ffi_any(value)),
                    value,
                )
            } else {
                Self::call_structural_mutate_hook_slow_raw(runtime, value, hook)
            }
        }
    }

    /// The packed-function arm of [`Self::call_structural_mutate_hook_raw`], outlined as cold.
    ///
    /// # Safety
    ///
    /// As [`Self::call_structural_mutate_hook_raw`].
    #[cold]
    #[inline(never)]
    unsafe extern "C-unwind" fn call_structural_mutate_hook_slow_raw(
        runtime: StructuralMutatorHandle,
        raw: TVMFFIAny,
        attr: TVMFFIAny,
    ) -> TVMFFIAny {
        let result = if attr.type_index == TVMFFITypeIndex::kTVMFFIFunction as i32 {
            unsafe {
                Function::try_from(AnyView::from_raw_ffi_any(attr)).and_then(|function| {
                    function.call_packed(&[
                        Self::borrowed_mutator_view(runtime),
                        AnyView::from_raw_ffi_any(raw),
                    ])
                })
            }
        } else {
            Err(invalid_mutation_hook_error())
        };
        // Preserve successful Error-valued returns until the public conversion.
        result_into_raw_ffi_any(result.map_err(|error| update_visit_error_context(error, raw)))
    }

    /// Borrow the live `runtime` as an object argument, without a reference count.
    ///
    /// # Safety
    ///
    /// `runtime` outlives the returned view.
    #[inline(always)]
    unsafe fn borrowed_mutator_view<'a>(runtime: StructuralMutatorHandle) -> AnyView<'a> {
        let object = runtime.cast::<TVMFFIObject>();
        let mut raw = TVMFFIAny::new();
        raw.type_index = unsafe { (*object).type_index };
        raw.small_str_len = 0;
        raw.data_union.v_obj = object;
        unsafe { AnyView::from_raw_ffi_any(raw) }
    }

    /// Run `callback` under requested `kind` on live borrowed `mutator`.
    /// Pattern precedence is retained; pass the effective kind to the callback and
    /// restore prior state on normal return or Rust unwind. Internal callers keep
    /// the runtime live and do not retain a reference to its mutable region field.
    #[inline(always)]
    fn with_def_region_kind<T>(
        mutator: StructuralMutatorHandle,
        kind: DefRegionKind,
        callback: impl FnOnce(DefRegionKind) -> T,
    ) -> T {
        unsafe {
            let previous = *(*mutator).def_region_mode.get();
            if previous == kind as i32 || previous == DefRegionKind::Pattern as i32 {
                // Inherited descent does not change state; Pattern keeps precedence.
                return callback(std::mem::transmute::<i32, DefRegionKind>(previous));
            }
            *(*mutator).def_region_mode.get() = kind as i32;
            struct Restore {
                mutator: StructuralMutatorHandle,
                previous: i32,
            }
            impl Drop for Restore {
                #[inline(always)]
                fn drop(&mut self) {
                    unsafe { *(*self.mutator).def_region_mode.get() = self.previous };
                }
            }
            let _restore = Restore { mutator, previous };
            // One call site keeps the continuation visible to the inliner.
            callback(kind)
        }
    }

    /// Mutate borrowed `raw` by reflection, caching free variables and DAG nodes
    /// through the vtable remap.
    ///
    /// # Safety
    ///
    /// `runtime` is a live mutator prefix with its vtable, and `raw` outlives the call.
    /// Outlined (frequent, not cold) to keep reflection scratch out of recursive frames.
    #[inline(never)]
    unsafe extern "C-unwind" fn mutate_without_hook_raw(
        runtime: StructuralMutatorHandle,
        raw: TVMFFIAny,
    ) -> TVMFFIAny {
        // Read the region here rather than on the native-hook path, which does not use it.
        let def_region_kind =
            unsafe { std::mem::transmute::<i32, DefRegionKind>(*(*runtime).def_region_mode.get()) };
        result_into_raw_ffi_any(
            Self::mutate_without_hook(runtime, raw, def_region_kind)
                .map_err(|error| update_visit_error_context(error, raw)),
        )
    }

    /// Borrow the native remap interface without assuming the complete engine layout.
    /// The vtable owns its returned replacement, including Unchanged markers.
    #[inline(always)]
    unsafe fn var_remap_get(
        runtime: StructuralMutatorHandle,
        raw: TVMFFIAny,
    ) -> Result<Option<Any>> {
        let callback = unsafe { (*(*runtime).vtable).var_remap_get };
        let value =
            unsafe { raw_ffi_any_into_result(callback(runtime, AnyView::from_raw_ffi_any(raw)))? };
        Ok((value.type_index() != TVMFFITypeIndex::kTVMFFINone as i32).then_some(value))
    }

    /// Borrow both inputs through the native remap interface; it retains the key
    /// and replacement. Import the owning None/Error result before returning.
    #[inline(always)]
    unsafe fn var_remap_set(
        runtime: StructuralMutatorHandle,
        raw: TVMFFIAny,
        value: &Any,
    ) -> Result<()> {
        let callback = unsafe { (*(*runtime).vtable).var_remap_set };
        unsafe {
            raw_ffi_any_into_result(callback(
                runtime,
                AnyView::from_raw_ffi_any(raw),
                AnyView::from_raw_ffi_any(*value.as_raw_ffi_any()),
            ))
            .map(|_| ())
        }
    }

    /// The reflective mutation of [`Self::mutate_without_hook_raw`], on owned results.
    #[inline(always)]
    fn mutate_without_hook(
        runtime: StructuralMutatorHandle,
        raw: TVMFFIAny,
        def_region_kind: DefRegionKind,
    ) -> Result<Any> {
        if raw.type_index < TVMFFITypeIndex::kTVMFFIStaticObjectBegin as i32 {
            return raw_ffi_any_to_owned_any(raw);
        }

        let type_info = checked_type_info(raw.type_index)?;
        let kind = unsafe { seq_hash_kind(type_info) };
        let is_free_var = kind == TVMFFISEqHashKind::kTVMFFISEqHashKindFreeVar as i32;
        let is_dag_node = kind == TVMFFISEqHashKind::kTVMFFISEqHashKindDAGNode as i32;
        if is_free_var || is_dag_node {
            // The ABI uses None for a miss; an Unchanged marker is a cached result.
            if let Some(mutated) = unsafe { Self::var_remap_get(runtime, raw)? } {
                return Ok(mutated);
            }
        }
        // A variable use with no binding retains its identity without visiting fields.
        if is_free_var && def_region_kind == DefRegionKind::None {
            return Ok(Unchanged.into());
        }

        let result = Self::map_reflected(runtime, raw, def_region_kind, type_info)?;
        if is_dag_node
            || (is_free_var
                && (def_region_kind == DefRegionKind::Pattern || !is_unchanged(&result)))
        {
            // Keep markers for DAG nodes and pattern definitions. An unchanged simple
            // definition needs no binding: subsequent uses retain the original on a miss.
            unsafe { Self::var_remap_set(runtime, raw, &result)? };
        }
        Ok(result)
    }
}

// -----------------------------------------------------------------------------
// Private utility functions
// -----------------------------------------------------------------------------

fn shallow_copy(raw: TVMFFIAny) -> Result<Any> {
    let Some(attr) = SHALLOW_COPY_COLUMN.get_raw_ffi_any(raw.type_index) else {
        return Err(missing_shallow_copy_error(
            raw.type_index,
            SHALLOW_COPY_ATTR,
        ));
    };
    if attr.type_index != TVMFFITypeIndex::kTVMFFIFunction as i32 {
        return Err(invalid_shallow_copy_hook_error(SHALLOW_COPY_ATTR));
    }
    let function = unsafe { attr.data_union.v_obj };
    if function.is_null() {
        return Err(runtime_error("shallow copy function pointer is null"));
    }
    // The registry owns this function throughout the call; borrowing it avoids
    // an atomic retain/release for every reflected node.
    let mut result = Any::new();
    let status = unsafe {
        TVMFFIFunctionCall(
            function.cast(),
            &raw,
            1,
            Any::as_raw_ffi_any_mut(&mut result),
        )
    };
    if status != 0 {
        return Err(Error::from_raised());
    }
    let result_raw = *result.as_raw_ffi_any();
    let result_pointer = unsafe { result_raw.data_union.v_obj };
    let source_pointer = unsafe { raw.data_union.v_obj };
    if result_raw.type_index != raw.type_index
        || result_pointer.is_null()
        || result_pointer == source_pointer
    {
        return Err(invalid_shallow_copy_result_error());
    }
    Ok(result)
}

fn call_field_setter(
    field: &TVMFFIFieldInfo,
    field_address: *mut c_void,
    value: &TVMFFIAny,
) -> Result<()> {
    if field.setter.is_null() {
        // SAFETY: registered field names are UTF-8 text that lives as long as the process.
        return Err(missing_field_setter_error(unsafe { field.name.as_str() }));
    }
    let return_code = unsafe {
        if field.flags & FLAG_SETTER_IS_FUNCTION == 0 {
            // SAFETY: reflection registration requires a non-Function setter
            // pointer to use the TVMFFIFieldSetter signature.
            let setter: TVMFFIFieldSetter = std::mem::transmute(field.setter);
            setter(field_address, value)
        } else {
            let mut args = [TVMFFIAny::new(), *value];
            args[0].type_index = TVMFFITypeIndex::kTVMFFIOpaquePtr as i32;
            args[0].data_union.v_ptr = field_address;
            // Own the result slot before entering foreign code so a partial
            // owning result is released on both success and failure.
            let mut result = Any::new();
            TVMFFIFunctionCall(
                field.setter as TVMFFIObjectHandle,
                args.as_ptr(),
                2,
                Any::as_raw_ffi_any_mut(&mut result),
            )
        }
    };
    if return_code == 0 {
        Ok(())
    } else {
        Err(Error::from_raised())
    }
}

fn object_identity_key(raw: TVMFFIAny) -> Result<NonNull<TVMFFIObject>> {
    if raw.type_index < TVMFFITypeIndex::kTVMFFIStaticObjectBegin as i32 {
        core::hint::cold_path();
        return Err(var_remap_key_error());
    }
    let pointer = unsafe { raw.data_union.v_obj };
    NonNull::new(pointer).ok_or_else(|| {
        core::hint::cold_path();
        runtime_error("native structural mutate: identity object has a null pointer")
    })
}

#[inline]
fn checked_type_info(type_index: i32) -> Result<*const crate::tvm_ffi_sys::TVMFFITypeInfo> {
    let info = unsafe { TVMFFIGetTypeInfo(type_index) };
    if info.is_null() {
        Err(unregistered_type_error(type_index))
    } else {
        Ok(info)
    }
}

#[inline(always)]
fn object_is_unique(raw: TVMFFIAny) -> bool {
    if raw.type_index < TVMFFITypeIndex::kTVMFFIStaticObjectBegin as i32 {
        return false;
    }
    let pointer = unsafe { raw.data_union.v_obj };
    !pointer.is_null() && unsafe { object::unsafe_::is_unique(pointer) }
}

/// Acquire an owning value from a valid borrowed carrier.
///
/// Inline values are copied and objects are retained once, including Error objects
/// as ordinary values. String/byte views are normalized by the runtime; an rvalue
/// slot transfers its reference. Internal callers keep borrowed resources live and
/// uniquely own each writable rvalue slot, converting it at most once. A null
/// object pointer or failed runtime conversion returns an error; successful Error
/// objects remain ordinary values rather than entering the error channel.
fn raw_ffi_any_to_owned_any(raw: TVMFFIAny) -> Result<Any> {
    if is_plain_inline(raw.type_index) {
        return Ok(unsafe { Any::from_raw_ffi_any(raw) });
    }
    if raw.type_index >= TVMFFITypeIndex::kTVMFFIStaticObjectBegin as i32 {
        let object = unsafe { raw.data_union.v_obj };
        if object.is_null() {
            return Err(runtime_error(
                "native structural mutate: object-backed value has a null pointer",
            ));
        }
        unsafe { object::unsafe_::inc_ref(object) };
        return Ok(unsafe { Any::from_raw_ffi_any(raw) });
    }

    // Raw string/bytes views and ObjectRValueRef require normalization (or a
    // move) rather than a bitwise copy; keep the generic C ABI conversion for
    // those uncommon representations.
    let mut owned = Any::new();
    let return_code = unsafe { TVMFFIAnyViewToOwnedAny(&raw, Any::as_raw_ffi_any_mut(&mut owned)) };
    if return_code == 0 {
        Ok(owned)
    } else {
        Err(Error::from_raised())
    }
}

// Cache registry columns, not their optional per-type cells. Absent cells retain
// the normal hook/reflection fallback.
static STRUCTURAL_MUTATE_COLUMN: ColdInitLazyLock<TypeAttrColumn> = ColdInitLazyLock::new(|| {
    TypeAttrColumn::lookup(STRUCTURAL_MUTATE_ATTR).expect("missing __s_mutate__ column")
});

static STRUCTURAL_MAYBE_INPLACE_MUTATE_COLUMN: ColdInitLazyLock<TypeAttrColumn> =
    ColdInitLazyLock::new(|| {
        TypeAttrColumn::lookup(STRUCTURAL_MAYBE_INPLACE_MUTATE_ATTR)
            .expect("missing __s_maybe_inplace_mutate__ column")
    });

/// Return the shared column for normal or permitted in-place mutation hooks.
/// Cache the column, not its per-type cells, so absent hooks still use fallback.
#[inline(always)]
fn structural_mutate_column<const INPLACE: bool>() -> TypeAttrColumn {
    if INPLACE {
        *STRUCTURAL_MAYBE_INPLACE_MUTATE_COLUMN
    } else {
        *STRUCTURAL_MUTATE_COLUMN
    }
}

static SHALLOW_COPY_COLUMN: ColdInitLazyLock<TypeAttrColumn> = ColdInitLazyLock::new(|| {
    TypeAttrColumn::lookup(SHALLOW_COPY_ATTR).expect("missing __ffi_shallow_copy__ column")
});

// -----------------------------------------------------------------------------
// Outlined errors
// -----------------------------------------------------------------------------

#[cold]
#[inline(never)]
fn missing_shallow_copy_error(type_index: i32, attribute: &str) -> Error {
    Error::new(
        TYPE_ERROR,
        &format!(
            "type `{}` cannot use reflected structural mutation because it does not define `{attribute}`",
            crate::object::type_key_of_index(type_index)
        ),
    )
}

#[cold]
#[inline(never)]
fn invalid_shallow_copy_hook_error(attribute: &str) -> Error {
    Error::new(TYPE_ERROR, &format!("{attribute} must be an ffi.Function"))
}

#[cold]
#[inline(never)]
fn invalid_shallow_copy_result_error() -> Error {
    Error::new(
        TYPE_ERROR,
        "shallow copy callback must return a distinct object with the same type as its input",
    )
}

#[cold]
#[inline(never)]
fn missing_field_setter_error(name: &str) -> Error {
    Error::new(
        TYPE_ERROR,
        &format!("cannot structurally mutate field `{name}` because it does not define a setter"),
    )
}

#[cold]
#[inline(never)]
fn invalid_field_offset_error(name: &str) -> Error {
    runtime_error(&format!(
        "native structural mutate: reflected field `{name}` has an invalid offset"
    ))
}

#[cold]
#[inline(never)]
fn invalid_mutation_hook_error() -> Error {
    Error::new(
        TYPE_ERROR,
        "__s_mutate__ must be an opaque function pointer or ffi.Function",
    )
}

#[cold]
#[inline(never)]
fn var_remap_key_error() -> Error {
    Error::new(
        TYPE_ERROR,
        "variable-remap keys must be object-backed values",
    )
}

#[cold]
#[inline(never)]
fn unregistered_type_error(type_index: i32) -> Error {
    runtime_error(&format!(
        "native structural mutate: unregistered type index {type_index}"
    ))
}