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,
};
pub trait FromScript {
type This<'s>;
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(),
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>())
}
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()
}
#[derive(Reflect)]
pub struct V<T>(pub T);
#[profiling::all_functions]
impl<T> V<T> {
pub fn new(value: T) -> Self {
V(value)
}
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,
)),
}
}
}
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();
if scope.claim_read_access(&reflect_reference.base.base_id) {
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)
}
}
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) => {
if scope.claim_write_access(&reflect_reference.base.base_id) {
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>];
pub struct Union<T1, T2>(Result<T1, T2>);
#[profiling::all_functions]
impl<T1, T2> Union<T1, T2> {
pub fn new_left(value: T1) -> Self {
Union(Ok(value))
}
pub fn is_left(&self) -> bool {
matches!(self, Union(Ok(_)))
}
pub fn is_right(&self) -> bool {
matches!(self, Union(Err(_)))
}
pub fn new_right(value: T2) -> Self {
Union(Err(value))
}
pub fn into_left(self) -> Result<T1, T2> {
match self.0 {
Ok(r) => Ok(r),
Err(l) => Err(l),
}
}
pub fn into_right(self) -> Result<T2, T1> {
match self.0 {
Err(r) => Ok(r),
Ok(l) => Err(l),
}
}
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);