Skip to main content

tvm_ffi/
type_traits.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 */
19use crate::any::{Any, AnyView};
20use tvm_ffi_sys::TVMFFITypeIndex as TypeIndex;
21use tvm_ffi_sys::{TVMFFIAny, TVMFFIGetTypeInfo};
22
23//-----------------------------------------------------
24// AnyCompatible
25//-----------------------------------------------------
26/// Trait to enable a value to be compatible with Any
27/// Enables TryFrom/Into AnyView/Any
28pub unsafe trait AnyCompatible: Sized {
29    /// Whether the `AnyView -> Self` conversion matches one exact leaf type.
30    ///
31    /// If this is `true`, [`Self::match_any_exact_type_index`] must always
32    /// return the same index for the process lifetime, and conversion from an
33    /// object-backed `AnyView` must succeed if and only if its runtime type
34    /// index equals that index. Matching must not depend on any other part of
35    /// the value. `match_any!` may use this contract to skip conversions for
36    /// all other arms.
37    #[doc(hidden)]
38    const MATCH_ANY_EXACT: bool = false;
39
40    /// Return the sole runtime object type index accepted by this conversion.
41    #[doc(hidden)]
42    fn match_any_exact_type_index() -> i32 {
43        unreachable!("MATCH_ANY_EXACT is false")
44    }
45
46    /// Whether `field`, which holds a value of this type or all-zero bytes,
47    /// holds all-zero bytes that are no value of this type, as a null object
48    /// reference, a string of type index None or a zero device type: a field
49    /// that a creator left undefined for reflection to set, as C++ `UnsafeInit`
50    /// leaves a reference undefined (null). Unlike a C++ undefined reference,
51    /// it is no value; a nullable reference is `Option<T>`, whose `None` is a
52    /// defined value.
53    ///
54    /// The field setter writes an undefined field without dropping it, the
55    /// field getter reads it as None, and the object's deleter skips it. The default,
56    /// false, fits a type whose all-zero bytes are a value whose drop does
57    /// nothing, as a scalar's, `Any`'s or `Optional`'s.
58    ///
59    /// # Safety
60    ///
61    /// `field` points to a value of this type or to all-zero bytes. An
62    /// implementation reads only bytes that each value initializes and, when
63    /// `Option<Self>` is niche-optimized, that its `None` initializes too.
64    #[inline]
65    unsafe fn is_undefined(field: *const Self) -> bool {
66        let _ = field;
67        false
68    }
69
70    /// the value to copy to TVMFFIAny
71    unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny);
72    /// consume the value to move to Any
73    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny);
74    // check if the value is compatible with the type
75    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool;
76
77    /// Copy value from TVMFFIAny after checking
78    /// caller must ensure that the value is compatible with the type
79    unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self;
80    /// the value to move from TVMFFIAny
81    /// NOTE: pay very careful attention to avoid memory leak!
82    /// - When calling from managed Any, remember to use std::mem::ManuallyDrop
83    unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self;
84    /// try to cast the value from AnyView
85    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()>;
86    /// Get the type key of a type when TryCastFromAnyView fails.
87    fn get_mismatch_type_info(data: &TVMFFIAny) -> String {
88        unsafe {
89            let info = TVMFFIGetTypeInfo(data.type_index);
90            assert!(!info.is_null(), "TVMFFIGetTypeInfo returned null");
91            (*info).type_key.as_str().to_string()
92        }
93    }
94    /// the type string of the type
95    fn type_str() -> String;
96
97    /// The type schema of the type: the JSON object C++
98    /// `TypeTraits<T>::TypeSchema` writes, which the type schemas of functions
99    /// and fields embed.
100    ///
101    /// The default, `{"type":"<type_str>"}`, fits a type whose type string is
102    /// its type key, as for object references.
103    fn type_schema() -> String {
104        type_schema(&Self::type_str(), &[])
105    }
106
107    /// Borrow `self` into an owned [`Any`], increfing object-backed values.
108    ///
109    /// The by-reference counterpart of `Any::from(value)`, for fields reached
110    /// through a `Deref` into shared object storage. `impl From<&T> for Any`
111    /// cannot be added instead: `&` is fundamental, so a downstream crate may
112    /// implement `AnyCompatible` for its own `&T` and the two impls overlap
113    /// (E0119).
114    #[inline]
115    fn to_any(&self) -> Any {
116        AnyView::from(self).into()
117    }
118}
119
120/// Writes a type schema, `{"type":"<origin>"}` or, with type arguments,
121/// `{"type":"<origin>","args":[...]}`, as C++ `TypeTraits<T>::TypeSchema` does.
122pub(crate) fn type_schema(origin: &str, args: &[String]) -> String {
123    if args.is_empty() {
124        format!(r#"{{"type":"{origin}"}}"#)
125    } else {
126        format!(r#"{{"type":"{origin}","args":[{}]}}"#, args.join(","))
127    }
128}
129
130/// The metadata C++ records for a function or field of type schema
131/// `type_schema`: `{"type_schema":<type_schema as a JSON string>}`.
132pub(crate) fn type_schema_metadata(type_schema: &str) -> String {
133    format!(r#"{{"type_schema":{}}}"#, escape_string_json(type_schema))
134}
135
136/// `text` as a JSON string literal, escaped as C++ `EscapeStringJSON`
137/// (`string.h`) escapes it, so that metadata matches the C++ one byte for byte.
138fn escape_string_json(text: &str) -> String {
139    let mut out = String::with_capacity(text.len() + 2);
140    out.push('"');
141    for ch in text.chars() {
142        match ch {
143            '"' => out.push_str("\\\""),
144            '\\' => out.push_str("\\\\"),
145            '/' => out.push_str("\\/"),
146            '\u{8}' => out.push_str("\\b"),
147            '\u{c}' => out.push_str("\\f"),
148            '\n' => out.push_str("\\n"),
149            '\r' => out.push_str("\\r"),
150            '\t' => out.push_str("\\t"),
151            ch if (ch as u32) < 0x20 || ch == '\u{7f}' => {
152                out.push_str(&format!("\\u{:04x}", ch as u32))
153            }
154            ch => out.push(ch),
155        }
156    }
157    out.push('"');
158    out
159}
160
161/// The type schema of a function parameter or return type.
162///
163/// This is [`AnyCompatible::type_schema`] for a type that converts through
164/// [`Any`], and `{"type":"Any"}` for `Any` and `AnyView` themselves, as C++
165/// `details::TypeSchema<T>` writes them.
166pub(crate) trait TypeSchema {
167    fn type_schema() -> String;
168}
169
170impl<T: AnyCompatible> TypeSchema for T {
171    fn type_schema() -> String {
172        <T as AnyCompatible>::type_schema()
173    }
174}
175
176impl TypeSchema for Any {
177    fn type_schema() -> String {
178        type_schema("Any", &[])
179    }
180}
181
182impl TypeSchema for AnyView<'_> {
183    fn type_schema() -> String {
184        type_schema("Any", &[])
185    }
186}
187
188/// Marker for a value that can be stored in an FFI container.
189///
190/// This is an implementation detail of [`crate::Array`] and [`crate::Map`].
191/// Users should implement [`AnyCompatible`]; the blanket implementation below
192/// then makes that type a container element automatically. [`Any`] is handled
193/// separately so heterogeneous containers such as `Array<Any>` also work.
194///
195/// The private supertrait seals this marker and owns all conversion operations,
196/// keeping them out of the user-facing trait API.
197#[doc(hidden)]
198pub trait ContainerElement: container_element_ops::Ops {}
199
200impl<T: AnyCompatible> ContainerElement for T {}
201impl ContainerElement for Any {}
202
203mod container_element_ops {
204    use super::{Any, AnyCompatible, AnyView, TVMFFIAny};
205
206    pub trait Ops: Sized {
207        const CONTAINER_IS_ANY: bool = false;
208
209        unsafe fn container_copy_to_any_view(src: &Self, data: &mut TVMFFIAny);
210        unsafe fn container_move_to_any(src: Self, data: &mut TVMFFIAny);
211        unsafe fn container_check_any_strict(data: &TVMFFIAny) -> bool;
212        unsafe fn container_copy_from_any_view_after_check(data: &TVMFFIAny) -> Self;
213        unsafe fn container_move_from_any_after_check(data: &mut TVMFFIAny) -> Self;
214        unsafe fn container_try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()>;
215        fn container_get_mismatch_type_info(data: &TVMFFIAny) -> String;
216        fn container_type_str() -> String;
217        fn container_type_schema() -> String;
218    }
219
220    impl<T: AnyCompatible> Ops for T {
221        #[inline]
222        unsafe fn container_copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
223            <T as AnyCompatible>::copy_to_any_view(src, data)
224        }
225
226        #[inline]
227        unsafe fn container_move_to_any(src: Self, data: &mut TVMFFIAny) {
228            <T as AnyCompatible>::move_to_any(src, data)
229        }
230
231        #[inline]
232        unsafe fn container_check_any_strict(data: &TVMFFIAny) -> bool {
233            <T as AnyCompatible>::check_any_strict(data)
234        }
235
236        #[inline]
237        unsafe fn container_copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
238            <T as AnyCompatible>::copy_from_any_view_after_check(data)
239        }
240
241        #[inline]
242        unsafe fn container_move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
243            <T as AnyCompatible>::move_from_any_after_check(data)
244        }
245
246        #[inline]
247        unsafe fn container_try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
248            <T as AnyCompatible>::try_cast_from_any_view(data)
249        }
250
251        #[inline]
252        fn container_get_mismatch_type_info(data: &TVMFFIAny) -> String {
253            <T as AnyCompatible>::get_mismatch_type_info(data)
254        }
255
256        #[inline]
257        fn container_type_str() -> String {
258            <T as AnyCompatible>::type_str()
259        }
260
261        #[inline]
262        fn container_type_schema() -> String {
263            <T as AnyCompatible>::type_schema()
264        }
265    }
266
267    impl Ops for Any {
268        const CONTAINER_IS_ANY: bool = true;
269
270        #[inline]
271        unsafe fn container_copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
272            *data = *src.as_raw_ffi_any();
273        }
274
275        #[inline]
276        unsafe fn container_move_to_any(src: Self, data: &mut TVMFFIAny) {
277            *data = Any::into_raw_ffi_any(src);
278        }
279
280        #[inline]
281        unsafe fn container_check_any_strict(_data: &TVMFFIAny) -> bool {
282            true
283        }
284
285        #[inline]
286        unsafe fn container_copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
287            Any::from(AnyView::from_raw_ffi_any(*data))
288        }
289
290        #[inline]
291        unsafe fn container_move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
292            Any::from_raw_ffi_any(std::mem::replace(data, TVMFFIAny::new()))
293        }
294
295        #[inline]
296        unsafe fn container_try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
297            Ok(Any::from(AnyView::from_raw_ffi_any(*data)))
298        }
299
300        #[inline]
301        fn container_get_mismatch_type_info(_data: &TVMFFIAny) -> String {
302            "Any".to_string()
303        }
304
305        #[inline]
306        fn container_type_str() -> String {
307            "Any".to_string()
308        }
309
310        #[inline]
311        fn container_type_schema() -> String {
312            <Any as super::TypeSchema>::type_schema()
313        }
314    }
315}
316
317/// AnyCompatible for bool
318unsafe impl AnyCompatible for bool {
319    unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
320        data.type_index = TypeIndex::kTVMFFIBool as i32;
321        data.small_str_len = 0;
322        data.data_union.v_int64 = *src as i64;
323    }
324    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
325        data.type_index == TypeIndex::kTVMFFIBool as i32
326    }
327
328    unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
329        data.data_union.v_int64 != 0
330    }
331
332    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
333        data.type_index = TypeIndex::kTVMFFIBool as i32;
334        data.small_str_len = 0;
335        data.data_union.v_int64 = src as i64;
336    }
337
338    unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
339        data.data_union.v_int64 != 0
340    }
341
342    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
343        if data.type_index == TypeIndex::kTVMFFIBool as i32
344            || data.type_index == TypeIndex::kTVMFFIInt as i32
345        {
346            unsafe { Ok(data.data_union.v_int64 != 0) }
347        } else {
348            Err(())
349        }
350    }
351
352    fn type_str() -> String {
353        "bool".to_string()
354    }
355}
356
357/// Macro to implement AnyCompatible for integer types
358macro_rules! impl_any_compatible_for_int {
359    ($($int_type:ty),* $(,)?) => {
360        $(
361            unsafe impl AnyCompatible for $int_type {
362                fn type_str() -> String {
363                    "int".to_string()
364                }
365
366                unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
367                    data.type_index = TypeIndex::kTVMFFIInt as i32;
368                    data.small_str_len = 0;
369                    data.data_union.v_int64 = *src as i64;
370                }
371
372                unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
373                    data.type_index == TypeIndex::kTVMFFIInt as i32
374                }
375
376                unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
377                    data.data_union.v_int64 as $int_type
378                }
379
380                unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
381                    data.type_index = TypeIndex::kTVMFFIInt as i32;
382                    data.small_str_len = 0;
383                    data.data_union.v_int64 = src as i64;
384                }
385
386                unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
387                    data.data_union.v_int64 as $int_type
388                }
389
390                unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
391                    if data.type_index == TypeIndex::kTVMFFIInt as i32 ||
392                       data.type_index == TypeIndex::kTVMFFIBool as i32 {
393                        Ok(data.data_union.v_int64 as $int_type)
394                    } else {
395                        Err(())
396                    }
397                }
398            }
399        )*
400    };
401}
402
403// Implement AnyCompatible for all integer types
404impl_any_compatible_for_int!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
405
406// Implement AnyCompatible for `Option<T>`
407unsafe impl<T: AnyCompatible> AnyCompatible for Option<T> {
408    fn type_str() -> String {
409        // make it consistent with c++ representation
410        "Optional<".to_string() + T::type_str().as_str() + ">"
411    }
412
413    fn type_schema() -> String {
414        type_schema("Optional", &[<T as AnyCompatible>::type_schema()])
415    }
416
417    unsafe fn is_undefined(field: *const Self) -> bool {
418        // With a tag, all-zero bytes are `None`. A niche-optimized `Option<T>`
419        // keeps `T`'s bytes, where all-zero bytes are `None` if `None` looks
420        // undefined to `T` (a reference's null pointer, a device's zero type),
421        // and undefined if `None` sits elsewhere in the niche.
422        if std::mem::size_of::<Self>() != std::mem::size_of::<T>() {
423            return false;
424        }
425        let none = std::mem::MaybeUninit::new(None::<T>);
426        T::is_undefined(field.cast::<T>()) && !T::is_undefined(none.as_ptr().cast::<T>())
427    }
428
429    unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
430        if let Some(ref value) = src {
431            T::copy_to_any_view(value, data);
432        } else {
433            data.type_index = TypeIndex::kTVMFFINone as i32;
434            data.small_str_len = 0;
435            data.data_union.v_int64 = 0;
436        }
437    }
438
439    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
440        if let Some(value) = src {
441            T::move_to_any(value, data);
442        } else {
443            data.type_index = TypeIndex::kTVMFFINone as i32;
444            data.small_str_len = 0;
445            data.data_union.v_int64 = 0;
446        }
447    }
448
449    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
450        return T::check_any_strict(data) || data.type_index == TypeIndex::kTVMFFINone as i32;
451    }
452
453    unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
454        if data.type_index == TypeIndex::kTVMFFINone as i32 {
455            None
456        } else {
457            Some(T::copy_from_any_view_after_check(data))
458        }
459    }
460
461    unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
462        if data.type_index == TypeIndex::kTVMFFINone as i32 {
463            None
464        } else {
465            Some(T::move_from_any_after_check(data))
466        }
467    }
468
469    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
470        if data.type_index == TypeIndex::kTVMFFINone as i32 {
471            Ok(None)
472        } else {
473            T::try_cast_from_any_view(data).map(Some)
474        }
475    }
476}
477
478/// AnyCompatible for void*
479unsafe impl AnyCompatible for *mut core::ffi::c_void {
480    unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
481        data.type_index = TypeIndex::kTVMFFIOpaquePtr as i32;
482        data.small_str_len = 0;
483        data.data_union.v_ptr = *src;
484    }
485    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
486        data.type_index == TypeIndex::kTVMFFIOpaquePtr as i32
487    }
488
489    unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
490        data.data_union.v_ptr
491    }
492
493    unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
494        data.type_index = TypeIndex::kTVMFFIOpaquePtr as i32;
495        data.small_str_len = 0;
496        data.data_union.v_int64 = src as i64;
497    }
498
499    unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
500        data.data_union.v_ptr
501    }
502
503    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
504        if data.type_index == TypeIndex::kTVMFFINone as i32 {
505            Ok(std::ptr::null_mut())
506        } else if data.type_index == TypeIndex::kTVMFFIOpaquePtr as i32 {
507            unsafe { Ok(data.data_union.v_ptr) }
508        } else {
509            Err(())
510        }
511    }
512
513    fn type_str() -> String {
514        "void*".to_string()
515    }
516}
517
518/// Macro to implement AnyCompatible for integer types
519macro_rules! impl_any_compatible_for_float {
520    ($($float_type:ty),* $(,)?) => {
521        $(
522            unsafe impl AnyCompatible for $float_type {
523                fn type_str() -> String {
524                    "float".to_string()
525                }
526
527                unsafe fn copy_to_any_view(src: &Self, data: &mut TVMFFIAny) {
528                    data.type_index = TypeIndex::kTVMFFIFloat as i32;
529                    data.small_str_len = 0;
530                    data.data_union.v_float64 = *src as f64;
531                }
532
533                unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
534                    data.type_index == TypeIndex::kTVMFFIFloat as i32
535                }
536
537                unsafe fn copy_from_any_view_after_check(data: &TVMFFIAny) -> Self {
538                    data.data_union.v_float64 as $float_type
539                }
540
541                unsafe fn move_to_any(src: Self, data: &mut TVMFFIAny) {
542                    data.type_index = TypeIndex::kTVMFFIFloat as i32;
543                    data.small_str_len = 0;
544                    data.data_union.v_float64 = src as f64;
545                }
546
547                unsafe fn move_from_any_after_check(data: &mut TVMFFIAny) -> Self {
548                    data.data_union.v_float64 as $float_type
549                }
550
551                unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
552                    if data.type_index == TypeIndex::kTVMFFIFloat as i32 {
553                        Ok(data.data_union.v_float64 as $float_type)
554                    } else if data.type_index == TypeIndex::kTVMFFIInt as i32 ||
555                       data.type_index == TypeIndex::kTVMFFIBool as i32 {
556                        Ok(data.data_union.v_int64 as $float_type)
557                    } else {
558                        Err(())
559                    }
560                }
561            }
562        )*
563    };
564}
565
566// Implement AnyCompatible for all float types
567impl_any_compatible_for_float!(f32, f64);
568
569// Special rule: we convert () to None
570// This allows us to effectively pass () around as null value
571// note that this is indeed a bit relaxation of the type
572// but it is necessary for us to enable void/none interoperability
573unsafe impl AnyCompatible for () {
574    fn type_str() -> String {
575        // make it consistent with c++ representation
576        "None".to_string()
577    }
578
579    unsafe fn copy_to_any_view(_src: &Self, data: &mut TVMFFIAny) {
580        data.type_index = TypeIndex::kTVMFFINone as i32;
581        data.small_str_len = 0;
582        data.data_union.v_int64 = 0;
583    }
584
585    unsafe fn move_to_any(_src: Self, data: &mut TVMFFIAny) {
586        data.type_index = TypeIndex::kTVMFFINone as i32;
587        data.small_str_len = 0;
588        data.data_union.v_int64 = 0;
589    }
590
591    unsafe fn check_any_strict(data: &TVMFFIAny) -> bool {
592        return data.type_index == TypeIndex::kTVMFFINone as i32;
593    }
594
595    unsafe fn copy_from_any_view_after_check(_data: &TVMFFIAny) -> Self {
596        ()
597    }
598
599    unsafe fn move_from_any_after_check(_data: &mut TVMFFIAny) -> Self {
600        ()
601    }
602
603    unsafe fn try_cast_from_any_view(data: &TVMFFIAny) -> Result<Self, ()> {
604        if data.type_index == TypeIndex::kTVMFFINone as i32 {
605            Ok(())
606        } else {
607            Err(())
608        }
609    }
610}