1mod 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
60pub trait Context: ConvertCx {
62 fn import(&mut self, path: &str) -> RunResult<Value>;
65 fn display(&self, value: &Value) -> String;
67 fn type_args(&self) -> &[TypeRef];
70 fn print(&mut self, text: &str) -> RunResult<()>;
72 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 fn call(&mut self, callee: &Value, args: &[Value]) -> RunResult<Value>;
82 fn spawn(&mut self, f: Value) -> RunResult<JoinHandle<RunResult<Value>>>;
85
86 fn describe_type(&self, value: &Value) -> String;
90 fn describe_span(&self, span: Span) -> String;
94 fn type_of(&self, value: &Value) -> RtType;
97 fn adt_info(&self, def: DefId) -> Option<AdtInfo>;
99 fn methods(&self, value: &Value) -> Vec<String>;
101 fn field(&mut self, value: &Value, name: &str) -> RunResult<Value>;
103 fn set_field(&mut self, value: &Value, name: &str, new: Value) -> RunResult<Value>;
105 fn call_method(&mut self, receiver: Value, name: &str, args: &[Value]) -> RunResult<Value>;
107
108 fn try_cast(&self, value: &Value, target: DefId) -> RunResult<Value>;
112
113 fn repr_value(&self, def: DefId) -> Option<i64>;
115
116 fn fn_info(&self, value: &Value) -> Option<crate::FnInfo>;
118
119 fn shared_handle(&self) -> Option<Box<dyn std::any::Any + Send + Sync>> {
123 None
124 }
125
126 fn def_name(&self, _def: DefId) -> Option<String> {
129 None
130 }
131
132 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#[derive(Debug, Clone)]
142pub struct Signature {
143 pub params: Vec<&'static Shape>,
144 pub ret: &'static Shape,
145 pub param_names: Vec<String>,
146 pub param_types: Vec<TypeDesc>,
148 pub ret_type: TypeDesc,
150 pub required: usize,
152}
153
154pub struct NativeFn {
155 pub name: String,
156 pub signature: Option<Signature>,
158 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 hooks: Option<TypeHooks>,
177 explicit_variants: Option<Vec<NativeVariantDecl>>,
180}
181
182type ModuleInit = Box<dyn FnOnce(&mut ModuleBuilder<'_>) + Send + Sync>;
184
185struct ModuleData {
186 name: String,
187 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#[derive(Default)]
202pub struct Registry {
203 inner: RwLock<Inner>,
204}
205
206#[derive(Default)]
207struct Inner {
208 fns: Vec<Arc<NativeFn>>,
209 builtin_methods: HashMap<(BuiltinType, String), NativeFnId>,
211 types: Vec<NativeType>,
212 modules: Vec<ModuleData>,
213 roots: Vec<usize>,
215 converters: Vec<(&'static Shape, Converter)>,
217}
218
219#[derive(Debug, Clone, PartialEq, Eq)]
221pub struct RecordCtor {
222 pub kind: NativeVariantKind,
223 pub fields: Vec<Symbol>,
225}
226
227fn 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
250pub 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 pub fn module(&self, path: &str) -> ModuleBuilder<'_> {
268 let module = self.write().module_at(path);
269 ModuleBuilder::new(self, module)
270 }
271
272 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 pub fn builtin(&self, ty: BuiltinType) -> BuiltinBuilder<'_> {
287 BuiltinBuilder::new(self, ty)
288 }
289
290 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 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 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 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 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 pub fn type_shape(&self, id: NativeTypeId) -> &'static Shape {
357 self.read().types[id.0 as usize].shape
358 }
359
360 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 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 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 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 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 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 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 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 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 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 pub fn converter(&self, shape: &'static Shape, convert: Converter) {
545 self.write().converters.push((shape, convert));
546 }
547
548 pub fn has_converter(&self, shape: &'static Shape) -> bool {
550 self.converter_of(shape).is_some()
551 }
552
553 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 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 pub fn has_shape(&self, shape: &'static Shape) -> bool {
587 self.read().types.iter().any(|ty| ty.shape == shape)
588 }
589
590 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 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 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 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 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 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 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 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 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 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 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 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}