1use crate::function::adapter::Token;
2use crate::object_method::{IntoMutObjectMethod, IntoObjectIterator, IntoObjectMethod};
3use crate::value::{load_owned_arguments, snapshot_value};
4use crate::{
5 Error, FromRustiaMulti, HostSchema, IntoRustiaMulti, Invocation, OpCapability, Result, Rustia,
6 Value,
7};
8use rustia_vm::{HostFunctionOp, HostObjectHooks, HostObjectTypeDefinition, Value as RawValue};
9use std::any::{type_name, TypeId};
10use std::marker::PhantomData;
11
12type Invariant<T> = PhantomData<fn(T) -> T>;
13
14pub struct ObjectType<T: 'static, H: HostSchema = ()> {
39 name: String,
40 pub(crate) methods: Vec<HostFunctionOp>,
41 pub(crate) hooks: HostObjectHooks,
42 marker: Invariant<(T, H)>,
44}
45
46impl<T: 'static, H: HostSchema> ObjectType<T, H> {
47 pub fn new(name: impl Into<String>) -> Self {
49 Self {
50 name: name.into(),
51 methods: Vec::new(),
52 hooks: HostObjectHooks::default(),
53 marker: PhantomData,
54 }
55 }
56
57 pub fn name(&self) -> &str {
59 &self.name
60 }
61
62 pub const fn fuel_policy(&self) -> crate::RustiaHostFuelPolicy {
64 crate::RUSTIA_HOST_FUEL_POLICY
65 }
66
67 pub fn methods(&self) -> impl Iterator<Item = crate::RustiaHostFunctionInfo<'_>> + '_ {
72 self.methods
73 .iter()
74 .map(|method| crate::RustiaHostFunctionInfo {
75 name: &method.name,
76 fuel_abi_version: crate::RUSTIA_HOST_FUEL_ABI_VERSION,
77 fuel_cost: method.fuel_cost,
78 capability: crate::OpCapability::from_core(method.capability),
79 parameter_count: method.parameter_count,
80 parameter_types: &method.parameter_types,
81 return_types: &method.return_types,
82 fallible: method.fallible,
83 })
84 }
85
86 pub fn method<F, A, R>(self, name: impl Into<String>, fuel_cost: u32, method: F) -> Self
92 where
93 F: IntoObjectMethod<T, A, R>,
94 {
95 self.method_with_capability(name, fuel_cost, OpCapability::Pure, method)
96 }
97
98 pub fn method_with_capability<F, A, R>(
104 mut self,
105 name: impl Into<String>,
106 fuel_cost: u32,
107 capability: OpCapability,
108 method: F,
109 ) -> Self
110 where
111 F: IntoObjectMethod<T, A, R>,
112 {
113 self.methods.push(method.into_object_method(
114 Token,
115 name.into(),
116 fuel_cost,
117 capability.to_core(),
118 ));
119 self
120 }
121
122 pub fn length<F, R>(self, fuel_cost: u32, length: F) -> Self
124 where
125 F: IntoObjectMethod<T, (), R>,
126 {
127 self.length_with_capability(fuel_cost, OpCapability::Pure, length)
128 }
129
130 pub fn length_with_capability<F, R>(
132 mut self,
133 fuel_cost: u32,
134 capability: OpCapability,
135 length: F,
136 ) -> Self
137 where
138 F: IntoObjectMethod<T, (), R>,
139 {
140 self.hooks.length = Some(length.into_object_method(
141 Token,
142 "__len".to_owned(),
143 fuel_cost,
144 capability.to_core(),
145 ));
146 self
147 }
148
149 pub fn iterator<Factory, Step, S, C, R>(
155 self,
156 fuel_cost: u32,
157 factory: Factory,
158 step: Step,
159 ) -> Self
160 where
161 (Factory, Step): IntoObjectIterator<T, S, C, R>,
162 {
163 self.iterator_with_capability(fuel_cost, OpCapability::Pure, factory, step)
164 }
165
166 pub fn iterator_with_capability<Factory, Step, S, C, R>(
168 mut self,
169 fuel_cost: u32,
170 capability: OpCapability,
171 factory: Factory,
172 step: Step,
173 ) -> Self
174 where
175 (Factory, Step): IntoObjectIterator<T, S, C, R>,
176 {
177 let (factory, step) = crate::object_method::adapter::Iterate::into_object_iterator(
178 (factory, step),
179 Token,
180 fuel_cost,
181 capability.to_core(),
182 );
183 self.hooks.iterator = Some(factory);
184 self.hooks.iterator_step = Some(step);
185 self
186 }
187
188 pub fn method_mut<F, A, R>(self, name: impl Into<String>, fuel_cost: u32, method: F) -> Self
195 where
196 F: IntoMutObjectMethod<T, A, R>,
197 {
198 self.mut_method(
199 name.into(),
200 fuel_cost,
201 OpCapability::ReadsExternalMutableState,
202 method,
203 )
204 }
205
206 pub fn method_mut_nondeterministic<F, A, R>(
208 self,
209 name: impl Into<String>,
210 fuel_cost: u32,
211 method: F,
212 ) -> Self
213 where
214 F: IntoMutObjectMethod<T, A, R>,
215 {
216 self.mut_method(
217 name.into(),
218 fuel_cost,
219 OpCapability::NondeterministicEffect,
220 method,
221 )
222 }
223
224 fn mut_method<F, A, R>(
225 mut self,
226 name: String,
227 fuel_cost: u32,
228 capability: OpCapability,
229 method: F,
230 ) -> Self
231 where
232 F: IntoMutObjectMethod<T, A, R>,
233 {
234 self.methods.push(method.into_mut_object_method(
235 Token,
236 name,
237 fuel_cost,
238 capability.to_core(),
239 ));
240 self
241 }
242}
243
244pub struct Object<T: 'static> {
250 value: Value,
251 marker: Invariant<T>,
253}
254
255impl<T: 'static> Clone for Object<T> {
256 fn clone(&self) -> Self {
257 Self::new(self.value.clone())
258 }
259}
260
261impl<T: 'static> std::fmt::Debug for Object<T> {
262 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
263 f.debug_struct("Object")
264 .field("rust_type", &type_name::<T>())
265 .field("value", &self.value)
266 .finish()
267 }
268}
269
270impl<T: 'static> Object<T> {
271 pub(crate) fn new(value: Value) -> Self {
272 Self {
273 value,
274 marker: PhantomData,
275 }
276 }
277
278 pub fn as_value(&self) -> Value {
280 self.value.clone()
281 }
282
283 pub fn decision_epoch(&self) -> u64 {
285 self.value.decision_epoch()
286 }
287
288 fn receiver(&self, vm: &mut rustia_vm::Vm, name: &str) -> Result<(RawValue, RawValue)> {
289 let receiver = self.value.raw(vm, "object handle")?;
290 let method = vm
291 .host_object_method(receiver, name)
292 .map_err(Error::from_engine)?;
293 Ok((receiver, method))
294 }
295
296 pub fn call_method<A: IntoRustiaMulti, R: FromRustiaMulti>(
302 &self,
303 lua: &mut Rustia,
304 name: &str,
305 args: A,
306 ) -> Result<R> {
307 let (receiver, method) = self.receiver(lua.vm_mut(), name)?;
308 let owned = args.into_rustia_multi()?;
309 let (mut raw, _argument_roots) = load_owned_arguments(lua.vm_mut(), &owned)?;
310 raw.insert(0, receiver);
311 let results = lua
312 .vm_mut()
313 .call_retained_function(method, &raw)
314 .map_err(Error::from_engine)?;
315 R::from_rustia_multi(
316 results
317 .into_iter()
318 .map(|v| snapshot_value(lua.vm_mut(), v))
319 .collect::<Result<_>>()?,
320 )
321 }
322
323 pub fn call_method_values(
325 &self,
326 lua: &mut Rustia,
327 name: &str,
328 args: &[Value],
329 ) -> Result<Vec<Value>> {
330 let (receiver, method) = self.receiver(lua.vm_mut(), name)?;
331 let mut raw = vec![receiver];
332 for value in args {
333 raw.push(value.raw(lua.vm(), "object method argument")?);
334 }
335 let results = lua
336 .vm_mut()
337 .call_retained_function(method, &raw)
338 .map_err(Error::from_engine)?;
339 Value::retain_many(lua.vm_mut(), &results)
340 }
341
342 pub fn call_method_in<H: HostSchema, A: IntoRustiaMulti, R: FromRustiaMulti>(
347 &self,
348 invocation: &mut Invocation<'_, H>,
349 name: &str,
350 args: A,
351 ) -> Result<R> {
352 invocation.scoped(|invocation| {
353 let (receiver, method) = self.receiver(invocation.vm, name)?;
354 let owned = args.into_rustia_multi()?;
355 let (mut raw, _argument_roots) = load_owned_arguments(invocation.vm, &owned)?;
356 raw.insert(0, receiver);
357 let results = invocation.call_retained_raw(method, &raw)?;
358 R::from_rustia_multi(
359 results
360 .into_iter()
361 .map(|v| snapshot_value(invocation.vm, v))
362 .collect::<Result<_>>()?,
363 )
364 })
365 }
366
367 pub fn call_method_values_in<H: HostSchema>(
369 &self,
370 invocation: &mut Invocation<'_, H>,
371 name: &str,
372 args: &[Value],
373 ) -> Result<Vec<Value>> {
374 invocation.scoped(|invocation| {
375 let (receiver, method) = self.receiver(invocation.vm, name)?;
376 let mut raw = vec![receiver];
377 for value in args {
378 raw.push(value.raw(invocation.vm, "object method argument")?);
379 }
380 let results = invocation.call_retained_raw(method, &raw)?;
381 Value::retain_many(invocation.vm, &results)
382 })
383 }
384}
385
386pub struct NewObject<T: 'static> {
392 pub(crate) value: T,
393}
394
395impl<T: 'static> NewObject<T> {
396 pub fn new(value: T) -> Self {
398 Self { value }
399 }
400}
401
402impl<H: HostSchema> Rustia<H> {
403 pub fn register_object_type<T: 'static>(&mut self, definition: ObjectType<T, H>) -> Result<()> {
408 self.vm_mut()
409 .register_host_object_type(HostObjectTypeDefinition {
410 rust_type_id: TypeId::of::<T>(),
411 rust_type_name: type_name::<T>(),
412 name: definition.name,
413 methods: definition.methods,
414 hooks: definition.hooks,
415 })
416 .map_err(Error::from_engine)
417 }
418
419 #[cfg(not(feature = "transferable"))]
424 pub fn create_object<T: 'static>(&mut self, value: T) -> Result<Object<T>> {
425 let epoch = self.vm().decision_epoch();
426 let value = self
427 .vm_mut()
428 .create_retained_host_object(value)
429 .map_err(Error::from_engine)?;
430 Ok(Object::new(Value::new(value, epoch)))
431 }
432
433 #[cfg(feature = "transferable")]
436 pub fn create_object<T: Send + Sync + 'static>(&mut self, value: T) -> Result<Object<T>> {
437 let epoch = self.vm().decision_epoch();
438 let value = self
439 .vm_mut()
440 .create_retained_host_object(value)
441 .map_err(Error::from_engine)?;
442 Ok(Object::new(Value::new(value, epoch)))
443 }
444}
445
446impl Value {
447 pub fn as_object<T: 'static>(
451 &self,
452 lua: &mut Rustia<impl HostSchema>,
453 ) -> Result<Option<Object<T>>> {
454 let raw = self.raw(lua.vm(), "value handle")?;
455 Ok(
456 (lua.vm_mut().host_object_type_id(raw) == Some(TypeId::of::<T>()))
457 .then(|| Object::new(self.clone())),
458 )
459 }
460}