Compare commits

...

31 Commits

Author SHA1 Message Date
Alex Orlenko 9caf3542d9 v0.10.3 2025-01-27 21:33:51 +00:00
Alex Orlenko cb45db05fa Update README/CHANGELOG 2025-01-27 21:33:24 +00:00
Alex Orlenko d1cb2a9a96 mlua-sys: v0.6.7 2025-01-27 21:20:47 +00:00
Alex Orlenko aa3f6ba46c Fix prototype of new Luau compiler options and methods 2025-01-27 21:19:31 +00:00
Alex Orlenko cc57bed4c8 Update Luau to 0.657 2025-01-27 14:19:40 +00:00
Radiant b5d38ab2e3 Set Default for LuaValue to be nil. (#512) 2025-01-19 23:52:58 +00:00
Alex Orlenko cd4091f64d Allow exhaustive match on Value.
It was not possible because `ValueRef` variant in `Value::Other` was private.
Closes #502 and #503
2024-12-10 23:37:19 +00:00
Alex Orlenko 91e069a77e Optimize (and simplify) protected mode for Rust function calls 2024-12-07 00:04:12 +00:00
Alex Orlenko cacd3dc70f Add Table::set_safeenv method (Luau) 2024-12-04 10:40:49 +00:00
Alex Orlenko 6f6cda0099 v0.10.2 2024-12-01 13:04:06 +00:00
Alex Orlenko d51ce86142 mlua-sys: v0.6.6 2024-12-01 12:56:39 +00:00
Alex Orlenko aa061bce6f mlua_derive: v0.10.1 2024-12-01 12:55:50 +00:00
Alex Orlenko 1c6b6ad801 Fix tests 2024-12-01 12:54:35 +00:00
Evie 031854fa2a Switch proc-macro-error to proc-macro-error2 (#493) 2024-11-30 22:37:40 +00:00
Alex Orlenko 5fd96c7908 Don't run GC finalizers on ref thread.
If this happen then we don't have full access to the ref thread stack.
Fixes #491
2024-11-30 01:00:31 +00:00
Alex Orlenko 7a3f19b857 Ensure that buffer with Luau compiled code is always freed 2024-11-29 13:36:51 +00:00
Alex Orlenko 55a5d7ef10 Protect Lua(u) during chunk loading if memory limit is enforced
Relates to #488
2024-11-27 00:34:21 +00:00
Alex Orlenko af31dbd180 Use c string literal in few places 2024-11-25 22:53:59 +00:00
Alex Orlenko 9ae3cb0a7c Add doc about possible chunk name prefixes 2024-11-24 12:00:06 +00:00
Alex Orlenko fc1c80c142 Mark Chunk::wrap as non-public 2024-11-22 20:03:17 +00:00
Alex Orlenko ee7ced6334 Add Chunk::wrap method 2024-11-22 14:40:52 +00:00
Alex Orlenko d8307d0e4c Reduce visibility of Wrapped* structs 2024-11-22 13:08:57 +00:00
Alex Orlenko bf9fcc5aca Simplify WrappedString 2024-11-22 13:06:50 +00:00
Alex Orlenko 7ce6b97da9 Add String::wrap method to wrap arbitrary AsRef<[u8]> 2024-11-22 11:48:20 +00:00
Alex Orlenko 4891a6ac10 Fix utf-8 test when bstr v1.11 switchted to LowerHex 2024-11-17 18:01:05 +00:00
Alex Orlenko 4ef0d583fc impl Send for UserDataTypeId (in send mode) 2024-11-16 01:56:18 +00:00
cos 30b0122f5d Make build script work with OpenBSD
On OpenBSD the pkg-config names takes a minimalist format. No dash, and
no separator between the major and minor version number. Build script is
thus adapted to have also these in their set of alt_probes.

Signed-off-by: Alex Orlenko <zxteam@protonmail.com>
2024-11-16 01:52:43 +00:00
cos c31c72076f Make build script work with FreeBSD
On FreeBSD the pkg-config names takes the format with a dash, rather
than without (e.g. lua-5.4, not lua5.4). Thus adapt build script to
iterate over an array of alt_probes until finding a match.

Signed-off-by: Alex Orlenko <zxteam@protonmail.com>
2024-11-16 01:49:02 +00:00
Alex Orlenko 3bfaee4ecc Delay "any" userdata metatable creation until first instance 2024-11-16 01:47:04 +00:00
Alex Orlenko 89b68e2a24 Remove generic from RawLua::push_userdata_metatable.
This should help to reduce amount of generated code.
2024-11-16 01:44:17 +00:00
Alex Orlenko cbf805f492 Avoid ptr->usize->ptr conversion to comply strict provenance 2024-11-15 21:47:19 +00:00
32 changed files with 613 additions and 295 deletions
+16
View File
@@ -1,3 +1,19 @@
## v0.10.2 (Jan 27th, 2025)
- Set `Default` for `Value` to be `Nil`
- Allow exhaustive match on `Value` (#502)
- Add `Table::set_safeenv` method (Luau)
## v0.10.2 (Dec 1st, 2024)
- Switch proc-macro-error to proc-macro-error2 (#493)
- Do not allow Lua to run GC finalizers on ref thread (#491)
- Fix chunks loading in Luau when memory limit is enforced (#488)
- Added `String::wrap` method to wrap arbitrary `AsRef<[u8]>` into `impl IntoLua`
- Better FreeBSD/OpenBSD support (thanks to cos)
- Delay "any" userdata metatable creation until first instance is created (#482)
- Reduce amount of generated code for `UserData` (less generics)
## v0.10.1 (Nov 9th, 2024)
- Minimal Luau updated to 0.650
+3 -3
View File
@@ -1,6 +1,6 @@
[package]
name = "mlua"
version = "0.10.1" # remember to update mlua_derive
version = "0.10.3" # remember to update mlua_derive
authors = ["Aleksandr Orlenko <zxteam@pm.me>", "kyren <catherine@kyju.org>"]
rust-version = "1.79.0"
edition = "2021"
@@ -46,7 +46,7 @@ anyhow = ["dep:anyhow", "error-send"]
userdata-wrappers = []
[dependencies]
mlua_derive = { version = "=0.10.0", optional = true, path = "mlua_derive" }
mlua_derive = { version = "=0.10.1", optional = true, path = "mlua_derive" }
bstr = { version = "1.0", features = ["std"], default-features = false }
either = "1.0"
num-traits = { version = "0.2.14" }
@@ -58,7 +58,7 @@ serde-value = { version = "0.7", optional = true }
parking_lot = { version = "0.12", features = ["arc_lock"] }
anyhow = { version = "1.0", optional = true }
ffi = { package = "mlua-sys", version = "0.6.5", path = "mlua-sys" }
ffi = { package = "mlua-sys", version = "0.6.6", path = "mlua-sys" }
[target.'cfg(unix)'.dependencies]
libloading = { version = "0.8", optional = true }
+2 -2
View File
@@ -133,7 +133,7 @@ Add to `Cargo.toml` :
``` toml
[dependencies]
mlua = { version = "0.10.1", features = ["lua54", "vendored"] }
mlua = { version = "0.10", features = ["lua54", "vendored"] }
```
`main.rs`
@@ -168,7 +168,7 @@ Add to `Cargo.toml` :
crate-type = ["cdylib"]
[dependencies]
mlua = { version = "0.10.1", features = ["lua54", "module"] }
mlua = { version = "0.10", features = ["lua54", "module"] }
```
`lib.rs` :
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "mlua-sys"
version = "0.6.5"
version = "0.6.7"
authors = ["Aleksandr Orlenko <zxteam@pm.me>"]
rust-version = "1.71"
edition = "2021"
@@ -40,7 +40,7 @@ cfg-if = "1.0"
pkg-config = "0.3.17"
lua-src = { version = ">= 547.0.0, < 547.1.0", optional = true }
luajit-src = { version = ">= 210.5.0, < 210.6.0", optional = true }
luau0-src = { version = "0.11.1", optional = true }
luau0-src = { version = "0.12.0", optional = true }
[lints.rust]
unexpected_cfgs = { level = "allow", check-cfg = ['cfg(raw_dylib)'] }
+19 -9
View File
@@ -32,15 +32,19 @@ pub fn probe_lua() {
// Find using `pkg-config`
#[cfg(feature = "lua54")]
let (incl_bound, excl_bound, alt_probe, ver) = ("5.4", "5.5", Some("lua5.4"), "5.4");
let (incl_bound, excl_bound, alt_probe, ver) =
("5.4", "5.5", ["lua5.4", "lua-5.4", "lua54"], "5.4");
#[cfg(feature = "lua53")]
let (incl_bound, excl_bound, alt_probe, ver) = ("5.3", "5.4", Some("lua5.3"), "5.3");
let (incl_bound, excl_bound, alt_probe, ver) =
("5.3", "5.4", ["lua5.3", "lua-5.3", "lua53"], "5.3");
#[cfg(feature = "lua52")]
let (incl_bound, excl_bound, alt_probe, ver) = ("5.2", "5.3", Some("lua5.2"), "5.2");
let (incl_bound, excl_bound, alt_probe, ver) =
("5.2", "5.3", ["lua5.2", "lua-5.2", "lua52"], "5.2");
#[cfg(feature = "lua51")]
let (incl_bound, excl_bound, alt_probe, ver) = ("5.1", "5.2", Some("lua5.1"), "5.1");
let (incl_bound, excl_bound, alt_probe, ver) =
("5.1", "5.2", ["lua5.1", "lua-5.1", "lua51"], "5.1");
#[cfg(feature = "luajit")]
let (incl_bound, excl_bound, alt_probe, ver) = ("2.0.4", "2.2", None, "JIT");
let (incl_bound, excl_bound, alt_probe, ver) = ("2.0.4", "2.2", [], "JIT");
#[rustfmt::skip]
let mut lua = pkg_config::Config::new()
@@ -48,10 +52,16 @@ pub fn probe_lua() {
.cargo_metadata(true)
.probe(if cfg!(feature = "luajit") { "luajit" } else { "lua" });
if lua.is_err() && alt_probe.is_some() {
lua = pkg_config::Config::new()
.cargo_metadata(true)
.probe(alt_probe.unwrap());
if lua.is_err() {
for pkg in alt_probe {
lua = pkg_config::Config::new()
.cargo_metadata(true)
.probe(pkg);
if lua.is_ok() {
break;
}
}
}
lua.unwrap_or_else(|err| panic!("cannot find Lua{ver} using `pkg-config`: {err}"));
+13 -2
View File
@@ -326,12 +326,16 @@ pub unsafe fn luaL_loadbufferenv(
mut size: usize,
name: *const c_char,
mode: *const c_char,
env: c_int,
mut env: c_int,
) -> c_int {
extern "C" {
fn free(p: *mut c_void);
}
unsafe extern "C-unwind" fn data_dtor(data: *mut c_void) {
free(*(data as *mut *mut c_char) as *mut c_void);
}
let chunk_is_text = size == 0 || (*data as u8) >= b'\t';
if !mode.is_null() {
let modeb = CStr::from_ptr(mode).to_bytes();
@@ -345,9 +349,16 @@ pub unsafe fn luaL_loadbufferenv(
}
if chunk_is_text {
if env < 0 {
env -= 1;
}
let data_ud = lua_newuserdatadtor(L, mem::size_of::<*mut c_char>(), data_dtor) as *mut *mut c_char;
let data = luau_compile_(data, size, ptr::null_mut(), &mut size);
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;
free(data as *mut c_void);
lua_replace(L, -2); // replace data with the result
if !ok {
return LUA_ERRSYNTAX;
}
+51
View File
@@ -1,5 +1,6 @@
//! Contains definitions from `luacode.h`.
use std::marker::{PhantomData, PhantomPinned};
use std::os::raw::{c_char, c_int, c_void};
use std::{ptr, slice};
@@ -15,6 +16,10 @@ pub struct lua_CompileOptions {
pub vectorType: *const c_char,
pub mutableGlobals: *const *const c_char,
pub userdataTypes: *const *const c_char,
pub librariesWithKnownMembers: *const *const c_char,
pub libraryMemberTypeCallback: Option<lua_LibraryMemberTypeCallback>,
pub libraryMemberConstantCallback: Option<lua_LibraryMemberConstantCallback>,
pub disabledBuiltins: *const *const c_char,
}
impl Default for lua_CompileOptions {
@@ -29,10 +34,56 @@ impl Default for lua_CompileOptions {
vectorType: ptr::null(),
mutableGlobals: ptr::null(),
userdataTypes: ptr::null(),
librariesWithKnownMembers: ptr::null(),
libraryMemberTypeCallback: None,
libraryMemberConstantCallback: None,
disabledBuiltins: ptr::null(),
}
}
}
#[repr(C)]
pub struct lua_CompileConstant {
_data: [u8; 0],
_marker: PhantomData<(*mut u8, PhantomPinned)>,
}
/// Type table tags
#[doc(hidden)]
#[repr(i32)]
#[non_exhaustive]
pub enum luau_BytecodeType {
Nil = 0,
Boolean,
Number,
String,
Table,
Function,
Thread,
UserData,
Vector,
Buffer,
Any = 15,
}
pub type lua_LibraryMemberTypeCallback =
unsafe extern "C-unwind" fn(library: *const c_char, member: *const c_char) -> c_int;
pub type lua_LibraryMemberConstantCallback = unsafe extern "C-unwind" fn(
library: *const c_char,
member: *const c_char,
constant: *mut lua_CompileConstant,
);
extern "C" {
pub fn luau_set_compile_constant_nil(cons: *mut lua_CompileConstant);
pub fn luau_set_compile_constant_boolean(cons: *mut lua_CompileConstant, b: c_int);
pub fn luau_set_compile_constant_number(cons: *mut lua_CompileConstant, n: f64);
pub fn luau_set_compile_constant_vector(cons: *mut lua_CompileConstant, x: f32, y: f32, z: f32, w: f32);
pub fn luau_set_compile_constant_string(cons: *mut lua_CompileConstant, s: *const c_char, l: usize);
}
extern "C-unwind" {
#[link_name = "luau_compile"]
pub fn luau_compile_(
+3 -3
View File
@@ -1,6 +1,6 @@
[package]
name = "mlua_derive"
version = "0.10.0"
version = "0.10.1"
authors = ["Aleksandr Orlenko <zxteam@pm.me>"]
edition = "2021"
description = "Procedural macros for the mlua crate."
@@ -12,12 +12,12 @@ license = "MIT"
proc-macro = true
[features]
macros = ["proc-macro-error", "itertools", "regex", "once_cell"]
macros = ["proc-macro-error2", "itertools", "regex", "once_cell"]
[dependencies]
quote = "1.0"
proc-macro2 = { version = "1.0", features = ["span-locations"] }
proc-macro-error = { version = "1.0", optional = true }
proc-macro-error2 = { version = "2.0.1", optional = true }
syn = { version = "2.0", features = ["full"] }
itertools = { version = "0.13", optional = true }
regex = { version = "1.4", optional = true }
+1 -1
View File
@@ -7,7 +7,7 @@ use syn::{parse_macro_input, ItemFn, LitStr, Result};
#[cfg(feature = "macros")]
use {
crate::chunk::Chunk, proc_macro::TokenTree, proc_macro2::TokenStream as TokenStream2,
proc_macro_error::proc_macro_error,
proc_macro_error2::proc_macro_error,
};
#[derive(Default)]
+1 -1
View File
@@ -74,7 +74,7 @@ fn parse_pos(span: &Span) -> Option<(usize, usize)> {
fn fallback_span_pos(span: &Span) -> (Pos, Pos) {
let (start, end) = match parse_pos(span) {
Some(v) => v,
None => proc_macro_error::abort_call_site!("Cannot retrieve span information; please use nightly"),
None => proc_macro_error2::abort_call_site!("Cannot retrieve span information; please use nightly"),
};
(Pos::new(1, start), Pos::new(1, end))
}
+41 -1
View File
@@ -2,6 +2,8 @@ use std::borrow::Cow;
use std::collections::HashMap;
use std::ffi::CString;
use std::io::Result as IoResult;
use std::marker::PhantomData;
use std::panic::Location;
use std::path::{Path, PathBuf};
use std::string::String as StdString;
@@ -9,13 +11,16 @@ use crate::error::{Error, Result};
use crate::function::Function;
use crate::state::{Lua, WeakLua};
use crate::table::Table;
use crate::traits::{FromLuaMulti, IntoLuaMulti};
use crate::traits::{FromLuaMulti, IntoLua, IntoLuaMulti};
use crate::value::Value;
/// Trait for types [loadable by Lua] and convertible to a [`Chunk`]
///
/// [loadable by Lua]: https://www.lua.org/manual/5.4/manual.html#3.3.2
pub trait AsChunk<'a> {
/// Returns optional chunk name
///
/// See [`Chunk::set_name`] for possible name prefixes.
fn name(&self) -> Option<StdString> {
None
}
@@ -303,6 +308,11 @@ impl Compiler {
impl Chunk<'_> {
/// Sets the name of this chunk, which results in more informative error traces.
///
/// Possible name prefixes:
/// - `@` - 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 {
self.name = name.into();
self
@@ -561,3 +571,33 @@ impl Chunk<'_> {
buf
}
}
struct WrappedChunk<'a, T: AsChunk<'a>> {
chunk: T,
caller: &'static Location<'static>,
_marker: PhantomData<&'a T>,
}
impl<'a> Chunk<'a> {
/// Wraps a chunk of Lua code, returning an opaque type that implements [`IntoLua`] trait.
///
/// The resulted `IntoLua` implementation will convert the chunk into a Lua function without
/// executing it.
#[doc(hidden)]
#[track_caller]
pub fn wrap(chunk: impl AsChunk<'a> + 'a) -> impl IntoLua + 'a {
WrappedChunk {
chunk,
caller: Location::caller(),
_marker: PhantomData,
}
}
}
impl<'a, T: AsChunk<'a>> IntoLua for WrappedChunk<'a, T> {
fn into_lua(self, lua: &Lua) -> Result<Value> {
lua.load_with_location(self.chunk, self.caller)
.into_function()
.map(Value::Function)
}
}
+2 -2
View File
@@ -509,10 +509,10 @@ impl Function {
}
}
pub(crate) struct WrappedFunction(pub(crate) Callback);
struct WrappedFunction(pub(crate) Callback);
#[cfg(feature = "async")]
pub(crate) struct WrappedAsyncFunction(pub(crate) AsyncCallback);
struct WrappedAsyncFunction(pub(crate) AsyncCallback);
impl Function {
/// Wraps a Rust function or closure, returning an opaque type that implements [`IntoLua`]
+4 -4
View File
@@ -174,9 +174,9 @@ impl<'scope, 'env: 'scope> Scope<'scope, 'env> {
let ud_ptr = util::push_uninit_userdata::<UserDataStorage<T>>(state, protect)?;
// Push the metatable and register it with no TypeId
let mut registry = UserDataRegistry::new_unique(ud_ptr as *mut _);
let mut registry = UserDataRegistry::new_unique(self.lua.lua(), ud_ptr as *mut _);
T::register(&mut registry);
self.lua.push_userdata_metatable(registry)?;
self.lua.push_userdata_metatable(registry.into_raw())?;
let mt_ptr = ffi::lua_topointer(state, -1);
self.lua.register_userdata_metatable(mt_ptr, None);
@@ -222,9 +222,9 @@ impl<'scope, 'env: 'scope> Scope<'scope, 'env> {
let ud_ptr = util::push_uninit_userdata::<UserDataStorage<T>>(state, protect)?;
// Push the metatable and register it with no TypeId
let mut registry = UserDataRegistry::new_unique(ud_ptr as *mut _);
let mut registry = UserDataRegistry::new_unique(self.lua.lua(), ud_ptr as *mut _);
register(&mut registry);
self.lua.push_userdata_metatable(registry)?;
self.lua.push_userdata_metatable(registry.into_raw())?;
let mt_ptr = ffi::lua_topointer(state, -1);
self.lua.register_userdata_metatable(mt_ptr, None);
+14 -7
View File
@@ -1003,10 +1003,17 @@ impl Lua {
/// [`Chunk::exec`]: crate::Chunk::exec
#[track_caller]
pub fn load<'a>(&self, chunk: impl AsChunk<'a>) -> Chunk<'a> {
let caller = Location::caller();
self.load_with_location(chunk, Location::caller())
}
pub(crate) fn load_with_location<'a>(
&self,
chunk: impl AsChunk<'a>,
location: &'static Location<'static>,
) -> Chunk<'a> {
Chunk {
lua: self.weak(),
name: chunk.name().unwrap_or_else(|| caller.to_string()),
name: chunk.name().unwrap_or_else(|| location.to_string()),
env: chunk.environment(self),
mode: chunk.mode(),
source: chunk.source(),
@@ -1036,8 +1043,8 @@ impl Lua {
let state = lua.state();
unsafe {
if lua.unlikely_memory_error() {
crate::util::push_buffer(lua.ref_thread(), buf.as_ref(), false)?;
return Ok(Buffer(lua.pop_ref_thread()));
crate::util::push_buffer(state, buf.as_ref(), false)?;
return Ok(Buffer(lua.pop_ref()));
}
let _sg = StackGuard::new(state);
@@ -1306,7 +1313,7 @@ impl Lua {
/// This methods provides a way to add fields or methods to userdata objects of a type `T`.
pub fn register_userdata_type<T: 'static>(&self, f: impl FnOnce(&mut UserDataRegistry<T>)) -> Result<()> {
let type_id = TypeId::of::<T>();
let mut registry = UserDataRegistry::new(type_id);
let mut registry = UserDataRegistry::new(self, type_id);
f(&mut registry);
let lua = self.lock();
@@ -1316,8 +1323,8 @@ impl Lua {
ffi::luaL_unref(lua.state(), ffi::LUA_REGISTRYINDEX, table_id);
}
// Register the type
lua.create_userdata_metatable(registry)?;
// Add to "pending" registration map
((*lua.extra.get()).pending_userdata_reg).insert(type_id, registry.into_raw());
}
Ok(())
}
+7 -2
View File
@@ -13,6 +13,7 @@ use crate::error::Result;
use crate::state::RawLua;
use crate::stdlib::StdLib;
use crate::types::{AppData, ReentrantMutex, XRc};
use crate::userdata::RawUserDataRegistry;
use crate::util::{get_internal_metatable, push_internal_userdata, TypeKey, WrappedFailure};
#[cfg(any(feature = "luau", doc))]
@@ -26,7 +27,7 @@ use super::{Lua, WeakLua};
// Unique key to store `ExtraData` in the registry
static EXTRA_REGISTRY_KEY: u8 = 0;
const WRAPPED_FAILURE_POOL_SIZE: usize = 64;
const WRAPPED_FAILURE_POOL_DEFAULT_CAPACITY: usize = 64;
const REF_STACK_RESERVE: c_int = 1;
/// Data associated with the Lua state.
@@ -35,6 +36,7 @@ pub(crate) struct ExtraData {
pub(super) weak: MaybeUninit<WeakLua>,
pub(super) owned: bool,
pub(super) pending_userdata_reg: FxHashMap<TypeId, RawUserDataRegistry>,
pub(super) registered_userdata_t: FxHashMap<TypeId, c_int>,
pub(super) registered_userdata_mt: FxHashMap<*const c_void, Option<TypeId>>,
pub(super) last_checked_userdata_mt: (*const c_void, Option<TypeId>),
@@ -58,6 +60,7 @@ pub(crate) struct ExtraData {
// Pool of `WrappedFailure` enums in the ref thread (as userdata)
pub(super) wrapped_failure_pool: Vec<c_int>,
pub(super) wrapped_failure_top: usize,
// Pool of `Thread`s (coroutines) for async execution
#[cfg(feature = "async")]
pub(super) thread_pool: Vec<c_int>,
@@ -144,6 +147,7 @@ impl ExtraData {
lua: MaybeUninit::uninit(),
weak: MaybeUninit::uninit(),
owned,
pending_userdata_reg: FxHashMap::default(),
registered_userdata_t: FxHashMap::default(),
registered_userdata_mt: FxHashMap::default(),
last_checked_userdata_mt: (ptr::null(), None),
@@ -157,7 +161,8 @@ impl ExtraData {
ref_stack_size: ffi::LUA_MINSTACK - REF_STACK_RESERVE,
ref_stack_top: ffi::lua_gettop(ref_thread),
ref_free: Vec::new(),
wrapped_failure_pool: Vec::with_capacity(WRAPPED_FAILURE_POOL_SIZE),
wrapped_failure_pool: Vec::with_capacity(WRAPPED_FAILURE_POOL_DEFAULT_CAPACITY),
wrapped_failure_top: 0,
#[cfg(feature = "async")]
thread_pool: Vec::new(),
wrapped_failure_mt_ptr,
+75 -61
View File
@@ -22,12 +22,14 @@ use crate::types::{
AppDataRef, AppDataRefMut, Callback, CallbackUpvalue, DestructedUserdata, Integer, LightUserData,
MaybeSend, ReentrantMutex, RegistryKey, ValueRef, XRc,
};
use crate::userdata::{AnyUserData, MetaMethod, UserData, UserDataRegistry, UserDataStorage};
use crate::userdata::{
AnyUserData, MetaMethod, RawUserDataRegistry, UserData, UserDataRegistry, UserDataStorage,
};
use crate::util::{
assert_stack, check_stack, get_destructed_userdata_metatable, get_internal_userdata, get_main_state,
get_metatable_ptr, get_userdata, init_error_registry, init_internal_metatable, init_userdata_metatable,
pop_error, push_internal_userdata, push_string, push_table, rawset_field, safe_pcall, safe_xpcall,
short_type_name, take_userdata, StackGuard, WrappedFailure,
short_type_name, StackGuard, WrappedFailure,
};
use crate::value::{Nil, Value};
@@ -317,41 +319,60 @@ impl RawLua {
let state = self.state();
unsafe {
let _sg = StackGuard::new(state);
check_stack(state, 2)?;
check_stack(state, 3)?;
let mode_str = match mode {
let name = name.map(CStr::as_ptr).unwrap_or(ptr::null());
let mode = match mode {
Some(ChunkMode::Binary) => cstr!("b"),
Some(ChunkMode::Text) => cstr!("t"),
None => cstr!("bt"),
};
match ffi::luaL_loadbufferenv(
state,
source.as_ptr() as *const c_char,
source.len(),
name.map(|n| n.as_ptr()).unwrap_or_else(ptr::null),
mode_str,
match env {
Some(env) => {
self.push_ref(&env.0);
-1
}
_ => 0,
},
) {
ffi::LUA_OK => {
#[cfg(feature = "luau-jit")]
if (*self.extra.get()).enable_jit && ffi::luau_codegen_supported() != 0 {
ffi::luau_codegen_compile(state, -1);
}
Ok(Function(self.pop_ref()))
}
let status = if self.unlikely_memory_error() {
self.load_chunk_inner(state, name, env, mode, source)
} else {
// Luau and Lua 5.2 can trigger an exception during chunk loading
protect_lua!(state, 0, 1, |state| {
self.load_chunk_inner(state, name, env, mode, source)
})?
};
match status {
ffi::LUA_OK => Ok(Function(self.pop_ref())),
err => Err(pop_error(state, err)),
}
}
}
pub(crate) unsafe fn load_chunk_inner(
&self,
state: *mut ffi::lua_State,
name: *const c_char,
env: Option<&Table>,
mode: *const c_char,
source: &[u8],
) -> c_int {
let status = ffi::luaL_loadbufferenv(
state,
source.as_ptr() as *const c_char,
source.len(),
name,
mode,
match env {
Some(env) => {
self.push_ref(&env.0);
-1
}
_ => 0,
},
);
#[cfg(feature = "luau-jit")]
if status == ffi::LUA_OK {
if (*self.extra.get()).enable_jit && ffi::luau_codegen_supported() != 0 {
ffi::luau_codegen_compile(state, -1);
}
}
status
}
/// Sets a 'hook' function for a thread (coroutine).
#[cfg(not(feature = "luau"))]
pub(crate) unsafe fn set_thread_hook<F>(
@@ -411,8 +432,8 @@ impl RawLua {
pub(crate) unsafe fn create_string(&self, s: impl AsRef<[u8]>) -> Result<String> {
let state = self.state();
if self.unlikely_memory_error() {
push_string(self.ref_thread(), s.as_ref(), false)?;
return Ok(String(self.pop_ref_thread()));
push_string(state, s.as_ref(), false)?;
return Ok(String(self.pop_ref()));
}
let _sg = StackGuard::new(state);
@@ -423,12 +444,12 @@ impl RawLua {
/// See [`Lua::create_table_with_capacity`]
pub(crate) unsafe fn create_table_with_capacity(&self, narr: usize, nrec: usize) -> Result<Table> {
let state = self.state();
if self.unlikely_memory_error() {
push_table(self.ref_thread(), narr, nrec, false)?;
return Ok(Table(self.pop_ref_thread()));
push_table(state, narr, nrec, false)?;
return Ok(Table(self.pop_ref()));
}
let state = self.state();
let _sg = StackGuard::new(state);
check_stack(state, 3)?;
push_table(state, narr, nrec, true)?;
@@ -713,6 +734,10 @@ impl RawLua {
pub(crate) unsafe fn drop_ref(&self, vref: &ValueRef) {
let ref_thread = self.ref_thread();
mlua_debug_assert!(
ffi::lua_gettop(ref_thread) >= vref.index,
"GC finalizer is not allowed in ref_thread"
);
ffi::lua_pushnil(ref_thread);
ffi::lua_replace(ref_thread, vref.index);
(*self.extra.get()).ref_free.push(vref.index);
@@ -754,10 +779,10 @@ impl RawLua {
}
// Create a new metatable from `UserData` definition
let mut registry = UserDataRegistry::new(type_id);
let mut registry = UserDataRegistry::new(self.lua(), type_id);
T::register(&mut registry);
self.create_userdata_metatable(registry)
self.create_userdata_metatable(registry.into_raw())
})
}
@@ -772,8 +797,11 @@ impl RawLua {
return Ok(table_id as Integer);
}
// Create an empty metatable
let registry = UserDataRegistry::<T>::new(type_id);
// Check if metatable creation is pending or create an empty metatable otherwise
let registry = match (*self.extra.get()).pending_userdata_reg.remove(&type_id) {
Some(registry) => registry,
None => UserDataRegistry::<T>::new(self.lua(), type_id).into_raw(),
};
self.create_userdata_metatable(registry)
})
}
@@ -810,12 +838,9 @@ impl RawLua {
Ok(AnyUserData(self.pop_ref()))
}
pub(crate) unsafe fn create_userdata_metatable<T>(
&self,
registry: UserDataRegistry<T>,
) -> Result<Integer> {
pub(crate) unsafe fn create_userdata_metatable(&self, registry: RawUserDataRegistry) -> Result<Integer> {
let state = self.state();
let type_id = registry.type_id();
let type_id = registry.type_id;
self.push_userdata_metatable(registry)?;
@@ -832,7 +857,7 @@ impl RawLua {
Ok(id as Integer)
}
pub(crate) unsafe fn push_userdata_metatable<T>(&self, mut registry: UserDataRegistry<T>) -> Result<()> {
pub(crate) unsafe fn push_userdata_metatable(&self, mut registry: RawUserDataRegistry) -> Result<()> {
let state = self.state();
let mut stack_guard = StackGuard::new(state);
check_stack(state, 13)?;
@@ -852,14 +877,14 @@ impl RawLua {
rawset_field(state, -2, MetaMethod::validate(&k)?)?;
}
let mut has_name = false;
for (k, push_field) in registry.meta_fields {
for (k, v) in registry.meta_fields {
has_name = has_name || k == MetaMethod::Type;
push_field(self)?;
v?.push_into_stack(self)?;
rawset_field(state, -2, MetaMethod::validate(&k)?)?;
}
// Set `__name/__type` if not provided
if !has_name {
let type_name = short_type_name::<T>();
let type_name = registry.type_name;
push_string(state, type_name.as_bytes(), !self.unlikely_memory_error())?;
rawset_field(state, -2, MetaMethod::Type.name())?;
}
@@ -876,8 +901,8 @@ impl RawLua {
ffi::lua_pop(state, 1);
push_table(state, 0, fields_nrec, true)?;
}
for (k, push_field) in mem::take(&mut registry.fields) {
push_field(self)?;
for (k, v) in mem::take(&mut registry.fields) {
v?.push_into_stack(self)?;
rawset_field(state, -2, &k)?;
}
rawset_field(state, metatable_index, "__index")?;
@@ -897,12 +922,12 @@ impl RawLua {
self.push(self.create_callback(m)?)?;
rawset_field(state, -2, &k)?;
}
for (k, push_field) in registry.fields {
for (k, v) in registry.fields {
unsafe extern "C-unwind" fn return_field(state: *mut ffi::lua_State) -> c_int {
ffi::lua_pushvalue(state, ffi::lua_upvalueindex(1));
1
}
push_field(self)?;
v?.push_into_stack(self)?;
protect_lua!(state, 1, 1, fn(state) {
ffi::lua_pushcclosure(state, return_field, 1);
})?;
@@ -960,18 +985,7 @@ impl RawLua {
}
}
unsafe extern "C-unwind" fn userdata_destructor<T>(state: *mut ffi::lua_State) -> c_int {
let ud = get_userdata::<UserDataStorage<T>>(state, -1);
if !(*ud).is_borrowed() {
take_userdata::<UserDataStorage<T>>(state);
ffi::lua_pushboolean(state, 1);
} else {
ffi::lua_pushboolean(state, 0);
}
1
}
ffi::lua_pushcfunction(state, userdata_destructor::<T>);
ffi::lua_pushcfunction(state, registry.destructor);
rawset_field(state, metatable_index, "__gc")?;
init_userdata_metatable(
+23 -35
View File
@@ -7,8 +7,6 @@ use crate::error::{Error, Result};
use crate::state::{ExtraData, RawLua};
use crate::util::{self, get_internal_metatable, WrappedFailure};
const WRAPPED_FAILURE_POOL_SIZE: usize = 64;
pub(super) struct StateGuard<'a>(&'a RawLua, *mut ffi::lua_State);
impl<'a> StateGuard<'a> {
@@ -42,26 +40,27 @@ where
enum PreallocatedFailure {
New(*mut WrappedFailure),
Existing(i32),
Reserved,
}
impl PreallocatedFailure {
unsafe fn reserve(state: *mut ffi::lua_State, extra: *mut ExtraData) -> Self {
match (*extra).wrapped_failure_pool.pop() {
Some(index) => PreallocatedFailure::Existing(index),
None => {
// We need to check stack for Luau in case when callback is called from interrupt
// See https://github.com/Roblox/luau/issues/446 and mlua #142 and #153
#[cfg(feature = "luau")]
ffi::lua_rawcheckstack(state, 2);
// Place it to the beginning of the stack
let ud = WrappedFailure::new_userdata(state);
ffi::lua_insert(state, 1);
PreallocatedFailure::New(ud)
}
if (*extra).wrapped_failure_top > 0 {
(*extra).wrapped_failure_top -= 1;
return PreallocatedFailure::Reserved;
}
// We need to check stack for Luau in case when callback is called from interrupt
// See https://github.com/Roblox/luau/issues/446 and mlua #142 and #153
#[cfg(feature = "luau")]
ffi::lua_rawcheckstack(state, 2);
// Place it to the beginning of the stack
let ud = WrappedFailure::new_userdata(state);
ffi::lua_insert(state, 1);
PreallocatedFailure::New(ud)
}
#[cold]
unsafe fn r#use(&self, state: *mut ffi::lua_State, extra: *mut ExtraData) -> *mut WrappedFailure {
let ref_thread = (*extra).ref_thread;
match *self {
@@ -69,12 +68,12 @@ where
ffi::lua_settop(state, 1);
ud
}
PreallocatedFailure::Existing(index) => {
PreallocatedFailure::Reserved => {
let index = (*extra).wrapped_failure_pool.pop().unwrap();
ffi::lua_settop(state, 0);
#[cfg(feature = "luau")]
ffi::lua_rawcheckstack(state, 2);
ffi::lua_pushvalue(ref_thread, index);
ffi::lua_xmove(ref_thread, state, 1);
ffi::lua_xpush(ref_thread, state, index);
ffi::lua_pushnil(ref_thread);
ffi::lua_replace(ref_thread, index);
(*extra).ref_free.push(index);
@@ -87,24 +86,13 @@ where
let ref_thread = (*extra).ref_thread;
match self {
PreallocatedFailure::New(_) => {
if (*extra).wrapped_failure_pool.len() < WRAPPED_FAILURE_POOL_SIZE {
ffi::lua_rotate(state, 1, -1);
ffi::lua_xmove(state, ref_thread, 1);
let index = ref_stack_pop(extra);
(*extra).wrapped_failure_pool.push(index);
} else {
ffi::lua_remove(state, 1);
}
}
PreallocatedFailure::Existing(index) => {
if (*extra).wrapped_failure_pool.len() < WRAPPED_FAILURE_POOL_SIZE {
(*extra).wrapped_failure_pool.push(index);
} else {
ffi::lua_pushnil(ref_thread);
ffi::lua_replace(ref_thread, index);
(*extra).ref_free.push(index);
}
ffi::lua_rotate(state, 1, -1);
ffi::lua_xmove(state, ref_thread, 1);
let index = ref_stack_pop(extra);
(*extra).wrapped_failure_pool.push(index);
(*extra).wrapped_failure_top += 1;
}
PreallocatedFailure::Reserved => (*extra).wrapped_failure_top += 1,
}
}
}
+19
View File
@@ -7,7 +7,9 @@ use std::{cmp, fmt, slice, str};
use crate::error::{Error, Result};
use crate::state::Lua;
use crate::traits::IntoLua;
use crate::types::{LuaType, ValueRef};
use crate::value::Value;
#[cfg(feature = "serialize")]
use {
@@ -366,6 +368,23 @@ impl<'a> IntoIterator for BorrowedBytes<'a> {
}
}
struct WrappedString<T: AsRef<[u8]>>(T);
impl String {
/// Wraps bytes, returning an opaque type that implements [`IntoLua`] trait.
///
/// This function uses [`Lua::create_string`] under the hood.
pub fn wrap(data: impl AsRef<[u8]>) -> impl IntoLua {
WrappedString(data)
}
}
impl<T: AsRef<[u8]>> IntoLua for WrappedString<T> {
fn into_lua(self, lua: &Lua) -> Result<Value> {
lua.create_string(self.0).map(Value::String)
}
}
impl LuaType for String {
const TYPE_ID: c_int = ffi::LUA_TSTRING;
}
+18
View File
@@ -581,6 +581,24 @@ impl Table {
unsafe { ffi::lua_getreadonly(ref_thread, self.0.index) != 0 }
}
/// Controls `safeenv` attribute on the table.
///
/// This a special flag that activates some performance optimizations for environment tables.
/// In particular, it controls:
/// - Optimization of import resolution (cache values of constant keys).
/// - Fast-path for built-in iteration with pairs/ipairs.
/// - Fast-path for some built-in functions (fastcall).
///
/// For `safeenv` environments, monkey patching or modifying values may not work as expected.
///
/// Requires `feature = "luau"`
#[cfg(any(feature = "luau", doc))]
#[cfg_attr(docsrs, doc(cfg(feature = "luau")))]
pub fn set_safeenv(&self, enabled: bool) {
let lua = self.0.lua.lock();
unsafe { ffi::lua_setsafeenv(lua.ref_thread(), self.0.index, enabled as _) };
}
/// Converts this table to a generic C pointer.
///
/// Different tables will give different pointers.
+1 -1
View File
@@ -4,7 +4,7 @@ use std::os::raw::{c_int, c_void};
use crate::state::{RawLua, WeakLua};
/// A reference to a Lua (complex) value stored in the Lua auxiliary thread.
pub(crate) struct ValueRef {
pub struct ValueRef {
pub(crate) lua: WeakLua,
pub(crate) index: c_int,
pub(crate) drop: bool,
+2 -2
View File
@@ -27,8 +27,8 @@ use {
// Re-export for convenience
pub(crate) use cell::UserDataStorage;
pub use cell::{UserDataRef, UserDataRefMut};
pub(crate) use registry::UserDataProxy;
pub use registry::UserDataRegistry;
pub(crate) use registry::{RawUserDataRegistry, UserDataProxy};
/// Kinds of metamethods that can be overridden.
///
@@ -1073,7 +1073,7 @@ impl Serialize for AnyUserData {
}
}
pub(crate) struct WrappedUserdata<F: FnOnce(&Lua) -> Result<AnyUserData>>(F);
struct WrappedUserdata<F: FnOnce(&Lua) -> Result<AnyUserData>>(F);
impl AnyUserData {
/// Wraps any Rust type, returning an opaque type that implements [`IntoLua`] trait.
+107 -89
View File
@@ -7,7 +7,7 @@ use std::os::raw::c_void;
use std::string::String as StdString;
use crate::error::{Error, Result};
use crate::state::{Lua, RawLua};
use crate::state::{Lua, LuaGuard};
use crate::traits::{FromLua, FromLuaMulti, IntoLua, IntoLuaMulti};
use crate::types::{Callback, MaybeSend};
use crate::userdata::{AnyUserData, MetaMethod, UserData, UserDataFields, UserDataMethods, UserDataStorage};
@@ -26,12 +26,10 @@ use std::rc::Rc;
#[cfg(feature = "userdata-wrappers")]
use std::sync::{Arc, Mutex, RwLock};
type StaticFieldCallback = Box<dyn FnOnce(&RawLua) -> Result<()> + 'static>;
#[derive(Clone, Copy)]
enum UserDataTypeId {
Shared(TypeId),
Unique(usize),
Unique(*mut c_void),
#[cfg(all(feature = "userdata-wrappers", not(feature = "send")))]
Rc(TypeId),
@@ -51,11 +49,18 @@ enum UserDataTypeId {
/// Handle to registry for userdata methods and metamethods.
pub struct UserDataRegistry<T> {
lua: LuaGuard,
raw: RawUserDataRegistry,
ud_type_id: UserDataTypeId,
_type: PhantomData<T>,
}
pub(crate) struct RawUserDataRegistry {
// Fields
pub(crate) fields: Vec<(String, StaticFieldCallback)>,
pub(crate) fields: Vec<(String, Result<Value>)>,
pub(crate) field_getters: Vec<(String, Callback)>,
pub(crate) field_setters: Vec<(String, Callback)>,
pub(crate) meta_fields: Vec<(String, StaticFieldCallback)>,
pub(crate) meta_fields: Vec<(String, Result<Value>)>,
// Methods
pub(crate) methods: Vec<(String, Callback)>,
@@ -65,42 +70,15 @@ pub struct UserDataRegistry<T> {
#[cfg(feature = "async")]
pub(crate) async_meta_methods: Vec<(String, AsyncCallback)>,
type_id: UserDataTypeId,
_type: PhantomData<T>,
pub(crate) destructor: ffi::lua_CFunction,
pub(crate) type_id: Option<TypeId>,
pub(crate) type_name: StdString,
}
impl<T> UserDataRegistry<T> {
#[inline(always)]
pub(crate) fn new(type_id: TypeId) -> Self {
Self::with_type_id(UserDataTypeId::Shared(type_id))
}
#[inline(always)]
pub(crate) fn new_unique(ud_ptr: *mut c_void) -> Self {
Self::with_type_id(UserDataTypeId::Unique(ud_ptr as usize))
}
#[inline(always)]
fn with_type_id(type_id: UserDataTypeId) -> Self {
UserDataRegistry {
fields: Vec::new(),
field_getters: Vec::new(),
field_setters: Vec::new(),
meta_fields: Vec::new(),
methods: Vec::new(),
#[cfg(feature = "async")]
async_methods: Vec::new(),
meta_methods: Vec::new(),
#[cfg(feature = "async")]
async_meta_methods: Vec::new(),
type_id,
_type: PhantomData,
}
}
impl UserDataTypeId {
#[inline]
pub(crate) fn type_id(&self) -> Option<TypeId> {
match self.type_id {
pub(crate) fn type_id(self) -> Option<TypeId> {
match self {
UserDataTypeId::Shared(type_id) => Some(type_id),
UserDataTypeId::Unique(_) => None,
#[cfg(all(feature = "userdata-wrappers", not(feature = "send")))]
@@ -119,6 +97,47 @@ impl<T> UserDataRegistry<T> {
UserDataTypeId::ArcParkingLotRwLock(type_id) => Some(type_id),
}
}
}
#[cfg(feature = "send")]
unsafe impl Send for UserDataTypeId {}
impl<T> UserDataRegistry<T> {
#[inline(always)]
pub(crate) fn new(lua: &Lua, type_id: TypeId) -> Self {
Self::with_type_id(lua, UserDataTypeId::Shared(type_id))
}
#[inline(always)]
pub(crate) fn new_unique(lua: &Lua, ud_ptr: *mut c_void) -> Self {
Self::with_type_id(lua, UserDataTypeId::Unique(ud_ptr))
}
#[inline(always)]
fn with_type_id(lua: &Lua, ud_type_id: UserDataTypeId) -> Self {
let raw = RawUserDataRegistry {
fields: Vec::new(),
field_getters: Vec::new(),
field_setters: Vec::new(),
meta_fields: Vec::new(),
methods: Vec::new(),
#[cfg(feature = "async")]
async_methods: Vec::new(),
meta_methods: Vec::new(),
#[cfg(feature = "async")]
async_meta_methods: Vec::new(),
destructor: super::util::userdata_destructor::<T>,
type_id: ud_type_id.type_id(),
type_name: short_type_name::<T>(),
};
UserDataRegistry {
lua: lua.lock_arc(),
raw,
ud_type_id,
_type: PhantomData,
}
}
fn box_method<M, A, R>(&self, name: &str, method: M) -> Callback
where
@@ -133,7 +152,7 @@ impl<T> UserDataRegistry<T> {
};
}
let target_type_id = self.type_id;
let target_type_id = self.ud_type_id;
Box::new(move |rawlua, nargs| unsafe {
if nargs == 0 {
let err = Error::from_lua_conversion("missing argument", "userdata", None);
@@ -157,7 +176,7 @@ impl<T> UserDataRegistry<T> {
}
#[rustfmt::skip]
UserDataTypeId::Unique(target_ptr)
if get_userdata::<UserDataStorage<T>>(state, self_index) as usize == target_ptr =>
if get_userdata::<UserDataStorage<T>>(state, self_index) as *mut c_void == target_ptr =>
{
let ud = target_ptr as *mut UserDataStorage<T>;
try_self_arg!((*ud).try_borrow_scoped(|ud| {
@@ -260,7 +279,7 @@ impl<T> UserDataRegistry<T> {
}
let method = RefCell::new(method);
let target_type_id = self.type_id;
let target_type_id = self.ud_type_id;
Box::new(move |rawlua, nargs| unsafe {
let mut method = method.try_borrow_mut().map_err(|_| Error::RecursiveMutCallback)?;
if nargs == 0 {
@@ -285,7 +304,7 @@ impl<T> UserDataRegistry<T> {
}
#[rustfmt::skip]
UserDataTypeId::Unique(target_ptr)
if get_userdata::<UserDataStorage<T>>(state, self_index) as usize == target_ptr =>
if get_userdata::<UserDataStorage<T>>(state, self_index) as *mut c_void == target_ptr =>
{
let ud = target_ptr as *mut UserDataStorage<T>;
try_self_arg!((*ud).try_borrow_scoped_mut(|ud| {
@@ -514,6 +533,11 @@ impl<T> UserDataRegistry<T> {
}
value.into_lua(lua)
}
#[inline(always)]
pub(crate) fn into_raw(self) -> RawUserDataRegistry {
self.raw
}
}
// Returns function name for the type `T`, without the module path
@@ -527,10 +551,7 @@ impl<T> UserDataFields<T> for UserDataRegistry<T> {
V: IntoLua + 'static,
{
let name = name.to_string();
self.fields.push((
name,
Box::new(move |rawlua| unsafe { value.push_into_stack(rawlua) }),
));
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)
@@ -540,7 +561,7 @@ impl<T> UserDataFields<T> for UserDataRegistry<T> {
{
let name = name.to_string();
let callback = self.box_method(&name, move |lua, data, ()| method(lua, data));
self.field_getters.push((name, callback));
self.raw.field_getters.push((name, callback));
}
fn add_field_method_set<M, A>(&mut self, name: impl ToString, method: M)
@@ -550,7 +571,7 @@ impl<T> UserDataFields<T> for UserDataRegistry<T> {
{
let name = name.to_string();
let callback = self.box_method_mut(&name, method);
self.field_setters.push((name, callback));
self.raw.field_setters.push((name, callback));
}
fn add_field_function_get<F, R>(&mut self, name: impl ToString, function: F)
@@ -560,7 +581,7 @@ impl<T> UserDataFields<T> for UserDataRegistry<T> {
{
let name = name.to_string();
let callback = self.box_function(&name, function);
self.field_getters.push((name, callback));
self.raw.field_getters.push((name, callback));
}
fn add_field_function_set<F, A>(&mut self, name: impl ToString, mut function: F)
@@ -570,20 +591,17 @@ impl<T> UserDataFields<T> for UserDataRegistry<T> {
{
let name = name.to_string();
let callback = self.box_function_mut(&name, move |lua, (data, val)| function(lua, data, val));
self.field_setters.push((name, callback));
self.raw.field_setters.push((name, callback));
}
fn add_meta_field<V>(&mut self, name: impl ToString, value: V)
where
V: IntoLua + 'static,
{
let lua = self.lua.lua();
let name = name.to_string();
self.meta_fields.push((
name.clone(),
Box::new(move |rawlua| unsafe {
Self::check_meta_field(rawlua.lua(), &name, value)?.push_into_stack(rawlua)
}),
));
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)
@@ -591,14 +609,10 @@ impl<T> UserDataFields<T> for UserDataRegistry<T> {
F: FnOnce(&Lua) -> Result<R> + 'static,
R: IntoLua,
{
let lua = self.lua.lua();
let name = name.to_string();
self.meta_fields.push((
name.clone(),
Box::new(move |rawlua| unsafe {
let lua = rawlua.lua();
Self::check_meta_field(lua, &name, f(lua)?)?.push_into_stack(rawlua)
}),
));
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));
}
}
@@ -611,7 +625,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
{
let name = name.to_string();
let callback = self.box_method(&name, method);
self.methods.push((name, callback));
self.raw.methods.push((name, callback));
}
fn add_method_mut<M, A, R>(&mut self, name: impl ToString, method: M)
@@ -622,7 +636,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
{
let name = name.to_string();
let callback = self.box_method_mut(&name, method);
self.methods.push((name, callback));
self.raw.methods.push((name, callback));
}
#[cfg(feature = "async")]
@@ -636,7 +650,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
{
let name = name.to_string();
let callback = self.box_async_method(&name, method);
self.async_methods.push((name, callback));
self.raw.async_methods.push((name, callback));
}
#[cfg(feature = "async")]
@@ -650,7 +664,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
{
let name = name.to_string();
let callback = self.box_async_method_mut(&name, method);
self.async_methods.push((name, callback));
self.raw.async_methods.push((name, callback));
}
fn add_function<F, A, R>(&mut self, name: impl ToString, function: F)
@@ -661,7 +675,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
{
let name = name.to_string();
let callback = self.box_function(&name, function);
self.methods.push((name, callback));
self.raw.methods.push((name, callback));
}
fn add_function_mut<F, A, R>(&mut self, name: impl ToString, function: F)
@@ -672,7 +686,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
{
let name = name.to_string();
let callback = self.box_function_mut(&name, function);
self.methods.push((name, callback));
self.raw.methods.push((name, callback));
}
#[cfg(feature = "async")]
@@ -685,7 +699,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
{
let name = name.to_string();
let callback = self.box_async_function(&name, function);
self.async_methods.push((name, callback));
self.raw.async_methods.push((name, callback));
}
fn add_meta_method<M, A, R>(&mut self, name: impl ToString, method: M)
@@ -696,7 +710,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
{
let name = name.to_string();
let callback = self.box_method(&name, method);
self.meta_methods.push((name, callback));
self.raw.meta_methods.push((name, callback));
}
fn add_meta_method_mut<M, A, R>(&mut self, name: impl ToString, method: M)
@@ -707,7 +721,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
{
let name = name.to_string();
let callback = self.box_method_mut(&name, method);
self.meta_methods.push((name, callback));
self.raw.meta_methods.push((name, callback));
}
#[cfg(all(feature = "async", not(any(feature = "lua51", feature = "luau"))))]
@@ -721,7 +735,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
{
let name = name.to_string();
let callback = self.box_async_method(&name, method);
self.async_meta_methods.push((name, callback));
self.raw.async_meta_methods.push((name, callback));
}
#[cfg(all(feature = "async", not(any(feature = "lua51", feature = "luau"))))]
@@ -735,7 +749,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
{
let name = name.to_string();
let callback = self.box_async_method_mut(&name, method);
self.async_meta_methods.push((name, callback));
self.raw.async_meta_methods.push((name, callback));
}
fn add_meta_function<F, A, R>(&mut self, name: impl ToString, function: F)
@@ -746,7 +760,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
{
let name = name.to_string();
let callback = self.box_function(&name, function);
self.meta_methods.push((name, callback));
self.raw.meta_methods.push((name, callback));
}
fn add_meta_function_mut<F, A, R>(&mut self, name: impl ToString, function: F)
@@ -757,7 +771,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
{
let name = name.to_string();
let callback = self.box_function_mut(&name, function);
self.meta_methods.push((name, callback));
self.raw.meta_methods.push((name, callback));
}
#[cfg(all(feature = "async", not(any(feature = "lua51", feature = "luau"))))]
@@ -770,7 +784,7 @@ impl<T> UserDataMethods<T> for UserDataRegistry<T> {
{
let name = name.to_string();
let callback = self.box_async_function(&name, function);
self.async_meta_methods.push((name, callback));
self.raw.async_meta_methods.push((name, callback));
}
}
@@ -782,22 +796,20 @@ macro_rules! lua_userdata_impl {
($type:ty, $type_id:expr) => {
impl<T: UserData + 'static> UserData for $type {
fn register(registry: &mut UserDataRegistry<Self>) {
let mut orig_registry = UserDataRegistry::with_type_id($type_id);
let mut orig_registry = UserDataRegistry::with_type_id(registry.lua.lua(), $type_id);
T::register(&mut orig_registry);
// Copy all fields, methods, etc. from the original registry
registry.fields.extend(orig_registry.fields);
registry.field_getters.extend(orig_registry.field_getters);
registry.field_setters.extend(orig_registry.field_setters);
registry.meta_fields.extend(orig_registry.meta_fields);
registry.methods.extend(orig_registry.methods);
(registry.raw.fields).extend(orig_registry.raw.fields);
(registry.raw.field_getters).extend(orig_registry.raw.field_getters);
(registry.raw.field_setters).extend(orig_registry.raw.field_setters);
(registry.raw.meta_fields).extend(orig_registry.raw.meta_fields);
(registry.raw.methods).extend(orig_registry.raw.methods);
#[cfg(feature = "async")]
registry.async_methods.extend(orig_registry.async_methods);
registry.meta_methods.extend(orig_registry.meta_methods);
(registry.raw.async_methods).extend(orig_registry.raw.async_methods);
(registry.raw.meta_methods).extend(orig_registry.raw.meta_methods);
#[cfg(feature = "async")]
registry
.async_meta_methods
.extend(orig_registry.async_meta_methods);
(registry.raw.async_meta_methods).extend(orig_registry.raw.async_meta_methods);
}
}
};
@@ -822,3 +834,9 @@ lua_userdata_impl!(Arc<RwLock<T>> => ArcRwLock);
lua_userdata_impl!(Arc<parking_lot::Mutex<T>> => ArcParkingLotMutex);
#[cfg(feature = "userdata-wrappers")]
lua_userdata_impl!(Arc<parking_lot::RwLock<T>> => ArcParkingLotRwLock);
#[cfg(test)]
mod assertions {
#[cfg(feature = "send")]
static_assertions::assert_impl_all!(super::RawUserDataRegistry: Send);
}
+15
View File
@@ -1,5 +1,9 @@
use std::cell::Cell;
use std::marker::PhantomData;
use std::os::raw::c_int;
use super::UserDataStorage;
use crate::util::{get_userdata, take_userdata};
// This is a trick to check if a type is `Sync` or not.
// It uses leaked specialization feature from stdlib.
@@ -29,3 +33,14 @@ pub(crate) fn is_sync<T>() -> bool {
.clone();
is_sync.get()
}
pub(super) unsafe extern "C-unwind" fn userdata_destructor<T>(state: *mut ffi::lua_State) -> c_int {
let ud = get_userdata::<UserDataStorage<T>>(state, -1);
if !(*ud).is_borrowed() {
take_userdata::<UserDataStorage<T>>(state);
ffi::lua_pushboolean(state, 1);
} else {
ffi::lua_pushboolean(state, 0);
}
1
}
+56 -63
View File
@@ -1,4 +1,3 @@
use std::ffi::CStr;
use std::os::raw::{c_int, c_void};
use std::{ptr, str};
@@ -222,50 +221,47 @@ unsafe fn init_userdata_metatable_index(state: *mut ffi::lua_State) -> Result<()
ffi::lua_pop(state, 1);
// Create and cache `__index` generator
let code = cstr!(
r#"
local error, isfunction, istable = ...
return function (__index, field_getters, methods)
-- Common case: has field getters and index is a table
if field_getters ~= nil and methods == nil and istable(__index) then
return function (self, key)
local field_getter = field_getters[key]
if field_getter ~= nil then
return field_getter(self)
end
return __index[key]
end
end
let code = cr#"
local error, isfunction, istable = ...
return function (__index, field_getters, methods)
-- Common case: has field getters and index is a table
if field_getters ~= nil and methods == nil and istable(__index) then
return function (self, key)
if field_getters ~= nil then
local field_getter = field_getters[key]
if field_getter ~= nil then
return field_getter(self)
end
end
if methods ~= nil then
local method = methods[key]
if method ~= nil then
return method
end
end
if isfunction(__index) then
return __index(self, key)
elseif __index == nil then
error("attempt to get an unknown field '"..key.."'")
else
return __index[key]
local field_getter = field_getters[key]
if field_getter ~= nil then
return field_getter(self)
end
return __index[key]
end
end
"#
);
let code_len = CStr::from_ptr(code).to_bytes().len();
return function (self, key)
if field_getters ~= nil then
local field_getter = field_getters[key]
if field_getter ~= nil then
return field_getter(self)
end
end
if methods ~= nil then
local method = methods[key]
if method ~= nil then
return method
end
end
if isfunction(__index) then
return __index(self, key)
elseif __index == nil then
error("attempt to get an unknown field '"..key.."'")
else
return __index[key]
end
end
end
"#;
protect_lua!(state, 0, 1, |state| {
let ret = ffi::luaL_loadbuffer(state, code, code_len, cstr!("__mlua_index"));
let ret = ffi::luaL_loadbuffer(state, code.as_ptr(), code.count_bytes(), cstr!("__mlua_index"));
if ret != ffi::LUA_OK {
ffi::lua_error(state);
}
@@ -293,33 +289,30 @@ unsafe fn init_userdata_metatable_newindex(state: *mut ffi::lua_State) -> Result
ffi::lua_pop(state, 1);
// Create and cache `__newindex` generator
let code = cstr!(
r#"
local error, isfunction = ...
return function (__newindex, field_setters)
return function (self, key, value)
if field_setters ~= nil then
local field_setter = field_setters[key]
if field_setter ~= nil then
field_setter(self, value)
return
end
end
if isfunction(__newindex) then
__newindex(self, key, value)
elseif __newindex == nil then
error("attempt to set an unknown field '"..key.."'")
else
__newindex[key] = value
let code = cr#"
local error, isfunction = ...
return function (__newindex, field_setters)
return function (self, key, value)
if field_setters ~= nil then
local field_setter = field_setters[key]
if field_setter ~= nil then
field_setter(self, value)
return
end
end
if isfunction(__newindex) then
__newindex(self, key, value)
elseif __newindex == nil then
error("attempt to set an unknown field '"..key.."'")
else
__newindex[key] = value
end
end
"#
);
let code_len = CStr::from_ptr(code).to_bytes().len();
end
"#;
protect_lua!(state, 0, 1, |state| {
let ret = ffi::luaL_loadbuffer(state, code, code_len, cstr!("__mlua_newindex"));
let ret = ffi::luaL_loadbuffer(state, code.as_ptr(), code.count_bytes(), cstr!("__mlua_newindex"));
if ret != ffi::LUA_OK {
ffi::lua_error(state);
}
+7 -2
View File
@@ -67,8 +67,7 @@ pub enum Value {
/// `Error` is a special builtin userdata type. When received from Lua it is implicitly cloned.
Error(Box<Error>),
/// Any other value not known to mlua (eg. LuaJIT CData).
#[allow(private_interfaces)]
Other(ValueRef),
Other(#[doc(hidden)] ValueRef),
}
pub use self::Value::Nil;
@@ -570,6 +569,12 @@ impl Value {
}
}
impl Default for Value {
fn default() -> Self {
Self::Nil
}
}
impl fmt::Debug for Value {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
if fmt.alternate() {
+18 -1
View File
@@ -1,6 +1,6 @@
use std::{fs, io};
use mlua::{Lua, Result};
use mlua::{Chunk, Lua, Result};
#[test]
fn test_chunk_path() -> Result<()> {
@@ -121,3 +121,20 @@ fn test_compiler() -> Result<()> {
Ok(())
}
#[test]
fn test_chunk_wrap() -> Result<()> {
let lua = Lua::new();
let f = Chunk::wrap("return 123");
lua.globals().set("f", f)?;
lua.load("assert(f() == 123)").exec().unwrap();
lua.globals().set("f2", Chunk::wrap("c()"))?;
assert!(
(lua.load("f2()").exec().err().unwrap().to_string()).contains(file!()),
"wrong chunk location"
);
Ok(())
}
+12
View File
@@ -75,9 +75,21 @@ fn test_function_calls() -> Result<()> {
let output = output.lock().unwrap();
if cfg!(feature = "luajit") && lua.load("jit.version_num").eval::<i64>()? >= 20100 {
#[cfg(not(force_memory_limit))]
assert_eq!(*output, vec![(None, "main"), (Some("len".to_string()), "Lua")]);
#[cfg(force_memory_limit)]
assert_eq!(
*output,
vec![(None, "C"), (None, "main"), (Some("len".to_string()), "Lua")]
);
} else {
#[cfg(not(force_memory_limit))]
assert_eq!(*output, vec![(None, "main"), (Some("len".to_string()), "C")]);
#[cfg(force_memory_limit)]
assert_eq!(
*output,
vec![(None, "C"), (None, "main"), (Some("len".to_string()), "C")]
);
}
Ok(())
+14
View File
@@ -282,6 +282,20 @@ fn test_sandbox() -> Result<()> {
Ok(())
}
#[test]
fn test_sandbox_safeenv() -> Result<()> {
let lua = Lua::new();
lua.sandbox(true)?;
lua.globals().set("state", lua.create_table()?)?;
lua.globals().set_safeenv(false);
lua.load("state.a = 123").exec()?;
let a: i32 = lua.load("state.a = 321; return state.a").eval()?;
assert_eq!(a, 321);
Ok(())
}
#[test]
fn test_sandbox_nolibs() -> Result<()> {
let lua = Lua::new_with(StdLib::NONE, LuaOptions::default()).unwrap();
+10
View File
@@ -31,6 +31,16 @@ fn test_memory_limit() -> Result<()> {
lua.set_memory_limit(0)?;
f.call::<()>(()).expect("should trigger no memory limit");
// Test memory limit during chunk loading
lua.set_memory_limit(1024)?;
match lua
.load("local t = {}; for i = 1,10000 do t[i] = i end")
.into_function()
{
Err(Error::MemoryError(_)) => {}
_ => panic!("did not trigger memory error"),
};
Ok(())
}
+17 -2
View File
@@ -96,8 +96,8 @@ fn test_string_fmt_debug() -> Result<()> {
assert_eq!(format!("{:?}", s.as_bytes()), "[104, 101, 108, 108, 111]");
// Invalid utf8
let s = lua.create_string(b"hello\0world\r\n\t\xF0\x90\x80")?;
assert_eq!(format!("{s:?}"), r#"b"hello\0world\r\n\t\xF0\x90\x80""#);
let s = lua.create_string(b"hello\0world\r\n\t\xf0\x90\x80")?;
assert_eq!(format!("{s:?}"), r#"b"hello\0world\r\n\t\xf0\x90\x80""#);
Ok(())
}
@@ -128,3 +128,18 @@ fn test_string_display() -> Result<()> {
Ok(())
}
#[test]
fn test_string_wrap() -> Result<()> {
let lua = Lua::new();
let s = String::wrap("hello, world");
lua.globals().set("s", s)?;
assert_eq!(lua.globals().get::<String>("s")?, "hello, world");
let s2 = String::wrap("hello, world (owned)".to_string());
lua.globals().set("s2", s2)?;
assert_eq!(lua.globals().get::<String>("s2")?, "hello, world (owned)");
Ok(())
}
+18
View File
@@ -1377,3 +1377,21 @@ fn test_exec_raw() -> Result<()> {
Ok(())
}
#[test]
fn test_gc_drop_ref_thread() -> Result<()> {
let lua = Lua::new();
let t = lua.create_table()?;
lua.create_function(move |_, ()| {
_ = &t;
Ok(())
})?;
for _ in 0..10000 {
// GC will run eventually to collect the function and the table above
lua.create_table()?;
}
Ok(())
}
+22
View File
@@ -296,3 +296,25 @@ fn test_value_conversions() -> Result<()> {
Ok(())
}
#[test]
fn test_value_exhaustive_match() {
match Value::Nil {
Value::Nil => {}
Value::Boolean(_) => {}
Value::LightUserData(_) => {}
Value::Integer(_) => {}
Value::Number(_) => {}
#[cfg(feature = "luau")]
Value::Vector(_) => {}
Value::String(_) => {}
Value::Table(_) => {}
Value::Function(_) => {}
Value::Thread(_) => {}
Value::UserData(_) => {}
#[cfg(feature = "luau")]
Value::Buffer(_) => {}
Value::Error(_) => {}
Value::Other(_) => {}
}
}