Skip to main content

luaur_rt/
chunk.rs

1//! The [`Chunk`] builder returned by [`Lua::load`]. Mirrors `mlua::Chunk`.
2//!
3//! Compilation reuses the same machinery as the umbrella `luaur` crate's
4//! `compile`/`eval` helpers: source -> `luaur_compiler::compile` -> bytecode ->
5//! `luau_load` -> a Lua function on the stack -> `lua_pcall`.
6
7use crate::error::{Error, Result};
8use crate::function::Function;
9use crate::state::Lua;
10use crate::sys::*;
11use crate::traits::FromLuaMulti;
12
13use luaur_ast::records::parse_options::ParseOptions;
14use luaur_compiler::functions::compile::compile as compiler_compile;
15use luaur_compiler::records::compile_options::CompileOptions;
16
17/// A not-yet-executed piece of Lua source.
18///
19/// Mirrors `mlua::Chunk`. Produced by [`Lua::load`]; finalized with
20/// [`Chunk::exec`], [`Chunk::eval`], or [`Chunk::into_function`].
21pub struct Chunk {
22    pub(crate) lua: Lua,
23    pub(crate) source: String,
24    pub(crate) name: String,
25    /// Optional environment table applied to the loaded function. Mirrors the
26    /// per-chunk environment set by `mlua::Chunk::set_environment`.
27    pub(crate) environment: Option<crate::table::Table>,
28    /// Optional per-chunk compiler. Mirrors `mlua::Chunk::set_compiler`. When
29    /// `None`, the VM-default compiler (`Lua::set_compiler`) is used, falling
30    /// back to luaur's default options.
31    pub(crate) compiler: Option<crate::compiler::Compiler>,
32}
33
34impl Chunk {
35    /// Override the chunk name shown in error messages / tracebacks.
36    ///
37    /// Mirrors `mlua::Chunk::set_name`.
38    pub fn set_name(mut self, name: impl Into<String>) -> Self {
39        self.name = name.into();
40        self
41    }
42
43    /// Set the environment (globals table) the loaded chunk runs in.
44    ///
45    /// Mirrors `mlua::Chunk::set_environment`. Applied to the function produced
46    /// by [`Chunk::into_function`] / [`Chunk::exec`] / [`Chunk::eval`].
47    pub fn set_environment(mut self, env: crate::table::Table) -> Self {
48        self.environment = Some(env);
49        self
50    }
51
52    /// Set the [`Compiler`](crate::Compiler) used to compile this chunk.
53    /// Mirrors `mlua::Chunk::set_compiler`.
54    pub fn set_compiler(mut self, compiler: crate::compiler::Compiler) -> Self {
55        self.compiler = Some(compiler);
56        self
57    }
58
59    /// Compile the chunk and call it with `args`, converting the result to `R`.
60    /// Mirrors `mlua::Chunk::call`.
61    pub fn call<R: FromLuaMulti>(self, args: impl crate::traits::IntoLuaMulti) -> Result<R> {
62        self.into_function()?.call::<R>(args)
63    }
64
65    /// The current chunk mode is always text here (luaur-rt loads source).
66    /// Mirrors `mlua::Chunk::set_mode` as a no-op accepting `mlua::ChunkMode`'s
67    /// role: luaur-rt auto-detects, so this is provided only for signature
68    /// parity and returns `self` unchanged.
69    pub fn set_mode(self, _mode: ChunkMode) -> Self {
70        self
71    }
72
73    /// The chunk name used for error messages / tracebacks.
74    ///
75    /// Mirrors `mlua::Chunk::name`.
76    pub fn name(&self) -> &str {
77        &self.name
78    }
79
80    /// Compile the source to bytecode (or return a [`Error::SyntaxError`]).
81    fn compile(&self) -> Result<Vec<u8>> {
82        // Pick the effective compiler: a per-chunk one wins over the VM-default
83        // one (`Lua::set_compiler`); otherwise use luaur's default options.
84        let effective = self.compiler.clone().or_else(|| self.lua.vm_compiler());
85        let mut scratch: Vec<*const core::ffi::c_char> = Vec::new();
86        let options = match &effective {
87            Some(c) => c.to_options(&mut scratch),
88            None => CompileOptions::default(),
89        };
90        let parse_options = ParseOptions::default();
91        let owned = self.source.clone();
92        let blob = compiler_compile(&owned, &options, &parse_options, None);
93        let bytes = blob.into_bytes();
94        // A leading 0 byte is the compiler's error marker.
95        if bytes.first() == Some(&0u8) {
96            let message = String::from_utf8_lossy(&bytes[1..]).into_owned();
97            // Luau reports a syntax error caused by hitting end-of-input (an
98            // unterminated block/expression) with a "got <eof>" suffix; mlua
99            // surfaces that as `incomplete_input: true` so a REPL can keep
100            // reading. Detect it the same way.
101            let incomplete_input = message.contains("<eof>");
102            return Err(Error::SyntaxError {
103                message,
104                incomplete_input,
105            });
106        }
107        Ok(bytes)
108    }
109
110    /// Load the compiled chunk and leave the resulting function on top of the
111    /// stack, returning a [`Function`] handle.
112    ///
113    /// Mirrors `mlua::Chunk::into_function`.
114    pub fn into_function(self) -> Result<Function> {
115        let bytecode = self.compile()?;
116        let state = self.lua.state();
117        unsafe {
118            let chunkname = std::ffi::CString::new(format!("={}", self.name))
119                .unwrap_or_else(|_| std::ffi::CString::new("=chunk").unwrap());
120            let rc = luau_load(
121                state,
122                chunkname.as_ptr(),
123                bytecode.as_ptr() as *const c_char,
124                bytecode.len(),
125                0,
126            );
127            if rc != 0 {
128                // luau_load failure leaves an error message on the stack.
129                return Err(self.lua.pop_error(rc));
130            }
131            let func = Function::from_ref(self.lua.pop_ref());
132            if let Some(env) = &self.environment {
133                func.set_environment(env.clone())?;
134            }
135            Ok(func)
136        }
137    }
138
139    /// Statically type-check this chunk's source against the owning [`Lua`]'s
140    /// accumulated host definitions (the `typecheck` feature).
141    ///
142    /// Returns `Ok(())` when the source type-checks clean, or
143    /// [`Error::TypeError`](crate::Error::TypeError) carrying the structured
144    /// diagnostics otherwise. Because Luau is dynamically typed, the check is
145    /// advisory — it composes with `?` ahead of [`Chunk::exec`] / [`Chunk::eval`]
146    /// without changing what running the chunk does:
147    ///
148    /// ```
149    /// # #[cfg(feature = "typecheck")] {
150    /// # use luaur_rt::Lua;
151    /// let lua = Lua::new();
152    /// let c = lua.load("local x: number = 1\nreturn x");
153    /// c.check().unwrap();
154    /// # }
155    /// ```
156    #[cfg(feature = "typecheck")]
157    #[cfg_attr(docsrs, doc(cfg(feature = "typecheck")))]
158    pub fn check(&self) -> Result<()> {
159        self.lua.check(&self.source)
160    }
161
162    /// Run the chunk for its side effects, discarding return values.
163    ///
164    /// Mirrors `mlua::Chunk::exec`.
165    pub fn exec(self) -> Result<()> {
166        let f = self.into_function()?;
167        f.call::<()>(())
168    }
169
170    /// Run the chunk and convert its return value(s) to `R`.
171    ///
172    /// Mirrors `mlua::Chunk::eval`. Like the Lua REPL (and mlua), the source is
173    /// first tried as an *expression* (by prepending `return `); if that
174    /// compiles it is used, otherwise the chunk is run as a statement block.
175    /// This is what lets `lua.load("coroutine.create(f)").eval::<Thread>()` and
176    /// `lua.load("function() ... end").eval::<Function>()` work.
177    pub fn eval<R: FromLuaMulti>(self) -> Result<R> {
178        // Try the expression form first.
179        let expr = Chunk {
180            lua: self.lua.clone(),
181            source: format!("return {}", self.source),
182            name: self.name.clone(),
183            environment: self.environment.clone(),
184            compiler: self.compiler.clone(),
185        };
186        if let Ok(f) = expr.into_function() {
187            return f.call::<R>(());
188        }
189        // Fall back to statement-block mode.
190        let f = self.into_function()?;
191        f.call::<R>(())
192    }
193
194    /// Asynchronously load the chunk and call it with `args` (the `async`
195    /// feature). Mirrors `mlua::Chunk::call_async`.
196    #[cfg(feature = "async")]
197    #[cfg_attr(docsrs, doc(cfg(feature = "async")))]
198    pub async fn call_async<R>(self, args: impl crate::traits::IntoLuaMulti) -> Result<R>
199    where
200        R: FromLuaMulti,
201    {
202        self.into_function()?.call_async(args).await
203    }
204
205    /// Asynchronously run the chunk for its side effects (the `async` feature).
206    /// Mirrors `mlua::Chunk::exec_async`.
207    #[cfg(feature = "async")]
208    #[cfg_attr(docsrs, doc(cfg(feature = "async")))]
209    pub async fn exec_async(self) -> Result<()> {
210        self.call_async(()).await
211    }
212
213    /// Asynchronously evaluate the chunk as an expression (or block) and convert
214    /// the result to `R` (the `async` feature). Mirrors `mlua::Chunk::eval_async`.
215    ///
216    /// Like [`Chunk::eval`], the source is first tried as an expression (by
217    /// prepending `return `); if that compiles it is driven, otherwise the chunk
218    /// runs as a statement block.
219    #[cfg(feature = "async")]
220    #[cfg_attr(docsrs, doc(cfg(feature = "async")))]
221    pub async fn eval_async<R>(self) -> Result<R>
222    where
223        R: FromLuaMulti,
224    {
225        // Try the expression form first (mirrors `eval`).
226        let expr = Chunk {
227            lua: self.lua.clone(),
228            source: format!("return {}", self.source),
229            name: self.name.clone(),
230            environment: self.environment.clone(),
231            compiler: self.compiler.clone(),
232        };
233        if let Ok(f) = expr.into_function() {
234            return f.call_async::<R>(()).await;
235        }
236        let f = self.into_function()?;
237        f.call_async::<R>(()).await
238    }
239}
240
241/// How a chunk's bytes are interpreted. Mirrors `mlua::ChunkMode`. luaur-rt
242/// always loads text source, so this exists for signature parity with
243/// [`Chunk::set_mode`].
244#[derive(Debug, Clone, Copy, PartialEq, Eq)]
245pub enum ChunkMode {
246    /// Text source (the default and only supported mode here).
247    Text,
248    /// Precompiled bytecode (not supported by luaur-rt's high-level loader).
249    Binary,
250}