1use 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#[derive(Clone, Copy)]
40pub struct TypeAttrColumn(NonNull<TVMFFITypeAttrColumn>);
41
42unsafe impl Send for TypeAttrColumn {}
46unsafe impl Sync for TypeAttrColumn {}
47
48impl TypeAttrColumn {
49 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 pub fn ensure(name: &str) -> Result<Self> {
66 {
67 let _registering = crate::object::lock_type_registration();
68 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 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 #[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
114pub fn type_key(type_index: i32) -> Option<&'static str> {
125 if !is_registered(type_index) {
126 return None;
127 }
128 let info: &'static TVMFFITypeInfo = unsafe { &*TVMFFIGetTypeInfo(type_index) };
131 Some(unsafe { info.type_key.as_str() })
133}
134
135pub fn field_default<T: ObjectCore>(name: &str) -> Option<Any> {
141 let info: &'static TVMFFITypeInfo = unsafe { &*TVMFFIGetTypeInfo(T::type_index()) };
144 let fields = unsafe {
146 crate::util::slice_from_nullable_raw_parts(info.fields, info.num_fields as usize)
147 };
148 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 Some(Any::from(unsafe {
160 AnyView::from_raw_ffi_any(field.default_value_or_factory)
161 }))
162}
163
164fn 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 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
198pub fn get_method(type_key: &str, method_name: &str) -> Result<Function> {
216 let mut type_index: i32 = 0;
217 let found =
219 unsafe { TVMFFITypeKeyToIndex(&TVMFFIByteArray::from_str(type_key), &mut type_index) == 0 };
220 if !found {
221 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
228pub fn get_method_by_index(type_index: i32, method_name: &str) -> Result<Function> {
251 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 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}
288pub 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 pub fn new(type_index: i32, field_name: &str) -> Result<Self> {
320 resolve(type_index, field_name)
321 }
322
323 pub fn of<N: ObjectCore>(field_name: &str) -> Result<FieldGetter<N>> {
329 resolve(N::type_index(), field_name)
330 }
331
332 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 unsafe { self.read(object) }
356 }
357
358 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 #[inline(always)]
371 pub fn get_any(&self, object: &N) -> Result<Any> {
372 unsafe { self.read(object) }
374 }
375
376 #[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 #[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 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 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 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}