1use super::bound::BoundFields;
4use super::script_function::{DynamicScriptFunction, DynamicScriptFunctionMut};
5use crate::{
6 EnumVariantRef, ReflectReference, ScriptValue, construct::construct_reference,
7 error::InteropError, script_value::VariadicTuple,
8};
9use bevy_mod_scripting_world::{CallScope, WorldGuard};
10use bevy_platform::collections::{HashMap, HashSet};
11use bevy_reflect::{FromReflect, Reflect};
12use nonmax::NonMaxU32;
13use std::{
14 any::TypeId,
15 collections::VecDeque,
16 ffi::OsString,
17 ops::{Deref, DerefMut},
18 path::PathBuf,
19};
20
21pub trait FromScript {
26 type This<'s>;
28
29 fn from_script<'s>(
34 value: ScriptValue,
35 scope: &'s CallScope<'_>,
36 ) -> Result<Self::This<'s>, InteropError>
37 where
38 Self: Sized;
39}
40
41#[profiling::all_functions]
42impl FromScript for ScriptValue {
43 type This<'w> = Self;
44 fn from_script(value: ScriptValue, _scope: &CallScope) -> Result<Self, InteropError> {
45 Ok(value)
46 }
47}
48
49#[profiling::all_functions]
50impl FromScript for () {
51 type This<'w> = Self;
52 fn from_script(_value: ScriptValue, _scope: &CallScope) -> Result<Self, InteropError> {
53 Ok(())
54 }
55}
56
57#[profiling::all_functions]
58impl FromScript for bool {
59 type This<'w> = Self;
60 #[profiling::function]
61 fn from_script<'s>(
62 value: ScriptValue,
63 scope: &'s CallScope<'_>,
64 ) -> Result<Self::This<'s>, InteropError>
65 where
66 Self: Sized,
67 {
68 match value {
69 ScriptValue::Bool(b) => Ok(b),
70 ScriptValue::Reference(r) => r.downcast::<Self>(scope.world()),
71 _ => Err(InteropError::value_mismatch(
72 std::any::TypeId::of::<Self>(),
73 value,
74 )),
75 }
76 }
77}
78
79macro_rules! impl_from_with_downcast {
80 ($($ty:ty),*) => {
81 $(
82 #[profiling::all_functions]
83 impl FromScript for $ty {
84 type This<'w> = Self;
85 #[profiling::function]
86 fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
87 match value {
88 ScriptValue::Integer(i) => Ok(i as $ty),
89 ScriptValue::Float(i) => Ok(i as $ty),
90 ScriptValue::Reference(r) => r.downcast::<Self>(scope.world()),
91 ScriptValue::Bool(b) => Ok(b as usize as $ty),
92 _ => Err(InteropError::value_mismatch(std::any::TypeId::of::<Self>(), value)),
93 }
94 }
95 }
96 )*
97 };
98}
99
100impl_from_with_downcast!(
101 i8, i16, i32, i64, i128, u8, u16, u32, u64, u128, f32, f64, usize, isize
102);
103
104macro_rules! impl_from_stringlike {
105 ($($ty:ty),*) => {
106 $(
107 #[profiling::all_functions]
108 impl FromScript for $ty {
109 type This<'w> = Self;
110 #[profiling::function]
111 fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
112 match value {
113 ScriptValue::String(s) => Ok(s.to_string().into()),
114 ScriptValue::Reference(r) => r.downcast::<Self>(scope.world()),
115 _ => Err(InteropError::value_mismatch(std::any::TypeId::of::<Self>(), value)),
116 }
117 }
118 }
119 )*
120 };
121}
122
123impl_from_stringlike!(String, PathBuf, OsString);
124
125impl FromScript for NonMaxU32 {
126 type This<'w> = Self;
127
128 fn from_script<'s>(
129 value: ScriptValue,
130 _scope: &'s CallScope<'_>,
131 ) -> Result<Self::This<'s>, InteropError>
132 where
133 Self: Sized,
134 {
135 let converted = match value {
136 ScriptValue::Integer(i) => u32::try_from(i).ok(),
137 ScriptValue::Float(f) if (0.0..u32::MAX as f64).contains(&f) => Some(f as u32),
139 _ => None,
140 };
141 converted
142 .and_then(NonMaxU32::new)
143 .ok_or_else(|| InteropError::value_mismatch(std::any::TypeId::of::<Self>(), value))
144 }
145}
146
147#[profiling::all_functions]
148impl FromScript for char {
149 type This<'w> = Self;
150 #[profiling::function]
151 fn from_script<'s>(
152 value: ScriptValue,
153 scope: &'s CallScope<'_>,
154 ) -> Result<Self::This<'s>, InteropError>
155 where
156 Self: Sized,
157 {
158 match value {
159 ScriptValue::Integer(i) => Ok(i as u8 as char),
160 ScriptValue::String(c) => c.chars().next().ok_or_else(|| {
161 InteropError::value_mismatch(TypeId::of::<char>(), ScriptValue::String(c))
162 }),
163 ScriptValue::Reference(r) => r.downcast::<Self>(scope.world()),
164 _ => Err(InteropError::value_mismatch(
165 std::any::TypeId::of::<Self>(),
166 value,
167 )),
168 }
169 }
170}
171
172#[profiling::all_functions]
173impl FromScript for ReflectReference {
174 type This<'w> = Self;
175 #[profiling::function]
176 fn from_script(value: ScriptValue, _scope: &CallScope) -> Result<Self, InteropError> {
177 match value {
178 ScriptValue::Reference(r) => Ok(r),
179 _ => Err(InteropError::value_mismatch(
180 std::any::TypeId::of::<ReflectReference>(),
181 value,
182 )),
183 }
184 }
185}
186
187fn variant_as_value<T: 'static>(
188 reference: &ReflectReference,
189 world: &WorldGuard,
190) -> Option<ReflectReference> {
191 variant_as_value_of(reference, world, TypeId::of::<T>())
192}
193
194pub(crate) fn variant_as_value_of(
196 reference: &ReflectReference,
197 world: &WorldGuard,
198 type_id: TypeId,
199) -> Option<ReflectReference> {
200 let variant = reference.downcast::<EnumVariantRef>(world.clone()).ok()?;
201 if variant.type_id != type_id {
202 return None;
203 }
204 construct_reference(
205 world,
206 variant.type_info(world).ok()?,
207 Some(variant.variant_name(world).ok()?),
208 BoundFields::Positional(VecDeque::new()),
209 false,
210 )
211 .ok()
212}
213
214#[derive(Reflect)]
219pub struct V<T>(pub T);
220
221#[profiling::all_functions]
222impl<T> V<T> {
223 pub fn new(value: T) -> Self {
225 V(value)
226 }
227
228 pub fn into_inner(self) -> T {
230 self.0
231 }
232}
233
234impl<T> Deref for V<T> {
235 type Target = T;
236
237 fn deref(&self) -> &Self::Target {
238 &self.0
239 }
240}
241
242impl<T> DerefMut for V<T> {
243 fn deref_mut(&mut self) -> &mut Self::Target {
244 &mut self.0
245 }
246}
247
248impl<T> From<T> for V<T> {
249 fn from(value: T) -> Self {
250 V(value)
251 }
252}
253
254#[profiling::all_functions]
255impl<T: FromReflect> FromScript for V<T> {
256 type This<'w> = Self;
257 #[profiling::function]
258 fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
259 let world = scope.world();
260 match value {
261 ScriptValue::Reference(reflect_reference) => {
262 let from_reflect = |reference: &ReflectReference| {
263 reference.with_reflect(world.clone(), |r| {
264 T::from_reflect(r).ok_or_else(|| {
265 InteropError::failed_from_reflect(
266 Some(TypeId::of::<T>()),
267 format!(
268 "Expected '{}' but receievd: {r:?}",
269 std::any::type_name::<T>()
270 ),
271 )
272 })
273 })?
274 };
275 match from_reflect(&reflect_reference) {
276 Ok(value) => Ok(V(value)),
277 Err(err) => match variant_as_value::<T>(&reflect_reference, &world) {
278 Some(value) => from_reflect(&value).map(V),
279 None => Err(err),
280 },
281 }
282 }
283 _ => Err(InteropError::value_mismatch(
284 std::any::TypeId::of::<T>(),
285 value,
286 )),
287 }
288 }
289}
290
291pub struct R<'w, T>(pub &'w T);
298
299impl<T> Deref for R<'_, T> {
300 type Target = T;
301
302 fn deref(&self) -> &Self::Target {
303 self.0
304 }
305}
306
307#[profiling::all_functions]
308impl<T: FromReflect> FromScript for R<'_, T> {
309 type This<'a> = R<'a, T>;
310 #[profiling::function]
311 fn from_script<'s>(
312 value: ScriptValue,
313 scope: &'s CallScope<'_>,
314 ) -> Result<Self::This<'s>, InteropError> {
315 match value {
316 ScriptValue::Reference(reflect_reference) => {
317 let world = scope.world();
318 if scope.claim_read_access(&reflect_reference.base.base_id) {
321 let ref_ =
323 unsafe { reflect_reference.reflect_unsafe_non_empty(world.clone()) }?;
324 match ref_.try_downcast_ref::<T>() {
325 Some(cast) => Ok(R(cast)),
326 None => match variant_as_value::<T>(&reflect_reference, &world) {
327 Some(value) => Self::from_script(ScriptValue::Reference(value), scope),
328 None => Err(InteropError::type_mismatch(
329 std::any::TypeId::of::<T>(),
330 ref_.get_represented_type_info().map(|i| i.type_id()),
331 )),
332 },
333 }
334 } else {
335 Err(InteropError::cannot_claim_access(
336 (&reflect_reference.base.base_id).into(),
337 format!("In conversion to type: R<{}>", std::any::type_name::<T>()),
338 ))
339 }
340 }
341 _ => Err(InteropError::value_mismatch(
342 std::any::TypeId::of::<T>(),
343 value,
344 )),
345 }
346 }
347}
348
349impl<'a, T> From<&'a T> for R<'a, T> {
350 fn from(value: &'a T) -> Self {
351 R(value)
352 }
353}
354
355pub struct M<'w, T>(pub &'w mut T);
375
376impl<T> Deref for M<'_, T> {
377 type Target = T;
378
379 fn deref(&self) -> &Self::Target {
380 self.0
381 }
382}
383
384impl<T> DerefMut for M<'_, T> {
385 fn deref_mut(&mut self) -> &mut Self::Target {
386 self.0
387 }
388}
389
390impl<'a, T> From<&'a mut T> for M<'a, T> {
391 fn from(value: &'a mut T) -> Self {
392 M(value)
393 }
394}
395
396#[profiling::all_functions]
397impl<T: FromReflect> FromScript for M<'_, T> {
398 type This<'w> = M<'w, T>;
399 #[profiling::function]
400 fn from_script<'s>(
401 value: ScriptValue,
402 scope: &'s CallScope<'_>,
403 ) -> Result<Self::This<'s>, InteropError> {
404 match value {
405 ScriptValue::Reference(reflect_reference) => {
406 if scope.claim_write_access(&reflect_reference.base.base_id) {
409 let ref_ =
411 unsafe { reflect_reference.reflect_mut_unsafe_non_empty(scope.world()) }?;
412 let type_id = ref_.get_represented_type_info().map(|i| i.type_id());
413 let cast = ref_.try_downcast_mut::<T>().ok_or_else(|| {
414 InteropError::type_mismatch(std::any::TypeId::of::<T>(), type_id)
415 })?;
416 Ok(M(cast))
417 } else {
418 Err(InteropError::cannot_claim_access(
419 (&reflect_reference.base.base_id).into(),
420 format!("In conversion to type: Mut<{}>", std::any::type_name::<T>()),
421 ))
422 }
423 }
424 _ => Err(InteropError::value_mismatch(
425 std::any::TypeId::of::<T>(),
426 value,
427 )),
428 }
429 }
430}
431
432#[profiling::all_functions]
433impl<T: FromScript> FromScript for Option<T> {
434 type This<'w> = Option<T::This<'w>>;
435 #[profiling::function]
436 fn from_script<'s>(
437 value: ScriptValue,
438 scope: &'s CallScope<'_>,
439 ) -> Result<Self::This<'s>, InteropError> {
440 match value {
441 ScriptValue::Unit => Ok(None),
442 _ => Ok(Some(T::from_script(value, scope)?)),
443 }
444 }
445}
446
447#[profiling::all_functions]
448impl<T: FromScript + 'static> FromScript for Vec<T>
449where
450 for<'w> T::This<'w>: Into<T>,
451{
452 type This<'w> = Self;
453 #[profiling::function]
454 fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
455 match value {
456 ScriptValue::List(list) => {
457 let mut vec = Vec::with_capacity(list.len());
458 for item in list {
459 vec.push(T::from_script(item, scope)?.into());
460 }
461 Ok(vec)
462 }
463 _ => Err(InteropError::value_mismatch(
464 std::any::TypeId::of::<Vec<T>>(),
465 value,
466 )),
467 }
468 }
469}
470
471#[profiling::all_functions]
472impl<T: FromScript + 'static> FromScript for VecDeque<T>
473where
474 for<'w> T::This<'w>: Into<T>,
475{
476 type This<'w> = Self;
477 #[profiling::function]
478 fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
479 match value {
480 ScriptValue::List(list) => {
481 let mut vec = VecDeque::with_capacity(list.len());
482 for item in list {
483 vec.push_back(T::from_script(item, scope)?.into());
484 }
485 Ok(vec)
486 }
487 _ => Err(InteropError::value_mismatch(
488 std::any::TypeId::of::<VecDeque<T>>(),
489 value,
490 )),
491 }
492 }
493}
494
495#[profiling::all_functions]
496impl<T: FromScript + 'static, const N: usize> FromScript for [T; N]
497where
498 for<'w> T::This<'w>: Into<T>,
499{
500 type This<'w> = Self;
501 #[profiling::function]
502 fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
503 match value {
504 ScriptValue::List(list) if list.len() == N => {
505 let converted_list = list
506 .into_iter()
507 .map(|item| T::from_script(item, scope).map(Into::into))
508 .collect::<Result<Vec<T>, _>>()?
509 .try_into()
510 .map_err(|list: Vec<T>| InteropError::length_mismatch(N, list.len()))?;
511 Ok(converted_list)
512 }
513 _ => Err(InteropError::value_mismatch(
514 std::any::TypeId::of::<[T; N]>(),
515 value,
516 )),
517 }
518 }
519}
520
521#[profiling::all_functions]
522impl FromScript for DynamicScriptFunctionMut {
523 type This<'w> = Self;
524 #[profiling::function]
525 fn from_script<'s>(
526 value: ScriptValue,
527 _: &'s CallScope<'_>,
528 ) -> Result<Self::This<'s>, InteropError>
529 where
530 Self: Sized,
531 {
532 match value {
533 ScriptValue::FunctionMut(f) => Ok(f),
534 _ => Err(InteropError::value_mismatch(
535 std::any::TypeId::of::<Self>(),
536 value,
537 )),
538 }
539 }
540}
541
542#[profiling::all_functions]
543impl FromScript for DynamicScriptFunction {
544 type This<'w> = Self;
545 #[profiling::function]
546 fn from_script<'s>(
547 value: ScriptValue,
548 _: &'s CallScope<'_>,
549 ) -> Result<Self::This<'s>, InteropError>
550 where
551 Self: Sized,
552 {
553 match value {
554 ScriptValue::Function(f) => Ok(f),
555 _ => Err(InteropError::value_mismatch(
556 std::any::TypeId::of::<Self>(),
557 value,
558 )),
559 }
560 }
561}
562
563macro_rules! impl_from_script_hashmap {
564 ($hashmap_type:path) => {
565 #[profiling::all_functions]
566 impl<V> FromScript for $hashmap_type
567 where
568 V: FromScript + 'static,
569 for<'w> V::This<'w>: Into<V>,
570 {
571 type This<'w> = Self;
572 #[profiling::function]
573 fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
574 match value {
575 ScriptValue::Map(map) => {
576 let mut hashmap = <$hashmap_type>::new();
577 for (key, value) in map {
578 hashmap.insert(key, V::from_script(value, scope)?.into());
579 }
580 Ok(hashmap)
581 }
582 ScriptValue::List(list) => {
583 let mut hashmap = <$hashmap_type>::new();
584 for elem in list {
585 let (key, val) = <(String, V)>::from_script(elem, scope)?;
586 hashmap.insert(key, val);
587 }
588 Ok(hashmap)
589 }
590 _ => Err(InteropError::value_mismatch(
591 std::any::TypeId::of::<$hashmap_type>(),
592 value,
593 )),
594 }
595 }
596 }
597 };
598}
599
600impl_from_script_hashmap!(HashMap<String, V>);
601impl_from_script_hashmap!(std::collections::HashMap<String, V>);
602
603macro_rules! impl_from_script_hashset {
604 ($hashset_type:path) => {
605 #[profiling::all_functions]
606 impl<V> FromScript for $hashset_type
607 where
608 V: FromScript + Eq + std::hash::Hash + 'static,
609 for<'w> V::This<'w>: Into<V>,
610 {
611 type This<'w> = Self;
612 #[profiling::function]
613 fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
614 match value {
615 ScriptValue::Map(map) => {
616 let mut hashmap = <$hashset_type>::new();
617 for (_, value) in map {
618 hashmap.insert(V::from_script(value, scope)?.into());
619 }
620 Ok(hashmap)
621 }
622 ScriptValue::List(list) => {
623 let mut hashmap = <$hashset_type>::new();
624 for elem in list {
625 let key = <V>::from_script(elem, scope)?;
626 hashmap.insert(key.into());
627 }
628 Ok(hashmap)
629 }
630 _ => Err(InteropError::value_mismatch(
631 std::any::TypeId::of::<$hashset_type>(),
632 value,
633 )),
634 }
635 }
636 }
637 };
638}
639
640impl_from_script_hashset![HashSet<V>];
641
642pub struct Union<T1, T2>(Result<T1, T2>);
644
645#[profiling::all_functions]
646impl<T1, T2> Union<T1, T2> {
647 pub fn new_left(value: T1) -> Self {
649 Union(Ok(value))
650 }
651
652 pub fn is_left(&self) -> bool {
654 matches!(self, Union(Ok(_)))
655 }
656
657 pub fn is_right(&self) -> bool {
659 matches!(self, Union(Err(_)))
660 }
661
662 pub fn new_right(value: T2) -> Self {
664 Union(Err(value))
665 }
666
667 pub fn into_left(self) -> Result<T1, T2> {
669 match self.0 {
670 Ok(r) => Ok(r),
671 Err(l) => Err(l),
672 }
673 }
674
675 pub fn into_right(self) -> Result<T2, T1> {
677 match self.0 {
678 Err(r) => Ok(r),
679 Ok(l) => Err(l),
680 }
681 }
682
683 pub fn map_both<U1, U2, F: Fn(T1) -> U1, G: Fn(T2) -> U2>(self, f: F, g: G) -> Union<U1, U2> {
685 match self.0 {
686 Ok(t) => Union(Ok(f(t))),
687 Err(t) => Union(Err(g(t))),
688 }
689 }
690}
691
692#[profiling::all_functions]
693impl<T1: FromScript, T2: FromScript> FromScript for Union<T1, T2> {
694 type This<'w> = Union<T1::This<'w>, T2::This<'w>>;
695 fn from_script<'s>(
696 value: ScriptValue,
697 scope: &'s CallScope<'_>,
698 ) -> Result<Self::This<'s>, InteropError> {
699 if let Ok(v) = T1::from_script(value.clone(), scope) {
700 return Ok(Union(Ok(v)));
701 }
702
703 T2::from_script(value, scope).map(|v| Union(Err(v)))
704 }
705}
706
707impl FromScript for VariadicTuple {
708 type This<'w> = Self;
709
710 fn from_script<'s>(
711 value: ScriptValue,
712 _scope: &'s CallScope<'_>,
713 ) -> Result<Self::This<'s>, InteropError>
714 where
715 Self: Sized,
716 {
717 match value {
718 ScriptValue::List(tuple) | ScriptValue::Tuple(VariadicTuple(tuple)) => Ok(Self(tuple)),
719 v => Ok(Self(VecDeque::from_iter([v]))),
720 }
721 }
722}
723
724#[cfg(test)]
725mod test {
726 use super::*;
727 use crate::{CurrentScriptAttachment, WorldExtensions};
728 use bevy_ecs::world::World;
729 use bevy_mod_scripting_world::WorldAccessGuard;
730
731 #[test]
732 fn non_max_u32_rejects_out_of_range_values() {
733 let mut world = World::default();
734 let cache = WorldAccessGuard::setup_cache(&world, CurrentScriptAttachment::empty());
735 let guard = WorldAccessGuard::new_exclusive(&mut world, cache);
736 guard.with_call_scope(|scope| {
737 let convert = |v| {
738 NonMaxU32::from_script(v, scope)
739 .ok()
740 .map(|v: NonMaxU32| v.get())
741 };
742 assert_eq!(convert(ScriptValue::Integer(0)), Some(0));
743 assert_eq!(convert(ScriptValue::Float(7.0)), Some(7));
744 for invalid in [
745 ScriptValue::Integer(-1),
746 ScriptValue::Integer(u32::MAX as i64),
747 ScriptValue::Integer(1 << 40),
748 ScriptValue::Float(-1.0),
749 ScriptValue::Float(u32::MAX as f64),
750 ScriptValue::Float(f64::NAN),
751 ] {
752 assert_eq!(convert(invalid.clone()), None, "{invalid:?}");
753 }
754 });
755 }
756}
757
758macro_rules! impl_from_script_tuple {
759 ($($ty:ident),*) => {
760 #[allow(non_snake_case)]
761 #[profiling::all_functions]
762 impl<$($ty: FromScript),*> FromScript for ($($ty,)*)
763 where
764 Self: 'static,
765 $(
766 for<'w> $ty::This<'w>: Into<$ty>,
767 )*
768 {
769 type This<'w> = Self;
770
771 fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
772 match value {
773 ScriptValue::List(list) | ScriptValue::Tuple(VariadicTuple(list)) => {
774 let expected_arg_count = $crate::function::script_function::count!( $($ty)* );
775 if list.len() != expected_arg_count {
776 return Err(InteropError::length_mismatch(expected_arg_count, list.len()));
777 }
778
779 let mut iter = list.into_iter();
780 $(
781 let next_item = iter.next().ok_or_else(|| InteropError::invariant("list has right amount of elements"))?;
782 let $ty = $ty::from_script(next_item, scope)?.into();
783 )*
784
785
786 Ok(($($ty,)*))
787 }
788 _ => Err(InteropError::value_mismatch(
789 std::any::TypeId::of::<Self>(),
790 value,
791 )),
792 }
793 }
794 }
795 };
796}
797
798variadics_please::all_tuples!(impl_from_script_tuple, 1, 14, T);