1use crate::any::{Any, AnyView, ArgTryFromAnyView};
20use crate::error::{Error, Result};
21use crate::function::FunctionObj;
22use crate::object::{ObjectCore, ObjectRefCore};
23use crate::rvalue_ref::RValueRef;
24use crate::string::{Bytes, String};
25use crate::type_traits::{AnyCompatible, ContainerElement, TypeSchema};
26use tvm_ffi_sys::{TVMFFIAny, TVMFFIByteArray, TVMFFIStringFromByteArray};
27
28#[doc(hidden)]
37#[inline(always)]
38pub unsafe fn packed_args<'a>(args: *const TVMFFIAny, num_args: i32) -> &'a [AnyView<'a>] {
39 if num_args <= 0 {
40 core::hint::cold_path();
43 return &[];
44 }
45 unsafe { std::slice::from_raw_parts(args as *const AnyView, num_args as usize) }
46}
47
48pub trait AsPackedCallable<I, O> {
56 fn call_packed(&self, packed_args: &[AnyView]) -> Result<Any>;
58
59 fn type_schema() -> std::string::String
65 where
66 Self: Sized,
67 {
68 crate::type_traits::type_schema(FunctionObj::TYPE_KEY, &[])
69 }
70}
71
72#[inline]
74pub fn type_schema_of<Fun, I, O>(_func: &Fun) -> std::string::String
75where
76 Fun: AsPackedCallable<I, O>,
77{
78 Fun::type_schema()
79}
80
81#[doc(hidden)]
90pub unsafe fn write_exported_str(text: Result<std::string::String>, result: *mut TVMFFIAny) -> i32 {
91 match text {
92 Ok(text) => {
93 let text = unsafe { TVMFFIByteArray::from_str(&text) };
94 unsafe { TVMFFIStringFromByteArray(&text, result) }
95 }
96 Err(error) => {
97 Error::set_raised(&error);
98 -1
99 }
100 }
101}
102
103#[doc(hidden)]
106pub fn exported_metadata<Fun, I, O>(func: &Fun) -> Result<std::string::String>
107where
108 Fun: AsPackedCallable<I, O>,
109{
110 let type_schema = type_schema_of(func);
111 Ok(crate::type_traits::type_schema_metadata(&type_schema))
112}
113
114#[inline]
115pub fn call_packed_callable<Fun, I, O>(func: Fun, packed_args: &[AnyView]) -> Result<Any>
116where
117 Fun: AsPackedCallable<I, O>,
118{
119 func.call_packed(packed_args)
120}
121
122macro_rules! impl_as_packed_callable {
123 ($len:literal; $($t:ident),*) => {
124 impl<Fun, $($t,)* Out> AsPackedCallable<($($t,)*), Out> for Fun
125 where
126 Fun: Fn($($t,)*) -> Result<Out> + 'static,
127 Any: From<Out>,
128 Out: TypeSchema,
129 $($t: ArgTryFromAnyView),*
130 {
131 fn type_schema() -> std::string::String {
132 let params: &[std::string::String] = &[$(<$t as TypeSchema>::type_schema()),*];
133 format!(
134 r#"{{"type":"{}","named_args":{{"return":[{}],"params":[{}]}}}}"#,
135 FunctionObj::TYPE_KEY,
136 Out::type_schema(),
137 params.join(","),
138 )
139 }
140
141 fn call_packed(&self, packed_args: &[AnyView]) -> Result<Any>
142 {
143 crate::ensure!(
144 packed_args.len() == $len, crate::error::TYPE_ERROR,
145 "Expected {} arguments, got {}", $len, packed_args.len()
146 );
147 let mut _arg_iter = packed_args.iter().enumerate();
149 let ret_value = self(
150 $({
151 let (i, view) = _arg_iter.next().unwrap();
153 $t::try_from_any_view(view, i)?
154 }),*
155 )?;
156 Ok(Any::from(ret_value))
157 }
158 }
159 }
160}
161
162impl_as_packed_callable!(0;);
163impl_as_packed_callable!(1; T0);
164impl_as_packed_callable!(2; T0, T1);
165impl_as_packed_callable!(3; T0, T1, T2);
166impl_as_packed_callable!(4; T0, T1, T2, T3);
167impl_as_packed_callable!(5; T0, T1, T2, T3, T4);
168impl_as_packed_callable!(6; T0, T1, T2, T3, T4, T5);
169impl_as_packed_callable!(7; T0, T1, T2, T3, T4, T5, T6);
170impl_as_packed_callable!(8; T0, T1, T2, T3, T4, T5, T6, T7);
171
172pub trait PackedCallArg {
176 type Holder;
178 fn into_packed_arg(self) -> Self::Holder;
179 fn as_packed_arg(holder: &Self::Holder) -> AnyView<'_>;
180}
181
182crate::impl_into_packed_arg!(Any);
184
185impl PackedCallArg for &str {
186 type Holder = String;
187 #[inline]
188 fn into_packed_arg(self) -> String {
189 String::from(self)
190 }
191 #[inline(always)]
192 fn as_packed_arg(holder: &String) -> AnyView<'_> {
193 AnyView::from(holder)
194 }
195}
196
197impl PackedCallArg for &[u8] {
198 type Holder = Bytes;
199 #[inline]
200 fn into_packed_arg(self) -> Bytes {
201 Bytes::from(self)
202 }
203 #[inline(always)]
204 fn as_packed_arg(holder: &Bytes) -> AnyView<'_> {
205 AnyView::from(holder)
206 }
207}
208
209impl<T: ObjectRefCore> PackedCallArg for RValueRef<T> {
210 type Holder = Self;
211 #[inline(always)]
212 fn into_packed_arg(self) -> Self {
213 self
214 }
215 #[inline(always)]
216 fn as_packed_arg(holder: &Self::Holder) -> AnyView<'_> {
217 AnyView::from(holder)
218 }
219}
220
221crate::impl_into_packed_arg!(impl[T: AnyCompatible] Option<T>);
223crate::impl_into_packed_arg!(impl[T: ContainerElement + Clone] crate::Array<T>);
224crate::impl_into_packed_arg!(impl[K: ContainerElement, V: ContainerElement] crate::Map<K, V>);
225crate::impl_into_packed_arg!(impl[T: ContainerElement] crate::List<T>);
226
227pub trait PackedCallArgs {
229 const LEN: usize;
230 fn with_packed_args<R>(self, f: impl FnOnce(&[AnyView<'_>]) -> R) -> R;
232}
233
234macro_rules! impl_into_packed_args {
235 ($len:literal; $($T:ident),*; $($idx:tt),*) => {
236 impl<$($T: PackedCallArg),*> PackedCallArgs for ($($T,)*) {
237 const LEN: usize = $len;
238 #[inline(always)]
239 fn with_packed_args<R>(self, f: impl FnOnce(&[AnyView<'_>]) -> R) -> R {
240 let _holders = ($(self.$idx.into_packed_arg(),)*);
241 let views: [AnyView<'_>; $len] = [$($T::as_packed_arg(&_holders.$idx)),*];
242 f(&views)
243 }
244 }
245 };
246}
247
248impl_into_packed_args!(0;;);
249impl_into_packed_args!(1; T0; 0);
250impl_into_packed_args!(2; T0, T1; 0, 1);
251impl_into_packed_args!(3; T0, T1, T2; 0, 1, 2);
252impl_into_packed_args!(4; T0, T1, T2, T3; 0, 1, 2, 3);
253impl_into_packed_args!(5; T0, T1, T2, T3, T4; 0, 1, 2, 3, 4);
254impl_into_packed_args!(6; T0, T1, T2, T3, T4, T5; 0, 1, 2, 3, 4, 5);
255impl_into_packed_args!(7; T0, T1, T2, T3, T4, T5, T6; 0, 1, 2, 3, 4, 5, 6);
256impl_into_packed_args!(8; T0, T1, T2, T3, T4, T5, T6, T7; 0, 1, 2, 3, 4, 5, 6, 7);