use facet::{Facet, Shape};
use super::{CallFn, Context, Signature};
use crate::marshal::{FromArg, IntoXurValue};
use crate::{RuntimeError, Value};
fn shape_or_unit(s: Option<&'static Shape>) -> &'static Shape {
s.unwrap_or(<() as Facet>::SHAPE)
}
fn arity_error(min: usize, max: usize, found: usize) -> RuntimeError {
if min == max {
RuntimeError::new(format!("expected {min} argument(s), found {found}"))
} else {
RuntimeError::new(format!(
"expected {min} to {max} argument(s), found {found}"
))
}
}
pub trait IntoNativeMethod<T, Marker> {
fn into_native(self) -> (Signature, Box<CallFn>);
}
pub trait IntoNativeMethodMut<T, Marker> {
fn into_native(self) -> (Signature, Box<CallFn>);
}
pub trait IntoNativeFn<Marker> {
fn into_native(self) -> (Signature, Box<CallFn>);
}
macro_rules! impl_into_native_fn {
($($arg:ident),*) => {
impl<F, R, $($arg),*> IntoNativeFn<fn($($arg),*) -> R> for F
where
F: Fn($($arg),*) -> R + Send + Sync + 'static,
R: IntoXurValue,
$($arg: FromArg,)*
{
fn into_native(self) -> (Signature, Box<CallFn>) {
let signature = Signature {
params: vec![$(shape_or_unit(<$arg as FromArg>::SHAPE)),*],
ret: shape_or_unit(<R as IntoXurValue>::SHAPE),
param_names: Vec::new(),
};
let max = signature.params.len();
let min = 0usize $(+ <$arg as FromArg>::REQUIRED as usize)*;
let call = move |cx: &mut dyn Context, args: &[Value]| {
if args.len() < min || args.len() > max {
return Err(arity_error(min, max, args.len()));
}
#[allow(non_snake_case, unused_mut, unused_variables)]
let mut rest = args.iter();
$(
#[allow(non_snake_case)]
let $arg = <$arg as FromArg>::from_arg(cx, rest.next())?;
)*
let result = self($($arg),*);
result.into_xur_value(cx)
};
(signature, Box::new(call))
}
}
impl<F, T, R, $($arg),*> IntoNativeMethod<T, fn($($arg),*) -> R> for F
where
F: Fn(&T, $($arg),*) -> R + Send + Sync + 'static,
T: Facet<'static> + Send + 'static,
R: IntoXurValue,
$($arg: FromArg,)*
{
#[allow(non_snake_case)]
fn into_native(self) -> (Signature, Box<CallFn>) {
impl_into_native_fn!(@method self, T, R, with, $($arg),*)
}
}
impl<F, T, R, $($arg),*> IntoNativeMethodMut<T, fn($($arg),*) -> R> for F
where
F: Fn(&mut T, $($arg),*) -> R + Send + Sync + 'static,
T: Facet<'static> + Send + 'static,
R: IntoXurValue,
$($arg: FromArg,)*
{
#[allow(non_snake_case)]
fn into_native(self) -> (Signature, Box<CallFn>) {
impl_into_native_fn!(@method self, T, R, with_mut, $($arg),*)
}
}
};
(@method $f:ident, $ty:ident, $ret:ident, $with:ident, $($arg:ident),*) => {{
let signature = Signature {
params: vec![$ty::SHAPE, $(shape_or_unit(<$arg as FromArg>::SHAPE)),*],
ret: shape_or_unit(<$ret as IntoXurValue>::SHAPE),
param_names: Vec::new(),
};
let max = signature.params.len();
let min = 1usize $(+ <$arg as FromArg>::REQUIRED as usize)*;
let call = move |cx: &mut dyn Context, args: &[Value]| {
if args.len() < min || args.len() > max {
return Err(arity_error(min, max, args.len()));
}
#[allow(unused_mut)]
let mut rest = args.iter();
let receiver = rest.next().expect("min >= 1 guarantees a receiver");
$(
#[allow(non_snake_case)]
let $arg = <$arg as FromArg>::from_arg(cx, rest.next())?;
)*
let object = match receiver {
Value::Native(object) => object,
Value::NativeEnum(ne) => &ne.object,
_ => {
return Err(RuntimeError::new(format!(
"expected `{}`, found {}",
$ty::SHAPE,
receiver.kind()
)));
}
};
let result = object.$with(|this| $f(this, $($arg),*)).ok_or_else(|| {
RuntimeError::new(format!("expected `{}`, found another native type", $ty::SHAPE))
})?;
result.into_xur_value(cx)
};
(signature, Box::new(call) as Box<CallFn>)
}};
}
impl_into_native_fn!();
impl_into_native_fn!(A);
impl_into_native_fn!(A, B);
impl_into_native_fn!(A, B, C);
impl_into_native_fn!(A, B, C, D);
impl_into_native_fn!(A, B, C, D, E);
impl_into_native_fn!(A, B, C, D, E, G);
use crate::value::lock;
use std::sync::Arc;
pub trait BuiltinRecv {
fn with<R>(value: &Value, f: impl FnOnce(&Self) -> R) -> Result<R, RuntimeError>;
}
impl BuiltinRecv for [u8] {
fn with<R>(value: &Value, f: impl FnOnce(&[u8]) -> R) -> Result<R, RuntimeError> {
let Value::Bytes(bytes) = value else {
return Err(RuntimeError::new(format!(
"expected bytes, found {}",
value.kind()
)));
};
Ok(f(&lock(bytes)))
}
}
impl BuiltinRecv for str {
fn with<R>(value: &Value, f: impl FnOnce(&str) -> R) -> Result<R, RuntimeError> {
let Value::Str(s) = value else {
return Err(RuntimeError::new(format!(
"expected string, found {}",
value.kind()
)));
};
Ok(f(s))
}
}
impl BuiltinRecv for [Value] {
fn with<R>(value: &Value, f: impl FnOnce(&[Value]) -> R) -> Result<R, RuntimeError> {
let Value::List(list) = value else {
return Err(RuntimeError::new(format!(
"expected list, found {}",
value.kind()
)));
};
Ok(f(&lock(list)))
}
}
impl BuiltinRecv for crate::XurList {
fn with<R>(value: &Value, f: impl FnOnce(&Self) -> R) -> Result<R, RuntimeError> {
let Value::List(list) = value else {
return Err(RuntimeError::new(format!(
"expected list, found {}",
value.kind()
)));
};
Ok(f(&crate::XurList(Arc::clone(list))))
}
}
impl BuiltinRecv for crate::XurBytes {
fn with<R>(value: &Value, f: impl FnOnce(&Self) -> R) -> Result<R, RuntimeError> {
let Value::Bytes(bytes) = value else {
return Err(RuntimeError::new(format!(
"expected bytes, found {}",
value.kind()
)));
};
Ok(f(&crate::XurBytes(Arc::clone(bytes))))
}
}
pub trait BuiltinRecvMut {
fn with_mut<R>(value: &Value, f: impl FnOnce(&mut Self) -> R) -> Result<R, RuntimeError>;
}
impl BuiltinRecvMut for Vec<u8> {
fn with_mut<R>(value: &Value, f: impl FnOnce(&mut Vec<u8>) -> R) -> Result<R, RuntimeError> {
let Value::Bytes(bytes) = value else {
return Err(RuntimeError::new(format!(
"expected bytes, found {}",
value.kind()
)));
};
Ok(f(&mut lock(bytes)))
}
}
impl BuiltinRecvMut for Vec<Value> {
fn with_mut<R>(value: &Value, f: impl FnOnce(&mut Vec<Value>) -> R) -> Result<R, RuntimeError> {
let Value::List(list) = value else {
return Err(RuntimeError::new(format!(
"expected list, found {}",
value.kind()
)));
};
Ok(f(&mut lock(list)))
}
}
pub trait IntoBuiltinMethod<Recv: ?Sized, Marker> {
fn into_native(self) -> (Signature, Box<CallFn>);
}
pub trait IntoBuiltinMethodMut<Recv, Marker> {
fn into_native(self) -> (Signature, Box<CallFn>);
}
macro_rules! impl_builtin_method {
($($arg:ident),*) => {
impl<F, Recv, R, $($arg),*> IntoBuiltinMethod<Recv, fn($($arg),*) -> R> for F
where
F: Fn(&Recv, $($arg),*) -> R + Send + Sync + 'static,
Recv: BuiltinRecv + ?Sized + 'static,
R: IntoXurValue,
$($arg: FromArg,)*
{
#[allow(non_snake_case)]
fn into_native(self) -> (Signature, Box<CallFn>) {
let signature = Signature {
params: vec![$(shape_or_unit(<$arg as FromArg>::SHAPE)),*],
ret: shape_or_unit(<R as IntoXurValue>::SHAPE),
param_names: Vec::new(),
};
let max = signature.params.len() + 1;
let min = 1usize $(+ <$arg as FromArg>::REQUIRED as usize)*;
let call = move |cx: &mut dyn Context, args: &[Value]| {
if args.len() < min || args.len() > max {
return Err(arity_error(min, max, args.len()));
}
#[allow(unused_mut)]
let mut rest = args.iter();
let receiver = rest.next().expect("min >= 1 guarantees a receiver");
$(
#[allow(non_snake_case)]
let $arg = <$arg as FromArg>::from_arg(cx, rest.next())?;
)*
let result = Recv::with(receiver, |recv| self(recv, $($arg),*))?;
result.into_xur_value(cx)
};
(signature, Box::new(call))
}
}
impl<F, Recv, R, $($arg),*> IntoBuiltinMethodMut<Recv, fn($($arg),*) -> R> for F
where
F: Fn(&mut Recv, $($arg),*) -> R + Send + Sync + 'static,
Recv: BuiltinRecvMut + 'static,
R: IntoXurValue,
$($arg: FromArg,)*
{
#[allow(non_snake_case)]
fn into_native(self) -> (Signature, Box<CallFn>) {
let signature = Signature {
params: vec![$(shape_or_unit(<$arg as FromArg>::SHAPE)),*],
ret: shape_or_unit(<R as IntoXurValue>::SHAPE),
param_names: Vec::new(),
};
let max = signature.params.len() + 1;
let min = 1usize $(+ <$arg as FromArg>::REQUIRED as usize)*;
let call = move |cx: &mut dyn Context, args: &[Value]| {
if args.len() < min || args.len() > max {
return Err(arity_error(min, max, args.len()));
}
#[allow(unused_mut)]
let mut rest = args.iter();
let receiver = rest.next().expect("min >= 1 guarantees a receiver");
$(
#[allow(non_snake_case)]
let $arg = <$arg as FromArg>::from_arg(cx, rest.next())?;
)*
let result = Recv::with_mut(receiver, |recv| self(recv, $($arg),*))?;
result.into_xur_value(cx)
};
(signature, Box::new(call))
}
}
};
}
impl_builtin_method!();
impl_builtin_method!(A);
impl_builtin_method!(A, B);
impl_builtin_method!(A, B, C);
impl_builtin_method!(A, B, C, D);
impl_builtin_method!(A, B, C, D, E);
impl_builtin_method!(A, B, C, D, E, G);