Skip to main content

xur_runtime/registry/
builder.rs

1use std::marker::PhantomData;
2
3use facet::{Facet, Shape};
4use xur_resolve::{NativeFnId, 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 an attribute whose arguments parse into `T` (a
132    /// `#[derive(Facet)]` type authored to match its syntax). After
133    /// resolution the parsed value is queryable via
134    /// `resolutions.attribute::<T>(target, name)`.
135    pub fn register_attribute<T>(
136        &mut self,
137        name: &str,
138        kind: xur_resolve::AttributeKind,
139    ) -> &mut Self
140    where
141        T: Facet<'static> + Send + Sync,
142    {
143        let spec = super::attribute::spec::<T>(kind);
144        self.registry.with_inner(|inner| {
145            inner.modules[self.module]
146                .attributes
147                .insert(name.to_owned(), spec);
148        });
149        self
150    }
151
152    /// Registers a Rust function or closure whose argument and return
153    /// types implement [`Facet`].
154    pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
155        let (signature, call) = f.into_native();
156        self.add_module_fn(name, Some(signature), Vec::new(), call, None)
157    }
158
159    /// Like [`function`](Self::function), with explicit parameter names for
160    /// LSP hover and inlay hints.
161    pub fn named_function<Marker>(
162        &mut self,
163        name: &str,
164        params: &[&str],
165        f: impl IntoNativeFn<Marker>,
166    ) -> &mut Self {
167        let (signature, call) = f.into_native();
168        let names = params.iter().map(|s| s.to_string()).collect();
169        self.add_module_fn(name, Some(signature), names, call, None)
170    }
171
172    /// Registers a function that works on Xur values directly and can use
173    /// the running program through its [`Context`].
174    pub fn raw_function(
175        &mut self,
176        name: &str,
177        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
178    ) -> &mut Self {
179        self.add_module_fn(name, None, Vec::new(), Box::new(f), None)
180    }
181
182    /// Like [`raw_function`](Self::raw_function), declaring the return type
183    /// for LSP inlay hints.
184    pub fn raw_function_returns<R: Returns>(
185        &mut self,
186        name: &str,
187        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
188    ) -> &mut Self {
189        self.add_module_fn(
190            name,
191            None,
192            Vec::new(),
193            Box::new(f),
194            Some(ReturnHint::Shape(R::RET)),
195        )
196    }
197
198    /// Like [`raw_function_returns`](Self::raw_function_returns) for
199    /// xur-internal types that have no Facet equivalent.
200    pub fn raw_function_returns_xur(
201        &mut self,
202        name: &str,
203        ret: XurType,
204        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
205    ) -> &mut Self {
206        self.add_module_fn(
207            name,
208            None,
209            Vec::new(),
210            Box::new(f),
211            Some(ReturnHint::Xur(ret)),
212        )
213    }
214
215    /// Like [`raw_function`](Self::raw_function), with explicit parameter
216    /// names for LSP hover and inlay hints.
217    pub fn named_raw_function(
218        &mut self,
219        name: &str,
220        params: &[&str],
221        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
222    ) -> &mut Self {
223        let names = params.iter().map(|s| s.to_string()).collect();
224        self.add_module_fn(name, None, names, Box::new(f), None)
225    }
226
227    /// Like [`named_raw_function`](Self::named_raw_function), declaring the
228    /// return type for LSP inlay hints.
229    pub fn named_raw_function_returns<R: Returns>(
230        &mut self,
231        name: &str,
232        params: &[&str],
233        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
234    ) -> &mut Self {
235        let names = params.iter().map(|s| s.to_string()).collect();
236        self.add_module_fn(
237            name,
238            None,
239            names,
240            Box::new(f),
241            Some(ReturnHint::Shape(R::RET)),
242        )
243    }
244
245    /// Like [`named_raw_function_returns`](Self::named_raw_function_returns)
246    /// for xur-internal types that have no Facet equivalent.
247    pub fn named_raw_function_returns_xur(
248        &mut self,
249        name: &str,
250        params: &[&str],
251        ret: XurType,
252        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
253    ) -> &mut Self {
254        let names = params.iter().map(|s| s.to_string()).collect();
255        self.add_module_fn(name, None, names, Box::new(f), Some(ReturnHint::Xur(ret)))
256    }
257
258    pub(super) fn add_raw(
259        &mut self,
260        name: &str,
261        names: Vec<String>,
262        call: Box<CallFn>,
263    ) -> NativeFnId {
264        let decl = self.registry.add_fn(name, None, names, call);
265        let id = decl.id;
266        let module = self.module;
267        self.registry
268            .with_inner(|inner| inner.modules[module].functions.push(decl));
269        id
270    }
271
272    fn add_module_fn(
273        &mut self,
274        name: &str,
275        signature: Option<Signature>,
276        names: Vec<String>,
277        call: Box<CallFn>,
278        return_hint: Option<ReturnHint>,
279    ) -> &mut Self {
280        let decl = self.registry.add_fn(name, signature, names, call);
281        if let Some(hint) = return_hint {
282            self.registry.set_return_hint(decl.id, hint);
283        }
284        let module = self.module;
285        self.registry
286            .with_inner(|inner| inner.modules[module].functions.push(decl));
287        self
288    }
289
290    /// Registers the type with facet shape `shape` as `name`, without its
291    /// Rust type: values of it passed to Xur become records of this type,
292    /// which written types can check and which display with its name. For
293    /// registering every type reachable from some shape, such as a
294    /// library's.
295    pub fn shape_type(&mut self, name: &str, shape: &'static Shape) -> NativeTypeId {
296        let module = self.module;
297        self.registry.with_inner(|inner| {
298            let id = NativeTypeId(inner.types.len() as u32);
299            inner.types.push(NativeType {
300                name: name.to_owned(),
301                shape,
302                functions: Vec::new(),
303                hooks: None,
304                explicit_variants: None,
305            });
306            inner.modules[module].types.push(id);
307            id
308        })
309    }
310
311    /// Registers a `#[repr(inttype)]` enum whose variants are integer
312    /// constants. Each `(name, value)` pair becomes a unit variant that
313    /// lowers to `Const(Int(value))`.
314    pub fn repr_enum(&mut self, name: &str, variants: &[(&str, i64)]) -> &mut Self {
315        let module = self.module;
316        let variant_decls: Vec<NativeVariantDecl> = variants
317            .iter()
318            .map(|(vname, value)| NativeVariantDecl {
319                name: vname.to_string(),
320                kind: NativeVariantKind::Unit,
321                repr_value: Some(*value),
322            })
323            .collect();
324        self.registry.with_inner(|inner| {
325            let id = NativeTypeId(inner.types.len() as u32);
326            inner.types.push(NativeType {
327                name: name.to_owned(),
328                shape: <()>::SHAPE,
329                functions: Vec::new(),
330                hooks: None,
331                explicit_variants: Some(variant_decls),
332            });
333            inner.modules[module].types.push(id);
334        });
335        self
336    }
337
338    /// Returns a [`TypeBuilder`] for a type `T` that was already registered
339    /// (by this or another module's [`ty`](Self::ty)). Use it to add methods
340    /// to a shared type from a different module. Panics if `T` has not been
341    /// registered yet.
342    pub fn ty_existing<T: Facet<'static> + Clone + Send + 'static>(
343        &mut self,
344    ) -> TypeBuilder<'_, T> {
345        let id = self
346            .registry
347            .type_of_shape(T::SHAPE)
348            .expect("ty_existing: type not registered");
349        TypeBuilder {
350            registry: self.registry,
351            ty: id,
352            _ty: PhantomData,
353        }
354    }
355
356    /// Registers the Rust type `T` as `name`. Values of `T` passed to Xur
357    /// become native objects holding the Rust value.
358    pub fn ty<T: Facet<'static> + Clone + Send + 'static>(
359        &mut self,
360        name: &str,
361    ) -> TypeBuilder<'_, T> {
362        let module = self.module;
363        let id = self.registry.with_inner(|inner| {
364            let id = NativeTypeId(inner.types.len() as u32);
365            inner.types.push(NativeType {
366                name: name.to_owned(),
367                shape: T::SHAPE,
368                functions: Vec::new(),
369                hooks: Some(TypeHooks::new::<T>()),
370                explicit_variants: None,
371            });
372            inner.modules[module].types.push(id);
373            id
374        });
375        TypeBuilder {
376            registry: self.registry,
377            ty: id,
378            _ty: PhantomData,
379        }
380    }
381
382    /// Registers the Rust type `T` as `name` without requiring `Clone`, for
383    /// a type that borrows memory kept alive beside it (see
384    /// [`Registry::borrowing_object`]). Its fields and methods work, but it
385    /// cannot be cloned into another value or rebuilt from Xur.
386    pub fn ty_borrowing<T: Facet<'static> + Send + 'static>(
387        &mut self,
388        name: &str,
389    ) -> TypeBuilder<'_, T> {
390        let module = self.module;
391        let id = self.registry.with_inner(|inner| {
392            let id = NativeTypeId(inner.types.len() as u32);
393            inner.types.push(NativeType {
394                name: name.to_owned(),
395                shape: T::SHAPE,
396                functions: Vec::new(),
397                hooks: Some(TypeHooks::borrowing::<T>()),
398                explicit_variants: None,
399            });
400            inner.modules[module].types.push(id);
401            id
402        });
403        TypeBuilder {
404            registry: self.registry,
405            ty: id,
406            _ty: PhantomData,
407        }
408    }
409}
410
411/// Adds functions to the registered native type `T`.
412pub struct TypeBuilder<'r, T> {
413    registry: &'r Registry,
414    ty: NativeTypeId,
415    _ty: PhantomData<T>,
416}
417
418impl<T: Facet<'static> + 'static> TypeBuilder<'_, T> {
419    /// Registers the associated function `Type::name`. If its first
420    /// parameter is `T` it can also be called as a method, on a copy.
421    pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
422        let (signature, call) = f.into_native();
423        self.add(name, Some(signature), Vec::new(), call, None)
424    }
425
426    /// Registers a function working on Xur values directly, with the
427    /// object first when called as a method. For methods taking or
428    /// returning arbitrary Xur values, like a channel's `send`.
429    pub fn raw_function(
430        &mut self,
431        name: &str,
432        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
433    ) -> &mut Self {
434        self.add(name, None, Vec::new(), Box::new(f), None)
435    }
436
437    /// Like [`raw_function`](Self::raw_function), declaring the return type
438    /// for LSP inlay hints.
439    pub fn raw_function_returns<R: Returns>(
440        &mut self,
441        name: &str,
442        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
443    ) -> &mut Self {
444        self.add(
445            name,
446            None,
447            Vec::new(),
448            Box::new(f),
449            Some(ReturnHint::Shape(R::RET)),
450        )
451    }
452
453    /// Like [`raw_function_returns`](Self::raw_function_returns) for
454    /// xur-internal types that have no Facet equivalent.
455    pub fn raw_function_returns_xur(
456        &mut self,
457        name: &str,
458        ret: XurType,
459        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
460    ) -> &mut Self {
461        self.add(
462            name,
463            None,
464            Vec::new(),
465            Box::new(f),
466            Some(ReturnHint::Xur(ret)),
467        )
468    }
469
470    /// Registers a method taking `&self`: `value.name(args)` in Xur.
471    pub fn method<Marker>(&mut self, name: &str, f: impl IntoNativeMethod<T, Marker>) -> &mut Self {
472        let (signature, call) = f.into_native();
473        self.add(name, Some(signature), Vec::new(), call, None)
474    }
475
476    /// Registers a method taking `&mut self`, which changes the object in
477    /// place.
478    pub fn method_mut<Marker>(
479        &mut self,
480        name: &str,
481        f: impl IntoNativeMethodMut<T, Marker>,
482    ) -> &mut Self {
483        let (signature, call) = f.into_native();
484        self.add(name, Some(signature), Vec::new(), call, None)
485    }
486
487    /// Like [`function`](Self::function), naming the parameters for hovers
488    /// and docs.
489    pub fn named_function<Marker>(
490        &mut self,
491        name: &str,
492        params: &[&str],
493        f: impl IntoNativeFn<Marker>,
494    ) -> &mut Self {
495        let (signature, call) = f.into_native();
496        self.add(name, Some(signature), owned(params), call, None)
497    }
498
499    /// Like [`method`](Self::method), naming the parameters after the
500    /// receiver for hovers and docs.
501    pub fn named_method<Marker>(
502        &mut self,
503        name: &str,
504        params: &[&str],
505        f: impl IntoNativeMethod<T, Marker>,
506    ) -> &mut Self {
507        let (signature, call) = f.into_native();
508        self.add(name, Some(signature), with_self(params), call, None)
509    }
510
511    /// Like [`method_mut`](Self::method_mut), naming the parameters after
512    /// the receiver for hovers and docs.
513    pub fn named_method_mut<Marker>(
514        &mut self,
515        name: &str,
516        params: &[&str],
517        f: impl IntoNativeMethodMut<T, Marker>,
518    ) -> &mut Self {
519        let (signature, call) = f.into_native();
520        self.add(name, Some(signature), with_self(params), call, None)
521    }
522
523    /// The registry being filled in.
524    pub fn registry(&self) -> &Registry {
525        self.registry
526    }
527
528    pub(super) fn add_raw(
529        &mut self,
530        name: &str,
531        names: Vec<String>,
532        call: Box<CallFn>,
533    ) -> NativeFnId {
534        let decl = self.registry.add_fn(name, None, names, call);
535        let id = decl.id;
536        let ty = self.ty;
537        self.registry
538            .with_inner(|inner| inner.types[ty.0 as usize].functions.push(decl));
539        id
540    }
541
542    fn add(
543        &mut self,
544        name: &str,
545        signature: Option<Signature>,
546        param_names: Vec<String>,
547        call: Box<CallFn>,
548        return_hint: Option<ReturnHint>,
549    ) -> &mut Self {
550        let decl = self.registry.add_fn(name, signature, param_names, call);
551        if let Some(hint) = return_hint {
552            self.registry.set_return_hint(decl.id, hint);
553        }
554        let ty = self.ty;
555        self.registry
556            .with_inner(|inner| inner.types[ty.0 as usize].functions.push(decl));
557        self
558    }
559}
560
561/// Adds methods to a built-in type, like `list` or `str`.
562pub struct BuiltinBuilder<'r> {
563    registry: &'r Registry,
564    ty: BuiltinType,
565}
566
567impl<'r> BuiltinBuilder<'r> {
568    pub(super) fn new(registry: &'r Registry, ty: BuiltinType) -> Self {
569        Self { registry, ty }
570    }
571
572    /// Registers a method as a Rust function taking the receiver, converted,
573    /// first: `|s: String| s.to_uppercase()` for `"a".to_upper()`.
574    ///
575    /// **Note:** this clones the receiver out of its `Value` wrapper. For
576    /// builtin types backed by `Arc<Mutex<..>>` (bytes, list), prefer
577    /// [`method`](Self::method) which borrows in place.
578    pub fn function<Marker>(&mut self, name: &str, f: impl IntoNativeFn<Marker>) -> &mut Self {
579        let (signature, call) = f.into_native();
580        self.add(name, Some(signature), Vec::new(), call, None)
581    }
582
583    /// Registers a method that borrows the receiver without cloning:
584    /// `|bytes: &[u8], i: i64| -> Option<i64>`.
585    ///
586    /// `Recv` is `[u8]` for bytes or `str` for strings — any type that
587    /// implements [`BuiltinRecv`].
588    pub fn method<Recv: ?Sized + 'static, Marker>(
589        &mut self,
590        name: &str,
591        f: impl IntoBuiltinMethod<Recv, Marker>,
592    ) -> &mut Self {
593        let (signature, call) = f.into_native();
594        self.add(name, Some(signature), Vec::new(), call, None)
595    }
596
597    /// Like [`method`](Self::method) but borrows mutably:
598    /// `|bytes: &mut Vec<u8>, val: i64| { bytes.push(val as u8); }`.
599    pub fn method_mut<Recv: 'static, Marker>(
600        &mut self,
601        name: &str,
602        f: impl IntoBuiltinMethodMut<Recv, Marker>,
603    ) -> &mut Self {
604        let (signature, call) = f.into_native();
605        self.add(name, Some(signature), Vec::new(), call, None)
606    }
607
608    /// Registers a method working on Xur values directly, with the receiver
609    /// first; needed to change a list in place.
610    pub fn raw_function(
611        &mut self,
612        name: &str,
613        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
614    ) -> &mut Self {
615        self.add(name, None, Vec::new(), Box::new(f), None)
616    }
617
618    /// Like [`raw_function`](Self::raw_function), declaring the return type
619    /// for LSP inlay hints.
620    pub fn raw_function_returns<R: Returns>(
621        &mut self,
622        name: &str,
623        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
624    ) -> &mut Self {
625        self.add(
626            name,
627            None,
628            Vec::new(),
629            Box::new(f),
630            Some(ReturnHint::Shape(R::RET)),
631        )
632    }
633
634    /// Like [`raw_function_returns`](Self::raw_function_returns) for
635    /// xur-internal types that have no Facet equivalent.
636    pub fn raw_function_returns_xur(
637        &mut self,
638        name: &str,
639        ret: XurType,
640        f: impl Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync + 'static,
641    ) -> &mut Self {
642        self.add(
643            name,
644            None,
645            Vec::new(),
646            Box::new(f),
647            Some(ReturnHint::Xur(ret)),
648        )
649    }
650
651    /// Like [`function`](Self::function), naming the parameters (the
652    /// receiver first) for hovers and docs.
653    pub fn named_function<Marker>(
654        &mut self,
655        name: &str,
656        params: &[&str],
657        f: impl IntoNativeFn<Marker>,
658    ) -> &mut Self {
659        let (signature, call) = f.into_native();
660        self.add(name, Some(signature), owned(params), call, None)
661    }
662
663    /// Like [`method`](Self::method), naming the parameters after the
664    /// receiver for hovers and docs.
665    pub fn named_method<Recv: ?Sized + 'static, Marker>(
666        &mut self,
667        name: &str,
668        params: &[&str],
669        f: impl IntoBuiltinMethod<Recv, Marker>,
670    ) -> &mut Self {
671        let (signature, call) = f.into_native();
672        self.add(name, Some(signature), owned(params), call, None)
673    }
674
675    /// Like [`method_mut`](Self::method_mut), naming the parameters after
676    /// the receiver for hovers and docs.
677    pub fn named_method_mut<Recv: 'static, Marker>(
678        &mut self,
679        name: &str,
680        params: &[&str],
681        f: impl IntoBuiltinMethodMut<Recv, Marker>,
682    ) -> &mut Self {
683        let (signature, call) = f.into_native();
684        self.add(name, Some(signature), owned(params), call, None)
685    }
686
687    /// The registry being filled in.
688    pub fn registry(&self) -> &'r Registry {
689        self.registry
690    }
691
692    pub(super) fn add_raw(
693        &mut self,
694        name: &str,
695        names: Vec<String>,
696        call: Box<CallFn>,
697    ) -> NativeFnId {
698        let decl = self.registry.add_fn(name, None, names, call);
699        let key = (self.ty, name.to_owned());
700        self.registry
701            .with_inner(|inner| inner.builtin_methods.insert(key, decl.id));
702        decl.id
703    }
704
705    fn add(
706        &mut self,
707        name: &str,
708        signature: Option<Signature>,
709        param_names: Vec<String>,
710        call: Box<CallFn>,
711        return_hint: Option<ReturnHint>,
712    ) -> &mut Self {
713        let decl = self.registry.add_fn(name, signature, param_names, call);
714        if let Some(hint) = return_hint {
715            self.registry.set_return_hint(decl.id, hint);
716        }
717        let key = (self.ty, name.to_owned());
718        self.registry
719            .with_inner(|inner| inner.builtin_methods.insert(key, decl.id));
720        self
721    }
722}
723
724fn owned(names: &[&str]) -> Vec<String> {
725    names.iter().map(|s| s.to_string()).collect()
726}
727
728/// Parameter names for a native type's method, whose signature includes the
729/// receiver: `self` and then `params`.
730fn with_self(params: &[&str]) -> Vec<String> {
731    std::iter::once("self")
732        .chain(params.iter().copied())
733        .map(String::from)
734        .collect()
735}