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), Vec::new(), 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, Vec::new(), 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(
410            name,
411            None,
412            Vec::new(),
413            Box::new(f),
414            Some(ReturnHint::Shape(R::RET)),
415        )
416    }
417
418    /// Like [`raw_function_returns`](Self::raw_function_returns) for
419    /// xur-internal types that have no Facet equivalent.
420    pub fn raw_function_returns_xur(
421        &mut self,
422        name: &str,
423        ret: XurType,
424        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
425    ) -> &mut Self {
426        self.add(
427            name,
428            None,
429            Vec::new(),
430            Box::new(f),
431            Some(ReturnHint::Xur(ret)),
432        )
433    }
434
435    /// Registers a method taking `&self`: `value.name(args)` in Xur.
436    pub fn method<Marker>(&mut self, name: &str, f: impl IntoNativeMethod<T, Marker>) -> &mut Self {
437        let (signature, call) = f.into_native();
438        self.add(name, Some(signature), Vec::new(), call, None)
439    }
440
441    /// Registers a method taking `&mut self`, which changes the object in
442    /// place.
443    pub fn method_mut<Marker>(
444        &mut self,
445        name: &str,
446        f: impl IntoNativeMethodMut<T, Marker>,
447    ) -> &mut Self {
448        let (signature, call) = f.into_native();
449        self.add(name, Some(signature), Vec::new(), call, None)
450    }
451
452    /// Like [`function`](Self::function), naming the parameters for hovers
453    /// and docs.
454    pub fn named_function<Marker>(
455        &mut self,
456        name: &str,
457        params: &[&str],
458        f: impl IntoNativeFn<Marker>,
459    ) -> &mut Self {
460        let (signature, call) = f.into_native();
461        self.add(name, Some(signature), owned(params), call, None)
462    }
463
464    /// Like [`method`](Self::method), naming the parameters after the
465    /// receiver for hovers and docs.
466    pub fn named_method<Marker>(
467        &mut self,
468        name: &str,
469        params: &[&str],
470        f: impl IntoNativeMethod<T, Marker>,
471    ) -> &mut Self {
472        let (signature, call) = f.into_native();
473        self.add(name, Some(signature), with_self(params), call, None)
474    }
475
476    /// Like [`method_mut`](Self::method_mut), naming the parameters after
477    /// the receiver for hovers and docs.
478    pub fn named_method_mut<Marker>(
479        &mut self,
480        name: &str,
481        params: &[&str],
482        f: impl IntoNativeMethodMut<T, Marker>,
483    ) -> &mut Self {
484        let (signature, call) = f.into_native();
485        self.add(name, Some(signature), with_self(params), call, None)
486    }
487
488    fn add(
489        &mut self,
490        name: &str,
491        signature: Option<Signature>,
492        param_names: Vec<String>,
493        call: Box<CallFn>,
494        return_hint: Option<ReturnHint>,
495    ) -> &mut Self {
496        let decl = self.registry.add_fn(name, signature, param_names, call);
497        if let Some(hint) = return_hint {
498            self.registry.set_return_hint(decl.id, hint);
499        }
500        let ty = self.ty;
501        self.registry
502            .with_inner(|inner| inner.types[ty.0 as usize].functions.push(decl));
503        self
504    }
505}
506
507/// Adds methods to a built-in type, like `list` or `str`.
508pub struct BuiltinBuilder<'r> {
509    registry: &'r Registry,
510    ty: BuiltinType,
511}
512
513impl<'r> BuiltinBuilder<'r> {
514    pub(super) fn new(registry: &'r Registry, ty: BuiltinType) -> Self {
515        Self { registry, ty }
516    }
517
518    /// Registers a method as a Rust function taking the receiver, converted,
519    /// first: `|s: String| s.to_uppercase()` for `"a".to_upper()`.
520    ///
521    /// **Note:** this clones the receiver out of its `Value` wrapper. For
522    /// builtin types backed by `Arc<Mutex<..>>` (bytes, list), prefer
523    /// [`method`](Self::method) which borrows in place.
524    pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
525        let (signature, call) = f.into_native();
526        self.add(name, Some(signature), Vec::new(), call, None)
527    }
528
529    /// Registers a method that borrows the receiver without cloning:
530    /// `|bytes: &[u8], i: i64| -> Option<i64>`.
531    ///
532    /// `Recv` is `[u8]` for bytes or `str` for strings — any type that
533    /// implements [`BuiltinRecv`].
534    pub fn method<Recv: ?Sized + 'static, Marker>(
535        &mut self,
536        name: &str,
537        f: impl IntoBuiltinMethod<Recv, Marker>,
538    ) -> &mut Self {
539        let (signature, call) = f.into_native();
540        self.add(name, Some(signature), Vec::new(), call, None)
541    }
542
543    /// Like [`method`](Self::method) but borrows mutably:
544    /// `|bytes: &mut Vec<u8>, val: i64| { bytes.push(val as u8); }`.
545    pub fn method_mut<Recv: 'static, Marker>(
546        &mut self,
547        name: &str,
548        f: impl IntoBuiltinMethodMut<Recv, Marker>,
549    ) -> &mut Self {
550        let (signature, call) = f.into_native();
551        self.add(name, Some(signature), Vec::new(), call, None)
552    }
553
554    /// Registers a method working on Xur values directly, with the receiver
555    /// first; needed to change a list in place.
556    pub fn raw_function(
557        &mut self,
558        name: &str,
559        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
560    ) -> &mut Self {
561        self.add(name, None, Vec::new(), Box::new(f), None)
562    }
563
564    /// Like [`raw_function`](Self::raw_function), declaring the return type
565    /// for LSP inlay hints.
566    pub fn raw_function_returns<R: Returns>(
567        &mut self,
568        name: &str,
569        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
570    ) -> &mut Self {
571        self.add(
572            name,
573            None,
574            Vec::new(),
575            Box::new(f),
576            Some(ReturnHint::Shape(R::RET)),
577        )
578    }
579
580    /// Like [`raw_function_returns`](Self::raw_function_returns) for
581    /// xur-internal types that have no Facet equivalent.
582    pub fn raw_function_returns_xur(
583        &mut self,
584        name: &str,
585        ret: XurType,
586        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
587    ) -> &mut Self {
588        self.add(
589            name,
590            None,
591            Vec::new(),
592            Box::new(f),
593            Some(ReturnHint::Xur(ret)),
594        )
595    }
596
597    /// Like [`function`](Self::function), naming the parameters (the
598    /// receiver first) for hovers and docs.
599    pub fn named_function<Marker>(
600        &mut self,
601        name: &str,
602        params: &[&str],
603        f: impl IntoNativeFn<Marker>,
604    ) -> &mut Self {
605        let (signature, call) = f.into_native();
606        self.add(name, Some(signature), owned(params), call, None)
607    }
608
609    /// Like [`method`](Self::method), naming the parameters after the
610    /// receiver for hovers and docs.
611    pub fn named_method<Recv: ?Sized + 'static, Marker>(
612        &mut self,
613        name: &str,
614        params: &[&str],
615        f: impl IntoBuiltinMethod<Recv, Marker>,
616    ) -> &mut Self {
617        let (signature, call) = f.into_native();
618        self.add(name, Some(signature), owned(params), call, None)
619    }
620
621    /// Like [`method_mut`](Self::method_mut), naming the parameters after
622    /// the receiver for hovers and docs.
623    pub fn named_method_mut<Recv: 'static, Marker>(
624        &mut self,
625        name: &str,
626        params: &[&str],
627        f: impl IntoBuiltinMethodMut<Recv, Marker>,
628    ) -> &mut Self {
629        let (signature, call) = f.into_native();
630        self.add(name, Some(signature), owned(params), call, None)
631    }
632
633    fn add(
634        &mut self,
635        name: &str,
636        signature: Option<Signature>,
637        param_names: Vec<String>,
638        call: Box<CallFn>,
639        return_hint: Option<ReturnHint>,
640    ) -> &mut Self {
641        let decl = self.registry.add_fn(name, signature, param_names, call);
642        if let Some(hint) = return_hint {
643            self.registry.set_return_hint(decl.id, hint);
644        }
645        let key = (self.ty, name.to_owned());
646        self.registry
647            .with_inner(|inner| inner.builtin_methods.insert(key, decl.id));
648        self
649    }
650}
651
652fn owned(names: &[&str]) -> Vec<String> {
653    names.iter().map(|s| s.to_string()).collect()
654}
655
656/// Parameter names for a native type's method, whose signature includes the
657/// receiver: `self` and then `params`.
658fn with_self(params: &[&str]) -> Vec<String> {
659    std::iter::once("self")
660        .chain(params.iter().copied())
661        .map(String::from)
662        .collect()
663}