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::{Peek, Shape};
use xur_resolve::{
NativeFnDecl, NativeFnId, NativeModule, NativeProvider, NativeTypeDecl, NativeTypeId,
};
use crate::convert::{Builder, ConvertCx};
use crate::value::NativeObject;
use crate::{BuiltinType, RunResult, Value};
pub use builder::{BuiltinBuilder, ModuleBuilder, TypeBuilder};
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) -> &[String];
fn print(&mut self, text: &str) -> RunResult<()>;
fn call(&mut self, callee: &Value, args: Vec<Value>) -> RunResult<Value>;
fn spawn(&mut self, f: Value) -> RunResult<JoinHandle<RunResult<Value>>>;
}
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 struct NativeFn {
pub name: String,
pub signature: Option<Signature>,
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: TypeHooks,
}
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>,
}
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 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_of_shape(&self, shape: &'static Shape) -> Option<NativeTypeId> {
let index = self.read().types.iter().position(|ty| ty.shape == shape)?;
Some(NativeTypeId(index as u32))
}
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)
}
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(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
}
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(super) fn add_fn(
&self,
name: &str,
signature: Option<Signature>,
call: Box<CallFn>,
) -> NativeFnDecl {
self.write().add_fn(name, signature, 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(),
}
})
.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>,
call: Box<CallFn>,
) -> NativeFnDecl {
let id = NativeFnId(self.fns.len() as u32);
self.fns.push(Arc::new(NativeFn {
name: name.to_owned(),
signature,
call,
}));
NativeFnDecl {
name: name.to_owned(),
id,
}
}
}
impl NativeProvider for Registry {
fn modules(&self) -> Vec<NativeModule> {
self.decls()
}
fn expand(&self, path: &[String]) -> NativeModule {
Registry::expand(self, path)
}
}