mod builder;
mod hooks;
mod into_native;
#[cfg(test)]
mod tests;
use std::collections::HashMap;
use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::thread::JoinHandle;
use facet::{Facet, Peek, Shape, StructKind, StructType, Type, UserType};
use xur_resolve::{
DefId, NativeFnDecl, NativeFnId, NativeModule, NativeProvider, NativeTypeDecl, NativeTypeId,
NativeVariantDecl, NativeVariantKind,
};
use xur_span::Symbol;
use crate::convert::{Builder, ConvertCx};
use crate::value::NativeObject;
use crate::{AdtInfo, BuiltinType, RunResult, RuntimeError, TypeRef, Value};
pub use builder::{BuiltinBuilder, ElemHint, ModuleBuilder, ReturnHint, Returns, TypeBuilder, XurType};
pub use into_native::{IntoNativeFn, IntoNativeMethod, IntoNativeMethodMut};
use hooks::TypeHooks;
pub trait Context: ConvertCx {
fn import(&mut self, path: &str) -> RunResult<Value>;
fn display(&self, value: &Value) -> String;
fn type_args(&self) -> &[TypeRef];
fn print(&mut self, text: &str) -> RunResult<()>;
fn call(&mut self, callee: &Value, args: &[Value]) -> RunResult<Value>;
fn spawn(&mut self, f: Value) -> RunResult<JoinHandle<RunResult<Value>>>;
fn describe_type(&self, value: &Value) -> String;
fn adt_info(&self, def: DefId) -> Option<AdtInfo>;
fn methods(&self, value: &Value) -> Vec<String>;
fn field(&mut self, value: &Value, name: &str) -> RunResult<Value>;
fn set_field(&mut self, value: &Value, name: &str, new: Value) -> RunResult<Value>;
fn call_method(&mut self, receiver: Value, name: &str, args: &[Value]) -> RunResult<Value>;
fn try_cast(&self, value: &Value, target: DefId) -> RunResult<Value>;
fn repr_value(&self, def: DefId) -> Option<i64>;
fn fn_info(&self, value: &Value) -> Option<crate::FnInfo>;
fn shared_handle(&self) -> Option<Box<dyn std::any::Any + Send + Sync>> {
None
}
fn def_name(&self, _def: DefId) -> Option<String> {
None
}
fn enum_variants(&self, _def: DefId) -> Vec<(String, DefId, bool)> {
Vec::new()
}
}
pub(crate) type CallFn = dyn Fn(&mut dyn Context, &[Value]) -> RunResult<Value> + Send + Sync;
#[derive(Debug, Clone)]
pub struct Signature {
pub params: Vec<&'static Shape>,
pub ret: &'static Shape,
pub param_names: Vec<String>,
}
pub struct NativeFn {
pub name: String,
pub signature: Option<Signature>,
pub return_hint: Option<ReturnHint>,
pub param_names: Vec<String>,
call: Box<CallFn>,
}
impl NativeFn {
pub fn call(&self, cx: &mut dyn Context, args: &[Value]) -> RunResult<Value> {
(self.call)(cx, args)
}
}
pub(super) struct NativeType {
name: String,
shape: &'static Shape,
functions: Vec<NativeFnDecl>,
hooks: Option<TypeHooks>,
explicit_variants: Option<Vec<NativeVariantDecl>>,
}
type ModuleInit = Box<dyn FnOnce(&mut ModuleBuilder<'_>) + Send + Sync>;
struct ModuleData {
name: String,
init: Option<ModuleInit>,
children: Vec<usize>,
functions: Vec<NativeFnDecl>,
types: Vec<NativeTypeId>,
}
#[derive(Default)]
pub struct Registry {
inner: RwLock<Inner>,
}
#[derive(Default)]
struct Inner {
fns: Vec<Arc<NativeFn>>,
builtin_methods: HashMap<(BuiltinType, String), NativeFnId>,
types: Vec<NativeType>,
modules: Vec<ModuleData>,
roots: Vec<usize>,
converters: Vec<(&'static Shape, Converter)>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RecordCtor {
pub kind: NativeVariantKind,
pub fields: Vec<Symbol>,
}
fn variant_decls(shape: &'static Shape) -> Vec<NativeVariantDecl> {
let Type::User(UserType::Enum(en)) = shape.ty else {
return Vec::new();
};
en.variants
.iter()
.map(|variant| NativeVariantDecl {
name: variant.name.to_owned(),
kind: variant_kind(variant.data.kind),
repr_value: None,
})
.collect()
}
fn variant_kind(kind: StructKind) -> NativeVariantKind {
match kind {
StructKind::Unit => NativeVariantKind::Unit,
StructKind::Tuple | StructKind::TupleStruct => NativeVariantKind::Tuple,
StructKind::Struct => NativeVariantKind::Named,
}
}
pub type Converter = fn(&dyn ConvertCx, Peek<'_, 'static>) -> RunResult<Value>;
impl Registry {
pub fn new() -> Self {
Self::default()
}
fn read(&self) -> RwLockReadGuard<'_, Inner> {
self.inner.read().unwrap_or_else(PoisonError::into_inner)
}
fn write(&self) -> RwLockWriteGuard<'_, Inner> {
self.inner.write().unwrap_or_else(PoisonError::into_inner)
}
pub fn module(&self, path: &str) -> ModuleBuilder<'_> {
let module = self.write().module_at(path);
ModuleBuilder::new(self, module)
}
pub fn lazy_module(
&self,
path: &str,
init: impl FnOnce(&mut ModuleBuilder<'_>) + Send + Sync + 'static,
) {
let mut inner = self.write();
let module = inner.module_at(path);
inner.modules[module].init = Some(Box::new(init));
}
pub fn builtin(&self, ty: BuiltinType) -> BuiltinBuilder<'_> {
BuiltinBuilder::new(self, ty)
}
pub fn builtin_method(&self, ty: BuiltinType, name: &str) -> Option<NativeFnId> {
self.read()
.builtin_methods
.get(&(ty, name.to_owned()))
.copied()
}
pub fn type_function(&self, ty: NativeTypeId, name: &str) -> Option<NativeFnId> {
let inner = self.read();
let functions = &inner.types[ty.0 as usize].functions;
functions.iter().find(|f| f.name == name).map(|f| f.id)
}
pub fn type_methods(&self, ty: NativeTypeId) -> Vec<String> {
let inner = self.read();
let native = &inner.types[ty.0 as usize];
native
.functions
.iter()
.filter(|decl| match &inner.fns[decl.id.0 as usize].signature {
Some(signature) => signature.params.first() == Some(&native.shape),
None => true,
})
.map(|decl| decl.name.clone())
.collect()
}
pub fn builtin_methods(&self, ty: BuiltinType) -> Vec<String> {
let mut names: Vec<_> = self
.read()
.builtin_methods
.keys()
.filter(|(builtin, _)| *builtin == ty)
.map(|(_, name)| name.clone())
.collect();
names.sort();
names
}
pub fn type_fields(&self, ty: NativeTypeId) -> Vec<String> {
let shape = self.read().types[ty.0 as usize].shape;
match shape.ty {
Type::User(UserType::Struct(StructType { fields, .. })) => {
fields.iter().map(|field| field.name.to_owned()).collect()
}
_ => Vec::new(),
}
}
pub fn function(&self, id: NativeFnId) -> Arc<NativeFn> {
Arc::clone(&self.read().fns[id.0 as usize])
}
pub fn type_name(&self, id: NativeTypeId) -> String {
self.read().types[id.0 as usize].name.clone()
}
pub fn type_id_by_name(&self, name: &str) -> Option<NativeTypeId> {
let inner = self.read();
inner.types.iter().enumerate().find_map(|(i, ty)| {
(ty.name == name).then_some(NativeTypeId(i as u32))
})
}
pub fn shape_xur_name(&self, shape: &'static Shape) -> String {
if let Some(id) = self.type_of_shape(shape) {
return self.type_name(id);
}
let name = shape.type_name().to_string();
match name.as_str() {
"String" | "&str" | "alloc::string::String" => "str".into(),
"bool" => "bool".into(),
"i64" => "i64".into(),
"f64" => "f64".into(),
"i32" => "i32".into(),
"u32" => "u32".into(),
"u64" => "u64".into(),
"usize" => "usize".into(),
"()" => "()".into(),
"Vec<u8>" | "alloc::vec::Vec<u8>" => "bytes".into(),
_ if name.starts_with("Vec<") || name == "Vec" => "list".into(),
_ => {
name.split('<').next().unwrap_or(&name).into()
}
}
}
pub fn native_return_shape(&self, id: NativeFnId) -> Option<&'static Shape> {
let f = self.function(id);
if let Some(sig) = &f.signature {
return Some(sig.ret);
}
match f.return_hint {
Some(ReturnHint::Shape(s)) => Some(s),
_ => None,
}
}
pub fn native_return_name(&self, id: NativeFnId) -> Option<String> {
let f = self.function(id);
if let Some(sig) = &f.signature {
return Some(self.shape_xur_name(sig.ret));
}
match f.return_hint {
Some(ReturnHint::Shape(s)) => Some(self.shape_xur_name(s)),
Some(ReturnHint::Xur(xur)) => Some(self.xur_type_name(xur)),
None => None,
}
}
fn xur_type_name(&self, ty: XurType) -> String {
match ty {
XurType::Ptr(Some(inner)) => format!("*{}", self.shape_xur_name(inner)),
XurType::Ptr(None) => "ptr".into(),
XurType::List(None) => "list".into(),
XurType::List(Some(hint)) => format!("list<{}>", self.elem_hint_name(hint)),
XurType::Map(None, None) => "map".into(),
XurType::Map(Some(k), Some(v)) => {
format!("map<{}, {}>", self.shape_xur_name(k), self.shape_xur_name(v))
}
XurType::Map(Some(k), None) => format!("map<{}, _>", self.shape_xur_name(k)),
XurType::Map(None, Some(v)) => format!("map<_, {}>", self.shape_xur_name(v)),
XurType::Named(name, params) if params.is_empty() => (*name).into(),
XurType::Named(name, params) => {
let args: Vec<_> = params.iter().map(|h| self.elem_hint_name(*h)).collect();
format!("{name}<{}>", args.join(", "))
}
XurType::Record => "record".into(),
XurType::Module => "module".into(),
XurType::Unit => "()".into(),
}
}
fn elem_hint_name(&self, hint: ElemHint) -> String {
match hint {
ElemHint::Shape(s) => self.shape_xur_name(s),
ElemHint::Name(n) => n.into(),
ElemHint::Param(n) => format!("T{n}"),
}
}
pub(super) fn set_return_hint(&self, id: NativeFnId, hint: ReturnHint) {
let mut inner = self.write();
let slot = &mut inner.fns[id.0 as usize];
Arc::get_mut(slot)
.expect("return hint set during registration")
.return_hint = Some(hint);
}
pub fn shape_type_param(&self, shape: &'static Shape, index: usize) -> Option<String> {
if let Ok(r) = shape.def.into_result() {
return match index {
0 => Some(self.shape_xur_name(r.t())),
1 => Some(self.shape_xur_name(r.e())),
_ => None,
};
}
if let Ok(o) = shape.def.into_option() {
return (index == 0).then(|| self.shape_xur_name(o.t()));
}
None
}
pub fn type_of_shape(&self, shape: &'static Shape) -> Option<NativeTypeId> {
let index = self
.read()
.types
.iter()
.position(|ty| ty.shape == shape && ty.hooks.is_some())?;
Some(NativeTypeId(index as u32))
}
pub fn record_type_of_shape(&self, shape: &'static Shape) -> Option<NativeTypeId> {
let index = self
.read()
.types
.iter()
.position(|ty| ty.shape == shape && ty.hooks.is_none())?;
Some(NativeTypeId(index as u32))
}
pub fn converter(&self, shape: &'static Shape, convert: Converter) {
self.write().converters.push((shape, convert));
}
pub fn has_converter(&self, shape: &'static Shape) -> bool {
self.converter_of(shape).is_some()
}
pub(crate) fn converter_of(&self, shape: &'static Shape) -> Option<Converter> {
let inner = self.read();
let (_, convert) = inner.converters.iter().find(|(s, _)| *s == shape)?;
Some(*convert)
}
pub fn record_ctor(&self, ty: NativeTypeId, variant: Option<Symbol>) -> Option<RecordCtor> {
let shape = self.read().types[ty.0 as usize].shape;
let data = match (shape.ty, variant) {
(Type::User(UserType::Struct(st)), None) => st,
(Type::User(UserType::Enum(en)), Some(variant)) => {
en.variants
.iter()
.find(|v| v.name == variant.as_str())?
.data
}
_ => return None,
};
Some(RecordCtor {
kind: variant_kind(data.kind),
fields: data
.fields
.iter()
.map(|field| Symbol::intern(field.name))
.collect(),
})
}
pub fn has_shape(&self, shape: &'static Shape) -> bool {
self.read().types.iter().any(|ty| ty.shape == shape)
}
pub fn field(
&self,
cx: &dyn ConvertCx,
object: &NativeObject,
name: &str,
) -> Option<RunResult<Value>> {
let field = self.hooks(object.ty).field;
object.with_any(|value| field(cx, value, name))
}
pub fn display(&self, object: &NativeObject) -> String {
object
.with_any(self.hooks(object.ty).display)
.unwrap_or_else(|| format!("<{}>", self.type_name(object.ty)))
}
pub fn native_eq(&self, a: &NativeObject, b: &NativeObject) -> bool {
if a.ty != b.ty {
return false;
}
if std::ptr::eq(a, b) {
return true;
}
let eq = self.hooks(a.ty).eq;
a.with_any(|a| b.with_any(|b| eq(a, b)))
}
pub fn borrowing_object<T: Facet<'static> + Send + 'static>(
&self,
value: T,
keep_alive: Arc<dyn std::any::Any + Send + Sync>,
) -> RunResult<Value> {
let ty = self
.type_of_shape(T::SHAPE)
.ok_or_else(|| RuntimeError::new(format!("`{}` is not a registered type", T::SHAPE)))?;
let object = NativeObject::borrowing(ty, Box::new(value), keep_alive);
Ok(Value::Native(object.into()))
}
pub(crate) fn object_from_peek(
&self,
ty: NativeTypeId,
peek: Peek<'_, 'static>,
) -> Option<NativeObject> {
let value = (self.hooks(ty).clone_peek)(peek)?;
Some(NativeObject::new(ty, value))
}
pub(crate) fn set_object(&self, partial: Builder, object: &NativeObject) -> RunResult<Builder> {
let set = self.hooks(object.ty).set;
object.with_any(|value| set(partial, value))
}
fn hooks(&self, ty: NativeTypeId) -> TypeHooks {
self.read().types[ty.0 as usize]
.hooks
.expect("native objects only exist for types registered with their Rust type")
}
pub fn decls(&self) -> Vec<NativeModule> {
let inner = self.read();
inner
.roots
.iter()
.map(|&module| inner.decl(module))
.collect()
}
pub fn expand(&self, path: &[String]) -> NativeModule {
let (module, init) = {
let mut inner = self.write();
let module = inner
.find(path)
.unwrap_or_else(|| panic!("no native module `{}`", path.join("::")));
(module, inner.modules[module].init.take())
};
if let Some(init) = init {
init(&mut ModuleBuilder::new(self, module));
}
self.read().decl(module)
}
pub fn add_fn(
&self,
name: &str,
signature: Option<Signature>,
param_names: Vec<String>,
call: Box<CallFn>,
) -> NativeFnDecl {
self.write().add_fn(name, signature, param_names, call)
}
fn with_inner<R>(&self, f: impl FnOnce(&mut Inner) -> R) -> R {
f(&mut self.write())
}
}
impl Inner {
fn module_at(&mut self, path: &str) -> usize {
let mut names = path.split("::");
let root = names.next().expect("split yields at least one item");
let mut module = self.child(None, root);
for name in names {
module = self.child(Some(module), name);
}
module
}
fn find(&self, path: &[String]) -> Option<usize> {
let mut module: Option<usize> = None;
for name in path {
let siblings = match module {
Some(parent) => &self.modules[parent].children,
None => &self.roots,
};
module = Some(*siblings.iter().find(|&&m| self.modules[m].name == *name)?);
}
module
}
fn decl(&self, module: usize) -> NativeModule {
let data = &self.modules[module];
if data.init.is_some() {
return NativeModule {
name: data.name.clone(),
lazy: true,
..NativeModule::default()
};
}
NativeModule {
name: data.name.clone(),
lazy: false,
functions: data.functions.clone(),
types: data
.types
.iter()
.map(|&id| {
let ty = &self.types[id.0 as usize];
NativeTypeDecl {
name: ty.name.clone(),
id,
functions: ty.functions.clone(),
variants: if let Some(ref v) = ty.explicit_variants {
v.clone()
} else if ty.hooks.is_none() {
variant_decls(ty.shape)
} else {
Vec::new()
},
}
})
.collect(),
modules: data
.children
.iter()
.map(|&child| self.decl(child))
.collect(),
}
}
fn child(&mut self, parent: Option<usize>, name: &str) -> usize {
let siblings = match parent {
Some(parent) => &self.modules[parent].children,
None => &self.roots,
};
if let Some(&existing) = siblings.iter().find(|&&m| self.modules[m].name == name) {
return existing;
}
let module = self.modules.len();
self.modules.push(ModuleData {
name: name.to_owned(),
init: None,
children: Vec::new(),
functions: Vec::new(),
types: Vec::new(),
});
match parent {
Some(parent) => self.modules[parent].children.push(module),
None => self.roots.push(module),
}
module
}
fn add_fn(
&mut self,
name: &str,
signature: Option<Signature>,
param_names: Vec<String>,
call: Box<CallFn>,
) -> NativeFnDecl {
let id = NativeFnId(self.fns.len() as u32);
self.fns.push(Arc::new(NativeFn {
name: name.to_owned(),
signature,
return_hint: None,
param_names: param_names.clone(),
call,
}));
NativeFnDecl {
name: name.to_owned(),
id,
param_names,
}
}
}
impl NativeProvider for Registry {
fn modules(&self) -> Vec<NativeModule> {
self.decls()
}
fn expand(&self, path: &[String]) -> NativeModule {
Registry::expand(self, path)
}
fn register_enum_builtins(&self, enum_def: DefId) -> Vec<NativeFnDecl> {
vec![
self.add_fn(
"from_str",
None,
vec!["name".into()],
Box::new({
let def = enum_def;
move |cx, args| enum_from_str(cx, def, args)
}),
),
self.add_fn(
"len",
None,
Vec::new(),
Box::new({
let def = enum_def;
move |cx, args| enum_len(cx, def, args)
}),
),
self.add_fn(
"values",
None,
Vec::new(),
Box::new({
let def = enum_def;
move |cx, args| enum_values(cx, def, args)
}),
),
]
}
}
fn enum_from_str(cx: &mut dyn Context, enum_def: DefId, args: &[Value]) -> RunResult<Value> {
let [Value::Str(name)] = args else {
return Err(RuntimeError::new("`from_str` takes a string"));
};
let lang = cx.lang();
for (vname, vdef, has_fields) in cx.enum_variants(enum_def) {
if vname == name.as_ref() && !has_fields {
return Ok(Value::adt(lang.some, vec![Value::adt(vdef, vec![])]));
}
}
Ok(Value::adt(lang.none, vec![]))
}
fn enum_len(cx: &mut dyn Context, enum_def: DefId, args: &[Value]) -> RunResult<Value> {
if !args.is_empty() {
return Err(RuntimeError::new("`len` takes no arguments"));
}
Ok(Value::Int(cx.enum_variants(enum_def).len() as i64))
}
fn enum_values(cx: &mut dyn Context, enum_def: DefId, args: &[Value]) -> RunResult<Value> {
if !args.is_empty() {
return Err(RuntimeError::new("`values` takes no arguments"));
}
let values: Vec<Value> = cx
.enum_variants(enum_def)
.into_iter()
.filter(|(_, _, has_fields)| !has_fields)
.map(|(_, vdef, _)| Value::adt(vdef, vec![]))
.collect();
Ok(Value::list(values))
}