Skip to main content

xur_runtime/registry/
builder.rs

1use std::marker::PhantomData;
2
3use facet::{Facet, Shape};
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};
10use xur_resolve::{NativeVariantDecl, NativeVariantKind};
11
12/// Adds items to one module of a [`Registry`].
13pub struct ModuleBuilder<'r> {
14    registry: &'r Registry,
15    pub(super) module: usize,
16}
17
18impl<'r> ModuleBuilder<'r> {
19    pub(super) fn new(registry: &'r Registry, module: usize) -> Self {
20        Self { registry, module }
21    }
22
23    /// The registry being filled in.
24    pub fn registry(&self) -> &'r Registry {
25        self.registry
26    }
27
28    /// The submodule `name` of this module, created if needed. A lazy
29    /// module can fill in submodules as well as itself.
30    pub fn submodule(&self, name: &str) -> ModuleBuilder<'r> {
31        let parent = self.module;
32        let module = self
33            .registry
34            .with_inner(|inner| inner.child(Some(parent), name));
35        ModuleBuilder::new(self.registry, module)
36    }
37}
38
39impl ModuleBuilder<'_> {
40    /// Registers a Rust function or closure whose argument and return
41    /// types implement [`Facet`].
42    pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
43        let (signature, call) = f.into_native();
44        let decl = self.registry.add_fn(name, Some(signature), Vec::new(), call);
45        let module = self.module;
46        self.registry
47            .with_inner(|inner| inner.modules[module].functions.push(decl));
48        self
49    }
50
51    /// Like [`function`](Self::function), with explicit parameter names for
52    /// LSP hover and inlay hints.
53    pub fn named_function<Marker>(
54        &mut self,
55        name: &str,
56        params: &[&str],
57        f: impl IntoNativeFn<Marker>,
58    ) -> &mut Self {
59        let (signature, call) = f.into_native();
60        let names = params.iter().map(|s| s.to_string()).collect();
61        let decl = self.registry.add_fn(name, Some(signature), names, call);
62        let module = self.module;
63        self.registry
64            .with_inner(|inner| inner.modules[module].functions.push(decl));
65        self
66    }
67
68    /// Registers a function that works on Xur values directly and can use
69    /// the running program through its [`Context`].
70    pub fn raw_function(
71        &mut self,
72        name: &str,
73        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
74    ) -> &mut Self {
75        let decl = self.registry.add_fn(name, None, Vec::new(), Box::new(f));
76        let module = self.module;
77        self.registry
78            .with_inner(|inner| inner.modules[module].functions.push(decl));
79        self
80    }
81
82    /// Like [`raw_function`](Self::raw_function), with explicit parameter
83    /// names for LSP hover and inlay hints.
84    pub fn named_raw_function(
85        &mut self,
86        name: &str,
87        params: &[&str],
88        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
89    ) -> &mut Self {
90        let names = params.iter().map(|s| s.to_string()).collect();
91        let decl = self.registry.add_fn(name, None, names, Box::new(f));
92        let module = self.module;
93        self.registry
94            .with_inner(|inner| inner.modules[module].functions.push(decl));
95        self
96    }
97
98    /// Registers the type with facet shape `shape` as `name`, without its
99    /// Rust type: values of it passed to Xur become records of this type,
100    /// which written types can check and which display with its name. For
101    /// registering every type reachable from some shape, such as a
102    /// library's.
103    pub fn shape_type(&mut self, name: &str, shape: &'static Shape) -> NativeTypeId {
104        let module = self.module;
105        self.registry.with_inner(|inner| {
106            let id = NativeTypeId(inner.types.len() as u32);
107            inner.types.push(NativeType {
108                name: name.to_owned(),
109                shape,
110                functions: Vec::new(),
111                hooks: None,
112                explicit_variants: None,
113            });
114            inner.modules[module].types.push(id);
115            id
116        })
117    }
118
119    /// Registers a `#[repr(inttype)]` enum whose variants are integer
120    /// constants. Each `(name, value)` pair becomes a unit variant that
121    /// lowers to `Const(Int(value))`.
122    pub fn repr_enum(&mut self, name: &str, variants: &[(&str, i64)]) -> &mut Self {
123        let module = self.module;
124        let variant_decls: Vec<NativeVariantDecl> = variants
125            .iter()
126            .map(|(vname, value)| NativeVariantDecl {
127                name: vname.to_string(),
128                kind: NativeVariantKind::Unit,
129                repr_value: Some(*value),
130            })
131            .collect();
132        self.registry.with_inner(|inner| {
133            let id = NativeTypeId(inner.types.len() as u32);
134            inner.types.push(NativeType {
135                name: name.to_owned(),
136                shape: <()>::SHAPE,
137                functions: Vec::new(),
138                hooks: None,
139                explicit_variants: Some(variant_decls),
140            });
141            inner.modules[module].types.push(id);
142        });
143        self
144    }
145
146    /// Registers the Rust type `T` as `name`. Values of `T` passed to Xur
147    /// become native objects holding the Rust value.
148    pub fn ty<T: Facet<'static> + Clone + Send + 'static>(
149        &mut self,
150        name: &str,
151    ) -> TypeBuilder<'_, T> {
152        let module = self.module;
153        let id = self.registry.with_inner(|inner| {
154            let id = NativeTypeId(inner.types.len() as u32);
155            inner.types.push(NativeType {
156                name: name.to_owned(),
157                shape: T::SHAPE,
158                functions: Vec::new(),
159                hooks: Some(TypeHooks::new::<T>()),
160                explicit_variants: None,
161            });
162            inner.modules[module].types.push(id);
163            id
164        });
165        TypeBuilder {
166            registry: self.registry,
167            ty: id,
168            _ty: PhantomData,
169        }
170    }
171
172    /// Registers the Rust type `T` as `name` without requiring `Clone`, for
173    /// a type that borrows memory kept alive beside it (see
174    /// [`Registry::borrowing_object`]). Its fields and methods work, but it
175    /// cannot be cloned into another value or rebuilt from Xur.
176    pub fn ty_borrowing<T: Facet<'static> + Send + 'static>(
177        &mut self,
178        name: &str,
179    ) -> TypeBuilder<'_, T> {
180        let module = self.module;
181        let id = self.registry.with_inner(|inner| {
182            let id = NativeTypeId(inner.types.len() as u32);
183            inner.types.push(NativeType {
184                name: name.to_owned(),
185                shape: T::SHAPE,
186                functions: Vec::new(),
187                hooks: Some(TypeHooks::borrowing::<T>()),
188                explicit_variants: None,
189            });
190            inner.modules[module].types.push(id);
191            id
192        });
193        TypeBuilder {
194            registry: self.registry,
195            ty: id,
196            _ty: PhantomData,
197        }
198    }
199}
200
201/// Adds functions to the registered native type `T`.
202pub struct TypeBuilder<'r, T> {
203    registry: &'r Registry,
204    ty: NativeTypeId,
205    _ty: PhantomData<T>,
206}
207
208impl<T: Facet<'static> + 'static> TypeBuilder<'_, T> {
209    /// Registers the associated function `Type::name`. If its first
210    /// parameter is `T` it can also be called as a method, on a copy.
211    pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
212        let (signature, call) = f.into_native();
213        self.add(name, signature, call)
214    }
215
216    /// Registers a function working on Xur values directly, with the
217    /// object first when called as a method. For methods taking or
218    /// returning arbitrary Xur values, like a channel's `send`.
219    pub fn raw_function(
220        &mut self,
221        name: &str,
222        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
223    ) -> &mut Self {
224        let decl = self.registry.add_fn(name, None, Vec::new(), Box::new(f));
225        let ty = self.ty;
226        self.registry
227            .with_inner(|inner| inner.types[ty.0 as usize].functions.push(decl));
228        self
229    }
230
231    /// Registers a method taking `&self`: `value.name(args)` in Xur.
232    pub fn method<Marker>(&mut self, name: &str, f: impl IntoNativeMethod<T, Marker>) -> &mut Self {
233        let (signature, call) = f.into_native();
234        self.add(name, signature, call)
235    }
236
237    /// Registers a method taking `&mut self`, which changes the object in
238    /// place.
239    pub fn method_mut<Marker>(
240        &mut self,
241        name: &str,
242        f: impl IntoNativeMethodMut<T, Marker>,
243    ) -> &mut Self {
244        let (signature, call) = f.into_native();
245        self.add(name, signature, call)
246    }
247
248    fn add(&mut self, name: &str, signature: Signature, call: Box<CallFn>) -> &mut Self {
249        let decl = self.registry.add_fn(name, Some(signature), Vec::new(), call);
250        let ty = self.ty;
251        self.registry
252            .with_inner(|inner| inner.types[ty.0 as usize].functions.push(decl));
253        self
254    }
255}
256
257/// Adds methods to a built-in type, like `list` or `str`.
258pub struct BuiltinBuilder<'r> {
259    registry: &'r Registry,
260    ty: BuiltinType,
261}
262
263impl<'r> BuiltinBuilder<'r> {
264    pub(super) fn new(registry: &'r Registry, ty: BuiltinType) -> Self {
265        Self { registry, ty }
266    }
267
268    /// Registers a method as a Rust function taking the receiver, converted,
269    /// first: `|s: String| s.to_uppercase()` for `"a".to_upper()`.
270    pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
271        let (signature, call) = f.into_native();
272        self.add(name, Some(signature), call)
273    }
274
275    /// Registers a method working on Xur values directly, with the receiver
276    /// first; needed to change a list in place.
277    pub fn raw_function(
278        &mut self,
279        name: &str,
280        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
281    ) -> &mut Self {
282        self.add(name, None, Box::new(f))
283    }
284
285    fn add(&mut self, name: &str, signature: Option<Signature>, call: Box<CallFn>) -> &mut Self {
286        let decl = self.registry.add_fn(name, signature, Vec::new(), call);
287        let key = (self.ty, name.to_owned());
288        self.registry
289            .with_inner(|inner| inner.builtin_methods.insert(key, decl.id));
290        self
291    }
292}