Skip to main content

rustia/
chunk.rs

1use crate::serde_value::from_live;
2use crate::value::snapshot_value;
3use crate::{CompiledModule, Error, Exports, FromRustia, HostSchema, Result, Rustia, Table, Value};
4
5/// Luau source prepared for one execution or module installation.
6///
7/// Created by [`Rustia::load`]. Give it a [`source_name`](Self::source_name) for
8/// useful diagnostics, then choose how to run it:
9///
10/// - [`eval`](Self::eval) returns ordinary Rust data.
11/// - [`eval_serde`](Self::eval_serde) deserializes into a Rust structure.
12/// - [`eval_live`](Self::eval_live) keeps a script value alive without copying it.
13/// - [`exec`](Self::exec) discards the result.
14/// - [`install`](Self::install) returns exports and rolls back guest state on failure.
15///
16/// Loading alone does not parse or execute the source. Each operation consumes
17/// the chunk; use [`Rustia::compile_module`] to compile once and install repeatedly.
18#[must_use = "a chunk does nothing until eval, eval_live, eval_serde, exec, or install is called"]
19pub struct Chunk<'rustia, 'source, C = ()>
20where
21    C: HostSchema,
22{
23    rustia: &'rustia mut Rustia<C>,
24    source: &'source [u8],
25    source_name: Option<String>,
26    source_map: crate::SourceMap,
27    environment: Option<Table>,
28}
29
30impl<'rustia, 'source, C> Chunk<'rustia, 'source, C>
31where
32    C: HostSchema,
33{
34    pub(crate) fn new(rustia: &'rustia mut Rustia<C>, source: &'source [u8]) -> Self {
35        Self {
36            rustia,
37            source,
38            source_name: None,
39            source_map: crate::SourceMap::default(),
40            environment: None,
41        }
42    }
43
44    /// Labels the source in errors and module resolution.
45    ///
46    /// Use a filename or another meaningful label, such as `"rules.luau"`.
47    /// The default is `"chunk"`. This name is also the referrer passed to the
48    /// module resolver for `require`; setting it does not read a file.
49    pub fn source_name(mut self, source_name: impl Into<String>) -> Self {
50        self.source_name = Some(source_name.into());
51        self
52    }
53
54    /// Maps generated wrapper text out of human-facing diagnostics.
55    ///
56    /// This only changes error presentation; it does not change script execution
57    /// or the source names and lines visible to scripts. See [`crate::SourceMap`].
58    pub fn source_map(mut self, mapping: crate::SourceMap) -> Self {
59        self.source_map = mapping;
60        self
61    }
62
63    /// Selects the exact table used as this chunk's lexical environment.
64    ///
65    /// Cross-VM and reset-stale handles are rejected before parsing or
66    /// compilation. For [`install`](Self::install), mutations to this table
67    /// commit only when the complete installation succeeds.
68    /// This replaces the default environment; globals are inherited only if the
69    /// supplied table's metatable provides that behavior.
70    pub fn environment(mut self, environment: impl Into<Table>) -> Self {
71        self.environment = Some(environment.into());
72        self
73    }
74
75    /// Runs the script and converts its first result to Rust data.
76    ///
77    /// Conversion uses [`FromRustia`] over an owned snapshot. No returned value
78    /// means Luau `nil`; extra results are ignored. Use [`eval_live`](Self::eval_live)
79    /// for functions and cyclic tables, or to preserve shared table identity.
80    ///
81    /// Invalid source, execution failures, and incompatible result types return
82    /// [`Error`]. Script mutations remain in place even when execution or result
83    /// conversion fails; use [`install`](Self::install) for guest-state rollback.
84    ///
85    /// ```
86    /// # use rustia::Rustia;
87    /// # let mut vm = Rustia::builder().build()?;
88    /// let scores: Vec<i32> = vm.load("return {10, 20, 30}").eval()?;
89    /// assert_eq!(scores, vec![10, 20, 30]);
90    /// # Ok::<(), rustia::Error>(())
91    /// ```
92    pub fn eval<T>(self) -> Result<T>
93    where
94        T: FromRustia,
95    {
96        let name = self
97            .source_name
98            .clone()
99            .unwrap_or_else(|| "chunk".to_owned());
100        let limits =
101            crate::DiagnosticLimits::from_core(self.rustia.vm().settings().diagnostic_limits);
102        let (rustia, value) = self.execute_raw()?;
103        snapshot_value(rustia.vm_mut(), value)
104            .and_then(T::from_rustia)
105            .map_err(|error| error.with_result_source(&name, limits))
106    }
107
108    /// Runs the script and returns a live handle to its first result.
109    ///
110    /// The handle keeps the value alive in this interpreter and preserves shared
111    /// and cyclic objects. It remains usable until [`Rustia::reset_decision`],
112    /// and cannot be used with another interpreter. No returned value becomes
113    /// a handle to `nil`. As with [`eval`](Self::eval), errors do not undo mutations.
114    pub fn eval_live(self) -> Result<Value> {
115        let (rustia, value) = self.execute_raw()?;
116        Value::retain(rustia.vm_mut(), value)
117    }
118
119    /// Runs the script and deserializes its first result into Rust data.
120    ///
121    /// Reads the live VM graph without an intermediate [`crate::OwnedValue`].
122    /// The destination still owns its strings and collections. Invalid source,
123    /// execution failures, and data that does not match `T` return [`Error`];
124    /// mutations remain in place on failure.
125    ///
126    /// ```
127    /// # use rustia::Rustia;
128    /// # let mut vm = Rustia::builder().build()?;
129    /// #[derive(serde::Deserialize)]
130    /// struct Settings {
131    ///     volume: f64,
132    /// }
133    /// let settings: Settings = vm.load("return { volume = 0.5 }").eval_serde()?;
134    /// assert_eq!(settings.volume, 0.5);
135    /// # Ok::<(), rustia::Error>(())
136    /// ```
137    pub fn eval_serde<T>(self) -> Result<T>
138    where
139        T: serde::de::DeserializeOwned,
140    {
141        let name = self
142            .source_name
143            .clone()
144            .unwrap_or_else(|| "chunk".to_owned());
145        let limits =
146            crate::DiagnosticLimits::from_core(self.rustia.vm().settings().diagnostic_limits);
147        let (rustia, value) = self.execute_raw()?;
148        from_live(rustia.vm_mut(), value).map_err(|error| error.with_result_source(&name, limits))
149    }
150
151    /// Executes the chunk and discards its returned value.
152    ///
153    /// Parse, compilation, and execution errors are returned as [`Error`].
154    /// Changes made before an error are retained, as with [`eval`](Self::eval).
155    pub fn exec(self) -> Result<()> {
156        self.execute_raw().map(|_| ())
157    }
158
159    /// Runs the script as a module and keeps its returned exports alive.
160    ///
161    /// Without [`environment`](Self::environment), installation creates a
162    /// fresh module environment that inherits VM globals and binds `_G` to
163    /// itself. Compile, runtime, quota, and result-retention failures leave
164    /// prior guest-visible state unchanged.
165    /// External effects from Rust callbacks or the module resolver cannot be
166    /// undone. A successful installation does not invalidate earlier exports;
167    /// the application chooses when to replace its active handle.
168    ///
169    /// ```
170    /// # use rustia::Rustia;
171    /// # let mut vm = Rustia::builder().build()?;
172    /// let exports = vm.load("return { double = function(n) return n * 2 end }")
173    ///     .source_name("math.luau")
174    ///     .install()?;
175    /// let double = exports.function(&mut vm, "double")?;
176    /// let answer: i32 = double.call(&mut vm, (21,))?;
177    /// assert_eq!(answer, 42);
178    /// # Ok::<(), rustia::Error>(())
179    /// ```
180    pub fn install(self) -> Result<Exports> {
181        let (rustia, module, environment) = self.prepare()?;
182        let raw_environment = environment
183            .as_ref()
184            .map(|environment| environment.raw(rustia.vm(), "chunk environment handle"))
185            .transpose()?;
186        rustia.install_with_environment(&module, raw_environment)
187    }
188
189    fn execute_raw(self) -> Result<(&'rustia mut Rustia<C>, rustia_vm::Value)> {
190        let (rustia, module, environment) = self.prepare()?;
191        let raw_environment = environment
192            .as_ref()
193            .map(|environment| environment.raw(rustia.vm(), "chunk environment handle"))
194            .transpose()?;
195        let value = match raw_environment {
196            Some(environment) => rustia
197                .vm_mut()
198                .run_with_environment(&module.program, environment)
199                .map_err(Error::from_engine)?,
200            None => rustia
201                .vm_mut()
202                .run(&module.program)
203                .map_err(Error::from_engine)?,
204        };
205        Ok((rustia, value))
206    }
207
208    fn prepare(self) -> Result<(&'rustia mut Rustia<C>, CompiledModule, Option<Table>)> {
209        let Self {
210            rustia,
211            source,
212            source_name,
213            source_map,
214            environment,
215        } = self;
216        rustia.ensure_dynamic_source_loading_allowed()?;
217        environment
218            .as_ref()
219            .map(|environment| environment.raw(rustia.vm(), "chunk environment handle"))
220            .transpose()?;
221        source_map.validate(source)?;
222        let limits = crate::DiagnosticLimits::from_core(rustia.vm().settings().diagnostic_limits);
223        let mut module = Rustia::compile_module_bytes_with_constructor_order(
224            source_name.unwrap_or_else(|| "chunk".to_owned()),
225            source,
226            rustia.vm().profile() == rustia_vm::Profile::Puc51Compat,
227            limits,
228        )
229        .map_err(|error| {
230            source_map
231                .apply_error(error, source, limits)
232                .admit_diagnostic(rustia.vm())
233        })?;
234        source_map.apply(&mut module, source, limits);
235        Ok((rustia, module, environment))
236    }
237}
238
239impl From<&Table> for Table {
240    fn from(table: &Table) -> Self {
241        table.clone()
242    }
243}
244
245impl<C> std::fmt::Debug for Chunk<'_, '_, C>
246where
247    C: HostSchema,
248{
249    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
250        formatter
251            .debug_struct("Chunk")
252            .field("source_bytes", &self.source.len())
253            .field("source_name", &self.source_name)
254            .field("has_environment", &self.environment.is_some())
255            .finish_non_exhaustive()
256    }
257}