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/// A type whose static [`Shape`] can serve as a return-type hint for the LSP.
13///
14/// Blanket-implemented for every [`Facet`] type. Implement manually for
15/// xur-only runtime types that have no Rust equivalent (see [`XurPtr`]).
16pub trait Returns {
17    const RET: &'static Shape;
18}
19
20impl<T: Facet<'static>> Returns for T {
21    const RET: &'static Shape = T::SHAPE;
22}
23
24/// Runtime-only xur types that have no Facet equivalent. Use with the
25/// An element type for compound return-type hints.
26#[derive(Clone, Copy)]
27pub enum ElemHint {
28    /// A Facet shape, introspectable for generics.
29    Shape(&'static Shape),
30    /// A type name for primitives that have no Facet representation (e.g. `type`).
31    Name(&'static str),
32    /// The nth type parameter of the receiver (e.g. element type of a list).
33    Param(u8),
34}
35
36/// `_xur` builder methods to annotate return types for the LSP.
37#[derive(Clone, Copy)]
38pub enum XurType {
39    /// Pointer with optional pointee type, displayed as `*T` or `ptr`.
40    Ptr(Option<&'static Shape>),
41    /// List with optional element type, displayed as `list` or `list[T]`.
42    List(Option<ElemHint>),
43    /// Map with optional key/value types, displayed as `map` or `map<K, V>`.
44    Map(Option<&'static Shape>, Option<&'static Shape>),
45    /// A named type with generic type parameters, e.g. `Result<module, str>`.
46    Named(&'static str, &'static [ElemHint]),
47    Record,
48    Module,
49    Unit,
50}
51
52impl XurType {
53    pub const PTR: Self = Self::Ptr(None);
54    pub const LIST: Self = Self::List(None);
55    pub const MAP: Self = Self::Map(None, None);
56    pub const UNIT: Self = Self::Unit;
57
58    pub fn ptr<T: Facet<'static>>() -> Self { Self::Ptr(Some(T::SHAPE)) }
59    pub fn list<T: Facet<'static>>() -> Self { Self::List(Some(ElemHint::Shape(T::SHAPE))) }
60    pub fn list_named(name: &'static str) -> Self { Self::List(Some(ElemHint::Name(name))) }
61    pub fn map<K: Facet<'static>, V: Facet<'static>>() -> Self {
62        Self::Map(Some(K::SHAPE), Some(V::SHAPE))
63    }
64    pub fn map_keys<K: Facet<'static>>() -> Self { Self::Map(Some(K::SHAPE), None) }
65    pub fn map_values<V: Facet<'static>>() -> Self { Self::Map(None, Some(V::SHAPE)) }
66}
67
68/// A return-type hint stored on a raw function: either a Facet [`Shape`]
69/// (introspectable for generics) or an [`XurType`] name.
70#[derive(Clone, Copy)]
71pub enum ReturnHint {
72    Shape(&'static Shape),
73    Xur(XurType),
74}
75
76/// Adds items to one module of a [`Registry`].
77pub struct ModuleBuilder<'r> {
78    registry: &'r Registry,
79    pub(super) module: usize,
80}
81
82impl<'r> ModuleBuilder<'r> {
83    pub(super) fn new(registry: &'r Registry, module: usize) -> Self {
84        Self { registry, module }
85    }
86
87    /// The registry being filled in.
88    pub fn registry(&self) -> &'r Registry {
89        self.registry
90    }
91
92    /// The submodule `name` of this module, created if needed. A lazy
93    /// module can fill in submodules as well as itself.
94    pub fn submodule(&self, name: &str) -> ModuleBuilder<'r> {
95        let parent = self.module;
96        let module = self
97            .registry
98            .with_inner(|inner| inner.child(Some(parent), name));
99        ModuleBuilder::new(self.registry, module)
100    }
101}
102
103impl ModuleBuilder<'_> {
104    /// Registers a Rust function or closure whose argument and return
105    /// types implement [`Facet`].
106    pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
107        let (signature, call) = f.into_native();
108        self.add_module_fn(name, Some(signature), Vec::new(), call, None)
109    }
110
111    /// Like [`function`](Self::function), with explicit parameter names for
112    /// LSP hover and inlay hints.
113    pub fn named_function<Marker>(
114        &mut self,
115        name: &str,
116        params: &[&str],
117        f: impl IntoNativeFn<Marker>,
118    ) -> &mut Self {
119        let (signature, call) = f.into_native();
120        let names = params.iter().map(|s| s.to_string()).collect();
121        self.add_module_fn(name, Some(signature), names, call, None)
122    }
123
124    /// Registers a function that works on Xur values directly and can use
125    /// the running program through its [`Context`].
126    pub fn raw_function(
127        &mut self,
128        name: &str,
129        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
130    ) -> &mut Self {
131        self.add_module_fn(name, None, Vec::new(), Box::new(f), None)
132    }
133
134    /// Like [`raw_function`](Self::raw_function), declaring the return type
135    /// for LSP inlay hints.
136    pub fn raw_function_returns<R: Returns>(
137        &mut self,
138        name: &str,
139        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
140    ) -> &mut Self {
141        self.add_module_fn(name, None, Vec::new(), Box::new(f), Some(ReturnHint::Shape(R::RET)))
142    }
143
144    /// Like [`raw_function_returns`](Self::raw_function_returns) for
145    /// xur-internal types that have no Facet equivalent.
146    pub fn raw_function_returns_xur(
147        &mut self,
148        name: &str,
149        ret: XurType,
150        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
151    ) -> &mut Self {
152        self.add_module_fn(name, None, Vec::new(), Box::new(f), Some(ReturnHint::Xur(ret)))
153    }
154
155    /// Like [`raw_function`](Self::raw_function), with explicit parameter
156    /// names for LSP hover and inlay hints.
157    pub fn named_raw_function(
158        &mut self,
159        name: &str,
160        params: &[&str],
161        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
162    ) -> &mut Self {
163        let names = params.iter().map(|s| s.to_string()).collect();
164        self.add_module_fn(name, None, names, Box::new(f), None)
165    }
166
167    /// Like [`named_raw_function`](Self::named_raw_function), declaring the
168    /// return type for LSP inlay hints.
169    pub fn named_raw_function_returns<R: Returns>(
170        &mut self,
171        name: &str,
172        params: &[&str],
173        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
174    ) -> &mut Self {
175        let names = params.iter().map(|s| s.to_string()).collect();
176        self.add_module_fn(name, None, names, Box::new(f), Some(ReturnHint::Shape(R::RET)))
177    }
178
179    /// Like [`named_raw_function_returns`](Self::named_raw_function_returns)
180    /// for xur-internal types that have no Facet equivalent.
181    pub fn named_raw_function_returns_xur(
182        &mut self,
183        name: &str,
184        params: &[&str],
185        ret: XurType,
186        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
187    ) -> &mut Self {
188        let names = params.iter().map(|s| s.to_string()).collect();
189        self.add_module_fn(name, None, names, Box::new(f), Some(ReturnHint::Xur(ret)))
190    }
191
192    fn add_module_fn(
193        &mut self,
194        name: &str,
195        signature: Option<Signature>,
196        names: Vec<String>,
197        call: Box<CallFn>,
198        return_hint: Option<ReturnHint>,
199    ) -> &mut Self {
200        let decl = self.registry.add_fn(name, signature, names, call);
201        if let Some(hint) = return_hint {
202            self.registry.set_return_hint(decl.id, hint);
203        }
204        let module = self.module;
205        self.registry
206            .with_inner(|inner| inner.modules[module].functions.push(decl));
207        self
208    }
209
210    /// Registers the type with facet shape `shape` as `name`, without its
211    /// Rust type: values of it passed to Xur become records of this type,
212    /// which written types can check and which display with its name. For
213    /// registering every type reachable from some shape, such as a
214    /// library's.
215    pub fn shape_type(&mut self, name: &str, shape: &'static Shape) -> NativeTypeId {
216        let module = self.module;
217        self.registry.with_inner(|inner| {
218            let id = NativeTypeId(inner.types.len() as u32);
219            inner.types.push(NativeType {
220                name: name.to_owned(),
221                shape,
222                functions: Vec::new(),
223                hooks: None,
224                explicit_variants: None,
225            });
226            inner.modules[module].types.push(id);
227            id
228        })
229    }
230
231    /// Registers a `#[repr(inttype)]` enum whose variants are integer
232    /// constants. Each `(name, value)` pair becomes a unit variant that
233    /// lowers to `Const(Int(value))`.
234    pub fn repr_enum(&mut self, name: &str, variants: &[(&str, i64)]) -> &mut Self {
235        let module = self.module;
236        let variant_decls: Vec<NativeVariantDecl> = variants
237            .iter()
238            .map(|(vname, value)| NativeVariantDecl {
239                name: vname.to_string(),
240                kind: NativeVariantKind::Unit,
241                repr_value: Some(*value),
242            })
243            .collect();
244        self.registry.with_inner(|inner| {
245            let id = NativeTypeId(inner.types.len() as u32);
246            inner.types.push(NativeType {
247                name: name.to_owned(),
248                shape: <()>::SHAPE,
249                functions: Vec::new(),
250                hooks: None,
251                explicit_variants: Some(variant_decls),
252            });
253            inner.modules[module].types.push(id);
254        });
255        self
256    }
257
258    /// Registers the Rust type `T` as `name`. Values of `T` passed to Xur
259    /// become native objects holding the Rust value.
260    pub fn ty<T: Facet<'static> + Clone + Send + 'static>(
261        &mut self,
262        name: &str,
263    ) -> TypeBuilder<'_, T> {
264        let module = self.module;
265        let id = self.registry.with_inner(|inner| {
266            let id = NativeTypeId(inner.types.len() as u32);
267            inner.types.push(NativeType {
268                name: name.to_owned(),
269                shape: T::SHAPE,
270                functions: Vec::new(),
271                hooks: Some(TypeHooks::new::<T>()),
272                explicit_variants: None,
273            });
274            inner.modules[module].types.push(id);
275            id
276        });
277        TypeBuilder {
278            registry: self.registry,
279            ty: id,
280            _ty: PhantomData,
281        }
282    }
283
284    /// Registers the Rust type `T` as `name` without requiring `Clone`, for
285    /// a type that borrows memory kept alive beside it (see
286    /// [`Registry::borrowing_object`]). Its fields and methods work, but it
287    /// cannot be cloned into another value or rebuilt from Xur.
288    pub fn ty_borrowing<T: Facet<'static> + Send + 'static>(
289        &mut self,
290        name: &str,
291    ) -> TypeBuilder<'_, T> {
292        let module = self.module;
293        let id = self.registry.with_inner(|inner| {
294            let id = NativeTypeId(inner.types.len() as u32);
295            inner.types.push(NativeType {
296                name: name.to_owned(),
297                shape: T::SHAPE,
298                functions: Vec::new(),
299                hooks: Some(TypeHooks::borrowing::<T>()),
300                explicit_variants: None,
301            });
302            inner.modules[module].types.push(id);
303            id
304        });
305        TypeBuilder {
306            registry: self.registry,
307            ty: id,
308            _ty: PhantomData,
309        }
310    }
311}
312
313/// Adds functions to the registered native type `T`.
314pub struct TypeBuilder<'r, T> {
315    registry: &'r Registry,
316    ty: NativeTypeId,
317    _ty: PhantomData<T>,
318}
319
320impl<T: Facet<'static> + 'static> TypeBuilder<'_, T> {
321    /// Registers the associated function `Type::name`. If its first
322    /// parameter is `T` it can also be called as a method, on a copy.
323    pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
324        let (signature, call) = f.into_native();
325        self.add(name, Some(signature), call, None)
326    }
327
328    /// Registers a function working on Xur values directly, with the
329    /// object first when called as a method. For methods taking or
330    /// returning arbitrary Xur values, like a channel's `send`.
331    pub fn raw_function(
332        &mut self,
333        name: &str,
334        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
335    ) -> &mut Self {
336        self.add(name, None, Box::new(f), None)
337    }
338
339    /// Like [`raw_function`](Self::raw_function), declaring the return type
340    /// for LSP inlay hints.
341    pub fn raw_function_returns<R: Returns>(
342        &mut self,
343        name: &str,
344        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
345    ) -> &mut Self {
346        self.add(name, None, Box::new(f), Some(ReturnHint::Shape(R::RET)))
347    }
348
349    /// Like [`raw_function_returns`](Self::raw_function_returns) for
350    /// xur-internal types that have no Facet equivalent.
351    pub fn raw_function_returns_xur(
352        &mut self,
353        name: &str,
354        ret: XurType,
355        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
356    ) -> &mut Self {
357        self.add(name, None, Box::new(f), Some(ReturnHint::Xur(ret)))
358    }
359
360    /// Registers a method taking `&self`: `value.name(args)` in Xur.
361    pub fn method<Marker>(&mut self, name: &str, f: impl IntoNativeMethod<T, Marker>) -> &mut Self {
362        let (signature, call) = f.into_native();
363        self.add(name, Some(signature), call, None)
364    }
365
366    /// Registers a method taking `&mut self`, which changes the object in
367    /// place.
368    pub fn method_mut<Marker>(
369        &mut self,
370        name: &str,
371        f: impl IntoNativeMethodMut<T, Marker>,
372    ) -> &mut Self {
373        let (signature, call) = f.into_native();
374        self.add(name, Some(signature), call, None)
375    }
376
377    fn add(
378        &mut self,
379        name: &str,
380        signature: Option<Signature>,
381        call: Box<CallFn>,
382        return_hint: Option<ReturnHint>,
383    ) -> &mut Self {
384        let decl = self.registry.add_fn(name, signature, Vec::new(), call);
385        if let Some(hint) = return_hint {
386            self.registry.set_return_hint(decl.id, hint);
387        }
388        let ty = self.ty;
389        self.registry
390            .with_inner(|inner| inner.types[ty.0 as usize].functions.push(decl));
391        self
392    }
393}
394
395/// Adds methods to a built-in type, like `list` or `str`.
396pub struct BuiltinBuilder<'r> {
397    registry: &'r Registry,
398    ty: BuiltinType,
399}
400
401impl<'r> BuiltinBuilder<'r> {
402    pub(super) fn new(registry: &'r Registry, ty: BuiltinType) -> Self {
403        Self { registry, ty }
404    }
405
406    /// Registers a method as a Rust function taking the receiver, converted,
407    /// first: `|s: String| s.to_uppercase()` for `"a".to_upper()`.
408    pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
409        let (signature, call) = f.into_native();
410        self.add(name, Some(signature), call, None)
411    }
412
413    /// Registers a method working on Xur values directly, with the receiver
414    /// first; needed to change a list in place.
415    pub fn raw_function(
416        &mut self,
417        name: &str,
418        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
419    ) -> &mut Self {
420        self.add(name, None, Box::new(f), None)
421    }
422
423    /// Like [`raw_function`](Self::raw_function), declaring the return type
424    /// for LSP inlay hints.
425    pub fn raw_function_returns<R: Returns>(
426        &mut self,
427        name: &str,
428        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
429    ) -> &mut Self {
430        self.add(name, None, Box::new(f), Some(ReturnHint::Shape(R::RET)))
431    }
432
433    /// Like [`raw_function_returns`](Self::raw_function_returns) for
434    /// xur-internal types that have no Facet equivalent.
435    pub fn raw_function_returns_xur(
436        &mut self,
437        name: &str,
438        ret: XurType,
439        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
440    ) -> &mut Self {
441        self.add(name, None, Box::new(f), Some(ReturnHint::Xur(ret)))
442    }
443
444    fn add(
445        &mut self,
446        name: &str,
447        signature: Option<Signature>,
448        call: Box<CallFn>,
449        return_hint: Option<ReturnHint>,
450    ) -> &mut Self {
451        let decl = self.registry.add_fn(name, signature, Vec::new(), call);
452        if let Some(hint) = return_hint {
453            self.registry.set_return_hint(decl.id, hint);
454        }
455        let key = (self.ty, name.to_owned());
456        self.registry
457            .with_inner(|inner| inner.builtin_methods.insert(key, decl.id));
458        self
459    }
460}