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::{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
55pub trait Context: ConvertCx {
57 fn import(&mut self, path: &str) -> RunResult<Value>;
60 fn display(&self, value: &Value) -> String;
62 fn type_args(&self) -> &[TypeRef];
65 fn print(&mut self, text: &str) -> RunResult<()>;
67 fn call(&mut self, callee: &Value, args: &[Value]) -> RunResult<Value>;
69 fn spawn(&mut self, f: Value) -> RunResult<JoinHandle<RunResult<Value>>>;
72
73 fn describe_type(&self, value: &Value) -> String;
77 fn adt_info(&self, def: DefId) -> Option<AdtInfo>;
79 fn methods(&self, value: &Value) -> Vec<String>;
81 fn field(&mut self, value: &Value, name: &str) -> RunResult<Value>;
83 fn set_field(&mut self, value: &Value, name: &str, new: Value) -> RunResult<Value>;
85 fn call_method(&mut self, receiver: Value, name: &str, args: &[Value]) -> RunResult<Value>;
87
88 fn try_cast(&self, value: &Value, target: DefId) -> RunResult<Value>;
92
93 fn repr_value(&self, def: DefId) -> Option<i64>;
95
96 fn fn_info(&self, value: &Value) -> Option<crate::FnInfo>;
98
99 fn shared_handle(&self) -> Option<Box<dyn std::any::Any + Send + Sync>> {
103 None
104 }
105
106 fn def_name(&self, _def: DefId) -> Option<String> {
109 None
110 }
111
112 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#[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 pub signature: Option<Signature>,
132 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 hooks: Option<TypeHooks>,
151 explicit_variants: Option<Vec<NativeVariantDecl>>,
154}
155
156type ModuleInit = Box<dyn FnOnce(&mut ModuleBuilder<'_>) + Send + Sync>;
158
159struct ModuleData {
160 name: String,
161 init: Option<ModuleInit>,
163 children: Vec<usize>,
164 functions: Vec<NativeFnDecl>,
165 types: Vec<NativeTypeId>,
166}
167
168#[derive(Default)]
175pub struct Registry {
176 inner: RwLock<Inner>,
177}
178
179#[derive(Default)]
180struct Inner {
181 fns: Vec<Arc<NativeFn>>,
182 builtin_methods: HashMap<(BuiltinType, String), NativeFnId>,
184 types: Vec<NativeType>,
185 modules: Vec<ModuleData>,
186 roots: Vec<usize>,
188 converters: Vec<(&'static Shape, Converter)>,
190}
191
192#[derive(Debug, Clone, PartialEq, Eq)]
194pub struct RecordCtor {
195 pub kind: NativeVariantKind,
196 pub fields: Vec<Symbol>,
198}
199
200fn 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
223pub 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 pub fn module(&self, path: &str) -> ModuleBuilder<'_> {
241 let module = self.write().module_at(path);
242 ModuleBuilder::new(self, module)
243 }
244
245 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 pub fn builtin(&self, ty: BuiltinType) -> BuiltinBuilder<'_> {
260 BuiltinBuilder::new(self, ty)
261 }
262
263 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 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 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 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 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 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 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 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 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 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 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 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 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 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 pub fn converter(&self, shape: &'static Shape, convert: Converter) {
470 self.write().converters.push((shape, convert));
471 }
472
473 pub fn has_converter(&self, shape: &'static Shape) -> bool {
475 self.converter_of(shape).is_some()
476 }
477
478 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 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 pub fn has_shape(&self, shape: &'static Shape) -> bool {
512 self.read().types.iter().any(|ty| ty.shape == shape)
513 }
514
515 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 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 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 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 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 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 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 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 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 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 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}