Skip to main content

xur_runtime/registry/
mod.rs

1//! Registering Rust functions and types as Xur modules.
2//!
3//! ```ignore
4//! let mut registry = Registry::new();
5//! registry
6//!     .module("std::math")
7//!     .function("sqrt", |x: f64| x.sqrt())
8//!     .function("max", |a: i64, b: i64| a.max(b));
9//! registry
10//!     .module("geo")
11//!     .ty::<Point>("Point")
12//!     .function("new", |x: f64, y: f64| Point { x, y }) // `Point::new(1.0, 2.0)`
13//!     .method("norm", |p: &Point| p.x.hypot(p.y)) //     `p.norm()`
14//!     .method_mut("scale", |p: &mut Point, k: f64| { p.x *= k; p.y *= k });
15//! ```
16//!
17//! Any `Fn(A, B, ...) -> R` whose argument and return types implement
18//! [`Facet`] can be registered: arguments are converted from Xur values and
19//! the result back with [`convert`](crate::convert). Functions that need the
20//! running program itself, such as `std::import`, are registered with
21//! [`ModuleBuilder::raw_function`] and receive a [`Context`].
22//!
23//! Values of a registered type live in Xur as [`Value::Native`]: the Rust
24//! value itself, shared, so methods taking `&mut self` change it in place.
25//! Its fields can be read (`p.x`) and it is displayed with its `Display` or
26//! `Debug` implementation.
27
28mod builder;
29mod hooks;
30mod into_native;
31#[cfg(test)]
32mod tests;
33
34use std::collections::HashMap;
35use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
36use std::thread::JoinHandle;
37
38use facet::{Facet, Peek, Shape, StructKind, StructType, Type, UserType};
39use xur_resolve::{
40    DefId, NativeFnDecl, NativeFnId, NativeModule, NativeProvider, NativeTypeDecl, NativeTypeId,
41    NativeVariantDecl, NativeVariantKind,
42};
43
44use xur_span::Symbol;
45
46use crate::convert::{Builder, ConvertCx};
47use crate::value::NativeObject;
48use crate::{AdtInfo, BuiltinType, RunResult, RuntimeError, TypeRef, Value};
49
50pub use builder::{BuiltinBuilder, ModuleBuilder, TypeBuilder};
51pub use into_native::{IntoNativeFn, IntoNativeMethod, IntoNativeMethodMut};
52
53use hooks::TypeHooks;
54
55/// What a native function can ask of the running program.
56pub trait Context: ConvertCx {
57    /// Loads the module at `path`, relative to the file of the module
58    /// making the call, and returns it as a value.
59    fn import(&mut self, path: &str) -> RunResult<Value>;
60    /// Formats `value` as `{}` does in format strings.
61    fn display(&self, value: &Value) -> String;
62    /// The generic arguments the native function was called with, as in
63    /// `type_name::<T>()`.
64    fn type_args(&self) -> &[TypeRef];
65    /// Writes `text` to the program's standard output.
66    fn print(&mut self, text: &str) -> RunResult<()>;
67    /// Calls a function, closure or constructor value.
68    fn call(&mut self, callee: &Value, args: &[Value]) -> RunResult<Value>;
69    /// Calls `f`, a function or closure taking no arguments, on a new
70    /// thread; joining the thread gives its result.
71    fn spawn(&mut self, f: Value) -> RunResult<JoinHandle<RunResult<Value>>>;
72
73    // Reflection, for `std::reflect`.
74
75    /// How the type of `value` is named in messages, e.g. `` `Point` ``.
76    fn describe_type(&self, value: &Value) -> String;
77    /// The struct or enum variant `def`, or `None` if it is neither.
78    fn adt_info(&self, def: DefId) -> Option<AdtInfo>;
79    /// The names of the methods `value.name()` can call.
80    fn methods(&self, value: &Value) -> Vec<String>;
81    /// `value.name`.
82    fn field(&mut self, value: &Value, name: &str) -> RunResult<Value>;
83    /// A copy of the struct `value` with the field `name` set to `new`.
84    fn set_field(&mut self, value: &Value, name: &str, new: Value) -> RunResult<Value>;
85    /// `receiver.name(args)`.
86    fn call_method(&mut self, receiver: Value, name: &str, args: &[Value]) -> RunResult<Value>;
87
88    /// Attempts to coerce `value` into the struct or enum `target`, as
89    /// `value as Type` does. Returns the coerced value, or an error if the
90    /// coercion fails.
91    fn try_cast(&self, value: &Value, target: DefId) -> RunResult<Value>;
92
93    /// Reflection data for a function, closure, or constructor value.
94    fn fn_info(&self, value: &Value) -> Option<crate::FnInfo>;
95}
96
97pub(crate) type CallFn = dyn Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync;
98
99/// The Rust types of a typed native function, for checking calls.
100#[derive(Debug, Clone)]
101pub struct Signature {
102    pub params: Vec<&'static Shape>,
103    pub ret: &'static Shape,
104    pub param_names: Vec<String>,
105}
106
107pub struct NativeFn {
108    pub name: String,
109    /// `None` for raw functions, which take any arguments.
110    pub signature: Option<Signature>,
111    pub param_names: Vec<String>,
112    call: Box<CallFn>,
113}
114
115impl NativeFn {
116    pub fn call(&self, cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
117        (self.call)(cx, args)
118    }
119}
120
121pub(super) struct NativeType {
122    name: String,
123    shape: &'static Shape,
124    functions: Vec<NativeFnDecl>,
125    /// `None` for types registered by shape only, whose values are
126    /// records rather than native objects.
127    hooks: Option<TypeHooks>,
128    /// Explicit variant declarations for repr enums registered from Rust.
129    /// When set, these are used instead of deriving variants from the shape.
130    explicit_variants: Option<Vec<NativeVariantDecl>>,
131}
132
133/// Fills in a lazy module, the first time a program uses it.
134type ModuleInit = Box<dyn FnOnce(&mut ModuleBuilder<'_>) + Send + Sync>;
135
136struct ModuleData {
137    name: String,
138    /// For a lazy module not yet needed, what registers its contents.
139    init: Option<ModuleInit>,
140    children: Vec<usize>,
141    functions: Vec<NativeFnDecl>,
142    types: Vec<NativeTypeId>,
143}
144
145/// Every native function and type, organised into modules.
146///
147/// A registry is shared by every thread of a running program and by name
148/// resolution, which may expand lazy modules while a native function runs,
149/// so it is internally locked: each operation holds the lock only briefly,
150/// and functions are handed out as `Arc`s to call without it.
151#[derive(Default)]
152pub struct Registry {
153    inner: RwLock<Inner>,
154}
155
156#[derive(Default)]
157struct Inner {
158    fns: Vec<Arc<NativeFn>>,
159    /// Methods of built-in values, such as `list.push`.
160    builtin_methods: HashMap<(BuiltinType, String), NativeFnId>,
161    types: Vec<NativeType>,
162    modules: Vec<ModuleData>,
163    /// Modules that are not submodules of another, like `std`.
164    roots: Vec<usize>,
165    /// Conversions to Xur for shapes facet cannot see inside.
166    converters: Vec<(&'static Shape, Converter)>,
167}
168
169/// The fields a record of a type registered by shape is built with.
170#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct RecordCtor {
172    pub kind: NativeVariantKind,
173    /// In declaration order; `0`, `1`, ... for tuple fields.
174    pub fields: Vec<Symbol>,
175}
176
177/// The variants of an enum's shape, as resolution declares them.
178fn variant_decls(shape: &'static Shape) -> Vec<NativeVariantDecl> {
179    let Type::User(UserType::Enum(en)) = shape.ty else {
180        return Vec::new();
181    };
182    en.variants
183        .iter()
184        .map(|variant| NativeVariantDecl {
185            name: variant.name.to_owned(),
186            kind: variant_kind(variant.data.kind),
187            repr_value: None,
188        })
189        .collect()
190}
191
192fn variant_kind(kind: StructKind) -> NativeVariantKind {
193    match kind {
194        StructKind::Unit => NativeVariantKind::Unit,
195        StructKind::Tuple | StructKind::TupleStruct => NativeVariantKind::Tuple,
196        StructKind::Struct => NativeVariantKind::Named,
197    }
198}
199
200/// Converts a value of some shape to Xur, given a peek at it.
201pub type Converter = fn(&dyn ConvertCx, Peek<'_, 'static>) -> RunResult<Value>;
202
203impl Registry {
204    pub fn new() -> Self {
205        Self::default()
206    }
207
208    fn read(&self) -> RwLockReadGuard<'_, Inner> {
209        self.inner.read().unwrap_or_else(PoisonError::into_inner)
210    }
211
212    fn write(&self) -> RwLockWriteGuard<'_, Inner> {
213        self.inner.write().unwrap_or_else(PoisonError::into_inner)
214    }
215
216    /// The module at `path`, such as `std::io`, created if needed.
217    pub fn module(&self, path: &str) -> ModuleBuilder<'_> {
218        let module = self.write().module_at(path);
219        ModuleBuilder::new(self, module)
220    }
221
222    /// Registers the module at `path` lazily: `init` registers its contents
223    /// the first time a program looks inside it, so large modules that a
224    /// program doesn't use cost nothing.
225    pub fn lazy_module(
226        &self,
227        path: &str,
228        init: impl FnOnce(&mut ModuleBuilder<'_>) + Send + Sync + 'static,
229    ) {
230        let mut inner = self.write();
231        let module = inner.module_at(path);
232        inner.modules[module].init = Some(Box::new(init));
233    }
234
235    /// Methods of the built-in type `ty`, such as `list.push(x)`.
236    pub fn builtin(&self, ty: BuiltinType) -> BuiltinBuilder<'_> {
237        BuiltinBuilder::new(self, ty)
238    }
239
240    /// The method `name` of the built-in type `ty`.
241    pub fn builtin_method(&self, ty: BuiltinType, name: &str) -> Option<NativeFnId> {
242        self.read()
243            .builtin_methods
244            .get(&(ty, name.to_owned()))
245            .copied()
246    }
247
248    /// The function `name` registered for the native type `ty`.
249    pub fn type_function(&self, ty: NativeTypeId, name: &str) -> Option<NativeFnId> {
250        let inner = self.read();
251        let functions = &inner.types[ty.0 as usize].functions;
252        functions.iter().find(|f| f.name == name).map(|f| f.id)
253    }
254
255    /// The functions of the native type `ty` that can be called as methods:
256    /// those whose first parameter is the type itself, and raw functions.
257    pub fn type_methods(&self, ty: NativeTypeId) -> Vec<String> {
258        let inner = self.read();
259        let native = &inner.types[ty.0 as usize];
260        native
261            .functions
262            .iter()
263            .filter(|decl| match &inner.fns[decl.id.0 as usize].signature {
264                Some(signature) => signature.params.first() == Some(&native.shape),
265                None => true,
266            })
267            .map(|decl| decl.name.clone())
268            .collect()
269    }
270
271    /// The names of the methods of the built-in type `ty`, sorted.
272    pub fn builtin_methods(&self, ty: BuiltinType) -> Vec<String> {
273        let mut names: Vec<_> = self
274            .read()
275            .builtin_methods
276            .keys()
277            .filter(|(builtin, _)| *builtin == ty)
278            .map(|(_, name)| name.clone())
279            .collect();
280        names.sort();
281        names
282    }
283
284    /// The names of the fields of the native type `ty`, if it is a struct.
285    pub fn type_fields(&self, ty: NativeTypeId) -> Vec<String> {
286        let shape = self.read().types[ty.0 as usize].shape;
287        match shape.ty {
288            Type::User(UserType::Struct(StructType { fields, .. })) => {
289                fields.iter().map(|field| field.name.to_owned()).collect()
290            }
291            _ => Vec::new(),
292        }
293    }
294
295    pub fn function(&self, id: NativeFnId) -> Arc<NativeFn> {
296        Arc::clone(&self.read().fns[id.0 as usize])
297    }
298
299    pub fn type_name(&self, id: NativeTypeId) -> String {
300        self.read().types[id.0 as usize].name.clone()
301    }
302
303    /// The native type registered under `name`, if any.
304    pub fn type_id_by_name(&self, name: &str) -> Option<NativeTypeId> {
305        let inner = self.read();
306        inner.types.iter().enumerate().find_map(|(i, ty)| {
307            (ty.name == name).then_some(NativeTypeId(i as u32))
308        })
309    }
310
311    /// The xur display name for `shape`, mapping Rust types to their xur
312    /// equivalents: `String` → `str`, `Vec<u8>` → `bytes`, registered types
313    /// by their xur name, and falling back to the Rust name.
314    pub fn shape_xur_name(&self, shape: &'static Shape) -> String {
315        if let Some(id) = self.type_of_shape(shape) {
316            return self.type_name(id);
317        }
318        let name = shape.type_name().to_string();
319        match name.as_str() {
320            "String" | "&str" | "alloc::string::String" => "str".into(),
321            "bool" => "bool".into(),
322            "i64" => "i64".into(),
323            "f64" => "f64".into(),
324            "i32" => "i32".into(),
325            "u32" => "u32".into(),
326            "u64" => "u64".into(),
327            "usize" => "usize".into(),
328            "()" => "()".into(),
329            "Vec<u8>" | "alloc::vec::Vec<u8>" => "bytes".into(),
330            _ if name.starts_with("Vec<") || name == "Vec" => "list".into(),
331            _ => {
332                name.split('<').next().unwrap_or(&name).into()
333            }
334        }
335    }
336
337    /// The return-type Shape of a native function, if it has a signature.
338    pub fn native_return_shape(&self, id: NativeFnId) -> Option<&'static Shape> {
339        self.function(id).signature.as_ref().map(|s| s.ret)
340    }
341
342    /// Extract the xur name of the `index`th type parameter from a generic
343    /// Shape: for `Result<T, E>`, index 0 → T, index 1 → E; for `Option<T>`,
344    /// index 0 → T.
345    pub fn shape_type_param(&self, shape: &'static Shape, index: usize) -> Option<String> {
346        if let Ok(r) = shape.def.into_result() {
347            return match index {
348                0 => Some(self.shape_xur_name(r.t())),
349                1 => Some(self.shape_xur_name(r.e())),
350                _ => None,
351            };
352        }
353        if let Ok(o) = shape.def.into_option() {
354            return (index == 0).then(|| self.shape_xur_name(o.t()));
355        }
356        None
357    }
358
359    /// The native type registered for `shape`, if any.
360    pub fn type_of_shape(&self, shape: &'static Shape) -> Option<NativeTypeId> {
361        let index = self
362            .read()
363            .types
364            .iter()
365            .position(|ty| ty.shape == shape && ty.hooks.is_some())?;
366        Some(NativeTypeId(index as u32))
367    }
368
369    /// The type registered by shape only for `shape`, whose values are
370    /// typed records.
371    pub fn record_type_of_shape(&self, shape: &'static Shape) -> Option<NativeTypeId> {
372        let index = self
373            .read()
374            .types
375            .iter()
376            .position(|ty| ty.shape == shape && ty.hooks.is_none())?;
377        Some(NativeTypeId(index as u32))
378    }
379
380    /// Converts values of `shape` to Xur with `convert`, for types facet
381    /// cannot see inside, such as opaque ones. Such values cannot be
382    /// converted back.
383    pub fn converter(&self, shape: &'static Shape, convert: Converter) {
384        self.write().converters.push((shape, convert));
385    }
386
387    /// Whether a conversion is registered for `shape`.
388    pub fn has_converter(&self, shape: &'static Shape) -> bool {
389        self.converter_of(shape).is_some()
390    }
391
392    /// The conversion registered for `shape`, if any.
393    pub(crate) fn converter_of(&self, shape: &'static Shape) -> Option<Converter> {
394        let inner = self.read();
395        let (_, convert) = inner.converters.iter().find(|(s, _)| *s == shape)?;
396        Some(*convert)
397    }
398
399    /// How a value of the type `ty`, registered by shape, is built: the
400    /// fields of the struct itself, or of its enum variant `variant`.
401    /// `None` if there is no such struct or variant.
402    pub fn record_ctor(&self, ty: NativeTypeId, variant: Option<Symbol>) -> Option<RecordCtor> {
403        let shape = self.read().types[ty.0 as usize].shape;
404        let data = match (shape.ty, variant) {
405            (Type::User(UserType::Struct(st)), None) => st,
406            (Type::User(UserType::Enum(en)), Some(variant)) => {
407                en.variants
408                    .iter()
409                    .find(|v| v.name == variant.as_str())?
410                    .data
411            }
412            _ => return None,
413        };
414        Some(RecordCtor {
415            kind: variant_kind(data.kind),
416            fields: data
417                .fields
418                .iter()
419                .map(|field| Symbol::intern(field.name))
420                .collect(),
421        })
422    }
423
424    /// Whether any type, of either kind, is registered for `shape`.
425    pub fn has_shape(&self, shape: &'static Shape) -> bool {
426        self.read().types.iter().any(|ty| ty.shape == shape)
427    }
428
429    /// Reads field `name` of a native object.
430    pub fn field(
431        &self,
432        cx: &dyn ConvertCx,
433        object: &NativeObject,
434        name: &str,
435    ) -> Option<RunResult<Value>> {
436        let field = self.hooks(object.ty).field;
437        object.with_any(|value| field(cx, value, name))
438    }
439
440    /// Formats a native object with its `Display`, or else `Debug`.
441    /// A native object's `Display`, or its Xur type name in angle brackets
442    /// when the Rust type has no `Display` (`<AnyImage>`), rather than a
443    /// debug dump.
444    pub fn display(&self, object: &NativeObject) -> String {
445        object
446            .with_any(self.hooks(object.ty).display)
447            .unwrap_or_else(|| format!("<{}>", self.type_name(object.ty)))
448    }
449
450    /// Whether two native objects are equal by their Rust `PartialEq`.
451    pub fn native_eq(&self, a: &NativeObject, b: &NativeObject) -> bool {
452        if a.ty != b.ty {
453            return false;
454        }
455        if std::ptr::eq(a, b) {
456            return true;
457        }
458        let eq = self.hooks(a.ty).eq;
459        a.with_any(|a| b.with_any(|b| eq(a, b)))
460    }
461
462    /// A native object of the type registered for `T`, holding `value` and
463    /// keeping `keep_alive` alive with it so any memory `value` borrows
464    /// stays valid. For types like `PEFile<'static>` that borrow a file's
465    /// bytes: the bytes go in `keep_alive`.
466    pub fn borrowing_object<T: Facet<'static> + Send + 'static>(
467        &self,
468        value: T,
469        keep_alive: Arc<dyn std::any::Any + Send + Sync>,
470    ) -> RunResult<Value> {
471        let ty = self
472            .type_of_shape(T::SHAPE)
473            .ok_or_else(|| RuntimeError::new(format!("`{}` is not a registered type", T::SHAPE)))?;
474        let object = NativeObject::borrowing(ty, Box::new(value), keep_alive);
475        Ok(Value::Native(object.into()))
476    }
477
478    /// A native object holding a clone of the registered value behind `peek`.
479    pub(crate) fn object_from_peek(
480        &self,
481        ty: NativeTypeId,
482        peek: Peek<'_, 'static>,
483    ) -> Option<NativeObject> {
484        let value = (self.hooks(ty).clone_peek)(peek)?;
485        Some(NativeObject::new(ty, value))
486    }
487
488    /// Writes a clone of `object` into a builder for its type.
489    pub(crate) fn set_object(&self, partial: Builder, object: &NativeObject) -> RunResult<Builder> {
490        let set = self.hooks(object.ty).set;
491        object.with_any(|value| set(partial, value))
492    }
493
494    /// The hooks of a type registered with its Rust type, which every type
495    /// with native objects is.
496    fn hooks(&self, ty: NativeTypeId) -> TypeHooks {
497        self.read().types[ty.0 as usize]
498            .hooks
499            .expect("native objects only exist for types registered with their Rust type")
500    }
501
502    /// The registered modules as name resolution sees them.
503    pub fn decls(&self) -> Vec<NativeModule> {
504        let inner = self.read();
505        inner
506            .roots
507            .iter()
508            .map(|&module| inner.decl(module))
509            .collect()
510    }
511
512    /// Registers the contents of the lazy module at `path`, if not yet
513    /// registered, and describes it.
514    pub fn expand(&self, path: &[String]) -> NativeModule {
515        let (module, init) = {
516            let mut inner = self.write();
517            let module = inner
518                .find(path)
519                .unwrap_or_else(|| panic!("no native module `{}`", path.join("::")));
520            (module, inner.modules[module].init.take())
521        };
522        // The initializer registers through the builder, which locks.
523        if let Some(init) = init {
524            init(&mut ModuleBuilder::new(self, module));
525        }
526        self.read().decl(module)
527    }
528
529    pub(super) fn add_fn(
530        &self,
531        name: &str,
532        signature: Option<Signature>,
533        param_names: Vec<String>,
534        call: Box<CallFn>,
535    ) -> NativeFnDecl {
536        self.write().add_fn(name, signature, param_names, call)
537    }
538
539    fn with_inner<R>(&self, f: impl FnOnce(&mut Inner) -> R) -> R {
540        f(&mut self.write())
541    }
542}
543
544impl Inner {
545    fn module_at(&mut self, path: &str) -> usize {
546        let mut names = path.split("::");
547        let root = names.next().expect("split yields at least one item");
548        let mut module = self.child(None, root);
549        for name in names {
550            module = self.child(Some(module), name);
551        }
552        module
553    }
554
555    fn find(&self, path: &[String]) -> Option<usize> {
556        let mut module: Option<usize> = None;
557        for name in path {
558            let siblings = match module {
559                Some(parent) => &self.modules[parent].children,
560                None => &self.roots,
561            };
562            module = Some(*siblings.iter().find(|&&m| self.modules[m].name == *name)?);
563        }
564        module
565    }
566
567    fn decl(&self, module: usize) -> NativeModule {
568        let data = &self.modules[module];
569        if data.init.is_some() {
570            return NativeModule {
571                name: data.name.clone(),
572                lazy: true,
573                ..NativeModule::default()
574            };
575        }
576        NativeModule {
577            name: data.name.clone(),
578            lazy: false,
579            functions: data.functions.clone(),
580            types: data
581                .types
582                .iter()
583                .map(|&id| {
584                    let ty = &self.types[id.0 as usize];
585                    NativeTypeDecl {
586                        name: ty.name.clone(),
587                        id,
588                        functions: ty.functions.clone(),
589                        variants: if let Some(ref v) = ty.explicit_variants {
590                            v.clone()
591                        } else if ty.hooks.is_none() {
592                            variant_decls(ty.shape)
593                        } else {
594                            Vec::new()
595                        },
596                    }
597                })
598                .collect(),
599            modules: data
600                .children
601                .iter()
602                .map(|&child| self.decl(child))
603                .collect(),
604        }
605    }
606
607    /// The submodule `name` of `parent` (or the root module `name`).
608    fn child(&mut self, parent: Option<usize>, name: &str) -> usize {
609        let siblings = match parent {
610            Some(parent) => &self.modules[parent].children,
611            None => &self.roots,
612        };
613        if let Some(&existing) = siblings.iter().find(|&&m| self.modules[m].name == name) {
614            return existing;
615        }
616        let module = self.modules.len();
617        self.modules.push(ModuleData {
618            name: name.to_owned(),
619            init: None,
620            children: Vec::new(),
621            functions: Vec::new(),
622            types: Vec::new(),
623        });
624        match parent {
625            Some(parent) => self.modules[parent].children.push(module),
626            None => self.roots.push(module),
627        }
628        module
629    }
630
631    fn add_fn(
632        &mut self,
633        name: &str,
634        signature: Option<Signature>,
635        param_names: Vec<String>,
636        call: Box<CallFn>,
637    ) -> NativeFnDecl {
638        let id = NativeFnId(self.fns.len() as u32);
639        self.fns.push(Arc::new(NativeFn {
640            name: name.to_owned(),
641            signature,
642            param_names: param_names.clone(),
643            call,
644        }));
645        NativeFnDecl {
646            name: name.to_owned(),
647            id,
648            param_names,
649        }
650    }
651}
652
653impl NativeProvider for Registry {
654    fn modules(&self) -> Vec<NativeModule> {
655        self.decls()
656    }
657
658    fn expand(&self, path: &[String]) -> NativeModule {
659        Registry::expand(self, path)
660    }
661}