rustia 0.2.0

Rustia is a pure-Rust interpreter for embedding standalone Luau in games and tools. Edit scripts without a rebuild and let players write mods. Rustia grew out of a game by Slowchop Studios that needed to script character decisions and replay them on desktop and in a browser.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
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>;

/// A Rust type and the methods scripts may call on it.
///
/// Register the definition once, then create as many objects as needed. Each
/// object keeps the method definition it was created with. Re-registering a
/// type changes future objects; existing objects and detached methods keep
/// their original behavior. Definitions survive decision reset.
///
/// ```
/// use rustia::{ObjectType, Rustia};
/// struct Player { score: i64 }
/// let mut lua = Rustia::builder().build()?;
/// lua.register_object_type(ObjectType::<Player>::new("Player")
///     .method("score", 1, |player: &Player| player.score))?;
/// let player = lua.create_object(Player { score: 42 })?;
/// lua.globals()?.set_live(&mut lua, "player", &player.as_value())?;
/// assert_eq!(lua.eval::<i64>("return player:score()")?, 42);
/// # Ok::<(), rustia::Error>(())
/// ```
///
/// Read-only methods promise replay-stable input, including anything reached
/// through captures or interior mutability. Use capability-specific methods
/// for staged actions or external changes. Opaque Rust payload allocations
/// are outside the VM memory limit, like callback captures. Payload destructors
/// must not panic; the application must avoid ownership cycles in Rust data.
pub struct ObjectType<T: 'static, H: HostSchema = ()> {
    name: String,
    pub(crate) methods: Vec<HostFunctionOp>,
    pub(crate) hooks: HostObjectHooks,
    // Method adapters erase these types after capturing their exact TypeIds.
    marker: Invariant<(T, H)>,
}

impl<T: 'static, H: HostSchema> ObjectType<T, H> {
    /// Starts a method definition for `T`, using `name` in diagnostics.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            methods: Vec::new(),
            hooks: HostObjectHooks::default(),
            marker: PhantomData,
        }
    }

    /// Returns the name used for this definition's registration diagnostics.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the versioned policy used to charge method-call fuel.
    pub const fn fuel_policy(&self) -> crate::RustiaHostFuelPolicy {
        crate::RUSTIA_HOST_FUEL_POLICY
    }

    /// Describes each method before registration, in declaration order.
    ///
    /// The first parameter is the object receiver. Borrowed capability views
    /// are supplied by Rustia and are not counted as guest arguments.
    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,
            })
    }

    /// Adds a read-only method with an explicit host-call fuel cost.
    ///
    /// The receiver comes first, followed by up to eight ordinary or live
    /// arguments. The callback follows the same return and panic rules as
    /// [`crate::HostFunction`]. It receives no VM borrow and cannot re-enter Luau.
    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)
    }

    /// Adds a read-only method with a declared captured-state capability.
    ///
    /// A read-only Rust receiver does not make captured or interior state
    /// deterministic. Declare its actual capability here, or use the typed
    /// context helpers when borrowing per-invocation application state.
    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
    }

    /// Defines `#object` with a typed, read-only payload callback.
    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)
    }

    /// Defines `#object` with an explicit captured-state capability.
    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
    }

    /// Defines generalized iteration with independent owned state per loop.
    ///
    /// The factory borrows the object once. The step mutates only that loop's
    /// state and receives the previous typed control. `None` completes iteration; the first returned value is Luau's
    /// next control value and first loop variable.
    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)
    }

    /// Defines generalized iteration with an explicit captured-state capability.
    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
    }

    /// Adds a method that changes its Rust payload immediately.
    ///
    /// This declares external mutable state and is rejected atomically by
    /// deterministic construction. Payload changes survive script errors and
    /// failed installation; reset drops the payload. Effects on external
    /// application state are not undone by reset.
    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,
        )
    }

    /// Adds an immediately mutable method that also performs nondeterministic effects.
    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
    }
}

/// A live, type-checked handle to a Rust object in one VM and decision epoch.
///
/// Clones share the same object without cloning `T`. Payload references exist
/// only during method callbacks. Reset invalidates every handle and releases
/// the VM's payload ownership even if an old Rust handle is still retained.
pub struct Object<T: 'static> {
    value: Value,
    // A live handle's Rust brand must remain the exact registered payload type.
    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,
        }
    }

    /// Clones the underlying live value for globals, tables, and callback results.
    pub fn as_value(&self) -> Value {
        self.value.clone()
    }

    /// Returns the decision epoch in which this object was retained.
    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))
    }

    /// Calls a method with Rust arguments and copies all returned values into Rust.
    ///
    /// The receiver is supplied automatically. `()` passes no arguments. Use
    /// [`call_method_values`](Self::call_method_values) for object results or
    /// other values that cannot be copied into [`crate::OwnedValue`].
    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<_>>()?,
        )
    }

    /// Calls a method with live arguments and keeps every result live.
    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)
    }

    /// Calls a method within a typed invocation's shared budget and record journal.
    ///
    /// A conversion or execution error discards this call's staged records.
    /// Guest writes and external application changes remain.
    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<_>>()?,
            )
        })
    }

    /// Calls a method with live values inside a typed invocation.
    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)
        })
    }
}

/// A fresh Rust payload returned by a synchronous callback.
///
/// Register `T` before the callback runs. Rustia checks every fresh-object
/// registration and live result before allocating any guest return values.
/// This can be mixed with ordinary and live results in a tuple.
pub struct NewObject<T: 'static> {
    pub(crate) value: T,
}

impl<T: 'static> NewObject<T> {
    /// Moves `value` into a new guest object when the callback returns.
    pub fn new(value: T) -> Self {
        Self { value }
    }
}

impl<H: HostSchema> Rustia<H> {
    /// Registers or replaces the methods used by future objects of `T`.
    ///
    /// The complete definition is validated before publication. A forbidden
    /// method rejects the whole definition, preserving any previous one.
    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)
    }

    /// Moves a payload into a registered object type and retains its live handle.
    ///
    /// `T` need not implement `Clone`, `Send`, or `Sync`. Hardened leaves reject
    /// object construction before allocating guest memory.
    #[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)))
    }

    /// Moves a transferable payload into a registered object type and retains
    /// its live handle.
    #[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 {
    /// Returns a typed Rust-object handle, or `None` for another payload type.
    ///
    /// A stale handle or a handle from another VM returns an error first.
    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())),
        )
    }
}