Skip to main content

rustia/
lib.rs

1//! Embed Luau in Rust games and tools.
2//! Edit scripts without a rebuild and let players write mods.
3//!
4//! Rustia grew out of a game by [Slowchop Studios](https://slowchop.com/) that
5//! needed to script character decisions and replay them on desktop and in a
6//! browser.
7//!
8//! Rustia is a pure-Rust interpreter for standalone Luau. Use
9//! [`RustiaBuilder::deterministic`] when the same script, seed, and inputs need
10//! to produce the same decisions.
11//!
12//! # A first script
13//!
14//! Rust gives Luau a score and a function called `double`. Luau calls the function
15//! and returns the new score to Rust. In a [new Cargo app], put this in `src/main.rs`.
16//!
17//! ```rust
18//! use rustia::Rustia;
19//!
20//! fn main() -> rustia::Result<()> {
21//!     let mut vm = Rustia::builder().build()?;
22//!     vm.insert_global("base_score", 21)?;
23//!     vm.add_fn("double", |value: f64| value * 2.0)?;
24//!
25//!     let score: f64 = vm
26//!         .load("return double(base_score)")
27//!         .source_name("score.luau")
28//!         .eval()?;
29//!
30//!     println!("The score is {score}");
31//!     assert_eq!(score, 42.0);
32//!     Ok(())
33//! }
34//! ```
35//!
36//! Run `cargo run`. It prints `The score is 42`.
37//!
38//! # Find what you need
39//!
40//! | I want to… | Start here |
41//! | --- | --- |
42//! | Run a script or get a result back | [`Chunk::exec`] runs it. [`Chunk::eval`] returns a Rust value. |
43//! | Pass data from Rust to Luau | [`Rustia::insert_global`] sets a named value. [`Rustia::insert_serde`] passes a struct or collection. |
44//! | Call a Luau function from Rust | [`Chunk::install`] loads its module. [`Exports::function`] looks up the function for [`Function::call`]. |
45//! | Change a script while the app runs | Keep the old functions until the edit installs successfully. See the [hot reload example]. |
46//! | Show where a script failed | Give the script a name with [`Chunk::source_name`] and display [`Error::report`]. |
47//! | Run Luau in a browser | Follow the [browser setup] or build the [bare WebAssembly example]. |
48//!
49//! Start with [`Rustia::builder`] for everyday scripting. Use [`RustiaBuilder::live`]
50//! when a script needs the current time or a fresh random seed. To limit a script’s
51//! work or memory, set [`RustiaBuilder::fuel`] or [`RustiaBuilder::memory_limit_bytes`].
52//!
53//! # Keeping state across script edits
54//!
55//! Keep the running app's state in Rust, or save the Luau values you want to
56//! carry forward and pass them to the replacement script. The embedder decides
57//! which values to keep. A newly created script local starts with its initializer.
58//!
59//! Use [`Chunk::install`] to try the replacement, then switch to the new exports
60//! after it succeeds. If installation fails, Rustia rolls back guest changes and
61//! the app can keep using the previous functions. See the [hot reload example].
62//!
63// Keep comparison rows together in Rustdoc's horizontally scrollable table.
64#![doc = "<style>table:has(a[href='#luau-note-1']) :is(td, th) { white-space: nowrap; }</style>"]
65#![doc = include_str!("../compare.md")]
66//!
67//! # Performance
68//!
69//! The chart compares five workloads on Linux x86-64. Each language has its own
70//! version. Roto's array workload uses a handwritten quadratic sort. It uses a
71//! list for sparse lookups and an ordinary function for the closure test.
72//! Compare times within a column. Lower is better.
73//! The upstream C++ Luau interpreter ran all five faster than Rustia in this run.
74//!
75#![doc = include_str!("../performance.svg")]
76//!
77//! These October 2026 measurements cover scripts already running. Small timing
78//! differences may vary between runs. [Full results] · [Benchmark limitations]
79//!
80//! # More about embedding
81//!
82//! <details>
83//! <summary>Read a Luau table from Rust</summary>
84//!
85//! Use [`Chunk::eval`] to copy a value into Rust, or [`Chunk::eval_serde`] to read a
86//! table into a Rust struct. These copies stay usable after the interpreter is gone.
87//! Copying strings into a Rust `String` requires UTF-8. Tables with cycles cannot
88//! be copied, and copying the same table twice makes two independent values.
89//!
90//! Use [`Chunk::eval_live`] to keep a table with shared references, cycles, or
91//! binary strings in Luau. A live [`Value`], [`Table`], [`Function`], or [`Exports`]
92//! belongs to one interpreter. Resetting it with [`Rustia::reset_decision`] invalidates
93//! those handles. See the [live values example] for a table that refers to itself.
94//!
95//! </details>
96//!
97//! <details>
98//! <summary>Give scripts access to Rust functions and objects</summary>
99//!
100//! Use [`Rustia::add_fn`] for a calculation such as `double`. Rustia trusts that
101//! the function only uses its inputs. In the standard and live environments,
102//! scripts can change a Rust object immediately. See the [mutable object example].
103//!
104//! If a callback needs data borrowed for just one request or frame, pass it in a
105//! [`HostContext`] with [`Rustia::invoke`]. The [typed invocation example] shows how.
106//! For deterministic replay, let scripts propose changes for Rust to apply
107//! after a successful call. See the [game object example]. [`HostFunction`] documents callback permissions
108//! and the rules for data captured by a closure.
109//!
110//! </details>
111//!
112//! <details>
113//! <summary>Keep using the interpreter after a script fails</summary>
114//!
115//! | What you ran | What happens when an error reaches Rust |
116//! | --- | --- |
117//! | A script or function with [`Chunk::eval`], [`Chunk::exec`], or [`Function::call`] | Changes the script already made stay in the interpreter, even if converting the result to Rust failed. |
118//! | A replacement module with [`Chunk::install`] | Rustia restores the previous script state. You can keep calling the old functions. |
119//! | A call with [`Rustia::invoke`] or [`Rustia::invoke_into`] | Rust receives none of the changes the script queued for it. Changes made in Luau still survive, except those rolled back by [`Invocation::install`]. |
120//! | A stateless decision with [`Rustia::invoke_entry_into`] | Rustia discards the queued changes and resets the script state. It also resets after success. Rust can reuse the [`CompiledEntry`] for the next call. See the [stateless decision example]. |
121//!
122//! A Luau `pcall` can catch a script error. If the outer invocation succeeds, it
123//! can still deliver changes queued by earlier successful callbacks. Resetting
124//! the interpreter clears its script state and releases the Rust objects it holds.
125//! Files a callback wrote and changes it made to your application’s state persist.
126//!
127//! An ordinary script error lets you keep using the interpreter. If Rustia catches
128//! a panic in a Rust callback, call [`Rustia::reset_decision`] before running more
129//! Luau. For exhausted limits, [`VmError::kind`] identifies the resource.
130//!
131//! </details>
132//!
133//! For more, [browse the Rust examples] or read about [moving an idle interpreter
134//! to another thread](struct.Rustia.html#threads).
135//!
136//! [new Cargo app]: https://github.com/slowchop/rustia#try-it
137//! [hot reload example]: https://github.com/slowchop/rustia/blob/main/crates/rustia/examples/hot_reload.rs
138//! [browser setup]: https://github.com/slowchop/rustia/blob/main/demos/web-live/README.md
139//! [bare WebAssembly example]: https://github.com/slowchop/rustia/blob/main/demos/live-wasm/README.md
140//! [full results]: https://github.com/slowchop/rustia/blob/da1b8e546d4108d657d875b60ad28dffb354a974/bench/RESULTS.md
141//! [benchmark limitations]: https://github.com/slowchop/rustia/blob/da1b8e546d4108d657d875b60ad28dffb354a974/bench/CLAIMS.md
142//! [live values example]: https://github.com/slowchop/rustia/blob/main/crates/rustia/examples/live_values.rs
143//! [mutable object example]: https://github.com/slowchop/rustia/blob/main/crates/rustia/examples/mutable_objects.rs
144//! [typed invocation example]: https://github.com/slowchop/rustia/blob/main/crates/rustia/examples/typed_invocation.rs
145//! [game object example]: https://github.com/slowchop/rustia/blob/main/crates/rustia/examples/game_objects.rs
146//! [stateless decision example]: https://github.com/slowchop/rustia/blob/main/crates/rustia/examples/hardened_decision.rs
147//! [browse the Rust examples]: https://github.com/slowchop/rustia/tree/main/crates/rustia/examples
148
149#[cfg(doctest)]
150mod brand_contract;
151mod chunk;
152mod diagnostic;
153mod diagnostic_data;
154#[cfg(test)]
155mod engine_boundary_tests;
156mod error;
157mod extension_api;
158mod function;
159mod host_function;
160mod invocation;
161mod live_value;
162mod macros;
163mod object;
164mod object_context;
165mod object_conversion;
166mod object_method;
167mod profile;
168mod runtime_error;
169mod serde_value;
170mod settings;
171mod source_error;
172mod source_map;
173mod value;
174
175use invocation::TypedHostDispatcher;
176use rustia_compiler::{compile_with_options, CompileOptions};
177use rustia_vm::{HardenedLeafProgram, Program, Vm};
178use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
179
180#[cfg(test)]
181extern crate self as rustia;
182
183pub use chunk::Chunk;
184pub use diagnostic::DiagnosticReason;
185pub use diagnostic::{
186    Diagnostic, DiagnosticFrame, DiagnosticLimits, DiagnosticSpan, ErrorReport, SourceSnapshot,
187};
188pub use error::{Error, ErrorKind};
189pub use extension_api::{
190    ModuleSource, RustiaBuilder, RustiaExecutionProfile, RustiaExtension, RustiaHostFuelPolicy,
191    RustiaHostFunctionInfo, ServiceClock, ServiceEntropy, ServiceModuleResolver,
192    RUSTIA_DEFAULT_HOST_FUNCTION_FUEL, RUSTIA_HOST_FUEL_ABI_VERSION, RUSTIA_HOST_FUEL_POLICY,
193    RUSTIA_MIN_HOST_FUNCTION_FUEL,
194};
195pub use function::{
196    Exports, FromHostArgument, Function, IntoHostFunction, IntoHostReturn, IntoHostValue,
197};
198pub use host_function::{HostFunction, IntoHostFunctionDefinition};
199pub use invocation::{
200    Effects, HostContext, HostModule, HostMut, HostSchema, Input, IntoEffectFunction,
201    IntoExternalFunction, IntoInputFunction, IntoSlotReadFunction, IntoSlotWriteFunction,
202    Invocation, InvocationChunk, InvocationLimits, InvocationOutcome, InvocationReceipt,
203    InvocationUsage, SlotWrites, Slots,
204};
205pub use live_value::{Table, Value, ValueType};
206pub use object::{NewObject, Object, ObjectType};
207pub use object_context::{
208    IntoEffectObjectMethod, IntoExternalMutObjectMethod, IntoExternalObjectMethod,
209    IntoInputObjectMethod, IntoSlotReadObjectMethod, IntoSlotWriteObjectMethod,
210};
211pub use object_method::{IntoMutObjectMethod, IntoObjectIterator, IntoObjectMethod};
212pub use profile::{GuestSurface, OpCapability, Profile};
213pub use runtime_error::{VmError, VmErrorKind, VmErrorMessage};
214/// Version of the decision-reset lifecycle contract.
215pub const RUSTIA_DECISION_RESET_ABI_VERSION: u32 = rustia_vm::DECISION_RESET_ABI_VERSION;
216/// Version of the hardened-leaf guest environment contract.
217pub const RUSTIA_HARDENED_LEAF_GUEST_ABI_VERSION: u32 = rustia_vm::HARDENED_LEAF_GUEST_ABI_VERSION;
218/// Version of installation rollback and publication behavior.
219pub const RUSTIA_INSTALL_TRANSACTION_ABI_VERSION: u32 = rustia_vm::INSTALL_TRANSACTION_ABI_VERSION;
220/// Version of module resolution, suspension, and cache behavior.
221///
222/// Replay protocols should record this value and their resolver's own content
223/// identity. See [`ServiceModuleResolver`] for loading and failure rules.
224pub const RUSTIA_MODULE_RESOLUTION_ABI_VERSION: u32 = rustia_vm::MODULE_RESOLUTION_ABI_VERSION;
225pub use serde_value::SerdeValueError;
226pub use settings::{ServiceDeterminism, Settings, VmMemoryStats};
227pub use source_error::{CompileError, LexError, ParseError, SourceError, UnclosedBlock};
228pub use source_map::SourceMap;
229pub use value::{
230    FromRustia, FromRustiaMulti, IntoRustia, IntoRustiaMulti, OwnedKey, OwnedTable, OwnedValue,
231};
232
233/// Owns one Luau interpreter and the Rust functions installed in it.
234///
235/// Create one with [`builder`](Self::builder), then use [`load`](Self::load) to
236/// run scripts. Globals and script objects persist between calls until
237/// [`reset_decision`](Self::reset_decision); an ordinary evaluation error does
238/// not undo earlier script mutations.
239///
240/// ```
241/// use rustia::Rustia;
242///
243/// let mut vm = Rustia::builder().build()?;
244/// vm.insert_global("name", "Ada")?;
245/// let greeting: String = vm.eval("return 'Hello, ' .. name")?;
246/// assert_eq!(greeting, "Hello, Ada");
247/// # Ok::<(), rustia::Error>(())
248/// ```
249///
250/// # Threads
251///
252/// By default, an interpreter and its live handles are thread-affine. Create
253/// each interpreter in the worker that will run it. Enabling the Cargo feature
254/// `transferable` makes the interpreter and its live handles `Send` when their
255/// typed host record and Rust payload types are also transferable. Move the
256/// whole idle interpreter and its handles together; every execution operation
257/// still needs exclusive `&mut` access, so this does not permit concurrent entry.
258/// Transferable service closures require `Send`, entropy providers require
259/// `Fn + Send + Sync`, and object payloads require `Send + Sync`. Host-owned
260/// [`CompiledModule`] and [`CompiledEntry`] values can
261/// always be reused across interpreters without sharing their guest state.
262///
263/// # Typed host contexts
264///
265/// The default `Rustia<()>` needs no per-call host context. For applications that
266/// lend state to a script for one call, `Rustia<H>` stores a lifetime-independent
267/// [`HostSchema`] and registered callbacks. Each execution borrows a fresh
268/// [`HostContext<H>`] through
269/// [`invoke`](Self::invoke) or [`invoke_into`](Self::invoke_into).
270///
271/// <details>
272/// <summary>Why typed hosts require an invocation</summary>
273///
274/// Typed hosts cannot bypass that authority boundary with the context-free
275/// execution helpers:
276///
277/// ```compile_fail
278/// use rustia::{HostSchema, Rustia};
279///
280/// struct Host;
281/// impl HostSchema for Host {
282///     type Input = ();
283///     type Slots = ();
284///     type External = ();
285///     type Effect = ();
286///     type SlotWrite = ();
287///     type Record = ();
288/// }
289///
290/// fn bypass(mut rustia: Rustia<Host>) {
291///     let _: i32 = rustia.eval("return 42").unwrap();
292/// }
293/// ```
294///
295/// </details>
296pub struct Rustia<C: HostSchema = ()> {
297    vm: Vm,
298    journal: Vec<C::Record>,
299}
300
301impl<C> Rustia<C>
302where
303    C: HostSchema,
304{
305    #[cfg(test)]
306    fn from_profile(profile: Profile) -> Self {
307        Self {
308            vm: Vm::new(profile.to_core()),
309            journal: Vec::new(),
310        }
311    }
312
313    fn from_settings(profile: Profile, settings: rustia_vm::VmSettings) -> Self {
314        Self {
315            vm: Vm::with_settings(profile.to_core(), settings),
316            journal: Vec::new(),
317        }
318    }
319
320    /// Reports live and reserved memory owned by the interpreter.
321    ///
322    /// These are logical accounting totals, not process memory usage. Captured
323    /// Rust callback state is outside these totals; diagnostic source retention
324    /// has a separate budget. See [`VmMemoryStats`] for the totals and optional
325    /// instruction-boundary peaks.
326    pub fn memory_stats(&mut self) -> VmMemoryStats {
327        VmMemoryStats::from_core(self.vm.memory_stats())
328    }
329
330    /// Returns the bytes charged for retained diagnostic source snapshots.
331    ///
332    /// This host-side retention is separate from the script memory limit.
333    pub fn diagnostic_source_bytes(&self) -> usize {
334        self.vm.diagnostic_source_bytes()
335    }
336
337    /// Returns the selected language profile and guest surface.
338    ///
339    /// This descriptor does not include budgets, services, or host callbacks.
340    pub fn execution_profile(&self) -> RustiaExecutionProfile {
341        RustiaExecutionProfile::from_vm(self.vm.profile(), self.vm.settings().guest_surface)
342    }
343
344    /// Returns the interpreter's effective application settings.
345    ///
346    /// Use [`Settings::identity_bytes`] when binding configuration to a replay
347    /// or package identity. Engine implementation controls remain private.
348    pub fn settings(&self) -> Settings {
349        Settings::from_core(Profile::from_core(self.vm.profile()), self.vm.settings())
350    }
351
352    #[cfg(test)]
353    pub(crate) const fn vm_settings(&self) -> &rustia_vm::VmSettings {
354        self.vm.settings()
355    }
356
357    /// Returns the generation used to validate live handles.
358    ///
359    /// It starts at zero and advances when [`reset_decision`](Self::reset_decision)
360    /// succeeds.
361    pub fn decision_epoch(&self) -> u64 {
362        self.vm.decision_epoch()
363    }
364
365    /// Discards all guest state and begins a fresh decision epoch.
366    ///
367    /// VM configuration, services, extensions, and installed host functions
368    /// persist. Globals inserted with [`insert_global`](Self::insert_global)
369    /// and [`insert_serde`](Self::insert_serde) are decision inputs and must be
370    /// rebound afterward. Every prior [`Value`], [`Table`], [`Function`], and
371    /// [`Exports`] handle is invalidated, while host-owned [`CompiledModule`]
372    /// and [`CompiledEntry`] values remain reusable. A hardened-leaf VM preserves its sealed
373    /// immutable environment in place and discards every decision-local
374    /// allocation after that seal.
375    ///
376    /// Replay protocols must record
377    /// [`RUSTIA_DECISION_RESET_ABI_VERSION`].
378    /// Reset requires an idle interpreter; attempting it during execution fails.
379    pub fn reset_decision(&mut self) -> Result<()> {
380        self.vm.reset_decision().map_err(Error::from_engine)?;
381        self.journal.clear();
382        Ok(())
383    }
384
385    /// Runs one typed, fuel-bounded host invocation and exposes its committed
386    /// deterministic records from Rustia's reusable journal.
387    ///
388    /// Failure rolls back staged records, not ordinary guest heap/global
389    /// mutation. Call [`reset_decision`](Self::reset_decision) when the host
390    /// requires a fresh guest-state decision boundary.
391    ///
392    /// A panic in `operation` itself is ordinary caller-side Rust control
393    /// flow: the private journal is dropped without publication and the panic
394    /// continues unwinding; it is not translated into `HostPanicked` or VM
395    /// poisoning. Panics from callbacks invoked by the VM are contained and
396    /// poison the VM.
397    pub fn invoke<'rustia, Return, Func>(
398        &'rustia mut self,
399        context: &mut dyn HostContext<C>,
400        limits: InvocationLimits,
401        operation: Func,
402    ) -> Result<InvocationOutcome<'rustia, Return, C::Record>>
403    where
404        Func: for<'call> FnOnce(&mut Invocation<'call, C>) -> Result<Return>,
405    {
406        let (value, usage) = self.invoke_core(context, limits, operation)?;
407        Ok(InvocationOutcome {
408            value,
409            records: &self.journal,
410            usage,
411        })
412    }
413
414    /// Runs one typed invocation and publishes its committed records into a
415    /// caller-owned lane. Capacity is reserved before guest execution, so the
416    /// final append cannot fail or allocate.
417    pub fn invoke_into<Return, Func>(
418        &mut self,
419        context: &mut dyn HostContext<C>,
420        limits: InvocationLimits,
421        records: &mut Vec<C::Record>,
422        operation: Func,
423    ) -> Result<InvocationReceipt<Return>>
424    where
425        Func: for<'call> FnOnce(&mut Invocation<'call, C>) -> Result<Return>,
426    {
427        self.ensure_healthy()?;
428        let reserve = usize::try_from(limits.max_records()).map_err(|_| {
429            Error::from(VmError::new(VmErrorKind::HostResourceExhausted {
430                resource: "effect-record count",
431                limit: u64::from(limits.max_records()),
432            }))
433        })?;
434        records
435            .try_reserve(reserve)
436            .map_err(|_| Error::from(VmError::new(VmErrorKind::OutOfMemory)))?;
437        let (value, usage) = self.invoke_core(context, limits, operation)?;
438        records.append(&mut self.journal);
439        Ok(InvocationReceipt { value, usage })
440    }
441
442    /// Executes one precompiled stateless entry, publishes its committed
443    /// records, and resets the decision epoch before returning.
444    ///
445    /// Reset runs after success, returned failure, and an unwinding panic from
446    /// guest-value conversion or a contained host callback. The original panic
447    /// resumes after reset. If reset itself fails after a normal return, any
448    /// records published by the invocation are removed from the caller lane
449    /// and the reset error wins. `panic = "abort"` builds cannot unwind and
450    /// therefore cannot provide panic containment. This is the complete
451    /// authoritative-leaf lifecycle used by worker lanes.
452    pub fn invoke_entry_into<Return>(
453        &mut self,
454        context: &mut dyn HostContext<C>,
455        limits: InvocationLimits,
456        records: &mut Vec<C::Record>,
457        entry: &CompiledEntry,
458    ) -> Result<InvocationReceipt<Return>>
459    where
460        Return: FromRustia,
461    {
462        let records_checkpoint = records.len();
463        let outcome = catch_unwind(AssertUnwindSafe(|| {
464            self.invoke_into(context, limits, records, |invocation| {
465                invocation.call_entry::<Return>(entry)
466            })
467        }));
468        let reset = self.reset_decision();
469        finish_entry_lifecycle(records, records_checkpoint, outcome, reset)
470    }
471
472    fn invoke_core<Return, Func>(
473        &mut self,
474        context: &mut dyn HostContext<C>,
475        limits: InvocationLimits,
476        operation: Func,
477    ) -> Result<(Return, InvocationUsage)>
478    where
479        Func: for<'call> FnOnce(&mut Invocation<'call, C>) -> Result<Return>,
480    {
481        self.ensure_healthy()?;
482        self.journal.clear();
483        let reserve = usize::try_from(limits.max_records()).map_err(|_| {
484            Error::from(VmError::new(VmErrorKind::HostResourceExhausted {
485                resource: "effect-record count",
486                limit: u64::from(limits.max_records()),
487            }))
488        })?;
489        self.journal
490            .try_reserve(reserve)
491            .map_err(|_| Error::from(VmError::new(VmErrorKind::OutOfMemory)))?;
492
493        let journal = std::mem::take(&mut self.journal);
494        let dispatcher = TypedHostDispatcher::new(context, journal, limits);
495        let mut invocation = Invocation::new(&mut self.vm, dispatcher, limits);
496        let result = operation(&mut invocation);
497        let commit_installation = result.is_ok() && invocation.can_commit_installation();
498        let (dispatcher, fuel_used) = invocation.finish(commit_installation);
499        let (journal, record_bytes, hard_error) = dispatcher.finish();
500        self.journal = journal;
501        if let Some(error) = hard_error {
502            self.journal.clear();
503            return Err(Error::from_engine(error));
504        }
505        match result {
506            Ok(value) => {
507                let record_count = u32::try_from(self.journal.len()).unwrap_or(u32::MAX);
508                Ok((
509                    value,
510                    InvocationUsage {
511                        fuel_used,
512                        record_count,
513                        record_bytes,
514                    },
515                ))
516            }
517            Err(error) => {
518                self.journal.clear();
519                Err(error)
520            }
521        }
522    }
523
524    fn ensure_healthy(&self) -> Result<()> {
525        if self.vm.is_poisoned() {
526            Err(Error::from(VmError::new(VmErrorKind::VmPoisoned)))
527        } else {
528            Ok(())
529        }
530    }
531
532    /// Copies Rust data into a script global, replacing any existing value.
533    ///
534    /// Uses [`IntoRustia`] for conversion. The value is available to later scripts
535    /// until replaced or [`reset_decision`](Self::reset_decision) clears it.
536    /// Conversion errors and script memory-limit failures are returned as [`Error`].
537    /// To insert a live handle without copying it, use [`Table::set_live`] on
538    /// [`globals`](Self::globals).
539    ///
540    /// ```
541    /// # use rustia::Rustia;
542    /// # let mut vm = Rustia::builder().build()?;
543    /// vm.insert_global("scores", vec![10, 20, 30])?;
544    /// let first: i32 = vm.eval("return scores[1]")?;
545    /// assert_eq!(first, 10);
546    /// # Ok::<(), rustia::Error>(())
547    /// ```
548    pub fn insert_global<T>(&mut self, name: impl AsRef<str>, value: T) -> Result<()>
549    where
550        T: IntoRustia,
551    {
552        let value = value.into_rustia()?;
553        let value = value::load_owned_value(&mut self.vm, &value)?;
554        self.vm
555            .set_global_value(name, value)
556            .map_err(Error::from_engine)
557    }
558
559    /// Serializes Rust data into a script global, replacing any existing value.
560    ///
561    /// This copies the data; later script changes do not modify the Rust input.
562    /// Serialization and script memory-limit failures are returned as [`Error`].
563    /// Like [`insert_global`](Self::insert_global), the binding is cleared by reset.
564    pub fn insert_serde<T>(&mut self, name: impl AsRef<str>, value: &T) -> Result<()>
565    where
566        T: serde::Serialize + ?Sized,
567    {
568        let value = OwnedValue::from_serialize(value)?;
569        let value = value::load_owned_value(&mut self.vm, &value)?;
570        self.vm
571            .set_global_value(name, value)
572            .map_err(Error::from_engine)
573    }
574
575    /// Returns a live handle to the interpreter's globals table.
576    ///
577    /// Reads and writes through [`Table`] preserve identity and are visible to
578    /// subsequently executed guest code. Like ordinary global inputs, these
579    /// mutations are decision-local and are discarded by
580    /// [`reset_decision`](Self::reset_decision). Hardened leaves reject this
581    /// mutable authority.
582    pub fn globals(&mut self) -> Result<Table> {
583        let value = self.vm.retain_globals().map_err(Error::from_engine)?;
584        Ok(Table::new(Value::new(value, self.vm.decision_epoch())))
585    }
586
587    /// Creates an empty live table in this interpreter.
588    ///
589    /// The table and its root participate in the logical-live memory quota as
590    /// one admission. Hardened leaves reject live table construction.
591    ///
592    /// ```
593    /// # use rustia::Rustia;
594    /// # let mut vm = Rustia::builder().build()?;
595    /// let settings = vm.create_table()?;
596    /// settings.set(&mut vm, "volume", 0.5)?;
597    /// vm.globals()?.set_live(&mut vm, "settings", &settings.as_value())?;
598    /// let volume: f64 = vm.eval("return settings.volume")?;
599    /// assert_eq!(volume, 0.5);
600    /// # Ok::<(), rustia::Error>(())
601    /// ```
602    pub fn create_table(&mut self) -> Result<Table> {
603        let value = self
604            .vm
605            .create_retained_table()
606            .map_err(Error::from_engine)?;
607        Ok(Table::new(Value::new(value, self.vm.decision_epoch())))
608    }
609
610    /// Creates an immutable live Luau vector in this interpreter.
611    ///
612    /// The vector and its root participate in the logical-live memory quota as
613    /// one admission. Components use Luau's canonical `f32` vector semantics.
614    /// The returned handle belongs to this VM and decision epoch like every
615    /// other live [`Value`].
616    ///
617    /// ```
618    /// # use rustia::Rustia;
619    /// # let mut vm = Rustia::builder().build()?;
620    /// let direction = vm.create_vector(1.5, -2.0, 3.0)?;
621    /// vm.globals()?.set_live(&mut vm, "direction", &direction)?;
622    /// let x: f64 = vm.eval("return direction.x")?;
623    /// assert_eq!(x, 1.5);
624    /// # Ok::<(), rustia::Error>(())
625    /// ```
626    pub fn create_vector(&mut self, x: f32, y: f32, z: f32) -> Result<Value> {
627        let value = self
628            .vm
629            .create_retained_vector(x, y, z)
630            .map_err(Error::from_engine)?;
631        Ok(Value::new(value, self.vm.decision_epoch()))
632    }
633
634    fn ensure_dynamic_source_loading_allowed(&self) -> Result<()> {
635        if self.vm.settings().guest_surface.is_hardened_leaf() {
636            return Err(Error::from(
637                VmError::new(VmErrorKind::HardenedLeafViolation {
638                    feature: "dynamic source loading",
639                })
640                .without_source_location(),
641            ));
642        }
643        self.ensure_healthy()
644    }
645
646    /// Registers a context-free `Fn(A, B, ...) -> R` with an explicit fuel
647    /// charge. The registration method fixes the capability to `Pure`;
648    /// `Result<R>` creates a fallible host call.
649    pub fn add_pure<Func, Args, Return>(
650        &mut self,
651        name: impl Into<String>,
652        fuel_cost: u32,
653        function: Func,
654    ) -> Result<()>
655    where
656        Func: IntoHostFunction<Args, Return>,
657    {
658        self.register_function(name, HostFunction::pure(function).fuel_cost(fuel_cost))
659    }
660
661    /// Registers a deterministic input reader with closure shape
662    /// `for<'a> Fn(Input<'a, C>, A, B, ...) -> R`.
663    pub fn add_input<Func, Args, Return>(
664        &mut self,
665        name: impl Into<String>,
666        fuel_cost: u32,
667        function: Func,
668    ) -> Result<()>
669    where
670        Func: IntoInputFunction<C, Args, Return>,
671    {
672        self.register_function(name, HostFunction::input(function).fuel_cost(fuel_cost))
673    }
674
675    /// Registers a deterministic slot reader with closure shape
676    /// `for<'a> Fn(Slots<'a, C>, A, B, ...) -> R`.
677    pub fn add_slot_read<Func, Args, Return>(
678        &mut self,
679        name: impl Into<String>,
680        fuel_cost: u32,
681        function: Func,
682    ) -> Result<()>
683    where
684        Func: IntoSlotReadFunction<C, Args, Return>,
685    {
686        self.register_function(name, HostFunction::slot_read(function).fuel_cost(fuel_cost))
687    }
688
689    /// Registers a deterministic effect recorder with closure shape
690    /// `for<'a> Fn(Effects<'a, C>, A, B, ...) -> R`.
691    pub fn add_effect<Func, Args, Return>(
692        &mut self,
693        name: impl Into<String>,
694        fuel_cost: u32,
695        function: Func,
696    ) -> Result<()>
697    where
698        Func: IntoEffectFunction<C, Args, Return>,
699    {
700        self.register_function(name, HostFunction::effect(function).fuel_cost(fuel_cost))
701    }
702
703    /// Registers a deterministic slot-write recorder with closure shape
704    /// `for<'a> Fn(SlotWrites<'a, C>, A, B, ...) -> R`.
705    pub fn add_slot_write<Func, Args, Return>(
706        &mut self,
707        name: impl Into<String>,
708        fuel_cost: u32,
709        function: Func,
710    ) -> Result<()>
711    where
712        Func: IntoSlotWriteFunction<C, Args, Return>,
713    {
714        self.register_function(
715            name,
716            HostFunction::slot_write(function).fuel_cost(fuel_cost),
717        )
718    }
719
720    /// Registers an external-state callback with closure shape
721    /// `for<'a> Fn(HostMut<'a, C>, A, B, ...) -> R`.
722    ///
723    /// Deterministic profiles reject it before installation, and mutations
724    /// through `HostMut` are outside Rustia's record rollback.
725    pub fn add_external<Func, Args, Return>(
726        &mut self,
727        name: impl Into<String>,
728        fuel_cost: u32,
729        function: Func,
730    ) -> Result<()>
731    where
732        Func: IntoExternalFunction<C, Args, Return>,
733    {
734        self.register_function(name, HostFunction::external(function).fuel_cost(fuel_cost))
735    }
736
737    /// Registers an explicitly nondeterministic `HostMut` callback.
738    ///
739    /// Deterministic profiles reject it before installation.
740    pub fn add_nondeterministic<Func, Args, Return>(
741        &mut self,
742        name: impl Into<String>,
743        fuel_cost: u32,
744        function: Func,
745    ) -> Result<()>
746    where
747        Func: IntoExternalFunction<C, Args, Return>,
748    {
749        self.register_function(
750            name,
751            HostFunction::nondeterministic(function).fuel_cost(fuel_cost),
752        )
753    }
754
755    /// Installs a namespaced collection of capability-checked host functions.
756    ///
757    /// Installation is fail-closed: if validation or VM binding fails, no
758    /// callable namespace or typed dispatcher bindings are retained.
759    pub fn install_host_module(&mut self, module: HostModule<C>) -> Result<()> {
760        module.install(&mut self.vm)
761    }
762
763    #[inline]
764    pub(crate) fn vm_mut(&mut self) -> &mut Vm {
765        &mut self.vm
766    }
767
768    #[inline]
769    pub(crate) fn vm(&self) -> &Vm {
770        &self.vm
771    }
772}
773
774fn finish_entry_lifecycle<T, Record>(
775    records: &mut Vec<Record>,
776    records_checkpoint: usize,
777    outcome: std::thread::Result<Result<T>>,
778    reset: Result<()>,
779) -> Result<T> {
780    match (outcome, reset) {
781        (Ok(outcome), Ok(())) => outcome,
782        (Ok(_), Err(reset_error)) => {
783            records.truncate(records_checkpoint);
784            Err(reset_error)
785        }
786        (Err(payload), _) => {
787            records.truncate(records_checkpoint);
788            resume_unwind(payload)
789        }
790    }
791}
792
793impl Rustia<()> {
794    /// Compiles a script once for later installation in one or more interpreters.
795    ///
796    /// Compilation does not run the script or change a VM. `source_name` labels
797    /// diagnostics and identifies the caller to the module resolver for `require`.
798    /// Invalid source returns a parse or compilation error. Call
799    /// [`install`](Self::install) to run the compiled module and retain its exports.
800    /// For PUC Lua 5.1 compatibility, use
801    /// [`compile_module_with_profile`](Self::compile_module_with_profile).
802    pub fn compile_module(source_name: impl Into<String>, source: &str) -> Result<CompiledModule> {
803        Self::compile_module_bytes(source_name, source.as_bytes())
804    }
805
806    /// Compiles a reusable module with code generation appropriate for
807    /// `profile`. Use this when the module will be installed into a VM whose
808    /// profile is known ahead of time. `source_name` labels diagnostics and
809    /// nested `require` resolver referrers.
810    pub fn compile_module_with_profile(
811        source_name: impl Into<String>,
812        source: &str,
813        profile: Profile,
814    ) -> Result<CompiledModule> {
815        Self::compile_module_bytes_with_profile(source_name, source.as_bytes(), profile)
816    }
817
818    /// Compiles bytes with the standard (source-order) table-constructor write
819    /// order. `source_name` labels diagnostics and nested `require` resolver
820    /// referrers. `Profile::Puc51Compat` hosts need PUC write order instead;
821    /// compile through the instance `load` builder (which reads the VM profile)
822    /// or use [`compile_module_bytes_with_profile`](Self::compile_module_bytes_with_profile).
823    pub fn compile_module_bytes(
824        source_name: impl Into<String>,
825        source: &[u8],
826    ) -> Result<CompiledModule> {
827        Self::compile_module_bytes_with_constructor_order(
828            source_name,
829            source,
830            false,
831            DiagnosticLimits::default(),
832        )
833    }
834
835    /// Byte-oriented form of [`compile_module_with_profile`](Self::compile_module_with_profile).
836    pub fn compile_module_bytes_with_profile(
837        source_name: impl Into<String>,
838        source: &[u8],
839        profile: Profile,
840    ) -> Result<CompiledModule> {
841        Self::compile_module_bytes_with_constructor_order(
842            source_name,
843            source,
844            profile == Profile::Puc51Compat,
845            DiagnosticLimits::default(),
846        )
847    }
848
849    fn compile_module_bytes_with_constructor_order(
850        source_name: impl Into<String>,
851        source: &[u8],
852        puc51_constructor_order: bool,
853        diagnostic_limits: DiagnosticLimits,
854    ) -> Result<CompiledModule> {
855        let source_name = source_name.into();
856        let chunk = rustia_parser::parse_source_bytes(source).map_err(|error| {
857            Error::from_engine(error).with_source(&source_name, source, diagnostic_limits)
858        })?;
859        let options = CompileOptions {
860            puc51_constructor_order,
861            ..CompileOptions::default()
862        }
863        .with_source_bytes(source_name.clone(), source);
864        let mut program = compile_with_options(&chunk, options).map_err(|error| {
865            Error::from_engine(error).with_source(&source_name, source, diagnostic_limits)
866        })?;
867        program.diagnostic_source = rustia_vm::diagnostic::SourceSnapshot::copy_with_limit(
868            source,
869            diagnostic_limits.source_bytes,
870        );
871        Ok(CompiledModule {
872            source_name,
873            program,
874        })
875    }
876
877    /// Compiles a chunk whose top-level body is invoked directly on each
878    /// decision without installing exports or retaining bytecode in the VM.
879    ///
880    /// Stateless entries cannot contain nested function prototypes. Inputs and
881    /// outputs should cross the typed host context, and the source should
882    /// return its decision value directly.
883    ///
884    /// Compiles with the standard (source-order) table-constructor write
885    /// order; see [`compile_module_bytes`](Self::compile_module_bytes).
886    pub fn compile_entry(source_name: impl Into<String>, source: &str) -> Result<CompiledEntry> {
887        let source_name = source_name.into();
888        let chunk = rustia_parser::parse_source(source).map_err(Error::from_engine)?;
889        let options = CompileOptions::default().with_source(source_name.clone(), source);
890        let program = compile_with_options(&chunk, options).map_err(Error::from_engine)?;
891        let program = HardenedLeafProgram::new(program).map_err(Error::from_engine)?;
892        Ok(CompiledEntry {
893            source_name,
894            program,
895        })
896    }
897
898    /// Returns the [`standard`](RustiaBuilder::standard) preset:
899    /// reproducible-by-default, with a real stdout `print` sink on native
900    /// targets.
901    pub fn builder() -> RustiaBuilder {
902        RustiaBuilder::standard()
903    }
904
905    /// Creates a service-free interpreter with the selected language profile.
906    ///
907    /// Unlike [`builder`](Self::builder), this constructor installs no stdout
908    /// sink. Use the builder presets for normal application defaults and host
909    /// clock, output, entropy, or module services.
910    #[cfg(test)]
911    pub(crate) fn new(profile: Profile) -> Self {
912        Self::from_profile(profile)
913    }
914
915    /// Creates an interpreter with explicit low-level settings and services.
916    ///
917    /// Prefer [`builder`](Self::builder) for ordinary application configuration.
918    #[cfg(test)]
919    pub(crate) fn with_settings(profile: Profile, settings: rustia_vm::VmSettings) -> Self {
920        Self::from_settings(profile, settings)
921    }
922
923    /// Creates a typed interpreter with explicit low-level settings and services.
924    ///
925    /// Prefer [`RustiaBuilder::build_for_host`] for application configuration.
926    #[cfg(test)]
927    pub(crate) fn for_host_with_settings<H>(
928        profile: Profile,
929        settings: rustia_vm::VmSettings,
930    ) -> Rustia<H>
931    where
932        H: HostSchema,
933    {
934        Rustia::<H>::from_settings(profile, settings)
935    }
936
937    /// Prepares Luau source text or bytes to run in this interpreter.
938    ///
939    /// Building the chunk is inert: parsing, compilation, VM allocation, and
940    /// execution begin only when a terminal operation is called.
941    /// Use [`Chunk::source_name`] to label errors, then choose [`Chunk::eval`],
942    /// [`Chunk::exec`], or [`Chunk::install`]. The source only needs to live until
943    /// that operation finishes; returned values do not borrow it.
944    ///
945    /// ```
946    /// # use rustia::Rustia;
947    /// # let mut vm = Rustia::builder().build()?;
948    /// let answer: i32 = vm
949    ///     .load("return 6 * 7")
950    ///     .source_name("answer.luau")
951    ///     .eval()?;
952    /// assert_eq!(answer, 42);
953    /// # Ok::<(), rustia::Error>(())
954    /// ```
955    pub fn load<'rustia, 'source, S>(
956        &'rustia mut self,
957        source: &'source S,
958    ) -> Chunk<'rustia, 'source>
959    where
960        S: AsRef<[u8]> + ?Sized,
961    {
962        Chunk::new(self, source.as_ref())
963    }
964
965    /// Evaluates source and converts its first result through [`FromRustia`].
966    ///
967    /// Shorthand for `load(source).eval()`. Use [`load`](Self::load) to give the
968    /// source a name or select its environment. See [`Chunk::eval`] for conversion
969    /// and failure behavior.
970    pub fn eval<T>(&mut self, source: impl AsRef<[u8]>) -> Result<T>
971    where
972        T: FromRustia,
973    {
974        let source = source;
975        self.load(&source).eval()
976    }
977
978    /// Evaluates source and deserializes its first result directly from the VM.
979    ///
980    /// Shorthand for `load(source).eval_serde()`; see [`Chunk::eval_serde`].
981    pub fn eval_serde<T>(&mut self, source: impl AsRef<[u8]>) -> Result<T>
982    where
983        T: serde::de::DeserializeOwned,
984    {
985        let source = source;
986        self.load(&source).eval_serde()
987    }
988
989    /// Executes source for side effects and discards its result.
990    ///
991    /// Shorthand for `load(source).exec()`; see [`Chunk::exec`].
992    pub fn exec(&mut self, source: impl AsRef<[u8]>) -> Result<()> {
993        let source = source;
994        self.load(&source).exec()
995    }
996
997    /// Runs a compiled module in a fresh environment and retains its exports.
998    ///
999    /// The environment inherits VM globals. A failed installation restores prior
1000    /// guest state; external host callback and module-resolver effects cannot be
1001    /// undone. Previously installed exports remain usable until reset.
1002    /// See [`Chunk::install`] to compile and install source in one step.
1003    ///
1004    /// ```
1005    /// # use rustia::Rustia;
1006    /// let module = Rustia::compile_module(
1007    ///     "greeting.luau",
1008    ///     "return { greet = function(name) return 'Hello, ' .. name end }",
1009    /// )?;
1010    /// let mut vm = Rustia::builder().build()?;
1011    /// let exports = vm.install(&module)?;
1012    /// let greet = exports.function(&mut vm, "greet")?;
1013    /// let greeting: String = greet.call(&mut vm, ("Ada",))?;
1014    /// assert_eq!(greeting, "Hello, Ada");
1015    /// # Ok::<(), rustia::Error>(())
1016    /// ```
1017    pub fn install(&mut self, module: &CompiledModule) -> Result<Exports> {
1018        self.install_with_environment(module, None)
1019    }
1020}
1021
1022impl<C> Rustia<C>
1023where
1024    C: HostSchema,
1025{
1026    fn install_with_environment(
1027        &mut self,
1028        module: &CompiledModule,
1029        environment: Option<rustia_vm::Value>,
1030    ) -> Result<Exports> {
1031        self.vm
1032            .begin_guest_transaction()
1033            .map_err(Error::from_engine)?;
1034        let outcome: Result<Exports> = (|| {
1035            let module_cohort = self.vm.create_module_cohort().map_err(Error::from_engine)?;
1036            let environment = match environment {
1037                Some(environment) => environment,
1038                None => self
1039                    .vm
1040                    .create_module_environment()
1041                    .map_err(Error::from_engine)?,
1042            };
1043            let value = self
1044                .vm
1045                .run_installation_with_environment(&module.program, environment, module_cohort)
1046                .map_err(Error::from_engine)?;
1047            let value = self.vm.retain_value(value).map_err(Error::from_engine)?;
1048            Ok(Exports::new(value, self.decision_epoch()))
1049        })();
1050        match outcome {
1051            Ok(exports) => {
1052                if let Err(error) = self.vm.commit_guest_transaction() {
1053                    self.vm.rollback_guest_transaction();
1054                    Err(Error::from_engine(error).installation_rolled_back())
1055                } else {
1056                    Ok(exports)
1057                }
1058            }
1059            Err(error) => {
1060                self.vm.rollback_guest_transaction();
1061                Err(error.installation_rolled_back())
1062            }
1063        }
1064    }
1065}
1066
1067impl Rustia<()> {
1068    /// Registers a Rust function as a script global.
1069    ///
1070    /// Arguments and results are converted automatically. Return [`Result<T>`]
1071    /// from the callback to report a script-visible error. A call costs one fuel
1072    /// unit in addition to guest instructions; use [`add_fn_with`](Self::add_fn_with)
1073    /// to select another cost or declare captured-state effects.
1074    ///
1075    /// The callback must be `Fn + Send + Sync + 'static`. This helper declares
1076    /// it pure, so captured state must honour that promise. The registration
1077    /// survives [`reset_decision`](Self::reset_decision). For a live function
1078    /// value instead of a global binding, use [`create_function`](Self::create_function).
1079    ///
1080    /// ```
1081    /// # use rustia::Rustia;
1082    /// # let mut vm = Rustia::builder().build()?;
1083    /// vm.add_fn("divide", |a: f64, b: f64| -> rustia::Result<f64> {
1084    ///     if b == 0.0 {
1085    ///         return Err(rustia::Error::embed("division by zero"));
1086    ///     }
1087    ///     Ok(a / b)
1088    /// })?;
1089    /// let quotient: f64 = vm.eval("return divide(84, 2)")?;
1090    /// assert_eq!(quotient, 42.0);
1091    /// # Ok::<(), rustia::Error>(())
1092    /// ```
1093    pub fn add_fn<Func, Args, Return>(
1094        &mut self,
1095        name: impl Into<String>,
1096        function: Func,
1097    ) -> Result<()>
1098    where
1099        Func: IntoHostFunction<Args, Return>,
1100    {
1101        self.add_fn_with(name, 1, OpCapability::Pure, function)
1102    }
1103
1104    /// Registers a pure callback; equivalent to [`add_fn`](Self::add_fn).
1105    pub fn add_pure_fn<Func, Args, Return>(
1106        &mut self,
1107        name: impl Into<String>,
1108        function: Func,
1109    ) -> Result<()>
1110    where
1111        Func: IntoHostFunction<Args, Return>,
1112    {
1113        self.add_fn_with(name, 1, OpCapability::Pure, function)
1114    }
1115
1116    /// Registers a callback declared to read deterministic captured input.
1117    ///
1118    /// The callback receives ordinary arguments. For borrowed per-invocation
1119    /// input in a typed host, use [`add_input`](Self::add_input).
1120    pub fn add_input_fn<Func, Args, Return>(
1121        &mut self,
1122        name: impl Into<String>,
1123        function: Func,
1124    ) -> Result<()>
1125    where
1126        Func: IntoHostFunction<Args, Return>,
1127    {
1128        self.add_fn_with(name, 1, OpCapability::ReadsDeterministicInput, function)
1129    }
1130
1131    /// Registers a callback declared to read captured slot state.
1132    ///
1133    /// For a borrowed [`Slots`] view in a typed host, use
1134    /// [`add_slot_read`](Self::add_slot_read).
1135    pub fn add_slot_read_fn<Func, Args, Return>(
1136        &mut self,
1137        name: impl Into<String>,
1138        function: Func,
1139    ) -> Result<()>
1140    where
1141        Func: IntoHostFunction<Args, Return>,
1142    {
1143        self.add_fn_with(name, 1, OpCapability::ReadsSlotState, function)
1144    }
1145
1146    /// Registers a callback declared to produce slot-write effects.
1147    ///
1148    /// Captured Rust mutations are not rolled back. For a transactional
1149    /// [`SlotWrites`] journal, use [`add_slot_write`](Self::add_slot_write).
1150    pub fn add_slot_write_fn<Func, Args, Return>(
1151        &mut self,
1152        name: impl Into<String>,
1153        function: Func,
1154    ) -> Result<()>
1155    where
1156        Func: IntoHostFunction<Args, Return>,
1157    {
1158        self.add_fn_with(name, 1, OpCapability::WritesSlotEffect, function)
1159    }
1160
1161    /// Registers a callback declared to produce deterministic effects.
1162    ///
1163    /// Captured Rust mutations are not rolled back. For a transactional
1164    /// [`Effects`] journal, use [`add_effect`](Self::add_effect).
1165    pub fn add_effect_fn<Func, Args, Return>(
1166        &mut self,
1167        name: impl Into<String>,
1168        function: Func,
1169    ) -> Result<()>
1170    where
1171        Func: IntoHostFunction<Args, Return>,
1172    {
1173        self.add_fn_with(name, 1, OpCapability::EmitsDeterministicEffect, function)
1174    }
1175
1176    /// Registers a callback declared to access mutable external state.
1177    ///
1178    /// Deterministic profiles reject this capability. For a borrowed [`HostMut`]
1179    /// view in a typed host, use [`add_external`](Self::add_external).
1180    pub fn add_external_state_fn<Func, Args, Return>(
1181        &mut self,
1182        name: impl Into<String>,
1183        function: Func,
1184    ) -> Result<()>
1185    where
1186        Func: IntoHostFunction<Args, Return>,
1187    {
1188        self.add_fn_with(name, 1, OpCapability::ReadsExternalMutableState, function)
1189    }
1190
1191    /// Registers a callback declared to have nondeterministic effects.
1192    ///
1193    /// Deterministic profiles reject this capability. Captured Rust effects are
1194    /// outside installation and invocation rollback.
1195    pub fn add_nondeterministic_fn<Func, Args, Return>(
1196        &mut self,
1197        name: impl Into<String>,
1198        function: Func,
1199    ) -> Result<()>
1200    where
1201        Func: IntoHostFunction<Args, Return>,
1202    {
1203        self.add_fn_with(name, 1, OpCapability::NondeterministicEffect, function)
1204    }
1205
1206    /// Registers a callback with an explicit fuel cost and capability.
1207    ///
1208    /// A zero fuel cost or a capability forbidden by the selected profile fails
1209    /// before registration. The capability describes captured host behavior;
1210    /// it does not restrict what a Rust closure can do. See [`add_fn`](Self::add_fn)
1211    /// for the callback's conversion and lifetime rules.
1212    pub fn add_fn_with<Func, Args, Return>(
1213        &mut self,
1214        name: impl Into<String>,
1215        fuel_cost: u32,
1216        capability: OpCapability,
1217        function: Func,
1218    ) -> Result<()>
1219    where
1220        Func: IntoHostFunction<Args, Return>,
1221    {
1222        self.register_function(
1223            name,
1224            HostFunction::with_capability(capability, function).fuel_cost(fuel_cost),
1225        )
1226    }
1227
1228    /// Installs a collection of host functions and modules atomically.
1229    ///
1230    /// Validation or binding failure leaves existing registrations unchanged.
1231    /// Use [`RustiaExtension`] to assemble a reusable application API.
1232    pub fn install_extension(&mut self, extension: RustiaExtension) -> Result<()> {
1233        extension.install(self)
1234    }
1235}
1236
1237impl Default for Rustia {
1238    /// Creates the standard preset, matching [`Rustia::builder`].
1239    fn default() -> Self {
1240        Self::builder()
1241            .build()
1242            .expect("the standard preset is valid without caller-supplied configuration")
1243    }
1244}
1245
1246/// A value returned by Rustia, or a script, conversion, or embedding [`Error`].
1247pub type Result<T> = std::result::Result<T, Error>;
1248
1249/// A compiled script ready for [`Rustia::install`].
1250///
1251/// Create it with [`Rustia::compile_module`]. It owns its source metadata and
1252/// compiled code independently of any interpreter, and remains reusable after
1253/// reset. A clone shares constant and string storage; function and debug metadata
1254/// are currently copied.
1255#[derive(Clone)]
1256pub struct CompiledModule {
1257    source_name: String,
1258    program: Program,
1259}
1260
1261impl CompiledModule {
1262    /// Returns the source label supplied when this module was compiled.
1263    pub fn source_name(&self) -> &str {
1264        &self.source_name
1265    }
1266}
1267
1268/// Precompiled top-level decision body for allocation-light repeated
1269/// invocation through [`Invocation::call_entry`].
1270#[derive(Clone)]
1271pub struct CompiledEntry {
1272    source_name: String,
1273    program: HardenedLeafProgram,
1274}
1275
1276impl CompiledEntry {
1277    /// Returns the source label supplied when this entry was compiled.
1278    pub fn source_name(&self) -> &str {
1279        &self.source_name
1280    }
1281}
1282
1283/// A half-open byte range in the source, `start..end`.
1284#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1285pub struct SourceSpan {
1286    /// Byte offset of the first included byte.
1287    pub start: usize,
1288    /// Byte offset immediately after the range.
1289    pub end: usize,
1290}
1291
1292impl SourceSpan {
1293    pub(crate) fn from_lexer(span: rustia_lexer::Span) -> Self {
1294        Self {
1295            start: span.start,
1296            end: span.end,
1297        }
1298    }
1299}
1300
1301/// The source label and one-based line number attached to an error.
1302#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1303pub struct SourceLocation<'a> {
1304    /// Source label, such as `"rules.luau"`; it need not be a filesystem path.
1305    pub source: &'a str,
1306    /// One-based source line number.
1307    pub line: u32,
1308}
1309
1310#[cfg(test)]
1311mod tests {
1312    use super::{
1313        finish_entry_lifecycle, Error, FromRustia, GuestSurface, IntoRustia, OpCapability,
1314        OwnedTable, OwnedValue, Profile, Result, Rustia, RustiaBuilder, RustiaExecutionProfile,
1315        RustiaExtension, RustiaHostFunctionInfo, ServiceClock, ServiceEntropy, SourceSpan,
1316        ValueType, VmErrorKind, RUSTIA_DECISION_RESET_ABI_VERSION,
1317        RUSTIA_DEFAULT_HOST_FUNCTION_FUEL, RUSTIA_HOST_FUEL_ABI_VERSION, RUSTIA_HOST_FUEL_POLICY,
1318        RUSTIA_MIN_HOST_FUNCTION_FUEL,
1319    };
1320    use rustia_compiler::{compile_with_options, CompileOptions};
1321    use rustia_parser::parse_source;
1322    use rustia_vm::{Vm, VmSettings};
1323    use serde::{Deserialize, Serialize};
1324    use std::collections::BTreeMap;
1325    use std::num::NonZeroU64;
1326    use std::sync::{Arc, Mutex};
1327
1328    #[test]
1329    fn install_smoke() {
1330        let mut rustia = Rustia::new(Profile::DeterministicSim);
1331        let result = rustia.eval("local x: number = 6 * 7; return x").unwrap();
1332        assert_eq!(f64::from_rustia(result).unwrap(), 42.0);
1333    }
1334
1335    #[test]
1336    fn live_values_preserve_identity_cycles_and_rich_payloads() {
1337        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
1338        let root = rustia
1339            .load(
1340                r#"
1341local root = {}
1342local richKey = {}
1343local shared = { answer = 42 }
1344root.self = root
1345root.left = shared
1346root.right = shared
1347root.binary = string.char(0, 255, 65)
1348root.bytes = buffer.fromstring(string.char(1, 0, 254))
1349root.direction = vector(1.5, -2, 3)
1350root[richKey] = shared
1351return root
1352"#,
1353            )
1354            .eval_live()
1355            .unwrap();
1356        assert_eq!(root.kind(&rustia).unwrap(), ValueType::Table);
1357        let table = root.as_table(&rustia).unwrap().unwrap();
1358
1359        let self_value = table.get(&mut rustia, "self").unwrap();
1360        assert!(root.raw_equal(&mut rustia, &self_value).unwrap());
1361        let left = table.get(&mut rustia, "left").unwrap();
1362        let right = table.get(&mut rustia, "right").unwrap();
1363        assert!(left.raw_equal(&mut rustia, &right).unwrap());
1364        assert_eq!(
1365            table
1366                .get(&mut rustia, "binary")
1367                .unwrap()
1368                .string_bytes(&mut rustia)
1369                .unwrap(),
1370            Some(vec![0, 255, 65])
1371        );
1372        assert_eq!(
1373            table
1374                .get(&mut rustia, "bytes")
1375                .unwrap()
1376                .buffer_bytes(&mut rustia)
1377                .unwrap(),
1378            Some(vec![1, 0, 254])
1379        );
1380        assert_eq!(
1381            table
1382                .get(&mut rustia, "direction")
1383                .unwrap()
1384                .vector_components(&mut rustia)
1385                .unwrap(),
1386            Some([1.5, -2.0, 3.0])
1387        );
1388
1389        table.set(&mut rustia, "added", 99_i32).unwrap();
1390        assert_eq!(
1391            table
1392                .get(&mut rustia, "added")
1393                .unwrap()
1394                .as_number(&rustia)
1395                .unwrap(),
1396            Some(99.0)
1397        );
1398        let rich_entry = table
1399            .entries(&mut rustia)
1400            .unwrap()
1401            .into_iter()
1402            .find(|(key, _)| key.kind(&rustia).unwrap() == ValueType::Table)
1403            .expect("table identity key");
1404        assert!(left.raw_equal(&mut rustia, &rich_entry.1).unwrap());
1405
1406        let exports = rustia
1407            .load("local live = { answer = 7 }; return { live = live }")
1408            .install()
1409            .unwrap();
1410        let exported = exports.get_live(&mut rustia, "live").unwrap();
1411        assert_eq!(
1412            exported
1413                .as_table(&rustia)
1414                .unwrap()
1415                .unwrap()
1416                .get(&mut rustia, "answer")
1417                .unwrap()
1418                .as_number(&rustia)
1419                .unwrap(),
1420            Some(7.0)
1421        );
1422
1423        let _: f64 = rustia.eval("collectgarbage('collect'); return 0").unwrap();
1424        assert_eq!(
1425            left.as_table(&rustia)
1426                .unwrap()
1427                .unwrap()
1428                .get(&mut rustia, "answer")
1429                .unwrap()
1430                .as_number(&rustia)
1431                .unwrap(),
1432            Some(42.0),
1433            "a live handle remains a collector root"
1434        );
1435        assert!(
1436            root.to_owned(&mut rustia).is_err(),
1437            "cyclic snapshots stay explicit"
1438        );
1439
1440        let mut other = Rustia::new(Profile::ReproducibleStandard);
1441        assert!(matches!(
1442            root.kind(&other)
1443                .unwrap_err()
1444                .as_vm_error()
1445                .map(|error| &error.kind),
1446            Some(VmErrorKind::RetainedValueFromDifferentVm)
1447        ));
1448        other.reset_decision().unwrap();
1449        rustia.reset_decision().unwrap();
1450        assert!(matches!(
1451            root.kind(&rustia)
1452                .unwrap_err()
1453                .as_vm_error()
1454                .map(|error| &error.kind),
1455            Some(VmErrorKind::StaleRetainedValue {
1456                retained_epoch: 0,
1457                current_epoch: 1
1458            })
1459        ));
1460    }
1461
1462    #[test]
1463    fn constructed_tables_install_into_the_live_globals_graph() {
1464        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
1465        let globals = rustia.globals().unwrap();
1466        let root = rustia.create_table().unwrap();
1467        root.set(&mut rustia, "answer", 42_i32).unwrap();
1468        root.set_live(&mut rustia, "self", &root.as_value())
1469            .unwrap();
1470        globals
1471            .set_live(&mut rustia, "host_graph", &root.as_value())
1472            .unwrap();
1473
1474        let returned = rustia.load("return host_graph").eval_live().unwrap();
1475        assert!(root.as_value().raw_equal(&mut rustia, &returned).unwrap());
1476        let returned_table = returned.as_table(&rustia).unwrap().unwrap();
1477        let returned_self = returned_table.get(&mut rustia, "self").unwrap();
1478        assert!(returned.raw_equal(&mut rustia, &returned_self).unwrap());
1479
1480        // Ordinary execution does not invalidate unrelated live handles.
1481        root.set(&mut rustia, "after_run", 7_i32).unwrap();
1482        let sees_mutation: bool = rustia
1483            .eval("return host_graph.answer == 42 and host_graph.after_run == 7")
1484            .unwrap();
1485        assert!(sees_mutation);
1486
1487        let globals_again = rustia.globals().unwrap();
1488        assert!(globals
1489            .as_value()
1490            .raw_equal(&mut rustia, &globals_again.as_value())
1491            .unwrap());
1492    }
1493
1494    #[test]
1495    fn live_table_constructors_are_available_in_every_standard_surface_profile() {
1496        for profile in [
1497            Profile::LuauCompat,
1498            Profile::ReproducibleStandard,
1499            Profile::DeterministicSim,
1500            Profile::Puc51Compat,
1501        ] {
1502            let mut rustia = Rustia::new(profile);
1503            let value = rustia.create_table().unwrap();
1504            value.set(&mut rustia, "profile_value", 9_i32).unwrap();
1505            rustia
1506                .globals()
1507                .unwrap()
1508                .set_live(&mut rustia, "host_value", &value.as_value())
1509                .unwrap();
1510            let observed: f64 = rustia.eval("return host_value.profile_value").unwrap();
1511            assert_eq!(observed, 9.0, "profile {profile:?}");
1512        }
1513    }
1514
1515    #[test]
1516    fn set_live_rejects_foreign_tables_and_values_before_mutation() {
1517        let mut first = Rustia::new(Profile::ReproducibleStandard);
1518        let mut second = Rustia::new(Profile::ReproducibleStandard);
1519        let first_table = first.create_table().unwrap();
1520        let second_table = second.create_table().unwrap();
1521
1522        let foreign_value = first_table
1523            .set_live(&mut first, "foreign", &second_table.as_value())
1524            .expect_err("a value from another VM must reject");
1525        assert!(matches!(
1526            foreign_value.as_vm_error().map(|error| &error.kind),
1527            Some(VmErrorKind::RetainedValueFromDifferentVm)
1528        ));
1529        assert!(first_table
1530            .get(&mut first, "foreign")
1531            .unwrap()
1532            .is_nil(&first)
1533            .unwrap());
1534
1535        let foreign_table = second_table
1536            .set_live(&mut first, "foreign", &first_table.as_value())
1537            .expect_err("a table from another VM must reject");
1538        assert!(matches!(
1539            foreign_table.as_vm_error().map(|error| &error.kind),
1540            Some(VmErrorKind::RetainedValueFromDifferentVm)
1541        ));
1542    }
1543
1544    #[test]
1545    fn decision_reset_stales_constructor_handles_and_discards_global_mutations() {
1546        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
1547        let globals = rustia.globals().unwrap();
1548        let table = rustia.create_table().unwrap();
1549        globals
1550            .set_live(&mut rustia, "decision_local", &table.as_value())
1551            .unwrap();
1552
1553        rustia.reset_decision().unwrap();
1554        assert!(matches!(
1555            globals
1556                .get(&mut rustia, "decision_local")
1557                .unwrap_err()
1558                .as_vm_error()
1559                .map(|error| &error.kind),
1560            Some(VmErrorKind::StaleRetainedValue {
1561                retained_epoch: 0,
1562                current_epoch: 1
1563            })
1564        ));
1565        assert!(matches!(
1566            table
1567                .set(&mut rustia, "value", 1_i32)
1568                .unwrap_err()
1569                .as_vm_error()
1570                .map(|error| &error.kind),
1571            Some(VmErrorKind::StaleRetainedValue {
1572                retained_epoch: 0,
1573                current_epoch: 1
1574            })
1575        ));
1576        let discarded: bool = rustia.eval("return decision_local == nil").unwrap();
1577        assert!(discarded);
1578    }
1579
1580    #[test]
1581    fn hardened_leaves_reject_live_table_authority_without_allocating() {
1582        let mut rustia = RustiaBuilder::deterministic_leaf()
1583            .memory_limit_bytes(512 * 1024)
1584            .build_for_host::<()>()
1585            .unwrap();
1586        let before = rustia.memory_stats().live_bytes();
1587
1588        let globals = rustia.globals().expect_err("hardened globals must reject");
1589        assert!(matches!(
1590            globals,
1591            Error { kind: crate::ErrorKind::Vm(ref error), .. }
1592                if matches!(
1593                    &error.kind,
1594                    VmErrorKind::HardenedLeafViolation {
1595                        feature: "mutable globals handles"
1596                    }
1597                )
1598        ));
1599        let table = rustia
1600            .create_table()
1601            .expect_err("hardened table construction must reject");
1602        assert!(matches!(
1603            table,
1604            Error { kind: crate::ErrorKind::Vm(ref error), .. }
1605                if matches!(
1606                    &error.kind,
1607                    VmErrorKind::HardenedLeafViolation {
1608                        feature: "live table construction"
1609                    }
1610                )
1611        ));
1612        assert_eq!(rustia.memory_stats().live_bytes(), before);
1613    }
1614
1615    #[test]
1616    fn live_table_constructor_quota_failure_recovers_after_a_root_is_dropped() {
1617        let mut baseline = RustiaBuilder::standard().build().unwrap();
1618        let limit = baseline
1619            .memory_stats()
1620            .live_bytes()
1621            .saturating_add(4 * 1024);
1622        drop(baseline);
1623        let mut rustia = RustiaBuilder::standard()
1624            .memory_limit_bytes(limit)
1625            .build()
1626            .unwrap();
1627        let mut retained = Vec::new();
1628        let error = loop {
1629            match rustia.create_table() {
1630                Ok(table) => {
1631                    retained.push(table);
1632                    assert!(retained.len() < 10_000, "constructor quota did not bind");
1633                }
1634                Err(error) => break error,
1635            }
1636        };
1637        assert!(matches!(
1638            error,
1639            Error { kind: crate::ErrorKind::Vm(ref error), .. } if matches!(&error.kind, VmErrorKind::OutOfMemory)
1640        ));
1641
1642        retained.pop().expect("at least one table fit before OOM");
1643        rustia
1644            .create_table()
1645            .expect("dropping one root must make one constructor admission recover");
1646    }
1647
1648    #[test]
1649    fn live_functions_accept_and_return_live_values() {
1650        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
1651        let function = rustia
1652            .load(
1653                "return function(value) local t = { value = value }; t.self = t; return value, t end",
1654            )
1655            .eval_live()
1656            .unwrap()
1657            .as_function(&rustia)
1658            .unwrap()
1659            .unwrap();
1660        let argument = rustia.load("return { answer = 42 }").eval_live().unwrap();
1661        let results = function
1662            .call_values(&mut rustia, std::slice::from_ref(&argument))
1663            .unwrap();
1664        assert_eq!(results.len(), 2);
1665        assert!(argument.raw_equal(&mut rustia, &results[0]).unwrap());
1666        let returned = results[1].as_table(&rustia).unwrap().unwrap();
1667        let returned_value = returned.get(&mut rustia, "value").unwrap();
1668        assert!(argument.raw_equal(&mut rustia, &returned_value).unwrap());
1669        let returned_self = returned.get(&mut rustia, "self").unwrap();
1670        assert!(returned
1671            .as_value()
1672            .raw_equal(&mut rustia, &returned_self)
1673            .unwrap());
1674    }
1675
1676    #[test]
1677    fn entry_lifecycle_removes_new_records_when_reset_fails() {
1678        let mut records = vec![1, 2, 3];
1679        let result = finish_entry_lifecycle(
1680            &mut records,
1681            2,
1682            Ok(Ok(42)),
1683            Err(Error::embed("reset failed".to_owned())),
1684        );
1685        assert!(
1686            matches!(result, Err(Error { kind: crate::ErrorKind::Embed(ref message), .. }) if message == "reset failed")
1687        );
1688        assert_eq!(records, [1, 2]);
1689    }
1690
1691    #[test]
1692    fn compiled_modules_can_be_cloned_across_vms() {
1693        let module = Rustia::compile_module(
1694            "shared.luau",
1695            "local greeting = 'compiled string shared across VMs'; return { greeting = greeting }",
1696        )
1697        .unwrap();
1698        let mut first = Rustia::new(Profile::ReproducibleStandard);
1699        let mut second = Rustia::new(Profile::ReproducibleStandard);
1700
1701        first.install(&module).unwrap();
1702        second.install(&module).unwrap();
1703    }
1704
1705    #[test]
1706    fn typed_run_converts_owned_results() {
1707        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
1708
1709        let answer: f64 = rustia.eval("return 40 + 2").unwrap();
1710        let numbers: Vec<i32> = rustia.eval("return { 1, 2, 3 }").unwrap();
1711        let missing: Option<String> = rustia.eval("return nil").unwrap();
1712        let named: BTreeMap<String, i32> = rustia.eval("return { scout = 5, brute = 9 }").unwrap();
1713
1714        assert_eq!(answer, 42.0);
1715        assert_eq!(numbers, vec![1, 2, 3]);
1716        assert_eq!(missing, None);
1717        assert_eq!(named.get("scout"), Some(&5));
1718        assert_eq!(named.get("brute"), Some(&9));
1719    }
1720
1721    #[test]
1722    fn typed_run_reports_conversion_errors() {
1723        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
1724        let error = rustia.eval::<String>("return 42").unwrap_err().to_string();
1725        assert!(error.contains("expected string, got number"), "{error}");
1726
1727        let array_error = rustia
1728            .eval::<BTreeMap<String, i32>>("return { 1, 2 }")
1729            .unwrap_err()
1730            .to_string();
1731        assert!(
1732            array_error.contains("expected string-keyed table, got table with array entries"),
1733            "{array_error}"
1734        );
1735
1736        let key_error = rustia
1737            .eval::<BTreeMap<String, i32>>("return { [true] = 1 }")
1738            .unwrap_err()
1739            .to_string();
1740        assert!(
1741            key_error.contains("expected string-keyed table, got non-string key"),
1742            "{key_error}"
1743        );
1744    }
1745
1746    #[test]
1747    fn numeric_table_keys_normalize_negative_zero_at_script_boundary() {
1748        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
1749        let result = rustia
1750            .eval(
1751                "\
1752local t = {}
1753t[-0] = 11
1754t[0] = t[0] + 31
1755return t[-0] == 42 and t[0] == 42 and rawget(t, -0) == 42 and rawget(t, 0) == 42
1756",
1757            )
1758            .unwrap();
1759        assert!(bool::from_rustia(result).unwrap());
1760    }
1761
1762    #[test]
1763    fn fuel_exhaustion_escapes_pcall_and_xpcall() {
1764        let cases = [
1765            "return pcall(function() while true do end end)",
1766            "return xpcall(function() while true do end end, function() return 'caught' end)",
1767        ];
1768
1769        for source in cases {
1770            let settings = VmSettings {
1771                initial_fuel: Some(1_000),
1772                ..VmSettings::default()
1773            };
1774            let mut rustia = Rustia::with_settings(Profile::DeterministicSim, settings);
1775            let Err(Error {
1776                kind: crate::ErrorKind::Vm(error),
1777                ..
1778            }) = rustia.eval::<OwnedValue>(source)
1779            else {
1780                panic!("expected fuel exhaustion to escape protected call: {source}");
1781            };
1782            assert!(matches!(
1783                error.kind,
1784                VmErrorKind::FuelExhausted { limit: 1_000 }
1785            ));
1786        }
1787    }
1788
1789    #[test]
1790    fn owned_values_snapshot_returned_tables() {
1791        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
1792        let value: OwnedValue = rustia
1793            .eval(
1794                "\
1795return {
1796    label = 'spawn',
1797    count = 3,
1798    flags = { true, false },
1799}
1800",
1801            )
1802            .unwrap();
1803        let table = value.table().unwrap();
1804        assert_eq!(
1805            table.get_string("label"),
1806            Some(&OwnedValue::String("spawn".to_owned()))
1807        );
1808        assert_eq!(table.get_string("count"), Some(&OwnedValue::Number(3.0)));
1809        let flags = table.get_string("flags").unwrap().table().unwrap();
1810        assert_eq!(
1811            flags.array,
1812            vec![OwnedValue::Boolean(true), OwnedValue::Boolean(false)]
1813        );
1814    }
1815
1816    #[test]
1817    fn owned_table_helpers_accept_typed_values_and_getters() {
1818        let labels = OwnedTable::string_entries([("kind", "scout"), ("role", "ai")]).unwrap();
1819        assert_eq!(
1820            labels.get_string_as::<String>("kind").unwrap().as_deref(),
1821            Some("scout")
1822        );
1823        assert_eq!(labels.get_string_as::<String>("missing").unwrap(), None);
1824
1825        let stats = OwnedTable::string_entries([("hp", 5_i32), ("speed", 7_i32)]).unwrap();
1826        assert_eq!(stats.get_string_as::<i32>("hp").unwrap(), Some(5));
1827
1828        let error = labels
1829            .get_string_as::<bool>("kind")
1830            .unwrap_err()
1831            .to_string();
1832        assert!(
1833            error.contains("expected boolean, got string"),
1834            "unexpected error: {error}"
1835        );
1836
1837        let array = OwnedTable::array_values([1_i32, 2, 3]).unwrap();
1838        assert_eq!(
1839            array.array,
1840            vec![
1841                OwnedValue::Number(1.0),
1842                OwnedValue::Number(2.0),
1843                OwnedValue::Number(3.0)
1844            ]
1845        );
1846        assert!(array.entries.is_empty());
1847    }
1848
1849    #[test]
1850    fn integer_embedding_rejects_silent_luau_number_rounding() {
1851        let exact = (1_u64 << 53).into_rustia().unwrap();
1852        assert_eq!(exact, OwnedValue::Number((1_u64 << 53) as f64));
1853
1854        for error in [
1855            ((1_u64 << 53) + 1).into_rustia().unwrap_err(),
1856            u64::MAX.into_rustia().unwrap_err(),
1857            i64::MAX.into_rustia().unwrap_err(),
1858        ] {
1859            assert!(
1860                error.to_string().contains("cannot be represented exactly"),
1861                "unexpected error: {error}"
1862            );
1863        }
1864
1865        assert!(u64::from_rustia(OwnedValue::Number(2.0_f64.powi(64))).is_err());
1866        assert!(i64::from_rustia(OwnedValue::Number(2.0_f64.powi(63))).is_err());
1867
1868        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
1869        assert!(rustia.insert_global("too_wide", u64::MAX).is_err());
1870    }
1871
1872    #[test]
1873    fn serde_integer_conversion_is_exact_for_values_and_map_keys() {
1874        assert_eq!(
1875            OwnedValue::from_serialize(&(1_u64 << 53)).unwrap(),
1876            OwnedValue::Number((1_u64 << 53) as f64)
1877        );
1878        assert!(OwnedValue::from_serialize(&((1_u64 << 53) + 1)).is_err());
1879        assert!(OwnedValue::from_serialize(&u128::MAX).is_err());
1880
1881        let exact_wide = 1_i128 << 100;
1882        let serialized = OwnedValue::from_serialize(&exact_wide).unwrap();
1883        assert_eq!(serialized.deserialize::<i128>().unwrap(), exact_wide);
1884
1885        let rounded_key = BTreeMap::from([((1_u64 << 53) + 1, true)]);
1886        assert!(OwnedValue::from_serialize(&rounded_key).is_err());
1887
1888        assert!(OwnedValue::Number(2.0_f64.powi(64))
1889            .deserialize::<u64>()
1890            .is_err());
1891        assert!(OwnedValue::Number(2.0_f64.powi(128))
1892            .deserialize::<u128>()
1893            .is_err());
1894    }
1895
1896    #[test]
1897    fn owned_table_helpers_support_nested_typed_access() {
1898        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
1899        let value: OwnedValue = rustia
1900            .eval(
1901                "\
1902return {
1903    config = {
1904        spawn = {
1905            kind = 'scout',
1906            stats = { 5, 7 },
1907        },
1908    },
1909}
1910",
1911            )
1912            .unwrap();
1913
1914        let root = value.table().unwrap();
1915        let config = root.get_string_table("config").unwrap().unwrap();
1916        let spawn = config.get_string_table("spawn").unwrap().unwrap();
1917        assert_eq!(
1918            spawn.get_string_as::<String>("kind").unwrap().as_deref(),
1919            Some("scout")
1920        );
1921        assert!(spawn.get_string_table("missing").unwrap().is_none());
1922
1923        let stats = spawn.get_string_table("stats").unwrap().unwrap();
1924        assert_eq!(stats.get_array(0), Some(&OwnedValue::Number(5.0)));
1925        assert_eq!(stats.get_array_as::<i32>(0).unwrap(), Some(5));
1926        assert_eq!(stats.get_array_as::<i32>(1).unwrap(), Some(7));
1927        assert_eq!(stats.get_array_as::<i32>(2).unwrap(), None);
1928
1929        let string_error = spawn.get_string_table("kind").unwrap_err().to_string();
1930        assert!(
1931            string_error.contains("expected table, got string"),
1932            "unexpected error: {string_error}"
1933        );
1934        let array_error = stats.get_array_table(0).unwrap_err().to_string();
1935        assert!(
1936            array_error.contains("expected table, got number"),
1937            "unexpected error: {array_error}"
1938        );
1939    }
1940
1941    #[test]
1942    fn owned_table_helpers_deserialize_nested_fields() {
1943        #[derive(Debug, Deserialize, PartialEq)]
1944        struct SpawnConfig<'a> {
1945            kind: &'a str,
1946            hp: u32,
1947            stats: Vec<u32>,
1948        }
1949
1950        #[derive(Debug, Deserialize, PartialEq)]
1951        struct Enemy<'a> {
1952            kind: &'a str,
1953            hp: u32,
1954        }
1955
1956        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
1957        let value: OwnedValue = rustia
1958            .eval(
1959                "\
1960return {
1961    config = {
1962        kind = 'scout',
1963        hp = 5,
1964        stats = { 7, 9 },
1965    },
1966    enemies = {
1967        { kind = 'brute', hp = 9 },
1968        { kind = 'scout', hp = 5 },
1969    },
1970}
1971",
1972            )
1973            .unwrap();
1974
1975        let root = value.table().unwrap();
1976        let config = root
1977            .get_string_deserialized::<SpawnConfig<'_>>("config")
1978            .unwrap()
1979            .unwrap();
1980        assert_eq!(
1981            config,
1982            SpawnConfig {
1983                kind: "scout",
1984                hp: 5,
1985                stats: vec![7, 9]
1986            }
1987        );
1988        assert!(root
1989            .get_string_deserialized::<SpawnConfig<'_>>("missing")
1990            .unwrap()
1991            .is_none());
1992
1993        let enemies = root.get_string_table("enemies").unwrap().unwrap();
1994        assert_eq!(
1995            enemies.get_array_deserialized::<Enemy<'_>>(0).unwrap(),
1996            Some(Enemy {
1997                kind: "brute",
1998                hp: 9
1999            })
2000        );
2001        assert_eq!(
2002            enemies.get_array_deserialized::<Enemy<'_>>(1).unwrap(),
2003            Some(Enemy {
2004                kind: "scout",
2005                hp: 5
2006            })
2007        );
2008        assert!(enemies
2009            .get_array_deserialized::<Enemy<'_>>(2)
2010            .unwrap()
2011            .is_none());
2012    }
2013
2014    #[test]
2015    fn insert_global_accepts_option_vec_and_owned_table() {
2016        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2017        let named_map = BTreeMap::from([("scout".to_owned(), 5_i32), ("brute".to_owned(), 9_i32)]);
2018        rustia.insert_global("maybe", Some(4_i32)).unwrap();
2019        rustia
2020            .insert_global("missing", Option::<i32>::None)
2021            .unwrap();
2022        rustia.insert_global("numbers", vec![1_i32, 2, 3]).unwrap();
2023        rustia.insert_global("named_map", named_map).unwrap();
2024        rustia
2025            .insert_global(
2026                "named",
2027                OwnedTable::string_entries([("kind", "scout")]).unwrap(),
2028            )
2029            .unwrap();
2030
2031        let value = rustia
2032            .eval(
2033                "\
2034return maybe == 4
2035    and missing == nil
2036    and numbers[1] == 1
2037    and numbers[3] == 3
2038    and named_map.scout == 5
2039    and named_map.brute == 9
2040    and named.kind == 'scout'
2041",
2042            )
2043            .unwrap();
2044        assert!(bool::from_rustia(value).unwrap());
2045    }
2046
2047    #[test]
2048    fn insert_global_and_typed_add_fn_are_callable() {
2049        let mut rustia = Rustia::new(Profile::DeterministicSim);
2050        rustia.insert_global("difficulty", 2_i32).unwrap();
2051        rustia
2052            .add_fn("clamp", |x: f64, lo: f64, hi: f64| x.clamp(lo, hi))
2053            .unwrap();
2054
2055        let result = rustia.eval("return clamp(12 + difficulty, 0, 10)").unwrap();
2056        assert_eq!(f64::from_rustia(result).unwrap(), 10.0);
2057    }
2058
2059    #[test]
2060    fn typed_host_functions_support_eight_arguments() {
2061        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2062        rustia
2063            .add_fn(
2064                "sum8",
2065                |a: f64, b: f64, c: f64, d: f64, e: f64, f: f64, g: f64, h: f64| {
2066                    a + b + c + d + e + f + g + h
2067                },
2068            )
2069            .unwrap();
2070
2071        let result = rustia.eval("return sum8(1, 2, 3, 4, 5, 6, 7, 8)").unwrap();
2072        assert_eq!(f64::from_rustia(result).unwrap(), 36.0);
2073    }
2074
2075    #[test]
2076    fn typed_host_functions_accept_and_return_owned_rust_shapes() {
2077        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2078        rustia
2079            .add_fn("sum_vec", |values: Vec<f64>| {
2080                values.into_iter().sum::<f64>()
2081            })
2082            .unwrap();
2083        rustia
2084            .add_fn("maybe_name", |enabled: bool| {
2085                enabled.then_some("scout".to_owned())
2086            })
2087            .unwrap();
2088        rustia.add_fn("make_vec", || vec![2.0, 4.0, 6.0]).unwrap();
2089        rustia
2090            .add_fn("sum_map", |values: BTreeMap<String, f64>| {
2091                values.values().sum::<f64>()
2092            })
2093            .unwrap();
2094        rustia
2095            .add_fn("make_map", || {
2096                BTreeMap::from([("scout".to_owned(), 5.0), ("brute".to_owned(), 9.0)])
2097            })
2098            .unwrap();
2099        rustia
2100            .add_fn("make_table", || {
2101                OwnedTable::string_entries([("kind", "scout")])
2102            })
2103            .unwrap();
2104
2105        let value = rustia
2106            .eval(
2107                "\
2108return sum_vec({ 1, 2, 3 }) == 6
2109    and maybe_name(true) == 'scout'
2110    and maybe_name(false) == nil
2111    and make_vec()[2] == 4
2112    and sum_map({ scout = 5, brute = 9 }) == 14
2113    and make_map().brute == 9
2114    and make_table().kind == 'scout'
2115",
2116            )
2117            .unwrap();
2118        assert!(bool::from_rustia(value).unwrap());
2119    }
2120
2121    #[test]
2122    fn facade_capability_helpers_register_allowed_deterministic_functions() {
2123        let mut rustia = Rustia::new(Profile::DeterministicSim);
2124        rustia.add_pure_fn("pure", || 5.0).unwrap();
2125        rustia.add_input_fn("input", || 2.0).unwrap();
2126        rustia.add_slot_read_fn("slot", || 3.0).unwrap();
2127        rustia
2128            .add_slot_write_fn("slot_write", |value: f64| value + 4.0)
2129            .unwrap();
2130        rustia
2131            .add_effect_fn("effect", |value: f64| value * 2.0)
2132            .unwrap();
2133
2134        let result = rustia
2135            .eval("return pure() + input() + slot() + slot_write(1) + effect(3)")
2136            .unwrap();
2137        assert_eq!(f64::from_rustia(result).unwrap(), 21.0);
2138    }
2139
2140    #[test]
2141    fn deterministic_facade_rejects_external_or_nondeterministic_helpers() {
2142        let mut external = Rustia::new(Profile::DeterministicSim);
2143        let Err(Error {
2144            kind: crate::ErrorKind::Vm(error),
2145            ..
2146        }) = external.add_external_state_fn("clock", || 1.0)
2147        else {
2148            panic!("expected deterministic profile to reject external-state host function");
2149        };
2150        assert!(matches!(error.kind, VmErrorKind::CapabilityRemoved { .. }));
2151
2152        let mut nondeterministic = Rustia::new(Profile::DeterministicSim);
2153        let Err(Error {
2154            kind: crate::ErrorKind::Vm(error),
2155            ..
2156        }) = nondeterministic.add_nondeterministic_fn("random", || 1.0)
2157        else {
2158            panic!("expected deterministic profile to reject nondeterministic host function");
2159        };
2160        assert!(matches!(error.kind, VmErrorKind::CapabilityRemoved { .. }));
2161    }
2162
2163    #[test]
2164    fn standard_facade_accepts_external_and_nondeterministic_helpers() {
2165        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2166        rustia.add_external_state_fn("clock", || 7.0).unwrap();
2167        rustia.add_nondeterministic_fn("random", || 11.0).unwrap();
2168
2169        let result = rustia.eval("return clock() + random()").unwrap();
2170        assert_eq!(f64::from_rustia(result).unwrap(), 18.0);
2171    }
2172
2173    #[test]
2174    fn typed_host_function_arg_errors_include_function_and_position() {
2175        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2176        rustia
2177            .add_fn("clamp", |x: f64, lo: f64, hi: f64| x.clamp(lo, hi))
2178            .unwrap();
2179
2180        let wrong_type = rustia
2181            .eval::<OwnedValue>("return clamp('bad', 0, 10)")
2182            .unwrap_err();
2183        let wrong_type = wrong_type.to_string();
2184        assert!(
2185            wrong_type.contains("host function `clamp` argument 1: expected number, got string"),
2186            "{wrong_type}"
2187        );
2188
2189        let missing_arg = rustia.eval::<OwnedValue>("return clamp(4, 0)").unwrap_err();
2190        let missing_arg = missing_arg.to_string();
2191        assert!(
2192            missing_arg.contains("host function `clamp` argument 3: expected number, got nil"),
2193            "{missing_arg}"
2194        );
2195    }
2196
2197    #[test]
2198    fn typed_host_functions_can_return_rustia_result_errors() {
2199        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2200        rustia
2201            .add_fn("checked_div", |x: f64, y: f64| -> Result<f64> {
2202                if y == 0.0 {
2203                    return Err(Error::embed("division by zero".to_owned()));
2204                }
2205                Ok(x / y)
2206            })
2207            .unwrap();
2208
2209        let value: f64 = rustia.eval("return checked_div(12, 3)").unwrap();
2210        assert_eq!(value, 4.0);
2211
2212        let error = rustia
2213            .eval::<OwnedValue>("return checked_div(12, 0)")
2214            .unwrap_err()
2215            .to_string();
2216        assert!(
2217            error.contains("host function `checked_div` return value: division by zero"),
2218            "{error}"
2219        );
2220    }
2221
2222    #[test]
2223    fn exports_facade_retains_script_functions() {
2224        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2225        let exports = rustia
2226            .load(
2227                "\
2228return {
2229    label = 'ai',
2230    decide = function(x)
2231        return x + 1
2232    end,
2233}
2234",
2235            )
2236            .install()
2237            .unwrap();
2238        assert_eq!(exports.get::<String>(&mut rustia, "label").unwrap(), "ai");
2239
2240        let decide = exports.function(&mut rustia, "decide").unwrap();
2241        let result: f64 = decide.call(&mut rustia, (41.0,)).unwrap();
2242        assert_eq!(result, 42.0);
2243    }
2244
2245    #[test]
2246    fn retained_script_functions_return_vec_and_option_shapes() {
2247        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2248        let exports = rustia
2249            .load(
2250                "\
2251return {
2252    values = function()
2253        return { 1, 2, 3 }
2254    end,
2255    maybe = function(enabled)
2256        if enabled then
2257            return 'scout'
2258        end
2259    end,
2260}
2261",
2262            )
2263            .install()
2264            .unwrap();
2265
2266        let values = exports.function(&mut rustia, "values").unwrap();
2267        let values: Vec<f64> = values.call(&mut rustia, ()).unwrap();
2268        assert_eq!(values, vec![1.0, 2.0, 3.0]);
2269
2270        let maybe = exports.function(&mut rustia, "maybe").unwrap();
2271        let found: Option<String> = maybe.call(&mut rustia, (true,)).unwrap();
2272        let missing: Option<String> = maybe.call(&mut rustia, (false,)).unwrap();
2273        assert_eq!(found.as_deref(), Some("scout"));
2274        assert_eq!(missing, None);
2275    }
2276
2277    #[test]
2278    fn retained_script_functions_support_eight_arguments_and_results() {
2279        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2280        let exports = rustia
2281            .load(
2282                "\
2283return {
2284    rotate = function(a, b, c, d, e, f, g, h)
2285        return h, g, f, e, d, c, b, a
2286    end,
2287}
2288",
2289            )
2290            .install()
2291            .unwrap();
2292
2293        let rotate = exports.function(&mut rustia, "rotate").unwrap();
2294        let result: (f64, f64, f64, f64, f64, f64, f64, f64) = rotate
2295            .call(&mut rustia, (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0))
2296            .unwrap();
2297        assert_eq!(result, (8.0, 7.0, 6.0, 5.0, 4.0, 3.0, 2.0, 1.0));
2298    }
2299
2300    #[test]
2301    fn builder_extension_installs_namespaced_deterministic_ops() {
2302        let extension = RustiaExtension::new("host")
2303            .fn_slot_read("bias", || 2.0)
2304            .fn_effect("emit", |value: f64| value + 1.0);
2305        let mut rustia = Rustia::builder()
2306            .profile(Profile::DeterministicSim)
2307            .extension(extension)
2308            .build()
2309            .unwrap();
2310
2311        let result = rustia.eval("return host.bias() + host.emit(4)").unwrap();
2312        assert_eq!(f64::from_rustia(result).unwrap(), 7.0);
2313    }
2314
2315    #[test]
2316    fn extension_reports_host_function_metadata() {
2317        let extension = RustiaExtension::new("host")
2318            .fn_pure("zero", || 1.0)
2319            .fn_pure("try_zero", || -> Result<f64> { Ok(1.0) })
2320            .fn_pure("split", |value: f64| (value, value > 0.0))
2321            .fn_with(
2322                "sum3",
2323                7,
2324                OpCapability::ReadsSlotState,
2325                |a: f64, b: f64, c: f64| a + b + c,
2326            );
2327
2328        assert_eq!(extension.namespace(), Some("host"));
2329        assert_eq!(extension.fuel_policy(), RUSTIA_HOST_FUEL_POLICY);
2330        assert_eq!(
2331            extension.fuel_policy().abi_version,
2332            RUSTIA_HOST_FUEL_ABI_VERSION
2333        );
2334        assert_eq!(
2335            extension.fuel_policy().default_function_fuel,
2336            RUSTIA_DEFAULT_HOST_FUNCTION_FUEL
2337        );
2338        assert_eq!(
2339            extension.fuel_policy().minimum_function_fuel,
2340            RUSTIA_MIN_HOST_FUNCTION_FUEL
2341        );
2342        let functions = extension.functions().collect::<Vec<_>>();
2343        assert_eq!(
2344            functions,
2345            vec![
2346                RustiaHostFunctionInfo {
2347                    name: "zero",
2348                    fuel_abi_version: RUSTIA_HOST_FUEL_ABI_VERSION,
2349                    fuel_cost: 1,
2350                    capability: OpCapability::Pure,
2351                    parameter_count: 0,
2352                    parameter_types: &[],
2353                    return_types: &["f64"],
2354                    fallible: false,
2355                },
2356                RustiaHostFunctionInfo {
2357                    name: "try_zero",
2358                    fuel_abi_version: RUSTIA_HOST_FUEL_ABI_VERSION,
2359                    fuel_cost: 1,
2360                    capability: OpCapability::Pure,
2361                    parameter_count: 0,
2362                    parameter_types: &[],
2363                    return_types: &["f64"],
2364                    fallible: true,
2365                },
2366                RustiaHostFunctionInfo {
2367                    name: "split",
2368                    fuel_abi_version: RUSTIA_HOST_FUEL_ABI_VERSION,
2369                    fuel_cost: 1,
2370                    capability: OpCapability::Pure,
2371                    parameter_count: 1,
2372                    parameter_types: &["f64"],
2373                    return_types: &["f64", "bool"],
2374                    fallible: false,
2375                },
2376                RustiaHostFunctionInfo {
2377                    name: "sum3",
2378                    fuel_abi_version: RUSTIA_HOST_FUEL_ABI_VERSION,
2379                    fuel_cost: 7,
2380                    capability: OpCapability::ReadsSlotState,
2381                    parameter_count: 3,
2382                    parameter_types: &["f64", "f64", "f64"],
2383                    return_types: &["f64"],
2384                    fallible: false,
2385                },
2386            ]
2387        );
2388    }
2389
2390    #[test]
2391    fn extension_rejects_zero_fuel_host_functions() {
2392        let extension = RustiaExtension::new("host").fn_with("free", 0, OpCapability::Pure, || 1.0);
2393        let result = Rustia::builder().extension(extension).build();
2394        let Err(Error {
2395            kind: crate::ErrorKind::Vm(error),
2396            ..
2397        }) = result
2398        else {
2399            panic!("expected zero-fuel host function to be rejected");
2400        };
2401        let VmErrorKind::InvalidProgram { reason } = error.kind else {
2402            panic!("expected invalid-program error, got {error:?}");
2403        };
2404        assert_eq!(reason, "host operation fuel cost must be non-zero");
2405    }
2406
2407    #[test]
2408    fn deterministic_builder_rejects_nondeterministic_extension() {
2409        let extension = RustiaExtension::new("host").fn_nondeterministic("clock", || 1.0);
2410        let result = Rustia::builder()
2411            .profile(Profile::DeterministicSim)
2412            .extension(extension)
2413            .build();
2414        let Err(Error {
2415            kind: crate::ErrorKind::Vm(error),
2416            ..
2417        }) = result
2418        else {
2419            panic!("expected deterministic profile to reject nondeterministic extension");
2420        };
2421        assert!(matches!(error.kind, VmErrorKind::CapabilityRemoved { .. }));
2422    }
2423
2424    #[test]
2425    fn deterministic_builder_rejects_external_state_extension() {
2426        let extension = RustiaExtension::new("host").fn_external_state("clock", || 1.0);
2427        let result = Rustia::builder()
2428            .profile(Profile::DeterministicSim)
2429            .extension(extension)
2430            .build();
2431        let Err(Error {
2432            kind: crate::ErrorKind::Vm(error),
2433            ..
2434        }) = result
2435        else {
2436            panic!("expected deterministic profile to reject external-state extension");
2437        };
2438        assert!(matches!(error.kind, VmErrorKind::CapabilityRemoved { .. }));
2439    }
2440
2441    #[test]
2442    fn failed_replacement_install_keeps_old_function_callable() {
2443        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2444        let exports = rustia
2445            .load("return { decide = function() return 1 end }")
2446            .source_name("ai.luau")
2447            .install()
2448            .unwrap();
2449        let decide = exports.function(&mut rustia, "decide").unwrap();
2450
2451        assert!(rustia
2452            .load("return {")
2453            .source_name("ai.luau")
2454            .install()
2455            .is_err());
2456        let result: f64 = decide.call(&mut rustia, ()).unwrap();
2457        assert_eq!(result, 1.0);
2458    }
2459
2460    #[test]
2461    fn successful_replacement_install_keeps_both_versions_callable() {
2462        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2463        let first_exports = rustia
2464            .load("return { label = 'old', decide = function() return 1 end }")
2465            .source_name("ai.luau")
2466            .install()
2467            .unwrap();
2468        let first_decide = first_exports.function(&mut rustia, "decide").unwrap();
2469
2470        let second_exports = rustia
2471            .load("return { label = 'new', decide = function() return 2 end }")
2472            .source_name("ai.luau")
2473            .install()
2474            .unwrap();
2475        let second_decide = second_exports.function(&mut rustia, "decide").unwrap();
2476
2477        assert_eq!(
2478            first_exports.get::<String>(&mut rustia, "label").unwrap(),
2479            "old"
2480        );
2481        assert_eq!(
2482            second_exports.get::<String>(&mut rustia, "label").unwrap(),
2483            "new"
2484        );
2485
2486        let old_result: f64 = first_decide.call(&mut rustia, ()).unwrap();
2487        let new_result: f64 = second_decide.call(&mut rustia, ()).unwrap();
2488        assert_eq!(old_result, 1.0);
2489        assert_eq!(new_result, 2.0);
2490    }
2491
2492    #[test]
2493    fn retained_function_root_survives_after_exports_are_dropped() {
2494        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2495        let exports = rustia
2496            .load(
2497                "local state = { answer = 42 }; \
2498                 return { read = function() return state.answer end }",
2499            )
2500            .install()
2501            .unwrap();
2502        let read = exports.function(&mut rustia, "read").unwrap();
2503        drop(exports);
2504
2505        let _: f64 = rustia.eval("collectgarbage('collect'); return 0").unwrap();
2506        let answer: f64 = read.call(&mut rustia, ()).unwrap();
2507        assert_eq!(answer, 42.0);
2508    }
2509
2510    #[test]
2511    fn retained_function_root_survives_repeated_slot_reuse() {
2512        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2513        let exports = rustia
2514            .load(
2515                "local state = { answer = 42 }; \
2516                 return { read = function() return state.answer end }",
2517            )
2518            .install()
2519            .unwrap();
2520        let read = exports.function(&mut rustia, "read").unwrap();
2521        drop(exports);
2522
2523        for _ in 0..32 {
2524            let _: f64 = rustia
2525                .eval(
2526                    "for i = 1, 256 do \
2527                         local state = { answer = i }; \
2528                         local function read() return state.answer end \
2529                         if read() ~= i then error('bad churn closure') end \
2530                     end \
2531                     collectgarbage('collect'); \
2532                     return 0",
2533                )
2534                .unwrap();
2535            let answer: f64 = read.call(&mut rustia, ()).unwrap();
2536            assert_eq!(answer, 42.0);
2537        }
2538    }
2539
2540    #[test]
2541    fn retained_handles_reject_a_different_vm() {
2542        let mut first = Rustia::new(Profile::ReproducibleStandard);
2543        let exports = first
2544            .load("return { read = function() return 42 end }")
2545            .install()
2546            .unwrap();
2547        let read = exports.function(&mut first, "read").unwrap();
2548        let mut second = Rustia::new(Profile::ReproducibleStandard);
2549
2550        let exports_error = exports.value(&mut second).unwrap_err();
2551        assert!(matches!(
2552            exports_error.as_vm_error().map(|error| &error.kind),
2553            Some(VmErrorKind::RetainedValueFromDifferentVm)
2554        ));
2555        let function_error = read.call::<_, f64>(&mut second, ()).unwrap_err();
2556        assert!(matches!(
2557            function_error.as_vm_error().map(|error| &error.kind),
2558            Some(VmErrorKind::RetainedValueFromDifferentVm)
2559        ));
2560    }
2561
2562    #[test]
2563    fn named_compile_preserves_source_name_in_runtime_diagnostics() {
2564        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2565        let error = rustia
2566            .load("local t = {}; t[0 / 0] = 1")
2567            .source_name("bad_ai.luau")
2568            .install()
2569            .unwrap_err();
2570        assert!(error.to_string().contains("bad_ai.luau:1:"), "{error}");
2571    }
2572
2573    #[test]
2574    fn chunk_builder_preserves_source_name_in_runtime_diagnostics() {
2575        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2576
2577        let answer: f64 = rustia
2578            .load("return 40 + 2")
2579            .source_name("inline.luau")
2580            .eval()
2581            .unwrap();
2582        assert_eq!(answer, 42.0);
2583
2584        let owned = rustia
2585            .load("return 'ok'")
2586            .source_name("owned.luau")
2587            .eval()
2588            .unwrap();
2589        assert_eq!(String::from_rustia(owned).unwrap(), "ok");
2590
2591        let exports = rustia
2592            .load("return { answer = 42 }")
2593            .source_name("exports.luau")
2594            .install()
2595            .unwrap();
2596        assert_eq!(exports.get::<i32>(&mut rustia, "answer").unwrap(), 42);
2597
2598        let error = rustia
2599            .load("local t = {}; t[0 / 0] = 1")
2600            .source_name("bad_inline.luau")
2601            .eval::<f64>()
2602            .unwrap_err();
2603        assert!(error.to_string().contains("bad_inline.luau:1:"), "{error}");
2604    }
2605
2606    #[test]
2607    fn public_errors_expose_source_span_and_runtime_location() {
2608        let Err(error) = Rustia::compile_module("compile-diag.luau", "break") else {
2609            panic!("break outside loop should fail compilation");
2610        };
2611        assert_eq!(error.source_span(), Some(SourceSpan { start: 0, end: 5 }));
2612        assert_eq!(
2613            error.source_location(),
2614            Some(crate::SourceLocation {
2615                source: "compile-diag.luau",
2616                line: 1
2617            })
2618        );
2619
2620        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2621        let Err(error) = rustia
2622            .load(
2623                "\
2624local t = {}
2625t[0 / 0] = 1
2626",
2627            )
2628            .source_name("runtime-diag.luau")
2629            .eval::<OwnedValue>()
2630        else {
2631            panic!("NaN table key should fail at runtime");
2632        };
2633        let location = error
2634            .source_location()
2635            .expect("runtime error should carry source location");
2636        assert_eq!(location.source, "runtime-diag.luau");
2637        assert_eq!(location.line, 2);
2638        assert!(error.source_span().is_some());
2639    }
2640
2641    #[derive(Debug, PartialEq, Deserialize, Serialize)]
2642    struct ScenarioSpec {
2643        name: String,
2644        difficulty: u32,
2645        enemies: Vec<EnemySpec>,
2646    }
2647
2648    #[derive(Debug, PartialEq, Deserialize, Serialize)]
2649    struct EnemySpec {
2650        kind: String,
2651        hp: u32,
2652    }
2653
2654    #[test]
2655    fn serde_deserializes_exports_and_inserts_globals() {
2656        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2657        let exports = rustia
2658            .load(
2659                "\
2660return {
2661    name = 'arena',
2662    difficulty = 3,
2663    enemies = {
2664        { kind = 'scout', hp = 5 },
2665        { kind = 'brute', hp = 9 },
2666    },
2667}
2668",
2669            )
2670            .install()
2671            .unwrap();
2672        let spec: ScenarioSpec = exports.deserialize(&mut rustia).unwrap();
2673        assert_eq!(
2674            spec,
2675            ScenarioSpec {
2676                name: "arena".to_owned(),
2677                difficulty: 3,
2678                enemies: vec![
2679                    EnemySpec {
2680                        kind: "scout".to_owned(),
2681                        hp: 5
2682                    },
2683                    EnemySpec {
2684                        kind: "brute".to_owned(),
2685                        hp: 9
2686                    },
2687                ],
2688            }
2689        );
2690        let second_spec: ScenarioSpec = exports.deserialize(&mut rustia).unwrap();
2691        assert_eq!(second_spec, spec);
2692
2693        rustia.insert_serde("config", &spec).unwrap();
2694        let value = rustia
2695            .eval("return config.enemies[2].kind .. ':' .. tostring(config.difficulty)")
2696            .unwrap();
2697        assert_eq!(String::from_rustia(value).unwrap(), "brute:3");
2698    }
2699
2700    #[test]
2701    fn rustia_extension_macro_builds_capability_tagged_extension() {
2702        let extension = crate::rustia_extension!("host" {
2703            pure(fuel = 2) fn fixed_mul(a: i32, b: i32) -> i32 {
2704                a * b
2705            }
2706
2707            effect fn emit(value: f64) -> f64 {
2708                value + 10.0
2709            }
2710        });
2711        let mut rustia = Rustia::builder()
2712            .profile(Profile::DeterministicSim)
2713            .extension(extension)
2714            .build()
2715            .unwrap();
2716
2717        let value = rustia
2718            .eval("return host.fixed_mul(6, 7) + host.emit(1)")
2719            .unwrap();
2720        assert_eq!(f64::from_rustia(value).unwrap(), 53.0);
2721    }
2722
2723    #[test]
2724    fn debug_traceback_for_errored_coroutine_reports_top_frame() {
2725        let source = "\
2726function halp(key, value)
2727    local t = {}
2728    t[key] = value
2729    return t
2730end
2731
2732local co = coroutine.create(halp)
2733local ok, err = coroutine.resume(co, 0 / 0, 42)
2734return tostring(ok) .. \"|\" .. tostring(err) .. \"|\" .. debug.traceback(co)
2735";
2736        let chunk = parse_source(source).unwrap();
2737        let program = compile_with_options(
2738            &chunk,
2739            CompileOptions::default().with_source("debug.luau", source),
2740        )
2741        .unwrap();
2742        let mut vm = Vm::new(Profile::ReproducibleStandard.to_core());
2743        let result = vm.run(&program).unwrap();
2744        let traceback = vm.string_value(result).unwrap().unwrap();
2745        assert_eq!(
2746            traceback,
2747            "false|debug.luau:3: table index is NaN|debug.luau:3 function halp\n"
2748        );
2749    }
2750
2751    #[test]
2752    fn debug_info_line_defined_precedes_active_line() {
2753        let source = "\
2754function testlinedefined()
2755    local line = debug.info(1, \"l\")
2756    local linedefined = debug.info(testlinedefined, \"l\")
2757    return tostring(line) .. \"|\" .. tostring(linedefined)
2758end
2759
2760return testlinedefined()
2761";
2762        let chunk = parse_source(source).unwrap();
2763        let program = compile_with_options(
2764            &chunk,
2765            CompileOptions::default().with_source("debug.luau", source),
2766        )
2767        .unwrap();
2768        let mut vm = Vm::new(Profile::ReproducibleStandard.to_core());
2769        let result = vm.run(&program).unwrap();
2770        let lines = vm.string_value(result).unwrap().unwrap();
2771        assert_eq!(lines, "2|1");
2772    }
2773
2774    #[test]
2775    fn conformance_int64_userdata_supports_metamethods_and_value_field() {
2776        let settings = VmSettings {
2777            enable_conformance_int64_userdata: true,
2778            ..VmSettings::default()
2779        };
2780        let mut rustia = Rustia::with_settings(Profile::ReproducibleStandard, settings);
2781        let result = rustia
2782            .eval(
2783                "\
2784local v = int64(42)
2785v.value = 4
2786return tostring(v + 2) .. '|' .. tostring(v == int64(4)) .. '|' .. tostring(int64(-5) // 2)
2787",
2788            )
2789            .unwrap();
2790        assert_eq!(String::from_rustia(result).unwrap(), "6|true|-3");
2791    }
2792
2793    #[test]
2794    fn conformance_native_userdata_supports_vec2_and_vertex_surface() {
2795        let settings = VmSettings {
2796            enable_conformance_native_userdata: true,
2797            ..VmSettings::default()
2798        };
2799        let mut rustia = Rustia::with_settings(Profile::ReproducibleStandard, settings);
2800        let result = rustia
2801            .eval(
2802                "\
2803local s = vec2(5, 4)
2804local t = vec2(1, 2)
2805local u = vec2(10, 20)
2806local x = -u + s * t
2807local m = u:Min(s)
2808local v = vertex(vector.create(1, 2, 3), vector.create(0.5, 0, 0.5), vec2(0.25, 0.5))
2809return x.X == -5 and x.Y == -12 and s:Dot(t) == 13 and m.X == 5 and m.Y == 4 and v.uv.X == 0.25 and v.normal.Z == 0.5
2810",
2811            )
2812            .unwrap();
2813        assert!(bool::from_rustia(result).unwrap());
2814    }
2815
2816    #[test]
2817    fn conformance_native_type_checks_validate_annotated_parameters() {
2818        let settings = VmSettings {
2819            enable_conformance_native_type_checks: true,
2820            ..VmSettings::default()
2821        };
2822        let mut rustia = Rustia::with_settings(Profile::ReproducibleStandard, settings);
2823        let result = rustia
2824            .eval(
2825                "\
2826local function add(a: number, b: number)
2827    assert(is_native())
2828    return a + b
2829end
2830local function checkbuffer(a: buffer?) return a == nil or type(a) == 'buffer' end
2831local ok = pcall(add, nil, 2)
2832return add(1, 3) == 4 and not ok and checkbuffer(nil) and checkbuffer(buffer.create(1))
2833",
2834            )
2835            .unwrap();
2836        assert!(bool::from_rustia(result).unwrap());
2837    }
2838
2839    #[test]
2840    fn coroutine_resume_arguments_return_from_yield() {
2841        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2842        let result = rustia
2843            .eval(
2844                "\
2845local co
2846local seen
2847local function body(a, ...)
2848    local arg = {...}
2849    for i = 1, #arg do
2850        seen = { coroutine.yield(table.unpack(arg[i])) }
2851    end
2852    return table.unpack(a)
2853end
2854co = coroutine.create(body)
2855local s, a, b, c, d = coroutine.resume(co, {1, 2, 3}, {}, {1}, {'a', 'b', 'c'})
2856local ok1 = s and a == nil and coroutine.status(co) == 'suspended'
2857s, a, b, c, d = coroutine.resume(co, 1, 2, 3)
2858local ok2 = s and #seen == 3 and seen[1] == 1 and seen[2] == 2 and seen[3] == 3
2859    and a == 1 and b == nil
2860s, a, b, c, d = coroutine.resume(co, 'done')
2861local ok3 = s and #seen == 1 and seen[1] == 'done'
2862    and a == 'a' and b == 'b' and c == 'c' and d == nil
2863s, a, b, c, d = coroutine.resume(co)
2864local ok4 = s and a == 1 and b == 2 and c == 3 and d == nil
2865    and coroutine.status(co) == 'dead'
2866return ok1 and ok2 and ok3 and ok4
2867",
2868            )
2869            .unwrap();
2870        assert!(bool::from_rustia(result).unwrap());
2871    }
2872
2873    #[test]
2874    fn coroutine_wrap_resumes_yield_call_results() {
2875        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2876        let result = rustia
2877            .eval(
2878                "\
2879local f = coroutine.wrap(function()
2880    local a, b = coroutine.yield('yielded')
2881    return a, b
2882end)
2883local first = f()
2884local second, third = f('resume', 42)
2885return first == 'yielded' and second == 'resume' and third == 42
2886",
2887            )
2888            .unwrap();
2889        assert!(bool::from_rustia(result).unwrap());
2890    }
2891
2892    #[test]
2893    fn pcall_can_yield_and_resume_successfully() {
2894        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2895        let result = rustia
2896            .eval(
2897                "\
2898local co = coroutine.create(function()
2899    return pcall(function()
2900        coroutine.yield('pause')
2901        return 1, 2, 3
2902    end)
2903end)
2904local ok, value = coroutine.resume(co)
2905local first = ok and value == 'pause' and coroutine.status(co) == 'suspended'
2906local done, protected, a, b, c = coroutine.resume(co)
2907return first and done and protected and a == 1 and b == 2 and c == 3
2908",
2909            )
2910            .unwrap();
2911        assert!(bool::from_rustia(result).unwrap());
2912    }
2913
2914    #[test]
2915    fn nested_pcall_preserves_protected_results_after_yield() {
2916        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2917        let result = rustia
2918            .eval(
2919                "\
2920local co = coroutine.create(function()
2921    return pcall(function()
2922        coroutine.yield(1)
2923        return pcall(function()
2924            coroutine.yield(2)
2925            return 3
2926        end)
2927    end)
2928end)
2929local ok, a = coroutine.resume(co)
2930local first = ok and a == 1
2931ok, a = coroutine.resume(co)
2932local second = ok and a == 2
2933local done, outer, inner, value = coroutine.resume(co)
2934return first and second and done and outer and inner and value == 3
2935",
2936            )
2937            .unwrap();
2938        assert!(bool::from_rustia(result).unwrap());
2939    }
2940
2941    #[test]
2942    fn pcall_catches_error_after_yield() {
2943        let mut rustia = Rustia::new(Profile::ReproducibleStandard);
2944        let result = rustia
2945            .eval(
2946                "\
2947local co = coroutine.create(function()
2948    return pcall(function()
2949        coroutine.yield()
2950        error('foo')
2951    end)
2952end)
2953local ok = coroutine.resume(co)
2954local done, protected, err = coroutine.resume(co)
2955return ok and done and not protected and string.find(err, 'foo', 1, true) ~= nil
2956",
2957            )
2958            .unwrap();
2959        assert!(bool::from_rustia(result).unwrap());
2960    }
2961
2962    #[test]
2963    fn deterministic_builder_captures_print_through_the_stdout_sink() {
2964        let captured = Arc::new(Mutex::new(String::new()));
2965        let sink = Arc::clone(&captured);
2966        let mut rustia = RustiaBuilder::deterministic()
2967            .stdout(move |text| sink.lock().unwrap().push_str(text))
2968            .build()
2969            .unwrap();
2970
2971        rustia.exec("print('hello', 42)").unwrap();
2972        assert_eq!(captured.lock().unwrap().as_str(), "hello\t42\n");
2973    }
2974
2975    #[test]
2976    fn execution_profiles_have_stable_unique_encodings() {
2977        let profiles = [
2978            (
2979                RustiaExecutionProfile::new(Profile::DeterministicSim, GuestSurface::HardenedLeaf),
2980                1,
2981                [1, 0, 0, 0, 3, 0, 0, 0, 2, 0, 0, 0],
2982            ),
2983            (
2984                RustiaExecutionProfile::new(Profile::LuauCompat, GuestSurface::Standard),
2985                2,
2986                [1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0],
2987            ),
2988            (
2989                RustiaExecutionProfile::new(Profile::ReproducibleStandard, GuestSurface::Standard),
2990                3,
2991                [1, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0],
2992            ),
2993            (
2994                RustiaExecutionProfile::new(Profile::DeterministicSim, GuestSurface::Standard),
2995                4,
2996                [1, 0, 0, 0, 3, 0, 0, 0, 1, 0, 0, 0],
2997            ),
2998            (
2999                RustiaExecutionProfile::new(Profile::LuauCompat, GuestSurface::HardenedLeaf),
3000                5,
3001                [1, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0],
3002            ),
3003            (
3004                RustiaExecutionProfile::new(
3005                    Profile::ReproducibleStandard,
3006                    GuestSurface::HardenedLeaf,
3007                ),
3008                6,
3009                [1, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0],
3010            ),
3011            (
3012                RustiaExecutionProfile::new(Profile::Puc51Compat, GuestSurface::Standard),
3013                7,
3014                [1, 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 0],
3015            ),
3016            (
3017                RustiaExecutionProfile::new(Profile::Puc51Compat, GuestSurface::HardenedLeaf),
3018                8,
3019                [1, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0],
3020            ),
3021        ];
3022        for (index, (profile, compatibility_id, identity_bytes)) in profiles.iter().enumerate() {
3023            assert_eq!(profile.compatibility_id(), *compatibility_id);
3024            assert_eq!(profile.identity_bytes(), *identity_bytes);
3025            for (other_profile, _, _) in &profiles[index + 1..] {
3026                assert_ne!(profile.compatibility_id(), other_profile.compatibility_id());
3027                assert_ne!(profile.identity_bytes(), other_profile.identity_bytes());
3028            }
3029        }
3030    }
3031
3032    #[test]
3033    fn hardened_execution_profile_transfers_to_the_live_vm() {
3034        let expected = RustiaExecutionProfile::DETERMINISTIC_HARDENED_LEAF;
3035
3036        let builder = RustiaBuilder::deterministic_leaf().memory_limit_bytes(512 * 1024);
3037        assert_eq!(builder.execution_profile(), expected);
3038        assert_eq!(builder.vm_settings().memory_limit_bytes, Some(512 * 1024));
3039        assert!(!builder.vm_settings().enable_memory_tracking);
3040        let rustia = builder.build_for_host::<()>().unwrap();
3041        assert_eq!(rustia.execution_profile(), expected);
3042        assert_eq!(rustia.vm_settings().memory_limit_bytes, Some(512 * 1024));
3043        assert!(!rustia.vm_settings().enable_memory_tracking);
3044
3045        assert_eq!(
3046            RustiaBuilder::deterministic().execution_profile(),
3047            RustiaExecutionProfile::DETERMINISTIC_STANDARD
3048        );
3049        assert_ne!(
3050            RustiaExecutionProfile::DETERMINISTIC_STANDARD.identity_bytes(),
3051            expected.identity_bytes()
3052        );
3053
3054        assert_eq!(
3055            RustiaBuilder::standard().execution_profile(),
3056            RustiaBuilder::live().execution_profile(),
3057            "services and dynamic-code settings are identity inputs owned by the embedder"
3058        );
3059
3060        let normalized = Rustia::with_settings(
3061            Profile::ReproducibleStandard,
3062            VmSettings {
3063                guest_surface: GuestSurface::HardenedLeaf.to_core(),
3064                memory_limit_bytes: Some(512 * 1024),
3065                ..VmSettings::default()
3066            },
3067        );
3068        assert_eq!(
3069            normalized.execution_profile(),
3070            RustiaExecutionProfile::DETERMINISTIC_HARDENED_LEAF,
3071            "live attestation must report the VM-normalized profile, not requested metadata"
3072        );
3073    }
3074
3075    #[test]
3076    fn deterministic_builder_admits_deterministic_clock_providers() {
3077        let mut rustia = RustiaBuilder::deterministic()
3078            .wall_clock(ServiceClock::fixed(1.5))
3079            .build()
3080            .unwrap();
3081
3082        let time: f64 = rustia.eval("return os.time()").unwrap();
3083        assert_eq!(time, 1.5);
3084        let surface: bool = rustia
3085            .eval(
3086                "\
3087return type(os) == 'table'
3088    and type(os.time) == 'function'
3089    and type(os.clock) == 'function'
3090    and type(os.date) == 'function'
3091    and type(os.difftime) == 'function'
3092",
3093            )
3094            .unwrap();
3095        assert!(surface);
3096    }
3097
3098    #[cfg(not(target_arch = "wasm32"))]
3099    #[test]
3100    fn deterministic_builder_rejects_system_service_clocks() {
3101        let result = RustiaBuilder::deterministic()
3102            .wall_clock(ServiceClock::system())
3103            .build();
3104        let Err(Error {
3105            kind: crate::ErrorKind::Vm(error),
3106            ..
3107        }) = result
3108        else {
3109            panic!("expected deterministic profile to reject a nondeterministic wall clock");
3110        };
3111        assert!(matches!(error.kind, VmErrorKind::CapabilityRemoved { .. }));
3112
3113        let result = RustiaBuilder::deterministic()
3114            .monotonic_clock(ServiceClock::monotonic())
3115            .build();
3116        let Err(Error {
3117            kind: crate::ErrorKind::Vm(error),
3118            ..
3119        }) = result
3120        else {
3121            panic!("expected deterministic profile to reject a nondeterministic monotonic clock");
3122        };
3123        assert!(matches!(error.kind, VmErrorKind::CapabilityRemoved { .. }));
3124
3125        let result = RustiaBuilder::deterministic()
3126            .entropy(ServiceEntropy::system())
3127            .build();
3128        let Err(Error {
3129            kind: crate::ErrorKind::Vm(error),
3130            ..
3131        }) = result
3132        else {
3133            panic!("expected deterministic profile to reject nondeterministic entropy");
3134        };
3135        assert!(matches!(error.kind, VmErrorKind::CapabilityRemoved { .. }));
3136    }
3137
3138    #[test]
3139    fn fixed_entropy_is_reproducible_and_changes_the_initial_random_sequence() {
3140        let sequence = |seed| {
3141            let mut rustia = RustiaBuilder::standard()
3142                .entropy(ServiceEntropy::fixed(seed))
3143                .build()
3144                .unwrap();
3145            [
3146                rustia.eval::<f64>("return math.random()").unwrap(),
3147                rustia.eval::<f64>("return math.random()").unwrap(),
3148            ]
3149        };
3150
3151        assert_eq!(sequence(42), sequence(42));
3152        assert_ne!(sequence(42), sequence(43));
3153        assert_eq!(sequence(0), {
3154            let mut rustia = RustiaBuilder::standard().build().unwrap();
3155            [
3156                rustia.eval::<f64>("return math.random()").unwrap(),
3157                rustia.eval::<f64>("return math.random()").unwrap(),
3158            ]
3159        });
3160    }
3161
3162    #[test]
3163    fn standard_preset_keeps_the_pinned_epoch_and_logical_clock_by_default() {
3164        let mut rustia = Rustia::builder().build().unwrap();
3165
3166        let time: f64 = rustia.eval("return os.time()").unwrap();
3167        assert_eq!(time, 1_700_000_000.0);
3168        let logical: bool = rustia
3169            .eval(
3170                "\
3171local first = os.clock()
3172local second = os.clock()
3173return first >= 0 and second >= first
3174",
3175            )
3176            .unwrap();
3177        assert!(logical);
3178    }
3179
3180    #[test]
3181    fn decision_reset_invalidates_every_retained_facade_handle() {
3182        assert_eq!(RUSTIA_DECISION_RESET_ABI_VERSION, 1);
3183        let module = Rustia::compile_module(
3184            "decision.luau",
3185            "return { answer = 42, decide = function(x) return x + 1 end }",
3186        )
3187        .unwrap();
3188        let mut rustia = RustiaBuilder::deterministic().build().unwrap();
3189        let exports = rustia.install(&module).unwrap();
3190        let decide = exports.function(&mut rustia, "decide").unwrap();
3191        let exports_clone = exports.clone();
3192        let decide_clone = decide.clone();
3193
3194        assert_eq!(exports.decision_epoch(), 0);
3195        assert_eq!(decide.decision_epoch(), 0);
3196        assert_eq!(decide.call::<_, f64>(&mut rustia, (4.0,)).unwrap(), 5.0);
3197
3198        rustia.reset_decision().unwrap();
3199        assert_eq!(rustia.decision_epoch(), 1);
3200        for result in [
3201            exports.get::<f64>(&mut rustia, "answer").map(|_| ()),
3202            exports_clone.get::<f64>(&mut rustia, "answer").map(|_| ()),
3203            decide.call::<_, f64>(&mut rustia, ()).map(|_| ()),
3204            decide_clone.call::<_, f64>(&mut rustia, ()).map(|_| ()),
3205        ] {
3206            let error = result.expect_err("pre-reset handle must be stale");
3207            assert!(
3208                error.to_string().contains("decision epoch 0"),
3209                "unexpected stale-handle error: {error}"
3210            );
3211        }
3212
3213        let fresh = rustia.install(&module).unwrap();
3214        let fresh_decide = fresh.function(&mut rustia, "decide").unwrap();
3215        assert_eq!(fresh.decision_epoch(), 1);
3216        assert_eq!(
3217            fresh_decide.call::<_, f64>(&mut rustia, (9.0,)).unwrap(),
3218            10.0
3219        );
3220    }
3221
3222    #[test]
3223    fn decision_reset_discards_guest_state_and_restores_host_configuration_and_rng() {
3224        let settings = VmSettings {
3225            deterministic_gc_interval: NonZeroU64::new(8).unwrap(),
3226            enable_memory_tracking: true,
3227            ..VmSettings::default()
3228        };
3229        let extension = RustiaExtension::new("host").fn_pure("bias", || -> f64 { 7.0 });
3230        let mut rustia = RustiaBuilder::deterministic()
3231            .raw_settings(settings)
3232            .wall_clock(ServiceClock::fixed(1_234.0))
3233            .extension(extension)
3234            .build()
3235            .unwrap();
3236        rustia
3237            .add_pure_fn("double", |value: f64| value * 2.0)
3238            .unwrap();
3239        rustia.insert_global("input", 5.0).unwrap();
3240
3241        let configured: bool = rustia
3242            .eval(
3243                "\
3244decision_global = (decision_global or 0) + 1
3245return input == 5 and decision_global == 1
3246    and host.bias() == 7 and double(3) == 6 and os.time() == 1234
3247",
3248            )
3249            .unwrap();
3250        assert!(configured);
3251        let first_random: Vec<f64> = rustia
3252            .eval("return { math.random(), math.random(), math.random() }")
3253            .unwrap();
3254        assert!(rustia.vm().deterministic_collection_count() > 0);
3255        let peak_before_reset = rustia.memory_stats().peak_live_bytes().unwrap();
3256
3257        rustia.reset_decision().unwrap();
3258        assert_eq!(rustia.vm().deterministic_collection_count(), 0);
3259        assert_eq!(
3260            rustia.memory_stats().peak_live_bytes(),
3261            Some(peak_before_reset),
3262            "lifetime peak telemetry must survive a decision reset"
3263        );
3264        let clean_and_configured: bool = rustia
3265            .eval(
3266                "\
3267return input == nil and decision_global == nil
3268    and host.bias() == 7 and double(3) == 6 and os.time() == 1234
3269",
3270            )
3271            .unwrap();
3272        assert!(clean_and_configured);
3273        let second_random: Vec<f64> = rustia
3274            .eval("return { math.random(), math.random(), math.random() }")
3275            .unwrap();
3276        assert_eq!(first_random, second_random);
3277        assert!(rustia.vm().deterministic_collection_count() > 0);
3278    }
3279
3280    #[test]
3281    fn decision_reset_reaches_a_many_decision_memory_plateau() {
3282        let module = Rustia::compile_module(
3283            "plateau.luau",
3284            "\
3285decision_global = {}
3286for i = 1, 64 do
3287    decision_global[i] = { value = i, label = 'temporary-' .. i }
3288end
3289local thread = coroutine.create(function()
3290    coroutine.yield(decision_global)
3291end)
3292coroutine.resume(thread)
3293return { count = #decision_global }
3294",
3295        )
3296        .unwrap();
3297        let mut rustia = RustiaBuilder::deterministic().build().unwrap();
3298        let mut plateau = None;
3299
3300        for decision in 0..600 {
3301            let exports = rustia.install(&module).unwrap();
3302            assert_eq!(exports.get::<usize>(&mut rustia, "count").unwrap(), 64);
3303            rustia.reset_decision().unwrap();
3304            let stats = rustia.memory_stats();
3305            if decision == 49 {
3306                plateau = Some(stats);
3307            } else if decision > 49 {
3308                assert_eq!(
3309                    Some(stats),
3310                    plateau,
3311                    "VM memory changed after the warm plateau at decision {decision}"
3312                );
3313            }
3314        }
3315        assert_eq!(rustia.decision_epoch(), 600);
3316        let clean: bool = rustia.eval("return decision_global == nil").unwrap();
3317        assert!(clean);
3318    }
3319
3320    #[cfg(not(target_arch = "wasm32"))]
3321    #[test]
3322    fn live_preset_installs_system_clocks_and_the_stock_loadstring_compiler() {
3323        let mut rustia = RustiaBuilder::live().build().unwrap();
3324
3325        let time: f64 = rustia.eval("return os.time()").unwrap();
3326        assert!(
3327            time >= 1_700_000_000.0,
3328            "live() os.time() should read the real wall clock, got {time}"
3329        );
3330        let clock: f64 = rustia.eval("return os.clock()").unwrap();
3331        assert!(
3332            clock > 0.0,
3333            "live() os.clock() should read the real monotonic clock, got {clock}"
3334        );
3335        let answer: f64 = rustia.eval("return loadstring('return 40 + 2')()").unwrap();
3336        assert_eq!(answer, 42.0);
3337        // print goes to real process stdout via `print!`, which a test cannot read back from
3338        // inside the process; sink delivery is covered by the VM-level capture tests.
3339    }
3340}