godot_core/meta/godot_convert/
impls.rs

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
/*
 * Copyright (c) godot-rust; Bromeon and contributors.
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

use crate::builtin::{Array, Variant};
use crate::meta::error::{ConvertError, ErrorKind, FromFfiError, FromVariantError};
use crate::meta::{
    ArrayElement, ClassName, FromGodot, GodotConvert, GodotNullableFfi, GodotType,
    PropertyHintInfo, PropertyInfo, ToGodot,
};
use crate::registry::method::MethodParamOrReturnInfo;
use godot_ffi as sys;

// The following ToGodot/FromGodot/Convert impls are auto-generated for each engine type, co-located with their definitions:
// - enum
// - const/mut pointer to native struct

// ----------------------------------------------------------------------------------------------------------------------------------------------
// Option<T>

impl<T> GodotType for Option<T>
where
    T: GodotType,
    T::Ffi: GodotNullableFfi,
    for<'f> T::ToFfi<'f>: GodotNullableFfi,
{
    type Ffi = T::Ffi;

    type ToFfi<'f> = T::ToFfi<'f>;

    fn to_ffi(&self) -> Self::ToFfi<'_> {
        GodotNullableFfi::flatten_option(self.as_ref().map(|t| t.to_ffi()))
    }

    fn into_ffi(self) -> Self::Ffi {
        GodotNullableFfi::flatten_option(self.map(|t| t.into_ffi()))
    }

    fn try_from_ffi(ffi: Self::Ffi) -> Result<Self, ConvertError> {
        if ffi.is_null() {
            return Ok(None);
        }

        GodotType::try_from_ffi(ffi).map(Some)
    }

    fn from_ffi(ffi: Self::Ffi) -> Self {
        if ffi.is_null() {
            return None;
        }

        Some(GodotType::from_ffi(ffi))
    }

    fn param_metadata() -> sys::GDExtensionClassMethodArgumentMetadata {
        T::param_metadata()
    }

    fn class_name() -> ClassName {
        T::class_name()
    }

    fn property_info(property_name: &str) -> PropertyInfo {
        T::property_info(property_name)
    }

    fn property_hint_info() -> PropertyHintInfo {
        T::property_hint_info()
    }

    fn argument_info(property_name: &str) -> MethodParamOrReturnInfo {
        T::argument_info(property_name)
    }

    fn return_info() -> Option<MethodParamOrReturnInfo> {
        T::return_info()
    }

    fn godot_type_name() -> String {
        T::godot_type_name()
    }
}

impl<T: GodotConvert> GodotConvert for Option<T>
where
    Option<T::Via>: GodotType,
{
    type Via = Option<T::Via>;
}

impl<T: ToGodot> ToGodot for Option<T>
where
    Option<T::Via>: GodotType,
    for<'v, 'f> T::ToVia<'v>: GodotType<
        // Associated types need to be nullable.
        Ffi: GodotNullableFfi,
        ToFfi<'f>: GodotNullableFfi,
    >,
{
    type ToVia<'v> = Option<T::ToVia<'v>>
    // type ToVia<'v> = Self::Via
    where Self: 'v;

    fn to_godot(&self) -> Self::ToVia<'_> {
        self.as_ref().map(ToGodot::to_godot)
    }

    fn to_variant(&self) -> Variant {
        match self {
            Some(inner) => inner.to_variant(),
            None => Variant::nil(),
        }
    }
}

impl<T: FromGodot> FromGodot for Option<T>
where
    Option<T::Via>: GodotType,
{
    fn try_from_godot(via: Self::Via) -> Result<Self, ConvertError> {
        match via {
            Some(via) => T::try_from_godot(via).map(Some),
            None => Ok(None),
        }
    }

    fn from_godot(via: Self::Via) -> Self {
        via.map(T::from_godot)
    }

    fn try_from_variant(variant: &Variant) -> Result<Self, ConvertError> {
        // Note: this forwards to T::Via, not Self::Via (= Option<T>::Via).
        // For Option<T>, there is a blanket impl GodotType, so case differentiations are not possible.
        if T::Via::qualifies_as_special_none(variant) {
            return Ok(None);
        }

        if variant.is_nil() {
            return Ok(None);
        }

        let value = T::try_from_variant(variant)?;
        Ok(Some(value))
    }

    fn from_variant(variant: &Variant) -> Self {
        if variant.is_nil() {
            return None;
        }

        Some(T::from_variant(variant))
    }
}

// ----------------------------------------------------------------------------------------------------------------------------------------------
// Scalars

macro_rules! impl_godot_scalar {
    ($T:ty as $Via:ty, $err:path, $param_metadata:expr) => {
        impl GodotType for $T {
            type Ffi = $Via;
            type ToFfi<'f> = $Via;

            fn to_ffi(&self) -> Self::ToFfi<'_> {
                (*self).into()
            }

            fn into_ffi(self) -> Self::Ffi {
                self.into()
            }

            fn try_from_ffi(ffi: Self::Ffi) -> Result<Self, ConvertError> {
                Self::try_from(ffi).map_err(|_rust_err| {
                    // rust_err is something like "out of range integral type conversion attempted", not adding extra information.
                    // TODO consider passing value into error message, but how thread-safely? don't eagerly convert to string.
                    $err.into_error(ffi)
                })
            }

            impl_godot_scalar!(@shared_fns; $Via, $param_metadata);
        }

        // For integer types, we can validate the conversion.
        impl ArrayElement for $T {
            fn debug_validate_elements(array: &Array<Self>) -> Result<(), ConvertError> {
                array.debug_validate_elements()
            }
        }

        impl_godot_scalar!(@shared_traits; $T);
    };

    ($T:ty as $Via:ty, $param_metadata:expr; lossy) => {
        impl GodotType for $T {
            type Ffi = $Via;
            type ToFfi<'f> = $Via;

            fn to_ffi(&self) -> Self::ToFfi<'_> {
                *self as $Via
            }

            fn into_ffi(self) -> Self::Ffi {
                self as $Via
            }

            fn try_from_ffi(ffi: Self::Ffi) -> Result<Self, ConvertError> {
                Ok(ffi as $T)
            }

            impl_godot_scalar!(@shared_fns; $Via, $param_metadata);
        }

        // For f32, conversion from f64 is lossy but will always succeed. Thus no debug validation needed.
        impl ArrayElement for $T {}

        impl_godot_scalar!(@shared_traits; $T);
    };

    (@shared_fns; $Via:ty, $param_metadata:expr) => {
        fn param_metadata() -> sys::GDExtensionClassMethodArgumentMetadata {
            $param_metadata
        }

        fn godot_type_name() -> String {
            <$Via as GodotType>::godot_type_name()
        }
    };

    (@shared_traits; $T:ty) => {
        impl GodotConvert for $T {
            type Via = $T;
        }

        impl ToGodot for $T {
            type ToVia<'v> = Self::Via;

            fn to_godot(&self) -> Self::ToVia<'_> {
               *self
            }
        }

        impl FromGodot for $T {
            fn try_from_godot(via: Self::Via) -> Result<Self, ConvertError> {
                Ok(via)
            }
        }

        $crate::impl_asarg_by_value!($T);
    };
}

// `GodotType` for these three is implemented in `godot-core/src/builtin/variant/impls.rs`.
crate::meta::impl_godot_as_self!(bool);
crate::meta::impl_godot_as_self!(i64);
crate::meta::impl_godot_as_self!(f64);
crate::meta::impl_godot_as_self!(());

// Also implements ArrayElement.
impl_godot_scalar!(
    i8 as i64,
    FromFfiError::I8,
    sys::GDEXTENSION_METHOD_ARGUMENT_METADATA_INT_IS_INT8
);
impl_godot_scalar!(
    u8 as i64,
    FromFfiError::U8,
    sys::GDEXTENSION_METHOD_ARGUMENT_METADATA_INT_IS_UINT8
);
impl_godot_scalar!(
    i16 as i64,
    FromFfiError::I16,
    sys::GDEXTENSION_METHOD_ARGUMENT_METADATA_INT_IS_INT16
);
impl_godot_scalar!(
    u16 as i64,
    FromFfiError::U16,
    sys::GDEXTENSION_METHOD_ARGUMENT_METADATA_INT_IS_UINT16
);
impl_godot_scalar!(
    i32 as i64,
    FromFfiError::I32,
    sys::GDEXTENSION_METHOD_ARGUMENT_METADATA_INT_IS_INT32
);
impl_godot_scalar!(
    u32 as i64,
    FromFfiError::U32,
    sys::GDEXTENSION_METHOD_ARGUMENT_METADATA_INT_IS_UINT32
);
impl_godot_scalar!(
    f32 as f64,
    sys::GDEXTENSION_METHOD_ARGUMENT_METADATA_REAL_IS_FLOAT;
    lossy
);

// ----------------------------------------------------------------------------------------------------------------------------------------------
// u64: manually implemented, to ensure that type is not altered during conversion.

impl GodotType for u64 {
    type Ffi = i64;
    type ToFfi<'f> = i64;

    fn to_ffi(&self) -> Self::ToFfi<'_> {
        *self as i64
    }

    fn into_ffi(self) -> Self::Ffi {
        self as i64
    }

    fn try_from_ffi(ffi: Self::Ffi) -> Result<Self, ConvertError> {
        // Ok(ffi as u64)
        Self::try_from(ffi).map_err(|_rust_err| FromFfiError::U64.into_error(ffi))
    }

    impl_godot_scalar!(@shared_fns; i64, sys::GDEXTENSION_METHOD_ARGUMENT_METADATA_INT_IS_UINT64);
}

impl GodotConvert for u64 {
    type Via = u64;
}

impl ToGodot for u64 {
    type ToVia<'v> = u64;

    fn to_godot(&self) -> Self::ToVia<'_> {
        *self
    }

    fn to_variant(&self) -> Variant {
        // TODO panic doesn't fit the trait's infallibility too well; maybe in the future try_to_godot/try_to_variant() methods are possible.
        i64::try_from(*self)
            .map(|v| v.to_variant())
            .unwrap_or_else(|_| {
                panic!("to_variant(): u64 value {} is not representable inside Variant, which can only store i64 integers", self)
            })
    }
}

impl FromGodot for u64 {
    fn try_from_godot(via: Self::Via) -> Result<Self, ConvertError> {
        Ok(via)
    }

    fn try_from_variant(variant: &Variant) -> Result<Self, ConvertError> {
        // Fail for values that are not representable as u64.
        let value = variant.try_to::<i64>()?;

        u64::try_from(value).map_err(|_rust_err| {
            // TODO maybe use better error enumerator
            FromVariantError::BadValue.into_error(value)
        })
    }
}

// ----------------------------------------------------------------------------------------------------------------------------------------------
// Collections

impl<T: ArrayElement> GodotConvert for Vec<T> {
    type Via = Array<T>;
}

impl<T: ArrayElement> ToGodot for Vec<T> {
    type ToVia<'v> = Array<T>;

    fn to_godot(&self) -> Self::ToVia<'_> {
        Array::from(self.as_slice())
    }
}

impl<T: ArrayElement> FromGodot for Vec<T> {
    fn try_from_godot(via: Self::Via) -> Result<Self, ConvertError> {
        Ok(via.iter_shared().collect())
    }
}

impl<T: ArrayElement, const LEN: usize> GodotConvert for [T; LEN] {
    type Via = Array<T>;
}

impl<T: ArrayElement, const LEN: usize> ToGodot for [T; LEN] {
    type ToVia<'v> = Array<T>;

    fn to_godot(&self) -> Self::ToVia<'_> {
        Array::from(self)
    }
}

impl<T: ArrayElement, const LEN: usize> FromGodot for [T; LEN] {
    fn try_from_godot(via: Self::Via) -> Result<Self, ConvertError> {
        let via_len = via.len(); // Caching this avoids an FFI call
        if via_len != LEN {
            let message =
                format!("Array<T> of length {via_len} cannot be stored in [T; {LEN}] Rust array");
            return Err(ConvertError::with_kind_value(
                ErrorKind::Custom(Some(message.into())),
                via,
            ));
        }

        let mut option_array = [const { None }; LEN];

        for (element, destination) in via.iter_shared().zip(&mut option_array) {
            *destination = Some(element);
        }

        let array = option_array.map(|some| {
            some.expect(
                "Elements were removed from Array during `iter_shared()`, this is not allowed",
            )
        });

        Ok(array)
    }
}

impl<T: ArrayElement> GodotConvert for &[T] {
    type Via = Array<T>;
}

impl<T: ArrayElement> ToGodot for &[T] {
    type ToVia<'v> = Array<T>
    where Self: 'v;

    fn to_godot(&self) -> Self::ToVia<'_> {
        Array::from(*self)
    }
}

// ----------------------------------------------------------------------------------------------------------------------------------------------
// Raw pointers

// const void* is used in some APIs like OpenXrApiExtension::transform_from_pose().
// void* is used by ScriptExtension::instance_create().
// Other impls for raw pointers are generated for native structures.

macro_rules! impl_pointer_convert {
    ($Ptr:ty) => {
        impl GodotConvert for $Ptr {
            type Via = i64;
        }

        impl ToGodot for $Ptr {
            type ToVia<'v> = i64;

            fn to_godot(&self) -> Self::ToVia<'_> {
                *self as i64
            }
        }

        impl FromGodot for $Ptr {
            fn try_from_godot(via: Self::Via) -> Result<Self, ConvertError> {
                Ok(via as Self)
            }
        }
    };
}

impl_pointer_convert!(*const std::ffi::c_void);
impl_pointer_convert!(*mut std::ffi::c_void);

// Some other pointer types are used by various other methods, see https://github.com/godot-rust/gdext/issues/677
// TODO: Find better solution to this, this may easily break still if godot decides to add more pointer arguments.

impl_pointer_convert!(*mut *const u8);
impl_pointer_convert!(*mut i32);
impl_pointer_convert!(*mut f64);
impl_pointer_convert!(*mut u8);
impl_pointer_convert!(*const u8);