Compare commits

...

59 Commits

Author SHA1 Message Date
Alex Orlenko 928d94d255 v0.11.0 2025-07-14 15:33:02 +01:00
Alex Orlenko 583c35a172 Prepare for v0.11.0 2025-07-12 22:47:20 +01:00
Alex Orlenko 1791c599f4 mlua-sys: v0.8.2 2025-07-12 22:46:37 +01:00
Alex Orlenko 1e48817a64 Fix deregistering previously-registered userdata 2025-07-12 19:20:15 +01:00
Alex Orlenko 8d219503dd Opt-out from R: MaybeSend in AsyncThread<R> 2025-07-12 15:34:04 +01:00
Alex Orlenko 95367855c1 Return AsyncCallFuture<R> instead of opaque impl Future from ObjectLike trait. 2025-07-12 15:30:58 +01:00
Alex Orlenko 49389c4aa4 Wrap Function::coverage callback to RefCell (Luau) 2025-07-12 13:34:39 +01:00
Alex Orlenko 13dc2b5352 Don't release Lua lock prematurely when when accessing Buffer bytes (Luau) 2025-07-12 13:08:33 +01:00
Alex Orlenko 7afbf74128 Add MaybeSend bound to async methods on ObjectLike trait (sealed) 2025-07-12 12:45:36 +01:00
Alex Orlenko 06c3bd9d69 Fix serde README section (close #613) 2025-07-12 11:50:11 +01:00
Alex Orlenko 1ddaea60ce Bump luau-src to 0.15.4+luau682 2025-07-12 11:27:41 +01:00
Alex Orlenko a653d08768 Simplify Compiler::add_library_constant (combine lib and member) 2025-07-09 00:11:46 +01:00
Alex Orlenko 2b6b0144a1 Merge Compiler::set_vector_lib into set_vector_ctor 2025-07-08 23:55:45 +01:00
Alex Orlenko 4cfe0be945 Update CHANGELOG 2025-07-08 23:22:18 +01:00
Alex Orlenko a9a4814c3c Use StdString for consistency in chunk.rs 2025-07-08 22:25:23 +01:00
Alex Orlenko b1f73ec29d Update Luau Compiler methods to better control extra options:
- Add `add_mutable_global`
- Add `add_userdata_type`
- Replace `set_library_constants` with `add_library_constant`
- Add `add_disabled_builtin`
2025-07-08 22:22:44 +01:00
Alex Orlenko 61a2141151 Don't panic when fourth library searcher does not exists.
When disabling C modules, we remove the last two searchers (C & C all-in-one).
In Pluto the C searches may not exist by design, in this case check that 4th searcher is present before removing it.
Closes #530
2025-07-08 13:37:48 +01:00
Alex Orlenko dea38f27a5 Change !cfg!(..) to cfg!(not(..)) for better readability 2025-07-08 10:42:15 +01:00
Sculas 04aaa18dc8 feat: Allow external build scripts to link Lua libraries (#529)
Allow external build scripts to link Lua libraries
2025-07-08 10:30:26 +01:00
Alex Orlenko d8455c038a Update CHANGELOG 2025-07-08 10:12:03 +01:00
Alex Orlenko ca22ea3be7 Deprecate Debug::curr_line() in favour of Debug::current_line() that returns Option 2025-07-08 10:09:26 +01:00
Alex Orlenko cf05593d66 Fix Debug::is_tail_call 2025-07-08 10:05:37 +01:00
Alex Orlenko d011a1f851 Update CHANGELOG 2025-07-07 23:15:46 +01:00
Alex Orlenko 1ec4661bf9 mlua_derive: v0.11.0 2025-07-07 22:58:41 +01:00
Alex Orlenko d3b2999d2f Remove MaybeSend requirement from Require trait and add to Lua::create_require_function instead 2025-07-07 22:58:24 +01:00
Alex Orlenko 72f6536efb Check table requested capacity limits before enabling unprotected mode.
Lua tables have limits and can overflow, which must be captured in protected mode.
2025-07-07 22:57:30 +01:00
Alex Orlenko 646827a6bb Update Table::set_metatable
- Return Err (instead of panic) when trying to change readonly table (Luau)
- Slightly optimize performance
2025-07-06 11:37:02 +01:00
Alex Orlenko 1882931cd9 Optimize Table::metatable 2025-07-06 10:57:26 +01:00
Alex Orlenko c90cac5189 Add Lua::set_globals method to replace global environment.
Closes #611
2025-07-06 10:57:25 +01:00
Alex Orlenko c0d839d8d2 Make Thread::state pub (hidden) 2025-07-05 22:36:47 +01:00
Alex Orlenko 80471c6dad Optimize AnyUserData::metatable 2025-07-05 11:33:11 +01:00
Alex Orlenko 4b9d1cf271 Replace impl ToString with Into<StdString>
This is a more canonical way to accept any types of stirng but not arbitrary types that implement `Display`
2025-07-05 11:21:18 +01:00
Alex Orlenko 55c07f3b28 Some minor changes in Luau TextRequirer (comments, naming, etc) 2025-07-03 14:42:24 +01:00
Alex Orlenko ef4eabd327 Don't use Value::as_str() internally 2025-07-01 22:51:16 +01:00
Alex Orlenko a3302afdc1 Deprecate Value::as_str and Value::as_string_lossy
These methods don't follow Rust naming convention, see
https://rust-lang.github.io/api-guidelines/naming.html#ad-hoc-conversions-follow-as_-to_-into_-conventions-c-conv
2025-07-01 22:35:40 +01:00
Alex Orlenko dfb4e9a668 Fix LuaJIT stack inspection tests 2025-07-01 21:40:06 +01:00
Alex Orlenko 92db0f6d3a Fix Lua::inspect_stack callback proto 2025-06-30 23:28:04 +01:00
Alex Orlenko a3697ab1db Add Debug::function method to get function running at a given level.
Close #607
2025-06-30 23:25:36 +01:00
Alex Orlenko 052740db15 Save lua_State at the moment of constructing Debug instead of resolving it dynamically 2025-06-30 22:38:46 +01:00
Alex Orlenko faf547c154 Refactor Lua::inspect_stack and debug interface.
It was possible to cause a crash when getting a `Debug` instance and keeping it while deallocating the Lua stack frames.
2025-06-30 12:21:10 +01:00
Alex Orlenko 0de7cd1c7d Don't move or wrap ffi::lua_Debug struct when inspecting stack
This can cause a crash if `ffi::lua_Debug` changed between `lua_getstack` and `lua_getinfo` calls.
Fixes #610
2025-06-29 11:49:34 +01:00
Alex Orlenko 58953e5635 v0.11.0-beta.3 2025-06-23 23:23:07 +01:00
Alex Orlenko 6406de405d mlua-sys: v0.8.1 2025-06-23 23:22:53 +01:00
Alex Orlenko 727096dd3b Handle OOM error during luau_load (Luau >= 0.679) 2025-06-23 23:22:36 +01:00
Alex Orlenko 2445230759 Update CHANGELOG 2025-06-23 22:44:36 +01:00
Alex Orlenko 1cd2bdc808 Ignore test_async_require on windows 2025-06-23 16:37:46 +01:00
Alex Orlenko f8ed33a2aa Fix tests 2025-06-23 16:23:53 +01:00
Alex Orlenko 25955893e0 (Luau Require) Resolve Lua file path relative to the current directory
and unrelated to Rust source file location.
When a Lua file is required inside a Rust file (in a chunk), we should resolve the Lua file relative to the current directory,
instead of relative to the Rust chunk path.
The Rust file location is an internal information that does not exist when the compiled binary runs.
Fixes #605
2025-06-23 15:53:35 +01:00
Alex Orlenko 3f0c69b70b Fix logic to terminate futures on drop.
The underlying Lua thread must stay in yielded state rather than finished.
2025-06-17 15:25:21 +01:00
Alex Orlenko 9da98d42c7 Move ref_stack_pop into ExtraData method. 2025-06-16 22:25:26 +01:00
Alex Orlenko f539f60987 Fix Function::deep_clone() method (Luau).
The `lua_clonefunction` function can fail (and trigger GC) so we need to return Result instead of allowing longjmp
2025-06-16 21:41:29 +01:00
Alex Orlenko aa187e6663 Increase REF_STACK_RESERVE to 3 slots 2025-06-16 21:37:16 +01:00
Alex Orlenko ec10bf2a39 Revert 2e0e86dab2 (Update stack_value helper) 2025-06-16 21:33:47 +01:00
Alex Orlenko 3ea80b763d cargo fmt 2025-06-16 11:21:51 +01:00
Alex Orlenko 2e0e86dab2 Update stack_value helper.
It uses zero stack spaces in Luau, and ref thread for `WrappedError` check in ther Lua versions.
Close #597
2025-06-16 11:12:53 +01:00
Alex Orlenko 0ac7aebb27 Update Lua::sandbox doc 2025-06-13 15:51:31 +01:00
Alex Orlenko 634e5d4550 Reduce collectgarbage options in sandboxed mode
See https://luau.org/sandbox#library
2025-06-13 15:47:54 +01:00
Alex Orlenko 05d6c20520 One more mismatched-lifetime-syntaxes 2025-06-12 23:44:47 +01:00
Alex Orlenko 63e7cfd31b Satisfy mismatched-lifetime-syntaxes lint (nightly)
See rust-lang/rust#141787
2025-06-12 16:30:48 +01:00
49 changed files with 800 additions and 533 deletions
+21
View File
@@ -1,3 +1,24 @@
## v0.11.0 (Jul 14, 2025)
Changes since v0.11.0-beta.3
- Allow linking external Lua libraries in a build script (e.g. pluto) using `external` mlua-sys feature flag
- `Lua::inspect_stack` takes a callback with `&Debug` argument, instead of returning `Debug` directly
- Added `Debug::function` method to get function running at a given level
- `Debug::curr_line` is deprecated in favour of `Debug::current_line` that returns `Option<usize>`
- Added `Lua::set_globals` method to replace global environment
- `Table::set_metatable` now returns `Result<()>` (this operation can fail in sandboxed Luau mode)
- `impl ToString` replaced with `Into<StdString>` in `UserData` registration
- `Value::as_str` and `Value::as_string_lossy` methods are deprecated (as they are non-idiomatic)
- Bugfixes and improvements
## v0.11.0-beta.3 (Jun 23, 2025)
- Luau in sandboxed mode has reduced options in `collectgarbage` function (to follow the official doc)
- `Function::deep_clone` now returns `Result<Function>` as this operation can trigger memory errors
- Luau "Require" resolves included Lua files relative to the current directory (#605)
- Fixed bug when finalizing `AsyncThread` on drop (`call_async` methods family)
## v0.11.0-beta.2 (Jun 12, 2025)
- Lua 5.4 updated to 5.4.8
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "mlua"
version = "0.11.0-beta.2" # remember to update mlua_derive
version = "0.11.0" # remember to update mlua_derive
authors = ["Aleksandr Orlenko <zxteam@pm.me>", "kyren <catherine@kyju.org>"]
rust-version = "1.79.0"
edition = "2021"
@@ -49,7 +49,7 @@ userdata-wrappers = ["parking_lot/send_guard"]
serialize = ["serde"]
[dependencies]
mlua_derive = { version = "=0.11.0-beta.2", optional = true, path = "mlua_derive" }
mlua_derive = { version = "=0.11.0", optional = true, path = "mlua_derive" }
bstr = { version = "1.0", features = ["std"], default-features = false }
either = "1.0"
num-traits = { version = "0.2.14" }
+5 -11
View File
@@ -17,12 +17,6 @@
[Benchmarks]: https://github.com/khvzak/script-bench-rs
[FAQ]: FAQ.md
# The main branch is the development version of `mlua`. Please see the [v0.10](https://github.com/mlua-rs/mlua/tree/v0.10) branch for the stable versions of `mlua`.
> **Note**
>
> See v0.10 [release notes](https://github.com/mlua-rs/mlua/blob/main/docs/release_notes/v0.10.md).
`mlua` is a set of bindings to the [Lua](https://www.lua.org) programming language for Rust with a goal to provide a
_safe_ (as much as possible), high level, easy to use, practical and flexible API.
@@ -100,11 +94,11 @@ cargo run --example async_http_server --features=lua54,async,macros,send
curl -v http://localhost:3000
```
### Serialization (serde) support
### Serde support
With the `serde` feature flag enabled, `mlua` allows you to serialize/deserialize any type that implements [`serde::Serialize`] and [`serde::Deserialize`] into/from [`mlua::Value`]. In addition, `mlua` provides the [`serde::Serialize`] trait implementation for it (including `UserData` support).
With the `serde` feature flag enabled, `mlua` allows you to serialize/deserialize any type that implements [`serde::Serialize`] and [`serde::Deserialize`] into/from [`mlua::Value`]. In addition, `mlua` provides the [`serde::Serialize`] trait implementation for `mlua::Value` (including `UserData` support).
[Example](examples/serialize.rs)
[Example](examples/serde.rs)
[`serde::Serialize`]: https://docs.serde.rs/serde/ser/trait.Serialize.html
[`serde::Deserialize`]: https://docs.serde.rs/serde/de/trait.Deserialize.html
@@ -135,7 +129,7 @@ Add to `Cargo.toml`:
``` toml
[dependencies]
mlua = { version = "0.10", features = ["lua54", "vendored"] }
mlua = { version = "0.11", features = ["lua54", "vendored"] }
```
`main.rs`
@@ -170,7 +164,7 @@ Add to `Cargo.toml`:
crate-type = ["cdylib"]
[dependencies]
mlua = { version = "0.10", features = ["lua54", "module"] }
mlua = { version = "0.11", features = ["lua54", "module"] }
```
`lib.rs`:
+3 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "mlua-sys"
version = "0.8.0"
version = "0.8.2"
authors = ["Aleksandr Orlenko <zxteam@pm.me>"]
rust-version = "1.71"
edition = "2021"
@@ -30,6 +30,7 @@ luau = ["luau0-src"]
luau-codegen = ["luau"]
luau-vector4 = ["luau"]
vendored = ["lua-src", "luajit-src"]
external = []
module = []
[dependencies]
@@ -40,7 +41,7 @@ cfg-if = "1.0"
pkg-config = "0.3.17"
lua-src = { version = ">= 548.1.0, < 548.2.0", optional = true }
luajit-src = { version = ">= 210.6.0, < 210.7.0", optional = true }
luau0-src = { version = "0.15.0", optional = true }
luau0-src = { version = "0.15.4", optional = true }
[lints.rust]
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(raw_dylib)'] }
+19 -12
View File
@@ -14,22 +14,29 @@ fn main() {
#[cfg(all(feature = "luau", feature = "module", windows))]
compile_error!("Luau does not support `module` mode on Windows");
#[cfg(all(feature = "module", feature = "vendored"))]
compile_error!("`vendored` and `module` features are mutually exclusive");
#[cfg(any(
all(feature = "vendored", any(feature = "external", feature = "module")),
all(feature = "external", any(feature = "vendored", feature = "module")),
all(feature = "module", any(feature = "vendored", feature = "external"))
))]
compile_error!("`vendored`, `external` and `module` features are mutually exclusive");
println!("cargo:rerun-if-changed=build");
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
if target_os == "windows" && cfg!(feature = "module") {
if !std::env::var("LUA_LIB_NAME").unwrap_or_default().is_empty() {
// Don't use raw-dylib linking
find::probe_lua();
return;
// Check if compilation and linking is handled by external crate
if cfg!(not(feature = "external")) {
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
if target_os == "windows" && cfg!(feature = "module") {
if !std::env::var("LUA_LIB_NAME").unwrap_or_default().is_empty() {
// Don't use raw-dylib linking
find::probe_lua();
return;
}
println!("cargo:rustc-cfg=raw_dylib");
}
println!("cargo:rustc-cfg=raw_dylib");
#[cfg(not(feature = "module"))]
find::probe_lua();
}
#[cfg(not(feature = "module"))]
find::probe_lua();
}
+12 -5
View File
@@ -388,7 +388,7 @@ pub unsafe fn luaL_loadbufferenv(
}
}
if chunk_is_text {
let status = if chunk_is_text {
if env < 0 {
env -= 1;
}
@@ -397,14 +397,21 @@ pub unsafe fn luaL_loadbufferenv(
ptr::write(data_ud, data);
// By deferring the `free(data)` to the userdata destructor, we ensure that
// even if `luau_load` throws an error, the `data` is still released.
let ok = luau_load(L, name, data, size, env) == 0;
let status = luau_load(L, name, data, size, env);
lua_replace(L, -2); // replace data with the result
if !ok {
return LUA_ERRSYNTAX;
status
} else {
luau_load(L, name, data, size, env)
};
if status != 0 {
if lua_isstring(L, -1) != 0 && CStr::from_ptr(lua_tostring(L, -1)) == c"not enough memory" {
// A case for Luau >= 0.679
return LUA_ERRMEM;
}
} else if luau_load(L, name, data, size, env) != 0 {
return LUA_ERRSYNTAX;
}
LUA_OK
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "mlua_derive"
version = "0.11.0-beta.2"
version = "0.11.0"
authors = ["Aleksandr Orlenko <zxteam@pm.me>"]
edition = "2021"
description = "Procedural macros for the mlua crate."
+3 -3
View File
@@ -129,13 +129,13 @@ pub fn chunk(input: TokenStream) -> TokenStream {
let globals = lua.globals();
let env = lua.create_table()?;
let meta = lua.create_table()?;
meta.raw_set("__index", globals.clone())?;
meta.raw_set("__newindex", globals)?;
meta.raw_set("__index", &globals)?;
meta.raw_set("__newindex", &globals)?;
// Add captured variables
#(#caps)*
env.set_metatable(Some(meta));
env.set_metatable(Some(meta))?;
Ok(env)
};
+18 -11
View File
@@ -1,6 +1,7 @@
#[cfg(feature = "serde")]
use serde::ser::{Serialize, Serializer};
use crate::state::RawLua;
use crate::types::ValueRef;
/// A Luau buffer type.
@@ -16,12 +17,14 @@ pub struct Buffer(pub(crate) ValueRef);
impl Buffer {
/// Copies the buffer data into a new `Vec<u8>`.
pub fn to_vec(&self) -> Vec<u8> {
unsafe { self.as_slice().to_vec() }
let lua = self.0.lua.lock();
self.as_slice(&lua).to_vec()
}
/// Returns the length of the buffer.
pub fn len(&self) -> usize {
unsafe { self.as_slice().len() }
let lua = self.0.lua.lock();
self.as_slice(&lua).len()
}
/// Returns `true` if the buffer is empty.
@@ -34,7 +37,8 @@ impl Buffer {
/// Offset is 0-based.
#[track_caller]
pub fn read_bytes<const N: usize>(&self, offset: usize) -> [u8; N] {
let data = unsafe { self.as_slice() };
let lua = self.0.lua.lock();
let data = self.as_slice(&lua);
let mut bytes = [0u8; N];
bytes.copy_from_slice(&data[offset..offset + N]);
bytes
@@ -45,21 +49,23 @@ impl Buffer {
/// Offset is 0-based.
#[track_caller]
pub fn write_bytes(&self, offset: usize, bytes: &[u8]) {
let lua = self.0.lua.lock();
let data = unsafe {
let (buf, size) = self.as_raw_parts();
let (buf, size) = self.as_raw_parts(&lua);
std::slice::from_raw_parts_mut(buf, size)
};
data[offset..offset + bytes.len()].copy_from_slice(bytes);
}
pub(crate) unsafe fn as_slice(&self) -> &[u8] {
let (buf, size) = self.as_raw_parts();
std::slice::from_raw_parts(buf, size)
pub(crate) fn as_slice(&self, lua: &RawLua) -> &[u8] {
unsafe {
let (buf, size) = self.as_raw_parts(lua);
std::slice::from_raw_parts(buf, size)
}
}
#[cfg(feature = "luau")]
unsafe fn as_raw_parts(&self) -> (*mut u8, usize) {
let lua = self.0.lua.lock();
unsafe fn as_raw_parts(&self, lua: &RawLua) -> (*mut u8, usize) {
let mut size = 0usize;
let buf = ffi::lua_tobuffer(lua.ref_thread(), self.0.index, &mut size);
mlua_assert!(!buf.is_null(), "invalid Luau buffer");
@@ -67,7 +73,7 @@ impl Buffer {
}
#[cfg(not(feature = "luau"))]
unsafe fn as_raw_parts(&self) -> (*mut u8, usize) {
unsafe fn as_raw_parts(&self, lua: &RawLua) -> (*mut u8, usize) {
unreachable!()
}
}
@@ -75,7 +81,8 @@ impl Buffer {
#[cfg(feature = "serde")]
impl Serialize for Buffer {
fn serialize<S: Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
serializer.serialize_bytes(unsafe { self.as_slice() })
let lua = self.0.lua.lock();
serializer.serialize_bytes(self.as_slice(&lua))
}
}
+98 -45
View File
@@ -160,18 +160,39 @@ pub enum CompileConstant {
Boolean(bool),
Number(crate::Number),
Vector(crate::Vector),
String(String),
String(StdString),
}
#[cfg(feature = "luau")]
impl From<&'static str> for CompileConstant {
fn from(s: &'static str) -> Self {
CompileConstant::String(s.to_string())
#[cfg(any(feature = "luau", doc))]
impl From<bool> for CompileConstant {
fn from(b: bool) -> Self {
CompileConstant::Boolean(b)
}
}
#[cfg(any(feature = "luau", doc))]
type LibraryMemberConstantMap = std::sync::Arc<HashMap<(String, String), CompileConstant>>;
impl From<crate::Number> for CompileConstant {
fn from(n: crate::Number) -> Self {
CompileConstant::Number(n)
}
}
#[cfg(any(feature = "luau", doc))]
impl From<crate::Vector> for CompileConstant {
fn from(v: crate::Vector) -> Self {
CompileConstant::Vector(v)
}
}
#[cfg(any(feature = "luau", doc))]
impl From<&str> for CompileConstant {
fn from(s: &str) -> Self {
CompileConstant::String(s.to_owned())
}
}
#[cfg(any(feature = "luau", doc))]
type LibraryMemberConstantMap = HashMap<(StdString, StdString), CompileConstant>;
/// Luau compiler
#[cfg(any(feature = "luau", doc))]
@@ -182,14 +203,14 @@ pub struct Compiler {
debug_level: u8,
type_info_level: u8,
coverage_level: u8,
vector_lib: Option<String>,
vector_ctor: Option<String>,
vector_type: Option<String>,
mutable_globals: Vec<String>,
userdata_types: Vec<String>,
libraries_with_known_members: Vec<String>,
vector_lib: Option<StdString>,
vector_ctor: Option<StdString>,
vector_type: Option<StdString>,
mutable_globals: Vec<StdString>,
userdata_types: Vec<StdString>,
libraries_with_known_members: Vec<StdString>,
library_constants: Option<LibraryMemberConstantMap>,
disabled_builtins: Vec<String>,
disabled_builtins: Vec<StdString>,
}
#[cfg(any(feature = "luau", doc))]
@@ -267,70 +288,102 @@ impl Compiler {
self
}
/// Sets alternative global builtin to construct vectors, in addition to default builtin
/// `vector.create`.
///
/// To set the library and method name, use the `lib.ctor` format.
#[doc(hidden)]
#[must_use]
pub fn set_vector_lib(mut self, lib: impl Into<String>) -> Self {
self.vector_lib = Some(lib.into());
pub fn set_vector_ctor(mut self, ctor: impl Into<StdString>) -> Self {
let ctor = ctor.into();
let lib_ctor = ctor.split_once('.');
self.vector_lib = lib_ctor.as_ref().map(|&(lib, _)| lib.to_owned());
self.vector_ctor = (lib_ctor.as_ref())
.map(|&(_, ctor)| ctor.to_owned())
.or(Some(ctor));
self
}
/// Sets alternative vector type name for type tables, in addition to default type `vector`.
#[doc(hidden)]
#[must_use]
pub fn set_vector_ctor(mut self, ctor: impl Into<String>) -> Self {
self.vector_ctor = Some(ctor.into());
self
}
#[doc(hidden)]
#[must_use]
pub fn set_vector_type(mut self, r#type: impl Into<String>) -> Self {
pub fn set_vector_type(mut self, r#type: impl Into<StdString>) -> Self {
self.vector_type = Some(r#type.into());
self
}
/// Adds a mutable global.
///
/// It disables the import optimization for fields accessed through it.
#[must_use]
pub fn add_mutable_global(mut self, global: impl Into<StdString>) -> Self {
self.mutable_globals.push(global.into());
self
}
/// Sets a list of globals that are mutable.
///
/// It disables the import optimization for fields accessed through these.
#[must_use]
pub fn set_mutable_globals<S: Into<String>>(mut self, globals: Vec<S>) -> Self {
pub fn set_mutable_globals<S: Into<StdString>>(mut self, globals: impl IntoIterator<Item = S>) -> Self {
self.mutable_globals = globals.into_iter().map(|s| s.into()).collect();
self
}
/// Adds a userdata type to the list that will be included in the type information.
#[must_use]
pub fn add_userdata_type(mut self, r#type: impl Into<StdString>) -> Self {
self.userdata_types.push(r#type.into());
self
}
/// Sets a list of userdata types that will be included in the type information.
#[must_use]
pub fn set_userdata_types<S: Into<String>>(mut self, types: Vec<S>) -> Self {
pub fn set_userdata_types<S: Into<StdString>>(mut self, types: impl IntoIterator<Item = S>) -> Self {
self.userdata_types = types.into_iter().map(|s| s.into()).collect();
self
}
/// Sets constants for known library members.
/// Adds a constant for a known library member.
///
/// The constants are used by the compiler to optimize the generated bytecode.
/// Optimization level must be at least 2 for this to have any effect.
///
/// The first element of the tuple is the library name,the second is the member name, and the
/// third is the constant value.
/// The `name` is a string in the format `lib.member`, where `lib` is the library name
/// and `member` is the member (constant) name.
#[must_use]
pub fn set_library_constants<L, M>(mut self, constants: Vec<(L, M, CompileConstant)>) -> Self
where
L: Into<String>,
M: Into<String>,
{
let map = constants
.into_iter()
.map(|(lib, member, cons)| ((lib.into(), member.into()), cons))
.collect::<HashMap<_, _>>();
self.library_constants = Some(std::sync::Arc::new(map));
self.libraries_with_known_members = (self.library_constants.clone())
.map(|map| map.keys().map(|(lib, _)| lib.clone()).collect())
.unwrap_or_default();
pub fn add_library_constant(
mut self,
name: impl AsRef<str>,
r#const: impl Into<CompileConstant>,
) -> Self {
let Some((lib, member)) = name.as_ref().split_once('.') else {
return self;
};
let (lib, member) = (lib.to_owned(), member.to_owned());
if !self.libraries_with_known_members.contains(&lib) {
self.libraries_with_known_members.push(lib.clone());
}
self.library_constants
.get_or_insert_with(HashMap::new)
.insert((lib, member), r#const.into());
self
}
/// Adds a builtin that should be disabled.
#[must_use]
pub fn add_disabled_builtin(mut self, builtin: impl Into<StdString>) -> Self {
self.disabled_builtins.push(builtin.into());
self
}
/// Sets a list of builtins that should be disabled.
#[must_use]
pub fn set_disabled_builtins<S: Into<String>>(mut self, builtins: Vec<S>) -> Self {
pub fn set_disabled_builtins<S: Into<StdString>>(
mut self,
builtins: impl IntoIterator<Item = S>,
) -> Self {
self.disabled_builtins = builtins.into_iter().map(|s| s.into()).collect();
self
}
@@ -437,7 +490,7 @@ impl Compiler {
if bytecode.first() == Some(&0) {
// The rest of the bytecode is the error message starting with `:`
// See https://github.com/luau-lang/luau/blob/0.640/Compiler/src/Compiler.cpp#L4336
let message = String::from_utf8_lossy(&bytecode[2..]).to_string();
let message = StdString::from_utf8_lossy(&bytecode[2..]).into_owned();
return Err(Error::SyntaxError {
incomplete_input: message.ends_with("<eof>"),
message,
@@ -460,7 +513,7 @@ impl Chunk<'_> {
/// - `@` - file path (when truncation is needed, the end of the file path is kept, as this is
/// more useful for identifying the file)
/// - `=` - custom chunk name (when truncation is needed, the beginning of the name is kept)
pub fn set_name(mut self, name: impl Into<String>) -> Self {
pub fn set_name(mut self, name: impl Into<StdString>) -> Self {
self.name = name.into();
self
}
@@ -708,7 +761,7 @@ impl Chunk<'_> {
ChunkMode::Text
}
fn convert_name(name: String) -> Result<CString> {
fn convert_name(name: StdString) -> Result<CString> {
CString::new(name).map_err(|err| Error::runtime(format!("invalid name: {err}")))
}
+1 -1
View File
@@ -645,7 +645,7 @@ impl FromLua for BString {
match value {
Value::String(s) => Ok((*s.as_bytes()).into()),
#[cfg(feature = "luau")]
Value::Buffer(buf) => unsafe { Ok(buf.as_slice().into()) },
Value::Buffer(buf) => Ok(buf.to_vec().into()),
_ => Ok((*lua
.coerce_string(value)?
.ok_or_else(|| Error::FromLuaConversionError {
+85 -102
View File
@@ -1,66 +1,33 @@
use std::borrow::Cow;
use std::cell::UnsafeCell;
use std::ops::Deref;
#[cfg(not(feature = "luau"))]
use std::ops::{BitOr, BitOrAssign};
use std::os::raw::c_int;
use ffi::lua_Debug;
use ffi::{lua_Debug, lua_State};
use crate::function::Function;
use crate::state::RawLua;
use crate::types::ReentrantMutexGuard;
use crate::util::{linenumber_to_usize, ptr_to_lossy_str, ptr_to_str};
use crate::util::{assert_stack, linenumber_to_usize, ptr_to_lossy_str, ptr_to_str, StackGuard};
/// Contains information about currently executing Lua code.
///
/// The `Debug` structure is provided as a parameter to the hook function set with
/// [`Lua::set_hook`]. You may call the methods on this structure to retrieve information about the
/// Lua code executing at the time that the hook function was called. Further information can be
/// found in the Lua [documentation].
/// You may call the methods on this structure to retrieve information about the Lua code executing
/// at the specific level. Further information can be found in the Lua [documentation].
///
/// [documentation]: https://www.lua.org/manual/5.4/manual.html#lua_Debug
/// [`Lua::set_hook`]: crate::Lua::set_hook
pub struct Debug<'a> {
lua: EitherLua<'a>,
ar: ActivationRecord,
#[cfg(feature = "luau")]
state: *mut lua_State,
lua: &'a RawLua,
#[cfg_attr(not(feature = "luau"), allow(unused))]
level: c_int,
}
enum EitherLua<'a> {
Owned(ReentrantMutexGuard<'a, RawLua>),
#[cfg(not(feature = "luau"))]
Borrowed(&'a RawLua),
}
impl Deref for EitherLua<'_> {
type Target = RawLua;
fn deref(&self) -> &Self::Target {
match self {
EitherLua::Owned(guard) => guard,
#[cfg(not(feature = "luau"))]
EitherLua::Borrowed(lua) => lua,
}
}
ar: *mut lua_Debug,
}
impl<'a> Debug<'a> {
// We assume the lock is held when this function is called.
#[cfg(not(feature = "luau"))]
pub(crate) fn new(lua: &'a RawLua, ar: *mut lua_Debug) -> Self {
pub(crate) fn new(lua: &'a RawLua, level: c_int, ar: *mut lua_Debug) -> Self {
Debug {
lua: EitherLua::Borrowed(lua),
ar: ActivationRecord::Borrowed(ar),
}
}
pub(crate) fn new_owned(guard: ReentrantMutexGuard<'a, RawLua>, _level: c_int, ar: lua_Debug) -> Self {
Debug {
lua: EitherLua::Owned(guard),
ar: ActivationRecord::Owned(UnsafeCell::new(ar)),
#[cfg(feature = "luau")]
level: _level,
state: lua.state(),
lua,
ar,
level,
}
}
@@ -74,7 +41,7 @@ impl<'a> Debug<'a> {
#[cfg_attr(docsrs, doc(cfg(not(feature = "luau"))))]
pub fn event(&self) -> DebugEvent {
unsafe {
match (*self.ar.get()).event {
match (*self.ar).event {
ffi::LUA_HOOKCALL => DebugEvent::Call,
ffi::LUA_HOOKRET => DebugEvent::Ret,
ffi::LUA_HOOKTAILCALL => DebugEvent::TailCall,
@@ -85,24 +52,48 @@ impl<'a> Debug<'a> {
}
}
/// Corresponds to the `n` what mask.
pub fn names(&self) -> DebugNames {
/// Returns the function that is running at the given level.
///
/// Corresponds to the `f` "what" mask.
pub fn function(&self) -> Function {
unsafe {
let _sg = StackGuard::new(self.state);
assert_stack(self.state, 1);
#[cfg(not(feature = "luau"))]
mlua_assert!(
ffi::lua_getinfo(self.state, cstr!("f"), self.ar) != 0,
"lua_getinfo failed with `f`"
);
#[cfg(feature = "luau")]
mlua_assert!(
ffi::lua_getinfo(self.state, self.level, cstr!("f"), self.ar) != 0,
"lua_getinfo failed with `f`"
);
ffi::lua_xmove(self.state, self.lua.ref_thread(), 1);
Function(self.lua.pop_ref_thread())
}
}
/// Corresponds to the `n` "what" mask.
pub fn names(&self) -> DebugNames<'_> {
unsafe {
#[cfg(not(feature = "luau"))]
mlua_assert!(
ffi::lua_getinfo(self.lua.state(), cstr!("n"), self.ar.get()) != 0,
ffi::lua_getinfo(self.state, cstr!("n"), self.ar) != 0,
"lua_getinfo failed with `n`"
);
#[cfg(feature = "luau")]
mlua_assert!(
ffi::lua_getinfo(self.lua.state(), self.level, cstr!("n"), self.ar.get()) != 0,
ffi::lua_getinfo(self.state, self.level, cstr!("n"), self.ar) != 0,
"lua_getinfo failed with `n`"
);
DebugNames {
name: ptr_to_lossy_str((*self.ar.get()).name),
name: ptr_to_lossy_str((*self.ar).name),
#[cfg(not(feature = "luau"))]
name_what: match ptr_to_str((*self.ar.get()).namewhat) {
name_what: match ptr_to_str((*self.ar).namewhat) {
Some("") => None,
val => val,
},
@@ -112,118 +103,110 @@ impl<'a> Debug<'a> {
}
}
/// Corresponds to the `S` what mask.
pub fn source(&self) -> DebugSource {
/// Corresponds to the `S` "what" mask.
pub fn source(&self) -> DebugSource<'_> {
unsafe {
#[cfg(not(feature = "luau"))]
mlua_assert!(
ffi::lua_getinfo(self.lua.state(), cstr!("S"), self.ar.get()) != 0,
ffi::lua_getinfo(self.state, cstr!("S"), self.ar) != 0,
"lua_getinfo failed with `S`"
);
#[cfg(feature = "luau")]
mlua_assert!(
ffi::lua_getinfo(self.lua.state(), self.level, cstr!("s"), self.ar.get()) != 0,
ffi::lua_getinfo(self.state, self.level, cstr!("s"), self.ar) != 0,
"lua_getinfo failed with `s`"
);
DebugSource {
source: ptr_to_lossy_str((*self.ar.get()).source),
source: ptr_to_lossy_str((*self.ar).source),
#[cfg(not(feature = "luau"))]
short_src: ptr_to_lossy_str((*self.ar.get()).short_src.as_ptr()),
short_src: ptr_to_lossy_str((*self.ar).short_src.as_ptr()),
#[cfg(feature = "luau")]
short_src: ptr_to_lossy_str((*self.ar.get()).short_src),
line_defined: linenumber_to_usize((*self.ar.get()).linedefined),
short_src: ptr_to_lossy_str((*self.ar).short_src),
line_defined: linenumber_to_usize((*self.ar).linedefined),
#[cfg(not(feature = "luau"))]
last_line_defined: linenumber_to_usize((*self.ar.get()).lastlinedefined),
last_line_defined: linenumber_to_usize((*self.ar).lastlinedefined),
#[cfg(feature = "luau")]
last_line_defined: None,
what: ptr_to_str((*self.ar.get()).what).unwrap_or("main"),
what: ptr_to_str((*self.ar).what).unwrap_or("main"),
}
}
}
/// Corresponds to the `l` what mask. Returns the current line.
#[doc(hidden)]
#[deprecated(note = "Use `current_line` instead")]
pub fn curr_line(&self) -> i32 {
self.current_line().map(|n| n as i32).unwrap_or(-1)
}
/// Corresponds to the `l` "what" mask. Returns the current line.
pub fn current_line(&self) -> Option<usize> {
unsafe {
#[cfg(not(feature = "luau"))]
mlua_assert!(
ffi::lua_getinfo(self.lua.state(), cstr!("l"), self.ar.get()) != 0,
ffi::lua_getinfo(self.state, cstr!("l"), self.ar) != 0,
"lua_getinfo failed with `l`"
);
#[cfg(feature = "luau")]
mlua_assert!(
ffi::lua_getinfo(self.lua.state(), self.level, cstr!("l"), self.ar.get()) != 0,
ffi::lua_getinfo(self.state, self.level, cstr!("l"), self.ar) != 0,
"lua_getinfo failed with `l`"
);
(*self.ar.get()).currentline
linenumber_to_usize((*self.ar).currentline)
}
}
/// Corresponds to the `t` what mask. Returns true if the hook is in a function tail call, false
/// otherwise.
#[cfg(not(feature = "luau"))]
#[cfg_attr(docsrs, doc(cfg(not(feature = "luau"))))]
/// Corresponds to the `t` "what" mask. Returns true if the hook is in a function tail call,
/// false otherwise.
#[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52"))]
#[cfg_attr(
docsrs,
doc(cfg(any(feature = "lua54", feature = "lua53", feature = "lua52")))
)]
pub fn is_tail_call(&self) -> bool {
unsafe {
mlua_assert!(
ffi::lua_getinfo(self.lua.state(), cstr!("t"), self.ar.get()) != 0,
ffi::lua_getinfo(self.state, cstr!("t"), self.ar) != 0,
"lua_getinfo failed with `t`"
);
(*self.ar.get()).currentline != 0
(*self.ar).istailcall != 0
}
}
/// Corresponds to the `u` what mask.
/// Corresponds to the `u` "what" mask.
pub fn stack(&self) -> DebugStack {
unsafe {
#[cfg(not(feature = "luau"))]
mlua_assert!(
ffi::lua_getinfo(self.lua.state(), cstr!("u"), self.ar.get()) != 0,
ffi::lua_getinfo(self.state, cstr!("u"), self.ar) != 0,
"lua_getinfo failed with `u`"
);
#[cfg(feature = "luau")]
mlua_assert!(
ffi::lua_getinfo(self.lua.state(), self.level, cstr!("au"), self.ar.get()) != 0,
ffi::lua_getinfo(self.state, self.level, cstr!("au"), self.ar) != 0,
"lua_getinfo failed with `au`"
);
#[cfg(not(feature = "luau"))]
let stack = DebugStack {
num_ups: (*self.ar.get()).nups as _,
num_ups: (*self.ar).nups as _,
#[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52"))]
num_params: (*self.ar.get()).nparams as _,
num_params: (*self.ar).nparams as _,
#[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52"))]
is_vararg: (*self.ar.get()).isvararg != 0,
is_vararg: (*self.ar).isvararg != 0,
};
#[cfg(feature = "luau")]
let stack = DebugStack {
num_ups: (*self.ar.get()).nupvals,
num_params: (*self.ar.get()).nparams,
is_vararg: (*self.ar.get()).isvararg != 0,
num_ups: (*self.ar).nupvals,
num_params: (*self.ar).nparams,
is_vararg: (*self.ar).isvararg != 0,
};
stack
}
}
}
enum ActivationRecord {
#[cfg(not(feature = "luau"))]
Borrowed(*mut lua_Debug),
Owned(UnsafeCell<lua_Debug>),
}
impl ActivationRecord {
#[inline]
fn get(&self) -> *mut lua_Debug {
match self {
#[cfg(not(feature = "luau"))]
ActivationRecord::Borrowed(x) => *x,
ActivationRecord::Owned(x) => x.get(),
}
}
}
/// Represents a specific event that triggered the hook.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DebugEvent {
@@ -382,7 +365,7 @@ impl HookTriggers {
}
#[cfg(not(feature = "luau"))]
impl BitOr for HookTriggers {
impl std::ops::BitOr for HookTriggers {
type Output = Self;
fn bitor(mut self, rhs: Self) -> Self::Output {
@@ -397,7 +380,7 @@ impl BitOr for HookTriggers {
}
#[cfg(not(feature = "luau"))]
impl BitOrAssign for HookTriggers {
impl std::ops::BitOrAssign for HookTriggers {
fn bitor_assign(&mut self, rhs: Self) {
*self = *self | rhs;
}
+34 -15
View File
@@ -434,7 +434,7 @@ impl Function {
/// [`Compiler::set_coverage_level`]: crate::chunk::Compiler::set_coverage_level
#[cfg(any(feature = "luau", doc))]
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
pub fn coverage<F>(&self, mut func: F)
pub fn coverage<F>(&self, func: F)
where
F: FnMut(CoverageInfo),
{
@@ -454,13 +454,16 @@ impl Function {
} else {
None
};
let rust_callback = &mut *(data as *mut F);
rust_callback(CoverageInfo {
function,
line_defined,
depth,
hits: slice::from_raw_parts(hits, size).to_vec(),
});
let rust_callback = &*(data as *const RefCell<F>);
if let Ok(mut rust_callback) = rust_callback.try_borrow_mut() {
// Call the Rust callback with CoverageInfo
rust_callback(CoverageInfo {
function,
line_defined,
depth,
hits: slice::from_raw_parts(hits, size).to_vec(),
});
}
}
let lua = self.0.lua.lock();
@@ -470,7 +473,8 @@ impl Function {
assert_stack(state, 1);
lua.push_ref(&self.0);
let func_ptr = &mut func as *mut F as *mut c_void;
let func = RefCell::new(func);
let func_ptr = &func as *const RefCell<F> as *mut c_void;
ffi::lua_getcoverage(state, -1, func_ptr, callback::<F>);
}
}
@@ -492,16 +496,24 @@ impl Function {
/// This function returns shallow clone (same handle) for Rust/C functions.
#[cfg(any(feature = "luau", doc))]
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
pub fn deep_clone(&self) -> Self {
pub fn deep_clone(&self) -> Result<Self> {
let lua = self.0.lua.lock();
let ref_thread = lua.ref_thread();
let state = lua.state();
unsafe {
if ffi::lua_iscfunction(ref_thread, self.0.index) != 0 {
return self.clone();
let _sg = StackGuard::new(state);
check_stack(state, 2)?;
lua.push_ref(&self.0);
if ffi::lua_iscfunction(state, -1) != 0 {
return Ok(self.clone());
}
ffi::lua_clonefunction(ref_thread, self.0.index);
Function(lua.pop_ref_thread())
if lua.unlikely_memory_error() {
ffi::lua_clonefunction(state, -1);
} else {
protect_lua!(state, 1, 1, fn(state) ffi::lua_clonefunction(state, -1))?;
}
Ok(Function(lua.pop_ref()))
}
}
}
@@ -645,6 +657,13 @@ impl LuaType for Function {
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct AsyncCallFuture<R: FromLuaMulti>(Result<AsyncThread<R>>);
#[cfg(feature = "async")]
impl<R: FromLuaMulti> AsyncCallFuture<R> {
pub(crate) fn error(err: Error) -> Self {
AsyncCallFuture(Err(err))
}
}
#[cfg(feature = "async")]
impl<R: FromLuaMulti> Future for AsyncCallFuture<R> {
type Output = Result<R>;
+3 -3
View File
@@ -75,9 +75,9 @@ mod macros;
mod buffer;
mod chunk;
mod conversion;
mod debug;
mod error;
mod function;
mod hook;
#[cfg(any(feature = "luau", doc))]
mod luau;
mod memory;
@@ -101,9 +101,9 @@ pub use bstr::BString;
pub use ffi::{self, lua_CFunction, lua_State};
pub use crate::chunk::{AsChunk, Chunk, ChunkMode};
pub use crate::debug::{Debug, DebugEvent, DebugNames, DebugSource, DebugStack};
pub use crate::error::{Error, ErrorContext, ExternalError, ExternalResult, Result};
pub use crate::function::{Function, FunctionInfo};
pub use crate::hook::{Debug, DebugEvent, DebugNames, DebugSource, DebugStack};
pub use crate::multi::{MultiValue, Variadic};
pub use crate::scope::Scope;
pub use crate::state::{GCMode, Lua, LuaOptions, WeakLua};
@@ -124,7 +124,7 @@ pub use crate::userdata::{
pub use crate::value::{Nil, Value};
#[cfg(not(feature = "luau"))]
pub use crate::hook::HookTriggers;
pub use crate::debug::HookTriggers;
#[cfg(any(feature = "luau", doc))]
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
+9 -7
View File
@@ -5,8 +5,9 @@ use std::ptr;
use crate::chunk::ChunkMode;
use crate::error::Result;
use crate::function::Function;
use crate::state::{callback_error_ext, Lua};
use crate::state::{callback_error_ext, ExtraData, Lua};
use crate::traits::{FromLuaMulti, IntoLua};
use crate::types::MaybeSend;
pub use require::{NavigateError, Require, TextRequirer};
@@ -17,7 +18,7 @@ impl Lua {
/// and load modules.
#[cfg(any(feature = "luau", doc))]
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
pub fn create_require_function<R: Require + 'static>(&self, require: R) -> Result<Function> {
pub fn create_require_function<R: Require + MaybeSend + 'static>(&self, require: R) -> Result<Function> {
require::create_require_function(self, require)
}
@@ -45,16 +46,17 @@ unsafe extern "C-unwind" fn lua_collectgarbage(state: *mut ffi::lua_State) -> c_
let option = ffi::luaL_optstring(state, 1, cstr!("collect"));
let option = CStr::from_ptr(option);
let arg = ffi::luaL_optinteger(state, 2, 0);
let is_sandboxed = (*ExtraData::get(state)).sandboxed;
match option.to_str() {
Ok("collect") => {
Ok("collect") if !is_sandboxed => {
ffi::lua_gc(state, ffi::LUA_GCCOLLECT, 0);
0
}
Ok("stop") => {
Ok("stop") if !is_sandboxed => {
ffi::lua_gc(state, ffi::LUA_GCSTOP, 0);
0
}
Ok("restart") => {
Ok("restart") if !is_sandboxed => {
ffi::lua_gc(state, ffi::LUA_GCRESTART, 0);
0
}
@@ -64,12 +66,12 @@ unsafe extern "C-unwind" fn lua_collectgarbage(state: *mut ffi::lua_State) -> c_
ffi::lua_pushnumber(state, kbytes + kbytes_rem / 1024.0);
1
}
Ok("step") => {
Ok("step") if !is_sandboxed => {
let res = ffi::lua_gc(state, ffi::LUA_GCSTEP, arg as _);
ffi::lua_pushboolean(state, res);
1
}
Ok("isrunning") => {
Ok("isrunning") if !is_sandboxed => {
let res = ffi::lua_gc(state, ffi::LUA_GCISRUNNING, 0);
ffi::lua_pushboolean(state, res);
1
+56 -30
View File
@@ -14,7 +14,7 @@ use crate::state::{callback_error_ext, Lua};
use crate::table::Table;
use crate::types::MaybeSend;
/// An error that can occur during navigation in the Luau `require` system.
/// An error that can occur during navigation in the Luau `require-by-string` system.
#[cfg(any(feature = "luau", doc))]
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
#[derive(Debug, Clone)]
@@ -50,10 +50,10 @@ impl From<Error> for NavigateError {
#[cfg(feature = "luau")]
type WriteResult = ffi::luarequire_WriteResult;
/// A trait for handling modules loading and navigation in the Luau `require` system.
/// A trait for handling modules loading and navigation in the Luau `require-by-string` system.
#[cfg(any(feature = "luau", doc))]
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
pub trait Require: MaybeSend {
pub trait Require {
/// Returns `true` if "require" is permitted for the given chunk name.
fn is_require_allowed(&self, chunk_name: &str) -> bool;
@@ -103,16 +103,26 @@ impl fmt::Debug for dyn Require {
}
}
/// The standard implementation of Luau `require` navigation.
#[doc(hidden)]
/// The standard implementation of Luau `require-by-string` navigation.
#[derive(Default, Debug)]
pub struct TextRequirer {
/// An absolute path to the current Luau module (not mapped to a physical file)
abs_path: PathBuf,
/// A relative path to the current Luau module (not mapped to a physical file)
rel_path: PathBuf,
module_path: PathBuf,
/// A physical path to the current Luau module, which is a file or a directory with an
/// `init.lua(u)` file
resolved_path: Option<PathBuf>,
}
impl TextRequirer {
/// The prefix used for chunk names in the require system.
/// Only chunk names starting with this prefix are allowed to be used in `require`.
const CHUNK_PREFIX: &str = "@";
/// The file extensions that are considered valid for Luau modules.
const FILE_EXTENSIONS: &[&str] = &["luau", "lua"];
/// Creates a new `TextRequirer` instance.
pub fn new() -> Self {
Self::default()
@@ -156,14 +166,17 @@ impl TextRequirer {
components.into_iter().collect()
}
fn find_module(path: &Path) -> StdResult<PathBuf, NavigateError> {
/// Resolve a Luau module path to a physical file or directory.
///
/// Empty directories without init files are considered valid as "intermediate" directories.
fn resolve_module(path: &Path) -> StdResult<Option<PathBuf>, NavigateError> {
let mut found_path = None;
if path.components().next_back() != Some(Component::Normal("init".as_ref())) {
let current_ext = (path.extension().and_then(|s| s.to_str()))
.map(|s| format!("{s}."))
.unwrap_or_default();
for ext in ["luau", "lua"] {
for ext in Self::FILE_EXTENSIONS {
let candidate = path.with_extension(format!("{current_ext}{ext}"));
if candidate.is_file() && found_path.replace(candidate).is_some() {
return Err(NavigateError::Ambiguous);
@@ -171,7 +184,7 @@ impl TextRequirer {
}
}
if path.is_dir() {
for component in ["init.luau", "init.lua"] {
for component in Self::FILE_EXTENSIONS.iter().map(|ext| format!("init.{ext}")) {
let candidate = path.join(component);
if candidate.is_file() && found_path.replace(candidate).is_some() {
return Err(NavigateError::Ambiguous);
@@ -179,48 +192,51 @@ impl TextRequirer {
}
if found_path.is_none() {
found_path = Some(PathBuf::new());
// Directories without init files are considered valid "intermediate" path
return Ok(None);
}
}
found_path.ok_or(NavigateError::NotFound)
Ok(Some(found_path.ok_or(NavigateError::NotFound)?))
}
}
impl Require for TextRequirer {
fn is_require_allowed(&self, chunk_name: &str) -> bool {
chunk_name.starts_with('@')
chunk_name.starts_with(Self::CHUNK_PREFIX)
}
fn reset(&mut self, chunk_name: &str) -> StdResult<(), NavigateError> {
if !chunk_name.starts_with('@') {
if !chunk_name.starts_with(Self::CHUNK_PREFIX) {
return Err(NavigateError::NotFound);
}
let chunk_name = Self::normalize_chunk_name(&chunk_name[1..]);
let chunk_path = Self::normalize_path(chunk_name.as_ref());
if chunk_path.extension() == Some("rs".as_ref()) {
// Special case for Rust source files, reset to the current directory
let chunk_filename = chunk_path.file_name().unwrap();
let cwd = env::current_dir().map_err(|_| NavigateError::NotFound)?;
self.abs_path = Self::normalize_path(&cwd.join(&chunk_path));
self.rel_path = chunk_path;
self.module_path = PathBuf::new();
self.abs_path = Self::normalize_path(&cwd.join(chunk_filename));
self.rel_path = ([Component::CurDir, Component::Normal(chunk_filename)].into_iter()).collect();
self.resolved_path = None;
return Ok(());
}
if chunk_path.is_absolute() {
let module_path = Self::find_module(&chunk_path)?;
let resolved_path = Self::resolve_module(&chunk_path)?;
self.abs_path = chunk_path.clone();
self.rel_path = chunk_path;
self.module_path = module_path;
self.resolved_path = resolved_path;
} else {
// Relative path
let cwd = env::current_dir().map_err(|_| NavigateError::NotFound)?;
let abs_path = Self::normalize_path(&cwd.join(&chunk_path));
let module_path = Self::find_module(&abs_path)?;
let resolved_path = Self::resolve_module(&abs_path)?;
self.abs_path = abs_path;
self.rel_path = chunk_path;
self.module_path = module_path;
self.resolved_path = resolved_path;
}
Ok(())
@@ -228,11 +244,11 @@ impl Require for TextRequirer {
fn jump_to_alias(&mut self, path: &str) -> StdResult<(), NavigateError> {
let path = Self::normalize_path(path.as_ref());
let module_path = Self::find_module(&path)?;
let resolved_path = Self::resolve_module(&path)?;
self.abs_path = path.clone();
self.rel_path = path;
self.module_path = module_path;
self.resolved_path = resolved_path;
Ok(())
}
@@ -240,15 +256,18 @@ impl Require for TextRequirer {
fn to_parent(&mut self) -> StdResult<(), NavigateError> {
let mut abs_path = self.abs_path.clone();
if !abs_path.pop() {
// It's important to return `NotFound` if we reached the root, as it's a "recoverable" error if we
// cannot go beyond the root directory.
// Luau "require-by-string` has a special logic to search for config file to resolve aliases.
return Err(NavigateError::NotFound);
}
let mut rel_parent = self.rel_path.clone();
rel_parent.pop();
let module_path = Self::find_module(&abs_path)?;
let resolved_path = Self::resolve_module(&abs_path)?;
self.abs_path = abs_path;
self.rel_path = Self::normalize_path(&rel_parent);
self.module_path = module_path;
self.resolved_path = resolved_path;
Ok(())
}
@@ -256,21 +275,23 @@ impl Require for TextRequirer {
fn to_child(&mut self, name: &str) -> StdResult<(), NavigateError> {
let abs_path = self.abs_path.join(name);
let rel_path = self.rel_path.join(name);
let module_path = Self::find_module(&abs_path)?;
let resolved_path = Self::resolve_module(&abs_path)?;
self.abs_path = abs_path;
self.rel_path = rel_path;
self.module_path = module_path;
self.resolved_path = resolved_path;
Ok(())
}
fn has_module(&self) -> bool {
self.module_path.is_file()
(self.resolved_path.as_deref())
.map(Path::is_file)
.unwrap_or(false)
}
fn cache_key(&self) -> String {
self.module_path.display().to_string()
self.resolved_path.as_deref().unwrap().display().to_string()
}
fn has_config(&self) -> bool {
@@ -283,7 +304,9 @@ impl Require for TextRequirer {
fn loader(&self, lua: &Lua) -> Result<Function> {
let name = format!("@{}", self.rel_path.display());
lua.load(&*self.module_path).set_name(name).into_function()
lua.load(self.resolved_path.as_deref().unwrap())
.set_name(name)
.into_function()
}
}
@@ -494,7 +517,10 @@ unsafe fn write_to_buffer(
}
#[cfg(feature = "luau")]
pub fn create_require_function<R: Require + 'static>(lua: &Lua, require: R) -> Result<Function> {
pub(super) fn create_require_function<R: Require + MaybeSend + 'static>(
lua: &Lua,
require: R,
) -> Result<Function> {
unsafe extern "C-unwind" fn find_current_file(state: *mut ffi::lua_State) -> c_int {
let mut ar: ffi::lua_Debug = mem::zeroed();
for level in 2.. {
+2 -1
View File
@@ -25,7 +25,8 @@ pub use crate::HookTriggers as LuaHookTriggers;
#[doc(no_inline)]
pub use crate::{
CompileConstant as LuaCompileConstant, CoverageInfo as LuaCoverageInfo,
NavigateError as LuaNavigateError, Require as LuaRequire, Vector as LuaVector,
NavigateError as LuaNavigateError, Require as LuaRequire, TextRequirer as LuaTextRequirer,
Vector as LuaVector,
};
#[cfg(feature = "async")]
+4 -1
View File
@@ -165,7 +165,10 @@ impl<'de> serde::Deserializer<'de> for Deserializer {
serde_userdata(ud, |value| value.deserialize_any(visitor))
}
#[cfg(feature = "luau")]
Value::Buffer(buf) => visitor.visit_bytes(unsafe { buf.as_slice() }),
Value::Buffer(buf) => {
let lua = buf.0.lua.lock();
visitor.visit_bytes(buf.as_slice(&lua))
}
Value::Function(_)
| Value::Thread(_)
| Value::UserData(_)
+3 -3
View File
@@ -256,7 +256,7 @@ impl<'a> ser::Serializer for Serializer<'a> {
fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
let table = self.lua.create_table_with_capacity(len.unwrap_or(0), 0)?;
if self.options.set_array_metatable {
table.set_metatable(Some(self.lua.array_metatable()));
table.set_metatable(Some(self.lua.array_metatable()))?;
}
Ok(SerializeSeq::new(self.lua, table, self.options))
}
@@ -529,8 +529,8 @@ impl ser::SerializeStruct for SerializeStruct<'_> {
fn end(self) -> Result<Value> {
match self.inner {
Some(table @ Value::Table(_)) => Ok(table),
Some(value) if self.options.detect_serde_json_arbitrary_precision => {
let number_s = value.as_str().expect("not an arbitrary precision number");
Some(value @ Value::String(_)) if self.options.detect_serde_json_arbitrary_precision => {
let number_s = value.to_string()?;
if number_s.contains(['.', 'e', 'E']) {
if let Ok(number) = number_s.parse().map(Value::Number) {
return Ok(number);
+57 -23
View File
@@ -8,9 +8,9 @@ use std::result::Result as StdResult;
use std::{fmt, mem, ptr};
use crate::chunk::{AsChunk, Chunk};
use crate::debug::Debug;
use crate::error::{Error, Result};
use crate::function::Function;
use crate::hook::Debug;
use crate::memory::MemoryState;
use crate::multi::MultiValue;
use crate::scope::Scope;
@@ -28,7 +28,7 @@ use crate::util::{assert_stack, check_stack, protect_lua_closure, push_string, r
use crate::value::{Nil, Value};
#[cfg(not(feature = "luau"))]
use crate::{hook::HookTriggers, types::HookKind};
use crate::{debug::HookTriggers, types::HookKind};
#[cfg(any(feature = "luau", doc))]
use crate::{buffer::Buffer, chunk::Compiler};
@@ -486,6 +486,7 @@ impl Lua {
/// - Set globals to read-only (and activates safeenv)
/// - Setup local environment table that performs writes locally and proxies reads to the global
/// environment.
/// - Allow only `count` mode in `collectgarbage` function.
///
/// # Examples
///
@@ -543,7 +544,7 @@ impl Lua {
#[cfg_attr(docsrs, doc(cfg(not(feature = "luau"))))]
pub fn set_global_hook<F>(&self, triggers: HookTriggers, callback: F) -> Result<()>
where
F: Fn(&Lua, Debug) -> Result<VmState> + MaybeSend + 'static,
F: Fn(&Lua, &Debug) -> Result<VmState> + MaybeSend + 'static,
{
let lua = self.lock();
unsafe {
@@ -576,7 +577,7 @@ impl Lua {
/// # fn main() -> Result<()> {
/// let lua = Lua::new();
/// lua.set_hook(HookTriggers::EVERY_LINE, |_lua, debug| {
/// println!("line {}", debug.curr_line());
/// println!("line {:?}", debug.current_line());
/// Ok(VmState::Continue)
/// });
///
@@ -593,7 +594,7 @@ impl Lua {
#[cfg_attr(docsrs, doc(cfg(not(feature = "luau"))))]
pub fn set_hook<F>(&self, triggers: HookTriggers, callback: F) -> Result<()>
where
F: Fn(&Lua, Debug) -> Result<VmState> + MaybeSend + 'static,
F: Fn(&Lua, &Debug) -> Result<VmState> + MaybeSend + 'static,
{
let lua = self.lock();
unsafe { lua.set_thread_hook(lua.state(), HookKind::Thread(triggers, XRc::new(callback))) }
@@ -868,18 +869,16 @@ impl Lua {
}
}
/// Gets information about the interpreter runtime stack.
/// Gets information about the interpreter runtime stack at a given level.
///
/// This function returns [`Debug`] structure that can be used to get information about the
/// function executing at a given level. Level `0` is the current running function, whereas
/// level `n+1` is the function that has called level `n` (except for tail calls, which do
/// not count in the stack).
///
/// [`Debug`]: crate::hook::Debug
pub fn inspect_stack(&self, level: usize) -> Option<Debug> {
/// This function calls callback `f`, passing the [`Debug`] structure that can be used to get
/// information about the function executing at a given level.
/// Level `0` is the current running function, whereas level `n+1` is the function that has
/// called level `n` (except for tail calls, which do not count in the stack).
pub fn inspect_stack<R>(&self, level: usize, f: impl FnOnce(&Debug) -> R) -> Option<R> {
let lua = self.lock();
unsafe {
let mut ar: ffi::lua_Debug = mem::zeroed();
let mut ar = mem::zeroed::<ffi::lua_Debug>();
let level = level as c_int;
#[cfg(not(feature = "luau"))]
if ffi::lua_getstack(lua.state(), level, &mut ar) == 0 {
@@ -889,7 +888,8 @@ impl Lua {
if ffi::lua_getinfo(lua.state(), level, cstr!(""), &mut ar) == 0 {
return None;
}
Some(Debug::new_owned(lua, level, ar))
Some(f(&Debug::new(&lua, level, &mut ar)))
}
}
@@ -1416,7 +1416,7 @@ impl Lua {
let lua = self.lock();
unsafe {
// Deregister the type if it already registered
if let Some(&table_id) = (*lua.extra.get()).registered_userdata_t.get(&type_id) {
if let Some(table_id) = (*lua.extra.get()).registered_userdata_t.remove(&type_id) {
ffi::luaL_unref(lua.state(), ffi::LUA_REGISTRYINDEX, table_id);
}
@@ -1550,6 +1550,39 @@ impl Lua {
}
}
/// Sets the global environment.
///
/// This will replace the current global environment with the provided `globals` table.
///
/// For Lua 5.2+ the globals table is stored in the registry and shared between all threads.
/// For Lua 5.1 and Luau the globals table is stored in each thread.
///
/// Please note that any existing Lua functions have cached global environment and will not
/// see the changes made by this method.
/// To update the environment for existing Lua functions, use [`Function::set_environment`].
pub fn set_globals(&self, globals: Table) -> Result<()> {
let lua = self.lock();
let state = lua.state();
unsafe {
#[cfg(feature = "luau")]
if (*lua.extra.get()).sandboxed {
return Err(Error::runtime("cannot change globals in a sandboxed Lua state"));
}
let _sg = StackGuard::new(state);
check_stack(state, 1)?;
lua.push_ref(&globals.0);
#[cfg(any(feature = "lua54", feature = "lua53", feature = "lua52"))]
ffi::lua_rawseti(state, ffi::LUA_REGISTRYINDEX, ffi::LUA_RIDX_GLOBALS);
#[cfg(any(feature = "lua51", feature = "luajit", feature = "luau"))]
ffi::lua_replace(state, ffi::LUA_GLOBALSINDEX);
}
Ok(())
}
/// Returns a handle to the active `Thread`.
///
/// For calls to `Lua` this will be the main Lua thread, for parameters given to a callback,
@@ -1955,7 +1988,7 @@ impl Lua {
/// Panics if the data object of type `T` is currently mutably borrowed. Multiple immutable
/// reads can be taken out at the same time.
#[track_caller]
pub fn app_data_ref<T: 'static>(&self) -> Option<AppDataRef<T>> {
pub fn app_data_ref<T: 'static>(&self) -> Option<AppDataRef<'_, T>> {
let guard = self.lock_arc();
let extra = unsafe { &*guard.extra.get() };
extra.app_data.borrow(Some(guard))
@@ -1963,7 +1996,7 @@ impl Lua {
/// Tries to get a reference to an application data object stored by [`Lua::set_app_data`] of
/// type `T`.
pub fn try_app_data_ref<T: 'static>(&self) -> StdResult<Option<AppDataRef<T>>, BorrowError> {
pub fn try_app_data_ref<T: 'static>(&self) -> StdResult<Option<AppDataRef<'_, T>>, BorrowError> {
let guard = self.lock_arc();
let extra = unsafe { &*guard.extra.get() };
extra.app_data.try_borrow(Some(guard))
@@ -1976,7 +2009,7 @@ impl Lua {
///
/// Panics if the data object of type `T` is currently borrowed.
#[track_caller]
pub fn app_data_mut<T: 'static>(&self) -> Option<AppDataRefMut<T>> {
pub fn app_data_mut<T: 'static>(&self) -> Option<AppDataRefMut<'_, T>> {
let guard = self.lock_arc();
let extra = unsafe { &*guard.extra.get() };
extra.app_data.borrow_mut(Some(guard))
@@ -1984,7 +2017,7 @@ impl Lua {
/// Tries to get a mutable reference to an application data object stored by
/// [`Lua::set_app_data`] of type `T`.
pub fn try_app_data_mut<T: 'static>(&self) -> StdResult<Option<AppDataRefMut<T>>, BorrowMutError> {
pub fn try_app_data_mut<T: 'static>(&self) -> StdResult<Option<AppDataRefMut<'_, T>>, BorrowMutError> {
let guard = self.lock_arc();
let extra = unsafe { &*guard.extra.get() };
extra.app_data.try_borrow_mut(Some(guard))
@@ -2029,7 +2062,6 @@ impl Lua {
WeakLua(XRc::downgrade(&self.raw))
}
// Luau version located in `luau/mod.rs`
#[cfg(not(feature = "luau"))]
fn disable_c_modules(&self) -> Result<()> {
let package: Table = self.globals().get("package")?;
@@ -2052,13 +2084,15 @@ impl Lua {
// The third and fourth searchers looks for a loader as a C library
searchers.raw_set(3, loader)?;
searchers.raw_remove(4)?;
if searchers.raw_len() >= 4 {
searchers.raw_remove(4)?;
}
Ok(())
}
#[inline(always)]
pub(crate) fn lock(&self) -> ReentrantMutexGuard<RawLua> {
pub(crate) fn lock(&self) -> ReentrantMutexGuard<'_, RawLua> {
let rawlua = self.raw.lock();
#[cfg(feature = "luau")]
if unsafe { (*rawlua.extra.get()).running_gc } {
+32 -4
View File
@@ -28,7 +28,7 @@ use super::{Lua, WeakLua};
static EXTRA_REGISTRY_KEY: u8 = 0;
const WRAPPED_FAILURE_POOL_DEFAULT_CAPACITY: usize = 64;
const REF_STACK_RESERVE: c_int = 2;
const REF_STACK_RESERVE: c_int = 3;
/// Data associated with the Lua state.
pub(crate) struct ExtraData {
@@ -76,7 +76,7 @@ pub(crate) struct ExtraData {
#[cfg(not(feature = "luau"))]
pub(super) hook_callback: Option<crate::types::HookCallback>,
#[cfg(not(feature = "luau"))]
pub(super) hook_triggers: crate::hook::HookTriggers,
pub(super) hook_triggers: crate::debug::HookTriggers,
#[cfg(feature = "lua54")]
pub(super) warn_callback: Option<crate::types::WarnCallback>,
#[cfg(feature = "luau")]
@@ -89,7 +89,7 @@ pub(crate) struct ExtraData {
#[cfg(feature = "luau")]
pub(crate) running_gc: bool,
#[cfg(feature = "luau")]
pub(super) sandboxed: bool,
pub(crate) sandboxed: bool,
#[cfg(feature = "luau")]
pub(super) compiler: Option<Compiler>,
#[cfg(feature = "luau-jit")]
@@ -212,7 +212,7 @@ impl ExtraData {
self.weak.write(WeakLua(XRc::downgrade(raw)));
}
pub(super) unsafe fn get(state: *mut ffi::lua_State) -> *mut Self {
pub(crate) unsafe fn get(state: *mut ffi::lua_State) -> *mut Self {
#[cfg(feature = "luau")]
if cfg!(not(feature = "module")) {
// In the main app we can use `lua_callbacks` to access ExtraData
@@ -259,4 +259,32 @@ impl ExtraData {
pub(super) unsafe fn weak(&self) -> &WeakLua {
self.weak.assume_init_ref()
}
/// Pops a reference from top of the auxiliary stack and move it to a first free slot.
pub(super) unsafe fn ref_stack_pop(&mut self) -> c_int {
if let Some(free) = self.ref_free.pop() {
ffi::lua_replace(self.ref_thread, free);
return free;
}
// Try to grow max stack size
if self.ref_stack_top >= self.ref_stack_size {
let mut inc = self.ref_stack_size; // Try to double stack size
while inc > 0 && ffi::lua_checkstack(self.ref_thread, inc) == 0 {
inc /= 2;
}
if inc == 0 {
// Pop item on top of the stack to avoid stack leaking and successfully run destructors
// during unwinding.
ffi::lua_pop(self.ref_thread, 1);
let top = self.ref_stack_top;
// It is a user error to create too many references to exhaust the Lua max stack size
// for the ref thread.
panic!("cannot create a Lua reference, out of auxiliary stack space (used {top} slots)");
}
self.ref_stack_size += inc;
}
self.ref_stack_top += 1;
self.ref_stack_top
}
}
+19 -15
View File
@@ -11,7 +11,7 @@ use crate::chunk::ChunkMode;
use crate::error::{Error, Result};
use crate::function::Function;
use crate::memory::{MemoryState, ALLOCATOR};
use crate::state::util::{callback_error_ext, ref_stack_pop};
use crate::state::util::callback_error_ext;
use crate::stdlib::StdLib;
use crate::string::String;
use crate::table::Table;
@@ -38,7 +38,7 @@ use super::{Lua, LuaOptions, WeakLua};
#[cfg(not(feature = "luau"))]
use crate::{
hook::Debug,
debug::Debug,
types::{HookCallback, HookKind, VmState},
};
@@ -296,7 +296,7 @@ impl RawLua {
if is_safe {
let curr_libs = (*self.extra.get()).libs;
if (curr_libs ^ (curr_libs | libs)).contains(StdLib::PACKAGE) {
mlua_expect!(self.lua().disable_c_modules(), "Error during disabling C modules");
mlua_expect!(self.lua().disable_c_modules(), "Error disabling C modules");
}
}
#[cfg(feature = "luau")]
@@ -316,7 +316,7 @@ impl RawLua {
/// Private version of [`Lua::app_data_ref`]
#[track_caller]
#[inline]
pub(crate) fn priv_app_data_ref<T: 'static>(&self) -> Option<AppDataRef<T>> {
pub(crate) fn priv_app_data_ref<T: 'static>(&self) -> Option<AppDataRef<'_, T>> {
let extra = unsafe { &*self.extra.get() };
extra.app_data_priv.borrow(None)
}
@@ -324,7 +324,7 @@ impl RawLua {
/// Private version of [`Lua::app_data_mut`]
#[track_caller]
#[inline]
pub(crate) fn priv_app_data_mut<T: 'static>(&self) -> Option<AppDataRefMut<T>> {
pub(crate) fn priv_app_data_mut<T: 'static>(&self) -> Option<AppDataRefMut<'_, T>> {
let extra = unsafe { &*self.extra.get() };
extra.app_data_priv.borrow_mut(None)
}
@@ -435,8 +435,8 @@ impl RawLua {
match (*extra).hook_callback.clone() {
Some(hook_callback) => {
let rawlua = (*extra).raw_lua();
let debug = Debug::new(rawlua, ar);
hook_callback((*extra).lua(), debug)
let debug = Debug::new(rawlua, 0, ar);
hook_callback((*extra).lua(), &debug)
}
None => {
ffi::lua_sethook(state, None, 0, 0);
@@ -465,9 +465,9 @@ impl RawLua {
let status = callback_error_ext(state, ptr::null_mut(), false, |extra, _| {
let rawlua = (*extra).raw_lua();
let debug = Debug::new(rawlua, ar);
let debug = Debug::new(rawlua, 0, ar);
let hook_callback = (*hook_callback_ptr).clone();
hook_callback((*extra).lua(), debug)
hook_callback((*extra).lua(), &debug)
});
process_status(state, (*ar).event, status)
}
@@ -694,7 +694,7 @@ impl RawLua {
/// Pops a value from the Lua stack.
///
/// Uses 2 stack spaces, does not call `checkstack`.
/// Uses up to 1 stack spaces, does not call `checkstack`.
pub(crate) unsafe fn pop_value(&self) -> Value {
let value = self.stack_value(-1, None);
ffi::lua_pop(self.state(), 1);
@@ -703,7 +703,7 @@ impl RawLua {
/// Returns value at given stack index without popping it.
///
/// Uses 2 stack spaces, does not call checkstack.
/// Uses up to 1 stack spaces, does not call `checkstack`.
pub(crate) unsafe fn stack_value(&self, idx: c_int, type_hint: Option<c_int>) -> Value {
let state = self.state();
match type_hint.unwrap_or_else(|| ffi::lua_type(state, idx)) {
@@ -816,21 +816,21 @@ impl RawLua {
#[inline]
pub(crate) unsafe fn pop_ref(&self) -> ValueRef {
ffi::lua_xmove(self.state(), self.ref_thread(), 1);
let index = ref_stack_pop(self.extra.get());
let index = (*self.extra.get()).ref_stack_pop();
ValueRef::new(self, index)
}
// Same as `pop_ref` but assumes the value is already on the reference thread
#[inline]
pub(crate) unsafe fn pop_ref_thread(&self) -> ValueRef {
let index = ref_stack_pop(self.extra.get());
let index = (*self.extra.get()).ref_stack_pop();
ValueRef::new(self, index)
}
#[inline]
pub(crate) unsafe fn clone_ref(&self, vref: &ValueRef) -> ValueRef {
ffi::lua_pushvalue(self.ref_thread(), vref.index);
let index = ref_stack_pop(self.extra.get());
let index = (*self.extra.get()).ref_stack_pop();
ValueRef::new(self, index)
}
@@ -1262,7 +1262,7 @@ impl RawLua {
if nargs == 1 && ffi::lua_tolightuserdata(state, -1) == Lua::poll_terminate().0 {
// Destroy the future and terminate the Lua thread
(*upvalue).data.take();
ffi::lua_pushinteger(state, 0);
ffi::lua_pushinteger(state, -1);
return Ok(1);
}
@@ -1347,6 +1347,10 @@ impl RawLua {
return res
elseif nres == 2 then
return res, res2
elseif nres < 0 then
-- Negative `nres` means that the future is terminated
-- It must stay yielded and never be resumed again
yield()
else
return unpack(res, nres)
end
+1 -29
View File
@@ -89,7 +89,7 @@ where
PreallocatedFailure::New(_) => {
ffi::lua_rotate(state, 1, -1);
ffi::lua_xmove(state, ref_thread, 1);
let index = ref_stack_pop(extra);
let index = (*extra).ref_stack_pop();
(*extra).wrapped_failure_pool.push(index);
(*extra).wrapped_failure_top += 1;
}
@@ -150,31 +150,3 @@ where
}
}
}
pub(super) unsafe fn ref_stack_pop(extra: *mut ExtraData) -> c_int {
let extra = &mut *extra;
if let Some(free) = extra.ref_free.pop() {
ffi::lua_replace(extra.ref_thread, free);
return free;
}
// Try to grow max stack size
if extra.ref_stack_top >= extra.ref_stack_size {
let mut inc = extra.ref_stack_size; // Try to double stack size
while inc > 0 && ffi::lua_checkstack(extra.ref_thread, inc) == 0 {
inc /= 2;
}
if inc == 0 {
// Pop item on top of the stack to avoid stack leaking and successfully run destructors
// during unwinding.
ffi::lua_pop(extra.ref_thread, 1);
let top = extra.ref_stack_top;
// It is a user error to create enough references to exhaust the Lua max stack size for
// the ref thread.
panic!("cannot create a Lua reference, out of auxiliary stack space (used {top} slots)");
}
extra.ref_stack_size += inc;
}
extra.ref_stack_top += 1;
extra.ref_stack_top
}
+7 -7
View File
@@ -43,7 +43,7 @@ impl String {
/// # }
/// ```
#[inline]
pub fn to_str(&self) -> Result<BorrowedStr> {
pub fn to_str(&self) -> Result<BorrowedStr<'_>> {
BorrowedStr::try_from(self)
}
@@ -86,7 +86,7 @@ impl String {
/// Get the bytes that make up this string.
///
/// The returned slice will not contain the terminating nul byte, but will contain any nul
/// The returned slice will not contain the terminating null byte, but will contain any null
/// bytes embedded into the Lua string.
///
/// # Examples
@@ -102,19 +102,19 @@ impl String {
/// # }
/// ```
#[inline]
pub fn as_bytes(&self) -> BorrowedBytes {
pub fn as_bytes(&self) -> BorrowedBytes<'_> {
BorrowedBytes::from(self)
}
/// Get the bytes that make up this string, including the trailing nul byte.
pub fn as_bytes_with_nul(&self) -> BorrowedBytes {
/// Get the bytes that make up this string, including the trailing null byte.
pub fn as_bytes_with_nul(&self) -> BorrowedBytes<'_> {
let BorrowedBytes { buf, borrow, _lua } = BorrowedBytes::from(self);
// Include the trailing nul byte (it's always present but excluded by default)
// Include the trailing null byte (it's always present but excluded by default)
let buf = unsafe { slice::from_raw_parts((*buf).as_ptr(), (*buf).len() + 1) };
BorrowedBytes { buf, borrow, _lua }
}
// Does not return the terminating nul byte
// Does not return the terminating null byte
unsafe fn to_slice(&self) -> (&[u8], Lua) {
let lua = self.0.lua.upgrade();
let slice = {
+20 -28
View File
@@ -13,7 +13,7 @@ use crate::util::{assert_stack, check_stack, get_metatable_ptr, StackGuard};
use crate::value::{Nil, Value};
#[cfg(feature = "async")]
use futures_util::future::{self, Either, Future};
use crate::function::AsyncCallFuture;
#[cfg(feature = "serde")]
use {
@@ -211,7 +211,7 @@ impl Table {
///
/// let always_equals_mt = lua.create_table()?;
/// always_equals_mt.set("__eq", lua.create_function(|_, (_t1, _t2): (Table, Table)| Ok(true))?)?;
/// table2.set_metatable(Some(always_equals_mt));
/// table2.set_metatable(Some(always_equals_mt))?;
///
/// assert!(table1.equals(&table1.clone())?);
/// assert!(table1.equals(&table2)?);
@@ -487,16 +487,12 @@ impl Table {
/// [`getmetatable`]: https://www.lua.org/manual/5.4/manual.html#pdf-getmetatable
pub fn metatable(&self) -> Option<Table> {
let lua = self.0.lua.lock();
let state = lua.state();
let ref_thread = lua.ref_thread();
unsafe {
let _sg = StackGuard::new(state);
assert_stack(state, 2);
lua.push_ref(&self.0);
if ffi::lua_getmetatable(state, -1) == 0 {
if ffi::lua_getmetatable(ref_thread, self.0.index) == 0 {
None
} else {
Some(Table(lua.pop_ref()))
Some(Table(lua.pop_ref_thread()))
}
}
}
@@ -505,27 +501,23 @@ impl Table {
///
/// If `metatable` is `None`, the metatable is removed (if no metatable is set, this does
/// nothing).
pub fn set_metatable(&self, metatable: Option<Table>) {
// Workaround to throw readonly error without returning Result
pub fn set_metatable(&self, metatable: Option<Table>) -> Result<()> {
#[cfg(feature = "luau")]
if self.is_readonly() {
panic!("attempt to modify a readonly table");
return Err(Error::runtime("attempt to modify a readonly table"));
}
let lua = self.0.lua.lock();
let state = lua.state();
let ref_thread = lua.ref_thread();
unsafe {
let _sg = StackGuard::new(state);
assert_stack(state, 2);
lua.push_ref(&self.0);
if let Some(metatable) = metatable {
lua.push_ref(&metatable.0);
ffi::lua_pushvalue(ref_thread, metatable.0.index);
} else {
ffi::lua_pushnil(state);
ffi::lua_pushnil(ref_thread);
}
ffi::lua_setmetatable(state, -2);
ffi::lua_setmetatable(ref_thread, self.0.index);
}
Ok(())
}
/// Returns true if the table has metatable attached.
@@ -613,7 +605,7 @@ impl Table {
/// ```
///
/// [Lua manual]: http://www.lua.org/manual/5.4/manual.html#pdf-next
pub fn pairs<K: FromLua, V: FromLua>(&self) -> TablePairs<K, V> {
pub fn pairs<K: FromLua, V: FromLua>(&self) -> TablePairs<'_, K, V> {
TablePairs {
guard: self.0.lua.lock(),
table: self,
@@ -678,7 +670,7 @@ impl Table {
/// # Ok(())
/// # }
/// ```
pub fn sequence_values<V: FromLua>(&self) -> TableSequence<V> {
pub fn sequence_values<V: FromLua>(&self) -> TableSequence<'_, V> {
TableSequence {
guard: self.0.lua.lock(),
table: self,
@@ -897,7 +889,7 @@ impl ObjectLike for Table {
#[cfg(feature = "async")]
#[inline]
fn call_async<R>(&self, args: impl IntoLuaMulti) -> impl Future<Output = Result<R>>
fn call_async<R>(&self, args: impl IntoLuaMulti) -> AsyncCallFuture<R>
where
R: FromLuaMulti,
{
@@ -913,7 +905,7 @@ impl ObjectLike for Table {
}
#[cfg(feature = "async")]
fn call_async_method<R>(&self, name: &str, args: impl IntoLuaMulti) -> impl Future<Output = Result<R>>
fn call_async_method<R>(&self, name: &str, args: impl IntoLuaMulti) -> AsyncCallFuture<R>
where
R: FromLuaMulti,
{
@@ -933,17 +925,17 @@ impl ObjectLike for Table {
#[cfg(feature = "async")]
#[inline]
fn call_async_function<R>(&self, name: &str, args: impl IntoLuaMulti) -> impl Future<Output = Result<R>>
fn call_async_function<R>(&self, name: &str, args: impl IntoLuaMulti) -> AsyncCallFuture<R>
where
R: FromLuaMulti,
{
match self.get(name) {
Ok(Value::Function(func)) => Either::Left(func.call_async(args)),
Ok(Value::Function(func)) => func.call_async(args),
Ok(val) => {
let msg = format!("attempt to call a {} value (function '{name}')", val.type_name());
Either::Right(future::ready(Err(Error::RuntimeError(msg))))
AsyncCallFuture::error(Error::RuntimeError(msg))
}
Err(err) => Either::Right(future::ready(Err(err))),
Err(err) => AsyncCallFuture::error(err),
}
}
+7 -4
View File
@@ -10,7 +10,7 @@ use crate::util::{check_stack, error_traceback_thread, pop_error, StackGuard};
#[cfg(not(feature = "luau"))]
use crate::{
hook::{Debug, HookTriggers},
debug::{Debug, HookTriggers},
types::HookKind,
};
@@ -86,13 +86,15 @@ unsafe impl Sync for Thread {}
#[must_use = "futures do nothing unless you `.await` or poll them"]
pub struct AsyncThread<R> {
thread: Thread,
ret: PhantomData<R>,
ret: PhantomData<fn() -> R>,
recycle: bool,
}
impl Thread {
/// Returns reference to the Lua state that this thread is associated with.
#[doc(hidden)]
#[inline(always)]
fn state(&self) -> *mut ffi::lua_State {
pub fn state(&self) -> *mut ffi::lua_State {
self.1
}
@@ -269,7 +271,7 @@ impl Thread {
#[cfg_attr(docsrs, doc(cfg(not(feature = "luau"))))]
pub fn set_hook<F>(&self, triggers: HookTriggers, callback: F) -> Result<()>
where
F: Fn(&crate::Lua, Debug) -> Result<crate::VmState> + crate::MaybeSend + 'static,
F: Fn(&crate::Lua, &Debug) -> Result<crate::VmState> + crate::MaybeSend + 'static,
{
let lua = self.0.lua.lock();
unsafe {
@@ -529,6 +531,7 @@ impl<R> Drop for AsyncThread<R> {
// The thread is dropped while yielded, resume it with the "terminate" signal
ffi::lua_pushlightuserdata(self.thread.1, crate::Lua::poll_terminate().0);
if let Ok((new_status, _)) = self.thread.resume_inner(&lua, 1) {
// `new_status` should always be `ThreadStatusInner::Yielded(0)`
status = new_status;
}
}
+4 -4
View File
@@ -11,7 +11,7 @@ use crate::util::{check_stack, short_type_name};
use crate::value::Value;
#[cfg(feature = "async")]
use std::future::Future;
use {crate::function::AsyncCallFuture, std::future::Future};
/// Trait for types convertible to [`Value`].
pub trait IntoLua: Sized {
@@ -162,7 +162,7 @@ pub trait ObjectLike: Sealed {
/// arguments.
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
fn call_async<R>(&self, args: impl IntoLuaMulti) -> impl Future<Output = Result<R>>
fn call_async<R>(&self, args: impl IntoLuaMulti) -> AsyncCallFuture<R>
where
R: FromLuaMulti;
@@ -178,7 +178,7 @@ pub trait ObjectLike: Sealed {
/// This might invoke the `__index` metamethod.
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
fn call_async_method<R>(&self, name: &str, args: impl IntoLuaMulti) -> impl Future<Output = Result<R>>
fn call_async_method<R>(&self, name: &str, args: impl IntoLuaMulti) -> AsyncCallFuture<R>
where
R: FromLuaMulti;
@@ -196,7 +196,7 @@ pub trait ObjectLike: Sealed {
/// This might invoke the `__index` metamethod.
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
fn call_async_function<R>(&self, name: &str, args: impl IntoLuaMulti) -> impl Future<Output = Result<R>>
fn call_async_function<R>(&self, name: &str, args: impl IntoLuaMulti) -> AsyncCallFuture<R>
where
R: FromLuaMulti;
+4 -4
View File
@@ -1,9 +1,9 @@
use std::cell::UnsafeCell;
use std::os::raw::{c_int, c_void};
use crate::error::Result;
#[cfg(not(feature = "luau"))]
use crate::hook::{Debug, HookTriggers};
use crate::debug::{Debug, HookTriggers};
use crate::error::Result;
use crate::state::{ExtraData, Lua, RawLua};
// Re-export mutex wrappers
@@ -79,10 +79,10 @@ pub(crate) enum HookKind {
}
#[cfg(all(feature = "send", not(feature = "luau")))]
pub(crate) type HookCallback = XRc<dyn Fn(&Lua, Debug) -> Result<VmState> + Send>;
pub(crate) type HookCallback = XRc<dyn Fn(&Lua, &Debug) -> Result<VmState> + Send>;
#[cfg(all(not(feature = "send"), not(feature = "luau")))]
pub(crate) type HookCallback = XRc<dyn Fn(&Lua, Debug) -> Result<VmState>>;
pub(crate) type HookCallback = XRc<dyn Fn(&Lua, &Debug) -> Result<VmState>>;
#[cfg(all(feature = "send", feature = "luau"))]
pub(crate) type InterruptCallback = XRc<dyn Fn(&Lua) -> Result<VmState> + Send>;
+4 -4
View File
@@ -43,7 +43,7 @@ impl AppData {
#[inline]
#[track_caller]
pub(crate) fn borrow<T: 'static>(&self, guard: Option<LuaGuard>) -> Option<AppDataRef<T>> {
pub(crate) fn borrow<T: 'static>(&self, guard: Option<LuaGuard>) -> Option<AppDataRef<'_, T>> {
match self.try_borrow(guard) {
Ok(data) => data,
Err(err) => panic!("already mutably borrowed: {err:?}"),
@@ -53,7 +53,7 @@ impl AppData {
pub(crate) fn try_borrow<T: 'static>(
&self,
guard: Option<LuaGuard>,
) -> Result<Option<AppDataRef<T>>, BorrowError> {
) -> Result<Option<AppDataRef<'_, T>>, BorrowError> {
let data = unsafe { &*self.container.get() }
.get(&TypeId::of::<T>())
.map(|c| c.try_borrow())
@@ -74,7 +74,7 @@ impl AppData {
#[inline]
#[track_caller]
pub(crate) fn borrow_mut<T: 'static>(&self, guard: Option<LuaGuard>) -> Option<AppDataRefMut<T>> {
pub(crate) fn borrow_mut<T: 'static>(&self, guard: Option<LuaGuard>) -> Option<AppDataRefMut<'_, T>> {
match self.try_borrow_mut(guard) {
Ok(data) => data,
Err(err) => panic!("already borrowed: {err:?}"),
@@ -84,7 +84,7 @@ impl AppData {
pub(crate) fn try_borrow_mut<T: 'static>(
&self,
guard: Option<LuaGuard>,
) -> Result<Option<AppDataRefMut<T>>, BorrowMutError> {
) -> Result<Option<AppDataRefMut<'_, T>>, BorrowMutError> {
let data = unsafe { &*self.container.get() }
.get(&TypeId::of::<T>())
.map(|c| c.try_borrow_mut())
+1 -1
View File
@@ -31,7 +31,7 @@ mod inner {
}
#[inline(always)]
pub(crate) fn lock(&self) -> ReentrantMutexGuard<T> {
pub(crate) fn lock(&self) -> ReentrantMutexGuard<'_, T> {
ReentrantMutexGuard(&self.0)
}
+36 -28
View File
@@ -240,6 +240,13 @@ impl AsRef<str> for MetaMethod {
}
}
impl From<MetaMethod> for StdString {
#[inline]
fn from(method: MetaMethod) -> Self {
method.name().to_owned()
}
}
/// Method registry for [`UserData`] implementors.
pub trait UserDataMethods<T> {
/// Add a regular method which accepts a `&T` as the first parameter.
@@ -249,7 +256,7 @@ pub trait UserDataMethods<T> {
///
/// If `add_meta_method` is used to set the `__index` metamethod, the `__index` metamethod will
/// be used as a fall-back if no regular method is found.
fn add_method<M, A, R>(&mut self, name: impl ToString, method: M)
fn add_method<M, A, R>(&mut self, name: impl Into<StdString>, method: M)
where
M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -260,7 +267,7 @@ pub trait UserDataMethods<T> {
/// Refer to [`add_method`] for more information about the implementation.
///
/// [`add_method`]: UserDataMethods::add_method
fn add_method_mut<M, A, R>(&mut self, name: impl ToString, method: M)
fn add_method_mut<M, A, R>(&mut self, name: impl Into<StdString>, method: M)
where
M: FnMut(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -273,7 +280,7 @@ pub trait UserDataMethods<T> {
/// [`add_method`]: UserDataMethods::add_method
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
fn add_async_method<M, A, MR, R>(&mut self, name: impl ToString, method: M)
fn add_async_method<M, A, MR, R>(&mut self, name: impl Into<StdString>, method: M)
where
T: 'static,
M: Fn(Lua, UserDataRef<T>, A) -> MR + MaybeSend + 'static,
@@ -288,7 +295,7 @@ pub trait UserDataMethods<T> {
/// [`add_method`]: UserDataMethods::add_method
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
fn add_async_method_mut<M, A, MR, R>(&mut self, name: impl ToString, method: M)
fn add_async_method_mut<M, A, MR, R>(&mut self, name: impl Into<StdString>, method: M)
where
T: 'static,
M: Fn(Lua, UserDataRefMut<T>, A) -> MR + MaybeSend + 'static,
@@ -301,7 +308,7 @@ pub trait UserDataMethods<T> {
/// The first argument will be a [`AnyUserData`] of type `T` if the method is called with Lua
/// method syntax: `my_userdata:my_method(arg1, arg2)`, or it is passed in as the first
/// argument: `my_userdata.my_method(my_userdata, arg1, arg2)`.
fn add_function<F, A, R>(&mut self, name: impl ToString, function: F)
fn add_function<F, A, R>(&mut self, name: impl Into<StdString>, function: F)
where
F: Fn(&Lua, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -312,7 +319,7 @@ pub trait UserDataMethods<T> {
/// This is a version of [`add_function`] that accepts a `FnMut` argument.
///
/// [`add_function`]: UserDataMethods::add_function
fn add_function_mut<F, A, R>(&mut self, name: impl ToString, function: F)
fn add_function_mut<F, A, R>(&mut self, name: impl Into<StdString>, function: F)
where
F: FnMut(&Lua, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -326,7 +333,7 @@ pub trait UserDataMethods<T> {
/// [`add_function`]: UserDataMethods::add_function
#[cfg(feature = "async")]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
fn add_async_function<F, A, FR, R>(&mut self, name: impl ToString, function: F)
fn add_async_function<F, A, FR, R>(&mut self, name: impl Into<StdString>, function: F)
where
F: Fn(Lua, A) -> FR + MaybeSend + 'static,
A: FromLuaMulti,
@@ -341,7 +348,7 @@ pub trait UserDataMethods<T> {
/// side has a metatable. To prevent this, use [`add_meta_function`].
///
/// [`add_meta_function`]: UserDataMethods::add_meta_function
fn add_meta_method<M, A, R>(&mut self, name: impl ToString, method: M)
fn add_meta_method<M, A, R>(&mut self, name: impl Into<StdString>, method: M)
where
M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -355,7 +362,7 @@ pub trait UserDataMethods<T> {
/// side has a metatable. To prevent this, use [`add_meta_function`].
///
/// [`add_meta_function`]: UserDataMethods::add_meta_function
fn add_meta_method_mut<M, A, R>(&mut self, name: impl ToString, method: M)
fn add_meta_method_mut<M, A, R>(&mut self, name: impl Into<StdString>, method: M)
where
M: FnMut(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -371,7 +378,7 @@ pub trait UserDataMethods<T> {
docsrs,
doc(cfg(all(feature = "async", not(any(feature = "lua51", feature = "luau")))))
)]
fn add_async_meta_method<M, A, MR, R>(&mut self, name: impl ToString, method: M)
fn add_async_meta_method<M, A, MR, R>(&mut self, name: impl Into<StdString>, method: M)
where
T: 'static,
M: Fn(Lua, UserDataRef<T>, A) -> MR + MaybeSend + 'static,
@@ -387,7 +394,7 @@ pub trait UserDataMethods<T> {
/// [`add_meta_method_mut`]: UserDataMethods::add_meta_method_mut
#[cfg(all(feature = "async", not(any(feature = "lua51", feature = "luau"))))]
#[cfg_attr(docsrs, doc(cfg(feature = "async")))]
fn add_async_meta_method_mut<M, A, MR, R>(&mut self, name: impl ToString, method: M)
fn add_async_meta_method_mut<M, A, MR, R>(&mut self, name: impl Into<StdString>, method: M)
where
T: 'static,
M: Fn(Lua, UserDataRefMut<T>, A) -> MR + MaybeSend + 'static,
@@ -400,7 +407,7 @@ pub trait UserDataMethods<T> {
/// Metamethods for binary operators can be triggered if either the left or right argument to
/// the binary operator has a metatable, so the first argument here is not necessarily a
/// userdata of type `T`.
fn add_meta_function<F, A, R>(&mut self, name: impl ToString, function: F)
fn add_meta_function<F, A, R>(&mut self, name: impl Into<StdString>, function: F)
where
F: Fn(&Lua, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -411,7 +418,7 @@ pub trait UserDataMethods<T> {
/// This is a version of [`add_meta_function`] that accepts a `FnMut` argument.
///
/// [`add_meta_function`]: UserDataMethods::add_meta_function
fn add_meta_function_mut<F, A, R>(&mut self, name: impl ToString, function: F)
fn add_meta_function_mut<F, A, R>(&mut self, name: impl Into<StdString>, function: F)
where
F: FnMut(&Lua, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
@@ -427,7 +434,7 @@ pub trait UserDataMethods<T> {
docsrs,
doc(cfg(all(feature = "async", not(any(feature = "lua51", feature = "luau")))))
)]
fn add_async_meta_function<F, A, FR, R>(&mut self, name: impl ToString, function: F)
fn add_async_meta_function<F, A, FR, R>(&mut self, name: impl Into<StdString>, function: F)
where
F: Fn(Lua, A) -> FR + MaybeSend + 'static,
A: FromLuaMulti,
@@ -446,7 +453,7 @@ pub trait UserDataFields<T> {
///
/// If `add_meta_method` is used to set the `__index` metamethod, it will
/// be used as a fall-back if no regular field or method are found.
fn add_field<V>(&mut self, name: impl ToString, value: V)
fn add_field<V>(&mut self, name: impl Into<StdString>, value: V)
where
V: IntoLua + 'static;
@@ -457,7 +464,7 @@ pub trait UserDataFields<T> {
///
/// If `add_meta_method` is used to set the `__index` metamethod, the `__index` metamethod will
/// be used as a fall-back if no regular field or method are found.
fn add_field_method_get<M, R>(&mut self, name: impl ToString, method: M)
fn add_field_method_get<M, R>(&mut self, name: impl Into<StdString>, method: M)
where
M: Fn(&Lua, &T) -> Result<R> + MaybeSend + 'static,
R: IntoLua;
@@ -470,21 +477,21 @@ pub trait UserDataFields<T> {
///
/// If `add_meta_method` is used to set the `__newindex` metamethod, the `__newindex` metamethod
/// will be used as a fall-back if no regular field is found.
fn add_field_method_set<M, A>(&mut self, name: impl ToString, method: M)
fn add_field_method_set<M, A>(&mut self, name: impl Into<StdString>, method: M)
where
M: FnMut(&Lua, &mut T, A) -> Result<()> + MaybeSend + 'static,
A: FromLua;
/// Add a regular field getter as a function which accepts a generic [`AnyUserData`] of type `T`
/// argument.
fn add_field_function_get<F, R>(&mut self, name: impl ToString, function: F)
fn add_field_function_get<F, R>(&mut self, name: impl Into<StdString>, function: F)
where
F: Fn(&Lua, AnyUserData) -> Result<R> + MaybeSend + 'static,
R: IntoLua;
/// Add a regular field setter as a function which accepts a generic [`AnyUserData`] of type `T`
/// first argument.
fn add_field_function_set<F, A>(&mut self, name: impl ToString, function: F)
fn add_field_function_set<F, A>(&mut self, name: impl Into<StdString>, function: F)
where
F: FnMut(&Lua, AnyUserData, A) -> Result<()> + MaybeSend + 'static,
A: FromLua;
@@ -497,7 +504,7 @@ pub trait UserDataFields<T> {
///
/// `mlua` will trigger an error on an attempt to define a protected metamethod,
/// like `__gc` or `__metatable`.
fn add_meta_field<V>(&mut self, name: impl ToString, value: V)
fn add_meta_field<V>(&mut self, name: impl Into<StdString>, value: V)
where
V: IntoLua + 'static;
@@ -509,7 +516,7 @@ pub trait UserDataFields<T> {
///
/// `mlua` will trigger an error on an attempt to define a protected metamethod,
/// like `__gc` or `__metatable`.
fn add_meta_field_with<F, R>(&mut self, name: impl ToString, f: F)
fn add_meta_field_with<F, R>(&mut self, name: impl Into<StdString>, f: F)
where
F: FnOnce(&Lua) -> Result<R> + 'static,
R: IntoLua;
@@ -881,16 +888,17 @@ impl AnyUserData {
self.raw_metatable().map(UserDataMetatable)
}
/// Returns a raw metatable of this [`AnyUserData`].
fn raw_metatable(&self) -> Result<Table> {
let lua = self.0.lua.lock();
let state = lua.state();
let ref_thread = lua.ref_thread();
unsafe {
let _sg = StackGuard::new(state);
check_stack(state, 3)?;
// Check that userdata is registered and not destructed
// All registered userdata types have a non-empty metatable
let _type_id = lua.get_userdata_ref_type_id(&self.0)?;
lua.push_userdata_ref(&self.0)?;
ffi::lua_getmetatable(state, -1); // Checked that non-empty on the previous call
Ok(Table(lua.pop_ref()))
ffi::lua_getmetatable(ref_thread, self.0.index);
Ok(Table(lua.pop_ref_thread()))
}
}
@@ -1008,7 +1016,7 @@ impl UserDataMetatable {
/// The pairs are wrapped in a [`Result`], since they are lazily converted to `V` type.
///
/// [`Result`]: crate::Result
pub fn pairs<V: FromLua>(&self) -> UserDataMetatablePairs<V> {
pub fn pairs<V: FromLua>(&self) -> UserDataMetatablePairs<'_, V> {
UserDataMetatablePairs(self.0.pairs())
}
}
+7 -7
View File
@@ -8,7 +8,7 @@ use crate::value::Value;
use crate::Function;
#[cfg(feature = "async")]
use futures_util::future::{self, Either, Future};
use crate::function::AsyncCallFuture;
impl ObjectLike for AnyUserData {
#[inline]
@@ -35,7 +35,7 @@ impl ObjectLike for AnyUserData {
#[cfg(feature = "async")]
#[inline]
fn call_async<R>(&self, args: impl IntoLuaMulti) -> impl Future<Output = Result<R>>
fn call_async<R>(&self, args: impl IntoLuaMulti) -> AsyncCallFuture<R>
where
R: FromLuaMulti,
{
@@ -51,7 +51,7 @@ impl ObjectLike for AnyUserData {
}
#[cfg(feature = "async")]
fn call_async_method<R>(&self, name: &str, args: impl IntoLuaMulti) -> impl Future<Output = Result<R>>
fn call_async_method<R>(&self, name: &str, args: impl IntoLuaMulti) -> AsyncCallFuture<R>
where
R: FromLuaMulti,
{
@@ -72,17 +72,17 @@ impl ObjectLike for AnyUserData {
}
#[cfg(feature = "async")]
fn call_async_function<R>(&self, name: &str, args: impl IntoLuaMulti) -> impl Future<Output = Result<R>>
fn call_async_function<R>(&self, name: &str, args: impl IntoLuaMulti) -> AsyncCallFuture<R>
where
R: FromLuaMulti,
{
match self.get(name) {
Ok(Value::Function(func)) => Either::Left(func.call_async(args)),
Ok(Value::Function(func)) => func.call_async(args),
Ok(val) => {
let msg = format!("attempt to call a {} value (function '{name}')", val.type_name());
Either::Right(future::ready(Err(Error::RuntimeError(msg))))
AsyncCallFuture::error(Error::RuntimeError(msg))
}
Err(err) => Either::Right(future::ready(Err(err))),
Err(err) => AsyncCallFuture::error(err),
}
}
+1 -1
View File
@@ -63,7 +63,7 @@ impl<T> TryFrom<UserDataVariant<T>> for UserDataRef<T> {
#[inline]
fn try_from(variant: UserDataVariant<T>) -> Result<Self> {
let guard = if !cfg!(feature = "send") || is_sync::<T>() {
let guard = if cfg!(not(feature = "send")) || is_sync::<T>() {
variant.raw_lock().try_lock_shared_guarded()
} else {
variant.raw_lock().try_lock_exclusive_guarded()
+42 -42
View File
@@ -365,101 +365,101 @@ fn get_function_name<T>(name: &str) -> StdString {
}
impl<T> UserDataFields<T> for UserDataRegistry<T> {
fn add_field<V>(&mut self, name: impl ToString, value: V)
fn add_field<V>(&mut self, name: impl Into<StdString>, value: V)
where
V: IntoLua + 'static,
{
let name = name.to_string();
let name = name.into();
self.raw.fields.push((name, value.into_lua(self.lua.lua())));
}
fn add_field_method_get<M, R>(&mut self, name: impl ToString, method: M)
fn add_field_method_get<M, R>(&mut self, name: impl Into<StdString>, method: M)
where
M: Fn(&Lua, &T) -> Result<R> + MaybeSend + 'static,
R: IntoLua,
{
let name = name.to_string();
let name = name.into();
let callback = self.box_method(&name, move |lua, data, ()| method(lua, data));
self.raw.field_getters.push((name, callback));
}
fn add_field_method_set<M, A>(&mut self, name: impl ToString, method: M)
fn add_field_method_set<M, A>(&mut self, name: impl Into<StdString>, method: M)
where
M: FnMut(&Lua, &mut T, A) -> Result<()> + MaybeSend + 'static,
A: FromLua,
{
let name = name.to_string();
let name = name.into();
let callback = self.box_method_mut(&name, method);
self.raw.field_setters.push((name, callback));
}
fn add_field_function_get<F, R>(&mut self, name: impl ToString, function: F)
fn add_field_function_get<F, R>(&mut self, name: impl Into<StdString>, function: F)
where
F: Fn(&Lua, AnyUserData) -> Result<R> + MaybeSend + 'static,
R: IntoLua,
{
let name = name.to_string();
let name = name.into();
let callback = self.box_function(&name, function);
self.raw.field_getters.push((name, callback));
}
fn add_field_function_set<F, A>(&mut self, name: impl ToString, mut function: F)
fn add_field_function_set<F, A>(&mut self, name: impl Into<StdString>, mut function: F)
where
F: FnMut(&Lua, AnyUserData, A) -> Result<()> + MaybeSend + 'static,
A: FromLua,
{
let name = name.to_string();
let name = name.into();
let callback = self.box_function_mut(&name, move |lua, (data, val)| function(lua, data, val));
self.raw.field_setters.push((name, callback));
}
fn add_meta_field<V>(&mut self, name: impl ToString, value: V)
fn add_meta_field<V>(&mut self, name: impl Into<StdString>, value: V)
where
V: IntoLua + 'static,
{
let lua = self.lua.lua();
let name = name.to_string();
let name = name.into();
let field = Self::check_meta_field(lua, &name, value).and_then(|v| v.into_lua(lua));
self.raw.meta_fields.push((name, field));
}
fn add_meta_field_with<F, R>(&mut self, name: impl ToString, f: F)
fn add_meta_field_with<F, R>(&mut self, name: impl Into<StdString>, f: F)
where
F: FnOnce(&Lua) -> Result<R> + 'static,
R: IntoLua,
{
let lua = self.lua.lua();
let name = name.to_string();
let name = name.into();
let field = f(lua).and_then(|v| Self::check_meta_field(lua, &name, v).and_then(|v| v.into_lua(lua)));
self.raw.meta_fields.push((name, field));
}
}
impl<T> UserDataMethods<T> for UserDataRegistry<T> {
fn add_method<M, A, R>(&mut self, name: impl ToString, method: M)
fn add_method<M, A, R>(&mut self, name: impl Into<StdString>, method: M)
where
M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
R: IntoLuaMulti,
{
let name = name.to_string();
let name = name.into();
let callback = self.box_method(&name, method);
self.raw.methods.push((name, callback));
}
fn add_method_mut<M, A, R>(&mut self, name: impl ToString, method: M)
fn add_method_mut<M, A, R>(&mut self, name: impl Into<StdString>, method: M)
where
M: FnMut(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
R: IntoLuaMulti,
{
let name = name.to_string();
let name = name.into();
let callback = self.box_method_mut(&name, method);
self.raw.methods.push((name, callback));
}
#[cfg(feature = "async")]
fn add_async_method<M, A, MR, R>(&mut self, name: impl ToString, method: M)
fn add_async_method<M, A, MR, R>(&mut self, name: impl Into<StdString>, method: M)
where
T: 'static,
M: Fn(Lua, UserDataRef<T>, A) -> MR + MaybeSend + 'static,
@@ -467,13 +467,13 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
MR: Future<Output = Result<R>> + MaybeSend + 'static,
R: IntoLuaMulti,
{
let name = name.to_string();
let name = name.into();
let callback = self.box_async_method(&name, method);
self.raw.async_methods.push((name, callback));
}
#[cfg(feature = "async")]
fn add_async_method_mut<M, A, MR, R>(&mut self, name: impl ToString, method: M)
fn add_async_method_mut<M, A, MR, R>(&mut self, name: impl Into<StdString>, method: M)
where
T: 'static,
M: Fn(Lua, UserDataRefMut<T>, A) -> MR + MaybeSend + 'static,
@@ -481,70 +481,70 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
MR: Future<Output = Result<R>> + MaybeSend + 'static,
R: IntoLuaMulti,
{
let name = name.to_string();
let name = name.into();
let callback = self.box_async_method_mut(&name, method);
self.raw.async_methods.push((name, callback));
}
fn add_function<F, A, R>(&mut self, name: impl ToString, function: F)
fn add_function<F, A, R>(&mut self, name: impl Into<StdString>, function: F)
where
F: Fn(&Lua, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
R: IntoLuaMulti,
{
let name = name.to_string();
let name = name.into();
let callback = self.box_function(&name, function);
self.raw.methods.push((name, callback));
}
fn add_function_mut<F, A, R>(&mut self, name: impl ToString, function: F)
fn add_function_mut<F, A, R>(&mut self, name: impl Into<StdString>, function: F)
where
F: FnMut(&Lua, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
R: IntoLuaMulti,
{
let name = name.to_string();
let name = name.into();
let callback = self.box_function_mut(&name, function);
self.raw.methods.push((name, callback));
}
#[cfg(feature = "async")]
fn add_async_function<F, A, FR, R>(&mut self, name: impl ToString, function: F)
fn add_async_function<F, A, FR, R>(&mut self, name: impl Into<StdString>, function: F)
where
F: Fn(Lua, A) -> FR + MaybeSend + 'static,
A: FromLuaMulti,
FR: Future<Output = Result<R>> + MaybeSend + 'static,
R: IntoLuaMulti,
{
let name = name.to_string();
let name = name.into();
let callback = self.box_async_function(&name, function);
self.raw.async_methods.push((name, callback));
}
fn add_meta_method<M, A, R>(&mut self, name: impl ToString, method: M)
fn add_meta_method<M, A, R>(&mut self, name: impl Into<StdString>, method: M)
where
M: Fn(&Lua, &T, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
R: IntoLuaMulti,
{
let name = name.to_string();
let name = name.into();
let callback = self.box_method(&name, method);
self.raw.meta_methods.push((name, callback));
}
fn add_meta_method_mut<M, A, R>(&mut self, name: impl ToString, method: M)
fn add_meta_method_mut<M, A, R>(&mut self, name: impl Into<StdString>, method: M)
where
M: FnMut(&Lua, &mut T, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
R: IntoLuaMulti,
{
let name = name.to_string();
let name = name.into();
let callback = self.box_method_mut(&name, method);
self.raw.meta_methods.push((name, callback));
}
#[cfg(all(feature = "async", not(any(feature = "lua51", feature = "luau"))))]
fn add_async_meta_method<M, A, MR, R>(&mut self, name: impl ToString, method: M)
fn add_async_meta_method<M, A, MR, R>(&mut self, name: impl Into<StdString>, method: M)
where
T: 'static,
M: Fn(Lua, UserDataRef<T>, A) -> MR + MaybeSend + 'static,
@@ -552,13 +552,13 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
MR: Future<Output = Result<R>> + MaybeSend + 'static,
R: IntoLuaMulti,
{
let name = name.to_string();
let name = name.into();
let callback = self.box_async_method(&name, method);
self.raw.async_meta_methods.push((name, callback));
}
#[cfg(all(feature = "async", not(any(feature = "lua51", feature = "luau"))))]
fn add_async_meta_method_mut<M, A, MR, R>(&mut self, name: impl ToString, method: M)
fn add_async_meta_method_mut<M, A, MR, R>(&mut self, name: impl Into<StdString>, method: M)
where
T: 'static,
M: Fn(Lua, UserDataRefMut<T>, A) -> MR + MaybeSend + 'static,
@@ -566,42 +566,42 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
MR: Future<Output = Result<R>> + MaybeSend + 'static,
R: IntoLuaMulti,
{
let name = name.to_string();
let name = name.into();
let callback = self.box_async_method_mut(&name, method);
self.raw.async_meta_methods.push((name, callback));
}
fn add_meta_function<F, A, R>(&mut self, name: impl ToString, function: F)
fn add_meta_function<F, A, R>(&mut self, name: impl Into<StdString>, function: F)
where
F: Fn(&Lua, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
R: IntoLuaMulti,
{
let name = name.to_string();
let name = name.into();
let callback = self.box_function(&name, function);
self.raw.meta_methods.push((name, callback));
}
fn add_meta_function_mut<F, A, R>(&mut self, name: impl ToString, function: F)
fn add_meta_function_mut<F, A, R>(&mut self, name: impl Into<StdString>, function: F)
where
F: FnMut(&Lua, A) -> Result<R> + MaybeSend + 'static,
A: FromLuaMulti,
R: IntoLuaMulti,
{
let name = name.to_string();
let name = name.into();
let callback = self.box_function_mut(&name, function);
self.raw.meta_methods.push((name, callback));
}
#[cfg(all(feature = "async", not(any(feature = "lua51", feature = "luau"))))]
fn add_async_meta_function<F, A, FR, R>(&mut self, name: impl ToString, function: F)
fn add_async_meta_function<F, A, FR, R>(&mut self, name: impl Into<StdString>, function: F)
where
F: Fn(Lua, A) -> FR + MaybeSend + 'static,
A: FromLuaMulti,
FR: Future<Output = Result<R>> + MaybeSend + 'static,
R: IntoLuaMulti,
{
let name = name.to_string();
let name = name.into();
let callback = self.box_async_function(&name, function);
self.raw.async_meta_methods.push((name, callback));
}
+2 -2
View File
@@ -88,7 +88,7 @@ impl Drop for StackGuard {
#[inline(always)]
pub(crate) unsafe fn push_string(state: *mut ffi::lua_State, s: &[u8], protect: bool) -> Result<()> {
// Always use protected mode if the string is too long
if protect || s.len() > (1 << 30) {
if protect || s.len() >= const { 1 << 30 } {
protect_lua!(state, 0, 1, |state| {
ffi::lua_pushlstring(state, s.as_ptr() as *const c_char, s.len());
})
@@ -122,7 +122,7 @@ pub(crate) unsafe fn push_table(
) -> Result<()> {
let narr: c_int = narr.try_into().unwrap_or(c_int::MAX);
let nrec: c_int = nrec.try_into().unwrap_or(c_int::MAX);
if protect {
if protect || narr >= const { 1 << 30 } || nrec >= const { 1 << 27 } {
protect_lua!(state, 0, 1, |state| ffi::lua_createtable(state, narr, nrec))
} else {
ffi::lua_createtable(state, narr, nrec);
+1 -1
View File
@@ -73,7 +73,7 @@ pub(crate) unsafe fn init_internal_metatable<T: TypeKey>(
Ok(())
}
// Uses 2 stack spaces, does not call checkstack
// Uses up to 1 stack space, does not call `checkstack`
pub(crate) unsafe fn get_internal_userdata<T: TypeKey>(
state: *mut ffi::lua_State,
index: c_int,
+10 -2
View File
@@ -356,14 +356,22 @@ impl Value {
///
/// If the value is a Lua [`String`], try to convert it to [`BorrowedStr`] or return `None`
/// otherwise.
#[deprecated(
since = "0.11.0",
note = "This method does not follow Rust naming convention. Use `as_string().and_then(|s| s.to_str().ok())` instead."
)]
#[inline]
pub fn as_str(&self) -> Option<BorrowedStr> {
pub fn as_str(&self) -> Option<BorrowedStr<'_>> {
self.as_string().and_then(|s| s.to_str().ok())
}
/// Cast the value to [`StdString`].
///
/// If the value is a Lua [`String`], converts it to [`StdString`] or returns `None` otherwise.
#[deprecated(
since = "0.11.0",
note = "This method does not follow Rust naming convention. Use `as_string().map(|s| s.to_string_lossy())` instead."
)]
#[inline]
pub fn as_string_lossy(&self) -> Option<StdString> {
self.as_string().map(|s| s.to_string_lossy())
@@ -484,7 +492,7 @@ impl Value {
#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
#[doc(hidden)]
pub fn to_serializable(&self) -> SerializableValue {
pub fn to_serializable(&self) -> SerializableValue<'_> {
SerializableValue::new(self, Default::default(), None)
}
+31 -1
View File
@@ -386,7 +386,7 @@ async fn test_async_table_object_like() -> Result<()> {
table.get::<i64>("val")
})?,
)?;
table.set_metatable(Some(metatable));
table.set_metatable(Some(metatable))?;
assert_eq!(table.call_async::<i64>(()).await.unwrap(), 15);
match table.call_async_method::<()>("non_existent", ()).await {
@@ -610,6 +610,36 @@ async fn test_async_task() -> Result<()> {
Ok(())
}
#[tokio::test]
async fn test_async_task_abort() -> Result<()> {
let lua = Lua::new();
let sleep = lua.create_async_function(move |_lua, n: u64| async move {
sleep_ms(n).await;
Ok(())
})?;
lua.globals().set("sleep", sleep)?;
let local = tokio::task::LocalSet::new();
local
.run_until(async {
let lua2 = lua.clone();
let jh = tokio::task::spawn_local(async move {
lua2.load("sleep(200) result = 'done'")
.exec_async()
.await
.unwrap();
});
sleep_ms(100).await; // Wait for the task to start
jh.abort();
})
.await;
local.await;
assert_eq!(lua.globals().get::<Value>("result")?, Value::Nil);
Ok(())
}
#[tokio::test]
#[cfg(not(feature = "luau"))]
async fn test_async_hook() -> Result<()> {
+9 -12
View File
@@ -119,12 +119,11 @@ fn test_compiler() -> Result<()> {
.set_debug_level(2)
.set_type_info_level(1)
.set_coverage_level(2)
.set_vector_lib("vector")
.set_vector_ctor("new")
.set_vector_ctor("vector.new")
.set_vector_type("vector")
.set_mutable_globals(vec!["mutable_global"])
.set_userdata_types(vec!["MyUserdata"])
.set_disabled_builtins(vec!["tostring"]);
.set_mutable_globals(["mutable_global"])
.set_userdata_types(["MyUserdata"])
.set_disabled_builtins(["tostring"]);
assert!(compiler.compile("return tostring(vector.new(1, 2, 3))").is_ok());
@@ -142,16 +141,14 @@ fn test_compiler() -> Result<()> {
#[cfg(feature = "luau")]
#[test]
fn test_compiler_library_constants() {
use mlua::{CompileConstant, Compiler, Vector};
use mlua::{Compiler, Vector};
let compiler = Compiler::new()
.set_optimization_level(2)
.set_library_constants(vec![
("mylib", "const_bool", CompileConstant::Boolean(true)),
("mylib", "const_num", CompileConstant::Number(123.0)),
("mylib", "const_vec", CompileConstant::Vector(Vector::zero())),
("mylib", "const_str", "value1".into()),
]);
.add_library_constant("mylib.const_bool", true)
.add_library_constant("mylib.const_num", 123.0)
.add_library_constant("mylib.const_vec", Vector::zero())
.add_library_constant("mylib.const_str", "value1");
let lua = Lua::new();
lua.set_compiler(compiler);
+6 -6
View File
@@ -267,7 +267,7 @@ fn test_registry_value_into_lua() -> Result<()> {
let r = lua.create_registry_value(&s)?;
let value1 = lua.pack(&r)?;
let value2 = lua.pack(r)?;
assert_eq!(value1.as_str().as_deref(), Some("hello, world"));
assert_eq!(value1.to_string()?, "hello, world");
assert_eq!(value1.to_pointer(), value2.to_pointer());
// Push into stack
@@ -560,11 +560,11 @@ fn test_osstring_into_from_lua() -> Result<()> {
let v = lua.pack(s.as_os_str())?;
assert!(v.is_string());
assert_eq!(v.as_str().unwrap(), "hello, world");
assert_eq!(v.as_string().unwrap(), "hello, world");
let v = lua.pack(s)?;
assert!(v.is_string());
assert_eq!(v.as_str().unwrap(), "hello, world");
assert_eq!(v.as_string().unwrap(), "hello, world");
let s = lua.create_string("hello, world")?;
let bstr = lua.unpack::<OsString>(Value::String(s))?;
@@ -588,11 +588,11 @@ fn test_pathbuf_into_from_lua() -> Result<()> {
let v = lua.pack(pb.as_path())?;
assert!(v.is_string());
assert_eq!(v.as_str().unwrap(), pb_str);
assert_eq!(v.to_string().unwrap(), pb_str);
let v = lua.pack(pb.clone())?;
assert!(v.is_string());
assert_eq!(v.as_str().unwrap(), pb_str);
assert_eq!(v.to_string().unwrap(), pb_str);
let s = lua.create_string(pb_str)?;
let bstr = lua.unpack::<PathBuf>(Value::String(s))?;
@@ -724,7 +724,7 @@ fn test_char_into_lua() -> Result<()> {
let v = '🦀';
let v2 = v.into_lua(&lua)?;
assert_eq!(Some(v.to_string()), v2.as_string_lossy());
assert_eq!(*v2.as_string().unwrap(), v.to_string());
Ok(())
}
+2 -2
View File
@@ -306,7 +306,7 @@ fn test_function_deep_clone() -> Result<()> {
lua.globals().set("a", 1)?;
let func1 = lua.load("a += 1; return a").into_function()?;
let func2 = func1.deep_clone();
let func2 = func1.deep_clone()?;
assert_ne!(func1.to_pointer(), func2.to_pointer());
assert_eq!(func1.call::<i32>(())?, 2);
@@ -314,7 +314,7 @@ fn test_function_deep_clone() -> Result<()> {
// Check that for Rust functions deep_clone is just a clone
let rust_func = lua.create_function(|_, ()| Ok(42))?;
let rust_func2 = rust_func.deep_clone();
let rust_func2 = rust_func.deep_clone()?;
assert_eq!(rust_func.to_pointer(), rust_func2.to_pointer());
Ok(())
+2 -2
View File
@@ -24,7 +24,7 @@ fn test_line_counts() -> Result<()> {
let lua = Lua::new();
lua.set_hook(HookTriggers::EVERY_LINE, move |_lua, debug| {
assert_eq!(debug.event(), DebugEvent::Line);
hook_output.lock().unwrap().push(debug.curr_line());
hook_output.lock().unwrap().push(debug.current_line().unwrap());
Ok(VmState::Continue)
})?;
lua.load(
@@ -240,7 +240,7 @@ fn test_hook_threads() -> Result<()> {
let hook_output = output.clone();
co.set_hook(HookTriggers::EVERY_LINE, move |_lua, debug| {
assert_eq!(debug.event(), DebugEvent::Line);
hook_output.lock().unwrap().push(debug.curr_line());
hook_output.lock().unwrap().push(debug.current_line().unwrap());
Ok(VmState::Continue)
})?;
+20 -6
View File
@@ -3,7 +3,6 @@
use std::cell::Cell;
use std::fmt::Debug;
use std::os::raw::c_void;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::atomic::{AtomicBool, AtomicPtr, AtomicU64, Ordering};
use std::sync::Arc;
@@ -120,11 +119,13 @@ fn test_vector_metatable() -> Result<()> {
"#,
)
.eval::<Table>()?;
vector_mt.set_metatable(Some(vector_mt.clone()));
vector_mt.set_metatable(Some(vector_mt.clone()))?;
lua.set_type_metatable::<Vector>(Some(vector_mt.clone()));
lua.globals().set("Vector3", vector_mt)?;
let compiler = Compiler::new().set_vector_lib("Vector3").set_vector_ctor("new");
let compiler = Compiler::new()
.set_vector_ctor("Vector3.new")
.set_vector_type("Vector3");
// Test vector methods (fastcall)
lua.load(
@@ -167,9 +168,9 @@ fn test_readonly_table() -> Result<()> {
check_readonly_error(t.raw_pop::<Value>());
// Special case
match catch_unwind(AssertUnwindSafe(|| t.set_metatable(None))) {
Ok(_) => panic!("expected panic, got nothing"),
Err(_) => {}
match t.set_metatable(None) {
Err(Error::RuntimeError(e)) if e.contains("attempt to modify a readonly table") => {}
r => panic!("expected RuntimeError(...) with a specific message, got {r:?}"),
}
Ok(())
@@ -196,6 +197,14 @@ fn test_sandbox() -> Result<()> {
co.sandbox()?;
assert_eq!(co.resume::<Option<i32>>(())?, Some(123));
// collectgarbage should be restricted in sandboxed mode
let collectgarbage = lua.globals().get::<Function>("collectgarbage")?;
for arg in ["collect", "stop", "restart", "step", "isrunning"] {
let err = collectgarbage.call::<()>(arg).err().unwrap().to_string();
assert!(err.contains("collectgarbage called with invalid option"));
}
assert!(collectgarbage.call::<u64>("count").unwrap() > 0);
lua.sandbox(false)?;
// Previously set variable `global` should be cleared now
@@ -205,6 +214,11 @@ fn test_sandbox() -> Result<()> {
let table = lua.globals().get::<Table>("table")?;
table.set("test", "test")?;
// collectgarbage should work now
for arg in ["collect", "stop", "restart", "count", "step", "isrunning"] {
collectgarbage.call::<()>(arg).unwrap();
}
Ok(())
}
+34 -19
View File
@@ -105,63 +105,69 @@ fn test_require_without_config() {
let lua = Lua::new();
// RequireSimpleRelativePath
let res = run_require(&lua, "./require/without_config/dependency").unwrap();
let res = run_require(&lua, "./tests/luau/require/without_config/dependency").unwrap();
assert_eq!("result from dependency", get_str(&res, 1));
// RequireSimpleRelativePathWithinPcall
let res = run_require_pcall(&lua, "./require/without_config/dependency").unwrap();
let res = run_require_pcall(&lua, "./tests/luau/require/without_config/dependency").unwrap();
assert!(res[0].as_boolean().unwrap());
assert_eq!("result from dependency", get_str(&res[1], 1));
// RequireRelativeToRequiringFile
let res = run_require(&lua, "./require/without_config/module").unwrap();
let res = run_require(&lua, "./tests/luau/require/without_config/module").unwrap();
assert_eq!("result from dependency", get_str(&res, 1));
assert_eq!("required into module", get_str(&res, 2));
// RequireLua
let res = run_require(&lua, "./require/without_config/lua_dependency").unwrap();
let res = run_require(&lua, "./tests/luau/require/without_config/lua_dependency").unwrap();
assert_eq!("result from lua_dependency", get_str(&res, 1));
// RequireInitLuau
let res = run_require(&lua, "./require/without_config/luau").unwrap();
let res = run_require(&lua, "./tests/luau/require/without_config/luau").unwrap();
assert_eq!("result from init.luau", get_str(&res, 1));
// RequireInitLua
let res = run_require(&lua, "./require/without_config/lua").unwrap();
let res = run_require(&lua, "./tests/luau/require/without_config/lua").unwrap();
assert_eq!("result from init.lua", get_str(&res, 1));
// RequireSubmoduleUsingSelfIndirectly
let res = run_require(&lua, "./require/without_config/nested_module_requirer").unwrap();
let res = run_require(&lua, "./tests/luau/require/without_config/nested_module_requirer").unwrap();
assert_eq!("result from submodule", get_str(&res, 1));
// RequireSubmoduleUsingSelfDirectly
let res = run_require(&lua, "./require/without_config/nested").unwrap();
let res = run_require(&lua, "./tests/luau/require/without_config/nested").unwrap();
assert_eq!("result from submodule", get_str(&res, 1));
// CannotRequireInitLuauDirectly
let res = run_require(&lua, "./require/without_config/nested/init");
let res = run_require(&lua, "./tests/luau/require/without_config/nested/init");
assert!(res.is_err());
assert!((res.unwrap_err().to_string()).contains("could not resolve child component \"init\""));
// RequireNestedInits
let res = run_require(&lua, "./require/without_config/nested_inits_requirer").unwrap();
let res = run_require(&lua, "./tests/luau/require/without_config/nested_inits_requirer").unwrap();
assert_eq!("result from nested_inits/init", get_str(&res, 1));
assert_eq!("required into module", get_str(&res, 2));
// RequireWithFileAmbiguity
let res = run_require(&lua, "./require/without_config/ambiguous_file_requirer");
let res = run_require(
&lua,
"./tests/luau/require/without_config/ambiguous_file_requirer",
);
assert!(res.is_err());
assert!((res.unwrap_err().to_string())
.contains("could not resolve child component \"dependency\" (ambiguous)"));
// RequireWithDirectoryAmbiguity
let res = run_require(&lua, "./require/without_config/ambiguous_directory_requirer");
let res = run_require(
&lua,
"./tests/luau/require/without_config/ambiguous_directory_requirer",
);
assert!(res.is_err());
assert!((res.unwrap_err().to_string())
.contains("could not resolve child component \"dependency\" (ambiguous)"));
// CheckCachedResult
let res = run_require(&lua, "./require/without_config/validate_cache").unwrap();
let res = run_require(&lua, "./tests/luau/require/without_config/validate_cache").unwrap();
assert!(res.is_table());
}
@@ -170,15 +176,19 @@ fn test_require_with_config() {
let lua = Lua::new();
// RequirePathWithAlias
let res = run_require(&lua, "./require/with_config/src/alias_requirer").unwrap();
let res = run_require(&lua, "./tests/luau/require/with_config/src/alias_requirer").unwrap();
assert_eq!("result from dependency", get_str(&res, 1));
// RequirePathWithParentAlias
let res = run_require(&lua, "./require/with_config/src/parent_alias_requirer").unwrap();
let res = run_require(&lua, "./tests/luau/require/with_config/src/parent_alias_requirer").unwrap();
assert_eq!("result from other_dependency", get_str(&res, 1));
// RequirePathWithAliasPointingToDirectory
let res = run_require(&lua, "./require/with_config/src/directory_alias_requirer").unwrap();
let res = run_require(
&lua,
"./tests/luau/require/with_config/src/directory_alias_requirer",
)
.unwrap();
assert_eq!("result from subdirectory_dependency", get_str(&res, 1));
// RequireAliasThatDoesNotExist
@@ -192,7 +202,7 @@ fn test_require_with_config() {
assert!((res.unwrap_err().to_string()).contains("@ is not a valid alias"));
}
#[cfg(feature = "async")]
#[cfg(all(feature = "async", not(windows)))]
#[tokio::test]
async fn test_async_require() -> Result<()> {
let lua = Lua::new();
@@ -215,14 +225,19 @@ async fn test_async_require() -> Result<()> {
Ok(())
})?,
)?;
lua.globals().set("tmp_dir", temp_dir.path().to_str().unwrap())?;
lua.globals().set(
"curr_dir_components",
std::env::current_dir().unwrap().components().count(),
)?;
lua.load(
r#"
local result = require("./async_chunk")
local path_to_root = string.rep("/..", curr_dir_components - 1)
local result = require(`.{path_to_root}{tmp_dir}/async_chunk`)
assert(result == "result_after_async_sleep")
"#,
)
.set_name(format!("@{}", temp_dir.path().join("require.rs").display()))
.exec_async()
.await
}
+2 -2
View File
@@ -43,12 +43,12 @@ fn test_result_conversions() -> Result<()> {
let multi_err1 = err1.into_lua_multi(&lua)?;
assert_eq!(multi_err1.len(), 2);
assert_eq!(multi_err1[0], Value::Nil);
assert_eq!(multi_err1[1].as_str().unwrap(), "failure1");
assert_eq!(multi_err1[1].as_string().unwrap(), "failure1");
let ok2 = Ok::<_, Error>("!");
let multi_ok2 = ok2.into_lua_multi(&lua)?;
assert_eq!(multi_ok2.len(), 1);
assert_eq!(multi_ok2[0].as_str().unwrap(), "!");
assert_eq!(multi_ok2[0].as_string().unwrap(), "!");
let err2 = Err::<String, _>("failure2".into_lua_err());
let multi_err2 = err2.into_lua_multi(&lua)?;
assert_eq!(multi_err2.len(), 2);
+2 -2
View File
@@ -25,7 +25,7 @@ fn test_serialize() -> Result<(), Box<dyn StdError>> {
globals.set("null", lua.null())?;
let empty_array = lua.create_table()?;
empty_array.set_metatable(Some(lua.array_metatable()));
empty_array.set_metatable(Some(lua.array_metatable()))?;
globals.set("empty_array", empty_array)?;
let val = lua
@@ -173,7 +173,7 @@ fn test_serialize_sorted() -> LuaResult<()> {
globals.set("null", lua.null())?;
let empty_array = lua.create_table()?;
empty_array.set_metatable(Some(lua.array_metatable()));
empty_array.set_metatable(Some(lua.array_metatable()))?;
globals.set("empty_array", empty_array)?;
let value = lua
+2 -2
View File
@@ -298,10 +298,10 @@ fn test_metatable() -> Result<()> {
let table = lua.create_table()?;
let metatable = lua.create_table()?;
metatable.set("__index", lua.create_function(|_, ()| Ok("index_value"))?)?;
table.set_metatable(Some(metatable));
table.set_metatable(Some(metatable))?;
assert_eq!(table.get::<String>("any_key")?, "index_value");
assert_eq!(table.raw_get::<Value>("any_key")?, Value::Nil);
table.set_metatable(None);
table.set_metatable(None)?;
assert_eq!(table.get::<Value>("any_key")?, Value::Nil);
Ok(())
+55 -8
View File
@@ -147,6 +147,31 @@ fn test_eval() -> Result<()> {
Ok(())
}
#[test]
fn test_replace_globals() -> Result<()> {
let lua = Lua::new();
let globals = lua.create_table()?;
globals.set("foo", "bar")?;
lua.set_globals(globals.clone())?;
let val = lua.load("return foo").eval::<StdString>()?;
assert_eq!(val, "bar");
// Updating globals in sandboxed Lua state is not allowed
#[cfg(feature = "luau")]
{
lua.sandbox(true)?;
match lua.set_globals(globals) {
Err(Error::RuntimeError(msg))
if msg.contains("cannot change globals in a sandboxed Lua state") => {}
r => panic!("expected RuntimeError(...) with a specific error message, got {r:?}"),
}
}
Ok(())
}
#[test]
fn test_load_mode() -> Result<()> {
let lua = unsafe { Lua::unsafe_new() };
@@ -1251,14 +1276,18 @@ fn test_inspect_stack() -> Result<()> {
let lua = Lua::new();
// Not inside any function
assert!(lua.inspect_stack(0).is_none());
assert!(lua.inspect_stack(0, |_| ()).is_none());
let logline = lua.create_function(|lua, msg: StdString| {
let debug = lua.inspect_stack(1).unwrap(); // caller
let source = debug.source().short_src;
let source = source.as_deref().unwrap_or("?");
let line = debug.curr_line();
Ok(format!("{}:{} {}", source, line, msg))
let r = lua
.inspect_stack(1, |debug| {
let source = debug.source().short_src;
let source = source.as_deref().unwrap_or("?");
let line = debug.current_line().unwrap();
format!("{}:{} {}", source, line, msg)
})
.unwrap();
Ok(r)
})?;
lua.globals().set("logline", logline)?;
@@ -1281,8 +1310,7 @@ fn test_inspect_stack() -> Result<()> {
.exec()?;
let stack_info = lua.create_function(|lua, ()| {
let debug = lua.inspect_stack(1).unwrap(); // caller
let stack_info = debug.stack();
let stack_info = lua.inspect_stack(1, |debug| debug.stack()).unwrap();
Ok(format!("{stack_info:?}"))
})?;
lua.globals().set("stack_info", stack_info)?;
@@ -1312,6 +1340,25 @@ fn test_inspect_stack() -> Result<()> {
)
.exec()?;
// Test retrieving currently running function
let running_function =
lua.create_function(|lua, ()| Ok(lua.inspect_stack(1, |debug| debug.function())))?;
lua.globals().set("running_function", running_function)?;
lua.load(
r#"
local function baz()
return running_function()
end
if jit == nil then
assert(baz() == baz)
else
-- luajit inline the "baz" function and returns the chunk itself
assert(baz() == running_function())
end
"#,
)
.exec()?;
Ok(())
}
+1 -10
View File
@@ -255,16 +255,7 @@ fn test_value_conversions() -> Result<()> {
Value::String(lua.create_string("hello")?).as_string().unwrap(),
"hello"
);
assert_eq!(
Value::String(lua.create_string("hello")?).as_str().unwrap(),
"hello"
);
assert_eq!(
Value::String(lua.create_string("hello")?)
.as_string_lossy()
.unwrap(),
"hello"
);
assert_eq!(Value::String(lua.create_string("hello")?).to_string()?, "hello");
assert!(Value::Table(lua.create_table()?).is_table());
assert!(Value::Table(lua.create_table()?).as_table().is_some());
assert!(Value::Function(lua.create_function(|_, ()| Ok(())).unwrap()).is_function());