Skip to main content

rustia/
object.rs

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
14/// A Rust type and the methods scripts may call on it.
15///
16/// Register the definition once, then create as many objects as needed. Each
17/// object keeps the method definition it was created with. Re-registering a
18/// type changes future objects; existing objects and detached methods keep
19/// their original behavior. Definitions survive decision reset.
20///
21/// ```
22/// use rustia::{ObjectType, Rustia};
23/// struct Player { score: i64 }
24/// let mut lua = Rustia::builder().build()?;
25/// lua.register_object_type(ObjectType::<Player>::new("Player")
26///     .method("score", 1, |player: &Player| player.score))?;
27/// let player = lua.create_object(Player { score: 42 })?;
28/// lua.globals()?.set_live(&mut lua, "player", &player.as_value())?;
29/// assert_eq!(lua.eval::<i64>("return player:score()")?, 42);
30/// # Ok::<(), rustia::Error>(())
31/// ```
32///
33/// Read-only methods promise replay-stable input, including anything reached
34/// through captures or interior mutability. Use capability-specific methods
35/// for staged actions or external changes. Opaque Rust payload allocations
36/// are outside the VM memory limit, like callback captures. Payload destructors
37/// must not panic; the application must avoid ownership cycles in Rust data.
38pub struct ObjectType<T: 'static, H: HostSchema = ()> {
39    name: String,
40    pub(crate) methods: Vec<HostFunctionOp>,
41    pub(crate) hooks: HostObjectHooks,
42    // Method adapters erase these types after capturing their exact TypeIds.
43    marker: Invariant<(T, H)>,
44}
45
46impl<T: 'static, H: HostSchema> ObjectType<T, H> {
47    /// Starts a method definition for `T`, using `name` in diagnostics.
48    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    /// Returns the name used for this definition's registration diagnostics.
58    pub fn name(&self) -> &str {
59        &self.name
60    }
61
62    /// Returns the versioned policy used to charge method-call fuel.
63    pub const fn fuel_policy(&self) -> crate::RustiaHostFuelPolicy {
64        crate::RUSTIA_HOST_FUEL_POLICY
65    }
66
67    /// Describes each method before registration, in declaration order.
68    ///
69    /// The first parameter is the object receiver. Borrowed capability views
70    /// are supplied by Rustia and are not counted as guest arguments.
71    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    /// Adds a read-only method with an explicit host-call fuel cost.
87    ///
88    /// The receiver comes first, followed by up to eight ordinary or live
89    /// arguments. The callback follows the same return and panic rules as
90    /// [`crate::HostFunction`]. It receives no VM borrow and cannot re-enter Luau.
91    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    /// Adds a read-only method with a declared captured-state capability.
99    ///
100    /// A read-only Rust receiver does not make captured or interior state
101    /// deterministic. Declare its actual capability here, or use the typed
102    /// context helpers when borrowing per-invocation application state.
103    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    /// Defines `#object` with a typed, read-only payload callback.
123    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    /// Defines `#object` with an explicit captured-state capability.
131    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    /// Defines generalized iteration with independent owned state per loop.
150    ///
151    /// The factory borrows the object once. The step mutates only that loop's
152    /// state and receives the previous typed control. `None` completes iteration; the first returned value is Luau's
153    /// next control value and first loop variable.
154    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    /// Defines generalized iteration with an explicit captured-state capability.
167    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    /// Adds a method that changes its Rust payload immediately.
189    ///
190    /// This declares external mutable state and is rejected atomically by
191    /// deterministic construction. Payload changes survive script errors and
192    /// failed installation; reset drops the payload. Effects on external
193    /// application state are not undone by reset.
194    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    /// Adds an immediately mutable method that also performs nondeterministic effects.
207    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
244/// A live, type-checked handle to a Rust object in one VM and decision epoch.
245///
246/// Clones share the same object without cloning `T`. Payload references exist
247/// only during method callbacks. Reset invalidates every handle and releases
248/// the VM's payload ownership even if an old Rust handle is still retained.
249pub struct Object<T: 'static> {
250    value: Value,
251    // A live handle's Rust brand must remain the exact registered payload type.
252    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    /// Clones the underlying live value for globals, tables, and callback results.
279    pub fn as_value(&self) -> Value {
280        self.value.clone()
281    }
282
283    /// Returns the decision epoch in which this object was retained.
284    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    /// Calls a method with Rust arguments and copies all returned values into Rust.
297    ///
298    /// The receiver is supplied automatically. `()` passes no arguments. Use
299    /// [`call_method_values`](Self::call_method_values) for object results or
300    /// other values that cannot be copied into [`crate::OwnedValue`].
301    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    /// Calls a method with live arguments and keeps every result live.
324    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    /// Calls a method within a typed invocation's shared budget and record journal.
343    ///
344    /// A conversion or execution error discards this call's staged records.
345    /// Guest writes and external application changes remain.
346    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    /// Calls a method with live values inside a typed invocation.
368    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
386/// A fresh Rust payload returned by a synchronous callback.
387///
388/// Register `T` before the callback runs. Rustia checks every fresh-object
389/// registration and live result before allocating any guest return values.
390/// This can be mixed with ordinary and live results in a tuple.
391pub struct NewObject<T: 'static> {
392    pub(crate) value: T,
393}
394
395impl<T: 'static> NewObject<T> {
396    /// Moves `value` into a new guest object when the callback returns.
397    pub fn new(value: T) -> Self {
398        Self { value }
399    }
400}
401
402impl<H: HostSchema> Rustia<H> {
403    /// Registers or replaces the methods used by future objects of `T`.
404    ///
405    /// The complete definition is validated before publication. A forbidden
406    /// method rejects the whole definition, preserving any previous one.
407    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    /// Moves a payload into a registered object type and retains its live handle.
420    ///
421    /// `T` need not implement `Clone`, `Send`, or `Sync`. Hardened leaves reject
422    /// object construction before allocating guest memory.
423    #[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    /// Moves a transferable payload into a registered object type and retains
434    /// its live handle.
435    #[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    /// Returns a typed Rust-object handle, or `None` for another payload type.
448    ///
449    /// A stale handle or a handle from another VM returns an error first.
450    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}