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, RtType, macros::MacroExpander,
42};
43
44use xur_span::{Span, Symbol};
45
46use crate::convert::{Builder, ConvertCx};
47use crate::value::NativeObject;
48use crate::{AdtInfo, BuiltinType, RunResult, RuntimeError, TypeRef, Value};
49
50pub use builder::{
51 BuiltinBuilder, ElemHint, ModuleBuilder, ReturnHint, Returns, TypeBuilder, XurType,
52};
53pub use into_native::{
54 BuiltinRecv, BuiltinRecvMut, IntoBuiltinMethod, IntoBuiltinMethodMut, IntoNativeFn,
55 IntoNativeMethod, IntoNativeMethodMut,
56};
57
58use hooks::TypeHooks;
59
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}
147
148pub struct NativeFn {
149 pub name: String,
150 pub signature: Option<Signature>,
152 pub return_hint: Option<ReturnHint>,
154 pub param_names: Vec<String>,
155 call: Box<CallFn>,
156}
157
158impl NativeFn {
159 pub fn call(&self, cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
160 (self.call)(cx, args)
161 }
162}
163
164pub(super) struct NativeType {
165 name: String,
166 shape: &'static Shape,
167 functions: Vec<NativeFnDecl>,
168 hooks: Option<TypeHooks>,
171 explicit_variants: Option<Vec<NativeVariantDecl>>,
174}
175
176type ModuleInit = Box<dyn FnOnce(&mut ModuleBuilder<'_>) + Send + Sync>;
178
179struct ModuleData {
180 name: String,
181 init: Option<ModuleInit>,
183 children: Vec<usize>,
184 functions: Vec<NativeFnDecl>,
185 types: Vec<NativeTypeId>,
186 macros: HashMap<String, Arc<dyn MacroExpander>>,
187}
188
189#[derive(Default)]
196pub struct Registry {
197 inner: RwLock<Inner>,
198}
199
200#[derive(Default)]
201struct Inner {
202 fns: Vec<Arc<NativeFn>>,
203 builtin_methods: HashMap<(BuiltinType, String), NativeFnId>,
205 types: Vec<NativeType>,
206 modules: Vec<ModuleData>,
207 roots: Vec<usize>,
209 converters: Vec<(&'static Shape, Converter)>,
211}
212
213#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct RecordCtor {
216 pub kind: NativeVariantKind,
217 pub fields: Vec<Symbol>,
219}
220
221fn variant_decls(shape: &'static Shape) -> Vec<NativeVariantDecl> {
223 let Type::User(UserType::Enum(en)) = shape.ty else {
224 return Vec::new();
225 };
226 en.variants
227 .iter()
228 .map(|variant| NativeVariantDecl {
229 name: variant.name.to_owned(),
230 kind: variant_kind(variant.data.kind),
231 repr_value: None,
232 })
233 .collect()
234}
235
236fn variant_kind(kind: StructKind) -> NativeVariantKind {
237 match kind {
238 StructKind::Unit => NativeVariantKind::Unit,
239 StructKind::Tuple | StructKind::TupleStruct => NativeVariantKind::Tuple,
240 StructKind::Struct => NativeVariantKind::Named,
241 }
242}
243
244pub type Converter = fn(&dyn ConvertCx, Peek<'_, 'static>) -> RunResult<Value>;
246
247impl Registry {
248 pub fn new() -> Self {
249 Self::default()
250 }
251
252 fn read(&self) -> RwLockReadGuard<'_, Inner> {
253 self.inner.read().unwrap_or_else(PoisonError::into_inner)
254 }
255
256 fn write(&self) -> RwLockWriteGuard<'_, Inner> {
257 self.inner.write().unwrap_or_else(PoisonError::into_inner)
258 }
259
260 pub fn module(&self, path: &str) -> ModuleBuilder<'_> {
262 let module = self.write().module_at(path);
263 ModuleBuilder::new(self, module)
264 }
265
266 pub fn lazy_module(
270 &self,
271 path: &str,
272 init: impl FnOnce(&mut ModuleBuilder<'_>) + Send + Sync + 'static,
273 ) {
274 let mut inner = self.write();
275 let module = inner.module_at(path);
276 inner.modules[module].init = Some(Box::new(init));
277 }
278
279 pub fn builtin(&self, ty: BuiltinType) -> BuiltinBuilder<'_> {
281 BuiltinBuilder::new(self, ty)
282 }
283
284 pub fn builtin_method(&self, ty: BuiltinType, name: &str) -> Option<NativeFnId> {
286 self.read()
287 .builtin_methods
288 .get(&(ty, name.to_owned()))
289 .copied()
290 }
291
292 pub fn type_function(&self, ty: NativeTypeId, name: &str) -> Option<NativeFnId> {
294 let inner = self.read();
295 let functions = &inner.types[ty.0 as usize].functions;
296 functions.iter().find(|f| f.name == name).map(|f| f.id)
297 }
298
299 pub fn type_methods(&self, ty: NativeTypeId) -> Vec<String> {
302 let inner = self.read();
303 let native = &inner.types[ty.0 as usize];
304 native
305 .functions
306 .iter()
307 .filter(|decl| match &inner.fns[decl.id.0 as usize].signature {
308 Some(signature) => signature.params.first() == Some(&native.shape),
309 None => true,
310 })
311 .map(|decl| decl.name.clone())
312 .collect()
313 }
314
315 pub fn builtin_methods(&self, ty: BuiltinType) -> Vec<String> {
317 let mut names: Vec<_> = self
318 .read()
319 .builtin_methods
320 .keys()
321 .filter(|(builtin, _)| *builtin == ty)
322 .map(|(_, name)| name.clone())
323 .collect();
324 names.sort();
325 names
326 }
327
328 pub fn type_fields(&self, ty: NativeTypeId) -> Vec<String> {
330 let shape = self.read().types[ty.0 as usize].shape;
331 match shape.ty {
332 Type::User(UserType::Struct(StructType { fields, .. })) => {
333 fields.iter().map(|field| field.name.to_owned()).collect()
334 }
335 _ => Vec::new(),
336 }
337 }
338
339 pub fn function(&self, id: NativeFnId) -> Arc<NativeFn> {
340 Arc::clone(&self.read().fns[id.0 as usize])
341 }
342
343 pub fn type_name(&self, id: NativeTypeId) -> String {
344 self.read().types[id.0 as usize].name.clone()
345 }
346
347 pub fn type_id_by_name(&self, name: &str) -> Option<NativeTypeId> {
349 let inner = self.read();
350 inner
351 .types
352 .iter()
353 .enumerate()
354 .find_map(|(i, ty)| (ty.name == name).then_some(NativeTypeId(i as u32)))
355 }
356
357 pub fn shape_xur_name(&self, shape: &'static Shape) -> String {
361 if let Some(id) = self.type_of_shape(shape) {
362 return self.type_name(id);
363 }
364 let name = shape.type_name().to_string();
365 match name.as_str() {
366 "String" | "&str" | "alloc::string::String" => "str".into(),
367 "bool" => "bool".into(),
368 "i64" => "i64".into(),
369 "f64" => "f64".into(),
370 "i32" => "i32".into(),
371 "u32" => "u32".into(),
372 "u64" => "u64".into(),
373 "usize" => "usize".into(),
374 "()" => "()".into(),
375 "Vec<u8>" | "alloc::vec::Vec<u8>" => "bytes".into(),
376 _ if name.starts_with("Vec<") || name == "Vec" => "list".into(),
377 _ => name.split('<').next().unwrap_or(&name).into(),
378 }
379 }
380
381 pub fn native_return_shape(&self, id: NativeFnId) -> Option<&'static Shape> {
385 let f = self.function(id);
386 if let Some(sig) = &f.signature {
387 return Some(sig.ret);
388 }
389 match f.return_hint {
390 Some(ReturnHint::Shape(s)) => Some(s),
391 _ => None,
392 }
393 }
394
395 pub fn native_return_name(&self, id: NativeFnId) -> Option<String> {
397 let f = self.function(id);
398 if let Some(sig) = &f.signature {
399 return Some(self.shape_xur_name(sig.ret));
400 }
401 match f.return_hint {
402 Some(ReturnHint::Shape(s)) => Some(self.shape_xur_name(s)),
403 Some(ReturnHint::Xur(xur)) => Some(self.xur_type_name(xur)),
404 None => None,
405 }
406 }
407
408 fn xur_type_name(&self, ty: XurType) -> String {
409 match ty {
410 XurType::Ptr(Some(inner)) => format!("*{}", self.shape_xur_name(inner)),
411 XurType::Ptr(None) => "ptr".into(),
412 XurType::List(None) => "list".into(),
413 XurType::List(Some(hint)) => format!("list<{}>", self.elem_hint_name(hint)),
414 XurType::Map(None, None) => "map".into(),
415 XurType::Map(Some(k), Some(v)) => {
416 format!(
417 "map<{}, {}>",
418 self.shape_xur_name(k),
419 self.shape_xur_name(v)
420 )
421 }
422 XurType::Map(Some(k), None) => format!("map<{}, _>", self.shape_xur_name(k)),
423 XurType::Map(None, Some(v)) => format!("map<_, {}>", self.shape_xur_name(v)),
424 XurType::Named(name, []) => (*name).into(),
425 XurType::Named(name, params) => {
426 let args: Vec<_> = params.iter().map(|h| self.elem_hint_name(*h)).collect();
427 format!("{name}<{}>", args.join(", "))
428 }
429 XurType::Record => "record".into(),
430 XurType::Module => "module".into(),
431 XurType::Unit => "()".into(),
432 }
433 }
434
435 fn elem_hint_name(&self, hint: ElemHint) -> String {
437 match hint {
438 ElemHint::Shape(s) => self.shape_xur_name(s),
439 ElemHint::Name(n) => n.into(),
440 ElemHint::Param(n) => format!("T{n}"),
441 }
442 }
443
444 pub(super) fn set_return_hint(&self, id: NativeFnId, hint: ReturnHint) {
446 let mut inner = self.write();
447 let slot = &mut inner.fns[id.0 as usize];
448 Arc::get_mut(slot)
449 .expect("return hint set during registration")
450 .return_hint = Some(hint);
451 }
452
453 pub fn shape_type_param(&self, shape: &'static Shape, index: usize) -> Option<String> {
457 if let Ok(r) = shape.def.into_result() {
458 return match index {
459 0 => Some(self.shape_xur_name(r.t())),
460 1 => Some(self.shape_xur_name(r.e())),
461 _ => None,
462 };
463 }
464 if let Ok(o) = shape.def.into_option() {
465 return (index == 0).then(|| self.shape_xur_name(o.t()));
466 }
467 None
468 }
469
470 pub fn type_of_shape(&self, shape: &'static Shape) -> Option<NativeTypeId> {
472 let index = self
473 .read()
474 .types
475 .iter()
476 .position(|ty| ty.shape == shape && ty.hooks.is_some())?;
477 Some(NativeTypeId(index as u32))
478 }
479
480 pub fn record_type_of_shape(&self, shape: &'static Shape) -> Option<NativeTypeId> {
483 let index = self
484 .read()
485 .types
486 .iter()
487 .position(|ty| ty.shape == shape && ty.hooks.is_none())?;
488 Some(NativeTypeId(index as u32))
489 }
490
491 pub fn converter(&self, shape: &'static Shape, convert: Converter) {
495 self.write().converters.push((shape, convert));
496 }
497
498 pub fn has_converter(&self, shape: &'static Shape) -> bool {
500 self.converter_of(shape).is_some()
501 }
502
503 pub(crate) fn converter_of(&self, shape: &'static Shape) -> Option<Converter> {
505 let inner = self.read();
506 let (_, convert) = inner.converters.iter().find(|(s, _)| *s == shape)?;
507 Some(*convert)
508 }
509
510 pub fn record_ctor(&self, ty: NativeTypeId, variant: Option<Symbol>) -> Option<RecordCtor> {
514 let shape = self.read().types[ty.0 as usize].shape;
515 let data = match (shape.ty, variant) {
516 (Type::User(UserType::Struct(st)), None) => st,
517 (Type::User(UserType::Enum(en)), Some(variant)) => {
518 en.variants
519 .iter()
520 .find(|v| v.name == variant.as_str())?
521 .data
522 }
523 _ => return None,
524 };
525 Some(RecordCtor {
526 kind: variant_kind(data.kind),
527 fields: data
528 .fields
529 .iter()
530 .map(|field| Symbol::intern(field.name))
531 .collect(),
532 })
533 }
534
535 pub fn has_shape(&self, shape: &'static Shape) -> bool {
537 self.read().types.iter().any(|ty| ty.shape == shape)
538 }
539
540 pub fn field(
542 &self,
543 cx: &dyn ConvertCx,
544 object: &NativeObject,
545 name: &str,
546 ) -> Option<RunResult<Value>> {
547 let field = self.hooks(object.ty).field;
548 object.with_any(|value| field(cx, value, name))
549 }
550
551 pub fn display(&self, object: &NativeObject) -> String {
556 object
557 .with_any(self.hooks(object.ty).display)
558 .unwrap_or_else(|| format!("<{}>", self.type_name(object.ty)))
559 }
560
561 pub fn native_eq(&self, a: &NativeObject, b: &NativeObject) -> bool {
563 if a.ty != b.ty {
564 return false;
565 }
566 if std::ptr::eq(a, b) {
567 return true;
568 }
569 let eq = self.hooks(a.ty).eq;
570 a.with_any(|a| b.with_any(|b| eq(a, b)))
571 }
572
573 pub fn borrowing_object<T: Facet<'static> + Send + 'static>(
578 &self,
579 value: T,
580 keep_alive: Arc<dyn std::any::Any + Send + Sync>,
581 ) -> RunResult<Value> {
582 let ty = self
583 .type_of_shape(T::SHAPE)
584 .ok_or_else(|| RuntimeError::new(format!("`{}` is not a registered type", T::SHAPE)))?;
585 let object = NativeObject::borrowing(ty, Box::new(value), keep_alive);
586 Ok(Value::Native(object.into()))
587 }
588
589 pub(crate) fn object_from_peek(
591 &self,
592 ty: NativeTypeId,
593 peek: Peek<'_, 'static>,
594 ) -> Option<NativeObject> {
595 let value = (self.hooks(ty).clone_peek)(peek)?;
596 Some(NativeObject::new(ty, value))
597 }
598
599 pub(crate) fn set_object(&self, partial: Builder, object: &NativeObject) -> RunResult<Builder> {
601 let set = self.hooks(object.ty).set;
602 object.with_any(|value| set(partial, value))
603 }
604
605 fn hooks(&self, ty: NativeTypeId) -> TypeHooks {
608 self.read().types[ty.0 as usize]
609 .hooks
610 .expect("native objects only exist for types registered with their Rust type")
611 }
612
613 pub fn decls(&self) -> Vec<NativeModule> {
615 let inner = self.read();
616 inner
617 .roots
618 .iter()
619 .map(|&module| inner.decl(module))
620 .collect()
621 }
622
623 pub fn expand(&self, path: &[String]) -> NativeModule {
626 let (module, init) = {
627 let mut inner = self.write();
628 let module = inner
629 .find(path)
630 .unwrap_or_else(|| panic!("no native module `{}`", path.join("::")));
631 (module, inner.modules[module].init.take())
632 };
633 if let Some(init) = init {
635 init(&mut ModuleBuilder::new(self, module));
636 }
637 self.read().decl(module)
638 }
639
640 pub fn add_fn(
641 &self,
642 name: &str,
643 signature: Option<Signature>,
644 param_names: Vec<String>,
645 call: Box<CallFn>,
646 ) -> NativeFnDecl {
647 self.write().add_fn(name, signature, param_names, call)
648 }
649
650 fn with_inner<R>(&self, f: impl FnOnce(&mut Inner) -> R) -> R {
651 f(&mut self.write())
652 }
653}
654
655impl Inner {
656 fn module_at(&mut self, path: &str) -> usize {
657 let mut names = path.split("::");
658 let root = names.next().expect("split yields at least one item");
659 let mut module = self.child(None, root);
660 for name in names {
661 module = self.child(Some(module), name);
662 }
663 module
664 }
665
666 fn find(&self, path: &[String]) -> Option<usize> {
667 let mut module: Option<usize> = None;
668 for name in path {
669 let siblings = match module {
670 Some(parent) => &self.modules[parent].children,
671 None => &self.roots,
672 };
673 module = Some(*siblings.iter().find(|&&m| self.modules[m].name == *name)?);
674 }
675 module
676 }
677
678 fn decl(&self, module: usize) -> NativeModule {
679 let data = &self.modules[module];
680 if data.init.is_some() {
681 return NativeModule {
682 name: data.name.clone(),
683 lazy: true,
684 ..NativeModule::default()
685 };
686 }
687 NativeModule {
688 name: data.name.clone(),
689 lazy: false,
690 functions: data.functions.clone(),
691 types: data
692 .types
693 .iter()
694 .map(|&id| {
695 let ty = &self.types[id.0 as usize];
696 NativeTypeDecl {
697 name: ty.name.clone(),
698 id,
699 functions: ty.functions.clone(),
700 variants: if let Some(ref v) = ty.explicit_variants {
701 v.clone()
702 } else {
703 variant_decls(ty.shape)
704 },
705 }
706 })
707 .collect(),
708 modules: data
709 .children
710 .iter()
711 .map(|&child| self.decl(child))
712 .collect(),
713 }
714 }
715
716 fn child(&mut self, parent: Option<usize>, name: &str) -> usize {
718 let siblings = match parent {
719 Some(parent) => &self.modules[parent].children,
720 None => &self.roots,
721 };
722 if let Some(&existing) = siblings.iter().find(|&&m| self.modules[m].name == name) {
723 return existing;
724 }
725 let module = self.modules.len();
726 self.modules.push(ModuleData {
727 name: name.to_owned(),
728 init: None,
729 children: Vec::new(),
730 functions: Vec::new(),
731 types: Vec::new(),
732 macros: HashMap::new(),
733 });
734 match parent {
735 Some(parent) => self.modules[parent].children.push(module),
736 None => self.roots.push(module),
737 }
738 module
739 }
740
741 fn add_fn(
742 &mut self,
743 name: &str,
744 signature: Option<Signature>,
745 param_names: Vec<String>,
746 call: Box<CallFn>,
747 ) -> NativeFnDecl {
748 let id = NativeFnId(self.fns.len() as u32);
749 self.fns.push(Arc::new(NativeFn {
750 name: name.to_owned(),
751 signature,
752 return_hint: None,
753 param_names: param_names.clone(),
754 call,
755 }));
756 NativeFnDecl {
757 name: name.to_owned(),
758 id,
759 param_names,
760 }
761 }
762}
763
764impl NativeProvider for Registry {
765 fn modules(&self) -> Vec<NativeModule> {
766 self.decls()
767 }
768
769 fn expand(&self, path: &[String]) -> NativeModule {
770 Registry::expand(self, path)
771 }
772
773 fn macro_expander(&self, path: &[&str]) -> Option<Arc<dyn MacroExpander>> {
774 if path.is_empty() {
775 return None;
776 }
777 let (module_path, macro_name) = path.split_at(path.len() - 1);
778 let macro_name = macro_name[0];
779
780 let mut module: Option<usize> = None;
784 for name in module_path {
785 let idx = {
786 let inner = self.read();
787 let siblings = match module {
788 Some(parent) => &inner.modules[parent].children,
789 None => &inner.roots,
790 };
791 siblings
792 .iter()
793 .find(|&&m| inner.modules[m].name == *name)
794 .copied()?
795 };
796
797 let init = self.write().modules[idx].init.take();
798 if let Some(init) = init {
799 init(&mut ModuleBuilder::new(self, idx));
800 }
801 module = Some(idx);
802 }
803
804 let parent = module?;
805 self.read().modules[parent].macros.get(macro_name).cloned()
806 }
807
808 fn register_enum_builtins(&self, enum_def: DefId) -> Vec<NativeFnDecl> {
809 vec![
810 self.add_fn(
811 "from_str",
812 None,
813 vec!["name".into()],
814 Box::new({
815 let def = enum_def;
816 move |cx, args| enum_from_str(cx, def, args)
817 }),
818 ),
819 self.add_fn(
820 "len",
821 None,
822 Vec::new(),
823 Box::new({
824 let def = enum_def;
825 move |cx, args| enum_len(cx, def, args)
826 }),
827 ),
828 self.add_fn(
829 "values",
830 None,
831 Vec::new(),
832 Box::new({
833 let def = enum_def;
834 move |cx, args| enum_values(cx, def, args)
835 }),
836 ),
837 ]
838 }
839}
840
841fn enum_from_str(cx: &mut dyn Context, enum_def: DefId, args: &[Value]) -> RunResult<Value> {
842 let [Value::Str(name)] = args else {
843 return Err(RuntimeError::new("`from_str` takes a string"));
844 };
845 let lang = cx.lang();
846 for (vname, vdef, has_fields) in cx.enum_variants(enum_def) {
847 if vname == name.as_ref() && !has_fields {
848 return Ok(Value::adt(lang.some, vec![Value::adt(vdef, vec![])]));
849 }
850 }
851 Ok(Value::adt(lang.none, vec![]))
852}
853
854fn enum_len(cx: &mut dyn Context, enum_def: DefId, args: &[Value]) -> RunResult<Value> {
855 if !args.is_empty() {
856 return Err(RuntimeError::new("`len` takes no arguments"));
857 }
858 Ok(Value::int(cx.enum_variants(enum_def).len() as i64))
859}
860
861fn enum_values(cx: &mut dyn Context, enum_def: DefId, args: &[Value]) -> RunResult<Value> {
862 if !args.is_empty() {
863 return Err(RuntimeError::new("`values` takes no arguments"));
864 }
865 let values: Vec<Value> = cx
866 .enum_variants(enum_def)
867 .into_iter()
868 .filter(|(_, _, has_fields)| !has_fields)
869 .map(|(_, vdef, _)| Value::adt(vdef, vec![]))
870 .collect();
871 Ok(Value::list(values))
872}