Skip to main content

xur_runtime/registry/
builder.rs

1use std::marker::PhantomData;
2
3use facet::Facet;
4use xur_resolve::NativeTypeId;
5
6use super::hooks::TypeHooks;
7use super::into_native::{IntoNativeFn, IntoNativeMethod, IntoNativeMethodMut};
8use super::{CallFn, Context, NativeType, Registry, Signature};
9use crate::{BuiltinType, RunResult, Value};
10
11/// Adds items to one module of a [`Registry`].
12pub struct ModuleBuilder<'r> {
13    registry: &'r Registry,
14    pub(super) module: usize,
15}
16
17impl<'r> ModuleBuilder<'r> {
18    pub(super) fn new(registry: &'r Registry, module: usize) -> Self {
19        Self { registry, module }
20    }
21}
22
23impl ModuleBuilder<'_> {
24    /// Registers a Rust function or closure whose argument and return
25    /// types implement [`Facet`].
26    pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
27        let (signature, call) = f.into_native();
28        let decl = self.registry.add_fn(name, Some(signature), call);
29        let module = self.module;
30        self.registry
31            .with_inner(|inner| inner.modules[module].functions.push(decl));
32        self
33    }
34
35    /// Registers a function that works on Xur values directly and can use
36    /// the running program through its [`Context`].
37    pub fn raw_function(
38        &mut self,
39        name: &str,
40        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
41    ) -> &mut Self {
42        let decl = self.registry.add_fn(name, None, Box::new(f));
43        let module = self.module;
44        self.registry
45            .with_inner(|inner| inner.modules[module].functions.push(decl));
46        self
47    }
48
49    /// Registers the Rust type `T` as `name`. Values of `T` passed to Xur
50    /// become native objects holding the Rust value.
51    pub fn ty<T: Facet<'static> + Clone + Send + 'static>(
52        &mut self,
53        name: &str,
54    ) -> TypeBuilder<'_, T> {
55        let module = self.module;
56        let id = self.registry.with_inner(|inner| {
57            let id = NativeTypeId(inner.types.len() as u32);
58            inner.types.push(NativeType {
59                name: name.to_owned(),
60                shape: T::SHAPE,
61                functions: Vec::new(),
62                hooks: TypeHooks::new::<T>(),
63            });
64            inner.modules[module].types.push(id);
65            id
66        });
67        TypeBuilder {
68            registry: self.registry,
69            ty: id,
70            _ty: PhantomData,
71        }
72    }
73}
74
75/// Adds functions to the registered native type `T`.
76pub struct TypeBuilder<'r, T> {
77    registry: &'r Registry,
78    ty: NativeTypeId,
79    _ty: PhantomData<T>,
80}
81
82impl<T: Facet<'static> + 'static> TypeBuilder<'_, T> {
83    /// Registers the associated function `Type::name`. If its first
84    /// parameter is `T` it can also be called as a method, on a copy.
85    pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
86        let (signature, call) = f.into_native();
87        self.add(name, signature, call)
88    }
89
90    /// Registers a function working on Xur values directly, with the
91    /// object first when called as a method. For methods taking or
92    /// returning arbitrary Xur values, like a channel's `send`.
93    pub fn raw_function(
94        &mut self,
95        name: &str,
96        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
97    ) -> &mut Self {
98        let decl = self.registry.add_fn(name, None, Box::new(f));
99        let ty = self.ty;
100        self.registry
101            .with_inner(|inner| inner.types[ty.0 as usize].functions.push(decl));
102        self
103    }
104
105    /// Registers a method taking `&self`: `value.name(args)` in Xur.
106    pub fn method<Marker>(&mut self, name: &str, f: impl IntoNativeMethod<T, Marker>) -> &mut Self {
107        let (signature, call) = f.into_native();
108        self.add(name, signature, call)
109    }
110
111    /// Registers a method taking `&mut self`, which changes the object in
112    /// place.
113    pub fn method_mut<Marker>(
114        &mut self,
115        name: &str,
116        f: impl IntoNativeMethodMut<T, Marker>,
117    ) -> &mut Self {
118        let (signature, call) = f.into_native();
119        self.add(name, signature, call)
120    }
121
122    fn add(&mut self, name: &str, signature: Signature, call: Box<CallFn>) -> &mut Self {
123        let decl = self.registry.add_fn(name, Some(signature), call);
124        let ty = self.ty;
125        self.registry
126            .with_inner(|inner| inner.types[ty.0 as usize].functions.push(decl));
127        self
128    }
129}
130
131/// Adds methods to a built-in type, like `list` or `str`.
132pub struct BuiltinBuilder<'r> {
133    registry: &'r Registry,
134    ty: BuiltinType,
135}
136
137impl<'r> BuiltinBuilder<'r> {
138    pub(super) fn new(registry: &'r Registry, ty: BuiltinType) -> Self {
139        Self { registry, ty }
140    }
141
142    /// Registers a method as a Rust function taking the receiver, converted,
143    /// first: `|s: String| s.to_uppercase()` for `"a".to_upper()`.
144    pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
145        let (signature, call) = f.into_native();
146        self.add(name, Some(signature), call)
147    }
148
149    /// Registers a method working on Xur values directly, with the receiver
150    /// first; needed to change a list in place.
151    pub fn raw_function(
152        &mut self,
153        name: &str,
154        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
155    ) -> &mut Self {
156        self.add(name, None, Box::new(f))
157    }
158
159    fn add(&mut self, name: &str, signature: Option<Signature>, call: Box<CallFn>) -> &mut Self {
160        let decl = self.registry.add_fn(name, signature, call);
161        let key = (self.ty, name.to_owned());
162        self.registry
163            .with_inner(|inner| inner.builtin_methods.insert(key, decl.id));
164        self
165    }
166}