use crate::function::adapter::Token;
use crate::object_method::{IntoMutObjectMethod, IntoObjectIterator, IntoObjectMethod};
use crate::value::{load_owned_arguments, snapshot_value};
use crate::{
Error, FromRustiaMulti, HostSchema, IntoRustiaMulti, Invocation, OpCapability, Result, Rustia,
Value,
};
use rustia_vm::{HostFunctionOp, HostObjectHooks, HostObjectTypeDefinition, Value as RawValue};
use std::any::{type_name, TypeId};
use std::marker::PhantomData;
type Invariant<T> = PhantomData<fn(T) -> T>;
pub struct ObjectType<T: 'static, H: HostSchema = ()> {
name: String,
pub(crate) methods: Vec<HostFunctionOp>,
pub(crate) hooks: HostObjectHooks,
marker: Invariant<(T, H)>,
}
impl<T: 'static, H: HostSchema> ObjectType<T, H> {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
methods: Vec::new(),
hooks: HostObjectHooks::default(),
marker: PhantomData,
}
}
pub fn name(&self) -> &str {
&self.name
}
pub const fn fuel_policy(&self) -> crate::RustiaHostFuelPolicy {
crate::RUSTIA_HOST_FUEL_POLICY
}
pub fn methods(&self) -> impl Iterator<Item = crate::RustiaHostFunctionInfo<'_>> + '_ {
self.methods
.iter()
.map(|method| crate::RustiaHostFunctionInfo {
name: &method.name,
fuel_abi_version: crate::RUSTIA_HOST_FUEL_ABI_VERSION,
fuel_cost: method.fuel_cost,
capability: crate::OpCapability::from_core(method.capability),
parameter_count: method.parameter_count,
parameter_types: &method.parameter_types,
return_types: &method.return_types,
fallible: method.fallible,
})
}
pub fn method<F, A, R>(self, name: impl Into<String>, fuel_cost: u32, method: F) -> Self
where
F: IntoObjectMethod<T, A, R>,
{
self.method_with_capability(name, fuel_cost, OpCapability::Pure, method)
}
pub fn method_with_capability<F, A, R>(
mut self,
name: impl Into<String>,
fuel_cost: u32,
capability: OpCapability,
method: F,
) -> Self
where
F: IntoObjectMethod<T, A, R>,
{
self.methods.push(method.into_object_method(
Token,
name.into(),
fuel_cost,
capability.to_core(),
));
self
}
pub fn length<F, R>(self, fuel_cost: u32, length: F) -> Self
where
F: IntoObjectMethod<T, (), R>,
{
self.length_with_capability(fuel_cost, OpCapability::Pure, length)
}
pub fn length_with_capability<F, R>(
mut self,
fuel_cost: u32,
capability: OpCapability,
length: F,
) -> Self
where
F: IntoObjectMethod<T, (), R>,
{
self.hooks.length = Some(length.into_object_method(
Token,
"__len".to_owned(),
fuel_cost,
capability.to_core(),
));
self
}
pub fn iterator<Factory, Step, S, C, R>(
self,
fuel_cost: u32,
factory: Factory,
step: Step,
) -> Self
where
(Factory, Step): IntoObjectIterator<T, S, C, R>,
{
self.iterator_with_capability(fuel_cost, OpCapability::Pure, factory, step)
}
pub fn iterator_with_capability<Factory, Step, S, C, R>(
mut self,
fuel_cost: u32,
capability: OpCapability,
factory: Factory,
step: Step,
) -> Self
where
(Factory, Step): IntoObjectIterator<T, S, C, R>,
{
let (factory, step) = crate::object_method::adapter::Iterate::into_object_iterator(
(factory, step),
Token,
fuel_cost,
capability.to_core(),
);
self.hooks.iterator = Some(factory);
self.hooks.iterator_step = Some(step);
self
}
pub fn method_mut<F, A, R>(self, name: impl Into<String>, fuel_cost: u32, method: F) -> Self
where
F: IntoMutObjectMethod<T, A, R>,
{
self.mut_method(
name.into(),
fuel_cost,
OpCapability::ReadsExternalMutableState,
method,
)
}
pub fn method_mut_nondeterministic<F, A, R>(
self,
name: impl Into<String>,
fuel_cost: u32,
method: F,
) -> Self
where
F: IntoMutObjectMethod<T, A, R>,
{
self.mut_method(
name.into(),
fuel_cost,
OpCapability::NondeterministicEffect,
method,
)
}
fn mut_method<F, A, R>(
mut self,
name: String,
fuel_cost: u32,
capability: OpCapability,
method: F,
) -> Self
where
F: IntoMutObjectMethod<T, A, R>,
{
self.methods.push(method.into_mut_object_method(
Token,
name,
fuel_cost,
capability.to_core(),
));
self
}
}
pub struct Object<T: 'static> {
value: Value,
marker: Invariant<T>,
}
impl<T: 'static> Clone for Object<T> {
fn clone(&self) -> Self {
Self::new(self.value.clone())
}
}
impl<T: 'static> std::fmt::Debug for Object<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Object")
.field("rust_type", &type_name::<T>())
.field("value", &self.value)
.finish()
}
}
impl<T: 'static> Object<T> {
pub(crate) fn new(value: Value) -> Self {
Self {
value,
marker: PhantomData,
}
}
pub fn as_value(&self) -> Value {
self.value.clone()
}
pub fn decision_epoch(&self) -> u64 {
self.value.decision_epoch()
}
fn receiver(&self, vm: &mut rustia_vm::Vm, name: &str) -> Result<(RawValue, RawValue)> {
let receiver = self.value.raw(vm, "object handle")?;
let method = vm
.host_object_method(receiver, name)
.map_err(Error::from_engine)?;
Ok((receiver, method))
}
pub fn call_method<A: IntoRustiaMulti, R: FromRustiaMulti>(
&self,
lua: &mut Rustia,
name: &str,
args: A,
) -> Result<R> {
let (receiver, method) = self.receiver(lua.vm_mut(), name)?;
let owned = args.into_rustia_multi()?;
let (mut raw, _argument_roots) = load_owned_arguments(lua.vm_mut(), &owned)?;
raw.insert(0, receiver);
let results = lua
.vm_mut()
.call_retained_function(method, &raw)
.map_err(Error::from_engine)?;
R::from_rustia_multi(
results
.into_iter()
.map(|v| snapshot_value(lua.vm_mut(), v))
.collect::<Result<_>>()?,
)
}
pub fn call_method_values(
&self,
lua: &mut Rustia,
name: &str,
args: &[Value],
) -> Result<Vec<Value>> {
let (receiver, method) = self.receiver(lua.vm_mut(), name)?;
let mut raw = vec![receiver];
for value in args {
raw.push(value.raw(lua.vm(), "object method argument")?);
}
let results = lua
.vm_mut()
.call_retained_function(method, &raw)
.map_err(Error::from_engine)?;
Value::retain_many(lua.vm_mut(), &results)
}
pub fn call_method_in<H: HostSchema, A: IntoRustiaMulti, R: FromRustiaMulti>(
&self,
invocation: &mut Invocation<'_, H>,
name: &str,
args: A,
) -> Result<R> {
invocation.scoped(|invocation| {
let (receiver, method) = self.receiver(invocation.vm, name)?;
let owned = args.into_rustia_multi()?;
let (mut raw, _argument_roots) = load_owned_arguments(invocation.vm, &owned)?;
raw.insert(0, receiver);
let results = invocation.call_retained_raw(method, &raw)?;
R::from_rustia_multi(
results
.into_iter()
.map(|v| snapshot_value(invocation.vm, v))
.collect::<Result<_>>()?,
)
})
}
pub fn call_method_values_in<H: HostSchema>(
&self,
invocation: &mut Invocation<'_, H>,
name: &str,
args: &[Value],
) -> Result<Vec<Value>> {
invocation.scoped(|invocation| {
let (receiver, method) = self.receiver(invocation.vm, name)?;
let mut raw = vec![receiver];
for value in args {
raw.push(value.raw(invocation.vm, "object method argument")?);
}
let results = invocation.call_retained_raw(method, &raw)?;
Value::retain_many(invocation.vm, &results)
})
}
}
pub struct NewObject<T: 'static> {
pub(crate) value: T,
}
impl<T: 'static> NewObject<T> {
pub fn new(value: T) -> Self {
Self { value }
}
}
impl<H: HostSchema> Rustia<H> {
pub fn register_object_type<T: 'static>(&mut self, definition: ObjectType<T, H>) -> Result<()> {
self.vm_mut()
.register_host_object_type(HostObjectTypeDefinition {
rust_type_id: TypeId::of::<T>(),
rust_type_name: type_name::<T>(),
name: definition.name,
methods: definition.methods,
hooks: definition.hooks,
})
.map_err(Error::from_engine)
}
#[cfg(not(feature = "send"))]
pub fn create_object<T: 'static>(&mut self, value: T) -> Result<Object<T>> {
let epoch = self.vm().decision_epoch();
let value = self
.vm_mut()
.create_retained_host_object(value)
.map_err(Error::from_engine)?;
Ok(Object::new(Value::new(value, epoch)))
}
#[cfg(feature = "send")]
pub fn create_object<T: Send + Sync + 'static>(&mut self, value: T) -> Result<Object<T>> {
let epoch = self.vm().decision_epoch();
let value = self
.vm_mut()
.create_retained_host_object(value)
.map_err(Error::from_engine)?;
Ok(Object::new(Value::new(value, epoch)))
}
}
impl Value {
pub fn as_object<T: 'static>(
&self,
lua: &mut Rustia<impl HostSchema>,
) -> Result<Option<Object<T>>> {
let raw = self.raw(lua.vm(), "value handle")?;
Ok(
(lua.vm_mut().host_object_type_id(raw) == Some(TypeId::of::<T>()))
.then(|| Object::new(self.clone())),
)
}
}