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