use tvm_ffi::function::AsPackedCallable;
#[cfg(feature = "export-metadata")]
use tvm_ffi::tvm_ffi_sys::TVMFFIAny;
use tvm_ffi::*;
#[cfg(feature = "export-metadata")]
unsafe extern "C" {
fn __tvm_ffi__metadata_testing_dll_schema_id_int(
handle: *mut std::ffi::c_void,
args: *const TVMFFIAny,
num_args: i32,
result: *mut TVMFFIAny,
) -> i32;
}
#[cfg(feature = "export-metadata")]
fn call_getter(getter: tvm_ffi::tvm_ffi_sys::TVMFFISafeCallType) -> String {
let getter = unsafe { Function::from_extern_c(std::ptr::null_mut(), getter, None).unwrap() };
getter.call_packed(&[]).unwrap().try_into().unwrap()
}
fn global_metadata(name: &str) -> String {
assert_eq!(unsafe { tvm_ffi_sys::TVMFFITestingDummyTarget() }, 0);
Function::get_global("ffi.GetGlobalFuncMetadata")
.unwrap()
.call_tuple((String::from(name),))
.unwrap()
.try_into()
.unwrap()
}
fn rust_schema_id_int(x: i64) -> Result<i64> {
Ok(x)
}
tvm_ffi_dll_export_typed_func!(rust_schema_id_int, rust_schema_id_int);
#[cfg(feature = "export-metadata")]
#[test]
fn test_exported_metadata_matches_cpp() {
let rust = call_getter(__tvm_ffi__metadata_rust_schema_id_int);
let cpp = call_getter(__tvm_ffi__metadata_testing_dll_schema_id_int);
assert_eq!(rust.as_str(), cpp.as_str());
}
fn rust_add(a: i64, b: i64) -> Result<i64> {
Ok(a + b)
}
tvm_ffi_dll_export_typed_func!(rust_add, rust_add);
tvm_ffi_dll_export_typed_func_doc!(
rust_add,
"Add two integers and return the sum.\n\n\"a\" and \"b\" are integers."
);
#[cfg(feature = "export-metadata")]
#[test]
fn test_exported_doc_is_verbatim() {
let doc = call_getter(__tvm_ffi__doc_rust_add);
assert_eq!(
doc.as_str(),
"Add two integers and return the sum.\n\n\"a\" and \"b\" are integers."
);
}
struct Packed(fn(&[AnyView]) -> Result<Any>);
struct PackedArgs;
impl AsPackedCallable<PackedArgs, Any> for Packed {
fn call_packed(&self, packed_args: &[AnyView]) -> Result<Any> {
(self.0)(packed_args)
}
}
fn rust_packed(_args: &[AnyView]) -> Result<Any> {
Ok(Any::new())
}
tvm_ffi_dll_export_typed_func!(rust_packed, Packed(rust_packed));
#[cfg(feature = "export-metadata")]
#[test]
fn test_exported_packed_metadata_is_untyped() {
register_globals();
let rust = call_getter(__tvm_ffi__metadata_rust_packed);
assert_eq!(
rust.as_str(),
global_metadata("testing.schema_packed").as_str()
);
}
#[cfg(not(feature = "export-metadata"))]
mod without_export_metadata {
#[unsafe(no_mangle)]
pub extern "C" fn __tvm_ffi__metadata_rust_schema_id_int() {}
#[unsafe(no_mangle)]
pub extern "C" fn __tvm_ffi__metadata_rust_packed() {}
#[unsafe(no_mangle)]
pub extern "C" fn __tvm_ffi__doc_rust_add() {}
}
#[cfg(not(feature = "export-metadata"))]
#[test]
fn test_exports_without_metadata() {
let add =
unsafe { Function::from_extern_c(std::ptr::null_mut(), __tvm_ffi_rust_add, None).unwrap() };
let sum = add.call_tuple((1i64, 2i64)).unwrap();
assert_eq!(i64::try_from(sum).unwrap(), 3);
without_export_metadata::__tvm_ffi__metadata_rust_schema_id_int();
without_export_metadata::__tvm_ffi__metadata_rust_packed();
without_export_metadata::__tvm_ffi__doc_rust_add();
}
fn register_typed<F, I, O>(names: &mut Vec<&'static str>, name: &'static str, func: F)
where
F: AsPackedCallable<I, O> + Send + Sync + 'static,
{
Function::register_global_typed(&format!("testing.rust.{name}"), func, "").unwrap();
names.push(name);
}
fn register_globals() -> &'static [&'static str] {
static NAMES: std::sync::OnceLock<Vec<&'static str>> = std::sync::OnceLock::new();
NAMES.get_or_init(|| {
let mut names = Vec::new();
let n = &mut names;
register_typed(n, "schema_id_float", |x: f64| -> Result<f64> { Ok(x) });
register_typed(n, "schema_id_bool", |x: bool| -> Result<bool> { Ok(x) });
register_typed(n, "schema_id_device", |x: DLDevice| -> Result<DLDevice> {
Ok(x)
});
register_typed(
n,
"schema_id_dtype",
|x: DLDataType| -> Result<DLDataType> { Ok(x) },
);
register_typed(n, "schema_id_string", |x: String| -> Result<String> {
Ok(x)
});
register_typed(n, "schema_id_bytes", |x: Bytes| -> Result<Bytes> { Ok(x) });
register_typed(n, "schema_id_func", |x: Function| -> Result<Function> {
Ok(x)
});
register_typed(
n,
"schema_id_object",
|x: object::ObjectRef| -> Result<object::ObjectRef> { Ok(x) },
);
register_typed(n, "schema_id_tensor", |x: Tensor| -> Result<Tensor> {
Ok(x)
});
register_typed(
n,
"schema_tensor_view_input",
|_: TensorView| -> Result<()> { Ok(()) },
);
register_typed(
n,
"schema_id_opt_int",
|x: Option<i64>| -> Result<Option<i64>> { Ok(x) },
);
register_typed(
n,
"schema_id_opt_str",
|x: Option<String>| -> Result<Option<String>> { Ok(x) },
);
register_typed(
n,
"schema_id_opt_obj",
|x: Option<object::ObjectRef>| -> Result<Option<object::ObjectRef>> { Ok(x) },
);
register_typed(
n,
"schema_id_arr_int",
|x: Array<i64>| -> Result<Array<i64>> { Ok(x) },
);
register_typed(
n,
"schema_id_arr_str",
|x: Array<String>| -> Result<Array<String>> { Ok(x) },
);
register_typed(
n,
"schema_id_arr_obj",
|x: Array<object::ObjectRef>| -> Result<Array<object::ObjectRef>> { Ok(x) },
);
register_typed(
n,
"schema_id_map_str_int",
|x: Map<String, i64>| -> Result<Map<String, i64>> { Ok(x) },
);
register_typed(
n,
"schema_id_map_str_str",
|x: Map<String, String>| -> Result<Map<String, String>> { Ok(x) },
);
register_typed(
n,
"schema_id_map_str_obj",
|x: Map<String, object::ObjectRef>| -> Result<Map<String, object::ObjectRef>> { Ok(x) },
);
register_typed(
n,
"schema_arr_map_opt",
|_: Array<Option<i64>>,
mp: Map<String, Array<i64>>,
_: Option<String>|
-> Result<Map<String, Array<i64>>> { Ok(mp) },
);
register_typed(n, "schema_no_args", || -> Result<i64> { Ok(1) });
register_typed(n, "schema_no_return", |_: i64| -> Result<()> { Ok(()) });
register_typed(n, "schema_no_args_no_return", || -> Result<()> { Ok(()) });
let packed = Function::from_packed(|_: &[AnyView]| -> Result<Any> { Ok(Any::new()) });
Function::register_global("testing.rust.schema_packed", packed).unwrap();
Function::register_global_typed(
"testing.rust.add",
|a: i64, b: i64| -> Result<i64> { Ok(a + b) },
"Add two integers.",
)
.unwrap();
names
})
}
#[test]
fn test_global_metadata_matches_cpp() {
let names = register_globals();
assert_eq!(names.len(), 23);
for name in names {
assert_eq!(
global_metadata(&format!("testing.rust.{name}")).as_str(),
global_metadata(&format!("testing.{name}")).as_str(),
"{name}"
);
}
}
#[test]
fn test_global_untyped_metadata_matches_cpp() {
register_globals();
assert_eq!(
global_metadata("testing.rust.schema_packed").as_str(),
global_metadata("testing.schema_packed").as_str()
);
}
#[test]
fn test_global_typed_registration_calls_the_function() {
register_globals();
let add = Function::get_global("testing.rust.add").unwrap();
let sum = add.call_tuple((1i64, 2i64)).unwrap();
assert_eq!(i64::try_from(sum).unwrap(), 3);
}