Skip to main content

luaur/
lib.rs

1//! # luaur
2//!
3//! A faithful Rust translation of [Luau](https://github.com/luau-lang/luau) —
4//! Roblox's typed Lua. This umbrella crate re-exports the individual layers
5//! (lexer/parser/AST, bytecode, compiler, register VM, type checker, config and
6//! require resolution) and provides three thin convenience helpers — [`compile`],
7//! [`eval`], and [`check`] — for the common "compile a string / run a string /
8//! type-check a string" cases.
9//!
10//! For finer-grained control depend on the sub-crates directly; they are all
11//! re-exported here as modules.
12//!
13//! ```
14//! luaur::eval("assert(1 + 1 == 2)").unwrap();
15//! let bytecode = luaur::compile("return 2 + 2").unwrap();
16//! assert!(!bytecode.is_empty());
17//! luaur::check("local x: number = 1").unwrap();
18//! ```
19
20// Re-export the sub-crates as modules so `luaur::vm::...` etc. work from one dep.
21pub use luaur_analysis as analysis;
22pub use luaur_ast as ast;
23pub use luaur_bytecode as bytecode;
24pub use luaur_common as common;
25pub use luaur_compiler as compiler;
26pub use luaur_config as config;
27pub use luaur_require as require;
28pub use luaur_rt as rt;
29pub use luaur_vm as vm;
30
31/// Compile-time checked Luau source macros (`checked-macros` feature).
32#[cfg(feature = "checked-macros")]
33pub use luaur_checked_macros::{luau, luau_file};
34
35// The static type-check helpers now live on `luaur-rt` (behind its `typecheck`
36// feature, which the umbrella turns on by default). Re-export them so
37// `luaur::check` / `luaur::check_with_definitions` stay public, alongside the
38// structured `TypeDiagnostic` they now return.
39#[cfg(feature = "typecheck")]
40pub use luaur_rt::{
41    check, check_modules, check_modules_with_definitions, check_with_definitions, TypeDiagnostic,
42};
43
44// The headline high-level, mlua-style API. Re-exported flat at the crate root
45// so `luaur::Lua`, `luaur::Table`, etc. are available directly.
46//
47// NOTE on the derive macros: luaur-rt's `#[derive(UserData)]` /
48// `#[derive(FromLua)]` (behind luaur-rt's `macros` feature) emit absolute
49// `::luaur_rt::...` paths, so they are designed to be used through the
50// `luaur-rt` crate directly (`#[derive(luaur_rt::UserData)]`). They are **not**
51// re-exported here through the umbrella `luaur`: a `pub use` re-export does not
52// give the user's crate an extern-crate name `luaur_rt`, so the macro's
53// `::luaur_rt::...` paths would fail to resolve when invoked as
54// `luaur::UserData`. Mirroring mlua's single-crate model, the derives live on
55// `luaur-rt`. (Re-exported `luaur::rt` already aliases the crate for the rest
56// of the API.)
57pub use luaur_rt::{
58    AnyUserData, AppDataRef, AppDataRefMut, Buffer, Chunk, ChunkMode, Compiler, Debug, DebugWhat,
59    Error, ExternalError, ExternalResult, FromLua, FromLuaMulti, Function, FunctionInfo, Integer,
60    IntoLua, IntoLuaMulti, LightUserData, Lua, LuaNativeFn, LuaOptions, LuaString, MaybeSend,
61    MaybeSync, MetaMethod, MultiValue, Nil, Number, RegistryKey, Result, Scope, StdLib, Table,
62    TablePairs, TableSequence, Thread, ThreadStatus, TypeMetatable, UserData, UserDataFields,
63    UserDataMethods, UserDataRef, UserDataRefMut, Value, Variadic, Vector, VmState, WeakLua,
64};
65
66/// The `async`-feature coroutine-as-`Future`/`Stream` driver, re-exported when
67/// the umbrella's `async` feature (which forwards to `luaur-rt/async`) is on.
68#[cfg(feature = "async")]
69pub use luaur_rt::AsyncThread;
70
71/// The `serde`-feature Rust↔Lua serialization surface, re-exported when the
72/// umbrella's `serde` feature (forwarding to `luaur-rt/serde`) is on.
73#[cfg(feature = "serde")]
74pub use luaur_rt::{
75    DeserializeOptions, LuaDeserializer, LuaSerdeExt, LuaSerializer, SerializableTable,
76    SerializableValue, SerializeOptions,
77};
78
79/// Common entry points, re-exported for convenience.
80pub mod prelude {
81    /// The type-check helpers (the `typecheck` feature; on by default).
82    #[cfg(feature = "typecheck")]
83    pub use crate::{check, check_modules, check_modules_with_definitions, check_with_definitions};
84    pub use crate::{compile, eval};
85    pub use luaur_ast::records::parse_options::ParseOptions;
86    pub use luaur_compiler::records::compile_options::CompileOptions;
87
88    // The mlua-style high-level API prelude (Lua, Value, Table, traits, ...).
89    pub use luaur_rt::prelude::*;
90}
91
92use luaur_ast::records::parse_options::ParseOptions;
93use luaur_compiler::functions::compile::compile as compiler_compile;
94use luaur_compiler::records::compile_options::CompileOptions;
95
96/// Compile Luau `source` to bytecode using default compile/parse options.
97///
98/// On success the raw bytecode blob is returned. On a parse or compile error the
99/// compiler emits an "error blob" (a leading `\0` marker byte followed by the
100/// human-readable message); we detect that marker and surface the message as the
101/// `Err` variant instead.
102pub fn compile(source: &str) -> core::result::Result<Vec<u8>, String> {
103    let options = CompileOptions::default();
104    let parse_options = ParseOptions::default();
105    let owned = source.to_string();
106
107    let blob = compiler_compile(&owned, &options, &parse_options, None);
108
109    let bytes = blob.into_bytes();
110    // A leading 0 byte is the compiler's error marker (valid bytecode starts with
111    // the non-zero LBC_VERSION_TARGET).
112    if bytes.first() == Some(&0u8) {
113        let message = String::from_utf8_lossy(&bytes[1..]).into_owned();
114        return Err(message);
115    }
116    Ok(bytes)
117}
118
119/// Compile, load and run `source` on a fresh Luau VM, mirroring the reference
120/// `luau` CLI (`luau_run` driver): a fresh state with the standard library open,
121/// the chunk loaded into a new thread, and `lua_resume` to execute it.
122///
123/// Returns `Ok(())` if the script ran to completion, or `Err(message)` carrying
124/// the Lua error string (the same text the CLI would print) on a compile, load
125/// or runtime error.
126pub fn eval(source: &str) -> core::result::Result<(), String> {
127    use luaur_vm::functions::lua_l_newstate::lua_l_newstate;
128    use luaur_vm::functions::lua_l_openlibs::lua_l_openlibs;
129    use luaur_vm::functions::lua_newthread::lua_newthread;
130    use luaur_vm::functions::lua_resume::lua_resume;
131    use luaur_vm::functions::lua_tolstring::lua_tolstring;
132    use luaur_vm::functions::luau_load::luau_load;
133
134    let bytecode = compile(source)?;
135
136    // v11+ bytecode needs the default Luau flags enabled (matches the CLI's
137    // setLuauFlagsDefault(true)).
138    luaur_common::set_all_flags(true);
139
140    unsafe {
141        let l = lua_l_newstate();
142        if l.is_null() {
143            return Err("lua_l_newstate returned null".to_string());
144        }
145        lua_l_openlibs(l);
146
147        // Run on a fresh thread, like CLI/src/Repl.cpp's runCode.
148        let t = lua_newthread(l);
149        if t.is_null() {
150            return Err("lua_newthread returned null".to_string());
151        }
152
153        let rc = luau_load(
154            t,
155            c"=eval".as_ptr(),
156            bytecode.as_ptr() as *const core::ffi::c_char,
157            bytecode.len(),
158            0,
159        );
160        if rc != 0 {
161            return Err(format!("luau_load failed: rc={rc}"));
162        }
163
164        let status = lua_resume(t, core::ptr::null_mut(), 0);
165        if status != 0 {
166            // The error object is on top of T's stack; recover its text.
167            let mut len = 0usize;
168            let s = lua_tolstring(t, -1, &mut len);
169            let msg = if s.is_null() {
170                "<non-string error>".to_string()
171            } else {
172                let bytes = core::slice::from_raw_parts(s as *const u8, len);
173                String::from_utf8_lossy(bytes).into_owned()
174            };
175            return Err(msg);
176        }
177    }
178
179    Ok(())
180}
181
182#[cfg(test)]
183mod tests {
184    use super::{compile, eval};
185
186    #[test]
187    fn compile_returns_nonempty_bytecode() {
188        let bytecode = compile("return 1 + 1").expect("compile should succeed");
189        assert!(!bytecode.is_empty(), "bytecode must be non-empty");
190    }
191
192    #[test]
193    fn eval_runs_passing_assertion() {
194        eval("assert(1 + 1 == 2)").expect("eval should succeed");
195    }
196
197    #[test]
198    fn eval_reports_runtime_error() {
199        let err = eval("error('boom')").expect_err("eval should fail");
200        assert!(
201            err.contains("boom"),
202            "error message should mention boom: {err}"
203        );
204    }
205}