bevy_mod_scripting_bindings 0.24.0

Core traits and structures required for smoothly interfacing with other languages in a generic way
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
//! This module contains the [`FromScript`] trait and its implemenations.

use super::bound::BoundFields;
use super::script_function::{DynamicScriptFunction, DynamicScriptFunctionMut};
use crate::{
    EnumVariantRef, ReflectReference, ScriptValue, construct::construct_reference,
    error::InteropError, script_value::VariadicTuple,
};
use bevy_mod_scripting_world::{CallScope, WorldGuard};
use bevy_platform::collections::{HashMap, HashSet};
use bevy_reflect::{FromReflect, Reflect};
use nonmax::NonMaxU32;
use std::{
    any::TypeId,
    collections::VecDeque,
    ffi::OsString,
    ops::{Deref, DerefMut},
    path::PathBuf,
};

/// Describes the procedure for constructing a value of type `T` from a [`ScriptValue`].
///
/// The [`FromScript::This`] associated type is used to allow for the implementation of this trait to return
/// a type borrowing from the world for the duration of a [`CallScope`]. In 99% cases you can just use `Self` as the associated type.
pub trait FromScript {
    /// The type that is constructed from the script value.
    type This<'s>;

    /// Construct a value of type `T` from a [`ScriptValue`].
    ///
    /// Borrows from the world can't outlive the `scope`, which releases their accesses when it ends,
    /// see [`bevy_mod_scripting_world::WorldAccessGuard::with_call_scope`].
    fn from_script<'s>(
        value: ScriptValue,
        scope: &'s CallScope<'_>,
    ) -> Result<Self::This<'s>, InteropError>
    where
        Self: Sized;
}

#[profiling::all_functions]
impl FromScript for ScriptValue {
    type This<'w> = Self;
    fn from_script(value: ScriptValue, _scope: &CallScope) -> Result<Self, InteropError> {
        Ok(value)
    }
}

#[profiling::all_functions]
impl FromScript for () {
    type This<'w> = Self;
    fn from_script(_value: ScriptValue, _scope: &CallScope) -> Result<Self, InteropError> {
        Ok(())
    }
}

#[profiling::all_functions]
impl FromScript for bool {
    type This<'w> = Self;
    #[profiling::function]
    fn from_script<'s>(
        value: ScriptValue,
        scope: &'s CallScope<'_>,
    ) -> Result<Self::This<'s>, InteropError>
    where
        Self: Sized,
    {
        match value {
            ScriptValue::Bool(b) => Ok(b),
            ScriptValue::Reference(r) => r.downcast::<Self>(scope.world()),
            _ => Err(InteropError::value_mismatch(
                std::any::TypeId::of::<Self>(),
                value,
            )),
        }
    }
}

macro_rules! impl_from_with_downcast {
    ($($ty:ty),*) => {
        $(
            #[profiling::all_functions]
            impl FromScript for $ty {
                type This<'w> = Self;
                #[profiling::function]
                fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
                    match value {
                        ScriptValue::Integer(i) => Ok(i as $ty),
                        ScriptValue::Float(i) => Ok(i as $ty),
                        ScriptValue::Reference(r) => r.downcast::<Self>(scope.world()),
                        ScriptValue::Bool(b) => Ok(b as usize as $ty),
                        _ => Err(InteropError::value_mismatch(std::any::TypeId::of::<Self>(), value)),
                    }
                }
            }
        )*
    };
}

impl_from_with_downcast!(
    i8, i16, i32, i64, i128, u8, u16, u32, u64, u128, f32, f64, usize, isize
);

macro_rules! impl_from_stringlike {
    ($($ty:ty),*) => {
        $(
            #[profiling::all_functions]
            impl FromScript for $ty {
                type This<'w> = Self;
                #[profiling::function]
                fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
                    match value {
                        ScriptValue::String(s) => Ok(s.to_string().into()),
                        ScriptValue::Reference(r) => r.downcast::<Self>(scope.world()),
                        _ => Err(InteropError::value_mismatch(std::any::TypeId::of::<Self>(), value)),
                    }
                }
            }
        )*
    };
}

impl_from_stringlike!(String, PathBuf, OsString);

impl FromScript for NonMaxU32 {
    type This<'w> = Self;

    fn from_script<'s>(
        value: ScriptValue,
        _scope: &'s CallScope<'_>,
    ) -> Result<Self::This<'s>, InteropError>
    where
        Self: Sized,
    {
        let converted = match value {
            ScriptValue::Integer(i) => u32::try_from(i).ok(),
            // `as` saturates, so check the range first
            ScriptValue::Float(f) if (0.0..u32::MAX as f64).contains(&f) => Some(f as u32),
            _ => None,
        };
        converted
            .and_then(NonMaxU32::new)
            .ok_or_else(|| InteropError::value_mismatch(std::any::TypeId::of::<Self>(), value))
    }
}

#[profiling::all_functions]
impl FromScript for char {
    type This<'w> = Self;
    #[profiling::function]
    fn from_script<'s>(
        value: ScriptValue,
        scope: &'s CallScope<'_>,
    ) -> Result<Self::This<'s>, InteropError>
    where
        Self: Sized,
    {
        match value {
            ScriptValue::Integer(i) => Ok(i as u8 as char),
            ScriptValue::String(c) => c.chars().next().ok_or_else(|| {
                InteropError::value_mismatch(TypeId::of::<char>(), ScriptValue::String(c))
            }),
            ScriptValue::Reference(r) => r.downcast::<Self>(scope.world()),
            _ => Err(InteropError::value_mismatch(
                std::any::TypeId::of::<Self>(),
                value,
            )),
        }
    }
}

#[profiling::all_functions]
impl FromScript for ReflectReference {
    type This<'w> = Self;
    #[profiling::function]
    fn from_script(value: ScriptValue, _scope: &CallScope) -> Result<Self, InteropError> {
        match value {
            ScriptValue::Reference(r) => Ok(r),
            _ => Err(InteropError::value_mismatch(
                std::any::TypeId::of::<ReflectReference>(),
                value,
            )),
        }
    }
}

fn variant_as_value<T: 'static>(
    reference: &ReflectReference,
    world: &WorldGuard,
) -> Option<ReflectReference> {
    variant_as_value_of(reference, world, TypeId::of::<T>())
}

/// [`variant_as_value`] for a type known only by its [`TypeId`].
pub(crate) fn variant_as_value_of(
    reference: &ReflectReference,
    world: &WorldGuard,
    type_id: TypeId,
) -> Option<ReflectReference> {
    let variant = reference.downcast::<EnumVariantRef>(world.clone()).ok()?;
    if variant.type_id != type_id {
        return None;
    }
    construct_reference(
        world,
        variant.type_info(world).ok()?,
        Some(variant.variant_name(world).ok()?),
        BoundFields::Positional(VecDeque::new()),
        false,
    )
    .ok()
}

/// A wrapper around a value of type `T`.
///
/// This can be used to retrieve a value out of a [`ScriptValue::Reference`] corresponding to the type `T`.
/// You can also use this to return values from a script function to be allocated directly as a [`ScriptValue::Reference`].
#[derive(Reflect)]
pub struct V<T>(pub T);

#[profiling::all_functions]
impl<T> V<T> {
    /// Create a new `Val` with the given value.
    pub fn new(value: T) -> Self {
        V(value)
    }

    /// Unwrap the value from the `Val`.
    pub fn into_inner(self) -> T {
        self.0
    }
}

impl<T> Deref for V<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<T> DerefMut for V<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T> From<T> for V<T> {
    fn from(value: T) -> Self {
        V(value)
    }
}

#[profiling::all_functions]
impl<T: FromReflect> FromScript for V<T> {
    type This<'w> = Self;
    #[profiling::function]
    fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
        let world = scope.world();
        match value {
            ScriptValue::Reference(reflect_reference) => {
                let from_reflect = |reference: &ReflectReference| {
                    reference.with_reflect(world.clone(), |r| {
                        T::from_reflect(r).ok_or_else(|| {
                            InteropError::failed_from_reflect(
                                Some(TypeId::of::<T>()),
                                format!(
                                    "Expected '{}' but receievd: {r:?}",
                                    std::any::type_name::<T>()
                                ),
                            )
                        })
                    })?
                };
                match from_reflect(&reflect_reference) {
                    Ok(value) => Ok(V(value)),
                    Err(err) => match variant_as_value::<T>(&reflect_reference, &world) {
                        Some(value) => from_reflect(&value).map(V),
                        None => Err(err),
                    },
                }
            }
            _ => Err(InteropError::value_mismatch(
                std::any::TypeId::of::<T>(),
                value,
            )),
        }
    }
}

/// A wrapper around a reference to a value of type `T`.
///
/// This can be used to retrieve a reference out of a [`ScriptValue::Reference`] corresponding to the type `T`.
/// Before downcasting the reference, it will claim write access to the object to ensure that the reference is valid.
///
/// The access is released when the [`CallScope`] it was converted in ends, see [`M`].
pub struct R<'w, T>(pub &'w T);

impl<T> Deref for R<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.0
    }
}

#[profiling::all_functions]
impl<T: FromReflect> FromScript for R<'_, T> {
    type This<'a> = R<'a, T>;
    #[profiling::function]
    fn from_script<'s>(
        value: ScriptValue,
        scope: &'s CallScope<'_>,
    ) -> Result<Self::This<'s>, InteropError> {
        match value {
            ScriptValue::Reference(reflect_reference) => {
                let world = scope.world();
                // the claim keeps an allocated value alive, the borrow outlives `reflect_reference`
                // and is released when `scope` ends, which the borrow can't outlive
                if scope.claim_read_access(&reflect_reference.base.base_id) {
                    // Safety: we just claimed access
                    let ref_ =
                        unsafe { reflect_reference.reflect_unsafe_non_empty(world.clone()) }?;
                    match ref_.try_downcast_ref::<T>() {
                        Some(cast) => Ok(R(cast)),
                        None => match variant_as_value::<T>(&reflect_reference, &world) {
                            Some(value) => Self::from_script(ScriptValue::Reference(value), scope),
                            None => Err(InteropError::type_mismatch(
                                std::any::TypeId::of::<T>(),
                                ref_.get_represented_type_info().map(|i| i.type_id()),
                            )),
                        },
                    }
                } else {
                    Err(InteropError::cannot_claim_access(
                        (&reflect_reference.base.base_id).into(),
                        format!("In conversion to type: R<{}>", std::any::type_name::<T>()),
                    ))
                }
            }
            _ => Err(InteropError::value_mismatch(
                std::any::TypeId::of::<T>(),
                value,
            )),
        }
    }
}

impl<'a, T> From<&'a T> for R<'a, T> {
    fn from(value: &'a T) -> Self {
        R(value)
    }
}

/// A wrapper around a mutable reference to a value of type `T`.
///
/// This can be used to retrieve a mutable reference out of a [`ScriptValue::Reference`] corresponding to the type `T`.
/// Before downcasting the reference, it will claim write access to the object to ensure that the reference is valid.
///
/// The access is released when the [`CallScope`] it was converted in ends, i.e. when the function call returns,
/// which is why the borrow can't be kept past the call:
///
/// ```
/// # use bevy_mod_scripting_bindings::function::{from::M, script_function::ScriptFunction};
/// fn double(mut m: M<u32>) { *m.0 *= 2 }
/// let _ = double.into_dynamic_script_function();
/// ```
///
/// ```compile_fail
/// # use bevy_mod_scripting_bindings::function::{from::M, script_function::ScriptFunction};
/// fn stash(m: M<'static, u32>) {}
/// let _ = stash.into_dynamic_script_function();
/// ```
pub struct M<'w, T>(pub &'w mut T);

impl<T> Deref for M<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.0
    }
}

impl<T> DerefMut for M<'_, T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.0
    }
}

impl<'a, T> From<&'a mut T> for M<'a, T> {
    fn from(value: &'a mut T) -> Self {
        M(value)
    }
}

#[profiling::all_functions]
impl<T: FromReflect> FromScript for M<'_, T> {
    type This<'w> = M<'w, T>;
    #[profiling::function]
    fn from_script<'s>(
        value: ScriptValue,
        scope: &'s CallScope<'_>,
    ) -> Result<Self::This<'s>, InteropError> {
        match value {
            ScriptValue::Reference(reflect_reference) => {
                // the claim keeps an allocated value alive, the borrow outlives `reflect_reference`
                // and is released when `scope` ends, which the borrow can't outlive
                if scope.claim_write_access(&reflect_reference.base.base_id) {
                    // Safety: we just claimed write access
                    let ref_ =
                        unsafe { reflect_reference.reflect_mut_unsafe_non_empty(scope.world()) }?;
                    let type_id = ref_.get_represented_type_info().map(|i| i.type_id());
                    let cast = ref_.try_downcast_mut::<T>().ok_or_else(|| {
                        InteropError::type_mismatch(std::any::TypeId::of::<T>(), type_id)
                    })?;
                    Ok(M(cast))
                } else {
                    Err(InteropError::cannot_claim_access(
                        (&reflect_reference.base.base_id).into(),
                        format!("In conversion to type: Mut<{}>", std::any::type_name::<T>()),
                    ))
                }
            }
            _ => Err(InteropError::value_mismatch(
                std::any::TypeId::of::<T>(),
                value,
            )),
        }
    }
}

#[profiling::all_functions]
impl<T: FromScript> FromScript for Option<T> {
    type This<'w> = Option<T::This<'w>>;
    #[profiling::function]
    fn from_script<'s>(
        value: ScriptValue,
        scope: &'s CallScope<'_>,
    ) -> Result<Self::This<'s>, InteropError> {
        match value {
            ScriptValue::Unit => Ok(None),
            _ => Ok(Some(T::from_script(value, scope)?)),
        }
    }
}

#[profiling::all_functions]
impl<T: FromScript + 'static> FromScript for Vec<T>
where
    for<'w> T::This<'w>: Into<T>,
{
    type This<'w> = Self;
    #[profiling::function]
    fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
        match value {
            ScriptValue::List(list) => {
                let mut vec = Vec::with_capacity(list.len());
                for item in list {
                    vec.push(T::from_script(item, scope)?.into());
                }
                Ok(vec)
            }
            _ => Err(InteropError::value_mismatch(
                std::any::TypeId::of::<Vec<T>>(),
                value,
            )),
        }
    }
}

#[profiling::all_functions]
impl<T: FromScript + 'static> FromScript for VecDeque<T>
where
    for<'w> T::This<'w>: Into<T>,
{
    type This<'w> = Self;
    #[profiling::function]
    fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
        match value {
            ScriptValue::List(list) => {
                let mut vec = VecDeque::with_capacity(list.len());
                for item in list {
                    vec.push_back(T::from_script(item, scope)?.into());
                }
                Ok(vec)
            }
            _ => Err(InteropError::value_mismatch(
                std::any::TypeId::of::<VecDeque<T>>(),
                value,
            )),
        }
    }
}

#[profiling::all_functions]
impl<T: FromScript + 'static, const N: usize> FromScript for [T; N]
where
    for<'w> T::This<'w>: Into<T>,
{
    type This<'w> = Self;
    #[profiling::function]
    fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
        match value {
            ScriptValue::List(list) if list.len() == N => {
                let converted_list = list
                    .into_iter()
                    .map(|item| T::from_script(item, scope).map(Into::into))
                    .collect::<Result<Vec<T>, _>>()?
                    .try_into()
                    .map_err(|list: Vec<T>| InteropError::length_mismatch(N, list.len()))?;
                Ok(converted_list)
            }
            _ => Err(InteropError::value_mismatch(
                std::any::TypeId::of::<[T; N]>(),
                value,
            )),
        }
    }
}

#[profiling::all_functions]
impl FromScript for DynamicScriptFunctionMut {
    type This<'w> = Self;
    #[profiling::function]
    fn from_script<'s>(
        value: ScriptValue,
        _: &'s CallScope<'_>,
    ) -> Result<Self::This<'s>, InteropError>
    where
        Self: Sized,
    {
        match value {
            ScriptValue::FunctionMut(f) => Ok(f),
            _ => Err(InteropError::value_mismatch(
                std::any::TypeId::of::<Self>(),
                value,
            )),
        }
    }
}

#[profiling::all_functions]
impl FromScript for DynamicScriptFunction {
    type This<'w> = Self;
    #[profiling::function]
    fn from_script<'s>(
        value: ScriptValue,
        _: &'s CallScope<'_>,
    ) -> Result<Self::This<'s>, InteropError>
    where
        Self: Sized,
    {
        match value {
            ScriptValue::Function(f) => Ok(f),
            _ => Err(InteropError::value_mismatch(
                std::any::TypeId::of::<Self>(),
                value,
            )),
        }
    }
}

macro_rules! impl_from_script_hashmap {
    ($hashmap_type:path) => {
        #[profiling::all_functions]
        impl<V> FromScript for $hashmap_type
        where
            V: FromScript + 'static,
            for<'w> V::This<'w>: Into<V>,
        {
            type This<'w> = Self;
            #[profiling::function]
            fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
                match value {
                    ScriptValue::Map(map) => {
                        let mut hashmap = <$hashmap_type>::new();
                        for (key, value) in map {
                            hashmap.insert(key, V::from_script(value, scope)?.into());
                        }
                        Ok(hashmap)
                    }
                    ScriptValue::List(list) => {
                        let mut hashmap = <$hashmap_type>::new();
                        for elem in list {
                            let (key, val) = <(String, V)>::from_script(elem, scope)?;
                            hashmap.insert(key, val);
                        }
                        Ok(hashmap)
                    }
                    _ => Err(InteropError::value_mismatch(
                        std::any::TypeId::of::<$hashmap_type>(),
                        value,
                    )),
                }
            }
        }
    };
}

impl_from_script_hashmap!(HashMap<String, V>);
impl_from_script_hashmap!(std::collections::HashMap<String, V>);

macro_rules! impl_from_script_hashset {
    ($hashset_type:path) => {
        #[profiling::all_functions]
        impl<V> FromScript for $hashset_type
        where
            V: FromScript + Eq + std::hash::Hash + 'static,
            for<'w> V::This<'w>: Into<V>,
        {
            type This<'w> = Self;
            #[profiling::function]
            fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
                match value {
                    ScriptValue::Map(map) => {
                        let mut hashmap = <$hashset_type>::new();
                        for (_, value) in map {
                            hashmap.insert(V::from_script(value, scope)?.into());
                        }
                        Ok(hashmap)
                    }
                    ScriptValue::List(list) => {
                        let mut hashmap = <$hashset_type>::new();
                        for elem in list {
                            let key = <V>::from_script(elem, scope)?;
                            hashmap.insert(key.into());
                        }
                        Ok(hashmap)
                    }
                    _ => Err(InteropError::value_mismatch(
                        std::any::TypeId::of::<$hashset_type>(),
                        value,
                    )),
                }
            }
        }
    };
}

impl_from_script_hashset![HashSet<V>];

/// A union of two or more (by nesting unions) types.
pub struct Union<T1, T2>(Result<T1, T2>);

#[profiling::all_functions]
impl<T1, T2> Union<T1, T2> {
    /// Create a new union with the left value.
    pub fn new_left(value: T1) -> Self {
        Union(Ok(value))
    }

    /// Returns true if this union represents the left kind of value
    pub fn is_left(&self) -> bool {
        matches!(self, Union(Ok(_)))
    }

    /// Returns true if this union represents the right kind of value
    pub fn is_right(&self) -> bool {
        matches!(self, Union(Err(_)))
    }

    /// Create a new union with the right value.
    pub fn new_right(value: T2) -> Self {
        Union(Err(value))
    }

    /// Try interpret the union as the left type
    pub fn into_left(self) -> Result<T1, T2> {
        match self.0 {
            Ok(r) => Ok(r),
            Err(l) => Err(l),
        }
    }

    /// Try interpret the union as the right type
    pub fn into_right(self) -> Result<T2, T1> {
        match self.0 {
            Err(r) => Ok(r),
            Ok(l) => Err(l),
        }
    }

    /// Map the union to another type
    pub fn map_both<U1, U2, F: Fn(T1) -> U1, G: Fn(T2) -> U2>(self, f: F, g: G) -> Union<U1, U2> {
        match self.0 {
            Ok(t) => Union(Ok(f(t))),
            Err(t) => Union(Err(g(t))),
        }
    }
}

#[profiling::all_functions]
impl<T1: FromScript, T2: FromScript> FromScript for Union<T1, T2> {
    type This<'w> = Union<T1::This<'w>, T2::This<'w>>;
    fn from_script<'s>(
        value: ScriptValue,
        scope: &'s CallScope<'_>,
    ) -> Result<Self::This<'s>, InteropError> {
        if let Ok(v) = T1::from_script(value.clone(), scope) {
            return Ok(Union(Ok(v)));
        }

        T2::from_script(value, scope).map(|v| Union(Err(v)))
    }
}

impl FromScript for VariadicTuple {
    type This<'w> = Self;

    fn from_script<'s>(
        value: ScriptValue,
        _scope: &'s CallScope<'_>,
    ) -> Result<Self::This<'s>, InteropError>
    where
        Self: Sized,
    {
        match value {
            ScriptValue::List(tuple) | ScriptValue::Tuple(VariadicTuple(tuple)) => Ok(Self(tuple)),
            v => Ok(Self(VecDeque::from_iter([v]))),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::{CurrentScriptAttachment, WorldExtensions};
    use bevy_ecs::world::World;
    use bevy_mod_scripting_world::WorldAccessGuard;

    #[test]
    fn non_max_u32_rejects_out_of_range_values() {
        let mut world = World::default();
        let cache = WorldAccessGuard::setup_cache(&world, CurrentScriptAttachment::empty());
        let guard = WorldAccessGuard::new_exclusive(&mut world, cache);
        guard.with_call_scope(|scope| {
            let convert = |v| {
                NonMaxU32::from_script(v, scope)
                    .ok()
                    .map(|v: NonMaxU32| v.get())
            };
            assert_eq!(convert(ScriptValue::Integer(0)), Some(0));
            assert_eq!(convert(ScriptValue::Float(7.0)), Some(7));
            for invalid in [
                ScriptValue::Integer(-1),
                ScriptValue::Integer(u32::MAX as i64),
                ScriptValue::Integer(1 << 40),
                ScriptValue::Float(-1.0),
                ScriptValue::Float(u32::MAX as f64),
                ScriptValue::Float(f64::NAN),
            ] {
                assert_eq!(convert(invalid.clone()), None, "{invalid:?}");
            }
        });
    }
}

macro_rules! impl_from_script_tuple {
    ($($ty:ident),*) => {
        #[allow(non_snake_case)]
        #[profiling::all_functions]
        impl<$($ty: FromScript),*> FromScript for ($($ty,)*)
        where
            Self: 'static,
            $(
                for<'w> $ty::This<'w>: Into<$ty>,
            )*
        {
            type This<'w> = Self;

            fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
                match value {
                    ScriptValue::List(list) | ScriptValue::Tuple(VariadicTuple(list)) => {
                        let expected_arg_count = $crate::function::script_function::count!( $($ty)* );
                        if list.len() != expected_arg_count {
                            return Err(InteropError::length_mismatch(expected_arg_count, list.len()));
                        }

                        let mut iter = list.into_iter();
                        $(
                            let next_item = iter.next().ok_or_else(|| InteropError::invariant("list has right amount of elements"))?;
                            let $ty = $ty::from_script(next_item, scope)?.into();
                        )*


                        Ok(($($ty,)*))
                    }
                    _ => Err(InteropError::value_mismatch(
                        std::any::TypeId::of::<Self>(),
                        value,
                    )),
                }
            }
        }
    };
}

variadics_please::all_tuples!(impl_from_script_tuple, 1, 14, T);