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
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
/*
 * 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.
 */
//! Traits that map Rust types to TVM-FFI values.

use crate::any::{Any, AnyView};
use std::borrow::Borrow;
use tvm_ffi_sys::TVMFFITypeIndex as TypeIndex;
use tvm_ffi_sys::{TVMFFIAny, TVMFFIGetTypeInfo, TVMFFIObject};

/// A type whose values an FFI cell can hold: how a value is stored in a
/// `TVMFFIAny` and read back.
///
/// [`AnyView`] and [`TensorView`](crate::TensorView) borrow their value, so
/// they are not. Containers and generic code bound on [`ContainerElement`] to
/// also accept [`Any`].
///
/// # Implementing
///
/// Object references derive it with `#[derive(ObjectRef)]`. Any other type
/// implements it by hand, then calls
/// [`impl_any_compatible_conversions!`](crate::impl_any_compatible_conversions),
/// which adds its `From`, `TryFrom` and argument conversions. Coherence keeps
/// those out of this trait, so without the macro the type is stored but not
/// converted.
///
/// # Safety
/// - A value is written in the cell layout of its type index, and read back from it.
/// - Every `*_after_check` method is sound on each cell that `check_any_strict` accepts.
/// - `is_undefined` is false for every value. It is true for all-zero bytes,
///   unless those bytes are a value whose drop does nothing.
pub unsafe trait AnyCompatible: Sized {
    /// Whether the `AnyView -> Self` conversion matches one exact leaf type.
    ///
    /// If this is `true`, [`Self::match_any_exact_type_index`] must always
    /// return the same index for the process lifetime, and conversion from an
    /// object-backed `AnyView` must succeed if and only if its runtime type
    /// index equals that index. Matching must not depend on any other part of
    /// the value. `match_any!` may use this contract to skip conversions for
    /// all other arms.
    #[doc(hidden)]
    const MATCH_ANY_EXACT: bool = false;

    /// Return the sole runtime object type index accepted by this conversion.
    #[doc(hidden)]
    fn match_any_exact_type_index() -> i32 {
        unreachable!("MATCH_ANY_EXACT is false")
    }

    /// Whether `field`, which holds a value of this type or all-zero bytes,
    /// holds all-zero bytes that are no value of this type, as a null object
    /// reference, a string of type index None or a zero device type: a field
    /// that a creator left undefined for reflection to set. An undefined field
    /// is no value; a nullable reference is `Option<T>`, whose `None` is a
    /// defined value.
    ///
    /// The field setter writes an undefined field without dropping it, the
    /// field getter reads it as None, and the object's deleter skips it. The default,
    /// false, fits a type whose all-zero bytes are a value whose drop does
    /// nothing, as a scalar's, `Any`'s or `Optional`'s.
    ///
    /// # Safety
    ///
    /// `field` points to a value of this type or to all-zero bytes. An
    /// implementation reads only bytes that each value initializes and, when
    /// `Option<Self>` is niche-optimized, that its `None` initializes too.
    #[inline]
    unsafe fn is_undefined(field: *const Self) -> bool {
        let _ = field;
        false
    }

    /// Whether a reflected field of this type is laid out as readers of its
    /// static type index expect: an `Optional` field as a nullable object
    /// pointer or a `TVMFFIAny` cell.
    #[doc(hidden)]
    fn has_field_layout() -> bool {
        true
    }

    /// Write a cell that borrows `src` into `data`.
    ///
    /// # Safety
    /// The written cell borrows `src` without a reference and must not be used
    /// after `src` is dropped.
    unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny);
    /// Write a cell that owns `src` into `data`.
    ///
    /// # Safety
    /// The previous content of `data` is overwritten without release; the
    /// caller owns the written cell and must release it exactly once.
    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny);
    /// Whether `data` holds a `Self` as is, without conversion.
    ///
    /// # Safety
    /// `data` must be a valid `TVMFFIAny` cell.
    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool;

    /// Additional value-preservation checks used only by `match_any!` and
    /// dispatch handlers, after `check_any_strict` succeeds. Ordinary conversion
    /// APIs are unchanged.
    ///
    /// # Safety
    /// `data` must have passed `Self::check_any_strict`.
    #[doc(hidden)]
    unsafe fn match_constraints(_data: &TVMFFIAny) -> bool {
        true
    }

    /// Copy a `Self` out of a cell that holds one, retaining any object.
    ///
    /// # Safety
    /// `data` must have passed `Self::check_any_strict`.
    unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self;
    /// Move a `Self` out of an owning cell that holds one.
    ///
    /// # Safety
    /// `data` must have passed `Self::check_any_strict`. Its ownership moves
    /// into the result, so the caller must not release `data` again.
    unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self;
    /// Convert `data` into a `Self` by the FFI rules, such as an integer into a
    /// float; `Err` if it does not convert.
    ///
    /// # Safety
    /// `data` must be a valid `TVMFFIAny` cell.
    #[allow(clippy::result_unit_err)]
    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()>;
    /// The name of the mismatched value `data` in conversion errors; by
    /// default its runtime type key.
    fn get_mismatch_type_info(data: &TVMFFIAny) -> String {
        runtime_type_key(data.type_index)
    }
    /// The type name in conversion errors and type schemas, such as `int`,
    /// `ffi.String` or `Array<int>`.
    fn type_str() -> String;

    /// The type schema of the type: the JSON object that describes it, which
    /// the type schemas of functions and fields embed.
    ///
    /// The default, `{"type":"<type_str>"}`, fits a type whose type string is
    /// its type key, as for object references.
    fn type_schema() -> String {
        type_schema(&Self::type_str(), &[])
    }

    /// Borrow `self` into an owned [`Any`], increfing object-backed values.
    ///
    /// The by-reference counterpart of `Any::from(value)`, for fields reached
    /// through a `Deref` into shared object storage. `impl From<&T> for Any`
    /// cannot be added instead: `&` is fundamental, so a downstream crate may
    /// implement `AnyCompatible` for its own `&T` and the two impls overlap
    /// (E0119).
    #[inline]
    fn to_any(&self) -> Any {
        AnyView::from(self).into()
    }
}

/// A value an FFI container such as [`Array`](crate::Array) holds: every
/// [`AnyCompatible`] type, and [`Any`].
///
/// Sealed: implement [`AnyCompatible`] to make a type an element.
pub trait ContainerElement: container_element_ops::Ops {}

impl<T: AnyCompatible> ContainerElement for T {}
impl ContainerElement for Any {}

/// `Self` subsumes `Source`: every `Source` value, as stored, is a valid
/// `Self`, a compile-time fact checked by no code, as C++
/// `type_subsumes_v<Self, Source>`. So a container of `Source` is a container
/// of `Self` without a copy, as [`Array::upcast`](crate::Array::upcast) and
/// [`Map::upcast`](crate::Map::upcast) use.
///
/// It holds for every type and itself, and for a base object reference and
/// each derived one, which [`impl_object_ref_upcast!`](crate::impl_object_ref_upcast)
/// declares.
///
/// # Safety
///
/// Every cell that `Source` strictly accepts, `Self` strictly accepts, also
/// after a change made through `Self`.
pub unsafe trait TypeSubsumes<Source: ?Sized> {}

unsafe impl<T: ?Sized> TypeSubsumes<T> for T {}

/// A `T`, a `&T` or a subtype of `T`, taken where a `T` is expected; a `&str`
/// or `&[u8]` converts into a `String` or `Bytes`.
///
/// [`into_arg`](Self::into_arg) returns a `T` or a `&T` without changing a
/// reference count, but those two conversions allocate;
/// [`into_owned`](Self::into_owned) moves an owned value and clones only a
/// borrowed one, as [`Cow::into_owned`](std::borrow::Cow::into_owned).
pub trait IntoArg<T> {
    /// `T` when owned, `&T` when borrowed.
    type Output: Borrow<T>;

    /// Convert into a `T` or a `&T`.
    fn into_arg(self) -> Self::Output;

    /// Convert into an owned `T`, cloning only a borrowed value.
    fn into_owned(self) -> T;
}

impl IntoArg<crate::String> for &str {
    type Output = crate::String;
    #[inline]
    fn into_arg(self) -> crate::String {
        crate::String::from(self)
    }
    #[inline]
    fn into_owned(self) -> crate::String {
        crate::String::from(self)
    }
}

impl IntoArg<crate::string::Bytes> for &[u8] {
    type Output = crate::string::Bytes;
    #[inline]
    fn into_arg(self) -> crate::string::Bytes {
        crate::string::Bytes::from(self)
    }
    #[inline]
    fn into_owned(self) -> crate::string::Bytes {
        crate::string::Bytes::from(self)
    }
}

/// A type whose value an FFI cell stores in place, so `&Self` borrows from the
/// cell, as [`Array`](crate::Array) indexing does.
///
/// A reference type implemented by hand gets it from
/// [`impl_object_ref_downcast_ref!`](crate::impl_object_ref_downcast_ref).
///
/// # Safety
///
/// For a cell that `Self` strictly accepts, `ref_from_any_unchecked` must
/// return a reference into that cell that is a valid `Self` for as long as the
/// cell is borrowed.
#[doc(hidden)]
pub unsafe trait RefFromAnyUnchecked: ContainerElement {
    /// Borrow the value stored in `cell`.
    ///
    /// # Safety
    ///
    /// `cell` must hold a `Self`.
    unsafe fn ref_from_any_unchecked(cell: &TVMFFIAny) -> &Self;
}

// The whole cell is the value.
unsafe impl RefFromAnyUnchecked for Any {
    #[inline(always)]
    unsafe fn ref_from_any_unchecked(cell: &TVMFFIAny) -> &Self {
        unsafe { &*(cell as *const TVMFFIAny as *const Any) }
    }
}

// A `BigInt` is one cell, holding an inline `i64` or a `BigInt` object.
unsafe impl RefFromAnyUnchecked for crate::big_int::BigInt {
    #[inline(always)]
    unsafe fn ref_from_any_unchecked(cell: &TVMFFIAny) -> &Self {
        const {
            assert!(
                std::mem::size_of::<crate::big_int::BigInt>() == std::mem::size_of::<TVMFFIAny>()
            );
            assert!(
                std::mem::align_of::<crate::big_int::BigInt>() == std::mem::align_of::<TVMFFIAny>()
            );
        };
        unsafe { &*(cell as *const TVMFFIAny as *const crate::big_int::BigInt) }
    }
}

unsafe impl RefFromAnyUnchecked for crate::String {
    #[inline(always)]
    unsafe fn ref_from_any_unchecked(cell: &TVMFFIAny) -> &Self {
        unsafe { &*(cell as *const TVMFFIAny as *const crate::String) }
    }
}

unsafe impl RefFromAnyUnchecked for crate::string::Bytes {
    #[inline(always)]
    unsafe fn ref_from_any_unchecked(cell: &TVMFFIAny) -> &Self {
        unsafe { &*(cell as *const TVMFFIAny as *const crate::string::Bytes) }
    }
}

// The payload word holds the value in its own representation.
unsafe impl RefFromAnyUnchecked for i64 {
    #[inline(always)]
    unsafe fn ref_from_any_unchecked(cell: &TVMFFIAny) -> &Self {
        unsafe { &cell.data_union.v_int64 }
    }
}

unsafe impl RefFromAnyUnchecked for f64 {
    #[inline(always)]
    unsafe fn ref_from_any_unchecked(cell: &TVMFFIAny) -> &Self {
        unsafe { &cell.data_union.v_float64 }
    }
}

unsafe impl RefFromAnyUnchecked for tvm_ffi_sys::dlpack::DLDataType {
    #[inline(always)]
    unsafe fn ref_from_any_unchecked(cell: &TVMFFIAny) -> &Self {
        unsafe { &cell.data_union.v_dtype }
    }
}

unsafe impl RefFromAnyUnchecked for tvm_ffi_sys::dlpack::DLDevice {
    #[inline(always)]
    unsafe fn ref_from_any_unchecked(cell: &TVMFFIAny) -> &Self {
        unsafe { &cell.data_union.v_device }
    }
}

// An optional object reference is one nullable object pointer (`None` is null,
// as `OptionalCompatible` relies on), which is the payload word of a `None` or
// object cell, so `&Option<T>` borrows that word.
unsafe impl<T: crate::object::ObjectRefCore> RefFromAnyUnchecked for Option<T> {
    #[inline(always)]
    unsafe fn ref_from_any_unchecked(cell: &TVMFFIAny) -> &Self {
        const {
            assert!(std::mem::size_of::<Option<T>>() == std::mem::size_of::<*mut TVMFFIObject>());
            assert!(std::mem::align_of::<Option<T>>() == std::mem::align_of::<*mut TVMFFIObject>());
        };
        if cell.type_index == TypeIndex::kTVMFFINone as i32 {
            // A `None` cell's payload is zero by convention (C++ `Any()`), but
            // do not rely on a producer for it.
            return &None;
        }
        unsafe { &*(&cell.data_union.v_obj as *const *mut TVMFFIObject as *const Option<T>) }
    }
}

/// A type that [`Any::downcast_ref`] and [`AnyView::downcast_ref`] borrow from
/// an FFI cell in place, without a reference count change: object types
/// (`ArrayObj`), managed references (`Array<T>`, `String`, any
/// [`#[derive(ObjectRef)]`](crate::derive::ObjectRef) type), `Option` of a
/// reference and scalars such as `i64`.
///
/// Name it to bound a generic borrow, as in `fn get<T: DowncastRefFromAny>`.
/// Object types, derived references and containers implement it, not code by
/// hand: a reference with a hand-written `ObjectRefCore` calls
/// [`impl_object_ref_downcast_ref!`](crate::impl_object_ref_downcast_ref).
///
/// # Safety
///
/// `downcast_ref_from_any` must return `Some` only when `cell` holds a `Self`, with
/// a reference that stays valid while `cell` is borrowed.
pub unsafe trait DowncastRefFromAny {
    /// Borrow `cell` as `Self` when it holds one.
    ///
    /// # Safety
    ///
    /// `cell` must be a valid FFI cell.
    unsafe fn downcast_ref_from_any(cell: &TVMFFIAny) -> Option<&Self>;
}

// An object type borrows the object the cell points to.
unsafe impl<T: crate::object::ObjectCore> DowncastRefFromAny for T {
    #[inline(always)]
    unsafe fn downcast_ref_from_any(cell: &TVMFFIAny) -> Option<&Self> {
        if cell.type_index < TypeIndex::kTVMFFIStaticObjectBegin as i32
            || !crate::object::is_instance_of::<T>(cell.type_index)
        {
            return None;
        }
        // SAFETY: the type check establishes T's layout, and the cell keeps the
        // object alive while it is borrowed.
        Some(unsafe { &*cell.data_union.v_obj.cast::<T>() })
    }
}

/// Borrow `cell` as a [`RefFromAnyUnchecked`] type when it strictly holds one:
/// the [`DowncastRefFromAny`] of such a type.
///
/// # Safety
///
/// `cell` must be a valid FFI cell.
#[doc(hidden)]
#[inline(always)]
pub unsafe fn downcast_ref_from_any_in_place<T: RefFromAnyUnchecked>(
    cell: &TVMFFIAny,
) -> Option<&T> {
    if unsafe { T::container_check_any_strict(cell) } {
        Some(unsafe { T::ref_from_any_unchecked(cell) })
    } else {
        None
    }
}

unsafe impl<T: crate::object::ObjectRefCore> DowncastRefFromAny for Option<T> {
    #[inline(always)]
    unsafe fn downcast_ref_from_any(cell: &TVMFFIAny) -> Option<&Self> {
        unsafe { downcast_ref_from_any_in_place::<Self>(cell) }
    }
}

macro_rules! impl_downcast_ref_from_any {
    ($($t:ty),* $(,)?) => {
        $(unsafe impl DowncastRefFromAny for $t {
            #[inline(always)]
            unsafe fn downcast_ref_from_any(cell: &TVMFFIAny) -> Option<&Self> {
                unsafe { downcast_ref_from_any_in_place::<Self>(cell) }
            }
        })*
    };
}

// An `&Any` must own what it points at, as an `Any` does: a view's cell may
// instead borrow a C string, byte array, `DLTensor` or rvalue slot, whose
// `&Any` would clone into an owner of a borrowed resource. Those are refused;
// an `Any` or container cell never holds them.
unsafe impl DowncastRefFromAny for Any {
    #[inline(always)]
    unsafe fn downcast_ref_from_any(cell: &TVMFFIAny) -> Option<&Self> {
        let index = cell.type_index;
        let borrowed = index == TypeIndex::kTVMFFIRawStr as i32
            || index == TypeIndex::kTVMFFIByteArrayPtr as i32
            || index == TypeIndex::kTVMFFIDLTensorPtr as i32
            || index == TypeIndex::kTVMFFIObjectRValueRef as i32;
        if borrowed {
            None
        } else {
            Some(unsafe { Any::ref_from_any_unchecked(cell) })
        }
    }
}

impl_downcast_ref_from_any!(
    crate::String,
    crate::string::Bytes,
    i64,
    f64,
    crate::big_int::BigInt,
    tvm_ffi_sys::dlpack::DLDataType,
    tvm_ffi_sys::dlpack::DLDevice,
);

/// A type that an object reference's [`ObjectRefCore::downcast_ref`] borrows
/// from the reference's object pointer: object types (`ArrayObj`), and managed
/// references that are exactly one object pointer (`Array<T>`, every
/// `#[derive(ObjectRef)]` type). Object types, derived references and
/// containers implement it, not code by hand.
///
/// [`ObjectRefCore::downcast_ref`]: crate::object::ObjectRefCore::downcast_ref
///
/// # Safety
///
/// `Self` must be an object type or exactly one pointer to a live object.
/// `downcast_ref_from_object` must return `Some` only when the object at
/// `*place` is a `Self`, with a reference that stays valid while `place` is
/// borrowed.
#[doc(hidden)]
pub unsafe trait DowncastRefFromObject {
    /// Borrow the object at `*place` as `Self` when it is one.
    ///
    /// # Safety
    ///
    /// `place` must hold a pointer to a live object.
    unsafe fn downcast_ref_from_object(place: &*mut TVMFFIObject) -> Option<&Self>;

    /// The object that `self` is or refers to.
    #[inline(always)]
    fn as_object(&self) -> &crate::object::Object {
        // SAFETY: a reference type is one pointer to a live object (trait contract).
        unsafe { &**std::ptr::from_ref(self).cast::<*const crate::object::Object>() }
    }
}

// An object type borrows the object itself.
unsafe impl<T: crate::object::ObjectCore> DowncastRefFromObject for T {
    #[inline(always)]
    fn as_object(&self) -> &crate::object::Object {
        // SAFETY: an object type starts with its object header.
        unsafe { &*std::ptr::from_ref(self).cast::<crate::object::Object>() }
    }

    #[inline(always)]
    unsafe fn downcast_ref_from_object(place: &*mut TVMFFIObject) -> Option<&Self> {
        let object = *place;
        if unsafe { !crate::object::is_instance_of::<T>((*object).type_index) } {
            return None;
        }
        // SAFETY: the type check establishes T's layout.
        Some(unsafe { &*object.cast::<T>() })
    }
}

/// Borrow the object pointer at `place` as the one-pointer reference type `T`
/// when the object strictly is a `T`: the [`DowncastRefFromObject`] of such a
/// type.
///
/// # Safety
///
/// `place` must hold a pointer to a live object, and `T` must be exactly one
/// object pointer.
#[doc(hidden)]
#[inline(always)]
pub unsafe fn downcast_ref_from_object_in_place<T: RefFromAnyUnchecked>(
    place: &*mut TVMFFIObject,
) -> Option<&T> {
    const {
        assert!(
            std::mem::size_of::<T>() == std::mem::size_of::<*mut TVMFFIObject>(),
            "a reference downcast target must be exactly one object pointer"
        )
    };
    let object = *place;
    // An object header always carries an object-range type index.
    unsafe {
        core::hint::assert_unchecked(
            (*object).type_index >= TypeIndex::kTVMFFIStaticObjectBegin as i32,
        )
    };
    let mut cell = TVMFFIAny::new();
    cell.type_index = unsafe { (*object).type_index };
    cell.data_union.v_obj = object;
    if unsafe { T::container_check_any_strict(&cell) } {
        // SAFETY: `T` is exactly one object pointer, and the check shows the
        // object satisfies `T`.
        Some(unsafe { &*(place as *const *mut TVMFFIObject as *const T) })
    } else {
        None
    }
}

//-----------------------------------------------------
// AnyCompatible impls
//-----------------------------------------------------
unsafe impl AnyCompatible for bool {
    unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
        data.type_index = TypeIndex::kTVMFFIBool as i32;
        data.small_str_len = 0;
        data.data_union.v_int64 = *src as i64;
    }
    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
        data.type_index == TypeIndex::kTVMFFIBool as i32
    }

    unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
        unsafe { data.data_union.v_int64 != 0 }
    }

    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
        data.type_index = TypeIndex::kTVMFFIBool as i32;
        data.small_str_len = 0;
        data.data_union.v_int64 = src as i64;
    }

    unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
        unsafe { data.data_union.v_int64 != 0 }
    }

    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
        if data.type_index == TypeIndex::kTVMFFIBool as i32
            || data.type_index == TypeIndex::kTVMFFIInt as i32
        {
            unsafe { Ok(data.data_union.v_int64 != 0) }
        } else {
            Err(())
        }
    }

    fn type_str() -> String {
        "bool".to_string()
    }
}

macro_rules! impl_any_compatible_for_int {
    ($($int_type:ty),* $(,)?) => {
        $(
            unsafe impl AnyCompatible for $int_type {
                fn type_str() -> String {
                    "int".to_string()
                }

                unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
                    data.type_index = TypeIndex::kTVMFFIInt as i32;
                    data.small_str_len = 0;
                    data.data_union.v_int64 = *src as i64;
                }

                unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
                    data.type_index == TypeIndex::kTVMFFIInt as i32
                }

                unsafe fn match_constraints(data: &TVMFFIAny) -> bool {
                    <$int_type>::try_from(unsafe { data.data_union.v_int64 }).is_ok()
                }

                unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
                    unsafe { data.data_union.v_int64 as $int_type }
                }

                unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
                    data.type_index = TypeIndex::kTVMFFIInt as i32;
                    data.small_str_len = 0;
                    data.data_union.v_int64 = src as i64;
                }

                unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
                    unsafe { data.data_union.v_int64 as $int_type }
                }

                unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
                    if data.type_index == TypeIndex::kTVMFFIInt as i32 ||
                       data.type_index == TypeIndex::kTVMFFIBool as i32 {
                        Ok(unsafe { data.data_union.v_int64 } as $int_type)
                    } else {
                        Err(())
                    }
                }
            }
        )*
    };
}

// Implement AnyCompatible for all integer types
impl_any_compatible_for_int!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);

macro_rules! impl_any_compatible_for_float {
    ($($float_type:ty),* $(,)?) => {
        $(
            unsafe impl AnyCompatible for $float_type {
                fn type_str() -> String {
                    "float".to_string()
                }

                unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
                    data.type_index = TypeIndex::kTVMFFIFloat as i32;
                    data.small_str_len = 0;
                    data.data_union.v_float64 = *src as f64;
                }

                unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
                    data.type_index == TypeIndex::kTVMFFIFloat as i32
                }

                unsafe fn match_constraints(data: &TVMFFIAny) -> bool {
                    let value = unsafe { data.data_union.v_float64 };
                    ((value as $float_type) as f64).to_bits() == value.to_bits()
                }

                unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
                    unsafe { data.data_union.v_float64 as $float_type }
                }

                unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
                    data.type_index = TypeIndex::kTVMFFIFloat as i32;
                    data.small_str_len = 0;
                    data.data_union.v_float64 = src as f64;
                }

                unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
                    unsafe { data.data_union.v_float64 as $float_type }
                }

                unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
                    if data.type_index == TypeIndex::kTVMFFIFloat as i32 {
                        Ok(unsafe { data.data_union.v_float64 } as $float_type)
                    } else if data.type_index == TypeIndex::kTVMFFIInt as i32 ||
                       data.type_index == TypeIndex::kTVMFFIBool as i32 {
                        Ok(unsafe { data.data_union.v_int64 } as $float_type)
                    } else {
                        Err(())
                    }
                }
            }
        )*
    };
}

// Implement AnyCompatible for all float types
impl_any_compatible_for_float!(f32, f64);

// Implement AnyCompatible for `Option<T>`
unsafe impl<T: AnyCompatible> AnyCompatible for Option<T> {
    fn type_str() -> String {
        // make it consistent with c++ representation
        "Optional<".to_string() + T::type_str().as_str() + ">"
    }

    fn type_schema() -> String {
        type_schema("Optional", &[<T as AnyCompatible>::type_schema()])
    }

    fn has_field_layout() -> bool {
        // Only an `Option` of an object reference is the nullable pointer.
        crate::reflection::field_static_type_index(&T::type_str())
            >= TypeIndex::kTVMFFIStaticObjectBegin as i32
    }

    unsafe fn is_undefined(field: *const Self) -> bool {
        // With a tag, all-zero bytes are `None`. A niche-optimized `Option<T>`
        // keeps `T`'s bytes, where all-zero bytes are `None` if `None` looks
        // undefined to `T` (a reference's null pointer), and undefined if
        // `None` sits elsewhere in the niche.
        if std::mem::size_of::<Self>() != std::mem::size_of::<T>() {
            return false;
        }
        let none = std::mem::MaybeUninit::new(None::<T>);
        unsafe { T::is_undefined(field.cast::<T>()) && !T::is_undefined(none.as_ptr().cast::<T>()) }
    }

    unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
        if let Some(value) = src {
            unsafe { T::copy_to_any_view(value, data) };
        } else {
            data.type_index = TypeIndex::kTVMFFINone as i32;
            data.small_str_len = 0;
            data.data_union.v_int64 = 0;
        }
    }

    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
        if let Some(value) = src {
            unsafe { T::move_to_any(value, data) };
        } else {
            data.type_index = TypeIndex::kTVMFFINone as i32;
            data.small_str_len = 0;
            data.data_union.v_int64 = 0;
        }
    }

    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
        unsafe { T::check_any_strict(data) || data.type_index == TypeIndex::kTVMFFINone as i32 }
    }

    unsafe fn match_constraints(data: &TVMFFIAny) -> bool {
        unsafe { data.type_index == TypeIndex::kTVMFFINone as i32 || T::match_constraints(data) }
    }

    unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
        if data.type_index == TypeIndex::kTVMFFINone as i32 {
            None
        } else {
            Some(unsafe { T::copy_from_any_view_after_check(data) })
        }
    }

    unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
        if data.type_index == TypeIndex::kTVMFFINone as i32 {
            None
        } else {
            Some(unsafe { T::move_from_any_after_check(data) })
        }
    }

    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
        if data.type_index == TypeIndex::kTVMFFINone as i32 {
            Ok(None)
        } else {
            unsafe { T::try_cast_from_any_view(data).map(Some) }
        }
    }
}

// Special rule: we convert () to None
// This allows us to effectively pass () around as null value
// note that this is indeed a bit relaxation of the type
// but it is necessary for us to enable void/none interoperability
unsafe impl AnyCompatible for () {
    fn type_str() -> String {
        // make it consistent with c++ representation
        "None".to_string()
    }

    unsafe fn copy_to_any_view(_src: &Self, data: &mut TVMFFIAny) {
        data.type_index = TypeIndex::kTVMFFINone as i32;
        data.small_str_len = 0;
        data.data_union.v_int64 = 0;
    }

    unsafe fn move_to_any(_src: Self, data: &mut TVMFFIAny) {
        data.type_index = TypeIndex::kTVMFFINone as i32;
        data.small_str_len = 0;
        data.data_union.v_int64 = 0;
    }

    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
        data.type_index == TypeIndex::kTVMFFINone as i32
    }

    unsafe fn copy_from_any_view_after_check(_data: &TVMFFIAny) -> Self {}

    unsafe fn move_from_any_after_check(_data: &mut TVMFFIAny) -> Self {}

    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
        if data.type_index == TypeIndex::kTVMFFINone as i32 {
            Ok(())
        } else {
            Err(())
        }
    }
}

unsafe impl AnyCompatible for *mut core::ffi::c_void {
    unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
        data.type_index = TypeIndex::kTVMFFIOpaquePtr as i32;
        data.small_str_len = 0;
        data.data_union.v_ptr = *src;
    }
    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
        data.type_index == TypeIndex::kTVMFFIOpaquePtr as i32
    }

    unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
        unsafe { data.data_union.v_ptr }
    }

    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
        data.type_index = TypeIndex::kTVMFFIOpaquePtr as i32;
        data.small_str_len = 0;
        data.data_union.v_int64 = src as i64;
    }

    unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
        unsafe { data.data_union.v_ptr }
    }

    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
        if data.type_index == TypeIndex::kTVMFFINone as i32 {
            Ok(std::ptr::null_mut())
        } else if data.type_index == TypeIndex::kTVMFFIOpaquePtr as i32 {
            unsafe { Ok(data.data_union.v_ptr) }
        } else {
            Err(())
        }
    }

    fn type_str() -> String {
        "void*".to_string()
    }
}

mod container_element_ops {
    use super::{Any, AnyCompatible, AnyView, TVMFFIAny};

    pub trait Ops: Sized {
        const CONTAINER_IS_ANY: bool = false;

        unsafe fn container_copy_to_any_view(src: &Self, data: &mut TVMFFIAny);
        unsafe fn container_move_to_any(src: Self, data: &mut TVMFFIAny);
        unsafe fn container_check_any_strict(data: &TVMFFIAny) -> bool;
        unsafe fn container_match_constraints(data: &TVMFFIAny) -> bool;
        unsafe fn container_copy_from_any_view_after_check(data: &TVMFFIAny) -> Self;
        unsafe fn container_move_from_any_after_check(data: &mut TVMFFIAny) -> Self;
        unsafe fn container_try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()>;
        fn container_get_mismatch_type_info(data: &TVMFFIAny) -> String;
        fn container_type_str() -> String;
        fn container_type_schema() -> String;
    }

    impl<T: AnyCompatible> Ops for T {
        #[inline(always)]
        unsafe fn container_copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
            unsafe { <T as AnyCompatible>::copy_to_any_view(src, data) }
        }

        #[inline(always)]
        unsafe fn container_move_to_any(src: Self, data: &mut TVMFFIAny) {
            unsafe { <T as AnyCompatible>::move_to_any(src, data) }
        }

        #[inline(always)]
        unsafe fn container_check_any_strict(data: &TVMFFIAny) -> bool {
            unsafe { <T as AnyCompatible>::check_any_strict(data) }
        }
        #[inline(always)]
        unsafe fn container_match_constraints(data: &TVMFFIAny) -> bool {
            unsafe { <T as AnyCompatible>::match_constraints(data) }
        }

        #[inline(always)]
        unsafe fn container_copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
            unsafe { <T as AnyCompatible>::copy_from_any_view_after_check(data) }
        }

        #[inline(always)]
        unsafe fn container_move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
            unsafe { <T as AnyCompatible>::move_from_any_after_check(data) }
        }

        #[inline(always)]
        unsafe fn container_try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
            unsafe { <T as AnyCompatible>::try_cast_from_any_view(data) }
        }

        #[inline(always)]
        fn container_get_mismatch_type_info(data: &TVMFFIAny) -> String {
            <T as AnyCompatible>::get_mismatch_type_info(data)
        }

        #[inline(always)]
        fn container_type_str() -> String {
            <T as AnyCompatible>::type_str()
        }

        #[inline(always)]
        fn container_type_schema() -> String {
            <T as AnyCompatible>::type_schema()
        }
    }

    impl Ops for Any {
        const CONTAINER_IS_ANY: bool = true;

        #[inline(always)]
        unsafe fn container_copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
            *data = *src.as_raw_ffi_any();
        }

        #[inline(always)]
        unsafe fn container_move_to_any(src: Self, data: &mut TVMFFIAny) {
            *data = Any::into_raw_ffi_any(src);
        }

        #[inline(always)]
        unsafe fn container_check_any_strict(_data: &TVMFFIAny) -> bool {
            true
        }
        #[inline(always)]
        unsafe fn container_match_constraints(_data: &TVMFFIAny) -> bool {
            true
        }

        #[inline(always)]
        unsafe fn container_copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
            unsafe { Any::from(AnyView::from_raw_ffi_any(*data)) }
        }

        #[inline(always)]
        unsafe fn container_move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
            unsafe { Any::from_raw_ffi_any(std::mem::replace(data, TVMFFIAny::new())) }
        }

        #[inline(always)]
        unsafe fn container_try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
            Ok(unsafe { Any::from(AnyView::from_raw_ffi_any(*data)) })
        }

        #[inline(always)]
        fn container_get_mismatch_type_info(_data: &TVMFFIAny) -> String {
            "Any".to_string()
        }

        #[inline(always)]
        fn container_type_str() -> String {
            "Any".to_string()
        }

        #[inline(always)]
        fn container_type_schema() -> String {
            <Any as super::TypeSchema>::type_schema()
        }
    }
}

/// The type key of the runtime type index `type_index`.
pub(crate) fn runtime_type_key(type_index: i32) -> String {
    unsafe {
        let info = TVMFFIGetTypeInfo(type_index);
        assert!(!info.is_null(), "TVMFFIGetTypeInfo returned null");
        (*info).type_key.as_str().to_string()
    }
}

/// Writes a type schema, `{"type":"<origin>"}` or, with type arguments,
/// `{"type":"<origin>","args":[...]}`.
pub(crate) fn type_schema(origin: &str, args: &[String]) -> String {
    if args.is_empty() {
        format!(r#"{{"type":"{origin}"}}"#)
    } else {
        format!(r#"{{"type":"{origin}","args":[{}]}}"#, args.join(","))
    }
}

/// The metadata recorded for a function or field of type schema
/// `type_schema`: `{"type_schema":<type_schema as a JSON string>}`.
pub(crate) fn type_schema_metadata(type_schema: &str) -> String {
    format!(r#"{{"type_schema":{}}}"#, escape_string_json(type_schema))
}

/// `text` as a JSON string literal, escaped so that the metadata matches the
/// C++ runtime's byte for byte.
fn escape_string_json(text: &str) -> String {
    let mut out = String::with_capacity(text.len() + 2);
    out.push('"');
    for ch in text.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '/' => out.push_str("\\/"),
            '\u{8}' => out.push_str("\\b"),
            '\u{c}' => out.push_str("\\f"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            ch if (ch as u32) < 0x20 || ch == '\u{7f}' => {
                out.push_str(&format!("\\u{:04x}", ch as u32))
            }
            ch => out.push(ch),
        }
    }
    out.push('"');
    out
}

/// The type schema of a function parameter or return type.
///
/// This is [`AnyCompatible::type_schema`] for a type that converts through
/// [`Any`], and `{"type":"Any"}` for `Any` and `AnyView` themselves.
pub(crate) trait TypeSchema {
    fn type_schema() -> String;
}

impl<T: AnyCompatible> TypeSchema for T {
    fn type_schema() -> String {
        <T as AnyCompatible>::type_schema()
    }
}

impl TypeSchema for Any {
    fn type_schema() -> String {
        type_schema("Any", &[])
    }
}

impl TypeSchema for AnyView<'_> {
    fn type_schema() -> String {
        type_schema("Any", &[])
    }
}