Skip to main content

xur_runtime/registry/
mod.rs

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