1mod builder;
29mod hooks;
30mod into_native;
31mod raw_sig;
32#[cfg(test)]
33mod tests;
34
35use std::collections::HashMap;
36use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
37use std::thread::JoinHandle;
38
39use facet::{Def, Facet, Peek, PointerType, Shape, StructKind, StructType, Type, UserType};
40use xur_resolve::{
41 DefId, NativeFnDecl, NativeFnId, NativeModule, NativeProvider, NativeTypeDecl, NativeTypeId,
42 NativeVariantDecl, NativeVariantKind, RtType, macros::MacroExpander,
43};
44
45use xur_span::{Span, Symbol};
46
47use crate::convert::{Builder, ConvertCx};
48use crate::value::NativeObject;
49use crate::{AdtInfo, BuiltinType, RunResult, RuntimeError, TypeDesc, TypeRef, Value};
50
51pub use builder::{
52 BuiltinBuilder, ElemHint, ModuleBuilder, ReturnHint, Returns, TypeBuilder, XurType,
53};
54pub use into_native::{
55 BuiltinRecv, BuiltinRecvMut, IntoBuiltinMethod, IntoBuiltinMethodMut, IntoNativeFn,
56 IntoNativeMethod, IntoNativeMethodMut,
57};
58pub use raw_sig::{RawParam, RawSig};
59
60use hooks::TypeHooks;
61
62pub trait Context: ConvertCx {
64 fn import(&mut self, path: &str) -> RunResult<Value>;
67 fn display(&self, value: &Value) -> String;
69 fn type_args(&self) -> &[TypeRef];
72 fn print(&mut self, text: &str) -> RunResult<()>;
74 fn eprint(&mut self, text: &str) -> RunResult<()> {
77 use std::io::Write;
78 std::io::stderr()
79 .write_all(text.as_bytes())
80 .map_err(|error| RuntimeError::new(format!("couldn't write to stderr: {error}")))
81 }
82 fn call(&mut self, callee: &Value, args: &[Value]) -> RunResult<Value>;
84 fn spawn(&mut self, f: Value) -> RunResult<JoinHandle<RunResult<Value>>>;
87
88 fn describe_type(&self, value: &Value) -> String;
92 fn describe_span(&self, span: Span) -> String;
96 fn type_of(&self, value: &Value) -> RtType;
99 fn adt_info(&self, def: DefId) -> Option<AdtInfo>;
101 fn methods(&self, value: &Value) -> Vec<String>;
103 fn field(&mut self, value: &Value, name: &str) -> RunResult<Value>;
105 fn set_field(&mut self, value: &Value, name: &str, new: Value) -> RunResult<Value>;
107 fn call_method(&mut self, receiver: Value, name: &str, args: &[Value]) -> RunResult<Value>;
109
110 fn try_cast(&self, value: &Value, target: DefId) -> RunResult<Value>;
114
115 fn repr_value(&self, def: DefId) -> Option<i64>;
117
118 fn fn_info(&self, value: &Value) -> Option<crate::FnInfo>;
120
121 fn shared_handle(&self) -> Option<Box<dyn std::any::Any + Send + Sync>> {
125 None
126 }
127
128 fn def_name(&self, _def: DefId) -> Option<String> {
131 None
132 }
133
134 fn enum_variants(&self, _def: DefId) -> Vec<(String, DefId, bool)> {
136 Vec::new()
137 }
138}
139
140pub const ALIAS_INLINE_MAX: usize = 3;
142
143pub(crate) type CallFn = dyn Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync;
144
145#[derive(Debug, Clone)]
147pub struct Signature {
148 pub params: Vec<&'static Shape>,
149 pub ret: &'static Shape,
150 pub param_names: Vec<String>,
151 pub param_types: Vec<TypeDesc>,
153 pub ret_type: TypeDesc,
155 pub required: usize,
157}
158
159pub struct NativeFn {
160 pub name: String,
161 pub signature: Option<Signature>,
163 pub return_hint: Option<ReturnHint>,
165 pub raw_sig: Option<RawSig>,
167 pub param_names: Vec<String>,
168 call: Box<CallFn>,
169}
170
171impl NativeFn {
172 pub fn call(&self, cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
173 (self.call)(cx, args)
174 }
175}
176
177pub(super) struct NativeType {
178 name: String,
179 shape: &'static Shape,
180 functions: Vec<NativeFnDecl>,
181 hooks: Option<TypeHooks>,
184 explicit_variants: Option<Vec<NativeVariantDecl>>,
187}
188
189type ModuleInit = Box<dyn FnOnce(&mut ModuleBuilder<'_>) + Send + Sync>;
191
192struct ModuleData {
193 name: String,
194 init: Option<ModuleInit>,
196 children: Vec<usize>,
197 functions: Vec<NativeFnDecl>,
198 types: Vec<NativeTypeId>,
199 macros: HashMap<String, Arc<dyn MacroExpander>>,
200}
201
202#[derive(Default)]
209pub struct Registry {
210 inner: RwLock<Inner>,
211}
212
213#[derive(Default)]
214struct Inner {
215 fns: Vec<Arc<NativeFn>>,
216 builtin_methods: HashMap<(BuiltinType, String), NativeFnId>,
218 types: Vec<NativeType>,
219 modules: Vec<ModuleData>,
220 roots: Vec<usize>,
222 converters: Vec<(&'static Shape, Converter)>,
224}
225
226#[derive(Debug, Clone, PartialEq, Eq)]
228pub struct RecordCtor {
229 pub kind: NativeVariantKind,
230 pub fields: Vec<Symbol>,
232}
233
234fn variant_decls(shape: &'static Shape) -> Vec<NativeVariantDecl> {
236 let Type::User(UserType::Enum(en)) = shape.ty else {
237 return Vec::new();
238 };
239 en.variants
240 .iter()
241 .map(|variant| NativeVariantDecl {
242 name: variant.name.to_owned(),
243 kind: variant_kind(variant.data.kind),
244 repr_value: None,
245 })
246 .collect()
247}
248
249fn variant_kind(kind: StructKind) -> NativeVariantKind {
250 match kind {
251 StructKind::Unit => NativeVariantKind::Unit,
252 StructKind::Tuple | StructKind::TupleStruct => NativeVariantKind::Tuple,
253 StructKind::Struct => NativeVariantKind::Named,
254 }
255}
256
257pub type Converter = fn(&dyn ConvertCx, Peek<'_, 'static>) -> RunResult<Value>;
259
260impl Registry {
261 pub fn new() -> Self {
262 Self::default()
263 }
264
265 fn read(&self) -> RwLockReadGuard<'_, Inner> {
266 self.inner.read().unwrap_or_else(PoisonError::into_inner)
267 }
268
269 fn write(&self) -> RwLockWriteGuard<'_, Inner> {
270 self.inner.write().unwrap_or_else(PoisonError::into_inner)
271 }
272
273 pub fn module(&self, path: &str) -> ModuleBuilder<'_> {
275 let module = self.write().module_at(path);
276 ModuleBuilder::new(self, module)
277 }
278
279 pub fn lazy_module(
283 &self,
284 path: &str,
285 init: impl FnOnce(&mut ModuleBuilder<'_>) + Send + Sync + 'static,
286 ) {
287 let mut inner = self.write();
288 let module = inner.module_at(path);
289 inner.modules[module].init = Some(Box::new(init));
290 }
291
292 pub fn builtin(&self, ty: BuiltinType) -> BuiltinBuilder<'_> {
294 BuiltinBuilder::new(self, ty)
295 }
296
297 pub fn builtin_method(&self, ty: BuiltinType, name: &str) -> Option<NativeFnId> {
299 self.read()
300 .builtin_methods
301 .get(&(ty, name.to_owned()))
302 .copied()
303 }
304
305 pub fn type_function(&self, ty: NativeTypeId, name: &str) -> Option<NativeFnId> {
307 let inner = self.read();
308 let functions = &inner.types[ty.0 as usize].functions;
309 functions.iter().find(|f| f.name == name).map(|f| f.id)
310 }
311
312 pub fn type_methods(&self, ty: NativeTypeId) -> Vec<String> {
315 let inner = self.read();
316 let native = &inner.types[ty.0 as usize];
317 native
318 .functions
319 .iter()
320 .filter(|decl| match &inner.fns[decl.id.0 as usize].signature {
321 Some(signature) => signature.params.first() == Some(&native.shape),
322 None => true,
323 })
324 .map(|decl| decl.name.clone())
325 .collect()
326 }
327
328 pub fn builtin_methods(&self, ty: BuiltinType) -> Vec<String> {
330 let mut names: Vec<_> = self
331 .read()
332 .builtin_methods
333 .keys()
334 .filter(|(builtin, _)| *builtin == ty)
335 .map(|(_, name)| name.clone())
336 .collect();
337 names.sort();
338 names
339 }
340
341 pub fn type_fields(&self, ty: NativeTypeId) -> Vec<String> {
343 let shape = self.read().types[ty.0 as usize].shape;
344 match shape.ty {
345 Type::User(UserType::Struct(StructType { fields, .. })) => {
346 fields.iter().map(|field| field.name.to_owned()).collect()
347 }
348 _ => Vec::new(),
349 }
350 }
351
352 pub fn function_count(&self) -> usize {
354 self.read().fns.len()
355 }
356
357 pub fn function(&self, id: NativeFnId) -> Arc<NativeFn> {
358 Arc::clone(&self.read().fns[id.0 as usize])
359 }
360
361 pub fn type_name(&self, id: NativeTypeId) -> String {
362 self.read().types[id.0 as usize].name.clone()
363 }
364
365 pub fn type_shape(&self, id: NativeTypeId) -> &'static Shape {
369 self.read().types[id.0 as usize].shape
370 }
371
372 pub fn type_id_by_name(&self, name: &str) -> Option<NativeTypeId> {
374 let inner = self.read();
375 inner
376 .types
377 .iter()
378 .enumerate()
379 .find_map(|(i, ty)| (ty.name == name).then_some(NativeTypeId(i as u32)))
380 }
381
382 pub fn shape_xur_name(&self, shape: &'static Shape) -> String {
387 if let Some(id) = self.type_of_shape(shape) {
388 return self.type_name(id);
389 }
390 let elem = |t: &'static Shape, wrap: &str| {
391 if t == u8::SHAPE {
392 "bytes".to_string()
393 } else {
394 format!("{wrap}<{}>", self.shape_xur_name(t))
395 }
396 };
397 if let Type::Pointer(PointerType::Reference(p) | PointerType::Raw(p)) = shape.ty {
399 return self.shape_xur_name(p.target());
400 }
401 if let Def::Pointer(p) = shape.def
402 && let Some(pointee) = p.pointee()
403 {
404 return self.shape_xur_name(pointee);
405 }
406 if let Type::User(UserType::Struct(StructType {
408 kind: StructKind::Tuple,
409 fields,
410 ..
411 })) = shape.ty
412 {
413 let items: Vec<_> = fields
414 .iter()
415 .map(|f| self.shape_xur_name(f.shape()))
416 .collect();
417 return format!("({})", items.join(", "));
418 }
419 match shape.def {
420 Def::Option(o) => return format!("Option<{}>", self.shape_xur_name(o.t())),
421 Def::Result(r) => {
422 return format!(
423 "Result<{}, {}>",
424 self.shape_xur_name(r.t()),
425 self.shape_xur_name(r.e())
426 );
427 }
428 Def::List(l) => return elem(l.t(), "list"),
429 Def::Array(a) => return elem(a.t(), "list"),
430 Def::Slice(sl) => return elem(sl.t(), "list"),
431 Def::Set(set) => return format!("list<{}>", self.shape_xur_name(set.t())),
432 Def::Map(m) => {
433 return format!(
434 "map<{}, {}>",
435 self.shape_xur_name(m.k()),
436 self.shape_xur_name(m.v())
437 );
438 }
439 _ => {}
440 }
441 match shape.type_identifier {
442 "String" | "str" => "str".into(),
443 ident => ident.into(),
444 }
445 }
446
447 pub fn type_desc_name(&self, desc: &TypeDesc) -> String {
450 match desc {
451 TypeDesc::Shape(shape) => self.shape_xur_name(shape),
452 TypeDesc::Name(name) => (*name).into(),
453 TypeDesc::Generic(name, args) => {
454 let args: Vec<_> = args.iter().map(|a| self.type_desc_name(a)).collect();
455 format!("{name}<{}>", args.join(", "))
456 }
457 TypeDesc::Tuple(items) => {
458 let items: Vec<_> = items.iter().map(|a| self.type_desc_name(a)).collect();
459 format!("({})", items.join(", "))
460 }
461 TypeDesc::Alias(name, options) if options.len() > ALIAS_INLINE_MAX => (*name).into(),
462 TypeDesc::Alias(_, options) | TypeDesc::Union(options) => {
463 let options: Vec<_> = options.iter().map(|a| self.type_desc_name(a)).collect();
464 options.join(" | ")
465 }
466 TypeDesc::Unknown => "_".into(),
467 }
468 }
469
470 pub fn native_return_shape(&self, id: NativeFnId) -> Option<&'static Shape> {
474 let f = self.function(id);
475 if let Some(sig) = &f.signature {
476 return Some(sig.ret);
477 }
478 match f.return_hint {
479 Some(ReturnHint::Shape(s)) => Some(s),
480 _ => None,
481 }
482 }
483
484 pub fn native_return_name(&self, id: NativeFnId) -> Option<String> {
486 let f = self.function(id);
487 if let Some(sig) = &f.raw_sig {
488 return Some(
489 sig.ret
490 .as_ref()
491 .map_or_else(|| "()".into(), |t| self.type_desc_name(t)),
492 );
493 }
494 if let Some(sig) = &f.signature {
495 return Some(self.type_desc_name(&sig.ret_type));
496 }
497 match f.return_hint {
498 Some(ReturnHint::Shape(s)) => Some(self.shape_xur_name(s)),
499 Some(ReturnHint::Xur(xur)) => Some(self.xur_type_name(xur)),
500 None => None,
501 }
502 }
503
504 fn xur_type_name(&self, ty: XurType) -> String {
505 match ty {
506 XurType::Ptr(Some(inner)) => format!("*{}", self.shape_xur_name(inner)),
507 XurType::Ptr(None) => "ptr".into(),
508 XurType::List(None) => "list".into(),
509 XurType::List(Some(hint)) => format!("list<{}>", self.elem_hint_name(hint)),
510 XurType::Map(None, None) => "map".into(),
511 XurType::Map(Some(k), Some(v)) => {
512 format!(
513 "map<{}, {}>",
514 self.shape_xur_name(k),
515 self.shape_xur_name(v)
516 )
517 }
518 XurType::Map(Some(k), None) => format!("map<{}, _>", self.shape_xur_name(k)),
519 XurType::Map(None, Some(v)) => format!("map<_, {}>", self.shape_xur_name(v)),
520 XurType::Named(name, []) => (*name).into(),
521 XurType::Named(name, params) => {
522 let args: Vec<_> = params.iter().map(|h| self.elem_hint_name(*h)).collect();
523 format!("{name}<{}>", args.join(", "))
524 }
525 XurType::Record => "record".into(),
526 XurType::Module => "module".into(),
527 XurType::Unit => "()".into(),
528 }
529 }
530
531 fn elem_hint_name(&self, hint: ElemHint) -> String {
533 match hint {
534 ElemHint::Shape(s) => self.shape_xur_name(s),
535 ElemHint::Name(n) => n.into(),
536 ElemHint::Param(n) => format!("T{n}"),
537 }
538 }
539
540 pub(super) fn set_return_hint(&self, id: NativeFnId, hint: ReturnHint) {
542 self.with_fn_mut(id, |f| f.return_hint = Some(hint));
543 }
544
545 pub(super) fn with_fn_mut(&self, id: NativeFnId, change: impl FnOnce(&mut NativeFn)) {
547 let mut inner = self.write();
548 let slot = &mut inner.fns[id.0 as usize];
549 change(Arc::get_mut(slot).expect("changed during registration"));
550 }
551
552 pub fn shape_type_param(&self, shape: &'static Shape, index: usize) -> Option<String> {
556 if let Ok(r) = shape.def.into_result() {
557 return match index {
558 0 => Some(self.shape_xur_name(r.t())),
559 1 => Some(self.shape_xur_name(r.e())),
560 _ => None,
561 };
562 }
563 if let Ok(o) = shape.def.into_option() {
564 return (index == 0).then(|| self.shape_xur_name(o.t()));
565 }
566 None
567 }
568
569 pub fn type_of_shape(&self, shape: &'static Shape) -> Option<NativeTypeId> {
571 let index = self
572 .read()
573 .types
574 .iter()
575 .position(|ty| ty.shape == shape && ty.hooks.is_some())?;
576 Some(NativeTypeId(index as u32))
577 }
578
579 pub fn record_type_of_shape(&self, shape: &'static Shape) -> Option<NativeTypeId> {
582 let index = self
583 .read()
584 .types
585 .iter()
586 .position(|ty| ty.shape == shape && ty.hooks.is_none())?;
587 Some(NativeTypeId(index as u32))
588 }
589
590 pub fn converter(&self, shape: &'static Shape, convert: Converter) {
594 self.write().converters.push((shape, convert));
595 }
596
597 pub fn has_converter(&self, shape: &'static Shape) -> bool {
599 self.converter_of(shape).is_some()
600 }
601
602 pub(crate) fn converter_of(&self, shape: &'static Shape) -> Option<Converter> {
604 let inner = self.read();
605 let (_, convert) = inner.converters.iter().find(|(s, _)| *s == shape)?;
606 Some(*convert)
607 }
608
609 pub fn record_ctor(&self, ty: NativeTypeId, variant: Option<Symbol>) -> Option<RecordCtor> {
613 let shape = self.read().types[ty.0 as usize].shape;
614 let data = match (shape.ty, variant) {
615 (Type::User(UserType::Struct(st)), None) => st,
616 (Type::User(UserType::Enum(en)), Some(variant)) => {
617 en.variants
618 .iter()
619 .find(|v| v.name == variant.as_str())?
620 .data
621 }
622 _ => return None,
623 };
624 Some(RecordCtor {
625 kind: variant_kind(data.kind),
626 fields: data
627 .fields
628 .iter()
629 .map(|field| Symbol::intern(field.name))
630 .collect(),
631 })
632 }
633
634 pub fn has_shape(&self, shape: &'static Shape) -> bool {
636 self.read().types.iter().any(|ty| ty.shape == shape)
637 }
638
639 pub fn field(
641 &self,
642 cx: &dyn ConvertCx,
643 object: &NativeObject,
644 name: &str,
645 ) -> Option<RunResult<Value>> {
646 let field = self.hooks(object.ty).field;
647 object.with_any(|value| field(cx, value, name))
648 }
649
650 pub fn display(&self, object: &NativeObject) -> String {
655 object
656 .with_any(self.hooks(object.ty).display)
657 .unwrap_or_else(|| format!("<{}>", self.type_name(object.ty)))
658 }
659
660 pub fn native_eq(&self, a: &NativeObject, b: &NativeObject) -> bool {
662 if a.ty != b.ty {
663 return false;
664 }
665 if std::ptr::eq(a, b) {
666 return true;
667 }
668 let eq = self.hooks(a.ty).eq;
669 a.with_any(|a| b.with_any(|b| eq(a, b)))
670 }
671
672 pub fn borrowing_object<T: Facet<'static> + Send + 'static>(
677 &self,
678 value: T,
679 keep_alive: Arc<dyn std::any::Any + Send + Sync>,
680 ) -> RunResult<Value> {
681 let ty = self
682 .type_of_shape(T::SHAPE)
683 .ok_or_else(|| RuntimeError::new(format!("`{}` is not a registered type", T::SHAPE)))?;
684 let object = NativeObject::borrowing(ty, Box::new(value), keep_alive);
685 Ok(Value::Native(object.into()))
686 }
687
688 pub(crate) fn object_from_peek(
690 &self,
691 ty: NativeTypeId,
692 peek: Peek<'_, 'static>,
693 ) -> Option<NativeObject> {
694 let value = (self.hooks(ty).clone_peek)(peek)?;
695 Some(NativeObject::new(ty, value))
696 }
697
698 pub(crate) fn set_object(&self, partial: Builder, object: &NativeObject) -> RunResult<Builder> {
700 let set = self.hooks(object.ty).set;
701 object.with_any(|value| set(partial, value))
702 }
703
704 fn hooks(&self, ty: NativeTypeId) -> TypeHooks {
707 self.read().types[ty.0 as usize]
708 .hooks
709 .expect("native objects only exist for types registered with their Rust type")
710 }
711
712 pub fn decls(&self) -> Vec<NativeModule> {
714 let inner = self.read();
715 inner
716 .roots
717 .iter()
718 .map(|&module| inner.decl(module))
719 .collect()
720 }
721
722 pub fn expand(&self, path: &[String]) -> NativeModule {
725 let (module, init) = {
726 let mut inner = self.write();
727 let module = inner
728 .find(path)
729 .unwrap_or_else(|| panic!("no native module `{}`", path.join("::")));
730 (module, inner.modules[module].init.take())
731 };
732 if let Some(init) = init {
734 init(&mut ModuleBuilder::new(self, module));
735 }
736 self.read().decl(module)
737 }
738
739 pub fn add_fn(
740 &self,
741 name: &str,
742 signature: Option<Signature>,
743 param_names: Vec<String>,
744 call: Box<CallFn>,
745 ) -> NativeFnDecl {
746 self.write().add_fn(name, signature, param_names, call)
747 }
748
749 fn with_inner<R>(&self, f: impl FnOnce(&mut Inner) -> R) -> R {
750 f(&mut self.write())
751 }
752}
753
754impl Inner {
755 fn module_at(&mut self, path: &str) -> usize {
756 let mut names = path.split("::");
757 let root = names.next().expect("split yields at least one item");
758 let mut module = self.child(None, root);
759 for name in names {
760 module = self.child(Some(module), name);
761 }
762 module
763 }
764
765 fn find(&self, path: &[String]) -> Option<usize> {
766 let mut module: Option<usize> = None;
767 for name in path {
768 let siblings = match module {
769 Some(parent) => &self.modules[parent].children,
770 None => &self.roots,
771 };
772 module = Some(*siblings.iter().find(|&&m| self.modules[m].name == *name)?);
773 }
774 module
775 }
776
777 fn decl(&self, module: usize) -> NativeModule {
778 let data = &self.modules[module];
779 if data.init.is_some() {
780 return NativeModule {
781 name: data.name.clone(),
782 lazy: true,
783 ..NativeModule::default()
784 };
785 }
786 NativeModule {
787 name: data.name.clone(),
788 lazy: false,
789 functions: data.functions.clone(),
790 types: data
791 .types
792 .iter()
793 .map(|&id| {
794 let ty = &self.types[id.0 as usize];
795 NativeTypeDecl {
796 name: ty.name.clone(),
797 id,
798 functions: ty.functions.clone(),
799 variants: if let Some(ref v) = ty.explicit_variants {
800 v.clone()
801 } else {
802 variant_decls(ty.shape)
803 },
804 }
805 })
806 .collect(),
807 modules: data
808 .children
809 .iter()
810 .map(|&child| self.decl(child))
811 .collect(),
812 }
813 }
814
815 fn child(&mut self, parent: Option<usize>, name: &str) -> usize {
817 let siblings = match parent {
818 Some(parent) => &self.modules[parent].children,
819 None => &self.roots,
820 };
821 if let Some(&existing) = siblings.iter().find(|&&m| self.modules[m].name == name) {
822 return existing;
823 }
824 let module = self.modules.len();
825 self.modules.push(ModuleData {
826 name: name.to_owned(),
827 init: None,
828 children: Vec::new(),
829 functions: Vec::new(),
830 types: Vec::new(),
831 macros: HashMap::new(),
832 });
833 match parent {
834 Some(parent) => self.modules[parent].children.push(module),
835 None => self.roots.push(module),
836 }
837 module
838 }
839
840 fn add_fn(
841 &mut self,
842 name: &str,
843 signature: Option<Signature>,
844 param_names: Vec<String>,
845 call: Box<CallFn>,
846 ) -> NativeFnDecl {
847 let id = NativeFnId(self.fns.len() as u32);
848 self.fns.push(Arc::new(NativeFn {
849 name: name.to_owned(),
850 signature,
851 return_hint: None,
852 raw_sig: None,
853 param_names: param_names.clone(),
854 call,
855 }));
856 NativeFnDecl {
857 name: name.to_owned(),
858 id,
859 param_names,
860 }
861 }
862}
863
864impl NativeProvider for Registry {
865 fn modules(&self) -> Vec<NativeModule> {
866 self.decls()
867 }
868
869 fn expand(&self, path: &[String]) -> NativeModule {
870 Registry::expand(self, path)
871 }
872
873 fn macro_expander(&self, path: &[&str]) -> Option<Arc<dyn MacroExpander>> {
874 if path.is_empty() {
875 return None;
876 }
877 let (module_path, macro_name) = path.split_at(path.len() - 1);
878 let macro_name = macro_name[0];
879
880 let mut module: Option<usize> = None;
884 for name in module_path {
885 let idx = {
886 let inner = self.read();
887 let siblings = match module {
888 Some(parent) => &inner.modules[parent].children,
889 None => &inner.roots,
890 };
891 siblings
892 .iter()
893 .find(|&&m| inner.modules[m].name == *name)
894 .copied()?
895 };
896
897 let init = self.write().modules[idx].init.take();
898 if let Some(init) = init {
899 init(&mut ModuleBuilder::new(self, idx));
900 }
901 module = Some(idx);
902 }
903
904 let parent = module?;
905 self.read().modules[parent].macros.get(macro_name).cloned()
906 }
907
908 fn register_enum_builtins(&self, enum_def: DefId) -> Vec<NativeFnDecl> {
909 vec![
910 self.add_fn(
911 "from_str",
912 None,
913 vec!["name".into()],
914 Box::new({
915 let def = enum_def;
916 move |cx, args| enum_from_str(cx, def, args)
917 }),
918 ),
919 self.add_fn(
920 "len",
921 None,
922 Vec::new(),
923 Box::new({
924 let def = enum_def;
925 move |cx, args| enum_len(cx, def, args)
926 }),
927 ),
928 self.add_fn(
929 "values",
930 None,
931 Vec::new(),
932 Box::new({
933 let def = enum_def;
934 move |cx, args| enum_values(cx, def, args)
935 }),
936 ),
937 ]
938 }
939}
940
941fn enum_from_str(cx: &mut dyn Context, enum_def: DefId, args: &[Value]) -> RunResult<Value> {
942 let [Value::Str(name)] = args else {
943 return Err(RuntimeError::new("`from_str` takes a string"));
944 };
945 let lang = cx.lang();
946 for (vname, vdef, has_fields) in cx.enum_variants(enum_def) {
947 if vname == name.as_ref() && !has_fields {
948 return Ok(Value::adt(lang.some, vec![Value::adt(vdef, vec![])]));
949 }
950 }
951 Ok(Value::adt(lang.none, vec![]))
952}
953
954fn enum_len(cx: &mut dyn Context, enum_def: DefId, args: &[Value]) -> RunResult<Value> {
955 if !args.is_empty() {
956 return Err(RuntimeError::new("`len` takes no arguments"));
957 }
958 Ok(Value::int(cx.enum_variants(enum_def).len() as i64))
959}
960
961fn enum_values(cx: &mut dyn Context, enum_def: DefId, args: &[Value]) -> RunResult<Value> {
962 if !args.is_empty() {
963 return Err(RuntimeError::new("`values` takes no arguments"));
964 }
965 let values: Vec<Value> = cx
966 .enum_variants(enum_def)
967 .into_iter()
968 .filter(|(_, _, has_fields)| !has_fields)
969 .map(|(_, vdef, _)| Value::adt(vdef, vec![]))
970 .collect();
971 Ok(Value::list(values))
972}