pub use crate::function_internal::{AsPackedCallable, PackedCallArg, PackedCallArgs};
use crate::any::{Any, AnyView};
use crate::derive::{Object, ObjectRef};
use crate::error::{Error, Result};
use crate::object::{Object, ObjectArc, ObjectCore};
use crate::type_traits::AnyCompatible;
use tvm_ffi_sys::{
TVMFFIAny, TVMFFIByteArray, TVMFFIFunctionCell, TVMFFIFunctionCreate, TVMFFIFunctionGetGlobal,
TVMFFIFunctionSetGlobalFromMethodInfo, TVMFFIMethodInfo, TVMFFIObjectHandle,
TVMFFISafeCallType, TVMFFITypeIndex,
};
#[repr(C)]
#[derive(Object)]
#[object(type_key = "ffi.Function", unsafe type_index = TVMFFITypeIndex::kTVMFFIFunction)]
pub struct FunctionObj {
object: Object,
cell: TVMFFIFunctionCell,
}
#[derive(Clone, ObjectRef)]
#[object_ref(skip_deref)]
pub struct Function {
data: ObjectArc<FunctionObj>,
}
unsafe impl Send for Function {}
unsafe impl Sync for Function {}
#[repr(C)]
struct CallbackFunctionObjImpl<F: Fn(&[AnyView]) -> Result<Any> + Send + Sync + 'static> {
function: FunctionObj,
callback: F,
}
impl<F: Fn(&[AnyView]) -> Result<Any> + Send + Sync + 'static> CallbackFunctionObjImpl<F> {
pub fn from_callback(callback: F) -> Self {
Self {
function: FunctionObj {
object: Object::new(),
cell: TVMFFIFunctionCell {
safe_call: Self::invoke_callback,
cxx_call: std::ptr::null_mut(),
},
},
callback,
}
}
unsafe extern "C" fn invoke_callback(
handle: *mut std::ffi::c_void,
args: *const TVMFFIAny,
num_args: i32,
result: *mut TVMFFIAny,
) -> i32 {
let this = unsafe { &*(handle as *mut Self) };
let packed_args = unsafe { crate::function_internal::packed_args(args, num_args) };
let ret_value = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
(this.callback)(packed_args)
})) {
Ok(ret_value) => ret_value,
Err(payload) => Err(Error::from_panic(payload)),
};
match ret_value {
Ok(value) => {
unsafe { *result = Any::into_raw_ffi_any(value) };
0
}
Err(error) => {
Error::set_raised(&error);
-1
}
}
}
}
unsafe impl<F: Fn(&[AnyView]) -> Result<Any> + Send + Sync + 'static> ObjectCore
for CallbackFunctionObjImpl<F>
{
type Parent = FunctionObj;
const TYPE_KEY: &'static str = FunctionObj::TYPE_KEY;
const TYPE_DEPTH: i32 = FunctionObj::TYPE_DEPTH;
fn type_index() -> i32 {
FunctionObj::type_index()
}
unsafe fn object_header_mut(this: &mut Self) -> &mut tvm_ffi_sys::TVMFFIObject {
unsafe { FunctionObj::object_header_mut(&mut this.function) }
}
}
impl Function {
pub fn call_packed(&self, packed_args: &[AnyView]) -> Result<Any> {
unsafe {
let packed_args_ptr = packed_args.as_ptr() as *const TVMFFIAny;
let mut result = Any::new();
let ret_code = (self.data.cell.safe_call)(
ObjectArc::as_ptr(&self.data) as *mut FunctionObj as *mut std::ffi::c_void,
packed_args_ptr,
packed_args.len() as i32,
Any::as_raw_ffi_any_mut(&mut result),
);
if ret_code == 0 {
Ok(result)
} else {
Err(Error::from_raised())
}
}
}
pub fn call_tuple(&self, tuple_args: impl PackedCallArgs) -> Result<Any> {
tuple_args.with_packed_args(|packed_args| self.call_packed(packed_args))
}
pub fn get_global(name: &str) -> Result<Function> {
unsafe {
let name_arg = TVMFFIByteArray::from_str(name);
let mut result: TVMFFIObjectHandle = ::std::ptr::null_mut();
crate::check_safe_call!(TVMFFIFunctionGetGlobal(&name_arg, &mut result))?;
if result.is_null() {
crate::bail!(crate::error::VALUE_ERROR, "Function {} not found", name);
}
Ok(Self {
data: ObjectArc::<FunctionObj>::from_raw(result as *mut FunctionObj),
})
}
}
pub fn register_global(name: &str, func: Function) -> Result<()> {
let type_schema = crate::type_traits::type_schema(FunctionObj::TYPE_KEY, &[]);
Self::register_global_with_info(name, &func, &type_schema, "")
}
pub fn register_global_typed<F, I, O>(name: &str, func: F, doc: &str) -> Result<()>
where
F: AsPackedCallable<I, O> + Send + Sync + 'static,
{
let type_schema = F::type_schema();
Self::register_global_with_info(name, &Self::from_typed(func), &type_schema, doc)
}
fn register_global_with_info(
name: &str,
func: &Function,
type_schema: &str,
doc: &str,
) -> Result<()> {
let metadata = crate::type_traits::type_schema_metadata(type_schema);
let mut method = TVMFFIAny::new();
unsafe {
<Function as AnyCompatible>::copy_to_any_view(func, &mut method);
let info = TVMFFIMethodInfo {
name: TVMFFIByteArray::from_str(name),
doc: TVMFFIByteArray::from_str(doc),
metadata: TVMFFIByteArray::from_str(&metadata),
flags: 0,
method,
};
let can_override = 0;
crate::check_safe_call!(TVMFFIFunctionSetGlobalFromMethodInfo(&info, can_override))
}
}
pub fn from_packed<F>(func: F) -> Self
where
F: Fn(&[AnyView]) -> Result<Any> + Send + Sync + 'static,
{
unsafe {
let callback_arc = ObjectArc::new(CallbackFunctionObjImpl::from_callback(func));
let func_arc = ObjectArc::<FunctionObj>::from_raw(
ObjectArc::into_raw(callback_arc) as *mut FunctionObj
);
Self { data: func_arc }
}
}
pub fn from_typed<F, I, O>(func: F) -> Self
where
F: AsPackedCallable<I, O> + Send + Sync + 'static,
{
let closure = move |packed_args: &[AnyView]| -> Result<Any> {
let ret_value = func.call_packed(packed_args)?;
Ok(ret_value)
};
Self::from_packed(closure)
}
pub unsafe fn from_extern_c(
handle: *mut std::ffi::c_void,
safe_call: TVMFFISafeCallType,
deleter: Option<unsafe extern "C" fn(*mut std::ffi::c_void)>,
) -> Result<Self> {
unsafe {
let mut out_handle: TVMFFIObjectHandle = std::ptr::null_mut();
crate::check_safe_call!(TVMFFIFunctionCreate(
handle,
safe_call,
deleter,
&mut out_handle
))?;
Ok(Self {
data: ObjectArc::<FunctionObj>::from_raw(out_handle as *mut FunctionObj),
})
}
}
}