tvm_ffi/macros.rs
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19// Re-export paste for the export macros, so downstream crates need not depend on it.
20#[doc(hidden)]
21pub use paste;
22
23// ----------------------------------------------------------------------------
24// Macros for error handling
25// ----------------------------------------------------------------------------
26
27/// The path of the enclosing function, as `function_name!()`.
28#[doc(hidden)]
29#[macro_export]
30macro_rules! function_name {
31 () => {{
32 // dummy function to get the name of the function
33 fn f() {}
34 fn type_name_of<T>(_: T) -> &'static str {
35 ::core::any::type_name::<T>()
36 }
37 let name = type_name_of(f);
38 // remove the f() from the name
39 &name[..name.len() - 3]
40 }};
41}
42
43/// Look up a registered global [`Function`](crate::Function) by name once, and
44/// keep it for the process: a `&'static Function`.
45///
46/// Each call site has its own cache, which later calls read without a lock.
47/// Use it for a function that must be registered, such as a built-in one; it
48/// panics, naming the function, if the function is not. See also
49/// [`Function::get_global`](crate::Function::get_global), which returns an
50/// error instead.
51///
52/// # Examples
53///
54/// ```
55/// use tvm_ffi::{cached_global_func, Array};
56///
57/// let array = cached_global_func!("ffi.Array").call_tuple((1_i64, 2_i64))?;
58/// assert_eq!(Array::<i64>::try_from(array)?.len(), 2);
59/// # Ok::<(), tvm_ffi::Error>(())
60/// ```
61#[macro_export]
62macro_rules! cached_global_func {
63 ($name:literal) => {{
64 static FUNC: $crate::extra::cold_init_lazy_lock::ColdInitLazyLock<
65 $crate::function::Function,
66 > = $crate::extra::cold_init_lazy_lock::ColdInitLazyLock::new(|| {
67 $crate::function::Function::get_global($name).unwrap_or_else(|_| {
68 ::core::panic!(::core::concat!(
69 "global function `",
70 $name,
71 "` is not registered"
72 ))
73 })
74 });
75 &*FUNC
76 }};
77}
78
79/// Resolve a reflected field of the object type `N` once, and keep its getter
80/// for the process: a `&'static FieldGetter<N>`.
81///
82/// Each call site has its own cache, which later calls read without a lock.
83/// `N` must be a concrete type, not `Self` or a generic parameter. It panics,
84/// naming the field, if `N` has no such field. See also
85/// [`FieldGetter::of`](crate::reflection::FieldGetter::of), which returns an
86/// error instead.
87///
88/// # Examples
89///
90/// ```standalone_crate
91/// use tvm_ffi::{cached_field_getter, rs_object, Object, ObjectArc};
92///
93/// #[rs_object(type_key = "my_ext.Point")]
94/// pub struct PointObj {
95/// base_: Object,
96/// x: i64,
97/// }
98///
99/// let point = ObjectArc::new(PointObj { base_: Object::new(), x: 3 });
100/// let x: i64 = cached_field_getter!(PointObj, "x").get(&*point)?;
101/// assert_eq!(x, 3);
102/// # Ok::<(), tvm_ffi::Error>(())
103/// ```
104#[macro_export]
105macro_rules! cached_field_getter {
106 ($owner:ty, $name:literal) => {{
107 static GETTER: $crate::extra::cold_init_lazy_lock::ColdInitLazyLock<
108 $crate::reflection::FieldGetter<$owner>,
109 > = $crate::extra::cold_init_lazy_lock::ColdInitLazyLock::new(|| {
110 $crate::reflection::FieldGetter::of::<$owner>($name).unwrap_or_else(|_| {
111 ::core::panic!(::core::concat!(
112 "`",
113 ::core::stringify!($owner),
114 "` has no reflected field `",
115 $name,
116 "`"
117 ))
118 })
119 });
120 &*GETTER
121 }};
122}
123
124/// Turn the return code of a safe call into a `Result`, taking the raised
125/// error when it is nonzero: `check_safe_call!(function(args))?`.
126#[doc(hidden)]
127#[macro_export]
128macro_rules! check_safe_call {
129 ($expr:expr) => {{
130 let ret_code = $expr;
131 if ret_code == 0 {
132 ::core::result::Result::Ok(())
133 } else {
134 let error = $crate::error::Error::from_raised();
135 ::core::result::Result::Err(error)
136 }
137 }};
138}
139
140/// Make an [`Error`](crate::Error) of a kind with a formatted message,
141/// recording the source location in the backtrace, as [`bail!`](crate::bail)
142/// does without returning.
143///
144/// ```
145/// use tvm_ffi::{format_err, Result, KEY_ERROR};
146///
147/// fn lookup(names: &[&str], name: &str) -> Result<usize> {
148/// names.iter().position(|n| *n == name).ok_or_else(|| format_err!(KEY_ERROR, "no {name}"))
149/// }
150///
151/// assert_eq!(lookup(&["a"], "b").unwrap_err().to_string(), "KeyError: no b");
152/// ```
153#[macro_export]
154macro_rules! format_err {
155 ($error_kind:expr, $fmt:expr $(, $args:expr)* $(,)?) => {{
156 let context = ::std::format!(
157 " File \"{}\", line {}, in {}\n",
158 ::core::file!(),
159 ::core::line!(),
160 $crate::function_name!()
161 );
162 $crate::error::Error::new($error_kind, &::std::format!($fmt $(, $args)*))
163 .with_backtrace(&context)
164 }};
165}
166
167/// Return an [`Error`](crate::Error) of a kind with a formatted message from
168/// the current function.
169///
170/// `bail!(kind, fmt, args...)` formats the message as `format!` does and
171/// records the source location in the backtrace.
172///
173/// # Arguments
174///
175/// * `kind` - The kind of the error, such as [`VALUE_ERROR`](crate::VALUE_ERROR).
176/// * `fmt` - The format string of the message.
177/// * `args` - The format arguments.
178///
179/// # Returns
180///
181/// Returns `Err` of the error from the enclosing function.
182///
183/// # Examples
184///
185/// ```
186/// use tvm_ffi::{bail, Result, INDEX_ERROR};
187///
188/// fn get(items: &[i64], index: usize) -> Result<i64> {
189/// if index >= items.len() {
190/// bail!(INDEX_ERROR, "index {} out of range for length {}", index, items.len());
191/// }
192/// Ok(items[index])
193/// }
194///
195/// assert_eq!(get(&[1, 2], 1)?, 2);
196/// assert_eq!(get(&[1, 2], 5).unwrap_err().message(), "index 5 out of range for length 2");
197/// # Ok::<(), tvm_ffi::Error>(())
198/// ```
199#[macro_export]
200macro_rules! bail {
201 ($error_kind:expr, $fmt:expr $(, $args:expr)* $(,)?) => {{
202 return ::core::result::Result::Err($crate::format_err!($error_kind, $fmt $(, $args)*));
203 }};
204}
205
206/// Return an [`Error`](crate::Error) from the current function unless a
207/// condition holds.
208///
209/// `ensure!(cond, kind, fmt, args...)` is [`bail!`](crate::bail)`(kind, fmt,
210/// args...)` when `cond` is false.
211///
212/// # Arguments
213///
214/// * `cond` - The condition that must hold.
215/// * `kind` - The kind of the error.
216/// * `fmt` - The format string of the message.
217/// * `args` - The format arguments.
218///
219/// # Returns
220///
221/// Returns `Err` of the error from the enclosing function when `cond` is
222/// false, and does nothing otherwise.
223///
224/// # Examples
225///
226/// ```
227/// use tvm_ffi::{ensure, Result, VALUE_ERROR};
228///
229/// fn sqrt(x: f64) -> Result<f64> {
230/// ensure!(x >= 0.0, VALUE_ERROR, "sqrt of negative number {}", x);
231/// Ok(x.sqrt())
232/// }
233///
234/// assert_eq!(sqrt(4.0)?, 2.0);
235/// assert!(sqrt(-1.0).is_err());
236/// # Ok::<(), tvm_ffi::Error>(())
237/// ```
238#[macro_export]
239macro_rules! ensure {
240 ($cond:expr, $error_kind:expr, $fmt:expr $(, $args:expr)* $(,)?) => {{
241 if !$cond {
242 $crate::bail!($error_kind, $fmt $(, $args)*);
243 }
244 }};
245}
246
247/// Append the current source location to the backtrace of an `Err` result,
248/// and pass an `Ok` through.
249///
250/// # Arguments
251///
252/// * `result` - The result to attach the context to.
253///
254/// # Returns
255///
256/// The result, with the location appended to an error's backtrace.
257///
258/// # Examples
259///
260/// ```
261/// use tvm_ffi::{attach_context, bail, Result, RUNTIME_ERROR};
262///
263/// fn inner() -> Result<()> {
264/// bail!(RUNTIME_ERROR, "failed");
265/// }
266///
267/// fn outer() -> Result<()> {
268/// attach_context!(inner())
269/// }
270///
271/// assert!(outer().unwrap_err().backtrace().contains("outer"));
272/// ```
273#[macro_export]
274macro_rules! attach_context {
275 ($error:expr) => {{
276 match $error {
277 ::core::result::Result::Ok(value) => ::core::result::Result::Ok(value),
278 ::core::result::Result::Err(error) => {
279 let context = ::std::format!(
280 " File \"{}\", line {}, in {}\n",
281 ::core::file!(),
282 ::core::line!(),
283 $crate::function_name!()
284 );
285 ::core::result::Result::Err($crate::error::Error::with_appended_backtrace(
286 error, &context,
287 ))
288 }
289 }
290 }};
291}
292
293// ----------------------------------------------------------------------------
294// Macros for object references
295// ----------------------------------------------------------------------------
296
297/// Implement zero-copy conversions from a derived object reference to one of
298/// its base object-reference types: `From<Source>` and `From<&Source>` into
299/// `Target`, `AsRef<Target>`, which borrows a `&Source` as `&Target`
300/// without touching the reference count, and
301/// [`IntoArg<Target>`](crate::IntoArg) for `Source` and `&Source`,
302/// and [`TypeSubsumes<Source>`](crate::type_traits::TypeSubsumes) for `Target`, so
303/// [`Array::upcast`](crate::Array::upcast) turns an `Array<Source>` into an
304/// `Array<Target>`. It also implements the strict downcast back, `TryFrom<Target>` and
305/// `TryFrom<&Target>` for `Source`, which return a `TypeError` naming both types.
306///
307/// `impl_object_ref_upcast!(Add => BinaryOp, Add => Expr);` checks at compile
308/// time that the object type of `Source` derives from that of `Target`
309/// ([`ObjectDerivesFrom`](crate::object::ObjectDerivesFrom)), and that `Target`
310/// accepts every object of its type, as a non-generic
311/// [`#[derive(ObjectRef)]`](crate::derive::ObjectRef) reference does.
312///
313/// # Safety
314///
315/// For a `Target` that promises more than its object type, such as a generic
316/// reference or one with a custom
317/// [`ObjectRefAnyCompatible`](crate::object::ObjectRefAnyCompatible), write
318/// `impl_object_ref_upcast!(unsafe Add => PrimExpr);`. The leading `unsafe`
319/// skips both checks: writing it, the caller promises that `Target` is a base
320/// of `Source` and every `Source` satisfies the `Target` invariants. An
321/// incorrect declaration makes the generated safe conversions unsound.
322#[macro_export]
323macro_rules! impl_object_ref_upcast {
324 (unsafe $($source:ty => $target:ty),+ $(,)?) => {
325 $(
326 impl ::std::convert::From<$source> for $target {
327 #[inline]
328 fn from(value: $source) -> Self {
329 let data = <$source as $crate::object::ObjectRefCore>::into_data(value);
330 // SAFETY: The macro declaration promises that `target` is
331 // a registered base of `source`. Both references retain
332 // the same allocation and only change its static view.
333 let data = unsafe {
334 $crate::object::ObjectArc::from_raw(
335 $crate::object::ObjectArc::into_raw(data).cast::
336 <<$target as $crate::object::ObjectRefCore>::ContainerType>(),
337 )
338 };
339 // SAFETY: The macro declaration promises both the
340 // container inheritance relation and every additional
341 // invariant imposed by the target reference view.
342 unsafe {
343 <$target as $crate::object::ObjectRefCore>::from_data(data)
344 }
345 }
346 }
347
348 impl ::std::convert::From<&$source> for $target {
349 #[inline]
350 fn from(value: &$source) -> Self {
351 ::core::convert::Into::into(::core::clone::Clone::clone(value))
352 }
353 }
354
355 // SAFETY: the declaration promises every `source` is a valid
356 // `target`, and an object reference never changes its object.
357 unsafe impl $crate::type_traits::TypeSubsumes<$source> for $target {}
358
359 impl $crate::IntoArg<$target> for $source {
360 type Output = $target;
361 #[inline(always)]
362 fn into_arg(self) -> $target {
363 ::core::convert::Into::into(self)
364 }
365 #[inline(always)]
366 fn into_owned(self) -> $target {
367 ::core::convert::Into::into(self)
368 }
369 }
370
371 impl<'a> $crate::IntoArg<$target> for &'a $source {
372 type Output = &'a $target;
373 #[inline(always)]
374 fn into_arg(self) -> &'a $target {
375 ::core::convert::AsRef::<$target>::as_ref(self)
376 }
377 #[inline(always)]
378 fn into_owned(self) -> $target {
379 ::core::convert::Into::into(self)
380 }
381 }
382
383 impl ::core::convert::AsRef<$target> for $source {
384 #[inline(always)]
385 fn as_ref(&self) -> &$target {
386 const _: () = ::core::assert!(
387 ::core::mem::size_of::<$source>() == ::core::mem::size_of::<$target>()
388 && ::core::mem::align_of::<$source>()
389 == ::core::mem::align_of::<$target>(),
390 "an object reference upcast must keep the reference's layout"
391 );
392 // SAFETY: both references are exactly one object pointer, and the
393 // macro declaration promises that every `source` object is a valid
394 // `target`, so a `&source` is a valid `&target`.
395 unsafe { &*(self as *const $source as *const $target) }
396 }
397 }
398
399 // The strict downcast back, as a `TryFrom` for `?`: a reference
400 // never converts, so this only checks the object's runtime type.
401 impl ::core::convert::TryFrom<$target> for $source {
402 type Error = $crate::error::Error;
403 #[inline]
404 fn try_from(value: $target) -> ::core::result::Result<Self, Self::Error> {
405 $crate::object::ObjectRefCore::downcast::<$source>(value)
406 .map_err($crate::error::Error::downcast_failed::<$source>)
407 }
408 }
409
410 impl ::core::convert::TryFrom<&$target> for $source {
411 type Error = $crate::error::Error;
412 #[inline]
413 fn try_from(value: &$target) -> ::core::result::Result<Self, Self::Error> {
414 match $crate::object::ObjectRefCore::downcast_ref::<$source>(value) {
415 ::core::option::Option::Some(found) => {
416 ::core::result::Result::Ok(::core::clone::Clone::clone(found))
417 }
418 ::core::option::Option::None => ::core::result::Result::Err(
419 $crate::error::Error::downcast_failed::<$source>(
420 ::core::clone::Clone::clone(value),
421 ),
422 ),
423 }
424 }
425 }
426 )+
427 };
428 ($($source:ty => $target:ty),+ $(,)?) => {
429 $(
430 const _: () = {
431 fn derives_from<T: $crate::object::ObjectDerivesFrom<A, I>, A, I>() {}
432 fn plain<P: $crate::object::PlainObjectRef>() {}
433 let _ = derives_from::<
434 <$source as $crate::object::ObjectRefCore>::ContainerType,
435 <$target as $crate::object::ObjectRefCore>::ContainerType,
436 _,
437 >;
438 let _ = plain::<$target>;
439 };
440 )+
441 $crate::impl_object_ref_upcast!(unsafe $($source => $target),+);
442 };
443}
444
445/// Implement the in-place `downcast_ref` borrows (`array[i]`, `Any::downcast_ref`,
446/// [`ObjectRefCore::downcast_ref`](crate::ObjectRefCore::downcast_ref)) for each
447/// listed object reference type. [`#[derive(ObjectRef)]`](crate::derive::ObjectRef)
448/// emits it; a reference that implements `ObjectRefCore` by hand calls it.
449///
450/// # Safety
451///
452/// The leading `unsafe` is a required marker: writing it, the caller promises
453/// that each type is `repr(transparent)` over one object pointer, and its
454/// [`AnyCompatible::check_any_strict`](crate::AnyCompatible::check_any_strict)
455/// accepts exactly the objects that are a valid value of it.
456///
457/// # Examples
458///
459/// ```standalone_crate
460/// use tvm_ffi::derive::ObjectRef;
461/// use tvm_ffi::{rs_object, impl_object_ref_downcast_ref, Any};
462/// use tvm_ffi::{Object, ObjectArc, ObjectRefCore};
463/// use tvm_ffi::object::ObjectRefAnyCompatible;
464///
465/// #[rs_object(type_key = "my_ext.MyPair", final)]
466/// pub struct MyPairObj {
467/// base_: Object,
468/// pub first: i64,
469/// pub second: i64,
470/// }
471///
472/// #[derive(Clone, ObjectRef)]
473/// pub struct MyPair {
474/// data: ObjectArc<MyPairObj>,
475/// }
476///
477/// /// A `MyPair` whose `first` is positive.
478/// #[derive(Clone)]
479/// #[repr(transparent)]
480/// pub struct PositivePair(ObjectArc<MyPairObj>);
481///
482/// unsafe impl ObjectRefCore for PositivePair {
483/// type ContainerType = MyPairObj;
484/// fn data(this: &Self) -> &ObjectArc<MyPairObj> {
485/// &this.0
486/// }
487/// fn into_data(this: Self) -> ObjectArc<MyPairObj> {
488/// this.0
489/// }
490/// unsafe fn from_data(data: ObjectArc<MyPairObj>) -> Self {
491/// Self(data)
492/// }
493/// }
494///
495/// unsafe impl ObjectRefAnyCompatible for PositivePair {
496/// fn extra_check(pair: &MyPairObj) -> bool {
497/// pair.first > 0
498/// }
499/// }
500/// impl_object_ref_downcast_ref!(unsafe PositivePair);
501///
502/// let pair = Any::from(MyPair::from_object(MyPairObj::new(Object::new(), 1, 2)));
503/// assert!(pair.downcast_ref::<PositivePair>().is_some());
504/// ```
505#[macro_export]
506macro_rules! impl_object_ref_downcast_ref {
507 (unsafe $($name:ty),+ $(,)?) => {
508 $(
509 // SAFETY: the macro declaration promises that `$name` is one object
510 // pointer whose `check_any_strict` is its type check.
511 unsafe impl $crate::type_traits::RefFromAnyUnchecked for $name {
512 #[inline(always)]
513 unsafe fn ref_from_any_unchecked(
514 cell: &$crate::tvm_ffi_sys::TVMFFIAny,
515 ) -> &Self {
516 const {
517 ::core::assert!(
518 ::core::mem::size_of::<$name>()
519 == ::core::mem::size_of::<*mut $crate::tvm_ffi_sys::TVMFFIObject>()
520 && ::core::mem::align_of::<$name>()
521 == ::core::mem::align_of::<*mut $crate::tvm_ffi_sys::TVMFFIObject>(),
522 "a reference downcast target must be exactly one object pointer"
523 )
524 };
525 unsafe { &*(::core::ptr::addr_of!(cell.data_union) as *const Self) }
526 }
527 }
528
529 unsafe impl $crate::type_traits::DowncastRefFromAny for $name {
530 #[inline(always)]
531 unsafe fn downcast_ref_from_any(
532 cell: &$crate::tvm_ffi_sys::TVMFFIAny,
533 ) -> ::core::option::Option<&Self> {
534 unsafe { $crate::type_traits::downcast_ref_from_any_in_place::<Self>(cell) }
535 }
536 }
537
538 unsafe impl $crate::type_traits::DowncastRefFromObject for $name {
539 #[inline(always)]
540 unsafe fn downcast_ref_from_object(
541 place: &*mut $crate::tvm_ffi_sys::TVMFFIObject,
542 ) -> ::core::option::Option<&Self> {
543 unsafe { $crate::type_traits::downcast_ref_from_object_in_place::<Self>(place) }
544 }
545 }
546 )+
547 };
548}
549
550// ----------------------------------------------------------------------------
551// Macros for any definitions
552// ----------------------------------------------------------------------------
553
554/// Implement the conversions between each listed [`AnyCompatible`](crate::AnyCompatible)
555/// type and FFI values: `TryFrom<AnyView>`, `TryFrom<Any>` and `TryFrom<&Any>`,
556/// and use as an argument of [`Function::call_tuple`](crate::Function::call_tuple)
557/// and of functions from [`into_typed_fn!`](crate::into_typed_fn).
558///
559/// `#[derive(ObjectRef)]` calls it; a type that implements `AnyCompatible` by hand
560/// calls it after that impl. See also
561/// [`impl_object_ref_downcast_ref!`](crate::impl_object_ref_downcast_ref)
562/// for an object reference implemented by hand.
563#[macro_export]
564macro_rules! impl_any_compatible_conversions {
565 ($($t:ty),* $(,)?) => {
566 $crate::impl_try_from_any!($($t),*);
567 $crate::impl_into_arg!($($t),*);
568 $crate::impl_into_packed_arg!($($t),*);
569 };
570}
571
572/// `TryFrom` from FFI values; part of [`impl_any_compatible_conversions!`](crate::impl_any_compatible_conversions).
573#[doc(hidden)]
574#[macro_export]
575macro_rules! impl_try_from_any {
576 ($($t:ty),* $(,)?) => {
577 $(
578 impl<'a> ::core::convert::TryFrom<$crate::any::AnyView<'a>> for $t {
579 type Error = $crate::error::Error;
580 #[inline(always)]
581 fn try_from(
582 value: $crate::any::AnyView<'a>
583 ) -> ::core::result::Result<Self, Self::Error> {
584 type TryFromTemp = $crate::any::TryFromTemp<$t>;
585 return <TryFromTemp as ::core::convert::TryFrom<_>>::try_from(value).map(TryFromTemp::into_value);
586 }
587 }
588
589 impl ::core::convert::TryFrom<$crate::any::Any> for $t {
590 type Error = $crate::error::Error;
591 #[inline(always)]
592 fn try_from(
593 value: $crate::any::Any
594 ) -> ::core::result::Result<Self, Self::Error> {
595 type TryFromTemp = $crate::any::TryFromTemp<$t>;
596 return <TryFromTemp as ::core::convert::TryFrom<_>>::try_from(value).map(TryFromTemp::into_value);
597 }
598 }
599
600 impl<'a> ::core::convert::TryFrom<&'a $crate::any::Any> for $t {
601 type Error = $crate::error::Error;
602 #[inline(always)]
603 fn try_from(
604 value: &'a $crate::any::Any
605 ) -> ::core::result::Result<Self, Self::Error> {
606 type TryFromTemp = $crate::any::TryFromTemp<$t>;
607 return <TryFromTemp as ::core::convert::TryFrom<_>>::try_from(value).map(TryFromTemp::into_value);
608 }
609 }
610 )*
611 };
612}
613
614/// `IntoArg<T>` for `T` and `&T`; part of [`impl_any_compatible_conversions!`](crate::impl_any_compatible_conversions).
615#[doc(hidden)]
616#[macro_export]
617macro_rules! impl_into_arg {
618 ($($t:ty),* $(,)?) => {
619 $($crate::impl_into_arg!(impl[] $t);)*
620 };
621 (impl[$($g:tt)*] $t:ty) => {
622 impl<$($g)*> $crate::IntoArg<$t> for $t {
623 type Output = $t;
624 #[inline(always)]
625 fn into_arg(self) -> $t {
626 self
627 }
628 #[inline(always)]
629 fn into_owned(self) -> $t {
630 self
631 }
632 }
633
634 impl<'a, $($g)*> $crate::IntoArg<$t> for &'a $t {
635 type Output = &'a $t;
636 #[inline(always)]
637 fn into_arg(self) -> &'a $t {
638 self
639 }
640 #[inline(always)]
641 fn into_owned(self) -> $t {
642 ::core::clone::Clone::clone(self)
643 }
644 }
645 };
646}
647
648/// Macro to implement `TryFrom<AnyView>` and `TryFrom<Any>` for generic types like `Option<T>`
649#[doc(hidden)]
650#[macro_export]
651macro_rules! impl_try_from_any_for_parametric {
652 ($generic_type:ident<$param:ident>) => {
653 impl<'a, $param: $crate::type_traits::AnyCompatible>
654 ::core::convert::TryFrom<$crate::any::AnyView<'a>> for $generic_type<$param>
655 {
656 type Error = $crate::error::Error;
657 #[inline(always)]
658 fn try_from(
659 value: $crate::any::AnyView<'a>,
660 ) -> ::core::result::Result<Self, Self::Error> {
661 type TryFromTemp<T> = $crate::any::TryFromTemp<$generic_type<$param>>;
662 return <TryFromTemp<T> as ::core::convert::TryFrom<_>>::try_from(value)
663 .map(TryFromTemp::<T>::into_value);
664 }
665 }
666
667 impl<$param: $crate::type_traits::AnyCompatible> ::core::convert::TryFrom<$crate::any::Any>
668 for $generic_type<$param>
669 {
670 type Error = $crate::error::Error;
671 #[inline(always)]
672 fn try_from(value: $crate::any::Any) -> ::core::result::Result<Self, Self::Error> {
673 type TryFromTemp<T> = $crate::any::TryFromTemp<$generic_type<$param>>;
674 return <TryFromTemp<T> as ::core::convert::TryFrom<_>>::try_from(value)
675 .map(TryFromTemp::<T>::into_value);
676 }
677 }
678
679 impl<'a, $param: $crate::type_traits::AnyCompatible>
680 ::core::convert::TryFrom<&'a $crate::any::Any> for $generic_type<$param>
681 {
682 type Error = $crate::error::Error;
683 #[inline(always)]
684 fn try_from(value: &'a $crate::any::Any) -> ::core::result::Result<Self, Self::Error> {
685 type TryFromTemp<T> = $crate::any::TryFromTemp<$generic_type<$param>>;
686 return <TryFromTemp<T> as ::core::convert::TryFrom<_>>::try_from(value)
687 .map(TryFromTemp::<T>::into_value);
688 }
689 }
690 };
691}
692
693/// Packed-call arguments; part of [`impl_any_compatible_conversions!`](crate::impl_any_compatible_conversions).
694#[doc(hidden)]
695#[macro_export]
696macro_rules! impl_into_packed_arg {
697 ($($t:ty),* $(,)?) => {
698 $($crate::impl_into_packed_arg!(impl[] $t);)*
699 };
700 (impl[$($g:tt)*] $t:ty) => {
701 impl<$($g)*> $crate::function_internal::PackedCallArg for $t {
702 type Holder = $t;
703 #[inline(always)]
704 fn into_packed_arg(self) -> $t {
705 self
706 }
707 #[inline(always)]
708 fn as_packed_arg(holder: &Self::Holder) -> $crate::any::AnyView<'_> {
709 $crate::any::AnyView::from(holder)
710 }
711 }
712
713 impl<'a, $($g)*> $crate::function_internal::PackedCallArg for &'a $t {
714 type Holder = &'a $t;
715 #[inline(always)]
716 fn into_packed_arg(self) -> &'a $t {
717 self
718 }
719 #[inline(always)]
720 fn as_packed_arg(holder: &Self::Holder) -> $crate::any::AnyView<'_> {
721 $crate::any::AnyView::from(*holder)
722 }
723 }
724 };
725}
726
727// ----------------------------------------------------------------------------
728// Macros for function definitions
729// ----------------------------------------------------------------------------
730
731/// Macro to export a typed function as a C symbol that follows the tvm-ffi ABI
732///
733/// An error the function returns is raised to the caller. Report errors by
734/// returning them; a panic is also caught and raised, as an `InternalError`,
735/// since unwinding into the caller would abort the process, but panicking
736/// is discouraged.
737///
738/// With the `export-metadata` feature, the counterpart of C++
739/// `TVM_FFI_DLL_EXPORT_INCLUDE_METADATA`, the macro also exports the
740/// function's metadata, `{"type_schema":...}`, as `__tvm_ffi__metadata_<name>`,
741/// which [`Module::get_function_metadata`](crate::Module::get_function_metadata)
742/// and the stub generator read. A
743/// function's schema lists its parameter and return types; a callable whose
744/// signature is not known, such as a custom `AsPackedCallable`, has the
745/// schema of an untyped function. The feature is off by default, so exports
746/// are minimal.
747///
748/// # Arguments
749/// * `$name` - The name of the function
750/// * `$func` - The function to export
751///
752/// # Example
753/// ```rust,standalone_crate
754/// use tvm_ffi::*;
755///
756/// fn add_one(x: i32) -> Result<i32> { Ok(x + 1) }
757///
758/// tvm_ffi_dll_export_typed_func!(add_one, add_one);
759/// ```
760#[macro_export]
761macro_rules! tvm_ffi_dll_export_typed_func {
762 ($name:ident, $func:expr) => {
763 $crate::macros::paste::paste! {
764 // `no_mangle` keeps the symbol in a `cdylib` under the
765 // `__tvm_ffi_<name>` name that `Module` looks up.
766 //
767 // The path-qualified `$crate::tvm_ffi_sys::…` reference (rather
768 // than a bare `tvm_ffi_sys::…`) lets downstream crates use the
769 // macro without having to add `tvm-ffi-sys` to their own
770 // `[dependencies]`.
771 #[unsafe(no_mangle)]
772 pub unsafe extern "C" fn [<__tvm_ffi_ $name>](
773 _handle: *mut ::core::ffi::c_void,
774 args: *const $crate::tvm_ffi_sys::TVMFFIAny,
775 num_args: i32,
776 result: *mut $crate::tvm_ffi_sys::TVMFFIAny,
777 ) -> i32 {
778 let packed_args = $crate::function_internal::packed_args(args, num_args);
779 let ret_value = match ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| {
780 $crate::function_internal::call_packed_callable($func, packed_args)
781 })) {
782 ::core::result::Result::Ok(ret_value) => ret_value,
783 ::core::result::Result::Err(payload) => ::core::result::Result::Err($crate::error::Error::from_panic(payload)),
784 };
785 match ret_value {
786 ::core::result::Result::Ok(value) => {
787 *result = $crate::any::Any::into_raw_ffi_any(value);
788 0
789 }
790 ::core::result::Result::Err(error) => {
791 $crate::error::Error::set_raised(&error);
792 -1
793 }
794 }
795 }
796 }
797 $crate::__tvm_ffi_dll_export_metadata!($name, $func);
798 };
799}
800
801/// Macro to export the doc string of a function exported with
802/// [`tvm_ffi_dll_export_typed_func!`], as C++ `TVM_FFI_DLL_EXPORT_TYPED_FUNC_DOC`
803/// does
804///
805/// With the `export-metadata` feature, the doc string is exported as
806/// `__tvm_ffi__doc_<name>`, which
807/// [`Module::get_function_doc`](crate::Module::get_function_doc) and the stub
808/// generator read. Without it, the macro exports nothing, but
809/// still checks that the doc string is a string constant. The macro never
810/// exports the function itself.
811///
812/// # Arguments
813/// * `$name` - The name the function is exported as
814/// * `$doc` - The doc string, a string literal
815///
816/// # Example
817/// ```rust,standalone_crate
818/// use tvm_ffi::*;
819///
820/// fn add(a: i64, b: i64) -> Result<i64> { Ok(a + b) }
821///
822/// tvm_ffi_dll_export_typed_func!(add, add);
823/// tvm_ffi_dll_export_typed_func_doc!(add, "Add two integers and return the sum.");
824/// ```
825#[macro_export]
826macro_rules! tvm_ffi_dll_export_typed_func_doc {
827 ($name:ident, $doc:expr) => {
828 $crate::__tvm_ffi_dll_export_doc!($name, $doc);
829 };
830}
831
832// The metadata and doc getters the export macros emit with the
833// `export-metadata` feature. A `#[cfg]` in a `macro_rules!` expansion would
834// test the features of the crate that invokes the macro, so the feature
835// selects which definition of these helpers this crate compiles instead.
836
837#[cfg(feature = "export-metadata")]
838#[doc(hidden)]
839#[macro_export]
840macro_rules! __tvm_ffi_dll_export_metadata {
841 ($name:ident, $func:expr) => {
842 $crate::macros::paste::paste! {
843 #[unsafe(no_mangle)]
844 pub unsafe extern "C" fn [<__tvm_ffi__metadata_ $name>](
845 _handle: *mut ::core::ffi::c_void,
846 _args: *const $crate::tvm_ffi_sys::TVMFFIAny,
847 _num_args: i32,
848 result: *mut $crate::tvm_ffi_sys::TVMFFIAny,
849 ) -> i32 {
850 let metadata = match ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| {
851 $crate::function_internal::exported_metadata(&$func)
852 })) {
853 ::core::result::Result::Ok(metadata) => metadata,
854 ::core::result::Result::Err(payload) => ::core::result::Result::Err($crate::error::Error::from_panic(payload)),
855 };
856 $crate::function_internal::write_exported_str(metadata, result)
857 }
858 }
859 };
860}
861
862#[cfg(not(feature = "export-metadata"))]
863#[doc(hidden)]
864#[macro_export]
865macro_rules! __tvm_ffi_dll_export_metadata {
866 ($name:ident, $func:expr) => {};
867}
868
869#[cfg(feature = "export-metadata")]
870#[doc(hidden)]
871#[macro_export]
872macro_rules! __tvm_ffi_dll_export_doc {
873 ($name:ident, $doc:expr) => {
874 $crate::macros::paste::paste! {
875 #[unsafe(no_mangle)]
876 pub unsafe extern "C" fn [<__tvm_ffi__doc_ $name>](
877 _handle: *mut ::core::ffi::c_void,
878 _args: *const $crate::tvm_ffi_sys::TVMFFIAny,
879 _num_args: i32,
880 result: *mut $crate::tvm_ffi_sys::TVMFFIAny,
881 ) -> i32 {
882 const DOC: &str = $doc;
883 $crate::function_internal::write_exported_str(::core::result::Result::Ok(::std::string::ToString::to_string(DOC)), result)
884 }
885 }
886 };
887}
888
889#[cfg(not(feature = "export-metadata"))]
890#[doc(hidden)]
891#[macro_export]
892macro_rules! __tvm_ffi_dll_export_doc {
893 ($name:ident, $doc:expr) => {
894 const _: &str = $doc;
895 };
896}
897
898/// Wrap a [`Function`](crate::Function) as a typed closure with the given
899/// signature: `into_typed_fn!(func, Fn(A, B) -> Result<R>)`.
900///
901/// The closure converts its arguments and the result, and checks the argument
902/// count at compile time; it takes 0 to 8 arguments. An argument may be taken
903/// by value or by reference; prefer a reference for an object reference such as
904/// a `Tensor`, which the caller then keeps.
905///
906/// # Examples
907///
908/// ```
909/// use tvm_ffi::*;
910///
911/// let func = Function::from_typed(|x: i32, y: i32| -> Result<i32> { Ok(x + y) });
912/// let add = into_typed_fn!(func, Fn(i32, &i32) -> Result<i32>);
913/// assert_eq!(add(10, &20)?, 30);
914/// # Ok::<(), tvm_ffi::Error>(())
915/// ```
916#[macro_export]
917macro_rules! into_typed_fn {
918 // Case for 0 arguments
919 ($f:expr, Fn() -> $ret_ty:ty) => {{
920 let _f = $f;
921 move || -> $ret_ty {
922 ::core::convert::TryInto::try_into(_f.call_tuple(())?)
923 .map_err(::core::convert::Into::into)
924 }
925 }};
926 // Case for 1 argument
927 ($f:expr, Fn($t0:ty) -> $ret_ty:ty) => {{
928 let _f = $f;
929 move |a0: $t0| -> $ret_ty {
930 ::core::convert::TryInto::try_into(_f.call_tuple((a0,))?)
931 .map_err(::core::convert::Into::into)
932 }
933 }};
934 // Case for 2 arguments
935 ($f:expr, Fn($t0:ty, $t1:ty) -> $ret_ty:ty) => {{
936 let _f = $f;
937 move |a0: $t0, a1: $t1| -> $ret_ty {
938 ::core::convert::TryInto::try_into(_f.call_tuple((a0, a1))?)
939 .map_err(::core::convert::Into::into)
940 }
941 }};
942 // Case for 3 arguments
943 ($f:expr, Fn($t0:ty, $t1:ty, $t2:ty) -> $ret_ty:ty) => {{
944 let _f = $f;
945 move |a0: $t0, a1: $t1, a2: $t2| -> $ret_ty {
946 ::core::convert::TryInto::try_into(_f.call_tuple((a0, a1, a2))?)
947 .map_err(::core::convert::Into::into)
948 }
949 }};
950 // Case for 4 arguments
951 ($f:expr, Fn($t0:ty, $t1:ty, $t2:ty, $t3:ty) -> $ret_ty:ty) => {{
952 let _f = $f;
953 move |a0: $t0, a1: $t1, a2: $t2, a3: $t3| -> $ret_ty {
954 ::core::convert::TryInto::try_into(_f.call_tuple((a0, a1, a2, a3))?)
955 .map_err(::core::convert::Into::into)
956 }
957 }};
958 // Case for 5 arguments
959 ($f:expr, Fn($t0:ty, $t1:ty, $t2:ty, $t3:ty, $t4:ty) -> $ret_ty:ty) => {{
960 let _f = $f;
961 move |a0: $t0, a1: $t1, a2: $t2, a3: $t3, a4: $t4| -> $ret_ty {
962 ::core::convert::TryInto::try_into(_f.call_tuple((a0, a1, a2, a3, a4))?)
963 .map_err(::core::convert::Into::into)
964 }
965 }};
966 // Case for 6 arguments
967 ($f:expr, Fn($t0:ty, $t1:ty, $t2:ty, $t3:ty, $t4:ty, $t5:ty) -> $ret_ty:ty) => {{
968 let _f = $f;
969 move |a0: $t0, a1: $t1, a2: $t2, a3: $t3, a4: $t4, a5: $t5| -> $ret_ty {
970 ::core::convert::TryInto::try_into(_f.call_tuple((a0, a1, a2, a3, a4, a5))?)
971 .map_err(::core::convert::Into::into)
972 }
973 }};
974 // Case for 7 arguments
975 ($f:expr, Fn($t0:ty, $t1:ty, $t2:ty, $t3:ty, $t4:ty, $t5:ty, $t6:ty)
976 -> $ret_ty:ty) => {{
977 let _f = $f;
978 move |a0: $t0, a1: $t1, a2: $t2, a3: $t3, a4: $t4, a5: $t5, a6: $t6| -> $ret_ty {
979 ::core::convert::TryInto::try_into(_f.call_tuple((a0, a1, a2, a3, a4, a5, a6))?)
980 .map_err(::core::convert::Into::into)
981 }
982 }};
983 // Case for 8 arguments
984 ($f:expr, Fn($t0:ty, $t1:ty, $t2:ty, $t3:ty, $t4:ty, $t5:ty, $t6:ty, $t7:ty)
985 -> $ret_ty:ty) => {{
986 let _f = $f;
987 move |a0: $t0, a1: $t1, a2: $t2, a3: $t3, a4: $t4, a5: $t5, a6: $t6, a7: $t7| -> $ret_ty {
988 ::core::convert::TryInto::try_into(_f.call_tuple((a0, a1, a2, a3, a4, a5, a6, a7))?)
989 .map_err(::core::convert::Into::into)
990 }
991 }};
992 ($f:expr, $($signature:tt)*) => {
993 ::core::compile_error!(::core::concat!(
994 "expected `Fn(A, ...) -> R` with 0 to 8 arguments, ",
995 "as in `into_typed_fn!(func, Fn(i32) -> Result<i32>)`"
996 ))
997 };
998}