Skip to main content

bevy_mod_scripting_bindings/function/
namespace.rs

1//! A module for managing namespaces for functions
2
3use crate::{
4    DummyScriptFunctionRegistry, ScriptFunctionRegistryArc,
5    docgen::info::GetFunctionInfo,
6    function::script_function::{AppScriptFunctionRegistry, ScriptFunction},
7};
8use ::bevy_reflect::{GetTypeRegistration, Reflect};
9use bevy_ecs::{reflect::AppTypeRegistry, world::World};
10use bevy_mod_scripting_derive::DebugWithTypeInfo;
11use bevy_mod_scripting_display::{DisplayWithTypeInfo, WithTypeInfo};
12use bevy_mod_scripting_world::WorldGuard;
13use std::{any::TypeId, borrow::Cow, marker::PhantomData};
14
15use super::type_dependencies::GetFunctionTypeDependencies;
16
17/// A namespace for functions
18#[derive(Clone, Copy, PartialEq, Eq, Hash, Default, Reflect, DebugWithTypeInfo)]
19#[debug_with_type_info(bms_display_path = "bevy_mod_scripting_display")]
20pub enum Namespace {
21    /// The function is registered in the global namespace, i.e. with no namespace.
22    /// In practice functions in this namespace should be callable directly by their name, i.e. `my_function()`
23    #[default]
24    Global,
25    /// The function is registered in the namespace corresponding to the given type.
26    /// In practice functions in this namespace should be callable by their qualified name, i.e. `MyType.my_function()`
27    OnType(TypeId),
28}
29
30/// A type which implements [`IntoNamespace`] by always converting to the global namespace
31pub struct GlobalNamespace;
32
33/// A type convertible to a [`Namespace`]
34pub trait IntoNamespace {
35    /// Converts this type into a [`Namespace`]
36    fn into_namespace() -> Namespace;
37}
38
39impl<T: ?Sized + 'static> IntoNamespace for T {
40    fn into_namespace() -> Namespace {
41        if TypeId::of::<T>() == TypeId::of::<GlobalNamespace>() {
42            Namespace::Global
43        } else {
44            Namespace::OnType(TypeId::of::<T>())
45        }
46    }
47}
48
49/// A type which implements [`IntoNamespace`] by always converting to the global namespace
50#[profiling::all_functions]
51impl Namespace {
52    /// Returns the prefix for this namespace
53    pub fn prefix(self) -> Cow<'static, str> {
54        match self {
55            Namespace::Global => Cow::Borrowed(""),
56            Namespace::OnType(type_id) => Cow::Owned(format!("{type_id:?}::")),
57        }
58    }
59
60    /// Returns the fully qualified name of a function in this namespace
61    pub fn function_name<I: Into<Cow<'static, str>>>(self, name: I) -> Cow<'static, str> {
62        match self {
63            Namespace::Global => name.into(),
64            Namespace::OnType(type_id) => Cow::Owned(format!("{:?}::{}", type_id, name.into())),
65        }
66    }
67}
68
69/// A convenience builder for registering multiple functions in a namespace
70pub struct NamespaceBuilder<'a, N> {
71    /// If true will use the dummy function registry instead
72    registry: ScriptFunctionRegistryArc,
73    /// phantom data to reference the namespace type
74    namespace: PhantomData<N>,
75    /// a cached reference to the world
76    pub world: &'a mut World,
77}
78
79#[profiling::all_functions]
80impl<'a, S: IntoNamespace> NamespaceBuilder<'a, S> {
81    /// Creates a new `NamespaceBuilder` that will register functions in the namespace corresponding to the given type
82    /// It will also register the type itself in the type registry.
83    pub fn new(world: &'a mut World) -> Self
84    where
85        S: GetTypeRegistration,
86    {
87        {
88            let registry = world.get_resource_or_init::<AppTypeRegistry>();
89            let mut registry = registry.write();
90            registry.register::<S>();
91        }
92        Self {
93            registry: world
94                .get_resource_or_init::<AppScriptFunctionRegistry>()
95                .0
96                .clone(),
97            namespace: Default::default(),
98            world,
99        }
100    }
101
102    /// Prefer using the `register` method on the `NamespaceBuilder` instead
103    pub fn new_unregistered(world: &'a mut World) -> Self {
104        Self {
105            registry: world
106                .get_resource_or_init::<AppScriptFunctionRegistry>()
107                .0
108                .clone(),
109            namespace: Default::default(),
110            world,
111        }
112    }
113
114    /// Register functions for this namespace on the dummy function registry instead.
115    ///
116    /// This will appear in documentation but not become callable.
117    pub fn with_dummy_registry(mut self) -> Self {
118        self.registry = self
119            .world
120            .get_resource_or_init::<DummyScriptFunctionRegistry>()
121            .0
122            .clone();
123        self
124    }
125
126    /// Registers a function in the namespace
127    pub fn register<'env, N, F, M>(&mut self, name: N, function: F) -> &mut Self
128    where
129        N: Into<Cow<'static, str>>,
130        F: ScriptFunction<'env, M> + GetFunctionTypeDependencies<M> + GetFunctionInfo<M>,
131    {
132        self.register_inner(name, function, None, None)
133    }
134
135    /// Registers a function in the namespace with a docstring
136    pub fn register_documented<'env, N, F, M>(
137        &mut self,
138        name: N,
139        function: F,
140        docstring: &'static str,
141        arg_names: &'static [&'static str],
142    ) -> &mut Self
143    where
144        N: Into<Cow<'static, str>>,
145        F: ScriptFunction<'env, M> + GetFunctionTypeDependencies<M> + GetFunctionInfo<M>,
146    {
147        self.register_inner(name, function, Some(docstring), Some(arg_names))
148    }
149
150    fn register_inner<'env, N, F, M>(
151        &mut self,
152        name: N,
153        function: F,
154        docstring: Option<&'static str>,
155        arg_names: Option<&'static [&'static str]>,
156    ) -> &mut Self
157    where
158        N: Into<Cow<'static, str>>,
159        F: ScriptFunction<'env, M> + GetFunctionTypeDependencies<M> + GetFunctionInfo<M>,
160    {
161        {
162            {
163                let mut registry = self.registry.write();
164                registry.register_with_arg_names(
165                    S::into_namespace(),
166                    name,
167                    function,
168                    docstring.unwrap_or_default(),
169                    arg_names.unwrap_or(&[]),
170                );
171            }
172            {
173                let type_registry = self.world.get_resource_or_init::<AppTypeRegistry>();
174                let mut type_registry = type_registry.write();
175                F::register_type_dependencies(&mut type_registry);
176            }
177        }
178        self
179    }
180}
181
182impl From<TypeId> for Namespace {
183    fn from(value: TypeId) -> Self {
184        Namespace::OnType(value)
185    }
186}
187
188impl DisplayWithTypeInfo for Namespace {
189    fn display_with_type_info(
190        &self,
191        f: &mut std::fmt::Formatter<'_>,
192        type_info_provider: Option<&WorldGuard>,
193    ) -> std::fmt::Result {
194        match self {
195            Namespace::Global => f.write_str("Global Namespace"),
196            Namespace::OnType(type_id) => {
197                write!(
198                    f,
199                    "Namespace for type {}",
200                    WithTypeInfo::new_with_opt_info(type_id, type_info_provider)
201                )
202            }
203        }
204    }
205}