Skip to main content

tvm_ffi/extra/
structural_mutate.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20//! Native Rust structural mutation and mapping.
21//!
22//! [`structural_mutate`] lets a mutator drive recursion, while
23//! [`structural_map`](crate::structural_map) applies callbacks around engine-owned recursion.
24
25// `_raw` functions move one owned `TVMFFIAny`: forward it once, or import it into `Any` before
26// anything can unwind. Private `extern "C-unwind"` helpers return it in registers on AArch64.
27
28use std::cell::{RefCell, UnsafeCell};
29use std::collections::{HashMap, hash_map::Entry};
30use std::ffi::c_void;
31use std::marker::PhantomData;
32
33use super::cold_init_lazy_lock::ColdInitLazyLock;
34use super::dispatch::IntoDispatcher;
35use std::borrow::BorrowMut;
36use std::ops::ControlFlow;
37use std::ptr::NonNull;
38use std::rc::Rc;
39
40use super::dispatch::Dispatcher;
41use crate::any::{Any, AnyView, is_plain_inline};
42use crate::error::{Error, Result, TYPE_ERROR};
43use crate::function::Function;
44use crate::object::{self, Object, ObjectArc};
45use crate::reflection::TypeAttrColumn;
46use crate::tvm_ffi_sys::{
47    TVMFFIAny, TVMFFIAnyViewToOwnedAny, TVMFFIFieldInfo, TVMFFIFieldSetter, TVMFFIFunctionCall,
48    TVMFFIGetTypeInfo, TVMFFIObject, TVMFFITypeIndex,
49};
50use crate::tvm_ffi_sys::{TVMFFIObjectHandle, TVMFFISEqHashKind};
51
52use super::structural_common::{
53    FLAG_SEQ_HASH_IGNORE, FLAG_SETTER_IS_FUNCTION, field_def_region, for_each_field_info,
54    free_var_child_region, missing_field_getter_error, raw_ffi_any_into_result,
55    raw_ffi_any_same_as, registered_type_index, reject_error_value, result_into_raw_ffi_any,
56    runtime_error, seq_hash_kind, wrong_dispatcher,
57};
58use super::structural_visit::DefRegionKind;
59use super::unchanged::is_unchanged;
60use super::unchanged::{Unchanged, UnchangedOr};
61use super::visit_error_context::{enrich_visit_error, update_visit_error_context};
62
63const STRUCTURAL_MUTATE_ATTR: &str = "__s_mutate__";
64const STRUCTURAL_MAYBE_INPLACE_MUTATE_ATTR: &str = "__s_maybe_inplace_mutate__";
65const SHALLOW_COPY_ATTR: &str = "__ffi_shallow_copy__";
66
67// -----------------------------------------------------------------------------
68// Data structures and FFI layout
69// -----------------------------------------------------------------------------
70
71pub(super) type StructuralMutatorHandle = *mut StructuralMutatorObj;
72
73type FStructuralMutate =
74    unsafe extern "C" fn(StructuralMutatorHandle, AnyView<'static>) -> TVMFFIAny;
75
76type FStructuralVarRemapGet =
77    unsafe extern "C" fn(StructuralMutatorHandle, AnyView<'static>) -> TVMFFIAny;
78
79type FStructuralVarRemapSet =
80    unsafe extern "C" fn(StructuralMutatorHandle, AnyView<'static>, AnyView<'static>) -> TVMFFIAny;
81
82#[repr(C)]
83struct StructuralMutatorVTable {
84    mutate: FStructuralMutate,
85    maybe_inplace_mutate: FStructuralMutate,
86    var_remap_get: FStructuralVarRemapGet,
87    var_remap_set: FStructuralVarRemapSet,
88}
89
90/// The native mutator state, laid out as the prefix of the C++
91/// `StructuralMutatorObj`, with no Rust traversal state.
92#[repr(C)]
93pub struct StructuralMutatorObj {
94    base_: Object,
95    vtable: *const StructuralMutatorVTable,
96    def_region_mode: UnsafeCell<i32>,
97}
98
99// Scoped runtime prefixes are not independently allocatable ObjectCore values.
100impl StructuralMutatorObj {
101    const TYPE_KEY: &'static str = "ffi.StructuralMutator";
102}
103
104impl Default for StructuralMutatorObj {
105    #[inline(always)]
106    fn default() -> Self {
107        Self {
108            base_: Object::new(),
109            vtable: std::ptr::null(),
110            def_region_mode: UnsafeCell::new(DefRegionKind::None as i32),
111        }
112    }
113}
114
115const _: () = {
116    assert!(
117        std::mem::offset_of!(StructuralMutatorObj, vtable) == std::mem::size_of::<TVMFFIObject>()
118    );
119    assert!(
120        std::mem::offset_of!(StructuralMutatorObj, def_region_mode)
121            == std::mem::size_of::<TVMFFIObject>() + std::mem::size_of::<*const c_void>()
122    );
123};
124
125/// Native state and default mutation for [`StructuralMutateEngine`].
126/// The engine owns allocation, scoped dispatch, identity remaps and results.
127///
128/// # Safety
129///
130/// `Self` must have a complete initialized C layout with [`StructuralMutatorObj`]
131/// at offset zero, matching its registered native type and every field hooks access.
132/// Native-mutated fields require interior mutability; shared references must not
133/// freeze them during recursion. Hooks must preserve the vtable and valid region state.
134///
135/// The base must not implement [`crate::ObjectCore`] or otherwise allow callers
136/// to retain the runtime. Hooks may access the runtime and borrowed mutation
137/// state only synchronously, on the calling thread.
138///
139/// `default_mutate_raw` returns one owning ABI replacement/Unchanged/Error and recurses
140/// only through the installed vtable, preserving the input's in-place mode.
141/// No whole-base mutable reference may span recursion. Failures use the result
142/// carrier; panics must not cross native callbacks.
143pub unsafe trait StructuralMutatorBase: Sized {
144    /// Initialize the complete base before the engine installs its runtime header.
145    fn new() -> Result<Self>;
146
147    /// Native type registered for this complete base layout.
148    fn type_index() -> i32;
149
150    /// Descend from a borrowed view without dispatching that value again.
151    ///
152    /// # Safety
153    /// `runtime` is the base of a live `StructuralMutateEngine<Self>` with its
154    /// matching installed vtable.
155    /// The input and runtime remain borrowed for this synchronous call. The
156    /// caller has published the current exclusive dispatcher reborrow.
157    unsafe fn default_mutate_raw(runtime: *mut Self, value: MutationView<'_>) -> TVMFFIAny;
158}
159
160// SAFETY: this prefix exactly matches the ordinary native mutator. Its mutable
161// region is interior mutable, and it exposes no safe ownership conversion.
162unsafe impl StructuralMutatorBase for StructuralMutatorObj {
163    #[inline(always)]
164    fn new() -> Result<Self> {
165        Ok(Self::default())
166    }
167
168    fn type_index() -> i32 {
169        static TYPE_INDEX: ColdInitLazyLock<i32> =
170            ColdInitLazyLock::new(|| registered_type_index(StructuralMutatorObj::TYPE_KEY));
171        *TYPE_INDEX
172    }
173
174    #[inline(always)]
175    unsafe fn default_mutate_raw(runtime: *mut Self, value: MutationView<'_>) -> TVMFFIAny {
176        // Prefix-only: remaps go through the vtable, so any base may reuse this.
177        let raw = value.value;
178        // Registered hooks own their remapping policy; reflection handles its own.
179        // A hook that rewrites fields keeps the rebuilt object valid for the
180        // refined references that point at it.
181        if let Some(attr) = Self::structural_mutate_hook(raw, value.mode) {
182            return unsafe { Self::call_structural_mutate_hook_raw(runtime, raw, attr) };
183        }
184        unsafe { Self::mutate_without_hook_raw(runtime, raw) }
185    }
186}
187
188/// Scoped Rust mutator runtime with a statically selected native base.
189///
190/// Enter through [`StructuralMutateEngine::mutate_root`]. The engine owns the complete base,
191/// dispatcher reborrow handle and identity remaps. The dispatcher stays in the
192/// outer call; callbacks receive only a scoped [`StructuralMutatorView`].
193#[repr(C)]
194pub struct StructuralMutateEngine<Base = StructuralMutatorObj> {
195    base: Base,
196    dispatcher: *mut c_void,
197    remap: RefCell<StructuralVarRemap>,
198}
199
200/// Identity substitutions for structural mutation within one invocation.
201///
202/// Internal to the engine: handlers reach the remap through
203/// [`StructuralMutatorView::var_remap_get`] and [`StructuralMutatorView::var_remap_set`].
204///
205/// Each pointer key owns one strong reference to its original object, preventing
206/// address reuse until removal. Values are owning replacements, including
207/// [`Unchanged`] markers. Replacing a value does not acquire another key reference;
208/// lookup clones the replacement, and dropping releases every owner.
209// Perf note: Store only the replacement Any; raw identity keys avoid a second
210// Any payload, but still own one retained reference per distinct key. Replacing
211// a value does not retain the key again; Drop releases each key exactly once.
212#[derive(Default)]
213pub(crate) struct StructuralVarRemap {
214    entries: HashMap<NonNull<TVMFFIObject>, Any>,
215}
216
217impl StructuralVarRemap {
218    /// Look up an identity replacement previously stored for `var`.
219    pub(crate) fn get(&self, var: AnyView<'_>) -> Result<Option<Any>> {
220        let key = object_identity_key(*var.as_raw_ffi_any())?;
221        Ok(self.entries.get(&key).cloned())
222    }
223
224    /// Store a descent result or an [`Unchanged`] marker for `var`.
225    ///
226    /// A new key acquires one strong reference; replacing its value preserves
227    /// that reference. The replacement is cloned before modifying the table.
228    pub(crate) fn set(&mut self, var: AnyView<'_>, mutated_value: &Any) -> Result<()> {
229        let key = object_identity_key(*var.as_raw_ffi_any())?;
230        let value = mutated_value.clone();
231        match self.entries.entry(key) {
232            Entry::Occupied(mut entry) => {
233                entry.insert(value);
234            }
235            Entry::Vacant(entry) => {
236                entry.insert(value);
237                // Insertion may allocate, so retain only after it succeeds.
238                // The borrowed var still keeps key live; IncRef cannot unwind.
239                unsafe { object::unsafe_::inc_ref(key.as_ptr()) };
240            }
241        }
242        Ok(())
243    }
244}
245
246impl Drop for StructuralVarRemap {
247    fn drop(&mut self) {
248        // Release keys first: their C ABI deleters cannot unwind. Field Drop
249        // then releases values and buckets without resetting capacity for reuse.
250        // The remaining NonNull key bits are dropped without dereferencing them.
251        for key in self.entries.keys() {
252            unsafe { object::unsafe_::dec_ref(key.as_ptr()) };
253        }
254    }
255}
256
257/// Whether a [`MutationView`] may reuse its value's storage in place.
258///
259/// `Allow` is an upper bound: a value is reused in place only when it is also
260/// uniquely owned. A view made from `&mut Any` starts as `Allow`, and a view
261/// from [`MutationView::borrowed`] is always `Disallow`.
262///
263/// See also [`structural_mutate`].
264#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
265pub enum InplaceMode {
266    /// Use ordinary mutation, including for uniquely owned values.
267    #[default]
268    Disallow,
269    /// Permit reuse when ownership and alias checks allow it.
270    Allow,
271}
272
273impl InplaceMode {
274    // The mode is only an upper bound; ownership must still be unique here.
275    #[inline(always)]
276    fn for_value(self, raw: TVMFFIAny) -> Self {
277        if self == Self::Allow && object_is_unique(raw) {
278            Self::Allow
279        } else {
280            Self::Disallow
281        }
282    }
283}
284
285/// A borrowed value that a structural mutation may rewrite in place.
286///
287/// Mutation handlers receive a `MutationView` instead of an owned value, so
288/// matching a node does not retain it. Inspect the node through the view,
289/// then pass the view to [`StructuralMutatorView::default_mutate`] to rewrite
290/// its children, or rewrite one field with [`field`](MutationView::field).
291/// When the node is uniquely owned and the view carries
292/// [`InplaceMode::Allow`], its storage is reused instead of copied.
293///
294/// `T` is the matched type: `MutationView<'_, Array<Any>>` derefs to the
295/// array's node, and the default `MutationView<'_>` matches every value. The
296/// view is move-only: it cannot be copied or cloned, and consuming it passes
297/// on the same mode. A view made from `&mut Any` may reuse storage;
298/// one made with [`borrowed`](MutationView::borrowed) never does.
299///
300/// See also [`structural_mutate`].
301pub struct MutationView<'a, T = Any> {
302    value: TVMFFIAny,
303    mode: InplaceMode,
304    #[allow(clippy::type_complexity)]
305    _marker: PhantomData<(AnyView<'a>, fn() -> T, Rc<()>)>,
306}
307
308impl<T> MutationView<'_, T> {
309    /// The viewed cell, borrowed in place by `match_any!` reference patterns.
310    #[inline(always)]
311    pub(crate) fn cell(&self) -> &TVMFFIAny {
312        &self.value
313    }
314}
315
316impl<'a> MutationView<'a> {
317    #[inline(always)]
318    pub(super) fn new(value: AnyView<'a>, mode: InplaceMode) -> Self {
319        Self::from_raw(*value.as_raw_ffi_any(), mode)
320    }
321
322    /// Create a view of a borrowed value that never reuses its storage.
323    ///
324    /// The mutation result is always a new value or [`Unchanged`]. To allow reuse,
325    /// make the view from `&mut Any` instead.
326    ///
327    /// # Arguments
328    ///
329    /// * `value` - The value to view.
330    ///
331    /// # Returns
332    ///
333    /// A view with [`InplaceMode::Disallow`].
334    #[inline(always)]
335    pub fn borrowed(value: AnyView<'a>) -> Self {
336        Self::new(value, InplaceMode::Disallow)
337    }
338}
339
340impl<'a> From<&'a mut Any> for MutationView<'a> {
341    /// Borrow an owner exclusively without acquiring a reference count.
342    ///
343    /// Reuse still requires the runtime's uniqueness and alias checks.
344    #[inline(always)]
345    fn from(value: &'a mut Any) -> Self {
346        Self::new(AnyView::from(&*value), InplaceMode::Allow)
347    }
348}
349
350impl<'a, T> MutationView<'a, T> {
351    #[inline(always)]
352    fn from_raw(value: TVMFFIAny, mode: InplaceMode) -> Self {
353        Self {
354            value,
355            mode,
356            _marker: PhantomData,
357        }
358    }
359
360    /// # Safety
361    /// The original must not be used while the alias lives.
362    #[inline(always)]
363    pub(crate) unsafe fn alias(&self) -> MutationView<'a, T> {
364        MutationView::from_raw(self.value, self.mode)
365    }
366
367    // A chain may lend its view to one link at a time. The shorter lifetime
368    // prevents a matched link from retaining a borrow across the next link.
369    #[inline(always)]
370    pub(crate) fn reborrow(&mut self) -> MutationView<'_, T> {
371        MutationView::from_raw(self.value, self.mode)
372    }
373
374    /// Return the in-place mode this view carries.
375    ///
376    /// # Returns
377    ///
378    /// Whether this view may reuse its value's storage.
379    #[inline(always)]
380    pub fn inplace_mode(&self) -> InplaceMode {
381        self.mode
382    }
383
384    /// Restrict the mode, without ever upgrading it.
385    ///
386    /// `Disallow` turns off reuse. `Allow` keeps the current mode, so it never
387    /// grants reuse to a view that does not have it, such as a borrowed one.
388    ///
389    /// # Arguments
390    ///
391    /// * `requested` - The mode to restrict to.
392    ///
393    /// # Returns
394    ///
395    /// The view with the restricted mode.
396    #[inline(always)]
397    pub fn narrow_inplace_mode(mut self, requested: InplaceMode) -> Self {
398        if requested == InplaceMode::Disallow {
399            self.mode = InplaceMode::Disallow;
400        }
401        self
402    }
403
404    /// Borrow the current value.
405    ///
406    /// The view and its copies borrow this handle, so their last use must precede
407    /// consuming it for default mutation.
408    ///
409    /// # Returns
410    ///
411    /// The value as an [`AnyView`].
412    #[inline(always)]
413    pub fn as_any_view(&self) -> AnyView<'_> {
414        // SAFETY: the input owner, which a handler does not remove from a list
415        // or dict it modifies (the callback contract), keeps this payload live
416        // while the view is borrowed. The returned lifetime is bounded by self,
417        // not by 'a.
418        unsafe { AnyView::from_raw_ffi_any(self.value) }
419    }
420
421    /// Borrow the value as `U` without changing ownership or mode.
422    ///
423    /// `U` is anything [`AnyView::downcast_ref`] borrows: a managed reference such as
424    /// `Array<i64>`, an object type such as `ArrayObj`, or [`Any`], borrowed in place
425    /// without a reference-count bump. The check is strict, and the reference borrows
426    /// this view and cannot survive its consumption.
427    ///
428    /// # Returns
429    ///
430    /// The borrowed value, or `None` when the value is not a `U`.
431    #[inline(always)]
432    pub fn downcast_ref<U: crate::type_traits::DowncastRefFromAny>(&self) -> Option<&U> {
433        // SAFETY: the view holds a valid cell, borrowed for the returned lifetime,
434        // and the input owner keeps its payload live.
435        unsafe { U::downcast_ref_from_any(&self.value) }
436    }
437
438    /// Whether the value is a `U`, as [`Any::is`].
439    #[inline(always)]
440    pub fn is<U: crate::type_traits::AnyCompatible>(&self) -> bool {
441        self.as_any_view().is::<U>()
442    }
443
444    /// Narrow the matched type without acquiring an owning reference.
445    ///
446    /// The check is the strict one of `match_any!`: only a value that fits `U` as
447    /// is, elements included, matches. The view keeps its mode.
448    ///
449    /// # Returns
450    ///
451    /// The view typed as `MutationView<'_, U>`.
452    ///
453    /// # Errors
454    ///
455    /// Returns the view unchanged when the value is not a `U`, so another type can
456    /// be tried.
457    #[inline(always)]
458    pub fn downcast<U: crate::type_traits::ContainerElement>(
459        self,
460    ) -> std::result::Result<MutationView<'a, U>, Self> {
461        // SAFETY: the input owner keeps the borrowed value live for this handle's
462        // lifetime. This only checks its type and does not acquire ownership.
463        if unsafe {
464            U::container_check_any_strict(&self.value)
465                && U::container_match_constraints(&self.value)
466        } {
467            Ok(MutationView::from_raw(self.value, self.mode))
468        } else {
469            Err(self)
470        }
471    }
472
473    /// Erase the matched type while preserving the carried mode.
474    ///
475    /// # Returns
476    ///
477    /// The view as `MutationView<'_>`.
478    #[inline(always)]
479    pub fn into_untyped(self) -> MutationView<'a> {
480        MutationView::from_raw(self.value, self.mode)
481    }
482}
483
484mod mutation_field {
485    pub trait Sealed {}
486    impl Sealed for crate::Any {}
487    impl<T: crate::object::ObjectRefCore> Sealed for T {}
488}
489
490/// Owned storage supported by [`MutationView::field`].
491/// Sealed to `Any` and owning object handles; borrowed conversion adapters do not qualify.
492#[doc(hidden)]
493pub trait MutationField: crate::type_traits::ContainerElement + mutation_field::Sealed {}
494
495impl MutationField for Any {}
496
497impl<T: object::ObjectRefCore> MutationField for T {}
498
499impl<T: object::ObjectRefCore> std::ops::Deref for MutationView<'_, T> {
500    type Target = T::ContainerType;
501
502    #[inline(always)]
503    fn deref(&self) -> &Self::Target {
504        // SAFETY: typed view construction establishes T's object layout;
505        // this shared borrow cannot outlive or survive consumption of the handle.
506        unsafe { &*self.value.data_union.v_obj.cast::<T::ContainerType>() }
507    }
508}
509
510impl<T: object::ObjectRefCore> MutationView<'_, T> {
511    /// Borrow a direct owning field of the node as a view of its own, to rewrite it
512    /// with [`StructuralMutatorView::mutate`].
513    ///
514    /// The field view exclusively borrows this view. It may reuse the field's
515    /// storage only when this view may and the node remains uniquely owned. This
516    /// does not write the result back into the node: keep the node [`Unchanged`] or
517    /// rebuild it from the result.
518    ///
519    /// # Arguments
520    ///
521    /// * `selector` - Returns a reference to one of the node's own owning fields,
522    ///   an [`Any`] or a managed reference.
523    ///
524    /// # Returns
525    ///
526    /// A view of the field.
527    ///
528    /// # Panics
529    ///
530    /// Panics if `selector` returns a reference outside the node.
531    ///
532    /// ```standalone_crate
533    /// # use tvm_ffi::*;
534    /// # use tvm_ffi::StructuralMutatorView;
535    /// # #[rs_object(type_key = "my_ext.MyPair", final)]
536    /// # pub struct MyPairObj { base_: Object, pub first: Array<i64>, pub second: Array<i64> }
537    /// # #[derive(Clone, tvm_ffi::derive::ObjectRef)]
538    /// # pub struct MyPair { data: ObjectArc<MyPairObj> }
539    /// # struct Pass;
540    /// # #[dispatch(mutate, (MutationView<'_>, &mut StructuralMutatorView<'_, Self>), Result<UnchangedOr<Any>>)]
541    /// # impl Pass {
542    /// #     fn mutate_pair(&mut self, mut pair: MutationView<'_, MyPair>, mutator: &mut StructuralMutatorView<'_, Self>) -> Result<UnchangedOr<Any>> {
543    /// let second = mutator.mutate(self, pair.field(|pair| &pair.second))?;
544    /// #         Ok(second)
545    /// #     }
546    /// # }
547    /// # let pair = MyPairObj::new(Object::new(), Array::from_vec(vec![1_i64]), Array::from_vec(vec![2_i64]));
548    /// # structural_mutate(MyPair::from_object(pair), Pass)?;
549    /// # Ok::<(), tvm_ffi::Error>(())
550    /// ```
551    ///
552    /// See also [`structural_mutate`].
553    #[inline(always)]
554    pub fn field<U: MutationField>(
555        &mut self,
556        selector: impl for<'node> FnOnce(&'node T::ContainerType) -> &'node U,
557    ) -> MutationView<'_, U> {
558        let node: &T::ContainerType = self;
559        let child = selector(node);
560        let offset = (child as *const U)
561            .addr()
562            .checked_sub((node as *const T::ContainerType).addr());
563        assert!(
564            offset.is_some_and(|offset| {
565                offset <= std::mem::size_of::<T::ContainerType>()
566                    && std::mem::size_of::<U>() > 0
567                    && std::mem::size_of::<U>() <= std::mem::size_of::<T::ContainerType>() - offset
568            }),
569            "MutationView::field must select a direct owning field"
570        );
571        let mut value = TVMFFIAny::new();
572        // SAFETY: child is a live owning field. Copying its view acquires no owner;
573        // the returned view exclusively borrows the parent view.
574        unsafe { U::container_copy_to_any_view(child, &mut value) };
575        // Selection and conversion may retain aliases, so check the parent last.
576        let mode = self.mode.for_value(self.value);
577        MutationView::from_raw(value, mode)
578    }
579}
580
581/// The running structural mutation, passed to each handler.
582///
583/// A handler that matches a node decides how its children are rewritten: call
584/// [`default_mutate`](Self::default_mutate) to rewrite every child through the
585/// dispatcher, [`mutate`](Self::mutate) to rewrite one value, or neither to
586/// leave the children as they are. Pass the handler's own `self` as `dispatch`
587/// to every method.
588///
589/// See also [`structural_mutate`].
590pub struct StructuralMutatorView<'a, D, Base = StructuralMutatorObj> {
591    runtime: StructuralMutatorHandle,
592    #[allow(clippy::type_complexity)]
593    _marker: PhantomData<(&'a mut (), fn(&mut D) -> Base, Rc<()>)>,
594}
595
596// -----------------------------------------------------------------------------
597// Public mutation API and entrypoint
598// -----------------------------------------------------------------------------
599
600impl<D, Base: StructuralMutatorBase> StructuralMutatorView<'_, D, Base> {
601    /// Inspect the base state without retaining the scoped mutator runtime.
602    ///
603    /// # Returns
604    ///
605    /// The base state, borrowed for the lifetime of this view.
606    #[inline(always)]
607    pub fn base(&self) -> &Base {
608        // SAFETY: the unsafe base contract permits shared inspection, including
609        // native mutation through interior-mutable fields during recursion.
610        unsafe { &*self.runtime.cast::<Base>() }
611    }
612
613    #[inline(always)]
614    fn reborrow(&self) -> StructuralMutatorView<'_, D, Base> {
615        StructuralMutatorView {
616            runtime: self.runtime,
617            _marker: PhantomData,
618        }
619    }
620
621    /// Return the definition region the current value is in.
622    ///
623    /// Reflected fields marked as definitions set it while their values are
624    /// mutated; it is [`DefRegionKind::None`] elsewhere.
625    ///
626    /// # Returns
627    ///
628    /// The current definition region.
629    #[inline(always)]
630    pub fn def_region_kind(&self) -> DefRegionKind {
631        // SAFETY: the view's runtime is live.
632        unsafe { std::mem::transmute(*(*self.runtime).def_region_mode.get()) }
633    }
634
635    /// Run `callback` under a scoped definition region.
636    ///
637    /// An enclosing [`DefRegionKind::Pattern`] region keeps precedence, since a
638    /// pattern applies to everything inside it. The previous region is restored
639    /// afterwards.
640    ///
641    /// # Arguments
642    ///
643    /// * `kind` - The definition region to enter.
644    /// * `callback` - Runs inside the region, with this view.
645    ///
646    /// # Returns
647    ///
648    /// The result of `callback`.
649    #[inline(always)]
650    pub fn with_def_region_kind<R>(
651        &mut self,
652        kind: DefRegionKind,
653        callback: impl FnOnce(&mut StructuralMutatorView<'_, D, Base>) -> R,
654    ) -> R {
655        // SAFETY: the view's runtime outlives the callback.
656        StructuralMutatorObj::with_def_region_kind(self.runtime, kind, |_| {
657            callback(&mut self.reborrow())
658        })
659    }
660
661    /// Mutate `value` through the dispatcher, as if the traversal had reached it.
662    ///
663    /// `value` keeps the mode it carries. Use it to rewrite a value other
664    /// than the current node, such as a field selected with
665    /// [`MutationView::field`].
666    ///
667    /// # Arguments
668    ///
669    /// * `dispatch` - The handler's own `self`.
670    /// * `value` - The value to mutate.
671    ///
672    /// # Returns
673    ///
674    /// The replacement, or [`Unchanged`].
675    ///
676    /// # Errors
677    ///
678    /// Returns the error of the handler that `value` reaches.
679    #[inline(always)]
680    pub fn mutate<'input, T>(
681        &mut self,
682        dispatch: &mut D,
683        value: impl Into<MutationView<'input, T>>,
684    ) -> Result<UnchangedOr<Any>> {
685        let value = value.into();
686        unsafe {
687            let context =
688                StructuralMutateEngine::<Base>::checked_dispatcher(self.runtime, dispatch);
689            (*StructuralMutateEngine::<Base>::from_handle(self.runtime)).dispatcher = context;
690            StructuralMutatorObj::call_mutator(self.runtime, value.value, value.mode)
691        }
692        .and_then(UnchangedOr::from_carrier)
693    }
694
695    /// Rewrite the children of `value` through the dispatcher, without dispatching
696    /// `value` itself again.
697    ///
698    /// Children are found by the type's registered mutation hook or its reflected
699    /// fields. A hook uses the mutator only through its arguments, during the
700    /// call, and must not keep it or call it outside them. The result is
701    /// unchanged when no child changed; otherwise it is a node with the new
702    /// children, made in place when `value` allows it and is uniquely owned.
703    ///
704    /// # Arguments
705    ///
706    /// * `dispatch` - The handler's own `self`.
707    /// * `value` - The value whose children to mutate, usually the view the
708    ///   handler received.
709    ///
710    /// # Returns
711    ///
712    /// The rewritten node, or [`Unchanged`].
713    ///
714    /// # Errors
715    ///
716    /// Returns the first error of a child's handler.
717    #[inline(always)]
718    pub fn default_mutate<'input, T>(
719        &mut self,
720        dispatch: &mut D,
721        value: impl Into<MutationView<'input, T>>,
722    ) -> Result<UnchangedOr<Any>> {
723        let value = value.into();
724        unsafe {
725            let context =
726                StructuralMutateEngine::<Base>::checked_dispatcher(self.runtime, dispatch);
727            raw_ffi_any_into_result(StructuralMutateEngine::<Base>::publish_and_descend_raw(
728                self.runtime,
729                context,
730                value.value,
731                value.mode,
732            ))
733        }
734        .and_then(UnchangedOr::from_carrier)
735    }
736
737    /// Look up the replacement recorded for a variable in this mutation.
738    ///
739    /// Default mutation records the result of every free variable and DAG node it
740    /// rewrites, and replaces each later occurrence with it.
741    ///
742    /// # Arguments
743    ///
744    /// * `dispatch` - The handler's own `self`.
745    /// * `var` - The variable, an object.
746    ///
747    /// # Returns
748    ///
749    /// The recorded replacement, or `None`.
750    ///
751    /// # Errors
752    ///
753    /// Returns a `TypeError` if `var` is not an object.
754    #[inline(always)]
755    pub fn var_remap_get(&mut self, dispatch: &mut D, var: AnyView<'_>) -> Result<Option<Any>> {
756        unsafe {
757            StructuralMutateEngine::<Base>::checked_dispatcher(self.runtime, dispatch);
758            StructuralMutateEngine::<Base>::runtime_var_remap_get(
759                self.runtime,
760                *var.as_raw_ffi_any(),
761            )
762        }
763    }
764
765    /// Record a replacement for a variable for the rest of this mutation.
766    ///
767    /// Default mutation then replaces each later occurrence of `var`, a free
768    /// variable or DAG node, with `value`.
769    ///
770    /// # Arguments
771    ///
772    /// * `dispatch` - The handler's own `self`.
773    /// * `var` - The variable, an object.
774    /// * `value` - The replacement.
775    ///
776    /// # Returns
777    ///
778    /// `Ok(())` once the replacement is recorded.
779    ///
780    /// # Errors
781    ///
782    /// Returns a `TypeError` if `var` is not an object.
783    #[inline(always)]
784    pub fn var_remap_set(&mut self, dispatch: &mut D, var: AnyView<'_>, value: &Any) -> Result<()> {
785        unsafe {
786            StructuralMutateEngine::<Base>::checked_dispatcher(self.runtime, dispatch);
787            StructuralMutateEngine::<Base>::runtime_var_remap_set(
788                self.runtime,
789                *var.as_raw_ffi_any(),
790                value,
791            )
792        }
793    }
794}
795
796/// Mutate a structured value with an owned or borrowed [`Dispatcher`].
797///
798/// The root is consumed to establish the ownership boundary for optional
799/// in-place mutation. A matching callback supplies the final value; unmatched
800/// values use default mutation.
801///
802/// Callbacks must report failures through [`Result`] and must not panic: a panic
803/// reaching the non-unwinding native callback boundary aborts the process.
804///
805/// A callback must not modify an `ffi.List` or `ffi.Dict` that holds the
806/// value it receives or one of that value's ancestors: the traversal borrows
807/// their cells while the callback runs. A callback that returns an `Error`
808/// object as its value fails the traversal with a `TypeError`.
809///
810/// # Arguments
811///
812/// * `root` - Owned value to mutate, convertible into an [`Any`]. A uniquely
813///   owned container may be reused in place; clone first to preserve the original.
814/// * `dispatcher` - Owned or mutably borrowed dispatcher implementing [`IntoDispatcher`].
815///   Matching handlers return replacements and control recursion through
816///   [`StructuralMutatorView`]; unmatched values use default mutation. For closure
817///   callbacks with automatic recursion, use [`structural_map`](crate::structural_map).
818///
819/// # Examples
820///
821/// Double the integers in nested arrays; default mutation descends into the
822/// arrays:
823///
824/// ```
825/// use tvm_ffi::{dispatch, structural_mutate, Any, Array, MutationView, Result, UnchangedOr};
826/// use tvm_ffi::StructuralMutatorView;
827///
828/// struct Double;
829///
830/// #[dispatch(mutate, (MutationView<'_>, &mut StructuralMutatorView<'_, Self>), Result<UnchangedOr<Any>>)]
831/// impl Double {
832///     fn mutate_int(
833///         &mut self,
834///         value: i64,
835///         _: &mut StructuralMutatorView<'_, Self>,
836///     ) -> Result<UnchangedOr<Any>> {
837///         Ok((value * 2).into())
838///     }
839/// }
840///
841/// let root = Array::from_vec(vec![Array::from_vec(vec![1_i64, 2]), Array::from_vec(vec![3_i64])]);
842/// let result = Array::<Array<i64>>::try_from(structural_mutate(root, Double)?)?;
843/// assert_eq!(result[0].iter().copied().collect::<Vec<_>>(), vec![2, 4]);
844/// # Ok::<(), tvm_ffi::Error>(())
845/// ```
846pub fn structural_mutate<R, H, M, D, O>(root: R, dispatcher: H) -> Result<Any>
847where
848    R: Into<Any>,
849    O: BorrowMut<D>,
850    for<'v, 'c, 'r> H: IntoDispatcher<
851            (
852                MutationView<'v>,
853                &'c mut StructuralMutatorView<'r, D, StructuralMutatorObj>,
854            ),
855            Option<Result<UnchangedOr<Any>>>,
856            M,
857            Target = D,
858            Output = O,
859        >,
860    for<'s, 'v, 'c, 'r> &'s mut D: crate::Dispatcher<
861            (
862                MutationView<'v>,
863                &'c mut StructuralMutatorView<'r, D, StructuralMutatorObj>,
864            ),
865            Option<Result<UnchangedOr<Any>>>,
866        >,
867{
868    StructuralMutateEngine::mutate_root(root, dispatcher)
869}
870
871mod callback_result_sealed {
872    use super::{Any, Result};
873
874    pub trait Sealed {}
875
876    impl<T: Into<Any>> Sealed for T {}
877    impl<T: Into<Any>> Sealed for Result<T> {}
878}
879
880/// Convert an infallible or fallible map or mutation callback result into
881/// [`Result<UnchangedOr<Any>>`].
882///
883/// A callback may return any value convertible into [`Any`], including
884/// [`Unchanged`] and [`UnchangedOr`], or wrap it in [`Result`] to use `?`.
885///
886/// This trait is sealed and is not an extension point.
887#[doc(hidden)]
888pub trait IntoMutateResult: callback_result_sealed::Sealed {
889    fn into_mutate_result(self) -> Result<UnchangedOr<Any>>;
890}
891
892impl<T: Into<Any>> IntoMutateResult for T {
893    #[inline(always)]
894    fn into_mutate_result(self) -> Result<UnchangedOr<Any>> {
895        Ok(UnchangedOr::from_any(self.into()))
896    }
897}
898
899impl<T: Into<Any>> IntoMutateResult for Result<T> {
900    #[inline(always)]
901    fn into_mutate_result(self) -> Result<UnchangedOr<Any>> {
902        self.map(|value| UnchangedOr::from_any(value.into()))
903    }
904}
905
906// -----------------------------------------------------------------------------
907// StructuralMutateEngine implementation
908// -----------------------------------------------------------------------------
909
910// Perf note: Raw carriers avoid materializing an owning Any on the success path.
911// Private C-unwind boundaries return this 16-byte carrier in x0/x1 on AArch64,
912// avoiding the hidden result slot observed with the Rust ABI while allowing
913// Rust cleanup to unwind. Native vtables remain extern "C".
914// Raw bits provide no ownership guard: import an owning result into Any before
915// fallible work or destruction of an observer; borrowed inputs must stay live.
916impl<Base: StructuralMutatorBase> StructuralMutateEngine<Base> {
917    /// Mutate `root` with `dispatcher` on the native base `Base`. See also [`structural_mutate`].
918    #[inline(always)]
919    pub fn mutate_root<R, H, M, D, O>(root: R, dispatcher: H) -> Result<Any>
920    where
921        R: Into<Any>,
922        O: BorrowMut<D>,
923        for<'v, 'c, 'r> H: IntoDispatcher<
924                (MutationView<'v>, &'c mut StructuralMutatorView<'r, D, Base>),
925                Option<Result<UnchangedOr<Any>>>,
926                M,
927                Target = D,
928                Output = O,
929            >,
930        for<'s, 'v, 'c, 'r> &'s mut D: crate::Dispatcher<
931                (MutationView<'v>, &'c mut StructuralMutatorView<'r, D, Base>),
932                Option<Result<UnchangedOr<Any>>>,
933            >,
934    {
935        // Normalize the input once. Named dispatchers keep their own recursive view
936        // type; callback and tuple targets are their aggregate adapters.
937        let mut storage = dispatcher.into_dispatcher();
938        Self::run_mutator::<D, true>(root.into(), storage.borrow_mut())
939    }
940
941    /// The engine whose first field is the native prefix `runtime`.
942    ///
943    /// # Safety
944    ///
945    /// `runtime` is this live Rust engine, not an arbitrary native mutator; only raw
946    /// projections of the result may cross recursion.
947    #[inline(always)]
948    unsafe fn from_handle(runtime: StructuralMutatorHandle) -> *mut Self {
949        runtime.cast()
950    }
951
952    /// Validate a recursive caller and return its current exclusive reborrow.
953    ///
954    /// # Safety
955    /// `runtime` must belong to the live invocation of `dispatch` with matching `D`.
956    /// The identity check does not replace that lifetime/type contract; mismatch panics.
957    #[inline(always)]
958    unsafe fn checked_dispatcher<D>(
959        runtime: StructuralMutatorHandle,
960        dispatch: &mut D,
961    ) -> *mut c_void {
962        let context = std::ptr::from_mut(dispatch).cast();
963        if context != unsafe { (*Self::from_handle(runtime)).dispatcher } {
964            core::hint::cold_path();
965            wrong_dispatcher();
966        }
967        context
968    }
969
970    /// Build native callbacks for dispatcher `D`. `CALLBACK_CONTEXT` selects
971    /// whether direct callback failures receive input context; map adapters add their own.
972    #[inline(always)]
973    fn vtable<D, const CALLBACK_CONTEXT: bool>() -> &'static StructuralMutatorVTable
974    where
975        for<'s, 'v, 'c, 'r> &'s mut D: Dispatcher<
976                (MutationView<'v>, &'c mut StructuralMutatorView<'r, D, Base>),
977                Option<Result<UnchangedOr<Any>>>,
978            >,
979    {
980        &StructuralMutatorVTable {
981            mutate: Self::rust_vtable_mutate::<D, false, CALLBACK_CONTEXT>,
982            maybe_inplace_mutate: Self::rust_vtable_mutate::<D, true, CALLBACK_CONTEXT>,
983            var_remap_get: Self::rust_vtable_var_remap_get,
984            var_remap_set: Self::rust_vtable_var_remap_set,
985        }
986    }
987
988    /// Enter a native callback with borrowed `value` and return one owning raw result.
989    /// `INPLACE` sets the mode only; uniqueness is checked before dispatch.
990    ///
991    /// # Safety
992    /// `runtime` must have this `D` vtable and a live published exclusive reborrow.
993    /// The ABI lifetime on `value` is erased: it remains valid only during this call.
994    /// Callbacks report errors through results and must not unwind across this C boundary.
995    unsafe extern "C" fn rust_vtable_mutate<D, const INPLACE: bool, const CALLBACK_CONTEXT: bool>(
996        runtime: StructuralMutatorHandle,
997        value: AnyView<'static>,
998    ) -> TVMFFIAny
999    where
1000        for<'s, 'v, 'c, 'r> &'s mut D: Dispatcher<
1001                (MutationView<'v>, &'c mut StructuralMutatorView<'r, D, Base>),
1002                Option<Result<UnchangedOr<Any>>>,
1003            >,
1004    {
1005        let context = unsafe { (*Self::from_handle(runtime)).dispatcher };
1006        let raw = *value.as_raw_ffi_any();
1007        let mode = if INPLACE {
1008            InplaceMode::Allow
1009        } else {
1010            InplaceMode::Disallow
1011        };
1012        let mode = mode.for_value(raw);
1013        let dispatch = unsafe { &mut *context.cast::<D>() };
1014        let mut mutator = StructuralMutatorView {
1015            runtime,
1016            _marker: PhantomData,
1017        };
1018        let result = match Dispatcher::dispatch_tuple(
1019            &mut *dispatch,
1020            (MutationView::new(value, mode), &mut mutator),
1021        ) {
1022            // Map adapters attribute errors to their possibly replaced value;
1023            // direct mutation attributes callback failures to this input.
1024            Some(result) => {
1025                let result = result.map(Any::from).and_then(reject_error_value);
1026                result_into_raw_ffi_any(if CALLBACK_CONTEXT {
1027                    result.map_err(|error| update_visit_error_context(error, raw))
1028                } else {
1029                    result
1030                })
1031            }
1032            None => unsafe {
1033                Self::publish_and_descend_raw(
1034                    runtime,
1035                    std::ptr::from_mut(dispatch).cast(),
1036                    raw,
1037                    mode,
1038                )
1039            },
1040        };
1041        // All callback reborrows have ended before restoring the caller's provenance.
1042        unsafe { (*Self::from_handle(runtime)).dispatcher = context };
1043        result
1044    }
1045
1046    /// Publish `context`, then descend through hooks or reflection for borrowed `raw`.
1047    /// `mode` is an upper bound, not proof of uniqueness. Returns one owning token.
1048    ///
1049    /// # Safety
1050    /// `runtime` must be live; `context` must be its current exclusive dispatcher
1051    /// reborrow, and `raw` must remain valid throughout synchronous descent.
1052    #[inline(always)]
1053    unsafe fn publish_and_descend_raw(
1054        runtime: StructuralMutatorHandle,
1055        context: *mut c_void,
1056        raw: TVMFFIAny,
1057        mode: InplaceMode,
1058    ) -> TVMFFIAny {
1059        unsafe { (*Self::from_handle(runtime)).dispatcher = context };
1060        unsafe {
1061            <Base as StructuralMutatorBase>::default_mutate_raw(
1062                runtime.cast(),
1063                MutationView::new(AnyView::from_raw_ffi_any(raw), mode),
1064            )
1065        }
1066    }
1067
1068    /// Look up borrowed identity `raw` in the invocation remap, cloning its value.
1069    ///
1070    /// # Safety
1071    /// `runtime` and the object represented by `raw` must remain live for this lookup.
1072    /// The RefCell borrow ends before the owning result reaches the caller.
1073    #[inline(always)]
1074    unsafe fn runtime_var_remap_get(
1075        runtime: StructuralMutatorHandle,
1076        raw: TVMFFIAny,
1077    ) -> Result<Option<Any>> {
1078        unsafe {
1079            (*Self::from_handle(runtime))
1080                .remap
1081                .borrow()
1082                .get(AnyView::from_raw_ffi_any(raw))
1083        }
1084    }
1085
1086    /// Record borrowed identity `raw` and clone `value` into the invocation remap.
1087    ///
1088    /// # Safety
1089    /// `runtime`, `raw`, and `value` must remain live through insertion. The remap
1090    /// retains each new key once; no RefCell borrow escapes this call.
1091    #[inline(always)]
1092    unsafe fn runtime_var_remap_set(
1093        runtime: StructuralMutatorHandle,
1094        raw: TVMFFIAny,
1095        value: &Any,
1096    ) -> Result<()> {
1097        unsafe {
1098            (*Self::from_handle(runtime))
1099                .remap
1100                .borrow_mut()
1101                .set(AnyView::from_raw_ffi_any(raw), value)
1102        }
1103    }
1104
1105    /// Native remap lookup: borrow `var`, return an owning value, None, or Error.
1106    ///
1107    /// # Safety
1108    /// `runtime` must be this live engine and `var` valid for the call despite its
1109    /// erased ABI lifetime. Rust panics cannot cross this native C boundary.
1110    unsafe extern "C" fn rust_vtable_var_remap_get(
1111        runtime: StructuralMutatorHandle,
1112        var: AnyView<'static>,
1113    ) -> TVMFFIAny {
1114        match unsafe { Self::runtime_var_remap_get(runtime, *var.as_raw_ffi_any()) } {
1115            Ok(Some(value)) => Any::into_raw_ffi_any(value),
1116            Ok(None) => TVMFFIAny::new(),
1117            Err(error) => result_into_raw_ffi_any(Err(error)),
1118        }
1119    }
1120
1121    /// Native remap update borrowing `var` and `replacement`; return owning None/Error.
1122    ///
1123    /// # Safety
1124    /// Both views and this Rust `runtime` must remain live for the synchronous call.
1125    /// Replacement ownership is acquired before insertion; panics cannot cross C.
1126    unsafe extern "C" fn rust_vtable_var_remap_set(
1127        runtime: StructuralMutatorHandle,
1128        var: AnyView<'static>,
1129        replacement: AnyView<'static>,
1130    ) -> TVMFFIAny {
1131        // Finish replacement cleanup before constructing the ABI result.
1132        let result =
1133            raw_ffi_any_to_owned_any(*replacement.as_raw_ffi_any()).and_then(|value| unsafe {
1134                Self::runtime_var_remap_set(runtime, *var.as_raw_ffi_any(), &value)
1135            });
1136        result_into_raw_ffi_any(result.map(|()| Any::new()))
1137    }
1138
1139    /// Run the public mutate/map adapter with owned `root` and borrowed `dispatch`.
1140    /// `CALLBACK_CONTEXT` distinguishes direct mutation from map error attribution.
1141    /// Keep the owning result and root live across engine/remap destruction, including
1142    /// unwind, then replace Unchanged with the original root. Hooks may not retain
1143    /// the scoped runtime or dispatcher after this call.
1144    pub(super) fn run_mutator<D, const CALLBACK_CONTEXT: bool>(
1145        root: Any,
1146        dispatch: &mut D,
1147    ) -> Result<Any>
1148    where
1149        for<'s, 'v, 'c, 'r> &'s mut D: Dispatcher<
1150                (MutationView<'v>, &'c mut StructuralMutatorView<'r, D, Base>),
1151                Option<Result<UnchangedOr<Any>>>,
1152            >,
1153    {
1154        let mut base = Base::new()?;
1155        let type_index = Base::type_index();
1156        // Initialize the native prefix before allocation, so the ordinary base's
1157        // default region value and this reset can be folded into one write.
1158        unsafe {
1159            let prefix = std::ptr::from_mut(&mut base).cast::<StructuralMutatorObj>();
1160            *(*prefix).def_region_mode.get() = DefRegionKind::None as i32;
1161        }
1162        let mut engine = unsafe {
1163            ObjectArc::<Object>::new_opaque_unchecked(
1164                Self {
1165                    base,
1166                    dispatcher: std::ptr::from_mut(dispatch).cast(),
1167                    remap: RefCell::new(StructuralVarRemap::default()),
1168                },
1169                type_index,
1170            )
1171        };
1172        let runtime = ObjectArc::as_mut_ptr(&mut engine).cast::<StructuralMutatorObj>();
1173        unsafe { (*runtime).vtable = Self::vtable::<D, CALLBACK_CONTEXT>() };
1174        let result =
1175            StructuralMutatorObj::call_mutator(runtime, *root.as_raw_ffi_any(), InplaceMode::Allow);
1176        // Native hooks release temporary runtime owners before this synchronous run ends.
1177        drop(engine);
1178        match result {
1179            Ok(value) => Ok(if is_unchanged(&value) { root } else { value }),
1180            // The public traversal boundary, as the C++ `StructuralMutateExpected`.
1181            Err(error) => Err(enrich_visit_error(error, *root.as_raw_ffi_any())),
1182        }
1183    }
1184}
1185
1186// -----------------------------------------------------------------------------
1187// Prefix-only default traversal and native ABI operations
1188// -----------------------------------------------------------------------------
1189
1190// Prefix operations use only the native layout and installed vtable.
1191impl StructuralMutatorObj {
1192    /// Consume a native hook's `result`, naming the borrowed `raw` in it when it is an Error.
1193    ///
1194    /// # Safety
1195    ///
1196    /// `result` owns one valid value and `raw` outlives the call.
1197    #[inline(always)]
1198    unsafe fn with_native_mutation_context_raw(result: TVMFFIAny, raw: TVMFFIAny) -> TVMFFIAny {
1199        if result.type_index != TVMFFITypeIndex::kTVMFFIError as i32 {
1200            result
1201        } else {
1202            core::hint::cold_path();
1203            unsafe { Self::with_mutation_context_raw(result, raw) }
1204        }
1205    }
1206
1207    /// The cold arm of [`Self::with_native_mutation_context_raw`].
1208    ///
1209    /// # Safety
1210    ///
1211    /// `result` owns one Error, and `raw` is a live borrowed value.
1212    #[cold]
1213    #[inline(never)]
1214    unsafe extern "C-unwind" fn with_mutation_context_raw(
1215        result: TVMFFIAny,
1216        raw: TVMFFIAny,
1217    ) -> TVMFFIAny {
1218        unsafe {
1219            result_into_raw_ffi_any(
1220                raw_ffi_any_into_result(result)
1221                    .map_err(|error| update_visit_error_context(error, raw)),
1222            )
1223        }
1224    }
1225
1226    /// Mutate the reflected fields of a shallow copy of borrowed `raw`; `Unchanged` when no
1227    /// field changed.
1228    fn map_reflected(
1229        runtime: StructuralMutatorHandle,
1230        raw: TVMFFIAny,
1231        def_region_kind: DefRegionKind,
1232        type_info: *const crate::tvm_ffi_sys::TVMFFITypeInfo,
1233    ) -> Result<Any> {
1234        let inherited_region =
1235            free_var_child_region(def_region_kind, unsafe { seq_hash_kind(type_info) });
1236        // Match the C++ reflected-mutation contract: resolve and invoke the
1237        // shallow-copy hook before inspecting any fields. Besides providing
1238        // isolated setter storage, this means a missing or failing hook is an
1239        // error even when no field eventually changes.
1240        let output = shallow_copy(raw)?;
1241        let output_raw = *output.as_raw_ffi_any();
1242        let output_object = unsafe { output_raw.data_union.v_obj.cast::<u8>() };
1243        if output_object.is_null() {
1244            return Err(runtime_error(
1245                "native structural mutate: shallow copy has a null object pointer",
1246            ));
1247        }
1248
1249        let mut field_changed = false;
1250        let mut failure: Option<Error> = None;
1251        unsafe {
1252            for_each_field_info(type_info, &mut |field| {
1253                if field.flags & FLAG_SEQ_HASH_IGNORE != 0 {
1254                    return ControlFlow::Continue(());
1255                }
1256                match Self::map_reflected_field(
1257                    runtime,
1258                    output_object,
1259                    field,
1260                    inherited_region,
1261                    &mut field_changed,
1262                ) {
1263                    Ok(()) => ControlFlow::Continue(()),
1264                    Err(error) => {
1265                        failure = Some(error);
1266                        ControlFlow::Break(())
1267                    }
1268                }
1269            });
1270        }
1271        if let Some(error) = failure {
1272            return Err(error);
1273        }
1274        if field_changed {
1275            Ok(output)
1276        } else {
1277            Ok(Unchanged.into())
1278        }
1279    }
1280
1281    /// Mutate one reflected `field` of `output_object`, setting `field_changed` on a
1282    /// replacement.
1283    ///
1284    /// # Safety
1285    ///
1286    /// `runtime` is live, and `field` describes `output_object`'s storage.
1287    unsafe fn map_reflected_field(
1288        runtime: StructuralMutatorHandle,
1289        output_object: *mut u8,
1290        field: &TVMFFIFieldInfo,
1291        inherited_region: DefRegionKind,
1292        field_changed: &mut bool,
1293    ) -> Result<()> {
1294        let Some(getter) = field.getter else {
1295            return Err(unsafe {
1296                missing_field_getter_error("structural mutate", field.name.as_str())
1297            });
1298        };
1299        // Read every field from the copy so earlier setters' side effects are
1300        // visible to later field mappings, exactly as in the C++ fallback.
1301        let field_offset = usize::try_from(field.offset)
1302            .map_err(|_| unsafe { invalid_field_offset_error(field.name.as_str()) })?;
1303        // SAFETY: registered reflection metadata guarantees that the field
1304        // offset lies within this object's allocation. The checked conversion
1305        // above also prevents truncation on 32-bit targets.
1306        let source_address = unsafe { output_object.add(field_offset).cast::<c_void>() };
1307        // Own the output slot before entering foreign code. A getter may
1308        // populate an owning result and still report an error.
1309        let mut child = Any::new();
1310        if unsafe { getter(source_address, Any::as_raw_ffi_any_mut(&mut child)) } != 0 {
1311            return Err(Error::from_raised());
1312        }
1313        // Reflection getters return owning values. Keep the child alive for
1314        // the complete recursive call, then let normal Drop release it.
1315        let child_raw = *child.as_raw_ffi_any();
1316        let child_region = field_def_region(field, inherited_region);
1317        let mapped = Self::with_def_region_kind(runtime, child_region, |_| {
1318            Self::call_mutator(runtime, child_raw, InplaceMode::Disallow)
1319        })?;
1320        if is_unchanged(&mapped) || raw_ffi_any_same_as(child_raw, *mapped.as_raw_ffi_any()) {
1321            return Ok(());
1322        }
1323
1324        call_field_setter(field, source_address, mapped.as_raw_ffi_any())?;
1325        *field_changed = true;
1326        Ok(())
1327    }
1328
1329    /// Dispatch borrowed `raw` through the runtime's vtable, in place when `mode` allows
1330    /// it and `raw` is unique.
1331    #[inline(always)]
1332    fn call_mutator(
1333        runtime: StructuralMutatorHandle,
1334        raw: TVMFFIAny,
1335        mode: InplaceMode,
1336    ) -> Result<Any> {
1337        let callback = unsafe {
1338            if mode.for_value(raw) == InplaceMode::Allow {
1339                (*(*runtime).vtable).maybe_inplace_mutate
1340            } else {
1341                (*(*runtime).vtable).mutate
1342            }
1343        };
1344        unsafe {
1345            let view = AnyView::from_raw_ffi_any(raw);
1346            raw_ffi_any_into_result(callback(runtime, view))
1347        }
1348    }
1349
1350    /// The registered mutation hook of `raw`: the in-place one when `mode` allows it and
1351    /// `raw` is unique, otherwise the copying one.
1352    #[inline(always)]
1353    fn structural_mutate_hook(raw: TVMFFIAny, mode: InplaceMode) -> Option<TVMFFIAny> {
1354        if mode.for_value(raw) == InplaceMode::Allow
1355            && let Some(attr) = structural_mutate_column::<true>().get_raw_ffi_any(raw.type_index)
1356            && (attr.type_index == TVMFFITypeIndex::kTVMFFIOpaquePtr as i32
1357                || attr.type_index == TVMFFITypeIndex::kTVMFFIFunction as i32)
1358        {
1359            return Some(attr);
1360        }
1361        let attr = structural_mutate_column::<false>().get_raw_ffi_any(raw.type_index)?;
1362        (attr.type_index != TVMFFITypeIndex::kTVMFFINone as i32).then_some(attr)
1363    }
1364
1365    /// Call the registered mutation `hook` (native pointer or packed function) on `value`.
1366    ///
1367    /// # Safety
1368    ///
1369    /// `runtime` is live with its dispatcher published, `value` and `hook` outlive the call,
1370    /// the caller's mode allows any in-place mutation the hook performs, and a native hook
1371    /// has the mutation ABI for this runtime's layout and obeys [`StructuralMutatorBase`]'s
1372    /// non-escaping contract.
1373    #[inline(always)]
1374    pub unsafe fn call_structural_mutate_hook_raw(
1375        runtime: *mut Self,
1376        value: TVMFFIAny,
1377        hook: TVMFFIAny,
1378    ) -> TVMFFIAny {
1379        unsafe {
1380            if hook.type_index == TVMFFITypeIndex::kTVMFFIOpaquePtr as i32 {
1381                let callback: FStructuralMutate = std::mem::transmute(hook.data_union.v_ptr);
1382                Self::with_native_mutation_context_raw(
1383                    callback(runtime, AnyView::from_raw_ffi_any(value)),
1384                    value,
1385                )
1386            } else {
1387                Self::call_structural_mutate_hook_slow_raw(runtime, value, hook)
1388            }
1389        }
1390    }
1391
1392    /// The packed-function arm of [`Self::call_structural_mutate_hook_raw`], outlined as cold.
1393    ///
1394    /// # Safety
1395    ///
1396    /// As [`Self::call_structural_mutate_hook_raw`].
1397    #[cold]
1398    #[inline(never)]
1399    unsafe extern "C-unwind" fn call_structural_mutate_hook_slow_raw(
1400        runtime: StructuralMutatorHandle,
1401        raw: TVMFFIAny,
1402        attr: TVMFFIAny,
1403    ) -> TVMFFIAny {
1404        let result = if attr.type_index == TVMFFITypeIndex::kTVMFFIFunction as i32 {
1405            unsafe {
1406                Function::try_from(AnyView::from_raw_ffi_any(attr)).and_then(|function| {
1407                    function.call_packed(&[
1408                        Self::borrowed_mutator_view(runtime),
1409                        AnyView::from_raw_ffi_any(raw),
1410                    ])
1411                })
1412            }
1413        } else {
1414            Err(invalid_mutation_hook_error())
1415        };
1416        // Preserve successful Error-valued returns until the public conversion.
1417        result_into_raw_ffi_any(result.map_err(|error| update_visit_error_context(error, raw)))
1418    }
1419
1420    /// Borrow the live `runtime` as an object argument, without a reference count.
1421    ///
1422    /// # Safety
1423    ///
1424    /// `runtime` outlives the returned view.
1425    #[inline(always)]
1426    unsafe fn borrowed_mutator_view<'a>(runtime: StructuralMutatorHandle) -> AnyView<'a> {
1427        let object = runtime.cast::<TVMFFIObject>();
1428        let mut raw = TVMFFIAny::new();
1429        raw.type_index = unsafe { (*object).type_index };
1430        raw.small_str_len = 0;
1431        raw.data_union.v_obj = object;
1432        unsafe { AnyView::from_raw_ffi_any(raw) }
1433    }
1434
1435    /// Run `callback` under requested `kind` on live borrowed `mutator`.
1436    /// Pattern precedence is retained; pass the effective kind to the callback and
1437    /// restore prior state on normal return or Rust unwind. Internal callers keep
1438    /// the runtime live and do not retain a reference to its mutable region field.
1439    #[inline(always)]
1440    fn with_def_region_kind<T>(
1441        mutator: StructuralMutatorHandle,
1442        kind: DefRegionKind,
1443        callback: impl FnOnce(DefRegionKind) -> T,
1444    ) -> T {
1445        unsafe {
1446            let previous = *(*mutator).def_region_mode.get();
1447            if previous == kind as i32 || previous == DefRegionKind::Pattern as i32 {
1448                // Inherited descent does not change state; Pattern keeps precedence.
1449                return callback(std::mem::transmute::<i32, DefRegionKind>(previous));
1450            }
1451            *(*mutator).def_region_mode.get() = kind as i32;
1452            struct Restore {
1453                mutator: StructuralMutatorHandle,
1454                previous: i32,
1455            }
1456            impl Drop for Restore {
1457                #[inline(always)]
1458                fn drop(&mut self) {
1459                    unsafe { *(*self.mutator).def_region_mode.get() = self.previous };
1460                }
1461            }
1462            let _restore = Restore { mutator, previous };
1463            // One call site keeps the continuation visible to the inliner.
1464            callback(kind)
1465        }
1466    }
1467
1468    /// Mutate borrowed `raw` by reflection, caching free variables and DAG nodes
1469    /// through the vtable remap.
1470    ///
1471    /// # Safety
1472    ///
1473    /// `runtime` is a live mutator prefix with its vtable, and `raw` outlives the call.
1474    /// Outlined (frequent, not cold) to keep reflection scratch out of recursive frames.
1475    #[inline(never)]
1476    unsafe extern "C-unwind" fn mutate_without_hook_raw(
1477        runtime: StructuralMutatorHandle,
1478        raw: TVMFFIAny,
1479    ) -> TVMFFIAny {
1480        // Read the region here rather than on the native-hook path, which does not use it.
1481        let def_region_kind =
1482            unsafe { std::mem::transmute::<i32, DefRegionKind>(*(*runtime).def_region_mode.get()) };
1483        result_into_raw_ffi_any(
1484            Self::mutate_without_hook(runtime, raw, def_region_kind)
1485                .map_err(|error| update_visit_error_context(error, raw)),
1486        )
1487    }
1488
1489    /// Borrow the native remap interface without assuming the complete engine layout.
1490    /// The vtable owns its returned replacement, including Unchanged markers.
1491    #[inline(always)]
1492    unsafe fn var_remap_get(
1493        runtime: StructuralMutatorHandle,
1494        raw: TVMFFIAny,
1495    ) -> Result<Option<Any>> {
1496        let callback = unsafe { (*(*runtime).vtable).var_remap_get };
1497        let value =
1498            unsafe { raw_ffi_any_into_result(callback(runtime, AnyView::from_raw_ffi_any(raw)))? };
1499        Ok((value.type_index() != TVMFFITypeIndex::kTVMFFINone as i32).then_some(value))
1500    }
1501
1502    /// Borrow both inputs through the native remap interface; it retains the key
1503    /// and replacement. Import the owning None/Error result before returning.
1504    #[inline(always)]
1505    unsafe fn var_remap_set(
1506        runtime: StructuralMutatorHandle,
1507        raw: TVMFFIAny,
1508        value: &Any,
1509    ) -> Result<()> {
1510        let callback = unsafe { (*(*runtime).vtable).var_remap_set };
1511        unsafe {
1512            raw_ffi_any_into_result(callback(
1513                runtime,
1514                AnyView::from_raw_ffi_any(raw),
1515                AnyView::from_raw_ffi_any(*value.as_raw_ffi_any()),
1516            ))
1517            .map(|_| ())
1518        }
1519    }
1520
1521    /// The reflective mutation of [`Self::mutate_without_hook_raw`], on owned results.
1522    #[inline(always)]
1523    fn mutate_without_hook(
1524        runtime: StructuralMutatorHandle,
1525        raw: TVMFFIAny,
1526        def_region_kind: DefRegionKind,
1527    ) -> Result<Any> {
1528        if raw.type_index < TVMFFITypeIndex::kTVMFFIStaticObjectBegin as i32 {
1529            return raw_ffi_any_to_owned_any(raw);
1530        }
1531
1532        let type_info = checked_type_info(raw.type_index)?;
1533        let kind = unsafe { seq_hash_kind(type_info) };
1534        let is_free_var = kind == TVMFFISEqHashKind::kTVMFFISEqHashKindFreeVar as i32;
1535        let is_dag_node = kind == TVMFFISEqHashKind::kTVMFFISEqHashKindDAGNode as i32;
1536        if is_free_var || is_dag_node {
1537            // The ABI uses None for a miss; an Unchanged marker is a cached result.
1538            if let Some(mutated) = unsafe { Self::var_remap_get(runtime, raw)? } {
1539                return Ok(mutated);
1540            }
1541        }
1542        // A variable use with no binding retains its identity without visiting fields.
1543        if is_free_var && def_region_kind == DefRegionKind::None {
1544            return Ok(Unchanged.into());
1545        }
1546
1547        let result = Self::map_reflected(runtime, raw, def_region_kind, type_info)?;
1548        if is_dag_node
1549            || (is_free_var
1550                && (def_region_kind == DefRegionKind::Pattern || !is_unchanged(&result)))
1551        {
1552            // Keep markers for DAG nodes and pattern definitions. An unchanged simple
1553            // definition needs no binding: subsequent uses retain the original on a miss.
1554            unsafe { Self::var_remap_set(runtime, raw, &result)? };
1555        }
1556        Ok(result)
1557    }
1558}
1559
1560// -----------------------------------------------------------------------------
1561// Private utility functions
1562// -----------------------------------------------------------------------------
1563
1564fn shallow_copy(raw: TVMFFIAny) -> Result<Any> {
1565    let Some(attr) = SHALLOW_COPY_COLUMN.get_raw_ffi_any(raw.type_index) else {
1566        return Err(missing_shallow_copy_error(
1567            raw.type_index,
1568            SHALLOW_COPY_ATTR,
1569        ));
1570    };
1571    if attr.type_index != TVMFFITypeIndex::kTVMFFIFunction as i32 {
1572        return Err(invalid_shallow_copy_hook_error(SHALLOW_COPY_ATTR));
1573    }
1574    let function = unsafe { attr.data_union.v_obj };
1575    if function.is_null() {
1576        return Err(runtime_error("shallow copy function pointer is null"));
1577    }
1578    // The registry owns this function throughout the call; borrowing it avoids
1579    // an atomic retain/release for every reflected node.
1580    let mut result = Any::new();
1581    let status = unsafe {
1582        TVMFFIFunctionCall(
1583            function.cast(),
1584            &raw,
1585            1,
1586            Any::as_raw_ffi_any_mut(&mut result),
1587        )
1588    };
1589    if status != 0 {
1590        return Err(Error::from_raised());
1591    }
1592    let result_raw = *result.as_raw_ffi_any();
1593    let result_pointer = unsafe { result_raw.data_union.v_obj };
1594    let source_pointer = unsafe { raw.data_union.v_obj };
1595    if result_raw.type_index != raw.type_index
1596        || result_pointer.is_null()
1597        || result_pointer == source_pointer
1598    {
1599        return Err(invalid_shallow_copy_result_error());
1600    }
1601    Ok(result)
1602}
1603
1604fn call_field_setter(
1605    field: &TVMFFIFieldInfo,
1606    field_address: *mut c_void,
1607    value: &TVMFFIAny,
1608) -> Result<()> {
1609    if field.setter.is_null() {
1610        // SAFETY: registered field names are UTF-8 text that lives as long as the process.
1611        return Err(missing_field_setter_error(unsafe { field.name.as_str() }));
1612    }
1613    let return_code = unsafe {
1614        if field.flags & FLAG_SETTER_IS_FUNCTION == 0 {
1615            // SAFETY: reflection registration requires a non-Function setter
1616            // pointer to use the TVMFFIFieldSetter signature.
1617            let setter: TVMFFIFieldSetter = std::mem::transmute(field.setter);
1618            setter(field_address, value)
1619        } else {
1620            let mut args = [TVMFFIAny::new(), *value];
1621            args[0].type_index = TVMFFITypeIndex::kTVMFFIOpaquePtr as i32;
1622            args[0].data_union.v_ptr = field_address;
1623            // Own the result slot before entering foreign code so a partial
1624            // owning result is released on both success and failure.
1625            let mut result = Any::new();
1626            TVMFFIFunctionCall(
1627                field.setter as TVMFFIObjectHandle,
1628                args.as_ptr(),
1629                2,
1630                Any::as_raw_ffi_any_mut(&mut result),
1631            )
1632        }
1633    };
1634    if return_code == 0 {
1635        Ok(())
1636    } else {
1637        Err(Error::from_raised())
1638    }
1639}
1640
1641fn object_identity_key(raw: TVMFFIAny) -> Result<NonNull<TVMFFIObject>> {
1642    if raw.type_index < TVMFFITypeIndex::kTVMFFIStaticObjectBegin as i32 {
1643        core::hint::cold_path();
1644        return Err(var_remap_key_error());
1645    }
1646    let pointer = unsafe { raw.data_union.v_obj };
1647    NonNull::new(pointer).ok_or_else(|| {
1648        core::hint::cold_path();
1649        runtime_error("native structural mutate: identity object has a null pointer")
1650    })
1651}
1652
1653#[inline]
1654fn checked_type_info(type_index: i32) -> Result<*const crate::tvm_ffi_sys::TVMFFITypeInfo> {
1655    let info = unsafe { TVMFFIGetTypeInfo(type_index) };
1656    if info.is_null() {
1657        Err(unregistered_type_error(type_index))
1658    } else {
1659        Ok(info)
1660    }
1661}
1662
1663#[inline(always)]
1664fn object_is_unique(raw: TVMFFIAny) -> bool {
1665    if raw.type_index < TVMFFITypeIndex::kTVMFFIStaticObjectBegin as i32 {
1666        return false;
1667    }
1668    let pointer = unsafe { raw.data_union.v_obj };
1669    !pointer.is_null() && unsafe { object::unsafe_::is_unique(pointer) }
1670}
1671
1672/// Acquire an owning value from a valid borrowed carrier.
1673///
1674/// Inline values are copied and objects are retained once, including Error objects
1675/// as ordinary values. String/byte views are normalized by the runtime; an rvalue
1676/// slot transfers its reference. Internal callers keep borrowed resources live and
1677/// uniquely own each writable rvalue slot, converting it at most once. A null
1678/// object pointer or failed runtime conversion returns an error; successful Error
1679/// objects remain ordinary values rather than entering the error channel.
1680fn raw_ffi_any_to_owned_any(raw: TVMFFIAny) -> Result<Any> {
1681    if is_plain_inline(raw.type_index) {
1682        return Ok(unsafe { Any::from_raw_ffi_any(raw) });
1683    }
1684    if raw.type_index >= TVMFFITypeIndex::kTVMFFIStaticObjectBegin as i32 {
1685        let object = unsafe { raw.data_union.v_obj };
1686        if object.is_null() {
1687            return Err(runtime_error(
1688                "native structural mutate: object-backed value has a null pointer",
1689            ));
1690        }
1691        unsafe { object::unsafe_::inc_ref(object) };
1692        return Ok(unsafe { Any::from_raw_ffi_any(raw) });
1693    }
1694
1695    // Raw string/bytes views and ObjectRValueRef require normalization (or a
1696    // move) rather than a bitwise copy; keep the generic C ABI conversion for
1697    // those uncommon representations.
1698    let mut owned = Any::new();
1699    let return_code = unsafe { TVMFFIAnyViewToOwnedAny(&raw, Any::as_raw_ffi_any_mut(&mut owned)) };
1700    if return_code == 0 {
1701        Ok(owned)
1702    } else {
1703        Err(Error::from_raised())
1704    }
1705}
1706
1707// Cache registry columns, not their optional per-type cells. Absent cells retain
1708// the normal hook/reflection fallback.
1709static STRUCTURAL_MUTATE_COLUMN: ColdInitLazyLock<TypeAttrColumn> = ColdInitLazyLock::new(|| {
1710    TypeAttrColumn::lookup(STRUCTURAL_MUTATE_ATTR).expect("missing __s_mutate__ column")
1711});
1712
1713static STRUCTURAL_MAYBE_INPLACE_MUTATE_COLUMN: ColdInitLazyLock<TypeAttrColumn> =
1714    ColdInitLazyLock::new(|| {
1715        TypeAttrColumn::lookup(STRUCTURAL_MAYBE_INPLACE_MUTATE_ATTR)
1716            .expect("missing __s_maybe_inplace_mutate__ column")
1717    });
1718
1719/// Return the shared column for normal or permitted in-place mutation hooks.
1720/// Cache the column, not its per-type cells, so absent hooks still use fallback.
1721#[inline(always)]
1722fn structural_mutate_column<const INPLACE: bool>() -> TypeAttrColumn {
1723    if INPLACE {
1724        *STRUCTURAL_MAYBE_INPLACE_MUTATE_COLUMN
1725    } else {
1726        *STRUCTURAL_MUTATE_COLUMN
1727    }
1728}
1729
1730static SHALLOW_COPY_COLUMN: ColdInitLazyLock<TypeAttrColumn> = ColdInitLazyLock::new(|| {
1731    TypeAttrColumn::lookup(SHALLOW_COPY_ATTR).expect("missing __ffi_shallow_copy__ column")
1732});
1733
1734// -----------------------------------------------------------------------------
1735// Outlined errors
1736// -----------------------------------------------------------------------------
1737
1738#[cold]
1739#[inline(never)]
1740fn missing_shallow_copy_error(type_index: i32, attribute: &str) -> Error {
1741    Error::new(
1742        TYPE_ERROR,
1743        &format!(
1744            "type `{}` cannot use reflected structural mutation because it does not define `{attribute}`",
1745            crate::object::type_key_of_index(type_index)
1746        ),
1747    )
1748}
1749
1750#[cold]
1751#[inline(never)]
1752fn invalid_shallow_copy_hook_error(attribute: &str) -> Error {
1753    Error::new(TYPE_ERROR, &format!("{attribute} must be an ffi.Function"))
1754}
1755
1756#[cold]
1757#[inline(never)]
1758fn invalid_shallow_copy_result_error() -> Error {
1759    Error::new(
1760        TYPE_ERROR,
1761        "shallow copy callback must return a distinct object with the same type as its input",
1762    )
1763}
1764
1765#[cold]
1766#[inline(never)]
1767fn missing_field_setter_error(name: &str) -> Error {
1768    Error::new(
1769        TYPE_ERROR,
1770        &format!("cannot structurally mutate field `{name}` because it does not define a setter"),
1771    )
1772}
1773
1774#[cold]
1775#[inline(never)]
1776fn invalid_field_offset_error(name: &str) -> Error {
1777    runtime_error(&format!(
1778        "native structural mutate: reflected field `{name}` has an invalid offset"
1779    ))
1780}
1781
1782#[cold]
1783#[inline(never)]
1784fn invalid_mutation_hook_error() -> Error {
1785    Error::new(
1786        TYPE_ERROR,
1787        "__s_mutate__ must be an opaque function pointer or ffi.Function",
1788    )
1789}
1790
1791#[cold]
1792#[inline(never)]
1793fn var_remap_key_error() -> Error {
1794    Error::new(
1795        TYPE_ERROR,
1796        "variable-remap keys must be object-backed values",
1797    )
1798}
1799
1800#[cold]
1801#[inline(never)]
1802fn unregistered_type_error(type_index: i32) -> Error {
1803    runtime_error(&format!(
1804        "native structural mutate: unregistered type index {type_index}"
1805    ))
1806}