Skip to main content

tvm_ffi/reflection/
accessor.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//! Reads of registered types: methods, fields and type attributes.
21
22use std::ffi::c_void;
23use std::marker::PhantomData;
24use std::ptr::NonNull;
25use std::sync::{PoisonError, RwLock};
26
27use crate::tvm_ffi_sys::{
28    TVMFFIAny, TVMFFIByteArray, TVMFFIFieldFlagBitMask, TVMFFIFieldGetter, TVMFFIFieldInfo,
29    TVMFFIGetTypeAttrColumn, TVMFFIGetTypeInfo, TVMFFIObject, TVMFFITypeAttrColumn,
30    TVMFFITypeIndex, TVMFFITypeInfo, TVMFFITypeKeyToIndex,
31};
32use crate::type_traits::AnyCompatible;
33use crate::{Any, AnyView, Array, Error, Function, ObjectCore, Result, TYPE_ERROR};
34
35/// A registry-owned type-attribute column indexed by runtime type.
36///
37/// [`TypeAttrColumn::get`] returns owning copies. Registration must not race
38/// with reads.
39#[derive(Clone, Copy)]
40pub struct TypeAttrColumn(NonNull<TVMFFITypeAttrColumn>);
41
42// Type-attribute columns and their cells are registry-owned process-lifetime
43// data. Once registration is complete, reading a cell does not mutate the
44// registry and is safe from any thread.
45unsafe impl Send for TypeAttrColumn {}
46unsafe impl Sync for TypeAttrColumn {}
47
48impl TypeAttrColumn {
49    /// Look up a registered type-attribute column by name.
50    pub fn lookup(name: &str) -> Option<Self> {
51        unsafe {
52            let name = TVMFFIByteArray::from_str(name);
53            NonNull::new(TVMFFIGetTypeAttrColumn(&name).cast_mut()).map(Self)
54        }
55    }
56
57    /// The column `name`, created if no type registered it yet. Call it during
58    /// static initialization, like any registration, but not from the
59    /// `reflection = path` function of an [`rs_object`](crate::rs_object),
60    /// which already holds the registration lock.
61    ///
62    /// # Errors
63    ///
64    /// Returns an error if the runtime cannot create the column.
65    pub fn ensure(name: &str) -> Result<Self> {
66        {
67            let _registering = crate::object::lock_type_registration();
68            // A value for the None type index only creates the column.
69            super::registry::register_type_attr(
70                TVMFFITypeIndex::kTVMFFINone as i32,
71                name,
72                Any::new(),
73            )?;
74        }
75        Self::lookup(name).ok_or_else(|| {
76            Error::new(
77                crate::INTERNAL_ERROR,
78                &format!("type attribute column `{name}` was not created"),
79            )
80        })
81    }
82
83    /// The attribute of `type_index`, as an owned value, or `None` if unset.
84    pub fn get(self, type_index: i32) -> Option<Any> {
85        let raw = self.get_raw_ffi_any(type_index)?;
86        if raw.type_index == TVMFFITypeIndex::kTVMFFINone as i32 {
87            return None;
88        }
89        Some(Any::from(unsafe { AnyView::from_raw_ffi_any(raw) }))
90    }
91
92    /// The raw cell of `type_index`'s attribute, borrowed from the registry.
93    ///
94    /// The cell does not retain its value: the value must stay registered while
95    /// the cell is used, and registration must not race with reads. Use
96    /// [`Self::get`] for an owned [`Any`].
97    ///
98    /// Returns `None` when the index is outside the column or the column has no
99    /// data. Unlike [`Self::get`], it returns a `None`-valued cell as `Some`.
100    #[inline(always)]
101    pub fn get_raw_ffi_any(self, type_index: i32) -> Option<TVMFFIAny> {
102        unsafe {
103            let column = self.0.as_ref();
104            let index = type_index - column.begin_index;
105            if index < 0 || index >= column.size || column.data.is_null() {
106                None
107            } else {
108                Some(*column.data.offset(index as isize))
109            }
110        }
111    }
112}
113
114/// The type key registered for `type_index`, such as `"ffi.Array"`, or `None`
115/// if no type has that index.
116///
117/// ```
118/// use tvm_ffi::collections::array::ArrayObj;
119/// use tvm_ffi::{reflection, ObjectCore};
120///
121/// assert_eq!(reflection::type_key(ArrayObj::type_index()), Some("ffi.Array"));
122/// assert_eq!(reflection::type_key(-1), None);
123/// ```
124pub fn type_key(type_index: i32) -> Option<&'static str> {
125    if !is_registered(type_index) {
126        return None;
127    }
128    // SAFETY: the index is registered, and type information lives as long as
129    // the process.
130    let info: &'static TVMFFITypeInfo = unsafe { &*TVMFFIGetTypeInfo(type_index) };
131    // SAFETY: a type key is UTF-8 text.
132    Some(unsafe { info.type_key.as_str() })
133}
134
135/// The default value `T` registers for its field `name`, or `None` if `T`
136/// registers no such field, the field has no default, or its default comes
137/// from a factory.
138///
139/// Only fields `T` registers itself are searched, not those of its ancestors.
140pub fn field_default<T: ObjectCore>(name: &str) -> Option<Any> {
141    // SAFETY: `ObjectCore` types are registered, and type information lives
142    // as long as the process.
143    let info: &'static TVMFFITypeInfo = unsafe { &*TVMFFIGetTypeInfo(T::type_index()) };
144    // SAFETY: a registered type lists `num_fields` initialized fields.
145    let fields = unsafe {
146        crate::util::slice_from_nullable_raw_parts(info.fields, info.num_fields as usize)
147    };
148    // SAFETY: a field name is UTF-8 text.
149    let field = fields
150        .iter()
151        .find(|field| unsafe { field.name.as_str() } == name)?;
152    let has_default = TVMFFIFieldFlagBitMask::kTVMFFIFieldFlagBitMaskHasDefault as i64;
153    let from_factory = TVMFFIFieldFlagBitMask::kTVMFFIFieldFlagBitMaskDefaultFromFactory as i64;
154    if field.flags & has_default == 0 || field.flags & from_factory != 0 {
155        return None;
156    }
157    // SAFETY: the registry keeps the default alive; the view only borrows it
158    // for the copy.
159    Some(Any::from(unsafe {
160        AnyView::from_raw_ffi_any(field.default_value_or_factory)
161    }))
162}
163
164/// Whether a type is registered with index `type_index`. The registry aborts
165/// the process on a lookup of any other index, so the registered indices are
166/// listed once and again whenever an index is missing, as types register over
167/// time.
168fn is_registered(type_index: i32) -> bool {
169    static REGISTERED: RwLock<Vec<bool>> = RwLock::new(Vec::new());
170    let Ok(index) = usize::try_from(type_index) else {
171        return false;
172    };
173    let read = REGISTERED.read().unwrap_or_else(PoisonError::into_inner);
174    if read.get(index).copied().unwrap_or(false) {
175        return true;
176    }
177    drop(read);
178    let keys = crate::cached_global_func!("ffi.GetRegisteredTypeKeys")
179        .call_tuple(())
180        .and_then(Array::<crate::String>::try_from);
181    let mut registered = REGISTERED.write().unwrap_or_else(PoisonError::into_inner);
182    for key in keys.iter().flat_map(|keys| keys.iter()) {
183        let mut key_index = 0;
184        // SAFETY: the byte array borrows `key` for the call.
185        let found = unsafe {
186            TVMFFITypeKeyToIndex(&TVMFFIByteArray::from_str(key.as_str()), &mut key_index) == 0
187        };
188        if let (true, Ok(key_index)) = (found, usize::try_from(key_index)) {
189            if registered.len() <= key_index {
190                registered.resize(key_index + 1, false);
191            }
192            registered[key_index] = true;
193        }
194    }
195    registered.get(index).copied().unwrap_or(false)
196}
197
198/// Look up a reflected method of a type by type key and method name.
199///
200/// Same as [`get_method_by_index`], but resolves `type_key` to a type index
201/// first.
202///
203/// # Arguments
204///
205/// * `type_key` - The type key of the type that owns the method.
206/// * `method_name` - The name of the method.
207///
208/// # Returns
209///
210/// The reflected method.
211///
212/// # Errors
213///
214/// Returns a `TypeError` if the type or the method does not exist.
215pub fn get_method(type_key: &str, method_name: &str) -> Result<Function> {
216    let mut type_index: i32 = 0;
217    // SAFETY: the byte array borrows `type_key` for the call.
218    let found =
219        unsafe { TVMFFITypeKeyToIndex(&TVMFFIByteArray::from_str(type_key), &mut type_index) == 0 };
220    if !found {
221        // Discard the runtime's error, which reports an internal one.
222        drop(Error::from_raised());
223        crate::bail!(crate::error::TYPE_ERROR, "Cannot find type `{type_key}`");
224    }
225    get_method_by_index(type_index, method_name)
226}
227
228/// Look up a reflected method of a type by type index and method name, as
229/// [`get_method`] does by type key.
230///
231/// Reflected methods, registered in any language (such as with
232/// [`ObjectDef::def`](super::ObjectDef::def)), live in the type's method
233/// table rather than the global function table. The constructor is reachable
234/// under the reserved name `__ffi_init__`. For instance methods, the first
235/// argument is the object itself.
236///
237/// # Arguments
238///
239/// * `type_index` - The type index of the type that owns the method.
240/// * `method_name` - The name of the method.
241///
242/// # Returns
243///
244/// The reflected method.
245///
246/// # Errors
247///
248/// Returns a `TypeError` if `type_index` is not registered or the type has no
249/// method `method_name`.
250pub fn get_method_by_index(type_index: i32, method_name: &str) -> Result<Function> {
251    // The C API aborts the process on an unregistered index.
252    if !is_registered(type_index) {
253        crate::bail!(
254            crate::error::TYPE_ERROR,
255            "Cannot find type info for type_index={}",
256            type_index
257        );
258    }
259    unsafe {
260        let type_info = &*TVMFFIGetTypeInfo(type_index);
261        for i in 0..type_info.num_methods as usize {
262            let method_info = &*type_info.methods.add(i);
263            if method_info.name.as_str() != method_name {
264                continue;
265            }
266            if !<Function as AnyCompatible>::check_any_strict(&method_info.method) {
267                crate::bail!(
268                    crate::error::TYPE_ERROR,
269                    "Method `{}` of type `{}` is not a Function",
270                    method_name,
271                    type_info.type_key.as_str()
272                );
273            }
274            // the table entry stores the method as a non-owning AnyView;
275            // copy out a strong reference
276            return Ok(<Function as AnyCompatible>::copy_from_any_view_after_check(
277                &method_info.method,
278            ));
279        }
280        crate::bail!(
281            crate::error::TYPE_ERROR,
282            "Cannot find method `{}` of type `{}`",
283            method_name,
284            type_info.type_key.as_str()
285        );
286    }
287}
288/// Resolves a reflected field once, then uses its registered C ABI getter.
289///
290/// [`FieldGetter::new`] resolves a field by runtime type index into a
291/// `FieldGetter`, which checks the type of each object it reads. [`FieldGetter::of`] resolves a field of the
292/// object type `N` into a `FieldGetter<N>`, which reads only `&N`, so the
293/// type system replaces that check; [`cached_field_getter!`](crate::cached_field_getter)
294/// keeps one for the process.
295pub struct FieldGetter<N = ()> {
296    owner_type_index: i32,
297    owner_type_depth: i32,
298    field_offset: i64,
299    getter: TVMFFIFieldGetter,
300    owner: PhantomData<fn(&N)>,
301}
302
303impl<N> Clone for FieldGetter<N> {
304    #[inline(always)]
305    fn clone(&self) -> Self {
306        *self
307    }
308}
309
310impl<N> Copy for FieldGetter<N> {}
311
312impl FieldGetter {
313    /// Resolve a reflected field declared by `type_index` or one of its bases.
314    ///
315    /// # Errors
316    ///
317    /// Returns a `TypeError` if `type_index` is not registered or the type has
318    /// no reflected field `field_name` with a getter.
319    pub fn new(type_index: i32, field_name: &str) -> Result<Self> {
320        resolve(type_index, field_name)
321    }
322
323    /// Resolve a reflected field declared by `N` or one of its bases.
324    ///
325    /// # Errors
326    ///
327    /// As [`FieldGetter::new`] for `N::type_index()`.
328    pub fn of<N: ObjectCore>(field_name: &str) -> Result<FieldGetter<N>> {
329        resolve(N::type_index(), field_name)
330    }
331
332    /// Read the field as an owning [`Any`].
333    ///
334    /// `object` may have the declared owner type or any registered subtype.
335    pub fn get_any<N: ObjectCore>(&self, object: &N) -> Result<Any> {
336        let object_pointer = std::ptr::from_ref(object);
337        let header = object_pointer.cast::<TVMFFIObject>();
338        let dynamic_type_index = unsafe { (*header).type_index };
339        if !unsafe {
340            is_type_or_subtype(
341                dynamic_type_index,
342                self.owner_type_index,
343                self.owner_type_depth,
344            )
345        } {
346            return Err(Error::new(
347                TYPE_ERROR,
348                &format!(
349                    "Cannot read a field of type_index={} from object type_index={dynamic_type_index}",
350                    self.owner_type_index
351                ),
352            ));
353        }
354        // SAFETY: `object` has the resolved type or a subtype, which embeds it.
355        unsafe { self.read(object) }
356    }
357
358    /// Read and convert the field to `T`.
359    pub fn get<N, T>(&self, object: &N) -> Result<T>
360    where
361        N: ObjectCore,
362        T: TryFrom<Any, Error = Error>,
363    {
364        T::try_from(self.get_any(object)?)
365    }
366}
367
368impl<N: ObjectCore> FieldGetter<N> {
369    /// Read the field as an owning [`Any`].
370    #[inline(always)]
371    pub fn get_any(&self, object: &N) -> Result<Any> {
372        // SAFETY: the field was resolved for `N`, whose layout `object` has.
373        unsafe { self.read(object) }
374    }
375
376    /// Read and convert the field to `T`.
377    #[inline(always)]
378    pub fn get<T>(&self, object: &N) -> Result<T>
379    where
380        T: TryFrom<Any, Error = Error>,
381    {
382        T::try_from(self.get_any(object)?)
383    }
384}
385
386impl<N> FieldGetter<N> {
387    /// # Safety
388    ///
389    /// `object` has the layout of the type the field was resolved for.
390    #[inline(always)]
391    unsafe fn read<M>(&self, object: &M) -> Result<Any> {
392        let field_address = unsafe {
393            std::ptr::from_ref(object)
394                .cast::<u8>()
395                .offset(self.field_offset as isize)
396                .cast_mut()
397                .cast::<c_void>()
398        };
399        let mut result = Any::new();
400        if unsafe { (self.getter)(field_address, Any::as_raw_ffi_any_mut(&mut result)) } != 0 {
401            return Err(Error::from_raised());
402        }
403        Ok(result)
404    }
405}
406
407fn resolve<N>(type_index: i32, field_name: &str) -> Result<FieldGetter<N>> {
408    // The C API aborts the process on an unregistered index.
409    if !is_registered(type_index) {
410        return Err(Error::new(
411            TYPE_ERROR,
412            &format!("Cannot find type info for type_index={type_index}"),
413        ));
414    }
415    let type_info = unsafe { TVMFFIGetTypeInfo(type_index) };
416
417    let field = unsafe { find_field(type_info, field_name) }.ok_or_else(|| {
418        let type_key = unsafe { (*type_info).type_key.as_str() };
419        Error::new(
420            TYPE_ERROR,
421            &format!("Cannot find reflected field `{field_name}` in type `{type_key}`"),
422        )
423    })?;
424    let field = unsafe { field.as_ref() };
425    let getter = field.getter.ok_or_else(|| {
426        // SAFETY: a field name is UTF-8 text.
427        let name = unsafe { field.name.as_str() };
428        Error::new(
429            TYPE_ERROR,
430            &format!("Reflected field `{name}` has no getter"),
431        )
432    })?;
433    Ok(FieldGetter {
434        owner_type_index: type_index,
435        owner_type_depth: unsafe { (*type_info).type_depth },
436        field_offset: field.offset,
437        getter,
438        owner: PhantomData,
439    })
440}
441
442unsafe fn find_field(
443    type_info: *const crate::tvm_ffi_sys::TVMFFITypeInfo,
444    field_name: &str,
445) -> Option<NonNull<TVMFFIFieldInfo>> {
446    // Prefer the most-derived declaration, then search nearest ancestors.
447    if let Some(field) = unsafe { find_field_at_level(type_info, field_name) } {
448        return Some(field);
449    }
450    for depth in unsafe { (0..(*type_info).type_depth).rev() } {
451        let ancestor = unsafe { *(*type_info).type_acenstors.add(depth as usize) };
452        if let Some(field) = unsafe { find_field_at_level(ancestor, field_name) } {
453            return Some(field);
454        }
455    }
456    None
457}
458
459unsafe fn find_field_at_level(
460    type_info: *const crate::tvm_ffi_sys::TVMFFITypeInfo,
461    field_name: &str,
462) -> Option<NonNull<TVMFFIFieldInfo>> {
463    if type_info.is_null() || unsafe { (*type_info).fields.is_null() } {
464        return None;
465    }
466    for index in unsafe { 0..(*type_info).num_fields as usize } {
467        let field = unsafe { (*type_info).fields.add(index) };
468        if unsafe { (*field).name.as_str() } == field_name {
469            return NonNull::new(field.cast_mut());
470        }
471    }
472    None
473}
474
475unsafe fn is_type_or_subtype(
476    dynamic_type_index: i32,
477    target_type_index: i32,
478    target_type_depth: i32,
479) -> bool {
480    if dynamic_type_index == target_type_index {
481        return true;
482    }
483    let dynamic_info = unsafe { TVMFFIGetTypeInfo(dynamic_type_index) };
484    if unsafe { dynamic_info.is_null() || (*dynamic_info).type_depth <= target_type_depth }
485        || unsafe { (*dynamic_info).type_acenstors.is_null() }
486    {
487        return false;
488    }
489    let ancestor = unsafe {
490        *(*dynamic_info)
491            .type_acenstors
492            .add(target_type_depth as usize)
493    };
494    unsafe { !ancestor.is_null() && (*ancestor).type_index == target_type_index }
495}