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, ModuleBuilder, TypeBuilder};
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 fn_info(&self, value: &Value) -> Option<crate::FnInfo>;
95}
96
97pub(crate) type CallFn = dyn Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync;
98
99#[derive(Debug, Clone)]
101pub struct Signature {
102 pub params: Vec<&'static Shape>,
103 pub ret: &'static Shape,
104 pub param_names: Vec<String>,
105}
106
107pub struct NativeFn {
108 pub name: String,
109 pub signature: Option<Signature>,
111 pub param_names: Vec<String>,
112 call: Box<CallFn>,
113}
114
115impl NativeFn {
116 pub fn call(&self, cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
117 (self.call)(cx, args)
118 }
119}
120
121pub(super) struct NativeType {
122 name: String,
123 shape: &'static Shape,
124 functions: Vec<NativeFnDecl>,
125 hooks: Option<TypeHooks>,
128 explicit_variants: Option<Vec<NativeVariantDecl>>,
131}
132
133type ModuleInit = Box<dyn FnOnce(&mut ModuleBuilder<'_>) + Send + Sync>;
135
136struct ModuleData {
137 name: String,
138 init: Option<ModuleInit>,
140 children: Vec<usize>,
141 functions: Vec<NativeFnDecl>,
142 types: Vec<NativeTypeId>,
143}
144
145#[derive(Default)]
152pub struct Registry {
153 inner: RwLock<Inner>,
154}
155
156#[derive(Default)]
157struct Inner {
158 fns: Vec<Arc<NativeFn>>,
159 builtin_methods: HashMap<(BuiltinType, String), NativeFnId>,
161 types: Vec<NativeType>,
162 modules: Vec<ModuleData>,
163 roots: Vec<usize>,
165 converters: Vec<(&'static Shape, Converter)>,
167}
168
169#[derive(Debug, Clone, PartialEq, Eq)]
171pub struct RecordCtor {
172 pub kind: NativeVariantKind,
173 pub fields: Vec<Symbol>,
175}
176
177fn variant_decls(shape: &'static Shape) -> Vec<NativeVariantDecl> {
179 let Type::User(UserType::Enum(en)) = shape.ty else {
180 return Vec::new();
181 };
182 en.variants
183 .iter()
184 .map(|variant| NativeVariantDecl {
185 name: variant.name.to_owned(),
186 kind: variant_kind(variant.data.kind),
187 repr_value: None,
188 })
189 .collect()
190}
191
192fn variant_kind(kind: StructKind) -> NativeVariantKind {
193 match kind {
194 StructKind::Unit => NativeVariantKind::Unit,
195 StructKind::Tuple | StructKind::TupleStruct => NativeVariantKind::Tuple,
196 StructKind::Struct => NativeVariantKind::Named,
197 }
198}
199
200pub type Converter = fn(&dyn ConvertCx, Peek<'_, 'static>) -> RunResult<Value>;
202
203impl Registry {
204 pub fn new() -> Self {
205 Self::default()
206 }
207
208 fn read(&self) -> RwLockReadGuard<'_, Inner> {
209 self.inner.read().unwrap_or_else(PoisonError::into_inner)
210 }
211
212 fn write(&self) -> RwLockWriteGuard<'_, Inner> {
213 self.inner.write().unwrap_or_else(PoisonError::into_inner)
214 }
215
216 pub fn module(&self, path: &str) -> ModuleBuilder<'_> {
218 let module = self.write().module_at(path);
219 ModuleBuilder::new(self, module)
220 }
221
222 pub fn lazy_module(
226 &self,
227 path: &str,
228 init: impl FnOnce(&mut ModuleBuilder<'_>) + Send + Sync + 'static,
229 ) {
230 let mut inner = self.write();
231 let module = inner.module_at(path);
232 inner.modules[module].init = Some(Box::new(init));
233 }
234
235 pub fn builtin(&self, ty: BuiltinType) -> BuiltinBuilder<'_> {
237 BuiltinBuilder::new(self, ty)
238 }
239
240 pub fn builtin_method(&self, ty: BuiltinType, name: &str) -> Option<NativeFnId> {
242 self.read()
243 .builtin_methods
244 .get(&(ty, name.to_owned()))
245 .copied()
246 }
247
248 pub fn type_function(&self, ty: NativeTypeId, name: &str) -> Option<NativeFnId> {
250 let inner = self.read();
251 let functions = &inner.types[ty.0 as usize].functions;
252 functions.iter().find(|f| f.name == name).map(|f| f.id)
253 }
254
255 pub fn type_methods(&self, ty: NativeTypeId) -> Vec<String> {
258 let inner = self.read();
259 let native = &inner.types[ty.0 as usize];
260 native
261 .functions
262 .iter()
263 .filter(|decl| match &inner.fns[decl.id.0 as usize].signature {
264 Some(signature) => signature.params.first() == Some(&native.shape),
265 None => true,
266 })
267 .map(|decl| decl.name.clone())
268 .collect()
269 }
270
271 pub fn builtin_methods(&self, ty: BuiltinType) -> Vec<String> {
273 let mut names: Vec<_> = self
274 .read()
275 .builtin_methods
276 .keys()
277 .filter(|(builtin, _)| *builtin == ty)
278 .map(|(_, name)| name.clone())
279 .collect();
280 names.sort();
281 names
282 }
283
284 pub fn type_fields(&self, ty: NativeTypeId) -> Vec<String> {
286 let shape = self.read().types[ty.0 as usize].shape;
287 match shape.ty {
288 Type::User(UserType::Struct(StructType { fields, .. })) => {
289 fields.iter().map(|field| field.name.to_owned()).collect()
290 }
291 _ => Vec::new(),
292 }
293 }
294
295 pub fn function(&self, id: NativeFnId) -> Arc<NativeFn> {
296 Arc::clone(&self.read().fns[id.0 as usize])
297 }
298
299 pub fn type_name(&self, id: NativeTypeId) -> String {
300 self.read().types[id.0 as usize].name.clone()
301 }
302
303 pub fn type_id_by_name(&self, name: &str) -> Option<NativeTypeId> {
305 let inner = self.read();
306 inner.types.iter().enumerate().find_map(|(i, ty)| {
307 (ty.name == name).then_some(NativeTypeId(i as u32))
308 })
309 }
310
311 pub fn shape_xur_name(&self, shape: &'static Shape) -> String {
315 if let Some(id) = self.type_of_shape(shape) {
316 return self.type_name(id);
317 }
318 let name = shape.type_name().to_string();
319 match name.as_str() {
320 "String" | "&str" | "alloc::string::String" => "str".into(),
321 "bool" => "bool".into(),
322 "i64" => "i64".into(),
323 "f64" => "f64".into(),
324 "i32" => "i32".into(),
325 "u32" => "u32".into(),
326 "u64" => "u64".into(),
327 "usize" => "usize".into(),
328 "()" => "()".into(),
329 "Vec<u8>" | "alloc::vec::Vec<u8>" => "bytes".into(),
330 _ if name.starts_with("Vec<") || name == "Vec" => "list".into(),
331 _ => {
332 name.split('<').next().unwrap_or(&name).into()
333 }
334 }
335 }
336
337 pub fn native_return_shape(&self, id: NativeFnId) -> Option<&'static Shape> {
339 self.function(id).signature.as_ref().map(|s| s.ret)
340 }
341
342 pub fn shape_type_param(&self, shape: &'static Shape, index: usize) -> Option<String> {
346 if let Ok(r) = shape.def.into_result() {
347 return match index {
348 0 => Some(self.shape_xur_name(r.t())),
349 1 => Some(self.shape_xur_name(r.e())),
350 _ => None,
351 };
352 }
353 if let Ok(o) = shape.def.into_option() {
354 return (index == 0).then(|| self.shape_xur_name(o.t()));
355 }
356 None
357 }
358
359 pub fn type_of_shape(&self, shape: &'static Shape) -> Option<NativeTypeId> {
361 let index = self
362 .read()
363 .types
364 .iter()
365 .position(|ty| ty.shape == shape && ty.hooks.is_some())?;
366 Some(NativeTypeId(index as u32))
367 }
368
369 pub fn record_type_of_shape(&self, shape: &'static Shape) -> Option<NativeTypeId> {
372 let index = self
373 .read()
374 .types
375 .iter()
376 .position(|ty| ty.shape == shape && ty.hooks.is_none())?;
377 Some(NativeTypeId(index as u32))
378 }
379
380 pub fn converter(&self, shape: &'static Shape, convert: Converter) {
384 self.write().converters.push((shape, convert));
385 }
386
387 pub fn has_converter(&self, shape: &'static Shape) -> bool {
389 self.converter_of(shape).is_some()
390 }
391
392 pub(crate) fn converter_of(&self, shape: &'static Shape) -> Option<Converter> {
394 let inner = self.read();
395 let (_, convert) = inner.converters.iter().find(|(s, _)| *s == shape)?;
396 Some(*convert)
397 }
398
399 pub fn record_ctor(&self, ty: NativeTypeId, variant: Option<Symbol>) -> Option<RecordCtor> {
403 let shape = self.read().types[ty.0 as usize].shape;
404 let data = match (shape.ty, variant) {
405 (Type::User(UserType::Struct(st)), None) => st,
406 (Type::User(UserType::Enum(en)), Some(variant)) => {
407 en.variants
408 .iter()
409 .find(|v| v.name == variant.as_str())?
410 .data
411 }
412 _ => return None,
413 };
414 Some(RecordCtor {
415 kind: variant_kind(data.kind),
416 fields: data
417 .fields
418 .iter()
419 .map(|field| Symbol::intern(field.name))
420 .collect(),
421 })
422 }
423
424 pub fn has_shape(&self, shape: &'static Shape) -> bool {
426 self.read().types.iter().any(|ty| ty.shape == shape)
427 }
428
429 pub fn field(
431 &self,
432 cx: &dyn ConvertCx,
433 object: &NativeObject,
434 name: &str,
435 ) -> Option<RunResult<Value>> {
436 let field = self.hooks(object.ty).field;
437 object.with_any(|value| field(cx, value, name))
438 }
439
440 pub fn display(&self, object: &NativeObject) -> String {
445 object
446 .with_any(self.hooks(object.ty).display)
447 .unwrap_or_else(|| format!("<{}>", self.type_name(object.ty)))
448 }
449
450 pub fn native_eq(&self, a: &NativeObject, b: &NativeObject) -> bool {
452 if a.ty != b.ty {
453 return false;
454 }
455 if std::ptr::eq(a, b) {
456 return true;
457 }
458 let eq = self.hooks(a.ty).eq;
459 a.with_any(|a| b.with_any(|b| eq(a, b)))
460 }
461
462 pub fn borrowing_object<T: Facet<'static> + Send + 'static>(
467 &self,
468 value: T,
469 keep_alive: Arc<dyn std::any::Any + Send + Sync>,
470 ) -> RunResult<Value> {
471 let ty = self
472 .type_of_shape(T::SHAPE)
473 .ok_or_else(|| RuntimeError::new(format!("`{}` is not a registered type", T::SHAPE)))?;
474 let object = NativeObject::borrowing(ty, Box::new(value), keep_alive);
475 Ok(Value::Native(object.into()))
476 }
477
478 pub(crate) fn object_from_peek(
480 &self,
481 ty: NativeTypeId,
482 peek: Peek<'_, 'static>,
483 ) -> Option<NativeObject> {
484 let value = (self.hooks(ty).clone_peek)(peek)?;
485 Some(NativeObject::new(ty, value))
486 }
487
488 pub(crate) fn set_object(&self, partial: Builder, object: &NativeObject) -> RunResult<Builder> {
490 let set = self.hooks(object.ty).set;
491 object.with_any(|value| set(partial, value))
492 }
493
494 fn hooks(&self, ty: NativeTypeId) -> TypeHooks {
497 self.read().types[ty.0 as usize]
498 .hooks
499 .expect("native objects only exist for types registered with their Rust type")
500 }
501
502 pub fn decls(&self) -> Vec<NativeModule> {
504 let inner = self.read();
505 inner
506 .roots
507 .iter()
508 .map(|&module| inner.decl(module))
509 .collect()
510 }
511
512 pub fn expand(&self, path: &[String]) -> NativeModule {
515 let (module, init) = {
516 let mut inner = self.write();
517 let module = inner
518 .find(path)
519 .unwrap_or_else(|| panic!("no native module `{}`", path.join("::")));
520 (module, inner.modules[module].init.take())
521 };
522 if let Some(init) = init {
524 init(&mut ModuleBuilder::new(self, module));
525 }
526 self.read().decl(module)
527 }
528
529 pub(super) fn add_fn(
530 &self,
531 name: &str,
532 signature: Option<Signature>,
533 param_names: Vec<String>,
534 call: Box<CallFn>,
535 ) -> NativeFnDecl {
536 self.write().add_fn(name, signature, param_names, call)
537 }
538
539 fn with_inner<R>(&self, f: impl FnOnce(&mut Inner) -> R) -> R {
540 f(&mut self.write())
541 }
542}
543
544impl Inner {
545 fn module_at(&mut self, path: &str) -> usize {
546 let mut names = path.split("::");
547 let root = names.next().expect("split yields at least one item");
548 let mut module = self.child(None, root);
549 for name in names {
550 module = self.child(Some(module), name);
551 }
552 module
553 }
554
555 fn find(&self, path: &[String]) -> Option<usize> {
556 let mut module: Option<usize> = None;
557 for name in path {
558 let siblings = match module {
559 Some(parent) => &self.modules[parent].children,
560 None => &self.roots,
561 };
562 module = Some(*siblings.iter().find(|&&m| self.modules[m].name == *name)?);
563 }
564 module
565 }
566
567 fn decl(&self, module: usize) -> NativeModule {
568 let data = &self.modules[module];
569 if data.init.is_some() {
570 return NativeModule {
571 name: data.name.clone(),
572 lazy: true,
573 ..NativeModule::default()
574 };
575 }
576 NativeModule {
577 name: data.name.clone(),
578 lazy: false,
579 functions: data.functions.clone(),
580 types: data
581 .types
582 .iter()
583 .map(|&id| {
584 let ty = &self.types[id.0 as usize];
585 NativeTypeDecl {
586 name: ty.name.clone(),
587 id,
588 functions: ty.functions.clone(),
589 variants: if let Some(ref v) = ty.explicit_variants {
590 v.clone()
591 } else if ty.hooks.is_none() {
592 variant_decls(ty.shape)
593 } else {
594 Vec::new()
595 },
596 }
597 })
598 .collect(),
599 modules: data
600 .children
601 .iter()
602 .map(|&child| self.decl(child))
603 .collect(),
604 }
605 }
606
607 fn child(&mut self, parent: Option<usize>, name: &str) -> usize {
609 let siblings = match parent {
610 Some(parent) => &self.modules[parent].children,
611 None => &self.roots,
612 };
613 if let Some(&existing) = siblings.iter().find(|&&m| self.modules[m].name == name) {
614 return existing;
615 }
616 let module = self.modules.len();
617 self.modules.push(ModuleData {
618 name: name.to_owned(),
619 init: None,
620 children: Vec::new(),
621 functions: Vec::new(),
622 types: Vec::new(),
623 });
624 match parent {
625 Some(parent) => self.modules[parent].children.push(module),
626 None => self.roots.push(module),
627 }
628 module
629 }
630
631 fn add_fn(
632 &mut self,
633 name: &str,
634 signature: Option<Signature>,
635 param_names: Vec<String>,
636 call: Box<CallFn>,
637 ) -> NativeFnDecl {
638 let id = NativeFnId(self.fns.len() as u32);
639 self.fns.push(Arc::new(NativeFn {
640 name: name.to_owned(),
641 signature,
642 param_names: param_names.clone(),
643 call,
644 }));
645 NativeFnDecl {
646 name: name.to_owned(),
647 id,
648 param_names,
649 }
650 }
651}
652
653impl NativeProvider for Registry {
654 fn modules(&self) -> Vec<NativeModule> {
655 self.decls()
656 }
657
658 fn expand(&self, path: &[String]) -> NativeModule {
659 Registry::expand(self, path)
660 }
661}