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