Skip to main content

tvm_ffi/reflection/
registry.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//! Registration of the reflection of an object type defined in Rust.
21//!
22//! [`ObjectDef`] fills the type table entries that every language reads: the
23//! type metadata, one record per field with C ABI getter and setter, one
24//! record per method, and the `__ffi_shallow_copy__` and `__ffi_type_final__`
25//! type attributes; for an `#[rs_object]` type also the creator, and from it
26//! the `__ffi_new__` and `__ffi_init__` type attributes. Through them
27//! structural equality, hashing and mutation, `repr`, deep copy, JSON graphs
28//! and Python's generated classes reach the fields and methods of a Rust type,
29//! and construct it.
30//!
31//! Only [`rs_object`](crate::rs_object) creates an [`ObjectDef`], which
32//! guarantees that each registered field's type and offset match. Its
33//! `reflection = path` function receives the builder to register methods with
34//! [`ObjectDef::def`] and [`ObjectDef::def_static`].
35
36use std::ffi::c_void;
37use std::marker::PhantomData;
38use std::mem::{align_of, size_of};
39use std::ops::BitOr;
40use std::panic::{AssertUnwindSafe, catch_unwind};
41
42use super::NativeFunction;
43use crate::function_internal::AsPackedCallable;
44use crate::object::{
45    Object, ObjectArc, ObjectCore, ObjectRef, ObjectRefCore, lock_type_registration,
46};
47use crate::tvm_ffi_sys::{
48    TVMFFIAny, TVMFFIByteArray, TVMFFIFieldFlagBitMask, TVMFFIFieldInfo, TVMFFIFieldSetter,
49    TVMFFIGetTypeInfo, TVMFFIMethodInfo, TVMFFIObject, TVMFFIObjectCreator, TVMFFIObjectHandle,
50    TVMFFISEqHashKind, TVMFFITypeIndex, TVMFFITypeMetadata, TVMFFITypeRegisterAttr,
51    TVMFFITypeRegisterField, TVMFFITypeRegisterMetadata, TVMFFITypeRegisterMethod,
52};
53use crate::type_traits::{AnyCompatible, type_schema_metadata};
54use crate::{Any, Error, Function, INTERNAL_ERROR, Result, TYPE_ERROR, VALUE_ERROR};
55
56/// A copy of an object's own fields under a fresh object header, which
57/// `__ffi_shallow_copy__` returns; fields that are references share their
58/// objects, as `Clone` of an `Arc` does.
59///
60/// [`rs_object`](crate::rs_object) and `#[object(rs_parent)]` on
61/// [`derive(Object)`](crate::derive::Object) implement it by copying the
62/// parent with its `ShallowCopy` and cloning every other field. An
63/// `rs_object` needs its parent's object to implement it.
64pub trait ShallowCopy {
65    /// The copy, under a fresh object header.
66    fn shallow_copy(&self) -> Self;
67}
68
69impl ShallowCopy for Object {
70    fn shallow_copy(&self) -> Self {
71        Object::new()
72    }
73}
74
75/// How the structural engines treat instances of a type.
76#[derive(Clone, Copy, Debug, PartialEq, Eq)]
77#[non_exhaustive]
78pub enum SEqHashKind {
79    /// Rejected by structural equality and hashing; the default.
80    Unsupported,
81    /// Compared and hashed field by field.
82    TreeNode,
83    /// A free variable: bound by position inside a definition region, else by identity.
84    FreeVar,
85    /// Compared field by field, and once equal, mapped so later occurrences compare by mapping.
86    DAGNode,
87    /// A tree node whose identity is checked first, as a fast path.
88    ConstTreeNode,
89    /// Compared and hashed by identity only.
90    UniqueInstance,
91}
92
93impl SEqHashKind {
94    fn raw(self) -> i32 {
95        let kind = match self {
96            SEqHashKind::Unsupported => TVMFFISEqHashKind::kTVMFFISEqHashKindUnsupported,
97            SEqHashKind::TreeNode => TVMFFISEqHashKind::kTVMFFISEqHashKindTreeNode,
98            SEqHashKind::FreeVar => TVMFFISEqHashKind::kTVMFFISEqHashKindFreeVar,
99            SEqHashKind::DAGNode => TVMFFISEqHashKind::kTVMFFISEqHashKindDAGNode,
100            SEqHashKind::ConstTreeNode => TVMFFISEqHashKind::kTVMFFISEqHashKindConstTreeNode,
101            SEqHashKind::UniqueInstance => TVMFFISEqHashKind::kTVMFFISEqHashKindUniqueInstance,
102        };
103        kind as i32
104    }
105}
106
107/// The reflection flags of one field, combined with `|`.
108#[derive(Clone, Copy, Debug, PartialEq, Eq)]
109pub struct FieldFlags(i64);
110
111impl FieldFlags {
112    /// A read-only field that takes part in structural equality and hashing (`def_ro`).
113    pub const NONE: Self = Self(0);
114    /// Assignable through reflection, as from Python (`def_rw`).
115    pub const WRITABLE: Self = Self::of(TVMFFIFieldFlagBitMask::kTVMFFIFieldFlagBitMaskWritable);
116    /// Skipped by structural equality and hashing (`SEqHashIgnore`).
117    pub const SEQ_HASH_IGNORE: Self =
118        Self::of(TVMFFIFieldFlagBitMask::kTVMFFIFieldFlagBitMaskSEqHashIgnore);
119    /// Entered as a pattern definition region (`SEqHashDefPattern`).
120    pub const SEQ_HASH_DEF_PATTERN: Self =
121        Self::of(TVMFFIFieldFlagBitMask::kTVMFFIFieldFlagBitMaskSEqHashDefPattern);
122    /// Entered as a simple definition region (`SEqHashDefSimple`).
123    pub const SEQ_HASH_DEF_SIMPLE: Self =
124        Self::of(TVMFFIFieldFlagBitMask::kTVMFFIFieldFlagBitMaskSEqHashDefSimple);
125    /// Left out of `repr`.
126    pub const REPR_OFF: Self = Self::of(TVMFFIFieldFlagBitMask::kTVMFFIFieldFlagBitMaskReprOff);
127    /// Left out of `__eq__`.
128    pub const COMPARE_OFF: Self =
129        Self::of(TVMFFIFieldFlagBitMask::kTVMFFIFieldFlagBitMaskCompareOff);
130    /// Left out of `__hash__`.
131    pub const HASH_OFF: Self = Self::of(TVMFFIFieldFlagBitMask::kTVMFFIFieldFlagBitMaskHashOff);
132    /// Not a constructor argument of the Python class.
133    pub const INIT_OFF: Self = Self::of(TVMFFIFieldFlagBitMask::kTVMFFIFieldFlagBitMaskInitOff);
134    /// A keyword-only constructor argument of the Python class.
135    pub const KW_ONLY: Self = Self::of(TVMFFIFieldFlagBitMask::kTVMFFIFieldFlagBitMaskKwOnly);
136
137    const fn of(bit: TVMFFIFieldFlagBitMask) -> Self {
138        Self(bit as i64)
139    }
140
141    /// The raw `TVMFFIFieldInfo::flags` value.
142    pub fn bits(self) -> i64 {
143        self.0
144    }
145}
146
147impl BitOr for FieldFlags {
148    type Output = Self;
149    fn bitor(self, rhs: Self) -> Self {
150        Self(self.0 | rhs.0)
151    }
152}
153
154/// Registers the reflection of the object type `N`: the metadata, each
155/// `#[reflect]` field, the methods and the type attributes.
156///
157/// [`rs_object`](crate::rs_object) creates one while it registers its type
158/// and passes it to the function its `reflection = path` option names, which
159/// registers methods with [`ObjectDef::def`] and [`ObjectDef::def_static`].
160///
161/// That function runs under the registration lock, before `N::type_index()`
162/// returns, so it must not call `type_index()` of `N` or of another Rust type
163/// that is not registered yet, nor register attributes with [`TypeAttrDef`]
164/// or [`EnumDef`](super::EnumDef), nor call
165/// [`TypeAttrColumn::ensure`](super::TypeAttrColumn::ensure): each takes the
166/// same lock, which is not reentrant. When `N` already has metadata in the type
167/// table, every call is a no-op; registration fails if a previous one stopped
168/// partway.
169///
170/// # Examples
171///
172/// ```standalone_crate
173/// use tvm_ffi::derive::ObjectRef;
174/// use tvm_ffi::reflection::{self, ObjectDef};
175/// use tvm_ffi::{rs_object, Object, ObjectArc, Result};
176///
177/// #[rs_object(type_key = "my_ext.MyPair", final, reflection = MyPairObj::reflect_methods)]
178/// pub struct MyPairObj {
179///     base_: Object,
180///     pub first: i64,
181///     pub second: i64,
182/// }
183///
184/// #[derive(Clone, ObjectRef)]
185/// pub struct MyPair {
186///     data: ObjectArc<MyPairObj>,
187/// }
188///
189/// impl MyPairObj {
190///     fn reflect_methods(def: &mut ObjectDef<Self>) {
191///         def.def("sum", |p: MyPair| -> Result<i64> { Ok(p.first + p.second) }, "The sum.");
192///     }
193/// }
194///
195/// let pair = MyPair::from_object(MyPairObj::new(Object::new(), 1, 2));
196/// let sum = reflection::get_method("my_ext.MyPair", "sum")?;
197/// assert_eq!(i64::try_from(sum.call_tuple((&pair,))?)?, 3);
198/// # Ok::<(), tvm_ffi::Error>(())
199/// ```
200pub struct ObjectDef<N: ObjectCore> {
201    type_index: i32,
202    fresh: bool,
203    /// The creator registered in the metadata, from which `finish` registers
204    /// `__ffi_new__` and `__ffi_init__`.
205    creator: Option<TVMFFIObjectCreator>,
206    /// The first failed method registration, which `finish` reports.
207    error: Option<Error>,
208    method_names: Vec<String>,
209    _object: PhantomData<N>,
210}
211
212impl<N: ObjectCore> ObjectDef<N> {
213    /// Registers `N`'s metadata, unless the type already has some, while the
214    /// derive registers `N`'s type index, before `N::type_index()` returns.
215    ///
216    /// `kind` of `None` takes the nearest ancestor's kind. `creator` makes an
217    /// object of `N` for reflection to fill (`unsafe_init_creator::<N>` for an
218    /// `#[rs_object]`).
219    ///
220    /// # Safety
221    ///
222    /// The caller holds `lock_type_registration()` for the builder's lifetime, and
223    /// `type_index` is `N`'s. `creator` returns an owned handle of an object of
224    /// `N` that the field setters can fill.
225    unsafe fn registering(
226        type_index: i32,
227        kind: Option<SEqHashKind>,
228        creator: Option<TVMFFIObjectCreator>,
229    ) -> Result<Self> {
230        let info = unsafe { TVMFFIGetTypeInfo(type_index) };
231        crate::ensure!(
232            !info.is_null(),
233            INTERNAL_ERROR,
234            "no type info for `{}` (type index {type_index})",
235            N::TYPE_KEY
236        );
237        let fresh = unsafe { (*info).metadata.is_null() };
238        // `finish` writes `__ffi_type_final__` last, as C++ `ObjectDef` and
239        // Python `py_class` do: metadata without it is left by a registration
240        // that failed partway, or by one that does not publish finality.
241        crate::ensure!(
242            fresh
243                || super::TypeAttrColumn::lookup("__ffi_type_final__")
244                    .and_then(|column| column.get_raw_ffi_any(type_index))
245                    .is_some_and(|cell| cell.type_index != TVMFFITypeIndex::kTVMFFINone as i32),
246            INTERNAL_ERROR,
247            "`{}` has reflection metadata but no `__ffi_type_final__`: an earlier registration \
248             of it failed, or another language registered the key without it",
249            N::TYPE_KEY
250        );
251        if fresh {
252            let kind = match kind {
253                Some(kind) => kind.raw(),
254                None => unsafe { inherited_kind(info) },
255            };
256            let metadata = unsafe {
257                TVMFFITypeMetadata {
258                    doc: TVMFFIByteArray::from_str(""),
259                    creator,
260                    total_size: size_of::<N>() as i32,
261                    structural_eq_hash_kind: kind,
262                }
263            };
264            unsafe { crate::check_safe_call!(TVMFFITypeRegisterMetadata(type_index, &metadata))? };
265        }
266        Ok(Self {
267            type_index,
268            fresh,
269            creator,
270            error: None,
271            method_names: Vec::new(),
272            _object: PhantomData,
273        })
274    }
275
276    /// Registers the field of type `F` at byte offset `offset` in `N` under
277    /// `name`, which must be unique in `N`, with its doc string (an empty one
278    /// records none).
279    ///
280    /// # Safety
281    ///
282    /// `offset` is `std::mem::offset_of!` of a field of `N` whose type is `F`:
283    /// the registered getter and setter read and write an `F` there.
284    #[doc(hidden)]
285    pub unsafe fn field<F: AnyCompatible>(
286        self,
287        name: &str,
288        doc: &str,
289        offset: usize,
290        flags: FieldFlags,
291    ) -> Result<Self> {
292        if !self.fresh {
293            return Ok(self);
294        }
295        // `__ffi_init__` leaves an `init_off` field as the creator made it, all-zero.
296        if self.creator.is_some() && flags.bits() & FieldFlags::INIT_OFF.bits() != 0 {
297            let zero = std::mem::MaybeUninit::<F>::zeroed();
298            crate::ensure!(
299                !unsafe { F::is_undefined(zero.as_ptr()) },
300                VALUE_ERROR,
301                "`init_off` field `{name}` of `{}` stays all-zero after `__ffi_init__`, which \
302                 is no value of `{}`",
303                N::TYPE_KEY,
304                F::type_str()
305            );
306        }
307        let type_str = F::type_str();
308        crate::ensure!(
309            F::has_field_layout(),
310            TYPE_ERROR,
311            "field `{name}` of `{}`: `Option` of a non-object value (`{type_str}`) has no FFI \
312             field layout; use `tvm_ffi::Optional<T>`",
313            N::TYPE_KEY
314        );
315        let metadata = type_schema_metadata(&F::type_schema());
316        let info = TVMFFIFieldInfo {
317            name: unsafe { TVMFFIByteArray::from_str(name) },
318            doc: unsafe { TVMFFIByteArray::from_str(doc) },
319            metadata: unsafe { TVMFFIByteArray::from_str(&metadata) },
320            flags: flags.bits(),
321            size: size_of::<F>() as i64,
322            alignment: align_of::<F>() as i64,
323            offset: offset as i64,
324            getter: Some(field_getter::<F>),
325            setter: field_setter::<F> as TVMFFIFieldSetter as *mut c_void,
326            default_value_or_factory: TVMFFIAny::new(),
327            field_static_type_index: field_static_type_index(&type_str),
328        };
329        // The table copies the strings before returning.
330        crate::check_safe_call!(unsafe { TVMFFITypeRegisterField(self.type_index, &info) })?;
331        Ok(self)
332    }
333
334    /// Registers `__ffi_shallow_copy__` from [`ShallowCopy`], which reflected
335    /// mutation (copy on write through the field setters) needs.
336    fn shallow_copy(self) -> Result<Self>
337    where
338        N: ShallowCopy,
339    {
340        if !self.fresh {
341            return Ok(self);
342        }
343        let shallow_copy = Function::from_typed(|object: ObjectRef| shallow_copy_any::<N>(&object));
344        register_type_attr(
345            self.type_index,
346            "__ffi_shallow_copy__",
347            Any::from(shallow_copy),
348        )?;
349        Ok(self)
350    }
351
352    /// Registers `func`, a typed function as for [`Function::from_typed`]
353    /// whose first parameter is the object, as the method `name` of `N`,
354    /// which must be unique in `N`, with its type schema and `doc`. A failed
355    /// registration is reported when the type's registration finishes.
356    pub fn def<F, I, O>(&mut self, name: &str, func: F, doc: &str) -> &mut Self
357    where
358        F: AsPackedCallable<I, O> + Send + Sync + 'static,
359    {
360        self.method(name, func, doc, false)
361    }
362
363    /// Registers `func` as the static method `name` of `N`, which takes no
364    /// object; otherwise as [`ObjectDef::def`].
365    pub fn def_static<F, I, O>(&mut self, name: &str, func: F, doc: &str) -> &mut Self
366    where
367        F: AsPackedCallable<I, O> + Send + Sync + 'static,
368    {
369        self.method(name, func, doc, true)
370    }
371
372    fn method<F, I, O>(&mut self, name: &str, func: F, doc: &str, is_static: bool) -> &mut Self
373    where
374        F: AsPackedCallable<I, O> + Send + Sync + 'static,
375    {
376        if !self.fresh || self.error.is_some() {
377            return self;
378        }
379        if self.method_names.iter().any(|n| n == name) {
380            self.error = Some(Error::new(
381                VALUE_ERROR,
382                &format!("duplicate method `{name}` of `{}`", N::TYPE_KEY),
383            ));
384            return self;
385        }
386        self.method_names.push(name.to_string());
387        let metadata = type_schema_metadata(&F::type_schema());
388        let func = Function::from_typed(func);
389        let flags = if is_static {
390            TVMFFIFieldFlagBitMask::kTVMFFIFieldFlagBitMaskIsStaticMethod as i64
391        } else {
392            0
393        };
394        let mut method = TVMFFIAny::new();
395        // SAFETY: the strings outlive the call, which copies them, and the
396        // table takes its own reference to the function.
397        let registered = unsafe {
398            <Function as AnyCompatible>::copy_to_any_view(&func, &mut method);
399            let info = TVMFFIMethodInfo {
400                name: TVMFFIByteArray::from_str(name),
401                doc: TVMFFIByteArray::from_str(doc),
402                metadata: TVMFFIByteArray::from_str(&metadata),
403                flags,
404                method,
405            };
406            crate::check_safe_call!(TVMFFITypeRegisterMethod(self.type_index, &info))
407        };
408        // A static `__ffi_init__` is also the type's `__ffi_init__` attribute, which
409        // other languages call to construct it, as C++ `ObjectDef::def(init)` registers.
410        let registered = registered.and_then(|()| {
411            if is_static && name == "__ffi_init__" {
412                register_type_attr(self.type_index, name, Any::from(func))
413            } else {
414                Ok(())
415            }
416        });
417        if let Err(error) = registered {
418            self.error = Some(Error::new(
419                error.kind(),
420                &format!("registering method `{name}`: {}", error.message()),
421            ));
422        }
423        self
424    }
425
426    /// Registers `__ffi_new__` from the creator and
427    /// `__ffi_init__` from the fields unless the type defines its own, then
428    /// `__ffi_type_final__`, which no other registered metadata exposes; and
429    /// reports the first failed method registration.
430    fn finish(self) -> Result<()> {
431        if let Some(error) = self.error {
432            return Err(error);
433        }
434        if !self.fresh {
435            return Ok(());
436        }
437        if let Some(creator) = self.creator {
438            // Objects from this creator start zero-filled, in the `UnsafeInit`
439            // state: whoever creates one, in any language, must set every
440            // field before it is used.
441            let new = Function::from_typed(move || -> Result<ObjectRef> {
442                let mut handle: TVMFFIObjectHandle = std::ptr::null_mut();
443                crate::check_safe_call!(unsafe { creator(&mut handle) })?;
444                // SAFETY: the creator returns an owned handle, which `ObjectRef` views.
445                Ok(unsafe { ObjectRef::from_data(ObjectArc::from_raw(handle.cast::<Object>())) })
446            });
447            register_type_attr(self.type_index, "__ffi_new__", Any::from(new))?;
448            // C++ `ObjectDef` looks `ffi._RegisterFFIInit` up the same way, in case
449            // it is not registered yet.
450            let explicit_init = self.method_names.iter().any(|name| name == "__ffi_init__");
451            if !explicit_init
452                && let Ok(register_init) = Function::get_global("ffi._RegisterFFIInit")
453            {
454                register_init.call_tuple((self.type_index,))?;
455            }
456        }
457        register_type_attr(
458            self.type_index,
459            "__ffi_type_final__",
460            Any::from(N::TYPE_FINAL),
461        )
462    }
463}
464
465/// Registers the reflection of `N` for `#[derive(Object)]`: its metadata,
466/// then `fields` its fields, its `__ffi_shallow_copy__`, then `methods` its
467/// methods, then its type attributes.
468///
469/// # Safety
470///
471/// As `ObjectDef::registering`; `fields` registers fields of `N` as
472/// [`ObjectDef::field`] requires. Like every registration, it runs before
473/// other threads use the type or register types: during static
474/// initialization, or on the first `type_index()` of a type under a binding
475/// loaded later.
476#[doc(hidden)]
477pub unsafe fn register_object<N: ObjectCore + ShallowCopy>(
478    type_index: i32,
479    kind: Option<SEqHashKind>,
480    creator: Option<TVMFFIObjectCreator>,
481    fields: impl FnOnce(ObjectDef<N>) -> Result<ObjectDef<N>>,
482    methods: impl FnOnce(&mut ObjectDef<N>),
483) -> Result<()> {
484    let mut def =
485        unsafe { fields(ObjectDef::registering(type_index, kind, creator)?)?.shallow_copy()? };
486    methods(&mut def);
487    def.finish()
488}
489
490/// Registers type attributes of the object type `T`, each as soon as
491/// [`set_attr`](Self::set_attr) names it, for every language to read with
492/// [`TypeAttrColumn`](crate::reflection::TypeAttrColumn).
493///
494/// As in C++, attributes register during static initialization, such as in a
495/// [`static_init_block!`](crate::static_init_block), before other threads
496/// read them: registrations from Rust lock each other out, but readers take
497/// no lock.
498///
499/// # Examples
500///
501/// ```standalone_crate
502/// use tvm_ffi::reflection::TypeAttrDef;
503/// use tvm_ffi::reflection::TypeAttrColumn;
504/// use tvm_ffi::{rs_object, Object, ObjectCore};
505///
506/// #[rs_object(type_key = "my_ext.MyPair")]
507/// pub struct MyPairObj {
508///     base_: Object,
509/// }
510///
511/// TypeAttrDef::<MyPairObj>::new().set_attr("my_ext.arity", 2_i64)?;
512///
513/// let column = TypeAttrColumn::lookup("my_ext.arity").unwrap();
514/// let arity: i64 = column.get(MyPairObj::type_index()).unwrap().try_into()?;
515/// assert_eq!(arity, 2);
516/// # Ok::<(), tvm_ffi::Error>(())
517/// ```
518pub struct TypeAttrDef<T: ObjectCore> {
519    _type: PhantomData<fn() -> T>,
520}
521
522impl<T: ObjectCore> TypeAttrDef<T> {
523    /// A builder for the type attributes of `T`.
524    #[allow(clippy::new_without_default)]
525    pub fn new() -> Self {
526        Self { _type: PhantomData }
527    }
528
529    /// Register the type attribute `name` of `T`.
530    ///
531    /// # Arguments
532    ///
533    /// * `name` - The name of the attribute.
534    /// * `value` - The value of the attribute, `Send + Sync` since every
535    ///   thread reads it.
536    ///
537    /// # Returns
538    ///
539    /// The builder, for the next attribute.
540    ///
541    /// # Errors
542    ///
543    /// Returns an error if `T` already has the attribute `name`, or a
544    /// `TypeError` if `value` is an opaque pointer: register a native hook
545    /// with [`set_native_fn_attr`](Self::set_native_fn_attr).
546    pub fn set_attr(self, name: &str, value: impl Into<Any> + Send + Sync) -> Result<Self> {
547        let value = value.into();
548        ensure_not_opaque_ptr(name, &value)?;
549        self.register(name, value)
550    }
551
552    /// Register the native hook `f` as the type attribute `name` of `T`.
553    ///
554    /// # Arguments
555    ///
556    /// * `name` - The name of the attribute.
557    /// * `f` - The hook.
558    ///
559    /// # Returns
560    ///
561    /// The builder, for the next attribute.
562    ///
563    /// # Errors
564    ///
565    /// Returns an error if `T` already has the attribute `name`.
566    ///
567    /// # Safety
568    ///
569    /// Every caller of the column `name` calls its hooks with exactly `Args`
570    /// and reads `R`: a native caller calls the function pointer unchecked.
571    pub unsafe fn set_native_fn_attr<Args, R>(
572        self,
573        name: &str,
574        f: NativeFunction<Args, R>,
575    ) -> Result<Self> {
576        // SAFETY: the caller vouches for the readers of `name`.
577        self.register(name, unsafe { f.into_any() })
578    }
579
580    fn register(self, name: &str, value: Any) -> Result<Self> {
581        // Before the lock, which a first `type_index()` takes to register `T`.
582        let type_index = T::type_index();
583        let _registering = lock_type_registration();
584        register_type_attr(type_index, name, value)?;
585        Ok(self)
586    }
587}
588
589/// Native callers of an attribute call an opaque pointer as a function, so
590/// only [`NativeFunction`] may store one, through an `unsafe` registration.
591pub(super) fn ensure_not_opaque_ptr(name: &str, value: &Any) -> Result<()> {
592    crate::ensure!(
593        value.type_index() != TVMFFITypeIndex::kTVMFFIOpaquePtr as i32,
594        TYPE_ERROR,
595        "attribute `{name}` cannot be an opaque pointer; register a native hook through \
596         `NativeFunction`"
597    );
598    Ok(())
599}
600
601/// The structural kind of the nearest ancestor of `info` with metadata.
602unsafe fn inherited_kind(info: *const crate::tvm_ffi_sys::TVMFFITypeInfo) -> i32 {
603    for depth in unsafe { (0..(*info).type_depth).rev() } {
604        let ancestor = unsafe { *(*info).type_acenstors.add(depth as usize) };
605        if !ancestor.is_null() && unsafe { !(*ancestor).metadata.is_null() } {
606            return unsafe { (*(*ancestor).metadata).structural_eq_hash_kind };
607        }
608    }
609    SEqHashKind::Unsupported.raw()
610}
611
612/// `__ffi_shallow_copy__` of `N`: a copy of `object`, which must be an `N`, as a new object.
613fn shallow_copy_any<N: ObjectCore + ShallowCopy>(object: &ObjectRef) -> Result<Any> {
614    let Some(node) = object.downcast_ref::<N>() else {
615        return Err(Error::new(
616            TYPE_ERROR,
617            &format!(
618                "__ffi_shallow_copy__ of `{}` applied to a `{}`",
619                N::TYPE_KEY,
620                object_type_key(object)
621            ),
622        ));
623    };
624    let copy = ObjectArc::new(node.shallow_copy());
625    // SAFETY: `ObjectRef` is the view of any object; the allocation keeps its type index.
626    let copy =
627        unsafe { ObjectRef::from_data(ObjectArc::from_raw(ObjectArc::into_raw(copy).cast())) };
628    Ok(Any::from(copy))
629}
630
631fn object_type_key(object: &ObjectRef) -> String {
632    let type_index =
633        unsafe { (*ObjectArc::as_ptr(ObjectRef::data(object)).cast::<TVMFFIObject>()).type_index };
634    let info = unsafe { TVMFFIGetTypeInfo(type_index) };
635    if info.is_null() {
636        return format!("type index {type_index}");
637    }
638    unsafe { (*info).type_key.as_str().to_string() }
639}
640
641/// The caller holds the registration lock.
642pub(super) fn register_type_attr(type_index: i32, name: &str, mut value: Any) -> Result<()> {
643    let name = unsafe { TVMFFIByteArray::from_str(name) };
644    // The table takes its own reference to the value.
645    let value = Any::as_raw_ffi_any_mut(&mut value);
646    crate::check_safe_call!(unsafe { TVMFFITypeRegisterAttr(type_index, &name, value) })
647}
648
649/// Reflection getter of a field of type `F`: writes an owned `Any` of the field's value.
650/// `field` is the field's address inside the object.
651unsafe extern "C" fn field_getter<F: AnyCompatible>(
652    field: *mut c_void,
653    result: *mut TVMFFIAny,
654) -> i32 {
655    let read = catch_unwind(AssertUnwindSafe(|| {
656        let field = field.cast::<F>();
657        // An undefined field reads as None, as a null `ObjectRef` does in C++.
658        let value = if unsafe { F::is_undefined(field) } {
659            Any::new()
660        } else {
661            unsafe { (*field).to_any() }
662        };
663        unsafe { std::ptr::write(result, Any::into_raw_ffi_any(value)) };
664    }));
665    match read {
666        Ok(()) => 0,
667        Err(_) => {
668            let message = format!("panic while reading a field of type {}", F::type_str());
669            Error::set_raised(&Error::new(INTERNAL_ERROR, &message));
670            -1
671        }
672    }
673}
674
675/// Reflection setter of a field of type `F`: replaces the field with `value` converted to `F`.
676/// `field` is the field's address inside the object.
677unsafe extern "C" fn field_setter<F: AnyCompatible>(
678    field: *mut c_void,
679    value: *const TVMFFIAny,
680) -> i32 {
681    let written = catch_unwind(AssertUnwindSafe(|| {
682        match unsafe { F::try_cast_from_any_view(&*value) } {
683            Ok(converted) => {
684                let field = field.cast::<F>();
685                // An undefined field holds no value to drop.
686                if unsafe { F::is_undefined(field) } {
687                    unsafe { field.write(converted) };
688                } else {
689                    unsafe { *field = converted };
690                }
691                None
692            }
693            Err(()) => Some(unsafe {
694                Error::new(
695                    TYPE_ERROR,
696                    &format!(
697                        "expected a field value of type {}, got {}",
698                        F::type_str(),
699                        F::get_mismatch_type_info(&*value)
700                    ),
701                )
702            }),
703        }
704    }));
705    let error = match written {
706        Ok(None) => return 0,
707        Ok(Some(error)) => error,
708        Err(_) => Error::new(
709            INTERNAL_ERROR,
710            &format!("panic while writing a field of type {}", F::type_str()),
711        ),
712    };
713    Error::set_raised(&error);
714    -1
715}
716
717/// The static type index of a field, from the Rust type's `type_str()` (the names
718/// `AnyCompatible` reports, such as `int`, `ffi.String`, `Array<my.Node>`).
719// As C++ `TypeTraits<T>::field_static_type_index` states it.
720pub(crate) fn field_static_type_index(type_str: &str) -> i32 {
721    use TVMFFITypeIndex::*;
722    /// The static index of a field holding any value (`kTVMFFIAny`).
723    const ANY: i32 = -1;
724    let origin = type_str.split('<').next().unwrap_or(type_str).trim();
725    match origin {
726        "None" => kTVMFFINone as i32,
727        "int" => kTVMFFIInt as i32,
728        "bool" => kTVMFFIBool as i32,
729        "float" => kTVMFFIFloat as i32,
730        "void*" => kTVMFFIOpaquePtr as i32,
731        "DataType" => kTVMFFIDataType as i32,
732        "Device" => kTVMFFIDevice as i32,
733        "DLTensor*" => kTVMFFIDLTensorPtr as i32,
734        // C++ `String`, `Bytes` and `BigInt` fields are typed `Any` statically (they have
735        // inline forms), as is `Optional<T>`.
736        "ffi.String" | "ffi.Bytes" | "BigInt" | "Optional" => ANY,
737        "ffi.Function" => kTVMFFIFunction as i32,
738        "ffi.Shape" => kTVMFFIShape as i32,
739        "Array" => kTVMFFIArray as i32,
740        "List" => kTVMFFIList as i32,
741        // Any other object reference, `Map` included, is typed `Object` statically.
742        _ => kTVMFFIStaticObjectBegin as i32,
743    }
744}
745
746#[cfg(test)]
747mod tests {
748    use super::field_static_type_index;
749    use crate::type_traits::{AnyCompatible, type_schema_metadata};
750    use crate::{Array, List, Map};
751
752    #[test]
753    fn field_static_type_indices_follow_the_cpp_type_traits() {
754        assert_eq!(field_static_type_index("int"), 1);
755        assert_eq!(field_static_type_index("ffi.String"), -1);
756        assert_eq!(field_static_type_index("Optional<my.Node>"), -1);
757        assert_eq!(field_static_type_index("my.Node"), 64);
758        assert_eq!(field_static_type_index("Array<my.Node>"), 71);
759        assert_eq!(field_static_type_index("List<int>"), 75);
760        assert_eq!(field_static_type_index("Map<ffi.String, int>"), 64);
761    }
762
763    #[test]
764    fn field_schemas_follow_the_cpp_type_traits() {
765        assert_eq!(
766            <Map<crate::String, i64>>::type_schema(),
767            r#"{"type":"ffi.Map","args":[{"type":"ffi.String"},{"type":"int"}]}"#
768        );
769        assert_eq!(
770            <List<i64>>::type_schema(),
771            r#"{"type":"ffi.List","args":[{"type":"int"}]}"#
772        );
773        assert_eq!(
774            <Option<Array<crate::String>>>::type_schema(),
775            r#"{"type":"Optional","args":[{"type":"ffi.Array","args":[{"type":"ffi.String"}]}]}"#
776        );
777        assert_eq!(
778            type_schema_metadata(r#"{"type":"int"}"#),
779            r#"{"type_schema":"{\"type\":\"int\"}"}"#
780        );
781        // As C++ `EscapeStringJSON`, `/`, `\b` and DEL are escaped too.
782        assert_eq!(
783            type_schema_metadata("a/b\u{8}\u{7f}"),
784            r#"{"type_schema":"a\/b\b\u007f"}"#
785        );
786    }
787}