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