tvm-ffi 0.1.16

tvm-ffi rust support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
// Re-export paste for the export macros, so downstream crates need not depend on it.
#[doc(hidden)]
pub use paste;

// ----------------------------------------------------------------------------
// Macros for error handling
// ----------------------------------------------------------------------------

/// The path of the enclosing function, as `function_name!()`.
#[doc(hidden)]
#[macro_export]
macro_rules! function_name {
    () => {{
        // dummy function to get the name of the function
        fn f() {}
        fn type_name_of<T>(_: T) -> &'static str {
            ::core::any::type_name::<T>()
        }
        let name = type_name_of(f);
        // remove the f() from the name
        &name[..name.len() - 3]
    }};
}

/// Look up a registered global [`Function`](crate::Function) by name once, and
/// keep it for the process: a `&'static Function`.
///
/// Each call site has its own cache, which later calls read without a lock.
/// Use it for a function that must be registered, such as a built-in one; it
/// panics, naming the function, if the function is not. See also
/// [`Function::get_global`](crate::Function::get_global), which returns an
/// error instead.
///
/// # Examples
///
/// ```
/// use tvm_ffi::{cached_global_func, Array};
///
/// let array = cached_global_func!("ffi.Array").call_tuple((1_i64, 2_i64))?;
/// assert_eq!(Array::<i64>::try_from(array)?.len(), 2);
/// # Ok::<(), tvm_ffi::Error>(())
/// ```
#[macro_export]
macro_rules! cached_global_func {
    ($name:literal) => {{
        static FUNC: $crate::extra::cold_init_lazy_lock::ColdInitLazyLock<
            $crate::function::Function,
        > = $crate::extra::cold_init_lazy_lock::ColdInitLazyLock::new(|| {
            $crate::function::Function::get_global($name).unwrap_or_else(|_| {
                ::core::panic!(::core::concat!(
                    "global function `",
                    $name,
                    "` is not registered"
                ))
            })
        });
        &*FUNC
    }};
}

/// Resolve a reflected field of the object type `N` once, and keep its getter
/// for the process: a `&'static FieldGetter<N>`.
///
/// Each call site has its own cache, which later calls read without a lock.
/// `N` must be a concrete type, not `Self` or a generic parameter. It panics,
/// naming the field, if `N` has no such field. See also
/// [`FieldGetter::of`](crate::reflection::FieldGetter::of), which returns an
/// error instead.
///
/// # Examples
///
/// ```standalone_crate
/// use tvm_ffi::{cached_field_getter, rs_object, Object, ObjectArc};
///
/// #[rs_object(type_key = "my_ext.Point")]
/// pub struct PointObj {
///     base_: Object,
///     x: i64,
/// }
///
/// let point = ObjectArc::new(PointObj { base_: Object::new(), x: 3 });
/// let x: i64 = cached_field_getter!(PointObj, "x").get(&*point)?;
/// assert_eq!(x, 3);
/// # Ok::<(), tvm_ffi::Error>(())
/// ```
#[macro_export]
macro_rules! cached_field_getter {
    ($owner:ty, $name:literal) => {{
        static GETTER: $crate::extra::cold_init_lazy_lock::ColdInitLazyLock<
            $crate::reflection::FieldGetter<$owner>,
        > = $crate::extra::cold_init_lazy_lock::ColdInitLazyLock::new(|| {
            $crate::reflection::FieldGetter::of::<$owner>($name).unwrap_or_else(|_| {
                ::core::panic!(::core::concat!(
                    "`",
                    ::core::stringify!($owner),
                    "` has no reflected field `",
                    $name,
                    "`"
                ))
            })
        });
        &*GETTER
    }};
}

/// Turn the return code of a safe call into a `Result`, taking the raised
/// error when it is nonzero: `check_safe_call!(function(args))?`.
#[doc(hidden)]
#[macro_export]
macro_rules! check_safe_call {
    ($expr:expr) => {{
        let ret_code = $expr;
        if ret_code == 0 {
            ::core::result::Result::Ok(())
        } else {
            let error = $crate::error::Error::from_raised();
            ::core::result::Result::Err(error)
        }
    }};
}

/// Make an [`Error`](crate::Error) of a kind with a formatted message,
/// recording the source location in the backtrace, as [`bail!`](crate::bail)
/// does without returning.
///
/// ```
/// use tvm_ffi::{format_err, Result, KEY_ERROR};
///
/// fn lookup(names: &[&str], name: &str) -> Result<usize> {
///     names.iter().position(|n| *n == name).ok_or_else(|| format_err!(KEY_ERROR, "no {name}"))
/// }
///
/// assert_eq!(lookup(&["a"], "b").unwrap_err().to_string(), "KeyError: no b");
/// ```
#[macro_export]
macro_rules! format_err {
    ($error_kind:expr, $fmt:expr $(, $args:expr)* $(,)?) => {{
        let context = ::std::format!(
            "  File \"{}\", line {}, in {}\n",
            ::core::file!(),
            ::core::line!(),
            $crate::function_name!()
        );
        $crate::error::Error::new($error_kind, &::std::format!($fmt $(, $args)*))
            .with_backtrace(&context)
    }};
}

/// Return an [`Error`](crate::Error) of a kind with a formatted message from
/// the current function.
///
/// `bail!(kind, fmt, args...)` formats the message as `format!` does and
/// records the source location in the backtrace.
///
/// # Arguments
///
/// * `kind` - The kind of the error, such as [`VALUE_ERROR`](crate::VALUE_ERROR).
/// * `fmt` - The format string of the message.
/// * `args` - The format arguments.
///
/// # Returns
///
/// Returns `Err` of the error from the enclosing function.
///
/// # Examples
///
/// ```
/// use tvm_ffi::{bail, Result, INDEX_ERROR};
///
/// fn get(items: &[i64], index: usize) -> Result<i64> {
///     if index >= items.len() {
///         bail!(INDEX_ERROR, "index {} out of range for length {}", index, items.len());
///     }
///     Ok(items[index])
/// }
///
/// assert_eq!(get(&[1, 2], 1)?, 2);
/// assert_eq!(get(&[1, 2], 5).unwrap_err().message(), "index 5 out of range for length 2");
/// # Ok::<(), tvm_ffi::Error>(())
/// ```
#[macro_export]
macro_rules! bail {
    ($error_kind:expr, $fmt:expr $(, $args:expr)* $(,)?) => {{
        return ::core::result::Result::Err($crate::format_err!($error_kind, $fmt $(, $args)*));
    }};
}

/// Return an [`Error`](crate::Error) from the current function unless a
/// condition holds.
///
/// `ensure!(cond, kind, fmt, args...)` is [`bail!`](crate::bail)`(kind, fmt,
/// args...)` when `cond` is false.
///
/// # Arguments
///
/// * `cond` - The condition that must hold.
/// * `kind` - The kind of the error.
/// * `fmt` - The format string of the message.
/// * `args` - The format arguments.
///
/// # Returns
///
/// Returns `Err` of the error from the enclosing function when `cond` is
/// false, and does nothing otherwise.
///
/// # Examples
///
/// ```
/// use tvm_ffi::{ensure, Result, VALUE_ERROR};
///
/// fn sqrt(x: f64) -> Result<f64> {
///     ensure!(x >= 0.0, VALUE_ERROR, "sqrt of negative number {}", x);
///     Ok(x.sqrt())
/// }
///
/// assert_eq!(sqrt(4.0)?, 2.0);
/// assert!(sqrt(-1.0).is_err());
/// # Ok::<(), tvm_ffi::Error>(())
/// ```
#[macro_export]
macro_rules! ensure {
    ($cond:expr, $error_kind:expr, $fmt:expr $(, $args:expr)* $(,)?) => {{
        if !$cond {
            $crate::bail!($error_kind, $fmt $(, $args)*);
        }
    }};
}

/// Append the current source location to the backtrace of an `Err` result,
/// and pass an `Ok` through.
///
/// # Arguments
///
/// * `result` - The result to attach the context to.
///
/// # Returns
///
/// The result, with the location appended to an error's backtrace.
///
/// # Examples
///
/// ```
/// use tvm_ffi::{attach_context, bail, Result, RUNTIME_ERROR};
///
/// fn inner() -> Result<()> {
///     bail!(RUNTIME_ERROR, "failed");
/// }
///
/// fn outer() -> Result<()> {
///     attach_context!(inner())
/// }
///
/// assert!(outer().unwrap_err().backtrace().contains("outer"));
/// ```
#[macro_export]
macro_rules! attach_context {
    ($error:expr) => {{
        match $error {
            ::core::result::Result::Ok(value) => ::core::result::Result::Ok(value),
            ::core::result::Result::Err(error) => {
                let context = ::std::format!(
                    "  File \"{}\", line {}, in {}\n",
                    ::core::file!(),
                    ::core::line!(),
                    $crate::function_name!()
                );
                ::core::result::Result::Err($crate::error::Error::with_appended_backtrace(
                    error, &context,
                ))
            }
        }
    }};
}

// ----------------------------------------------------------------------------
// Macros for object references
// ----------------------------------------------------------------------------

/// Implement zero-copy conversions from a derived object reference to one of
/// its base object-reference types: `From<Source>` and `From<&Source>` into
/// `Target`, `AsRef<Target>`, which borrows a `&Source` as `&Target`
/// without touching the reference count, and
/// [`IntoArg<Target>`](crate::IntoArg) for `Source` and `&Source`,
/// and [`TypeSubsumes<Source>`](crate::type_traits::TypeSubsumes) for `Target`, so
/// [`Array::upcast`](crate::Array::upcast) turns an `Array<Source>` into an
/// `Array<Target>`. It also implements the strict downcast back, `TryFrom<Target>` and
/// `TryFrom<&Target>` for `Source`, which return a `TypeError` naming both types.
///
/// `impl_object_ref_upcast!(Add => BinaryOp, Add => Expr);` checks at compile
/// time that the object type of `Source` derives from that of `Target`
/// ([`ObjectDerivesFrom`](crate::object::ObjectDerivesFrom)), and that `Target`
/// accepts every object of its type, as a non-generic
/// [`#[derive(ObjectRef)]`](crate::derive::ObjectRef) reference does.
///
/// # Safety
///
/// For a `Target` that promises more than its object type, such as a generic
/// reference or one with a custom
/// [`ObjectRefAnyCompatible`](crate::object::ObjectRefAnyCompatible), write
/// `impl_object_ref_upcast!(unsafe Add => PrimExpr);`. The leading `unsafe`
/// skips both checks: writing it, the caller promises that `Target` is a base
/// of `Source` and every `Source` satisfies the `Target` invariants. An
/// incorrect declaration makes the generated safe conversions unsound.
#[macro_export]
macro_rules! impl_object_ref_upcast {
    (unsafe $($source:ty => $target:ty),+ $(,)?) => {
        $(
            impl ::std::convert::From<$source> for $target {
                #[inline]
                fn from(value: $source) -> Self {
                    let data = <$source as $crate::object::ObjectRefCore>::into_data(value);
                    // SAFETY: The macro declaration promises that `target` is
                    // a registered base of `source`. Both references retain
                    // the same allocation and only change its static view.
                    let data = unsafe {
                        $crate::object::ObjectArc::from_raw(
                            $crate::object::ObjectArc::into_raw(data).cast::
                                <<$target as $crate::object::ObjectRefCore>::ContainerType>(),
                        )
                    };
                    // SAFETY: The macro declaration promises both the
                    // container inheritance relation and every additional
                    // invariant imposed by the target reference view.
                    unsafe {
                        <$target as $crate::object::ObjectRefCore>::from_data(data)
                    }
                }
            }

            impl ::std::convert::From<&$source> for $target {
                #[inline]
                fn from(value: &$source) -> Self {
                    ::core::convert::Into::into(::core::clone::Clone::clone(value))
                }
            }

            // SAFETY: the declaration promises every `source` is a valid
            // `target`, and an object reference never changes its object.
            unsafe impl $crate::type_traits::TypeSubsumes<$source> for $target {}

            impl $crate::IntoArg<$target> for $source {
                type Output = $target;
                #[inline(always)]
                fn into_arg(self) -> $target {
                    ::core::convert::Into::into(self)
                }
                #[inline(always)]
                fn into_owned(self) -> $target {
                    ::core::convert::Into::into(self)
                }
            }

            impl<'a> $crate::IntoArg<$target> for &'a $source {
                type Output = &'a $target;
                #[inline(always)]
                fn into_arg(self) -> &'a $target {
                    ::core::convert::AsRef::<$target>::as_ref(self)
                }
                #[inline(always)]
                fn into_owned(self) -> $target {
                    ::core::convert::Into::into(self)
                }
            }

            impl ::core::convert::AsRef<$target> for $source {
                #[inline(always)]
                fn as_ref(&self) -> &$target {
                    const _: () = ::core::assert!(
                        ::core::mem::size_of::<$source>() == ::core::mem::size_of::<$target>()
                            && ::core::mem::align_of::<$source>()
                                == ::core::mem::align_of::<$target>(),
                        "an object reference upcast must keep the reference's layout"
                    );
                    // SAFETY: both references are exactly one object pointer, and the
                    // macro declaration promises that every `source` object is a valid
                    // `target`, so a `&source` is a valid `&target`.
                    unsafe { &*(self as *const $source as *const $target) }
                }
            }

            // The strict downcast back, as a `TryFrom` for `?`: a reference
            // never converts, so this only checks the object's runtime type.
            impl ::core::convert::TryFrom<$target> for $source {
                type Error = $crate::error::Error;
                #[inline]
                fn try_from(value: $target) -> ::core::result::Result<Self, Self::Error> {
                    $crate::object::ObjectRefCore::downcast::<$source>(value)
                        .map_err($crate::error::Error::downcast_failed::<$source>)
                }
            }

            impl ::core::convert::TryFrom<&$target> for $source {
                type Error = $crate::error::Error;
                #[inline]
                fn try_from(value: &$target) -> ::core::result::Result<Self, Self::Error> {
                    match $crate::object::ObjectRefCore::downcast_ref::<$source>(value) {
                        ::core::option::Option::Some(found) => {
                            ::core::result::Result::Ok(::core::clone::Clone::clone(found))
                        }
                        ::core::option::Option::None => ::core::result::Result::Err(
                            $crate::error::Error::downcast_failed::<$source>(
                                ::core::clone::Clone::clone(value),
                            ),
                        ),
                    }
                }
            }
        )+
    };
    ($($source:ty => $target:ty),+ $(,)?) => {
        $(
            const _: () = {
                fn derives_from<T: $crate::object::ObjectDerivesFrom<A, I>, A, I>() {}
                fn plain<P: $crate::object::PlainObjectRef>() {}
                let _ = derives_from::<
                    <$source as $crate::object::ObjectRefCore>::ContainerType,
                    <$target as $crate::object::ObjectRefCore>::ContainerType,
                    _,
                >;
                let _ = plain::<$target>;
            };
        )+
        $crate::impl_object_ref_upcast!(unsafe $($source => $target),+);
    };
}

/// Implement the in-place `downcast_ref` borrows (`array[i]`, `Any::downcast_ref`,
/// [`ObjectRefCore::downcast_ref`](crate::ObjectRefCore::downcast_ref)) for each
/// listed object reference type. [`#[derive(ObjectRef)]`](crate::derive::ObjectRef)
/// emits it; a reference that implements `ObjectRefCore` by hand calls it.
///
/// # Safety
///
/// The leading `unsafe` is a required marker: writing it, the caller promises
/// that each type is `repr(transparent)` over one object pointer, and its
/// [`AnyCompatible::check_any_strict`](crate::AnyCompatible::check_any_strict)
/// accepts exactly the objects that are a valid value of it.
///
/// # Examples
///
/// ```standalone_crate
/// use tvm_ffi::derive::ObjectRef;
/// use tvm_ffi::{rs_object, impl_object_ref_downcast_ref, Any};
/// use tvm_ffi::{Object, ObjectArc, ObjectRefCore};
/// use tvm_ffi::object::ObjectRefAnyCompatible;
///
/// #[rs_object(type_key = "my_ext.MyPair", final)]
/// pub struct MyPairObj {
///     base_: Object,
///     pub first: i64,
///     pub second: i64,
/// }
///
/// #[derive(Clone, ObjectRef)]
/// pub struct MyPair {
///     data: ObjectArc<MyPairObj>,
/// }
///
/// /// A `MyPair` whose `first` is positive.
/// #[derive(Clone)]
/// #[repr(transparent)]
/// pub struct PositivePair(ObjectArc<MyPairObj>);
///
/// unsafe impl ObjectRefCore for PositivePair {
///     type ContainerType = MyPairObj;
///     fn data(this: &Self) -> &ObjectArc<MyPairObj> {
///         &this.0
///     }
///     fn into_data(this: Self) -> ObjectArc<MyPairObj> {
///         this.0
///     }
///     unsafe fn from_data(data: ObjectArc<MyPairObj>) -> Self {
///         Self(data)
///     }
/// }
///
/// unsafe impl ObjectRefAnyCompatible for PositivePair {
///     fn extra_check(pair: &MyPairObj) -> bool {
///         pair.first > 0
///     }
/// }
/// impl_object_ref_downcast_ref!(unsafe PositivePair);
///
/// let pair = Any::from(MyPair::from_object(MyPairObj::new(Object::new(), 1, 2)));
/// assert!(pair.downcast_ref::<PositivePair>().is_some());
/// ```
#[macro_export]
macro_rules! impl_object_ref_downcast_ref {
    (unsafe $($name:ty),+ $(,)?) => {
        $(
            // SAFETY: the macro declaration promises that `$name` is one object
            // pointer whose `check_any_strict` is its type check.
            unsafe impl $crate::type_traits::RefFromAnyUnchecked for $name {
                #[inline(always)]
                unsafe fn ref_from_any_unchecked(
                    cell: &$crate::tvm_ffi_sys::TVMFFIAny,
                ) -> &Self {
                    const {
                        ::core::assert!(
                            ::core::mem::size_of::<$name>()
                                == ::core::mem::size_of::<*mut $crate::tvm_ffi_sys::TVMFFIObject>()
                                && ::core::mem::align_of::<$name>()
                                    == ::core::mem::align_of::<*mut $crate::tvm_ffi_sys::TVMFFIObject>(),
                            "a reference downcast target must be exactly one object pointer"
                        )
                    };
                    unsafe { &*(::core::ptr::addr_of!(cell.data_union) as *const Self) }
                }
            }

            unsafe impl $crate::type_traits::DowncastRefFromAny for $name {
                #[inline(always)]
                unsafe fn downcast_ref_from_any(
                    cell: &$crate::tvm_ffi_sys::TVMFFIAny,
                ) -> ::core::option::Option<&Self> {
                    unsafe { $crate::type_traits::downcast_ref_from_any_in_place::<Self>(cell) }
                }
            }

            unsafe impl $crate::type_traits::DowncastRefFromObject for $name {
                #[inline(always)]
                unsafe fn downcast_ref_from_object(
                    place: &*mut $crate::tvm_ffi_sys::TVMFFIObject,
                ) -> ::core::option::Option<&Self> {
                    unsafe { $crate::type_traits::downcast_ref_from_object_in_place::<Self>(place) }
                }
            }
        )+
    };
}

// ----------------------------------------------------------------------------
// Macros for any definitions
// ----------------------------------------------------------------------------

/// Implement the conversions between each listed [`AnyCompatible`](crate::AnyCompatible)
/// type and FFI values: `TryFrom<AnyView>`, `TryFrom<Any>` and `TryFrom<&Any>`,
/// and use as an argument of [`Function::call_tuple`](crate::Function::call_tuple)
/// and of functions from [`into_typed_fn!`](crate::into_typed_fn).
///
/// `#[derive(ObjectRef)]` calls it; a type that implements `AnyCompatible` by hand
/// calls it after that impl. See also
/// [`impl_object_ref_downcast_ref!`](crate::impl_object_ref_downcast_ref)
/// for an object reference implemented by hand.
#[macro_export]
macro_rules! impl_any_compatible_conversions {
    ($($t:ty),* $(,)?) => {
        $crate::impl_try_from_any!($($t),*);
        $crate::impl_into_arg!($($t),*);
        $crate::impl_into_packed_arg!($($t),*);
    };
}

/// `TryFrom` from FFI values; part of [`impl_any_compatible_conversions!`](crate::impl_any_compatible_conversions).
#[doc(hidden)]
#[macro_export]
macro_rules! impl_try_from_any {
    ($($t:ty),* $(,)?) => {
        $(
            impl<'a> ::core::convert::TryFrom<$crate::any::AnyView<'a>> for $t {
                type Error = $crate::error::Error;
                #[inline(always)]
                fn try_from(
                    value: $crate::any::AnyView<'a>
                ) -> ::core::result::Result<Self, Self::Error> {
                    type TryFromTemp = $crate::any::TryFromTemp<$t>;
                    return <TryFromTemp as ::core::convert::TryFrom<_>>::try_from(value).map(TryFromTemp::into_value);
                }
            }

            impl ::core::convert::TryFrom<$crate::any::Any> for $t {
                type Error = $crate::error::Error;
                #[inline(always)]
                fn try_from(
                    value: $crate::any::Any
                ) -> ::core::result::Result<Self, Self::Error> {
                    type TryFromTemp = $crate::any::TryFromTemp<$t>;
                    return <TryFromTemp as ::core::convert::TryFrom<_>>::try_from(value).map(TryFromTemp::into_value);
                }
            }

            impl<'a> ::core::convert::TryFrom<&'a $crate::any::Any> for $t {
                type Error = $crate::error::Error;
                #[inline(always)]
                fn try_from(
                    value: &'a $crate::any::Any
                ) -> ::core::result::Result<Self, Self::Error> {
                    type TryFromTemp = $crate::any::TryFromTemp<$t>;
                    return <TryFromTemp as ::core::convert::TryFrom<_>>::try_from(value).map(TryFromTemp::into_value);
                }
            }
        )*
    };
}

/// `IntoArg<T>` for `T` and `&T`; part of [`impl_any_compatible_conversions!`](crate::impl_any_compatible_conversions).
#[doc(hidden)]
#[macro_export]
macro_rules! impl_into_arg {
    ($($t:ty),* $(,)?) => {
        $($crate::impl_into_arg!(impl[] $t);)*
    };
    (impl[$($g:tt)*] $t:ty) => {
            impl<$($g)*> $crate::IntoArg<$t> for $t {
                type Output = $t;
                #[inline(always)]
                fn into_arg(self) -> $t {
                    self
                }
                #[inline(always)]
                fn into_owned(self) -> $t {
                    self
                }
            }

            impl<'a, $($g)*> $crate::IntoArg<$t> for &'a $t {
                type Output = &'a $t;
                #[inline(always)]
                fn into_arg(self) -> &'a $t {
                    self
                }
                #[inline(always)]
                fn into_owned(self) -> $t {
                    ::core::clone::Clone::clone(self)
                }
            }
    };
}

/// Macro to implement `TryFrom<AnyView>` and `TryFrom<Any>` for generic types like `Option<T>`
#[doc(hidden)]
#[macro_export]
macro_rules! impl_try_from_any_for_parametric {
    ($generic_type:ident<$param:ident>) => {
        impl<'a, $param: $crate::type_traits::AnyCompatible>
            ::core::convert::TryFrom<$crate::any::AnyView<'a>> for $generic_type<$param>
        {
            type Error = $crate::error::Error;
            #[inline(always)]
            fn try_from(
                value: $crate::any::AnyView<'a>,
            ) -> ::core::result::Result<Self, Self::Error> {
                type TryFromTemp<T> = $crate::any::TryFromTemp<$generic_type<$param>>;
                return <TryFromTemp<T> as ::core::convert::TryFrom<_>>::try_from(value)
                    .map(TryFromTemp::<T>::into_value);
            }
        }

        impl<$param: $crate::type_traits::AnyCompatible> ::core::convert::TryFrom<$crate::any::Any>
            for $generic_type<$param>
        {
            type Error = $crate::error::Error;
            #[inline(always)]
            fn try_from(value: $crate::any::Any) -> ::core::result::Result<Self, Self::Error> {
                type TryFromTemp<T> = $crate::any::TryFromTemp<$generic_type<$param>>;
                return <TryFromTemp<T> as ::core::convert::TryFrom<_>>::try_from(value)
                    .map(TryFromTemp::<T>::into_value);
            }
        }

        impl<'a, $param: $crate::type_traits::AnyCompatible>
            ::core::convert::TryFrom<&'a $crate::any::Any> for $generic_type<$param>
        {
            type Error = $crate::error::Error;
            #[inline(always)]
            fn try_from(value: &'a $crate::any::Any) -> ::core::result::Result<Self, Self::Error> {
                type TryFromTemp<T> = $crate::any::TryFromTemp<$generic_type<$param>>;
                return <TryFromTemp<T> as ::core::convert::TryFrom<_>>::try_from(value)
                    .map(TryFromTemp::<T>::into_value);
            }
        }
    };
}

/// Packed-call arguments; part of [`impl_any_compatible_conversions!`](crate::impl_any_compatible_conversions).
#[doc(hidden)]
#[macro_export]
macro_rules! impl_into_packed_arg {
    ($($t:ty),* $(,)?) => {
        $($crate::impl_into_packed_arg!(impl[] $t);)*
    };
    (impl[$($g:tt)*] $t:ty) => {
        impl<$($g)*> $crate::function_internal::PackedCallArg for $t {
            type Holder = $t;
            #[inline(always)]
            fn into_packed_arg(self) -> $t {
                self
            }
            #[inline(always)]
            fn as_packed_arg(holder: &Self::Holder) -> $crate::any::AnyView<'_> {
                $crate::any::AnyView::from(holder)
            }
        }

        impl<'a, $($g)*> $crate::function_internal::PackedCallArg for &'a $t {
            type Holder = &'a $t;
            #[inline(always)]
            fn into_packed_arg(self) -> &'a $t {
                self
            }
            #[inline(always)]
            fn as_packed_arg(holder: &Self::Holder) -> $crate::any::AnyView<'_> {
                $crate::any::AnyView::from(*holder)
            }
        }
    };
}

// ----------------------------------------------------------------------------
// Macros for function definitions
// ----------------------------------------------------------------------------

/// Macro to export a typed function as a C symbol that follows the tvm-ffi ABI
///
/// An error the function returns is raised to the caller. Report errors by
/// returning them; a panic is also caught and raised, as an `InternalError`,
/// since unwinding into the caller would abort the process, but panicking
/// is discouraged.
///
/// With the `export-metadata` feature, the counterpart of C++
/// `TVM_FFI_DLL_EXPORT_INCLUDE_METADATA`, the macro also exports the
/// function's metadata, `{"type_schema":...}`, as `__tvm_ffi__metadata_<name>`,
/// which [`Module::get_function_metadata`](crate::Module::get_function_metadata)
/// and the stub generator read. A
/// function's schema lists its parameter and return types; a callable whose
/// signature is not known, such as a custom `AsPackedCallable`, has the
/// schema of an untyped function. The feature is off by default, so exports
/// are minimal.
///
/// # Arguments
/// * `$name` - The name of the function
/// * `$func` - The function to export
///
/// # Example
/// ```rust,standalone_crate
/// use tvm_ffi::*;
///
/// fn add_one(x: i32) -> Result<i32> { Ok(x + 1) }
///
/// tvm_ffi_dll_export_typed_func!(add_one, add_one);
/// ```
#[macro_export]
macro_rules! tvm_ffi_dll_export_typed_func {
    ($name:ident, $func:expr) => {
        $crate::macros::paste::paste! {
            // `no_mangle` keeps the symbol in a `cdylib` under the
            // `__tvm_ffi_<name>` name that `Module` looks up.
            //
            // The path-qualified `$crate::tvm_ffi_sys::…` reference (rather
            // than a bare `tvm_ffi_sys::…`) lets downstream crates use the
            // macro without having to add `tvm-ffi-sys` to their own
            // `[dependencies]`.
            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn [<__tvm_ffi_ $name>](
                _handle: *mut ::core::ffi::c_void,
                args: *const $crate::tvm_ffi_sys::TVMFFIAny,
                num_args: i32,
                result: *mut $crate::tvm_ffi_sys::TVMFFIAny,
            ) -> i32 {
                let packed_args = $crate::function_internal::packed_args(args, num_args);
                let ret_value = match ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| {
                    $crate::function_internal::call_packed_callable($func, packed_args)
                })) {
                    ::core::result::Result::Ok(ret_value) => ret_value,
                    ::core::result::Result::Err(payload) => ::core::result::Result::Err($crate::error::Error::from_panic(payload)),
                };
                match ret_value {
                    ::core::result::Result::Ok(value) => {
                        *result = $crate::any::Any::into_raw_ffi_any(value);
                        0
                    }
                    ::core::result::Result::Err(error) => {
                        $crate::error::Error::set_raised(&error);
                        -1
                    }
                }
            }
        }
        $crate::__tvm_ffi_dll_export_metadata!($name, $func);
    };
}

/// Macro to export the doc string of a function exported with
/// [`tvm_ffi_dll_export_typed_func!`], as C++ `TVM_FFI_DLL_EXPORT_TYPED_FUNC_DOC`
/// does
///
/// With the `export-metadata` feature, the doc string is exported as
/// `__tvm_ffi__doc_<name>`, which
/// [`Module::get_function_doc`](crate::Module::get_function_doc) and the stub
/// generator read. Without it, the macro exports nothing, but
/// still checks that the doc string is a string constant. The macro never
/// exports the function itself.
///
/// # Arguments
/// * `$name` - The name the function is exported as
/// * `$doc` - The doc string, a string literal
///
/// # Example
/// ```rust,standalone_crate
/// use tvm_ffi::*;
///
/// fn add(a: i64, b: i64) -> Result<i64> { Ok(a + b) }
///
/// tvm_ffi_dll_export_typed_func!(add, add);
/// tvm_ffi_dll_export_typed_func_doc!(add, "Add two integers and return the sum.");
/// ```
#[macro_export]
macro_rules! tvm_ffi_dll_export_typed_func_doc {
    ($name:ident, $doc:expr) => {
        $crate::__tvm_ffi_dll_export_doc!($name, $doc);
    };
}

// The metadata and doc getters the export macros emit with the
// `export-metadata` feature. A `#[cfg]` in a `macro_rules!` expansion would
// test the features of the crate that invokes the macro, so the feature
// selects which definition of these helpers this crate compiles instead.

#[cfg(feature = "export-metadata")]
#[doc(hidden)]
#[macro_export]
macro_rules! __tvm_ffi_dll_export_metadata {
    ($name:ident, $func:expr) => {
        $crate::macros::paste::paste! {
            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn [<__tvm_ffi__metadata_ $name>](
                _handle: *mut ::core::ffi::c_void,
                _args: *const $crate::tvm_ffi_sys::TVMFFIAny,
                _num_args: i32,
                result: *mut $crate::tvm_ffi_sys::TVMFFIAny,
            ) -> i32 {
                let metadata = match ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| {
                    $crate::function_internal::exported_metadata(&$func)
                })) {
                    ::core::result::Result::Ok(metadata) => metadata,
                    ::core::result::Result::Err(payload) => ::core::result::Result::Err($crate::error::Error::from_panic(payload)),
                };
                $crate::function_internal::write_exported_str(metadata, result)
            }
        }
    };
}

#[cfg(not(feature = "export-metadata"))]
#[doc(hidden)]
#[macro_export]
macro_rules! __tvm_ffi_dll_export_metadata {
    ($name:ident, $func:expr) => {};
}

#[cfg(feature = "export-metadata")]
#[doc(hidden)]
#[macro_export]
macro_rules! __tvm_ffi_dll_export_doc {
    ($name:ident, $doc:expr) => {
        $crate::macros::paste::paste! {
            #[unsafe(no_mangle)]
            pub unsafe extern "C" fn [<__tvm_ffi__doc_ $name>](
                _handle: *mut ::core::ffi::c_void,
                _args: *const $crate::tvm_ffi_sys::TVMFFIAny,
                _num_args: i32,
                result: *mut $crate::tvm_ffi_sys::TVMFFIAny,
            ) -> i32 {
                const DOC: &str = $doc;
                $crate::function_internal::write_exported_str(::core::result::Result::Ok(::std::string::ToString::to_string(DOC)), result)
            }
        }
    };
}

#[cfg(not(feature = "export-metadata"))]
#[doc(hidden)]
#[macro_export]
macro_rules! __tvm_ffi_dll_export_doc {
    ($name:ident, $doc:expr) => {
        const _: &str = $doc;
    };
}

/// Wrap a [`Function`](crate::Function) as a typed closure with the given
/// signature: `into_typed_fn!(func, Fn(A, B) -> Result<R>)`.
///
/// The closure converts its arguments and the result, and checks the argument
/// count at compile time; it takes 0 to 8 arguments. An argument may be taken
/// by value or by reference; prefer a reference for an object reference such as
/// a `Tensor`, which the caller then keeps.
///
/// # Examples
///
/// ```
/// use tvm_ffi::*;
///
/// let func = Function::from_typed(|x: i32, y: i32| -> Result<i32> { Ok(x + y) });
/// let add = into_typed_fn!(func, Fn(i32, &i32) -> Result<i32>);
/// assert_eq!(add(10, &20)?, 30);
/// # Ok::<(), tvm_ffi::Error>(())
/// ```
#[macro_export]
macro_rules! into_typed_fn {
    // Case for 0 arguments
    ($f:expr, Fn() -> $ret_ty:ty) => {{
        let _f = $f;
        move || -> $ret_ty {
            ::core::convert::TryInto::try_into(_f.call_tuple(())?)
                .map_err(::core::convert::Into::into)
        }
    }};
    // Case for 1 argument
    ($f:expr, Fn($t0:ty) -> $ret_ty:ty) => {{
        let _f = $f;
        move |a0: $t0| -> $ret_ty {
            ::core::convert::TryInto::try_into(_f.call_tuple((a0,))?)
                .map_err(::core::convert::Into::into)
        }
    }};
    // Case for 2 arguments
    ($f:expr, Fn($t0:ty, $t1:ty) -> $ret_ty:ty) => {{
        let _f = $f;
        move |a0: $t0, a1: $t1| -> $ret_ty {
            ::core::convert::TryInto::try_into(_f.call_tuple((a0, a1))?)
                .map_err(::core::convert::Into::into)
        }
    }};
    // Case for 3 arguments
    ($f:expr, Fn($t0:ty, $t1:ty, $t2:ty) -> $ret_ty:ty) => {{
        let _f = $f;
        move |a0: $t0, a1: $t1, a2: $t2| -> $ret_ty {
            ::core::convert::TryInto::try_into(_f.call_tuple((a0, a1, a2))?)
                .map_err(::core::convert::Into::into)
        }
    }};
    // Case for 4 arguments
    ($f:expr, Fn($t0:ty, $t1:ty, $t2:ty, $t3:ty) -> $ret_ty:ty) => {{
        let _f = $f;
        move |a0: $t0, a1: $t1, a2: $t2, a3: $t3| -> $ret_ty {
            ::core::convert::TryInto::try_into(_f.call_tuple((a0, a1, a2, a3))?)
                .map_err(::core::convert::Into::into)
        }
    }};
    // Case for 5 arguments
    ($f:expr, Fn($t0:ty, $t1:ty, $t2:ty, $t3:ty, $t4:ty) -> $ret_ty:ty) => {{
        let _f = $f;
        move |a0: $t0, a1: $t1, a2: $t2, a3: $t3, a4: $t4| -> $ret_ty {
            ::core::convert::TryInto::try_into(_f.call_tuple((a0, a1, a2, a3, a4))?)
                .map_err(::core::convert::Into::into)
        }
    }};
    // Case for 6 arguments
    ($f:expr, Fn($t0:ty, $t1:ty, $t2:ty, $t3:ty, $t4:ty, $t5:ty) -> $ret_ty:ty) => {{
        let _f = $f;
        move |a0: $t0, a1: $t1, a2: $t2, a3: $t3, a4: $t4, a5: $t5| -> $ret_ty {
            ::core::convert::TryInto::try_into(_f.call_tuple((a0, a1, a2, a3, a4, a5))?)
                .map_err(::core::convert::Into::into)
        }
    }};
    // Case for 7 arguments
    ($f:expr, Fn($t0:ty, $t1:ty, $t2:ty, $t3:ty, $t4:ty, $t5:ty, $t6:ty)
        -> $ret_ty:ty) => {{
        let _f = $f;
        move |a0: $t0, a1: $t1, a2: $t2, a3: $t3, a4: $t4, a5: $t5, a6: $t6| -> $ret_ty {
            ::core::convert::TryInto::try_into(_f.call_tuple((a0, a1, a2, a3, a4, a5, a6))?)
                .map_err(::core::convert::Into::into)
        }
    }};
    // Case for 8 arguments
    ($f:expr, Fn($t0:ty, $t1:ty, $t2:ty, $t3:ty, $t4:ty, $t5:ty, $t6:ty, $t7:ty)
        -> $ret_ty:ty) => {{
        let _f = $f;
        move |a0: $t0, a1: $t1, a2: $t2, a3: $t3, a4: $t4, a5: $t5, a6: $t6, a7: $t7| -> $ret_ty {
            ::core::convert::TryInto::try_into(_f.call_tuple((a0, a1, a2, a3, a4, a5, a6, a7))?)
                .map_err(::core::convert::Into::into)
        }
    }};
    ($f:expr, $($signature:tt)*) => {
        ::core::compile_error!(::core::concat!(
            "expected `Fn(A, ...) -> R` with 0 to 8 arguments, ",
            "as in `into_typed_fn!(func, Fn(i32) -> Result<i32>)`"
        ))
    };
}