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;
31mod raw_sig;
32#[cfg(test)]
33mod tests;
34
35use std::collections::HashMap;
36use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
37use std::thread::JoinHandle;
38
39use facet::{Def, Facet, Peek, PointerType, Shape, StructKind, StructType, Type, UserType};
40use xur_resolve::{
41    DefId, NativeFnDecl, NativeFnId, NativeModule, NativeProvider, NativeTypeDecl, NativeTypeId,
42    NativeVariantDecl, NativeVariantKind, RtType, macros::MacroExpander,
43};
44
45use xur_span::{Span, Symbol};
46
47use crate::convert::{Builder, ConvertCx};
48use crate::value::NativeObject;
49use crate::{AdtInfo, BuiltinType, RunResult, RuntimeError, TypeDesc, TypeRef, Value};
50
51pub use builder::{
52    BuiltinBuilder, ElemHint, ModuleBuilder, ReturnHint, Returns, TypeBuilder, XurType,
53};
54pub use into_native::{
55    BuiltinRecv, BuiltinRecvMut, IntoBuiltinMethod, IntoBuiltinMethodMut, IntoNativeFn,
56    IntoNativeMethod, IntoNativeMethodMut,
57};
58pub use raw_sig::{RawParam, RawSig};
59
60use hooks::TypeHooks;
61
62/// What a native function can ask of the running program.
63pub trait Context: ConvertCx {
64    /// Loads the module at `path`, relative to the file of the module
65    /// making the call, and returns it as a value.
66    fn import(&mut self, path: &str) -> RunResult<Value>;
67    /// Formats `value` as `{}` does in format strings.
68    fn display(&self, value: &Value) -> String;
69    /// The generic arguments the native function was called with, as in
70    /// `type_name::<T>()`.
71    fn type_args(&self) -> &[TypeRef];
72    /// Writes `text` to the program's standard output.
73    fn print(&mut self, text: &str) -> RunResult<()>;
74    /// Writes `text` to the program's standard error. By default this is the
75    /// process's stderr; embedders can redirect it.
76    fn eprint(&mut self, text: &str) -> RunResult<()> {
77        use std::io::Write;
78        std::io::stderr()
79            .write_all(text.as_bytes())
80            .map_err(|error| RuntimeError::new(format!("couldn't write to stderr: {error}")))
81    }
82    /// Calls a function, closure or constructor value.
83    fn call(&mut self, callee: &Value, args: &[Value]) -> RunResult<Value>;
84    /// Calls `f`, a function or closure taking no arguments, on a new
85    /// thread; joining the thread gives its result.
86    fn spawn(&mut self, f: Value) -> RunResult<JoinHandle<RunResult<Value>>>;
87
88    // Reflection, for `std::reflect`.
89
90    /// How the type of `value` is named in messages, e.g. `` `Point` ``.
91    fn describe_type(&self, value: &Value) -> String;
92    /// A `file:line:col` location for `span`, for reporting errors raised inside
93    /// a native callback (e.g. an egui draw function) where the span would
94    /// otherwise be lost. Returns an empty string if it can't be resolved.
95    fn describe_span(&self, span: Span) -> String;
96    /// The runtime type of `value` as a type value, preserving int/float width
97    /// (`reflect::type_of`).
98    fn type_of(&self, value: &Value) -> RtType;
99    /// The struct or enum variant `def`, or `None` if it is neither.
100    fn adt_info(&self, def: DefId) -> Option<AdtInfo>;
101    /// The names of the methods `value.name()` can call.
102    fn methods(&self, value: &Value) -> Vec<String>;
103    /// `value.name`.
104    fn field(&mut self, value: &Value, name: &str) -> RunResult<Value>;
105    /// A copy of the struct `value` with the field `name` set to `new`.
106    fn set_field(&mut self, value: &Value, name: &str, new: Value) -> RunResult<Value>;
107    /// `receiver.name(args)`.
108    fn call_method(&mut self, receiver: Value, name: &str, args: &[Value]) -> RunResult<Value>;
109
110    /// Attempts to coerce `value` into the struct or enum `target`, as
111    /// `value as Type` does. Returns the coerced value, or an error if the
112    /// coercion fails.
113    fn try_cast(&self, value: &Value, target: DefId) -> RunResult<Value>;
114
115    /// The integer repr value of a repr enum variant, if `def` is one.
116    fn repr_value(&self, def: DefId) -> Option<i64>;
117
118    /// Reflection data for a function, closure, or constructor value.
119    fn fn_info(&self, value: &Value) -> Option<crate::FnInfo>;
120
121    /// An opaque handle for calling xur closures from outside the normal
122    /// execution path, such as from native hook callbacks. Returns `None`
123    /// if the engine doesn't support it.
124    fn shared_handle(&self) -> Option<Box<dyn std::any::Any + Send + Sync>> {
125        None
126    }
127
128    /// The name of a definition: the variant name for an enum variant,
129    /// the type name for a struct or enum.
130    fn def_name(&self, _def: DefId) -> Option<String> {
131        None
132    }
133
134    /// The variants of the enum `def`: `(name, variant_def, has_fields)`.
135    fn enum_variants(&self, _def: DefId) -> Vec<(String, DefId, bool)> {
136        Vec::new()
137    }
138}
139
140/// Named unions with up to this many options print inline (`str | bytes`).
141pub const ALIAS_INLINE_MAX: usize = 3;
142
143pub(crate) type CallFn = dyn Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync;
144
145/// The Rust types of a typed native function, for checking calls.
146#[derive(Debug, Clone)]
147pub struct Signature {
148    pub params: Vec<&'static Shape>,
149    pub ret: &'static Shape,
150    pub param_names: Vec<String>,
151    /// The parameters' types for display, one per entry in `params`.
152    pub param_types: Vec<TypeDesc>,
153    /// The return type for display.
154    pub ret_type: TypeDesc,
155    /// How many leading parameters are required; the rest are optional.
156    pub required: usize,
157}
158
159pub struct NativeFn {
160    pub name: String,
161    /// `None` for raw functions, which take any arguments.
162    pub signature: Option<Signature>,
163    /// Return type for raw functions that lack a full signature.
164    pub return_hint: Option<ReturnHint>,
165    /// What a raw function takes and returns, when it says.
166    pub raw_sig: Option<RawSig>,
167    pub param_names: Vec<String>,
168    call: Box<CallFn>,
169}
170
171impl NativeFn {
172    pub fn call(&self, cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
173        (self.call)(cx, args)
174    }
175}
176
177pub(super) struct NativeType {
178    name: String,
179    shape: &'static Shape,
180    functions: Vec<NativeFnDecl>,
181    /// `None` for types registered by shape only, whose values are
182    /// records rather than native objects.
183    hooks: Option<TypeHooks>,
184    /// Explicit variant declarations for repr enums registered from Rust.
185    /// When set, these are used instead of deriving variants from the shape.
186    explicit_variants: Option<Vec<NativeVariantDecl>>,
187}
188
189/// Fills in a lazy module, the first time a program uses it.
190type ModuleInit = Box<dyn FnOnce(&mut ModuleBuilder<'_>) + Send + Sync>;
191
192struct ModuleData {
193    name: String,
194    /// For a lazy module not yet needed, what registers its contents.
195    init: Option<ModuleInit>,
196    children: Vec<usize>,
197    functions: Vec<NativeFnDecl>,
198    types: Vec<NativeTypeId>,
199    macros: HashMap<String, Arc<dyn MacroExpander>>,
200}
201
202/// Every native function and type, organised into modules.
203///
204/// A registry is shared by every thread of a running program and by name
205/// resolution, which may expand lazy modules while a native function runs,
206/// so it is internally locked: each operation holds the lock only briefly,
207/// and functions are handed out as `Arc`s to call without it.
208#[derive(Default)]
209pub struct Registry {
210    inner: RwLock<Inner>,
211}
212
213#[derive(Default)]
214struct Inner {
215    fns: Vec<Arc<NativeFn>>,
216    /// Methods of built-in values, such as `list.push`.
217    builtin_methods: HashMap<(BuiltinType, String), NativeFnId>,
218    types: Vec<NativeType>,
219    modules: Vec<ModuleData>,
220    /// Modules that are not submodules of another, like `std`.
221    roots: Vec<usize>,
222    /// Conversions to Xur for shapes facet cannot see inside.
223    converters: Vec<(&'static Shape, Converter)>,
224}
225
226/// The fields a record of a type registered by shape is built with.
227#[derive(Debug, Clone, PartialEq, Eq)]
228pub struct RecordCtor {
229    pub kind: NativeVariantKind,
230    /// In declaration order; `0`, `1`, ... for tuple fields.
231    pub fields: Vec<Symbol>,
232}
233
234/// The variants of an enum's shape, as resolution declares them.
235fn variant_decls(shape: &'static Shape) -> Vec<NativeVariantDecl> {
236    let Type::User(UserType::Enum(en)) = shape.ty else {
237        return Vec::new();
238    };
239    en.variants
240        .iter()
241        .map(|variant| NativeVariantDecl {
242            name: variant.name.to_owned(),
243            kind: variant_kind(variant.data.kind),
244            repr_value: None,
245        })
246        .collect()
247}
248
249fn variant_kind(kind: StructKind) -> NativeVariantKind {
250    match kind {
251        StructKind::Unit => NativeVariantKind::Unit,
252        StructKind::Tuple | StructKind::TupleStruct => NativeVariantKind::Tuple,
253        StructKind::Struct => NativeVariantKind::Named,
254    }
255}
256
257/// Converts a value of some shape to Xur, given a peek at it.
258pub type Converter = fn(&dyn ConvertCx, Peek<'_, 'static>) -> RunResult<Value>;
259
260impl Registry {
261    pub fn new() -> Self {
262        Self::default()
263    }
264
265    fn read(&self) -> RwLockReadGuard<'_, Inner> {
266        self.inner.read().unwrap_or_else(PoisonError::into_inner)
267    }
268
269    fn write(&self) -> RwLockWriteGuard<'_, Inner> {
270        self.inner.write().unwrap_or_else(PoisonError::into_inner)
271    }
272
273    /// The module at `path`, such as `std::io`, created if needed.
274    pub fn module(&self, path: &str) -> ModuleBuilder<'_> {
275        let module = self.write().module_at(path);
276        ModuleBuilder::new(self, module)
277    }
278
279    /// Registers the module at `path` lazily: `init` registers its contents
280    /// the first time a program looks inside it, so large modules that a
281    /// program doesn't use cost nothing.
282    pub fn lazy_module(
283        &self,
284        path: &str,
285        init: impl FnOnce(&mut ModuleBuilder<'_>) + Send + Sync + 'static,
286    ) {
287        let mut inner = self.write();
288        let module = inner.module_at(path);
289        inner.modules[module].init = Some(Box::new(init));
290    }
291
292    /// Methods of the built-in type `ty`, such as `list.push(x)`.
293    pub fn builtin(&self, ty: BuiltinType) -> BuiltinBuilder<'_> {
294        BuiltinBuilder::new(self, ty)
295    }
296
297    /// The method `name` of the built-in type `ty`.
298    pub fn builtin_method(&self, ty: BuiltinType, name: &str) -> Option<NativeFnId> {
299        self.read()
300            .builtin_methods
301            .get(&(ty, name.to_owned()))
302            .copied()
303    }
304
305    /// The function `name` registered for the native type `ty`.
306    pub fn type_function(&self, ty: NativeTypeId, name: &str) -> Option<NativeFnId> {
307        let inner = self.read();
308        let functions = &inner.types[ty.0 as usize].functions;
309        functions.iter().find(|f| f.name == name).map(|f| f.id)
310    }
311
312    /// The functions of the native type `ty` that can be called as methods:
313    /// those whose first parameter is the type itself, and raw functions.
314    pub fn type_methods(&self, ty: NativeTypeId) -> Vec<String> {
315        let inner = self.read();
316        let native = &inner.types[ty.0 as usize];
317        native
318            .functions
319            .iter()
320            .filter(|decl| match &inner.fns[decl.id.0 as usize].signature {
321                Some(signature) => signature.params.first() == Some(&native.shape),
322                None => true,
323            })
324            .map(|decl| decl.name.clone())
325            .collect()
326    }
327
328    /// The names of the methods of the built-in type `ty`, sorted.
329    pub fn builtin_methods(&self, ty: BuiltinType) -> Vec<String> {
330        let mut names: Vec<_> = self
331            .read()
332            .builtin_methods
333            .keys()
334            .filter(|(builtin, _)| *builtin == ty)
335            .map(|(_, name)| name.clone())
336            .collect();
337        names.sort();
338        names
339    }
340
341    /// The names of the fields of the native type `ty`, if it is a struct.
342    pub fn type_fields(&self, ty: NativeTypeId) -> Vec<String> {
343        let shape = self.read().types[ty.0 as usize].shape;
344        match shape.ty {
345            Type::User(UserType::Struct(StructType { fields, .. })) => {
346                fields.iter().map(|field| field.name.to_owned()).collect()
347            }
348            _ => Vec::new(),
349        }
350    }
351
352    /// How many native functions are registered (ids are `0..count`).
353    pub fn function_count(&self) -> usize {
354        self.read().fns.len()
355    }
356
357    pub fn function(&self, id: NativeFnId) -> Arc<NativeFn> {
358        Arc::clone(&self.read().fns[id.0 as usize])
359    }
360
361    pub fn type_name(&self, id: NativeTypeId) -> String {
362        self.read().types[id.0 as usize].name.clone()
363    }
364
365    /// The Rust shape `id` was registered with: its fields, variants and
366    /// the doc comments on all of them (`shape.doc`, `field.doc`), for
367    /// generated docs.
368    pub fn type_shape(&self, id: NativeTypeId) -> &'static Shape {
369        self.read().types[id.0 as usize].shape
370    }
371
372    /// The native type registered under `name`, if any.
373    pub fn type_id_by_name(&self, name: &str) -> Option<NativeTypeId> {
374        let inner = self.read();
375        inner
376            .types
377            .iter()
378            .enumerate()
379            .find_map(|(i, ty)| (ty.name == name).then_some(NativeTypeId(i as u32)))
380    }
381
382    /// The xur display name for `shape`, mapping Rust types to their xur
383    /// equivalents: `String` → `str`, `Vec<u8>` → `bytes`, `Vec<T>` →
384    /// `list<T>`, `Option`/`Result` with their type arguments, registered
385    /// types by their xur name, and falling back to the Rust name.
386    pub fn shape_xur_name(&self, shape: &'static Shape) -> String {
387        if let Some(id) = self.type_of_shape(shape) {
388            return self.type_name(id);
389        }
390        let elem = |t: &'static Shape, wrap: &str| {
391            if t == u8::SHAPE {
392                "bytes".to_string()
393            } else {
394                format!("{wrap}<{}>", self.shape_xur_name(t))
395            }
396        };
397        // `&T`, `Box<T>`, `Arc<T>`: what they point to.
398        if let Type::Pointer(PointerType::Reference(p) | PointerType::Raw(p)) = shape.ty {
399            return self.shape_xur_name(p.target());
400        }
401        if let Def::Pointer(p) = shape.def
402            && let Some(pointee) = p.pointee()
403        {
404            return self.shape_xur_name(pointee);
405        }
406        // Tuples: `(str, i64)`.
407        if let Type::User(UserType::Struct(StructType {
408            kind: StructKind::Tuple,
409            fields,
410            ..
411        })) = shape.ty
412        {
413            let items: Vec<_> = fields
414                .iter()
415                .map(|f| self.shape_xur_name(f.shape()))
416                .collect();
417            return format!("({})", items.join(", "));
418        }
419        match shape.def {
420            Def::Option(o) => return format!("Option<{}>", self.shape_xur_name(o.t())),
421            Def::Result(r) => {
422                return format!(
423                    "Result<{}, {}>",
424                    self.shape_xur_name(r.t()),
425                    self.shape_xur_name(r.e())
426                );
427            }
428            Def::List(l) => return elem(l.t(), "list"),
429            Def::Array(a) => return elem(a.t(), "list"),
430            Def::Slice(sl) => return elem(sl.t(), "list"),
431            Def::Set(set) => return format!("list<{}>", self.shape_xur_name(set.t())),
432            Def::Map(m) => {
433                return format!(
434                    "map<{}, {}>",
435                    self.shape_xur_name(m.k()),
436                    self.shape_xur_name(m.v())
437                );
438            }
439            _ => {}
440        }
441        match shape.type_identifier {
442            "String" | "str" => "str".into(),
443            ident => ident.into(),
444        }
445    }
446
447    /// The display name of a [`TypeDesc`]. A named union with more than
448    /// [`ALIAS_INLINE_MAX`] options shows its name.
449    pub fn type_desc_name(&self, desc: &TypeDesc) -> String {
450        match desc {
451            TypeDesc::Shape(shape) => self.shape_xur_name(shape),
452            TypeDesc::Name(name) => (*name).into(),
453            TypeDesc::Generic(name, args) => {
454                let args: Vec<_> = args.iter().map(|a| self.type_desc_name(a)).collect();
455                format!("{name}<{}>", args.join(", "))
456            }
457            TypeDesc::Tuple(items) => {
458                let items: Vec<_> = items.iter().map(|a| self.type_desc_name(a)).collect();
459                format!("({})", items.join(", "))
460            }
461            TypeDesc::Alias(name, options) if options.len() > ALIAS_INLINE_MAX => (*name).into(),
462            TypeDesc::Alias(_, options) | TypeDesc::Union(options) => {
463                let options: Vec<_> = options.iter().map(|a| self.type_desc_name(a)).collect();
464                options.join(" | ")
465            }
466            TypeDesc::Unknown => "_".into(),
467        }
468    }
469
470    /// The return-type Shape of a native function (from its typed signature
471    /// or a [`ReturnHint::Shape`] hint). Returns `None` for raw functions
472    /// with no hint or an [`XurType`] hint.
473    pub fn native_return_shape(&self, id: NativeFnId) -> Option<&'static Shape> {
474        let f = self.function(id);
475        if let Some(sig) = &f.signature {
476            return Some(sig.ret);
477        }
478        match f.return_hint {
479            Some(ReturnHint::Shape(s)) => Some(s),
480            _ => None,
481        }
482    }
483
484    /// The xur type name of a native function's return type, if known.
485    pub fn native_return_name(&self, id: NativeFnId) -> Option<String> {
486        let f = self.function(id);
487        if let Some(sig) = &f.raw_sig {
488            return Some(
489                sig.ret
490                    .as_ref()
491                    .map_or_else(|| "()".into(), |t| self.type_desc_name(t)),
492            );
493        }
494        if let Some(sig) = &f.signature {
495            return Some(self.type_desc_name(&sig.ret_type));
496        }
497        match f.return_hint {
498            Some(ReturnHint::Shape(s)) => Some(self.shape_xur_name(s)),
499            Some(ReturnHint::Xur(xur)) => Some(self.xur_type_name(xur)),
500            None => None,
501        }
502    }
503
504    fn xur_type_name(&self, ty: XurType) -> String {
505        match ty {
506            XurType::Ptr(Some(inner)) => format!("*{}", self.shape_xur_name(inner)),
507            XurType::Ptr(None) => "ptr".into(),
508            XurType::List(None) => "list".into(),
509            XurType::List(Some(hint)) => format!("list<{}>", self.elem_hint_name(hint)),
510            XurType::Map(None, None) => "map".into(),
511            XurType::Map(Some(k), Some(v)) => {
512                format!(
513                    "map<{}, {}>",
514                    self.shape_xur_name(k),
515                    self.shape_xur_name(v)
516                )
517            }
518            XurType::Map(Some(k), None) => format!("map<{}, _>", self.shape_xur_name(k)),
519            XurType::Map(None, Some(v)) => format!("map<_, {}>", self.shape_xur_name(v)),
520            XurType::Named(name, []) => (*name).into(),
521            XurType::Named(name, params) => {
522                let args: Vec<_> = params.iter().map(|h| self.elem_hint_name(*h)).collect();
523                format!("{name}<{}>", args.join(", "))
524            }
525            XurType::Record => "record".into(),
526            XurType::Module => "module".into(),
527            XurType::Unit => "()".into(),
528        }
529    }
530
531    /// Sets the return-type hint on a raw function registered without a
532    fn elem_hint_name(&self, hint: ElemHint) -> String {
533        match hint {
534            ElemHint::Shape(s) => self.shape_xur_name(s),
535            ElemHint::Name(n) => n.into(),
536            ElemHint::Param(n) => format!("T{n}"),
537        }
538    }
539
540    /// full signature, for LSP inlay hints.
541    pub(super) fn set_return_hint(&self, id: NativeFnId, hint: ReturnHint) {
542        self.with_fn_mut(id, |f| f.return_hint = Some(hint));
543    }
544
545    /// Changes a function while it's being registered.
546    pub(super) fn with_fn_mut(&self, id: NativeFnId, change: impl FnOnce(&mut NativeFn)) {
547        let mut inner = self.write();
548        let slot = &mut inner.fns[id.0 as usize];
549        change(Arc::get_mut(slot).expect("changed during registration"));
550    }
551
552    /// Extract the xur name of the `index`th type parameter from a generic
553    /// Shape: for `Result<T, E>`, index 0 → T, index 1 → E; for `Option<T>`,
554    /// index 0 → T.
555    pub fn shape_type_param(&self, shape: &'static Shape, index: usize) -> Option<String> {
556        if let Ok(r) = shape.def.into_result() {
557            return match index {
558                0 => Some(self.shape_xur_name(r.t())),
559                1 => Some(self.shape_xur_name(r.e())),
560                _ => None,
561            };
562        }
563        if let Ok(o) = shape.def.into_option() {
564            return (index == 0).then(|| self.shape_xur_name(o.t()));
565        }
566        None
567    }
568
569    /// The native type registered for `shape`, if any.
570    pub fn type_of_shape(&self, shape: &'static Shape) -> Option<NativeTypeId> {
571        let index = self
572            .read()
573            .types
574            .iter()
575            .position(|ty| ty.shape == shape && ty.hooks.is_some())?;
576        Some(NativeTypeId(index as u32))
577    }
578
579    /// The type registered by shape only for `shape`, whose values are
580    /// typed records.
581    pub fn record_type_of_shape(&self, shape: &'static Shape) -> Option<NativeTypeId> {
582        let index = self
583            .read()
584            .types
585            .iter()
586            .position(|ty| ty.shape == shape && ty.hooks.is_none())?;
587        Some(NativeTypeId(index as u32))
588    }
589
590    /// Converts values of `shape` to Xur with `convert`, for types facet
591    /// cannot see inside, such as opaque ones. Such values cannot be
592    /// converted back.
593    pub fn converter(&self, shape: &'static Shape, convert: Converter) {
594        self.write().converters.push((shape, convert));
595    }
596
597    /// Whether a conversion is registered for `shape`.
598    pub fn has_converter(&self, shape: &'static Shape) -> bool {
599        self.converter_of(shape).is_some()
600    }
601
602    /// The conversion registered for `shape`, if any.
603    pub(crate) fn converter_of(&self, shape: &'static Shape) -> Option<Converter> {
604        let inner = self.read();
605        let (_, convert) = inner.converters.iter().find(|(s, _)| *s == shape)?;
606        Some(*convert)
607    }
608
609    /// How a value of the type `ty`, registered by shape, is built: the
610    /// fields of the struct itself, or of its enum variant `variant`.
611    /// `None` if there is no such struct or variant.
612    pub fn record_ctor(&self, ty: NativeTypeId, variant: Option<Symbol>) -> Option<RecordCtor> {
613        let shape = self.read().types[ty.0 as usize].shape;
614        let data = match (shape.ty, variant) {
615            (Type::User(UserType::Struct(st)), None) => st,
616            (Type::User(UserType::Enum(en)), Some(variant)) => {
617                en.variants
618                    .iter()
619                    .find(|v| v.name == variant.as_str())?
620                    .data
621            }
622            _ => return None,
623        };
624        Some(RecordCtor {
625            kind: variant_kind(data.kind),
626            fields: data
627                .fields
628                .iter()
629                .map(|field| Symbol::intern(field.name))
630                .collect(),
631        })
632    }
633
634    /// Whether any type, of either kind, is registered for `shape`.
635    pub fn has_shape(&self, shape: &'static Shape) -> bool {
636        self.read().types.iter().any(|ty| ty.shape == shape)
637    }
638
639    /// Reads field `name` of a native object.
640    pub fn field(
641        &self,
642        cx: &dyn ConvertCx,
643        object: &NativeObject,
644        name: &str,
645    ) -> Option<RunResult<Value>> {
646        let field = self.hooks(object.ty).field;
647        object.with_any(|value| field(cx, value, name))
648    }
649
650    /// Formats a native object with its `Display`, or else `Debug`.
651    /// A native object's `Display`, or its Xur type name in angle brackets
652    /// when the Rust type has no `Display` (`<AnyImage>`), rather than a
653    /// debug dump.
654    pub fn display(&self, object: &NativeObject) -> String {
655        object
656            .with_any(self.hooks(object.ty).display)
657            .unwrap_or_else(|| format!("<{}>", self.type_name(object.ty)))
658    }
659
660    /// Whether two native objects are equal by their Rust `PartialEq`.
661    pub fn native_eq(&self, a: &NativeObject, b: &NativeObject) -> bool {
662        if a.ty != b.ty {
663            return false;
664        }
665        if std::ptr::eq(a, b) {
666            return true;
667        }
668        let eq = self.hooks(a.ty).eq;
669        a.with_any(|a| b.with_any(|b| eq(a, b)))
670    }
671
672    /// A native object of the type registered for `T`, holding `value` and
673    /// keeping `keep_alive` alive with it so any memory `value` borrows
674    /// stays valid. For types like `PEFile<'static>` that borrow a file's
675    /// bytes: the bytes go in `keep_alive`.
676    pub fn borrowing_object<T: Facet<'static> + Send + 'static>(
677        &self,
678        value: T,
679        keep_alive: Arc<dyn std::any::Any + Send + Sync>,
680    ) -> RunResult<Value> {
681        let ty = self
682            .type_of_shape(T::SHAPE)
683            .ok_or_else(|| RuntimeError::new(format!("`{}` is not a registered type", T::SHAPE)))?;
684        let object = NativeObject::borrowing(ty, Box::new(value), keep_alive);
685        Ok(Value::Native(object.into()))
686    }
687
688    /// A native object holding a clone of the registered value behind `peek`.
689    pub(crate) fn object_from_peek(
690        &self,
691        ty: NativeTypeId,
692        peek: Peek<'_, 'static>,
693    ) -> Option<NativeObject> {
694        let value = (self.hooks(ty).clone_peek)(peek)?;
695        Some(NativeObject::new(ty, value))
696    }
697
698    /// Writes a clone of `object` into a builder for its type.
699    pub(crate) fn set_object(&self, partial: Builder, object: &NativeObject) -> RunResult<Builder> {
700        let set = self.hooks(object.ty).set;
701        object.with_any(|value| set(partial, value))
702    }
703
704    /// The hooks of a type registered with its Rust type, which every type
705    /// with native objects is.
706    fn hooks(&self, ty: NativeTypeId) -> TypeHooks {
707        self.read().types[ty.0 as usize]
708            .hooks
709            .expect("native objects only exist for types registered with their Rust type")
710    }
711
712    /// The registered modules as name resolution sees them.
713    pub fn decls(&self) -> Vec<NativeModule> {
714        let inner = self.read();
715        inner
716            .roots
717            .iter()
718            .map(|&module| inner.decl(module))
719            .collect()
720    }
721
722    /// Registers the contents of the lazy module at `path`, if not yet
723    /// registered, and describes it.
724    pub fn expand(&self, path: &[String]) -> NativeModule {
725        let (module, init) = {
726            let mut inner = self.write();
727            let module = inner
728                .find(path)
729                .unwrap_or_else(|| panic!("no native module `{}`", path.join("::")));
730            (module, inner.modules[module].init.take())
731        };
732        // The initializer registers through the builder, which locks.
733        if let Some(init) = init {
734            init(&mut ModuleBuilder::new(self, module));
735        }
736        self.read().decl(module)
737    }
738
739    pub fn add_fn(
740        &self,
741        name: &str,
742        signature: Option<Signature>,
743        param_names: Vec<String>,
744        call: Box<CallFn>,
745    ) -> NativeFnDecl {
746        self.write().add_fn(name, signature, param_names, call)
747    }
748
749    fn with_inner<R>(&self, f: impl FnOnce(&mut Inner) -> R) -> R {
750        f(&mut self.write())
751    }
752}
753
754impl Inner {
755    fn module_at(&mut self, path: &str) -> usize {
756        let mut names = path.split("::");
757        let root = names.next().expect("split yields at least one item");
758        let mut module = self.child(None, root);
759        for name in names {
760            module = self.child(Some(module), name);
761        }
762        module
763    }
764
765    fn find(&self, path: &[String]) -> Option<usize> {
766        let mut module: Option<usize> = None;
767        for name in path {
768            let siblings = match module {
769                Some(parent) => &self.modules[parent].children,
770                None => &self.roots,
771            };
772            module = Some(*siblings.iter().find(|&&m| self.modules[m].name == *name)?);
773        }
774        module
775    }
776
777    fn decl(&self, module: usize) -> NativeModule {
778        let data = &self.modules[module];
779        if data.init.is_some() {
780            return NativeModule {
781                name: data.name.clone(),
782                lazy: true,
783                ..NativeModule::default()
784            };
785        }
786        NativeModule {
787            name: data.name.clone(),
788            lazy: false,
789            functions: data.functions.clone(),
790            types: data
791                .types
792                .iter()
793                .map(|&id| {
794                    let ty = &self.types[id.0 as usize];
795                    NativeTypeDecl {
796                        name: ty.name.clone(),
797                        id,
798                        functions: ty.functions.clone(),
799                        variants: if let Some(ref v) = ty.explicit_variants {
800                            v.clone()
801                        } else {
802                            variant_decls(ty.shape)
803                        },
804                    }
805                })
806                .collect(),
807            modules: data
808                .children
809                .iter()
810                .map(|&child| self.decl(child))
811                .collect(),
812        }
813    }
814
815    /// The submodule `name` of `parent` (or the root module `name`).
816    fn child(&mut self, parent: Option<usize>, name: &str) -> usize {
817        let siblings = match parent {
818            Some(parent) => &self.modules[parent].children,
819            None => &self.roots,
820        };
821        if let Some(&existing) = siblings.iter().find(|&&m| self.modules[m].name == name) {
822            return existing;
823        }
824        let module = self.modules.len();
825        self.modules.push(ModuleData {
826            name: name.to_owned(),
827            init: None,
828            children: Vec::new(),
829            functions: Vec::new(),
830            types: Vec::new(),
831            macros: HashMap::new(),
832        });
833        match parent {
834            Some(parent) => self.modules[parent].children.push(module),
835            None => self.roots.push(module),
836        }
837        module
838    }
839
840    fn add_fn(
841        &mut self,
842        name: &str,
843        signature: Option<Signature>,
844        param_names: Vec<String>,
845        call: Box<CallFn>,
846    ) -> NativeFnDecl {
847        let id = NativeFnId(self.fns.len() as u32);
848        self.fns.push(Arc::new(NativeFn {
849            name: name.to_owned(),
850            signature,
851            return_hint: None,
852            raw_sig: None,
853            param_names: param_names.clone(),
854            call,
855        }));
856        NativeFnDecl {
857            name: name.to_owned(),
858            id,
859            param_names,
860        }
861    }
862}
863
864impl NativeProvider for Registry {
865    fn modules(&self) -> Vec<NativeModule> {
866        self.decls()
867    }
868
869    fn expand(&self, path: &[String]) -> NativeModule {
870        Registry::expand(self, path)
871    }
872
873    fn macro_expander(&self, path: &[&str]) -> Option<Arc<dyn MacroExpander>> {
874        if path.is_empty() {
875            return None;
876        }
877        let (module_path, macro_name) = path.split_at(path.len() - 1);
878        let macro_name = macro_name[0];
879
880        // Walk the module tree, expanding lazy modules along the way.
881        // Each lock is acquired and released before the next to avoid
882        // deadlocking when a lazy init needs a write lock.
883        let mut module: Option<usize> = None;
884        for name in module_path {
885            let idx = {
886                let inner = self.read();
887                let siblings = match module {
888                    Some(parent) => &inner.modules[parent].children,
889                    None => &inner.roots,
890                };
891                siblings
892                    .iter()
893                    .find(|&&m| inner.modules[m].name == *name)
894                    .copied()?
895            };
896
897            let init = self.write().modules[idx].init.take();
898            if let Some(init) = init {
899                init(&mut ModuleBuilder::new(self, idx));
900            }
901            module = Some(idx);
902        }
903
904        let parent = module?;
905        self.read().modules[parent].macros.get(macro_name).cloned()
906    }
907
908    fn register_enum_builtins(&self, enum_def: DefId) -> Vec<NativeFnDecl> {
909        vec![
910            self.add_fn(
911                "from_str",
912                None,
913                vec!["name".into()],
914                Box::new({
915                    let def = enum_def;
916                    move |cx, args| enum_from_str(cx, def, args)
917                }),
918            ),
919            self.add_fn(
920                "len",
921                None,
922                Vec::new(),
923                Box::new({
924                    let def = enum_def;
925                    move |cx, args| enum_len(cx, def, args)
926                }),
927            ),
928            self.add_fn(
929                "values",
930                None,
931                Vec::new(),
932                Box::new({
933                    let def = enum_def;
934                    move |cx, args| enum_values(cx, def, args)
935                }),
936            ),
937        ]
938    }
939}
940
941fn enum_from_str(cx: &mut dyn Context, enum_def: DefId, args: &[Value]) -> RunResult<Value> {
942    let [Value::Str(name)] = args else {
943        return Err(RuntimeError::new("`from_str` takes a string"));
944    };
945    let lang = cx.lang();
946    for (vname, vdef, has_fields) in cx.enum_variants(enum_def) {
947        if vname == name.as_ref() && !has_fields {
948            return Ok(Value::adt(lang.some, vec![Value::adt(vdef, vec![])]));
949        }
950    }
951    Ok(Value::adt(lang.none, vec![]))
952}
953
954fn enum_len(cx: &mut dyn Context, enum_def: DefId, args: &[Value]) -> RunResult<Value> {
955    if !args.is_empty() {
956        return Err(RuntimeError::new("`len` takes no arguments"));
957    }
958    Ok(Value::int(cx.enum_variants(enum_def).len() as i64))
959}
960
961fn enum_values(cx: &mut dyn Context, enum_def: DefId, args: &[Value]) -> RunResult<Value> {
962    if !args.is_empty() {
963        return Err(RuntimeError::new("`values` takes no arguments"));
964    }
965    let values: Vec<Value> = cx
966        .enum_variants(enum_def)
967        .into_iter()
968        .filter(|(_, _, has_fields)| !has_fields)
969        .map(|(_, vdef, _)| Value::adt(vdef, vec![]))
970        .collect();
971    Ok(Value::list(values))
972}