Skip to main content

Rustia

Struct Rustia 

Source
pub struct Rustia<C: HostSchema = ()> { /* private fields */ }
Expand description

Owns one Luau interpreter and the Rust functions installed in it.

Create one with builder, then use load to run scripts. Globals and script objects persist between calls until reset_decision; an ordinary evaluation error does not undo earlier script mutations.

use rustia::Rustia;

let mut vm = Rustia::builder().build()?;
vm.insert_global("name", "Ada")?;
let greeting: String = vm.eval("return 'Hello, ' .. name")?;
assert_eq!(greeting, "Hello, Ada");

§Threads

By default, an interpreter and its live handles are thread-affine. Create each interpreter in the worker that will run it. Enabling the Cargo feature transferable makes the interpreter and its live handles Send when their typed host record and Rust payload types are also transferable. Move the whole idle interpreter and its handles together; every execution operation still needs exclusive &mut access, so this does not permit concurrent entry. Transferable service closures require Send, entropy providers require Fn + Send + Sync, and object payloads require Send + Sync. Host-owned CompiledModule and CompiledEntry values can always be reused across interpreters without sharing their guest state.

§Typed host contexts

The default Rustia<()> needs no per-call host context. For applications that lend state to a script for one call, Rustia<H> stores a lifetime-independent HostSchema and registered callbacks. Each execution borrows a fresh HostContext<H> through invoke or invoke_into.

Why typed hosts require an invocation

Typed hosts cannot bypass that authority boundary with the context-free execution helpers:

ⓘ
use rustia::{HostSchema, Rustia};

struct Host;
impl HostSchema for Host {
    type Input = ();
    type Slots = ();
    type External = ();
    type Effect = ();
    type SlotWrite = ();
    type Record = ();
}

fn bypass(mut rustia: Rustia<Host>) {
    let _: i32 = rustia.eval("return 42").unwrap();
}

Implementations§

Source§

impl<C: HostSchema> Rustia<C>

Source

pub fn create_function<F, S>(&mut self, function: F) -> Result<Function>

Creates a live Rust function without installing a global binding.

Script references keep the callback alive after its Rust handle is dropped. Collection can release it once all references are gone. Decision reset invalidates every handle and releases the VM’s ownership of the callback. Hardened leaves reject this constructor.

Use register_function for a global function that should be restored after reset.

Source

pub fn create_named_function<F, S>( &mut self, debug_name: impl Into<String>, function: F, ) -> Result<Function>

Creates a live Rust function with a name used in error reports. The name does not install a binding or change callback ownership.

Source

pub fn register_function<F, S>( &mut self, name: impl Into<String>, function: F, ) -> Result<()>

Installs a global Rust function and restores its binding after decision reset.

Replacing the registration releases the old configuration’s ownership. Existing script references to the old function still work until reset. Registration requires an idle VM without an active guest-state savepoint.

Source§

impl<H: HostSchema> Rustia<H>

Source

pub fn register_object_type<T: 'static>( &mut self, definition: ObjectType<T, H>, ) -> Result<()>

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.

Source

pub fn create_object<T: 'static>(&mut self, value: T) -> Result<Object<T>>

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.

Source§

impl<C> Rustia<C>
where C: HostSchema,

Source

pub fn memory_stats(&mut self) -> VmMemoryStats

Reports live and reserved memory owned by the interpreter.

These are logical accounting totals, not process memory usage. Captured Rust callback state is outside these totals; diagnostic source retention has a separate budget. See VmMemoryStats for the totals and optional instruction-boundary peaks.

Source

pub fn diagnostic_source_bytes(&self) -> usize

Returns the bytes charged for retained diagnostic source snapshots.

This host-side retention is separate from the script memory limit.

Source

pub fn execution_profile(&self) -> RustiaExecutionProfile

Returns the selected language profile and guest surface.

This descriptor does not include budgets, services, or host callbacks.

Source

pub fn settings(&self) -> Settings

Returns the interpreter’s effective application settings.

Use Settings::identity_bytes when binding configuration to a replay or package identity. Engine implementation controls remain private.

Source

pub fn decision_epoch(&self) -> u64

Returns the generation used to validate live handles.

It starts at zero and advances when reset_decision succeeds.

Source

pub fn reset_decision(&mut self) -> Result<()>

Discards all guest state and begins a fresh decision epoch.

VM configuration, services, extensions, and installed host functions persist. Globals inserted with insert_global and insert_serde are decision inputs and must be rebound afterward. Every prior Value, Table, Function, and Exports handle is invalidated, while host-owned CompiledModule and CompiledEntry values remain reusable. A hardened-leaf VM preserves its sealed immutable environment in place and discards every decision-local allocation after that seal.

Replay protocols must record RUSTIA_DECISION_RESET_ABI_VERSION. Reset requires an idle interpreter; attempting it during execution fails.

Source

pub fn invoke<'rustia, Return, Func>( &'rustia mut self, context: &mut dyn HostContext<C>, limits: InvocationLimits, operation: Func, ) -> Result<InvocationOutcome<'rustia, Return, C::Record>>
where Func: for<'call> FnOnce(&mut Invocation<'call, C>) -> Result<Return>,

Runs one typed, fuel-bounded host invocation and exposes its committed deterministic records from Rustia’s reusable journal.

Failure rolls back staged records, not ordinary guest heap/global mutation. Call reset_decision when the host requires a fresh guest-state decision boundary.

A panic in operation itself is ordinary caller-side Rust control flow: the private journal is dropped without publication and the panic continues unwinding; it is not translated into HostPanicked or VM poisoning. Panics from callbacks invoked by the VM are contained and poison the VM.

Source

pub fn invoke_into<Return, Func>( &mut self, context: &mut dyn HostContext<C>, limits: InvocationLimits, records: &mut Vec<C::Record>, operation: Func, ) -> Result<InvocationReceipt<Return>>
where Func: for<'call> FnOnce(&mut Invocation<'call, C>) -> Result<Return>,

Runs one typed invocation and publishes its committed records into a caller-owned lane. Capacity is reserved before guest execution, so the final append cannot fail or allocate.

Source

pub fn invoke_entry_into<Return>( &mut self, context: &mut dyn HostContext<C>, limits: InvocationLimits, records: &mut Vec<C::Record>, entry: &CompiledEntry, ) -> Result<InvocationReceipt<Return>>
where Return: FromRustia,

Executes one precompiled stateless entry, publishes its committed records, and resets the decision epoch before returning.

Reset runs after success, returned failure, and an unwinding panic from guest-value conversion or a contained host callback. The original panic resumes after reset. If reset itself fails after a normal return, any records published by the invocation are removed from the caller lane and the reset error wins. panic = "abort" builds cannot unwind and therefore cannot provide panic containment. This is the complete authoritative-leaf lifecycle used by worker lanes.

Source

pub fn insert_global<T>( &mut self, name: impl AsRef<str>, value: T, ) -> Result<()>
where T: IntoRustia,

Copies Rust data into a script global, replacing any existing value.

Uses IntoRustia for conversion. The value is available to later scripts until replaced or reset_decision clears it. Conversion errors and script memory-limit failures are returned as Error. To insert a live handle without copying it, use Table::set_live on globals.

vm.insert_global("scores", vec![10, 20, 30])?;
let first: i32 = vm.eval("return scores[1]")?;
assert_eq!(first, 10);
Source

pub fn insert_serde<T>( &mut self, name: impl AsRef<str>, value: &T, ) -> Result<()>
where T: Serialize + ?Sized,

Serializes Rust data into a script global, replacing any existing value.

This copies the data; later script changes do not modify the Rust input. Serialization and script memory-limit failures are returned as Error. Like insert_global, the binding is cleared by reset.

Source

pub fn globals(&mut self) -> Result<Table>

Returns a live handle to the interpreter’s globals table.

Reads and writes through Table preserve identity and are visible to subsequently executed guest code. Like ordinary global inputs, these mutations are decision-local and are discarded by reset_decision. Hardened leaves reject this mutable authority.

Source

pub fn create_table(&mut self) -> Result<Table>

Creates an empty live table in this interpreter.

The table and its root participate in the logical-live memory quota as one admission. Hardened leaves reject live table construction.

let settings = vm.create_table()?;
settings.set(&mut vm, "volume", 0.5)?;
vm.globals()?.set_live(&mut vm, "settings", &settings.as_value())?;
let volume: f64 = vm.eval("return settings.volume")?;
assert_eq!(volume, 0.5);
Source

pub fn create_vector(&mut self, x: f32, y: f32, z: f32) -> Result<Value>

Creates an immutable live Luau vector in this interpreter.

The vector and its root participate in the logical-live memory quota as one admission. Components use Luau’s canonical f32 vector semantics. The returned handle belongs to this VM and decision epoch like every other live Value.

let direction = vm.create_vector(1.5, -2.0, 3.0)?;
vm.globals()?.set_live(&mut vm, "direction", &direction)?;
let x: f64 = vm.eval("return direction.x")?;
assert_eq!(x, 1.5);
Source

pub fn add_pure<Func, Args, Return>( &mut self, name: impl Into<String>, fuel_cost: u32, function: Func, ) -> Result<()>
where Func: IntoHostFunction<Args, Return>,

Registers a context-free Fn(A, B, ...) -> R with an explicit fuel charge. The registration method fixes the capability to Pure; Result<R> creates a fallible host call.

Source

pub fn add_input<Func, Args, Return>( &mut self, name: impl Into<String>, fuel_cost: u32, function: Func, ) -> Result<()>
where Func: IntoInputFunction<C, Args, Return>,

Registers a deterministic input reader with closure shape for<'a> Fn(Input<'a, C>, A, B, ...) -> R.

Source

pub fn add_slot_read<Func, Args, Return>( &mut self, name: impl Into<String>, fuel_cost: u32, function: Func, ) -> Result<()>
where Func: IntoSlotReadFunction<C, Args, Return>,

Registers a deterministic slot reader with closure shape for<'a> Fn(Slots<'a, C>, A, B, ...) -> R.

Source

pub fn add_effect<Func, Args, Return>( &mut self, name: impl Into<String>, fuel_cost: u32, function: Func, ) -> Result<()>
where Func: IntoEffectFunction<C, Args, Return>,

Registers a deterministic effect recorder with closure shape for<'a> Fn(Effects<'a, C>, A, B, ...) -> R.

Source

pub fn add_slot_write<Func, Args, Return>( &mut self, name: impl Into<String>, fuel_cost: u32, function: Func, ) -> Result<()>
where Func: IntoSlotWriteFunction<C, Args, Return>,

Registers a deterministic slot-write recorder with closure shape for<'a> Fn(SlotWrites<'a, C>, A, B, ...) -> R.

Source

pub fn add_external<Func, Args, Return>( &mut self, name: impl Into<String>, fuel_cost: u32, function: Func, ) -> Result<()>
where Func: IntoExternalFunction<C, Args, Return>,

Registers an external-state callback with closure shape for<'a> Fn(HostMut<'a, C>, A, B, ...) -> R.

Deterministic profiles reject it before installation, and mutations through HostMut are outside Rustia’s record rollback.

Source

pub fn add_nondeterministic<Func, Args, Return>( &mut self, name: impl Into<String>, fuel_cost: u32, function: Func, ) -> Result<()>
where Func: IntoExternalFunction<C, Args, Return>,

Registers an explicitly nondeterministic HostMut callback.

Deterministic profiles reject it before installation.

Source

pub fn install_host_module(&mut self, module: HostModule<C>) -> Result<()>

Installs a namespaced collection of capability-checked host functions.

Installation is fail-closed: if validation or VM binding fails, no callable namespace or typed dispatcher bindings are retained.

Source§

impl Rustia<()>

Source

pub fn compile_module( source_name: impl Into<String>, source: &str, ) -> Result<CompiledModule>

Compiles a script once for later installation in one or more interpreters.

Compilation does not run the script or change a VM. source_name labels diagnostics and identifies the caller to the module resolver for require. Invalid source returns a parse or compilation error. Call install to run the compiled module and retain its exports. For PUC Lua 5.1 compatibility, use compile_module_with_profile.

Source

pub fn compile_module_with_profile( source_name: impl Into<String>, source: &str, profile: Profile, ) -> Result<CompiledModule>

Compiles a reusable module with code generation appropriate for profile. Use this when the module will be installed into a VM whose profile is known ahead of time. source_name labels diagnostics and nested require resolver referrers.

Source

pub fn compile_module_bytes( source_name: impl Into<String>, source: &[u8], ) -> Result<CompiledModule>

Compiles bytes with the standard (source-order) table-constructor write order. source_name labels diagnostics and nested require resolver referrers. Profile::Puc51Compat hosts need PUC write order instead; compile through the instance load builder (which reads the VM profile) or use compile_module_bytes_with_profile.

Source

pub fn compile_module_bytes_with_profile( source_name: impl Into<String>, source: &[u8], profile: Profile, ) -> Result<CompiledModule>

Byte-oriented form of compile_module_with_profile.

Source

pub fn compile_entry( source_name: impl Into<String>, source: &str, ) -> Result<CompiledEntry>

Compiles a chunk whose top-level body is invoked directly on each decision without installing exports or retaining bytecode in the VM.

Stateless entries cannot contain nested function prototypes. Inputs and outputs should cross the typed host context, and the source should return its decision value directly.

Compiles with the standard (source-order) table-constructor write order; see compile_module_bytes.

Source

pub fn builder() -> RustiaBuilder

Returns the standard preset: reproducible-by-default, with a real stdout print sink on native targets.

Source

pub fn load<'rustia, 'source, S>( &'rustia mut self, source: &'source S, ) -> Chunk<'rustia, 'source>
where S: AsRef<[u8]> + ?Sized,

Prepares Luau source text or bytes to run in this interpreter.

Building the chunk is inert: parsing, compilation, VM allocation, and execution begin only when a terminal operation is called. Use Chunk::source_name to label errors, then choose Chunk::eval, Chunk::exec, or Chunk::install. The source only needs to live until that operation finishes; returned values do not borrow it.

let answer: i32 = vm
    .load("return 6 * 7")
    .source_name("answer.luau")
    .eval()?;
assert_eq!(answer, 42);
Source

pub fn eval<T>(&mut self, source: impl AsRef<[u8]>) -> Result<T>
where T: FromRustia,

Evaluates source and converts its first result through FromRustia.

Shorthand for load(source).eval(). Use load to give the source a name or select its environment. See Chunk::eval for conversion and failure behavior.

Source

pub fn eval_serde<T>(&mut self, source: impl AsRef<[u8]>) -> Result<T>

Evaluates source and deserializes its first result directly from the VM.

Shorthand for load(source).eval_serde(); see Chunk::eval_serde.

Source

pub fn exec(&mut self, source: impl AsRef<[u8]>) -> Result<()>

Executes source for side effects and discards its result.

Shorthand for load(source).exec(); see Chunk::exec.

Source

pub fn install(&mut self, module: &CompiledModule) -> Result<Exports>

Runs a compiled module in a fresh environment and retains its exports.

The environment inherits VM globals. A failed installation restores prior guest state; external host callback and module-resolver effects cannot be undone. Previously installed exports remain usable until reset. See Chunk::install to compile and install source in one step.

let module = Rustia::compile_module(
    "greeting.luau",
    "return { greet = function(name) return 'Hello, ' .. name end }",
)?;
let mut vm = Rustia::builder().build()?;
let exports = vm.install(&module)?;
let greet = exports.function(&mut vm, "greet")?;
let greeting: String = greet.call(&mut vm, ("Ada",))?;
assert_eq!(greeting, "Hello, Ada");
Source§

impl Rustia<()>

Source

pub fn add_fn<Func, Args, Return>( &mut self, name: impl Into<String>, function: Func, ) -> Result<()>
where Func: IntoHostFunction<Args, Return>,

Registers a Rust function as a script global.

Arguments and results are converted automatically. Return Result<T> from the callback to report a script-visible error. A call costs one fuel unit in addition to guest instructions; use add_fn_with to select another cost or declare captured-state effects.

The callback must be Fn + Send + Sync + 'static. This helper declares it pure, so captured state must honour that promise. The registration survives reset_decision. For a live function value instead of a global binding, use create_function.

vm.add_fn("divide", |a: f64, b: f64| -> rustia::Result<f64> {
    if b == 0.0 {
        return Err(rustia::Error::embed("division by zero"));
    }
    Ok(a / b)
})?;
let quotient: f64 = vm.eval("return divide(84, 2)")?;
assert_eq!(quotient, 42.0);
Source

pub fn add_pure_fn<Func, Args, Return>( &mut self, name: impl Into<String>, function: Func, ) -> Result<()>
where Func: IntoHostFunction<Args, Return>,

Registers a pure callback; equivalent to add_fn.

Source

pub fn add_input_fn<Func, Args, Return>( &mut self, name: impl Into<String>, function: Func, ) -> Result<()>
where Func: IntoHostFunction<Args, Return>,

Registers a callback declared to read deterministic captured input.

The callback receives ordinary arguments. For borrowed per-invocation input in a typed host, use add_input.

Source

pub fn add_slot_read_fn<Func, Args, Return>( &mut self, name: impl Into<String>, function: Func, ) -> Result<()>
where Func: IntoHostFunction<Args, Return>,

Registers a callback declared to read captured slot state.

For a borrowed Slots view in a typed host, use add_slot_read.

Source

pub fn add_slot_write_fn<Func, Args, Return>( &mut self, name: impl Into<String>, function: Func, ) -> Result<()>
where Func: IntoHostFunction<Args, Return>,

Registers a callback declared to produce slot-write effects.

Captured Rust mutations are not rolled back. For a transactional SlotWrites journal, use add_slot_write.

Source

pub fn add_effect_fn<Func, Args, Return>( &mut self, name: impl Into<String>, function: Func, ) -> Result<()>
where Func: IntoHostFunction<Args, Return>,

Registers a callback declared to produce deterministic effects.

Captured Rust mutations are not rolled back. For a transactional Effects journal, use add_effect.

Source

pub fn add_external_state_fn<Func, Args, Return>( &mut self, name: impl Into<String>, function: Func, ) -> Result<()>
where Func: IntoHostFunction<Args, Return>,

Registers a callback declared to access mutable external state.

Deterministic profiles reject this capability. For a borrowed HostMut view in a typed host, use add_external.

Source

pub fn add_nondeterministic_fn<Func, Args, Return>( &mut self, name: impl Into<String>, function: Func, ) -> Result<()>
where Func: IntoHostFunction<Args, Return>,

Registers a callback declared to have nondeterministic effects.

Deterministic profiles reject this capability. Captured Rust effects are outside installation and invocation rollback.

Source

pub fn add_fn_with<Func, Args, Return>( &mut self, name: impl Into<String>, fuel_cost: u32, capability: OpCapability, function: Func, ) -> Result<()>
where Func: IntoHostFunction<Args, Return>,

Registers a callback with an explicit fuel cost and capability.

A zero fuel cost or a capability forbidden by the selected profile fails before registration. The capability describes captured host behavior; it does not restrict what a Rust closure can do. See add_fn for the callback’s conversion and lifetime rules.

Source

pub fn install_extension(&mut self, extension: RustiaExtension) -> Result<()>

Installs a collection of host functions and modules atomically.

Validation or binding failure leaves existing registrations unchanged. Use RustiaExtension to assemble a reusable application API.

Trait Implementations§

Source§

impl Default for Rustia

Source§

fn default() -> Self

Creates the standard preset, matching Rustia::builder.

Auto Trait Implementations§

§

impl<C> Freeze for Rustia<C>

§

impl<C = ()> !RefUnwindSafe for Rustia<C>

§

impl<C = ()> !Send for Rustia<C>

§

impl<C = ()> !Sync for Rustia<C>

§

impl<C> Unpin for Rustia<C>
where <C as HostSchema>::Record: Unpin,

§

impl<C> UnsafeUnpin for Rustia<C>

§

impl<C = ()> !UnwindSafe for Rustia<C>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.