use std::ffi::c_void;
use std::marker::PhantomData;
use std::ptr::NonNull;
use std::sync::{PoisonError, RwLock};
use crate::tvm_ffi_sys::{
TVMFFIAny, TVMFFIByteArray, TVMFFIFieldFlagBitMask, TVMFFIFieldGetter, TVMFFIFieldInfo,
TVMFFIGetTypeAttrColumn, TVMFFIGetTypeInfo, TVMFFIObject, TVMFFITypeAttrColumn,
TVMFFITypeIndex, TVMFFITypeInfo, TVMFFITypeKeyToIndex,
};
use crate::type_traits::AnyCompatible;
use crate::{Any, AnyView, Array, Error, Function, ObjectCore, Result, TYPE_ERROR};
#[derive(Clone, Copy)]
pub struct TypeAttrColumn(NonNull<TVMFFITypeAttrColumn>);
unsafe impl Send for TypeAttrColumn {}
unsafe impl Sync for TypeAttrColumn {}
impl TypeAttrColumn {
pub fn lookup(name: &str) -> Option<Self> {
unsafe {
let name = TVMFFIByteArray::from_str(name);
NonNull::new(TVMFFIGetTypeAttrColumn(&name).cast_mut()).map(Self)
}
}
pub fn ensure(name: &str) -> Result<Self> {
{
let _registering = crate::object::lock_type_registration();
super::registry::register_type_attr(
TVMFFITypeIndex::kTVMFFINone as i32,
name,
Any::new(),
)?;
}
Self::lookup(name).ok_or_else(|| {
Error::new(
crate::INTERNAL_ERROR,
&format!("type attribute column `{name}` was not created"),
)
})
}
pub fn get(self, type_index: i32) -> Option<Any> {
let raw = self.get_raw_ffi_any(type_index)?;
if raw.type_index == TVMFFITypeIndex::kTVMFFINone as i32 {
return None;
}
Some(Any::from(unsafe { AnyView::from_raw_ffi_any(raw) }))
}
#[inline(always)]
pub fn get_raw_ffi_any(self, type_index: i32) -> Option<TVMFFIAny> {
unsafe {
let column = self.0.as_ref();
let index = type_index - column.begin_index;
if index < 0 || index >= column.size || column.data.is_null() {
None
} else {
Some(*column.data.offset(index as isize))
}
}
}
}
pub fn type_key(type_index: i32) -> Option<&'static str> {
if !is_registered(type_index) {
return None;
}
let info: &'static TVMFFITypeInfo = unsafe { &*TVMFFIGetTypeInfo(type_index) };
Some(unsafe { info.type_key.as_str() })
}
pub fn field_default<T: ObjectCore>(name: &str) -> Option<Any> {
let info: &'static TVMFFITypeInfo = unsafe { &*TVMFFIGetTypeInfo(T::type_index()) };
let fields = unsafe {
crate::util::slice_from_nullable_raw_parts(info.fields, info.num_fields as usize)
};
let field = fields
.iter()
.find(|field| unsafe { field.name.as_str() } == name)?;
let has_default = TVMFFIFieldFlagBitMask::kTVMFFIFieldFlagBitMaskHasDefault as i64;
let from_factory = TVMFFIFieldFlagBitMask::kTVMFFIFieldFlagBitMaskDefaultFromFactory as i64;
if field.flags & has_default == 0 || field.flags & from_factory != 0 {
return None;
}
Some(Any::from(unsafe {
AnyView::from_raw_ffi_any(field.default_value_or_factory)
}))
}
fn is_registered(type_index: i32) -> bool {
static REGISTERED: RwLock<Vec<bool>> = RwLock::new(Vec::new());
let Ok(index) = usize::try_from(type_index) else {
return false;
};
let read = REGISTERED.read().unwrap_or_else(PoisonError::into_inner);
if read.get(index).copied().unwrap_or(false) {
return true;
}
drop(read);
let keys = crate::cached_global_func!("ffi.GetRegisteredTypeKeys")
.call_tuple(())
.and_then(Array::<crate::String>::try_from);
let mut registered = REGISTERED.write().unwrap_or_else(PoisonError::into_inner);
for key in keys.iter().flat_map(|keys| keys.iter()) {
let mut key_index = 0;
let found = unsafe {
TVMFFITypeKeyToIndex(&TVMFFIByteArray::from_str(key.as_str()), &mut key_index) == 0
};
if let (true, Ok(key_index)) = (found, usize::try_from(key_index)) {
if registered.len() <= key_index {
registered.resize(key_index + 1, false);
}
registered[key_index] = true;
}
}
registered.get(index).copied().unwrap_or(false)
}
pub fn get_method(type_key: &str, method_name: &str) -> Result<Function> {
let mut type_index: i32 = 0;
let found =
unsafe { TVMFFITypeKeyToIndex(&TVMFFIByteArray::from_str(type_key), &mut type_index) == 0 };
if !found {
drop(Error::from_raised());
crate::bail!(crate::error::TYPE_ERROR, "Cannot find type `{type_key}`");
}
get_method_by_index(type_index, method_name)
}
pub fn get_method_by_index(type_index: i32, method_name: &str) -> Result<Function> {
if !is_registered(type_index) {
crate::bail!(
crate::error::TYPE_ERROR,
"Cannot find type info for type_index={}",
type_index
);
}
unsafe {
let type_info = &*TVMFFIGetTypeInfo(type_index);
for i in 0..type_info.num_methods as usize {
let method_info = &*type_info.methods.add(i);
if method_info.name.as_str() != method_name {
continue;
}
if !<Function as AnyCompatible>::check_any_strict(&method_info.method) {
crate::bail!(
crate::error::TYPE_ERROR,
"Method `{}` of type `{}` is not a Function",
method_name,
type_info.type_key.as_str()
);
}
return Ok(<Function as AnyCompatible>::copy_from_any_view_after_check(
&method_info.method,
));
}
crate::bail!(
crate::error::TYPE_ERROR,
"Cannot find method `{}` of type `{}`",
method_name,
type_info.type_key.as_str()
);
}
}
pub struct FieldGetter<N = ()> {
owner_type_index: i32,
owner_type_depth: i32,
field_offset: i64,
getter: TVMFFIFieldGetter,
owner: PhantomData<fn(&N)>,
}
impl<N> Clone for FieldGetter<N> {
#[inline(always)]
fn clone(&self) -> Self {
*self
}
}
impl<N> Copy for FieldGetter<N> {}
impl FieldGetter {
pub fn new(type_index: i32, field_name: &str) -> Result<Self> {
resolve(type_index, field_name)
}
pub fn of<N: ObjectCore>(field_name: &str) -> Result<FieldGetter<N>> {
resolve(N::type_index(), field_name)
}
pub fn get_any<N: ObjectCore>(&self, object: &N) -> Result<Any> {
let object_pointer = std::ptr::from_ref(object);
let header = object_pointer.cast::<TVMFFIObject>();
let dynamic_type_index = unsafe { (*header).type_index };
if !unsafe {
is_type_or_subtype(
dynamic_type_index,
self.owner_type_index,
self.owner_type_depth,
)
} {
return Err(Error::new(
TYPE_ERROR,
&format!(
"Cannot read a field of type_index={} from object type_index={dynamic_type_index}",
self.owner_type_index
),
));
}
unsafe { self.read(object) }
}
pub fn get<N, T>(&self, object: &N) -> Result<T>
where
N: ObjectCore,
T: TryFrom<Any, Error = Error>,
{
T::try_from(self.get_any(object)?)
}
}
impl<N: ObjectCore> FieldGetter<N> {
#[inline(always)]
pub fn get_any(&self, object: &N) -> Result<Any> {
unsafe { self.read(object) }
}
#[inline(always)]
pub fn get<T>(&self, object: &N) -> Result<T>
where
T: TryFrom<Any, Error = Error>,
{
T::try_from(self.get_any(object)?)
}
}
impl<N> FieldGetter<N> {
#[inline(always)]
unsafe fn read<M>(&self, object: &M) -> Result<Any> {
let field_address = unsafe {
std::ptr::from_ref(object)
.cast::<u8>()
.offset(self.field_offset as isize)
.cast_mut()
.cast::<c_void>()
};
let mut result = Any::new();
if unsafe { (self.getter)(field_address, Any::as_raw_ffi_any_mut(&mut result)) } != 0 {
return Err(Error::from_raised());
}
Ok(result)
}
}
fn resolve<N>(type_index: i32, field_name: &str) -> Result<FieldGetter<N>> {
if !is_registered(type_index) {
return Err(Error::new(
TYPE_ERROR,
&format!("Cannot find type info for type_index={type_index}"),
));
}
let type_info = unsafe { TVMFFIGetTypeInfo(type_index) };
let field = unsafe { find_field(type_info, field_name) }.ok_or_else(|| {
let type_key = unsafe { (*type_info).type_key.as_str() };
Error::new(
TYPE_ERROR,
&format!("Cannot find reflected field `{field_name}` in type `{type_key}`"),
)
})?;
let field = unsafe { field.as_ref() };
let getter = field.getter.ok_or_else(|| {
let name = unsafe { field.name.as_str() };
Error::new(
TYPE_ERROR,
&format!("Reflected field `{name}` has no getter"),
)
})?;
Ok(FieldGetter {
owner_type_index: type_index,
owner_type_depth: unsafe { (*type_info).type_depth },
field_offset: field.offset,
getter,
owner: PhantomData,
})
}
unsafe fn find_field(
type_info: *const crate::tvm_ffi_sys::TVMFFITypeInfo,
field_name: &str,
) -> Option<NonNull<TVMFFIFieldInfo>> {
if let Some(field) = unsafe { find_field_at_level(type_info, field_name) } {
return Some(field);
}
for depth in unsafe { (0..(*type_info).type_depth).rev() } {
let ancestor = unsafe { *(*type_info).type_acenstors.add(depth as usize) };
if let Some(field) = unsafe { find_field_at_level(ancestor, field_name) } {
return Some(field);
}
}
None
}
unsafe fn find_field_at_level(
type_info: *const crate::tvm_ffi_sys::TVMFFITypeInfo,
field_name: &str,
) -> Option<NonNull<TVMFFIFieldInfo>> {
if type_info.is_null() || unsafe { (*type_info).fields.is_null() } {
return None;
}
for index in unsafe { 0..(*type_info).num_fields as usize } {
let field = unsafe { (*type_info).fields.add(index) };
if unsafe { (*field).name.as_str() } == field_name {
return NonNull::new(field.cast_mut());
}
}
None
}
unsafe fn is_type_or_subtype(
dynamic_type_index: i32,
target_type_index: i32,
target_type_depth: i32,
) -> bool {
if dynamic_type_index == target_type_index {
return true;
}
let dynamic_info = unsafe { TVMFFIGetTypeInfo(dynamic_type_index) };
if unsafe { dynamic_info.is_null() || (*dynamic_info).type_depth <= target_type_depth }
|| unsafe { (*dynamic_info).type_acenstors.is_null() }
{
return false;
}
let ancestor = unsafe {
*(*dynamic_info)
.type_acenstors
.add(target_type_depth as usize)
};
unsafe { !ancestor.is_null() && (*ancestor).type_index == target_type_index }
}