bevy_mod_scripting_bindings 0.24.0

Core traits and structures required for smoothly interfacing with other languages in a generic way
Documentation
//! Generic parameters, which reflection can only see through the types they are instantiated with.

use std::{any::TypeId, marker::PhantomData, ops::Deref};

use bevy_app::App;
use bevy_asset::Asset;
use bevy_ecs::resource::Resource;
use bevy_mod_scripting_world::{CallScope, WorldGuard};
use bevy_reflect::{CreateTypeData, Reflect, TypeInfo, TypeRegistry, Typed};

use crate::{
    ReflectReference, ScriptValue,
    docgen::{TypedThrough, typed_through::ThroughTypeInfo},
    error::InteropError,
    function::{
        arg_meta::ArgMeta, from::FromScript, into::IntoScript,
        type_dependencies::GetTypeDependencies,
    },
};

/// Stands in for the generic parameter of a generic type, so the type's definition can be reflected.
///
/// Reflecting `Time<A>` gives `context: A` wherever the definition says `context: T`, which instantiations
/// like `Time<Virtual>` can't tell apart from a field that happens to be of the argument's type.
/// It implements the traits generic parameters are commonly bounded by, so it can instantiate most generic types,
/// types with more parameters use [`B`] and [`C`] too, and types with other bounds a [`generic_marker`](crate::generic_marker) of their own.
///
/// In the signature of a script function, it is a parameter of the function, see [`TypeOf`] and [`ValueOf`].
#[derive(Reflect, Asset, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[reflect(GenericMarker)]
pub struct A;

/// Type data marking a type as a generic marker, see [`generic_marker`](crate::generic_marker).
#[derive(Clone)]
pub struct ReflectGenericMarker;

impl<T> CreateTypeData<T> for ReflectGenericMarker {
    fn create_type_data(_: ()) -> Self {
        ReflectGenericMarker
    }
}

/// Whether the type is a generic marker: [`A`], [`B`], [`C`], or one declared with [`generic_marker`](crate::generic_marker) and registered.
pub fn is_generic_marker(type_registry: &TypeRegistry, type_id: TypeId) -> bool {
    [TypeId::of::<A>(), TypeId::of::<B>(), TypeId::of::<C>()].contains(&type_id)
        || type_registry
            .get_type_data::<ReflectGenericMarker>(type_id)
            .is_some()
}

/// Declares a marker standing for a generic parameter like [`A`], for generic types with more parameters or with
/// bounds [`A`] doesn't satisfy, which the declaring crate implements on the marker:
/// ```rust,ignore
/// generic_marker! {
///     /// Stands for the material of `MeshMaterial2d<M>`
///     pub struct M2d;
/// }
/// impl Material2d for M2d {}
/// app.register_type::<M2d>()
///     .register_generic_type::<MeshMaterial2d<M2d>>("sprite", &["M"], "...");
/// ```
/// The declaring crate needs `bevy_reflect`, and must register the marker, so it's not documented as a type of its own.
#[macro_export]
macro_rules! generic_marker {
    ($(#[$meta:meta])* $vis:vis struct $name:ident;) => {
        $(#[$meta])*
        #[derive(
            ::bevy_reflect::Reflect, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug,
        )]
        #[reflect($crate::function::generics::GenericMarker)]
        $vis struct $name;
    };
}

generic_marker! {
    /// Stands for the second parameter of a generic type, see [`A`].
    pub struct B;
}

generic_marker! {
    /// Stands for the third parameter of a generic type, see [`A`].
    pub struct C;
}

/// A type passed to a generic script function, converted as `R`, i.e. the component type `get_component` takes:
///
/// ```rust,ignore
/// fn get_component(entity: V<Entity>, registration: TypeOf<V<ScriptComponentRegistration>, A>)
///     -> Result<Option<ValueOf<A>>, InteropError>
/// ```
///
/// `M` is the marker standing for the function's parameter ([`A`]), [`ValueOf`] values of the same marker are of that type.
/// It only changes how the function is documented.
///
/// A type passed as a `String` is named by its path, i.e. `get_type_by_name("bevy_transform::components::transform::Transform")`.
pub struct TypeOf<R, M>(pub R, PhantomData<fn() -> M>);

impl<R, M> TypeOf<R, M> {
    /// Wrap the value the type is passed as.
    pub fn new(inner: R) -> Self {
        TypeOf(inner, PhantomData)
    }

    /// Unwrap the value the type is passed as.
    pub fn into_inner(self) -> R {
        self.0
    }
}

impl<R, M> Deref for TypeOf<R, M> {
    type Target = R;

    fn deref(&self) -> &R {
        &self.0
    }
}

impl<R: FromScript, M> FromScript for TypeOf<R, M> {
    type This<'w> = TypeOf<R::This<'w>, M>;

    fn from_script<'s>(
        value: ScriptValue,
        scope: &'s CallScope<'_>,
    ) -> Result<Self::This<'s>, InteropError> {
        R::from_script(value, scope).map(|inner| TypeOf(inner, PhantomData))
    }
}

impl<R: IntoScript, M> IntoScript for TypeOf<R, M> {
    fn into_script(self, world: WorldGuard) -> Result<ScriptValue, InteropError> {
        self.0.into_script(world)
    }
}

impl<R: ArgMeta, M> ArgMeta for TypeOf<R, M> {
    fn default_value() -> Option<ScriptValue> {
        R::default_value()
    }
}

impl<R: GetTypeDependencies, M> GetTypeDependencies for TypeOf<R, M> {
    type Underlying = R::Underlying;

    fn register_type_dependencies(registry: &mut TypeRegistry) {
        R::register_type_dependencies(registry)
    }
}

impl<R: TypedThrough, M: Typed> TypedThrough for TypeOf<R, M> {
    fn through_type_info() -> ThroughTypeInfo {
        ThroughTypeInfo::TypeOf {
            of: M::type_info(),
            erased: Box::new(R::through_type_info()),
        }
    }
}

/// A value of the type a [`TypeOf`] with the same marker was given, i.e. the component `get_component` returns.
///
/// It is a reference at runtime, and only changes how the function is documented.
pub struct ValueOf<M>(pub ReflectReference, PhantomData<fn() -> M>);

impl<M> ValueOf<M> {
    /// Wrap a reference to a value of the type.
    pub fn new(reference: ReflectReference) -> Self {
        ValueOf(reference, PhantomData)
    }

    /// Unwrap the reference.
    pub fn into_inner(self) -> ReflectReference {
        self.0
    }
}

impl<M> Deref for ValueOf<M> {
    type Target = ReflectReference;

    fn deref(&self) -> &ReflectReference {
        &self.0
    }
}

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

    fn from_script(value: ScriptValue, scope: &CallScope) -> Result<Self, InteropError> {
        ReflectReference::from_script(value, scope).map(ValueOf::new)
    }
}

impl<M> IntoScript for ValueOf<M> {
    fn into_script(self, world: WorldGuard) -> Result<ScriptValue, InteropError> {
        self.0.into_script(world)
    }
}

impl<M> ArgMeta for ValueOf<M> {}

impl<M> GetTypeDependencies for ValueOf<M> {
    type Underlying = ReflectReference;

    fn register_type_dependencies(registry: &mut TypeRegistry) {
        ReflectReference::register_type_dependencies(registry)
    }
}

impl<M: Typed> TypedThrough for ValueOf<M> {
    fn through_type_info() -> ThroughTypeInfo {
        ThroughTypeInfo::Val(M::type_info())
    }
}

/// A generic type declared for documentation, see [`GenericTypesAppExt::register_generic_type`].
#[derive(Clone, Debug)]
pub struct GenericTypeDeclaration {
    /// The generic type instantiated with markers in place of its parameters, i.e. `Handle<A>`
    pub type_info: &'static TypeInfo,
    /// The namespace of the generic type, i.e. `asset` for `Handle`
    pub namespace: &'static str,
    /// The names of the parameters, in order
    pub params: Vec<&'static str>,
    /// The documentation of the generic type
    pub documentation: &'static str,
}

/// The generic types declared for documentation, which documentation generators describe in terms of their parameters.
#[derive(Resource, Default, Clone, Debug)]
pub struct AppGenericTypes(pub Vec<GenericTypeDeclaration>);

/// Declares generic types for documentation, see [`AppGenericTypes`].
pub trait GenericTypesAppExt {
    /// Declares a generic type, so its instantiations are documented as such instead of as unrelated types.
    ///
    /// `G` is the generic type instantiated with [`A`] in place of its parameter, i.e. `Time<A>`, `namespace` is the one
    /// of its instantiations, i.e. `time`, and `params` names the parameters in order, i.e. `["T"]`.
    /// Also registers [`A`], so reflection can describe the uses of the parameter which only expose type ids, i.e. `HashSet<A>`.
    fn register_generic_type<G: Typed>(
        &mut self,
        namespace: &'static str,
        params: &[&'static str],
        documentation: &'static str,
    ) -> &mut Self;
}

impl GenericTypesAppExt for App {
    fn register_generic_type<G: Typed>(
        &mut self,
        namespace: &'static str,
        params: &[&'static str],
        documentation: &'static str,
    ) -> &mut Self {
        self.register_type::<A>()
            .register_type::<B>()
            .register_type::<C>();
        self.world_mut()
            .get_resource_or_init::<AppGenericTypes>()
            .0
            .push(GenericTypeDeclaration {
                type_info: G::type_info(),
                namespace,
                params: params.to_vec(),
                documentation,
            });
        self
    }
}