diff --git a/README.md b/README.md index 46aa0260..cd50afbc 100644 --- a/README.md +++ b/README.md @@ -234,63 +234,6 @@ fn main() { } ``` -### Creating a Lua module - -**Note: OBSOLETE ; this is still some pre-Rust-1.0 stuff** - -This library also includes a second library named `rust-hl-lua-module` which allows you to create Lua modules in Rust. - -To use it, add this to `Cargo.toml`: - -```toml -[dependencies.rust-hl-lua-modules] -git = "https://github.com/tomaka/hlua" -``` - -Then you can use it like this: - -```rust -#![feature(phase)] -#[!plugin(rust-hl-lua-modules)] - -#[export_lua_module] -pub mod mylib { // <-- must be the name of the Lua module - static PI: f32 = 3.141592; - - fn function1(a: int, b: int) -> int { - a + b - } - - fn function2(a: int) -> int { - a + 5 - } - - #[lua_module_init] - fn init() { - println!("module initialized!") - } -} -``` - -This module will then be usable by Lua: - -```lua -> mylib = require("mylib") -module initialized! -> return mylib.function1(2, 4) -6 -> return mylib.PI -3.141592 -``` - -Two syntax extensions are defined: - - `#[export_lua_module]`: Must be put in front of a module. The name of the module must be the same as the name of your Lua module. - - `#[lua_module_init]`: Can be put in front of a function inside the module. This function will be executed when the module is loaded. - -**Restrictions**: - - `fail!()` will crash the program. - - If you spawn tasks, they will have to end before the hand is given back to lua. - ### Contributing Contributions are welcome! diff --git a/hlua/Cargo.toml b/hlua/Cargo.toml index 9083971b..984ddee6 100644 --- a/hlua/Cargo.toml +++ b/hlua/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "hlua" -version = "0.4.1" +version = "0.4.2" authors = [ "pierre.krieger1708@gmail.com" ] description = "Zero-cost high-level wrapper for Lua" keywords = ["lua"] diff --git a/hlua/examples/sound-api.rs b/hlua/examples/sound-api.rs index 8a6b865a..cb305464 100644 --- a/hlua/examples/sound-api.rs +++ b/hlua/examples/sound-api.rs @@ -13,7 +13,8 @@ fn main() { sound_namespace.set("new", hlua::function0(|| Sound::new())); } - lua.execute::<()>(r#" + lua.execute::<()>( + r#" s = Sound.new(); s:play(); @@ -23,8 +24,9 @@ fn main() { s:stop(); print("is the sound playing:", s:is_playing()); - "#) - .unwrap(); + "#, + ) + .unwrap(); } // this `Sound` struct is the object that we will use to demonstrate hlua @@ -43,8 +45,10 @@ implement_lua_push!(Sound, |mut metatable| { index.set("stop", hlua::function1(|snd: &mut Sound| snd.stop())); - index.set("is_playing", - hlua::function1(|snd: &Sound| snd.is_playing())); + index.set( + "is_playing", + hlua::function1(|snd: &Sound| snd.is_playing()), + ); }); // this macro implements the require traits so that we can *read* the object back diff --git a/hlua/src/any.rs b/hlua/src/any.rs index ec893d5c..96514f58 100644 --- a/hlua/src/any.rs +++ b/hlua/src/any.rs @@ -3,11 +3,11 @@ use ffi; use AsLua; use AsMutLua; +use LuaRead; +use LuaTable; use Push; use PushGuard; use PushOne; -use LuaRead; -use LuaTable; use Void; #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] @@ -44,9 +44,10 @@ pub enum AnyLuaValue { } impl<'lua, L> Push for AnyLuaValue - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { - type Err = Void; // TODO: use `!` instead (https://github.com/rust-lang/rust/issues/35121) + type Err = Void; // TODO: use `!` instead (https://github.com/rust-lang/rust/issues/35121) #[inline] fn push_to_lua(self, mut lua: L) -> Result, (Void, L)> { @@ -65,7 +66,9 @@ impl<'lua, L> Push for AnyLuaValue // We also need to destroy and recreate the push guard, otherwise the type parameter // doesn't match. - let size = val.push_no_err(&mut lua as &mut AsMutLua<'lua>).forget_internal(); + let size = val + .push_no_err(&mut lua as &mut AsMutLua<'lua>) + .forget_internal(); Ok(PushGuard { lua: lua, @@ -91,21 +94,21 @@ impl<'lua, L> Push for AnyLuaValue impl<'lua, L> PushOne for AnyLuaValue where L: AsMutLua<'lua> {} impl<'lua, L> LuaRead for AnyLuaValue - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { #[inline] fn lua_read_at_position(mut lua: L, index: i32) -> Result { - // If we know that the value on the stack is a string, we should try // to parse it as a string instead of a number or boolean, so that // values such as '1.10' don't become `AnyLuaValue::LuaNumber(1.1)`. let data_type = unsafe { ffi::lua_type(lua.as_lua().0, index) }; if data_type == ffi::LUA_TSTRING { - - let mut lua = match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { - Ok(v) => return Ok(AnyLuaValue::LuaString(v)), - Err(lua) => lua, - }; + let mut lua = + match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { + Ok(v) => return Ok(AnyLuaValue::LuaString(v)), + Err(lua) => lua, + }; let _lua = match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { Ok(v) => return Ok(AnyLuaValue::LuaAnyString(v)), @@ -113,23 +116,24 @@ impl<'lua, L> LuaRead for AnyLuaValue }; Ok(AnyLuaValue::LuaOther) - } else { - - let mut lua = match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { - Ok(v) => return Ok(AnyLuaValue::LuaNumber(v)), - Err(lua) => lua, - }; - - let mut lua = match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { - Ok(v) => return Ok(AnyLuaValue::LuaBoolean(v)), - Err(lua) => lua, - }; - - let mut lua = match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { - Ok(v) => return Ok(AnyLuaValue::LuaString(v)), - Err(lua) => lua, - }; + let mut lua = + match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { + Ok(v) => return Ok(AnyLuaValue::LuaNumber(v)), + Err(lua) => lua, + }; + + let mut lua = + match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { + Ok(v) => return Ok(AnyLuaValue::LuaBoolean(v)), + Err(lua) => lua, + }; + + let mut lua = + match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { + Ok(v) => return Ok(AnyLuaValue::LuaString(v)), + Err(lua) => lua, + }; let lua = match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { Ok(v) => return Ok(AnyLuaValue::LuaAnyString(v)), @@ -142,8 +146,13 @@ impl<'lua, L> LuaRead for AnyLuaValue let table: Result, _> = LuaRead::lua_read_at_position(lua, index); let _lua = match table { - Ok(mut v) => return Ok(AnyLuaValue::LuaArray(v.iter::() - .filter_map(|e| e).collect())), + Ok(mut v) => { + return Ok(AnyLuaValue::LuaArray( + v.iter::() + .filter_map(|e| e) + .collect(), + )) + } Err(lua) => lua, }; @@ -153,9 +162,10 @@ impl<'lua, L> LuaRead for AnyLuaValue } impl<'lua, L> Push for AnyHashableLuaValue - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { - type Err = Void; // TODO: use `!` instead (https://github.com/rust-lang/rust/issues/35121) + type Err = Void; // TODO: use `!` instead (https://github.com/rust-lang/rust/issues/35121) #[inline] fn push_to_lua(self, mut lua: L) -> Result, (Void, L)> { @@ -174,7 +184,9 @@ impl<'lua, L> Push for AnyHashableLuaValue // We also need to destroy and recreate the push guard, otherwise the type parameter // doesn't match. - let size = val.push_no_err(&mut lua as &mut AsMutLua<'lua>).forget_internal(); + let size = val + .push_no_err(&mut lua as &mut AsMutLua<'lua>) + .forget_internal(); Ok(PushGuard { lua: lua, @@ -192,7 +204,9 @@ impl<'lua, L> Push for AnyHashableLuaValue raw_lua: raw_lua, }) } // Use ffi::lua_pushnil. - AnyHashableLuaValue::LuaOther => panic!("can't push a AnyHashableLuaValue of type Other"), + AnyHashableLuaValue::LuaOther => { + panic!("can't push a AnyHashableLuaValue of type Other") + } } } } @@ -200,56 +214,64 @@ impl<'lua, L> Push for AnyHashableLuaValue impl<'lua, L> PushOne for AnyHashableLuaValue where L: AsMutLua<'lua> {} impl<'lua, L> LuaRead for AnyHashableLuaValue - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { #[inline] fn lua_read_at_position(mut lua: L, index: i32) -> Result { let data_type = unsafe { ffi::lua_type(lua.as_lua().0, index) }; if data_type == ffi::LUA_TSTRING { - - let mut lua = match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { - Ok(v) => return Ok(AnyHashableLuaValue::LuaString(v)), - Err(lua) => lua, - }; + let mut lua = + match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { + Ok(v) => return Ok(AnyHashableLuaValue::LuaString(v)), + Err(lua) => lua, + }; let _lua = match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { Ok(v) => return Ok(AnyHashableLuaValue::LuaAnyString(v)), Err(lua) => lua, }; - - Ok(AnyHashableLuaValue::LuaOther) + Ok(AnyHashableLuaValue::LuaOther) } else { - - let mut lua = match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { - Ok(v) => return Ok(AnyHashableLuaValue::LuaNumber(v)), - Err(lua) => lua, - }; - - let mut lua = match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { - Ok(v) => return Ok(AnyHashableLuaValue::LuaBoolean(v)), - Err(lua) => lua, - }; - - let mut lua = match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { - Ok(v) => return Ok(AnyHashableLuaValue::LuaString(v)), - Err(lua) => lua, - }; - - let mut lua = match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { - Ok(v) => return Ok(AnyHashableLuaValue::LuaAnyString(v)), - Err(lua) => lua, - }; + let mut lua = + match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { + Ok(v) => return Ok(AnyHashableLuaValue::LuaNumber(v)), + Err(lua) => lua, + }; + + let mut lua = + match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { + Ok(v) => return Ok(AnyHashableLuaValue::LuaBoolean(v)), + Err(lua) => lua, + }; + + let mut lua = + match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { + Ok(v) => return Ok(AnyHashableLuaValue::LuaString(v)), + Err(lua) => lua, + }; + + let mut lua = + match LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index) { + Ok(v) => return Ok(AnyHashableLuaValue::LuaAnyString(v)), + Err(lua) => lua, + }; if unsafe { ffi::lua_isnil(lua.as_lua().0, index) } { return Ok(AnyHashableLuaValue::LuaNil); } - let table: Result, _> = LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index); + let table: Result, _> = + LuaRead::lua_read_at_position(&mut lua as &mut AsMutLua<'lua>, index); let _lua = match table { - Ok(mut v) => return Ok(AnyHashableLuaValue::LuaArray(v - .iter::() - .filter_map(|e| e).collect())), + Ok(mut v) => { + return Ok(AnyHashableLuaValue::LuaArray( + v.iter::() + .filter_map(|e| e) + .collect(), + )) + } Err(lua) => lua, }; @@ -260,10 +282,10 @@ impl<'lua, L> LuaRead for AnyHashableLuaValue #[cfg(test)] mod tests { - use Lua; - use AnyLuaValue; use AnyHashableLuaValue; use AnyLuaString; + use AnyLuaValue; + use Lua; #[test] fn read_numbers() { @@ -368,20 +390,26 @@ mod tests { #[test] fn read_tables() { let mut lua = Lua::new(); - lua.execute::<()>(" + lua.execute::<()>( + " a = {x = 12, y = 19} b = {z = a, w = 'test string'} c = {'first', 'second'} - ").unwrap(); + ", + ) + .unwrap(); fn get<'a>(table: &'a AnyLuaValue, key: &str) -> &'a AnyLuaValue { let test_key = AnyLuaValue::LuaString(key.to_owned()); match table { &AnyLuaValue::LuaArray(ref vec) => { - let &(_, ref value) = vec.iter().find(|&&(ref key, _)| key == &test_key).expect("key not found"); + let &(_, ref value) = vec + .iter() + .find(|&&(ref key, _)| key == &test_key) + .expect("key not found"); value - }, - _ => panic!("not a table") + } + _ => panic!("not a table"), } } @@ -389,10 +417,13 @@ mod tests { let test_key = AnyLuaValue::LuaNumber(key as f64); match table { &AnyLuaValue::LuaArray(ref vec) => { - let &(_, ref value) = vec.iter().find(|&&(ref key, _)| key == &test_key).expect("key not found"); + let &(_, ref value) = vec + .iter() + .find(|&&(ref key, _)| key == &test_key) + .expect("key not found"); value - }, - _ => panic!("not a table") + } + _ => panic!("not a table"), } } @@ -405,27 +436,39 @@ mod tests { assert_eq!(get(&get(&b, "z"), "y"), get(&a, "y")); let c: AnyLuaValue = lua.get("c").unwrap(); - assert_eq!(get_numeric(&c, 1), &AnyLuaValue::LuaString("first".to_owned())); - assert_eq!(get_numeric(&c, 2), &AnyLuaValue::LuaString("second".to_owned())); + assert_eq!( + get_numeric(&c, 1), + &AnyLuaValue::LuaString("first".to_owned()) + ); + assert_eq!( + get_numeric(&c, 2), + &AnyLuaValue::LuaString("second".to_owned()) + ); } #[test] fn read_hashable_tables() { let mut lua = Lua::new(); - lua.execute::<()>(" + lua.execute::<()>( + " a = {x = 12, y = 19} b = {z = a, w = 'test string'} c = {'first', 'second'} - ").unwrap(); + ", + ) + .unwrap(); fn get<'a>(table: &'a AnyHashableLuaValue, key: &str) -> &'a AnyHashableLuaValue { let test_key = AnyHashableLuaValue::LuaString(key.to_owned()); match table { &AnyHashableLuaValue::LuaArray(ref vec) => { - let &(_, ref value) = vec.iter().find(|&&(ref key, _)| key == &test_key).expect("key not found"); + let &(_, ref value) = vec + .iter() + .find(|&&(ref key, _)| key == &test_key) + .expect("key not found"); value - }, - _ => panic!("not a table") + } + _ => panic!("not a table"), } } @@ -433,10 +476,13 @@ mod tests { let test_key = AnyHashableLuaValue::LuaNumber(key as i32); match table { &AnyHashableLuaValue::LuaArray(ref vec) => { - let &(_, ref value) = vec.iter().find(|&&(ref key, _)| key == &test_key).expect("key not found"); + let &(_, ref value) = vec + .iter() + .find(|&&(ref key, _)| key == &test_key) + .expect("key not found"); value - }, - _ => panic!("not a table") + } + _ => panic!("not a table"), } } @@ -449,8 +495,14 @@ mod tests { assert_eq!(get(&get(&b, "z"), "y"), get(&a, "y")); let c: AnyHashableLuaValue = lua.get("c").unwrap(); - assert_eq!(get_numeric(&c, 1), &AnyHashableLuaValue::LuaString("first".to_owned())); - assert_eq!(get_numeric(&c, 2), &AnyHashableLuaValue::LuaString("second".to_owned())); + assert_eq!( + get_numeric(&c, 1), + &AnyHashableLuaValue::LuaString("first".to_owned()) + ); + assert_eq!( + get_numeric(&c, 2), + &AnyHashableLuaValue::LuaString("second".to_owned()) + ); } #[test] @@ -520,9 +572,11 @@ mod tests { lua.set("a", AnyLuaValue::LuaNil); let x: Option = lua.get("a"); - assert!(x.is_none(), - "x is a Some value when it should be a None value. X: {:?}", - x); + assert!( + x.is_none(), + "x is a Some value when it should be a None value. X: {:?}", + x + ); } #[test] @@ -532,19 +586,23 @@ mod tests { lua.set("a", AnyHashableLuaValue::LuaNil); let x: Option = lua.get("a"); - assert!(x.is_none(), - "x is a Some value when it should be a None value. X: {:?}", - x); + assert!( + x.is_none(), + "x is a Some value when it should be a None value. X: {:?}", + x + ); } #[test] fn non_utf_8_string() { let mut lua = Lua::new(); - let a = lua.execute::(r"return '\xff\xfe\xff\xfe'").unwrap(); + let a = lua + .execute::(r"return '\xff\xfe\xff\xfe'") + .unwrap(); match a { AnyLuaValue::LuaAnyString(AnyLuaString(v)) => { assert_eq!(Vec::from(&b"\xff\xfe\xff\xfe"[..]), v); - }, + } _ => panic!("Decoded to wrong variant"), } } diff --git a/hlua/src/functions_write.rs b/hlua/src/functions_write.rs index 1e42e289..d9b4fdd1 100644 --- a/hlua/src/functions_write.rs +++ b/hlua/src/functions_write.rs @@ -11,8 +11,8 @@ use PushGuard; use PushOne; use Void; -use std::marker::PhantomData; use std::fmt::Display; +use std::marker::PhantomData; use std::mem; use std::ptr; @@ -359,45 +359,54 @@ unsafe impl<'a, 'lua> AsMutLua<'lua> for &'a mut InsideCallback { } impl<'a, T, E, P> Push<&'a mut InsideCallback> for Result - where T: Push<&'a mut InsideCallback, Err = P> + for<'b> Push<&'b mut &'a mut InsideCallback, Err = P>, - E: Display +where + T: Push<&'a mut InsideCallback, Err = P> + + for<'b> Push<&'b mut &'a mut InsideCallback, Err = P>, + E: Display, { type Err = P; #[inline] - fn push_to_lua(self, lua: &'a mut InsideCallback) -> Result, (P, &'a mut InsideCallback)> { + fn push_to_lua( + self, + lua: &'a mut InsideCallback, + ) -> Result, (P, &'a mut InsideCallback)> { match self { Ok(val) => val.push_to_lua(lua), - Err(val) => { - Ok((AnyLuaValue::LuaNil, format!("{}", val)).push_no_err(lua)) - } + Err(val) => Ok((AnyLuaValue::LuaNil, format!("{}", val)).push_no_err(lua)), } } } impl<'a, T, E, P> PushOne<&'a mut InsideCallback> for Result - where T: PushOne<&'a mut InsideCallback, Err = P> + for<'b> PushOne<&'b mut &'a mut InsideCallback, Err = P>, - E: Display +where + T: PushOne<&'a mut InsideCallback, Err = P> + + for<'b> PushOne<&'b mut &'a mut InsideCallback, Err = P>, + E: Display, { } // this function is called when Lua wants to call one of our functions #[inline] extern "C" fn wrapper(lua: *mut ffi::lua_State) -> libc::c_int - where T: FunctionExt, - P: for<'p> LuaRead<&'p mut InsideCallback> + 'static, - R: for<'p> Push<&'p mut InsideCallback> +where + T: FunctionExt, + P: for<'p> LuaRead<&'p mut InsideCallback> + 'static, + R: for<'p> Push<&'p mut InsideCallback>, { // loading the object that we want to call from the Lua context let data_raw = unsafe { ffi::lua_touserdata(lua, ffi::lua_upvalueindex(1)) }; let data: &mut T = unsafe { mem::transmute(data_raw) }; // creating a temporary Lua context in order to pass it to push & read functions - let mut tmp_lua = InsideCallback { lua: LuaContext(lua) }; + let mut tmp_lua = InsideCallback { + lua: LuaContext(lua), + }; // trying to read the arguments let arguments_count = unsafe { ffi::lua_gettop(lua) } as i32; - let args = match LuaRead::lua_read_at_position(&mut tmp_lua, -arguments_count as libc::c_int) { // TODO: what if the user has the wrong params? + let args = match LuaRead::lua_read_at_position(&mut tmp_lua, -arguments_count as libc::c_int) { + // TODO: what if the user has the wrong params? Err(_) => { let err_msg = format!("wrong parameter types for callback function"); match err_msg.push_to_lua(&mut tmp_lua) { @@ -417,18 +426,18 @@ extern "C" fn wrapper(lua: *mut ffi::lua_State) -> libc::c_int // pushing back the result of the function on the stack let nb = match ret_value.push_to_lua(&mut tmp_lua) { Ok(p) => p.forget_internal(), - Err(_) => panic!(), // TODO: wrong + Err(_) => panic!(), // TODO: wrong }; nb as libc::c_int } #[cfg(test)] mod tests { - use Lua; - use LuaError; use function0; use function1; use function2; + use Lua; + use LuaError; use std::sync::Arc; @@ -496,11 +505,13 @@ mod tests { }; lua.set("always_fails", function0(always_fails)); - match lua.execute::<()>(r#" + match lua.execute::<()>( + r#" local res, err = always_fails(); assert(res == nil); assert(err == "oops, problem"); - "#) { + "#, + ) { Ok(()) => {} Err(e) => panic!("{:?}", e), } @@ -523,7 +534,8 @@ mod tests { #[test] fn closures_lifetime() { fn t(f: F) - where F: Fn(i32, i32) -> i32 + where + F: Fn(i32, i32) -> i32, { let mut lua = Lua::new(); @@ -557,7 +569,7 @@ mod tests { static mut DID_DESTRUCTOR_RUN: bool = false; #[derive(Debug)] - struct Foo { }; + struct Foo {}; impl Drop for Foo { fn drop(&mut self) { unsafe { @@ -566,7 +578,7 @@ mod tests { } } { - let foo = Arc::new(Foo { }); + let foo = Arc::new(Foo {}); { let mut lua = Lua::new(); diff --git a/hlua/src/lib.rs b/hlua/src/lib.rs index 7ac9d9d5..8b313ed5 100644 --- a/hlua/src/lib.rs +++ b/hlua/src/lib.rs @@ -107,24 +107,24 @@ // Export the version of lua52_sys in use by this crate. This allows clients to perform low-level // Lua operations without worrying about semver. +extern crate libc; #[doc(hidden)] pub extern crate lua52_sys as ffi; -extern crate libc; -use std::ffi::{CStr, CString}; -use std::io::Read; -use std::io::Error as IoError; use std::borrow::Borrow; -use std::marker::PhantomData; +use std::convert::From; use std::error::Error; +use std::ffi::{CStr, CString}; use std::fmt; -use std::convert::From; use std::io; +use std::io::Error as IoError; +use std::io::Read; +use std::marker::PhantomData; pub use any::{AnyHashableLuaValue, AnyLuaString, AnyLuaValue}; -pub use functions_write::{Function, InsideCallback}; pub use functions_write::{function0, function1, function2, function3, function4, function5}; -pub use functions_write::{function6, function7, function8, function9, function10}; +pub use functions_write::{function10, function6, function7, function8, function9}; +pub use functions_write::{Function, InsideCallback}; pub use lua_functions::LuaFunction; pub use lua_functions::LuaFunctionCallError; pub use lua_functions::{LuaCode, LuaCodeFromReader}; @@ -141,9 +141,9 @@ mod lua_functions; mod lua_tables; mod macros; mod rust_tables; +mod tuples; mod userdata; mod values; -mod tuples; /// Main object of the library. /// @@ -173,7 +173,8 @@ pub struct PushGuard { } impl<'lua, L> PushGuard - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { /// Creates a new `PushGuard` from this Lua context representing `size` items on the stack. /// When this `PushGuard` is destroyed, `size` items will be popped. @@ -182,11 +183,7 @@ impl<'lua, L> PushGuard #[inline] pub unsafe fn new(mut lua: L, size: i32) -> Self { let raw_lua = lua.as_mut_lua(); - PushGuard { - lua, - size, - raw_lua, - } + PushGuard { lua, size, raw_lua } } #[inline] @@ -291,7 +288,8 @@ unsafe impl<'lua> AsMutLua<'lua> for Lua<'lua> { } unsafe impl<'lua, L> AsLua<'lua> for PushGuard - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { #[inline] fn as_lua(&self) -> LuaContext { @@ -300,7 +298,8 @@ unsafe impl<'lua, L> AsLua<'lua> for PushGuard } unsafe impl<'lua, L> AsMutLua<'lua> for PushGuard - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { #[inline] fn as_mut_lua(&mut self) -> LuaContext { @@ -309,7 +308,8 @@ unsafe impl<'lua, L> AsMutLua<'lua> for PushGuard } unsafe impl<'a, 'lua, L: ?Sized> AsLua<'lua> for &'a L - where L: AsLua<'lua> +where + L: AsLua<'lua>, { #[inline] fn as_lua(&self) -> LuaContext { @@ -318,7 +318,8 @@ unsafe impl<'a, 'lua, L: ?Sized> AsLua<'lua> for &'a L } unsafe impl<'a, 'lua, L: ?Sized> AsLua<'lua> for &'a mut L - where L: AsLua<'lua> +where + L: AsLua<'lua>, { #[inline] fn as_lua(&self) -> LuaContext { @@ -327,7 +328,8 @@ unsafe impl<'a, 'lua, L: ?Sized> AsLua<'lua> for &'a mut L } unsafe impl<'a, 'lua, L: ?Sized> AsMutLua<'lua> for &'a mut L - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { #[inline] fn as_mut_lua(&mut self) -> LuaContext { @@ -354,9 +356,10 @@ pub trait Push { // TODO: when https://github.com/rust-lang/rust/issues/20041 is fixed, use `Self::Err == Void` #[inline] fn push_no_err(self, lua: L) -> PushGuard - where Self: Sized, - Self: Push, - E: Into, + where + Self: Sized, + Self: Push, + E: Into, { match self.push_to_lua(lua) { Ok(p) => p, @@ -491,11 +494,12 @@ impl<'lua> Lua<'lua> { } // this alloc function is required to create a lua state. - extern "C" fn alloc(_ud: *mut libc::c_void, - ptr: *mut libc::c_void, - _osize: libc::size_t, - nsize: libc::size_t) - -> *mut libc::c_void { + extern "C" fn alloc( + _ud: *mut libc::c_void, + ptr: *mut libc::c_void, + _osize: libc::size_t, + nsize: libc::size_t, + ) -> *mut libc::c_void { unsafe { if nsize == 0 { libc::free(ptr as *mut libc::c_void); @@ -674,7 +678,8 @@ impl<'lua> Lua<'lua> { /// ``` #[inline] pub fn execute<'a, T>(&'a mut self, code: &str) -> Result - where T: for<'g> LuaRead>>> + where + T: for<'g> LuaRead>>>, { let mut f = try!(lua_functions::LuaFunction::load(self, code)); f.call() @@ -701,8 +706,9 @@ impl<'lua> Lua<'lua> { /// ``` #[inline] pub fn execute_from_reader<'a, T, R>(&'a mut self, code: R) -> Result - where T: for<'g> LuaRead>>>, - R: Read + where + T: for<'g> LuaRead>>>, + R: Read, { let mut f = try!(lua_functions::LuaFunction::load_from_reader(self, code)); f.call() @@ -727,8 +733,9 @@ impl<'lua> Lua<'lua> { /// ``` #[inline] pub fn get<'l, V, I>(&'l mut self, index: I) -> Option - where I: Borrow, - V: LuaRead>> + where + I: Borrow, + V: LuaRead>>, { let index = CString::new(index.borrow()).unwrap(); unsafe { @@ -755,8 +762,9 @@ impl<'lua> Lua<'lua> { /// Reads the value of a global, capturing the context by value. #[inline] pub fn into_get(self, index: I) -> Result> - where I: Borrow, - V: LuaRead>> + where + I: Borrow, + V: LuaRead>>, { let index = CString::new(index.borrow()).unwrap(); unsafe { @@ -797,9 +805,10 @@ impl<'lua> Lua<'lua> { /// ``` #[inline] pub fn set(&mut self, index: I, value: V) - where I: Borrow, - for<'a> V: PushOne<&'a mut Lua<'lua>, Err = E>, - E: Into, + where + I: Borrow, + for<'a> V: PushOne<&'a mut Lua<'lua>, Err = E>, + E: Into, { match self.checked_set(index, value) { Ok(_) => (), @@ -811,8 +820,9 @@ impl<'lua> Lua<'lua> { // TODO: docs #[inline] pub fn checked_set(&mut self, index: I, value: V) -> Result<(), E> - where I: Borrow, - for<'a> V: PushOne<&'a mut Lua<'lua>, Err = E> + where + I: Borrow, + for<'a> V: PushOne<&'a mut Lua<'lua>, Err = E>, { unsafe { // TODO: can be simplified @@ -873,7 +883,8 @@ impl<'lua> Lua<'lua> { /// ``` #[inline] pub fn empty_array<'a, I>(&'a mut self, index: I) -> LuaTable>> - where I: Borrow + where + I: Borrow, { unsafe { let mut me = self; @@ -972,7 +983,7 @@ mod tests { fn open_base_opens_base_library() { let mut lua = Lua::new(); match lua.execute::<()>("return assert(true)") { - Err(LuaError::ExecutionError(_)) => { }, + Err(LuaError::ExecutionError(_)) => {} Err(_) => panic!("Wrong error"), Ok(_) => panic!("Unexpected success"), } diff --git a/hlua/src/lua_functions.rs b/hlua/src/lua_functions.rs index 7a101e3e..8fed92eb 100644 --- a/hlua/src/lua_functions.rs +++ b/hlua/src/lua_functions.rs @@ -4,8 +4,8 @@ use libc; use std::error::Error; use std::fmt; use std::io::Cursor; -use std::io::Read; use std::io::Error as IoError; +use std::io::Read; use std::mem; use std::ptr; @@ -13,8 +13,8 @@ use AsLua; use AsMutLua; use LuaContext; -use LuaRead; use LuaError; +use LuaRead; use Push; use PushGuard; use PushOne; @@ -43,7 +43,8 @@ use Void; pub struct LuaCode<'a>(pub &'a str); impl<'lua, 'c, L> Push for LuaCode<'c> - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { type Err = LuaError; @@ -80,8 +81,9 @@ impl<'lua, 'c, L> PushOne for LuaCode<'c> where L: AsMutLua<'lua> {} pub struct LuaCodeFromReader(pub R); impl<'lua, L, R> Push for LuaCodeFromReader - where L: AsMutLua<'lua>, - R: Read +where + L: AsMutLua<'lua>, + R: Read, { type Err = LuaError; @@ -96,15 +98,17 @@ impl<'lua, L, R> Push for LuaCodeFromReader let mut read_data = ReadData { reader: self.0, - buffer: mem::uninitialized(), + buffer: [0; 128], triggered_error: None, }; - extern "C" fn reader(_: *mut ffi::lua_State, - data: *mut libc::c_void, - size: *mut libc::size_t) - -> *const libc::c_char - where R: Read + extern "C" fn reader( + _: *mut ffi::lua_State, + data: *mut libc::c_void, + size: *mut libc::size_t, + ) -> *const libc::c_char + where + R: Read, { unsafe { let data: *mut ReadData = data as *mut _; @@ -128,18 +132,22 @@ impl<'lua, L, R> Push for LuaCodeFromReader } let (load_return_value, pushed_value) = { - let code = ffi::lua_load(lua.as_mut_lua().0, - reader::, - &mut read_data as *mut ReadData<_> as *mut libc::c_void, - b"chunk\0".as_ptr() as *const _, - ptr::null()); + let code = ffi::lua_load( + lua.as_mut_lua().0, + reader::, + &mut read_data as *mut ReadData<_> as *mut libc::c_void, + b"chunk\0".as_ptr() as *const _, + ptr::null(), + ); let raw_lua = lua.as_lua(); - (code, - PushGuard { - lua: lua, - size: 1, - raw_lua: raw_lua, - }) + ( + code, + PushGuard { + lua: lua, + size: 1, + raw_lua: raw_lua, + }, + ) }; if read_data.triggered_error.is_some() { @@ -169,8 +177,9 @@ impl<'lua, L, R> Push for LuaCodeFromReader } impl<'lua, L, R> PushOne for LuaCodeFromReader - where L: AsMutLua<'lua>, - R: Read +where + L: AsMutLua<'lua>, + R: Read, { } @@ -198,7 +207,8 @@ pub struct LuaFunction { } unsafe impl<'lua, L> AsLua<'lua> for LuaFunction - where L: AsLua<'lua> +where + L: AsLua<'lua>, { #[inline] fn as_lua(&self) -> LuaContext { @@ -207,7 +217,8 @@ unsafe impl<'lua, L> AsLua<'lua> for LuaFunction } unsafe impl<'lua, L> AsMutLua<'lua> for LuaFunction - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { #[inline] fn as_mut_lua(&mut self) -> LuaContext { @@ -216,7 +227,8 @@ unsafe impl<'lua, L> AsMutLua<'lua> for LuaFunction } impl<'lua, L> LuaFunction - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { /// Calls the function. Doesn't allow passing parameters. /// @@ -228,7 +240,8 @@ impl<'lua, L> LuaFunction /// > **Note**: In order to pass parameters, see `call_with_args` instead. #[inline] pub fn call<'a, V>(&'a mut self) -> Result - where V: LuaRead> + where + V: LuaRead>, { match self.call_with_args(()) { Ok(v) => Ok(v), @@ -262,8 +275,9 @@ impl<'lua, L> LuaFunction /// ``` #[inline] pub fn call_with_args<'a, V, A, E>(&'a mut self, args: A) -> Result> - where A: for<'r> Push<&'r mut LuaFunction, Err = E>, - V: LuaRead> + where + A: for<'r> Push<&'r mut LuaFunction, Err = E>, + V: LuaRead>, { // calling pcall pops the parameters and pushes output let (pcall_return_value, pushed_value) = unsafe { @@ -273,7 +287,7 @@ impl<'lua, L> LuaFunction Ok(g) => g.forget_internal(), Err((err, _)) => return Err(LuaFunctionCallError::PushError(err)), }; - let pcall_return_value = ffi::lua_pcall(self.variable.as_mut_lua().0, num_pushed, 1, 0); // TODO: num ret values + let pcall_return_value = ffi::lua_pcall(self.variable.as_mut_lua().0, num_pushed, 1, 0); // TODO: num ret values let raw_lua = self.variable.as_lua(); let guard = PushGuard { @@ -295,9 +309,14 @@ impl<'lua, L> LuaFunction let error_msg: String = LuaRead::lua_read(pushed_value) .ok() .expect("can't find error message at the top of the Lua stack"); - Err(LuaFunctionCallError::LuaError(LuaError::ExecutionError(error_msg))) + Err(LuaFunctionCallError::LuaError(LuaError::ExecutionError( + error_msg, + ))) } - _ => panic!("Unknown error code returned by lua_pcall: {}", pcall_return_value), + _ => panic!( + "Unknown error code returned by lua_pcall: {}", + pcall_return_value + ), } } @@ -319,7 +338,8 @@ impl<'lua, L> LuaFunction /// ``` #[inline] pub fn load_from_reader(lua: L, code: R) -> Result>, LuaError> - where R: Read + where + R: Read, { match LuaCodeFromReader(code).push_to_lua(lua) { Ok(pushed) => Ok(LuaFunction { variable: pushed }), @@ -350,7 +370,8 @@ pub enum LuaFunctionCallError { } impl fmt::Display for LuaFunctionCallError - where E: fmt::Display +where + E: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { @@ -380,7 +401,8 @@ impl From> for LuaError { } impl Error for LuaFunctionCallError - where E: Error +where + E: Error, { fn description(&self) -> &str { match *self { @@ -421,11 +443,12 @@ impl Error for LuaFunctionCallError { // } impl<'lua, L> LuaRead for LuaFunction - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { #[inline] fn lua_read_at_position(mut lua: L, index: i32) -> Result, L> { - assert!(index == -1); // FIXME: + assert!(index == -1); // FIXME: if unsafe { ffi::lua_isfunction(lua.as_mut_lua().0, -1) } { Ok(LuaFunction { variable: lua }) } else { @@ -443,8 +466,8 @@ mod tests { use LuaTable; use Void; - use std::io::{Error as IoError, ErrorKind as IoErrorKind, Read}; use std::error::Error; + use std::io::{Error as IoError, ErrorKind as IoErrorKind, Read}; #[test] fn basic() { @@ -457,16 +480,26 @@ mod tests { #[test] fn args() { let mut lua = Lua::new(); - lua.execute::<()>("function foo(a) return a * 5 end").unwrap(); - let val: i32 = lua.get::, _>("foo").unwrap().call_with_args(3).unwrap(); + lua.execute::<()>("function foo(a) return a * 5 end") + .unwrap(); + let val: i32 = lua + .get::, _>("foo") + .unwrap() + .call_with_args(3) + .unwrap(); assert_eq!(val, 15); } #[test] fn args_in_order() { let mut lua = Lua::new(); - lua.execute::<()>("function foo(a, b) return a - b end").unwrap(); - let val: i32 = lua.get::, _>("foo").unwrap().call_with_args((5, 3)).unwrap(); + lua.execute::<()>("function foo(a, b) return a - b end") + .unwrap(); + let val: i32 = lua + .get::, _>("foo") + .unwrap() + .call_with_args((5, 3)) + .unwrap(); assert_eq!(val, 2); } @@ -519,7 +552,7 @@ mod tests { #[test] fn execute_from_reader_errors_if_cant_read() { - struct Reader { }; + struct Reader {}; impl Read for Reader { fn read(&mut self, _: &mut [u8]) -> ::std::io::Result { @@ -529,11 +562,13 @@ mod tests { } let mut lua = Lua::new(); - let reader = Reader { }; + let reader = Reader {}; let res: Result<(), _> = lua.execute_from_reader(reader); match res { Ok(_) => panic!("Reading succeded"), - Err(LuaError::ReadError(e)) => { assert_eq!("oh no!", e.description()) }, + Err(LuaError::ReadError(e)) => { + assert_eq!("oh no!", e.description()) + } Err(_) => panic!("Unexpected error happened"), } } @@ -543,6 +578,9 @@ mod tests { fn _assert(_: T) {} _assert(LuaFunctionCallError::LuaError::(LuaError::WrongType)); - _assert(LuaFunctionCallError::PushError(IoError::new(IoErrorKind::Other, "Test"))); + _assert(LuaFunctionCallError::PushError(IoError::new( + IoErrorKind::Other, + "Test", + ))); } } diff --git a/hlua/src/lua_tables.rs b/hlua/src/lua_tables.rs index 8eb445da..888dec72 100644 --- a/hlua/src/lua_tables.rs +++ b/hlua/src/lua_tables.rs @@ -5,10 +5,10 @@ use LuaContext; use AsLua; use AsMutLua; +use LuaRead; use Push; use PushGuard; use PushOne; -use LuaRead; use Void; /// Represents a table stored in the Lua context. @@ -55,7 +55,8 @@ impl LuaTable { } unsafe impl<'lua, L> AsLua<'lua> for LuaTable - where L: AsLua<'lua> +where + L: AsLua<'lua>, { #[inline] fn as_lua(&self) -> LuaContext { @@ -64,7 +65,8 @@ unsafe impl<'lua, L> AsLua<'lua> for LuaTable } unsafe impl<'lua, L> AsMutLua<'lua> for LuaTable - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { #[inline] fn as_mut_lua(&mut self) -> LuaContext { @@ -73,7 +75,8 @@ unsafe impl<'lua, L> AsMutLua<'lua> for LuaTable } impl<'lua, L> LuaRead for LuaTable - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { #[inline] fn lua_read_at_position(mut lua: L, index: i32) -> Result, L> { @@ -89,7 +92,8 @@ impl<'lua, L> LuaRead for LuaTable } impl<'lua, L> LuaTable - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { /// Destroys the `LuaTable` and returns its inner Lua context. Useful when it takes Lua by /// value. @@ -143,9 +147,10 @@ impl<'lua, L> LuaTable /// #[inline] pub fn get<'a, R, I, E>(&'a mut self, index: I) -> Option - where R: LuaRead>>, - I: for<'b> PushOne<&'b mut &'a mut LuaTable, Err = E>, - E: Into, + where + R: LuaRead>>, + I: for<'b> PushOne<&'b mut &'a mut LuaTable, Err = E>, + E: Into, { unsafe { // Because of a weird borrow error, we need to push the index by borrowing `&mut &mut L` @@ -177,9 +182,10 @@ impl<'lua, L> LuaTable // TODO: doc #[inline] pub fn into_get(mut self, index: I) -> Result> - where R: LuaRead>>, - I: for<'b> PushOne<&'b mut LuaTable, Err = E>, - E: Into, + where + R: LuaRead>>, + I: for<'b> PushOne<&'b mut LuaTable, Err = E>, + E: Into, { unsafe { index.push_no_err(&mut self).assert_one_and_forget(); @@ -212,10 +218,11 @@ impl<'lua, L> LuaTable // TODO: doc #[inline] pub fn set(&mut self, index: I, value: V) - where I: for<'r> PushOne<&'r mut LuaTable, Err = Ei>, - V: for<'r, 's> PushOne<&'r mut PushGuard<&'s mut LuaTable>, Err = Ev>, - Ei: Into, - Ev: Into, + where + I: for<'r> PushOne<&'r mut LuaTable, Err = Ei>, + V: for<'r, 's> PushOne<&'r mut PushGuard<&'s mut LuaTable>, Err = Ev>, + Ei: Into, + Ev: Into, { match self.checked_set(index, value) { Ok(()) => (), @@ -229,12 +236,14 @@ impl<'lua, L> LuaTable /// limited set of types. You are encouraged to use the `set` method if writing cannot fail. // TODO: doc #[inline] - pub fn checked_set(&mut self, - index: I, - value: V) - -> Result<(), CheckedSetError> - where I: for<'r> PushOne<&'r mut LuaTable, Err = Ke>, - V: for<'r, 's> PushOne<&'r mut PushGuard<&'s mut LuaTable>, Err = Ve> + pub fn checked_set( + &mut self, + index: I, + value: V, + ) -> Result<(), CheckedSetError> + where + I: for<'r> PushOne<&'r mut LuaTable, Err = Ke>, + V: for<'r, 's> PushOne<&'r mut PushGuard<&'s mut LuaTable>, Err = Ve>, { unsafe { let raw_lua = self.as_mut_lua().0; @@ -269,8 +278,9 @@ impl<'lua, L> LuaTable /// Inserts an empty array, then loads it. #[inline] pub fn empty_array<'s, I, E>(&'s mut self, index: I) -> LuaTable>> - where I: for<'a> PushOne<&'a mut &'s mut LuaTable, Err = E> + Clone, - E: Into, + where + I: for<'a> PushOne<&'a mut &'s mut LuaTable, Err = E> + Clone, + E: Into, { // TODO: cleaner implementation unsafe { @@ -280,12 +290,12 @@ impl<'lua, L> LuaTable assert_eq!(pushed.size, 1); pushed.forget() } - Err(_) => panic!(), // TODO: + Err(_) => panic!(), // TODO: }; match Vec::::with_capacity(0).push_to_lua(&mut me) { Ok(pushed) => pushed.forget(), - Err(_) => panic!(), // TODO: + Err(_) => panic!(), // TODO: }; ffi::lua_settable(me.as_mut_lua().0, me.offset(-2)); @@ -414,7 +424,8 @@ pub struct LuaTableIterator<'t, L: 't, K, V> { } unsafe impl<'t, 'lua, L, K, V> AsLua<'lua> for LuaTableIterator<'t, L, K, V> - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { #[inline] fn as_lua(&self) -> LuaContext { @@ -423,7 +434,8 @@ unsafe impl<'t, 'lua, L, K, V> AsLua<'lua> for LuaTableIterator<'t, L, K, V> } unsafe impl<'t, 'lua, L, K, V> AsMutLua<'lua> for LuaTableIterator<'t, L, K, V> - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { #[inline] fn as_mut_lua(&mut self) -> LuaContext { @@ -432,9 +444,10 @@ unsafe impl<'t, 'lua, L, K, V> AsMutLua<'lua> for LuaTableIterator<'t, L, K, V> } impl<'t, 'lua, L, K, V> Iterator for LuaTableIterator<'t, L, K, V> - where L: AsMutLua<'lua> + 't, - K: for<'i, 'j> LuaRead<&'i mut &'j mut LuaTableIterator<'t, L, K, V>> + 'static, - V: for<'i, 'j> LuaRead<&'i mut &'j mut LuaTableIterator<'t, L, K, V>> + 'static +where + L: AsMutLua<'lua> + 't, + K: for<'i, 'j> LuaRead<&'i mut &'j mut LuaTableIterator<'t, L, K, V>> + 'static, + V: for<'i, 'j> LuaRead<&'i mut &'j mut LuaTableIterator<'t, L, K, V>> + 'static, { type Item = Option<(K, V)>; @@ -483,10 +496,10 @@ impl<'t, L, K, V> Drop for LuaTableIterator<'t, L, K, V> { #[cfg(test)] mod tests { + use function0; use Lua; use LuaTable; use PushGuard; - use function0; #[test] fn iterable() { @@ -517,8 +530,10 @@ mod tests { for _ in 0..10 { let table_content: Vec> = table.iter().collect(); - assert_eq!(table_content, - vec![Some((1, 9)), Some((2, 8)), Some((3, 7))]); + assert_eq!( + table_content, + vec![Some((1, 9)), Some((2, 8)), Some((3, 7))] + ); } } diff --git a/hlua/src/macros.rs b/hlua/src/macros.rs index 4ca88f12..b98e17fc 100644 --- a/hlua/src/macros.rs +++ b/hlua/src/macros.rs @@ -1,16 +1,18 @@ #[macro_export] macro_rules! implement_lua_push { ($ty:ty, $cb:expr) => { - impl<'lua, L> $crate::Push for $ty where L: $crate::AsMutLua<'lua> { - type Err = $crate::Void; // TODO: use ! instead + impl<'lua, L> $crate::Push for $ty + where + L: $crate::AsMutLua<'lua>, + { + type Err = $crate::Void; // TODO: use ! instead #[inline] fn push_to_lua(self, lua: L) -> Result<$crate::PushGuard, ($crate::Void, L)> { Ok($crate::push_userdata(self, lua, $cb)) } } - - impl<'lua, L> $crate::PushOne for $ty where L: $crate::AsMutLua<'lua> { - } + + impl<'lua, L> $crate::PushOne for $ty where L: $crate::AsMutLua<'lua> {} }; } @@ -19,7 +21,10 @@ macro_rules! implement_lua_read { ($ty:ty) => { impl<'s, 'c> hlua::LuaRead<&'c mut hlua::InsideCallback> for &'s mut $ty { #[inline] - fn lua_read_at_position(lua: &'c mut hlua::InsideCallback, index: i32) -> Result<&'s mut $ty, &'c mut hlua::InsideCallback> { + fn lua_read_at_position( + lua: &'c mut hlua::InsideCallback, + index: i32, + ) -> Result<&'s mut $ty, &'c mut hlua::InsideCallback> { // FIXME: unsafe { ::std::mem::transmute($crate::read_userdata::<$ty>(lua, index)) } } @@ -27,7 +32,10 @@ macro_rules! implement_lua_read { impl<'s, 'c> hlua::LuaRead<&'c mut hlua::InsideCallback> for &'s $ty { #[inline] - fn lua_read_at_position(lua: &'c mut hlua::InsideCallback, index: i32) -> Result<&'s $ty, &'c mut hlua::InsideCallback> { + fn lua_read_at_position( + lua: &'c mut hlua::InsideCallback, + index: i32, + ) -> Result<&'s $ty, &'c mut hlua::InsideCallback> { // FIXME: unsafe { ::std::mem::transmute($crate::read_userdata::<$ty>(lua, index)) } } @@ -35,26 +43,32 @@ macro_rules! implement_lua_read { impl<'s, 'b, 'c> hlua::LuaRead<&'b mut &'c mut hlua::InsideCallback> for &'s mut $ty { #[inline] - fn lua_read_at_position(lua: &'b mut &'c mut hlua::InsideCallback, index: i32) -> Result<&'s mut $ty, &'b mut &'c mut hlua::InsideCallback> { + fn lua_read_at_position( + lua: &'b mut &'c mut hlua::InsideCallback, + index: i32, + ) -> Result<&'s mut $ty, &'b mut &'c mut hlua::InsideCallback> { let ptr_lua = lua as *mut &mut hlua::InsideCallback; let deref_lua = unsafe { ::std::ptr::read(ptr_lua) }; let res = Self::lua_read_at_position(deref_lua, index); match res { Ok(x) => Ok(x), - _ => Err(lua) + _ => Err(lua), } } } impl<'s, 'b, 'c> hlua::LuaRead<&'b mut &'c mut hlua::InsideCallback> for &'s $ty { #[inline] - fn lua_read_at_position(lua: &'b mut &'c mut hlua::InsideCallback, index: i32) -> Result<&'s $ty, &'b mut &'c mut hlua::InsideCallback> { + fn lua_read_at_position( + lua: &'b mut &'c mut hlua::InsideCallback, + index: i32, + ) -> Result<&'s $ty, &'b mut &'c mut hlua::InsideCallback> { let ptr_lua = lua as *mut &mut hlua::InsideCallback; let deref_lua = unsafe { ::std::ptr::read(ptr_lua) }; let res = Self::lua_read_at_position(deref_lua, index); match res { Ok(x) => Ok(x), - _ => Err(lua) + _ => Err(lua), } } } diff --git a/hlua/src/rust_tables.rs b/hlua/src/rust_tables.rs index 77126f80..e9f1df69 100644 --- a/hlua/src/rust_tables.rs +++ b/hlua/src/rust_tables.rs @@ -1,12 +1,12 @@ +use any::{AnyHashableLuaValue, AnyLuaValue}; use ffi; -use any::{AnyLuaValue, AnyHashableLuaValue}; +use AsMutLua; +use LuaRead; use Push; use PushGuard; use PushOne; -use AsMutLua; use TuplePushError; -use LuaRead; use std::collections::{BTreeMap, HashMap, HashSet}; use std::hash::Hash; @@ -14,9 +14,10 @@ use std::iter; #[inline] fn push_iter<'lua, L, V, I, E>(mut lua: L, iterator: I) -> Result, (E, L)> - where L: AsMutLua<'lua>, - V: for<'b> Push<&'b mut L, Err = E>, - I: Iterator +where + L: AsMutLua<'lua>, + V: for<'b> Push<&'b mut L, Err = E>, + I: Iterator, { // creating empty table unsafe { ffi::lua_newtable(lua.as_mut_lua().0) }; @@ -24,7 +25,7 @@ fn push_iter<'lua, L, V, I, E>(mut lua: L, iterator: I) -> Result, for (elem, index) in iterator.zip(1..) { let size = match elem.push_to_lua(&mut lua) { Ok(pushed) => pushed.forget_internal(), - Err((_err, _lua)) => panic!(), // TODO: wrong return Err((err, lua)), // FIXME: destroy the temporary table + Err((_err, _lua)) => panic!(), // TODO: wrong return Err((err, lua)), // FIXME: destroy the temporary table }; match size { @@ -53,9 +54,10 @@ fn push_iter<'lua, L, V, I, E>(mut lua: L, iterator: I) -> Result, #[inline] fn push_rec_iter<'lua, L, V, I, E>(mut lua: L, iterator: I) -> Result, (E, L)> - where L: AsMutLua<'lua>, - V: for<'a> Push<&'a mut L, Err = E>, - I: Iterator +where + L: AsMutLua<'lua>, + V: for<'a> Push<&'a mut L, Err = E>, + I: Iterator, { let (nrec, _) = iterator.size_hint(); @@ -65,7 +67,7 @@ fn push_rec_iter<'lua, L, V, I, E>(mut lua: L, iterator: I) -> Result pushed.forget_internal(), - Err((_err, _lua)) => panic!(), // TODO: wrong return Err((err, lua)), // FIXME: destroy the temporary table + Err((_err, _lua)) => panic!(), // TODO: wrong return Err((err, lua)), // FIXME: destroy the temporary table }; match size { @@ -84,8 +86,9 @@ fn push_rec_iter<'lua, L, V, I, E>(mut lua: L, iterator: I) -> Result Push for Vec - where L: AsMutLua<'lua>, - T: for<'a> Push<&'a mut L, Err = E> +where + L: AsMutLua<'lua>, + T: for<'a> Push<&'a mut L, Err = E>, { type Err = E; @@ -96,13 +99,15 @@ impl<'lua, L, T, E> Push for Vec } impl<'lua, L, T, E> PushOne for Vec - where L: AsMutLua<'lua>, - T: for<'a> Push<&'a mut L, Err = E> +where + L: AsMutLua<'lua>, + T: for<'a> Push<&'a mut L, Err = E>, { } impl<'lua, L> LuaRead for Vec - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { fn lua_read_at_position(lua: L, index: i32) -> Result { // We need this as iteration order isn't guaranteed to match order of @@ -120,28 +125,28 @@ impl<'lua, L> LuaRead for Vec } let key = { - let maybe_key: Option = - LuaRead::lua_read_at_position(&mut me, -2).ok(); + let maybe_key: Option = LuaRead::lua_read_at_position(&mut me, -2).ok(); match maybe_key { None => { // Cleaning up after ourselves unsafe { ffi::lua_pop(me.as_mut_lua().0, 2) }; - return Err(me) + return Err(me); } Some(k) => k, } }; - let value: AnyLuaValue = - LuaRead::lua_read_at_position(&mut me, -1).ok().unwrap(); + let value: AnyLuaValue = LuaRead::lua_read_at_position(&mut me, -1).ok().unwrap(); unsafe { ffi::lua_pop(me.as_mut_lua().0, 1) }; dict.insert(key, value); } - let (maximum_key, minimum_key) = - (*dict.keys().max().unwrap_or(&1), *dict.keys().min().unwrap_or(&1)); + let (maximum_key, minimum_key) = ( + *dict.keys().max().unwrap_or(&1), + *dict.keys().min().unwrap_or(&1), + ); if minimum_key != 1 { // Rust doesn't support sparse arrays or arrays with negative @@ -149,8 +154,7 @@ impl<'lua, L> LuaRead for Vec return Err(me); } - let mut result = - Vec::with_capacity(maximum_key as usize); + let mut result = Vec::with_capacity(maximum_key as usize); // We expect to start with first element of table and have this // be smaller that first key by one @@ -160,7 +164,7 @@ impl<'lua, L> LuaRead for Vec // and check that table represented non-sparse 1-indexed array for (k, v) in dict { if previous_key + 1 != k { - return Err(me) + return Err(me); } else { // We just push, thus converting Lua 1-based indexing // to Rust 0-based indexing @@ -174,8 +178,9 @@ impl<'lua, L> LuaRead for Vec } impl<'a, 'lua, L, T, E> Push for &'a [T] - where L: AsMutLua<'lua>, - T: Clone + for<'b> Push<&'b mut L, Err = E> +where + L: AsMutLua<'lua>, + T: Clone + for<'b> Push<&'b mut L, Err = E>, { type Err = E; @@ -186,13 +191,15 @@ impl<'a, 'lua, L, T, E> Push for &'a [T] } impl<'a, 'lua, L, T, E> PushOne for &'a [T] - where L: AsMutLua<'lua>, - T: Clone + for<'b> Push<&'b mut L, Err = E> +where + L: AsMutLua<'lua>, + T: Clone + for<'b> Push<&'b mut L, Err = E>, { } impl<'lua, L> LuaRead for HashMap - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { // TODO: this should be implemented using the LuaTable API instead of raw Lua calls. fn lua_read_at_position(lua: L, index: i32) -> Result { @@ -213,14 +220,13 @@ impl<'lua, L> LuaRead for HashMap None => { // Cleaning up after ourselves unsafe { ffi::lua_pop(me.as_mut_lua().0, 2) }; - return Err(me) + return Err(me); } Some(k) => k, } }; - let value: AnyLuaValue = - LuaRead::lua_read_at_position(&mut me, -1).ok().unwrap(); + let value: AnyLuaValue = LuaRead::lua_read_at_position(&mut me, -1).ok().unwrap(); unsafe { ffi::lua_pop(me.as_mut_lua().0, 1) }; @@ -233,9 +239,10 @@ impl<'lua, L> LuaRead for HashMap // TODO: use an enum for the error to allow different error types for K and V impl<'lua, L, K, V, E> Push for HashMap - where L: AsMutLua<'lua>, - K: for<'a, 'b> PushOne<&'a mut &'b mut L, Err = E> + Eq + Hash, - V: for<'a, 'b> PushOne<&'a mut &'b mut L, Err = E> +where + L: AsMutLua<'lua>, + K: for<'a, 'b> PushOne<&'a mut &'b mut L, Err = E> + Eq + Hash, + V: for<'a, 'b> PushOne<&'a mut &'b mut L, Err = E>, { type Err = E; @@ -250,15 +257,17 @@ impl<'lua, L, K, V, E> Push for HashMap } impl<'lua, L, K, V, E> PushOne for HashMap - where L: AsMutLua<'lua>, - K: for<'a, 'b> PushOne<&'a mut &'b mut L, Err = E> + Eq + Hash, - V: for<'a, 'b> PushOne<&'a mut &'b mut L, Err = E> +where + L: AsMutLua<'lua>, + K: for<'a, 'b> PushOne<&'a mut &'b mut L, Err = E> + Eq + Hash, + V: for<'a, 'b> PushOne<&'a mut &'b mut L, Err = E>, { } impl<'lua, L, K, E> Push for HashSet - where L: AsMutLua<'lua>, - K: for<'a, 'b> PushOne<&'a mut &'b mut L, Err = E> + Eq + Hash +where + L: AsMutLua<'lua>, + K: for<'a, 'b> PushOne<&'a mut &'b mut L, Err = E> + Eq + Hash, { type Err = E; @@ -273,18 +282,19 @@ impl<'lua, L, K, E> Push for HashSet } impl<'lua, L, K, E> PushOne for HashSet - where L: AsMutLua<'lua>, - K: for<'a, 'b> PushOne<&'a mut &'b mut L, Err = E> + Eq + Hash +where + L: AsMutLua<'lua>, + K: for<'a, 'b> PushOne<&'a mut &'b mut L, Err = E> + Eq + Hash, { } #[cfg(test)] mod tests { - use std::collections::{HashMap, HashSet, BTreeMap}; + use std::collections::{BTreeMap, HashMap, HashSet}; + use AnyHashableLuaValue; + use AnyLuaValue; use Lua; use LuaTable; - use AnyLuaValue; - use AnyHashableLuaValue; #[test] fn write() { @@ -331,7 +341,8 @@ mod tests { let mut table: LuaTable<_> = lua.get("a").unwrap(); - let values: HashSet = table.iter() + let values: HashSet = table + .iter() .filter_map(|e| e) .map(|(elem, set): (i32, bool)| { assert!(set); @@ -374,7 +385,8 @@ mod tests { fn reading_vec_from_sparse_table_doesnt_work() { let mut lua = Lua::new(); - lua.execute::<()>(r#"v = { [-1] = -1, [2] = 2, [42] = 42 }"#).unwrap(); + lua.execute::<()>(r#"v = { [-1] = -1, [2] = 2, [42] = 42 }"#) + .unwrap(); let read: Option> = lua.get("v"); if read.is_some() { @@ -396,7 +408,8 @@ mod tests { fn reading_vec_with_complex_indexes_doesnt_work() { let mut lua = Lua::new(); - lua.execute::<()>(r#"v = { [-1] = -1, ["foo"] = 2, [{}] = 42 }"#).unwrap(); + lua.execute::<()>(r#"v = { [-1] = -1, ["foo"] = 2, [{}] = 42 }"#) + .unwrap(); let read: Option> = lua.get("v"); if read.is_some() { @@ -431,15 +444,22 @@ mod tests { let read: Vec<_> = lua.get("v").unwrap(); assert_eq!( read, - [1., 2., 3.].iter() - .map(|x| AnyLuaValue::LuaNumber(*x)).collect::>()); + [1., 2., 3.] + .iter() + .map(|x| AnyLuaValue::LuaNumber(*x)) + .collect::>() + ); } #[test] fn reading_hashmap_works() { let mut lua = Lua::new(); - let orig: HashMap = [1., 2., 3.].into_iter().enumerate().map(|(k, v)| (k as i32, *v as f64)).collect(); + let orig: HashMap = [1., 2., 3.] + .into_iter() + .enumerate() + .map(|(k, v)| (k as i32, *v as f64)) + .collect(); let orig_copy = orig.clone(); // Collect to BTreeMap so that iterator yields values in order let orig_btree: BTreeMap<_, _> = orig_copy.into_iter().collect(); @@ -464,12 +484,22 @@ mod tests { fn reading_hashmap_from_sparse_table_works() { let mut lua = Lua::new(); - lua.execute::<()>(r#"v = { [-1] = -1, [2] = 2, [42] = 42 }"#).unwrap(); + lua.execute::<()>(r#"v = { [-1] = -1, [2] = 2, [42] = 42 }"#) + .unwrap(); let read: HashMap<_, _> = lua.get("v").unwrap(); - assert_eq!(read[&AnyHashableLuaValue::LuaNumber(-1)], AnyLuaValue::LuaNumber(-1.)); - assert_eq!(read[&AnyHashableLuaValue::LuaNumber(2)], AnyLuaValue::LuaNumber(2.)); - assert_eq!(read[&AnyHashableLuaValue::LuaNumber(42)], AnyLuaValue::LuaNumber(42.)); + assert_eq!( + read[&AnyHashableLuaValue::LuaNumber(-1)], + AnyLuaValue::LuaNumber(-1.) + ); + assert_eq!( + read[&AnyHashableLuaValue::LuaNumber(2)], + AnyLuaValue::LuaNumber(2.) + ); + assert_eq!( + read[&AnyHashableLuaValue::LuaNumber(42)], + AnyLuaValue::LuaNumber(42.) + ); assert_eq!(read.len(), 3); } @@ -487,12 +517,22 @@ mod tests { fn reading_hashmap_with_complex_indexes_works() { let mut lua = Lua::new(); - lua.execute::<()>(r#"v = { [-1] = -1, ["foo"] = 2, [2.] = 42 }"#).unwrap(); + lua.execute::<()>(r#"v = { [-1] = -1, ["foo"] = 2, [2.] = 42 }"#) + .unwrap(); let read: HashMap<_, _> = lua.get("v").unwrap(); - assert_eq!(read[&AnyHashableLuaValue::LuaNumber(-1)], AnyLuaValue::LuaNumber(-1.)); - assert_eq!(read[&AnyHashableLuaValue::LuaString("foo".to_owned())], AnyLuaValue::LuaNumber(2.)); - assert_eq!(read[&AnyHashableLuaValue::LuaNumber(2)], AnyLuaValue::LuaNumber(42.)); + assert_eq!( + read[&AnyHashableLuaValue::LuaNumber(-1)], + AnyLuaValue::LuaNumber(-1.) + ); + assert_eq!( + read[&AnyHashableLuaValue::LuaString("foo".to_owned())], + AnyLuaValue::LuaNumber(2.) + ); + assert_eq!( + read[&AnyHashableLuaValue::LuaNumber(2)], + AnyLuaValue::LuaNumber(42.) + ); assert_eq!(read.len(), 3); } @@ -500,13 +540,20 @@ mod tests { fn reading_hashmap_with_floating_indexes_works() { let mut lua = Lua::new(); - lua.execute::<()>(r#"v = { [-1.25] = -1, [2.5] = 42 }"#).unwrap(); + lua.execute::<()>(r#"v = { [-1.25] = -1, [2.5] = 42 }"#) + .unwrap(); let read: HashMap<_, _> = lua.get("v").unwrap(); // It works by truncating integers in some unspecified way // https://www.lua.org/manual/5.2/manual.html#lua_tointegerx - assert_eq!(read[&AnyHashableLuaValue::LuaNumber(-1)], AnyLuaValue::LuaNumber(-1.)); - assert_eq!(read[&AnyHashableLuaValue::LuaNumber(2)], AnyLuaValue::LuaNumber(42.)); + assert_eq!( + read[&AnyHashableLuaValue::LuaNumber(-1)], + AnyLuaValue::LuaNumber(-1.) + ); + assert_eq!( + read[&AnyHashableLuaValue::LuaNumber(2)], + AnyLuaValue::LuaNumber(42.) + ); assert_eq!(read.len(), 2); } @@ -515,9 +562,18 @@ mod tests { let mut lua = Lua::new(); let mut orig = HashMap::new(); - orig.insert(AnyHashableLuaValue::LuaNumber(42), AnyLuaValue::LuaNumber(42.)); - orig.insert(AnyHashableLuaValue::LuaString("foo".to_owned()), AnyLuaValue::LuaString("foo".to_owned())); - orig.insert(AnyHashableLuaValue::LuaBoolean(true), AnyLuaValue::LuaBoolean(true)); + orig.insert( + AnyHashableLuaValue::LuaNumber(42), + AnyLuaValue::LuaNumber(42.), + ); + orig.insert( + AnyHashableLuaValue::LuaString("foo".to_owned()), + AnyLuaValue::LuaString("foo".to_owned()), + ); + orig.insert( + AnyHashableLuaValue::LuaBoolean(true), + AnyLuaValue::LuaBoolean(true), + ); let orig_clone = orig.clone(); lua.set("v", orig); @@ -530,12 +586,20 @@ mod tests { fn reading_hashmap_set_from_lua_works() { let mut lua = Lua::new(); - lua.execute::<()>(r#"v = { [1] = 2, [2] = 3, [3] = 4 }"#).unwrap(); + lua.execute::<()>(r#"v = { [1] = 2, [2] = 3, [3] = 4 }"#) + .unwrap(); let read: HashMap<_, _> = lua.get("v").unwrap(); assert_eq!( read, - [2., 3., 4.].iter().enumerate() - .map(|(k, v)| (AnyHashableLuaValue::LuaNumber((k + 1) as i32), AnyLuaValue::LuaNumber(*v))).collect::>()); + [2., 3., 4.] + .iter() + .enumerate() + .map(|(k, v)| ( + AnyHashableLuaValue::LuaNumber((k + 1) as i32), + AnyLuaValue::LuaNumber(*v) + )) + .collect::>() + ); } } diff --git a/hlua/src/tuples.rs b/hlua/src/tuples.rs index 95cab9e1..ceeeddcf 100644 --- a/hlua/src/tuples.rs +++ b/hlua/src/tuples.rs @@ -1,10 +1,10 @@ -use AsMutLua; use AsLua; +use AsMutLua; +use LuaRead; use Push; -use PushOne; use PushGuard; -use LuaRead; +use PushOne; use Void; macro_rules! tuple_impl { diff --git a/hlua/src/userdata.rs b/hlua/src/userdata.rs index ae5f2d4a..e45bd3fa 100644 --- a/hlua/src/userdata.rs +++ b/hlua/src/userdata.rs @@ -1,7 +1,7 @@ use std::any::{Any, TypeId}; use std::marker::PhantomData; -use std::ops::{Deref, DerefMut}; use std::mem; +use std::ops::{Deref, DerefMut}; use std::ptr; use ffi; @@ -9,10 +9,10 @@ use libc; use AsLua; use AsMutLua; -use Push; -use PushGuard; use LuaContext; use LuaRead; +use Push; +use PushGuard; use InsideCallback; use LuaTable; @@ -53,9 +53,10 @@ extern "C" fn destructor_wrapper(lua: *mut ffi::lua_State) -> libc::c_int { /// #[inline] pub fn push_userdata<'lua, L, T, F>(data: T, mut lua: L, metatable: F) -> PushGuard - where F: FnOnce(LuaTable<&mut PushGuard<&mut L>>), - L: AsMutLua<'lua>, - T: Send + 'static + Any +where + F: FnOnce(LuaTable<&mut PushGuard<&mut L>>), + L: AsMutLua<'lua>, + T: Send + 'static + Any, { unsafe { let typeid = TypeId::of::(); @@ -121,10 +122,12 @@ pub fn push_userdata<'lua, L, T, F>(data: T, mut lua: L, metatable: F) -> PushGu /// #[inline] -pub fn read_userdata<'t, 'c, T>(lua: &'c mut InsideCallback, - index: i32) - -> Result<&'t mut T, &'c mut InsideCallback> - where T: 'static + Any +pub fn read_userdata<'t, 'c, T>( + lua: &'c mut InsideCallback, + index: i32, +) -> Result<&'t mut T, &'c mut InsideCallback> +where + T: 'static + Any, { unsafe { let data_ptr = ffi::lua_touserdata(lua.as_lua().0, index); @@ -151,8 +154,9 @@ pub struct UserdataOnStack { } impl<'lua, T, L> LuaRead for UserdataOnStack - where L: AsMutLua<'lua>, - T: 'lua + Any +where + L: AsMutLua<'lua>, + T: 'lua + Any, { #[inline] fn lua_read_at_position(lua: L, index: i32) -> Result, L> { @@ -177,8 +181,9 @@ impl<'lua, T, L> LuaRead for UserdataOnStack } unsafe impl<'lua, T, L> AsLua<'lua> for UserdataOnStack - where L: AsLua<'lua>, - T: 'lua + Any +where + L: AsLua<'lua>, + T: 'lua + Any, { #[inline] fn as_lua(&self) -> LuaContext { @@ -187,8 +192,9 @@ unsafe impl<'lua, T, L> AsLua<'lua> for UserdataOnStack } unsafe impl<'lua, T, L> AsMutLua<'lua> for UserdataOnStack - where L: AsMutLua<'lua>, - T: 'lua + Any +where + L: AsMutLua<'lua>, + T: 'lua + Any, { #[inline] fn as_mut_lua(&mut self) -> LuaContext { @@ -197,8 +203,9 @@ unsafe impl<'lua, T, L> AsMutLua<'lua> for UserdataOnStack } impl<'lua, T, L> Deref for UserdataOnStack - where L: AsLua<'lua>, - T: 'lua + Any +where + L: AsLua<'lua>, + T: 'lua + Any, { type Target = T; @@ -213,8 +220,9 @@ impl<'lua, T, L> Deref for UserdataOnStack } impl<'lua, T, L> DerefMut for UserdataOnStack - where L: AsMutLua<'lua>, - T: 'lua + Any +where + L: AsMutLua<'lua>, + T: 'lua + Any, { #[inline] fn deref_mut(&mut self) -> &mut T { diff --git a/hlua/src/values.rs b/hlua/src/values.rs index d648b0c6..f933e613 100644 --- a/hlua/src/values.rs +++ b/hlua/src/values.rs @@ -1,13 +1,13 @@ use std::mem; +use std::ops::Deref; use std::slice; use std::str; -use std::ops::Deref; use ffi; use libc; -use AnyLuaValue; use AnyLuaString; +use AnyLuaValue; use AsLua; use AsMutLua; use LuaRead; @@ -28,18 +28,20 @@ macro_rules! integer_impl( Ok(PushGuard { lua: lua, size: 1, raw_lua: raw_lua }) } } - + impl<'lua, L> PushOne for $t where L: AsMutLua<'lua> { } impl<'lua, L> LuaRead for $t where L: AsLua<'lua> { #[inline] fn lua_read_at_position(lua: L, index: i32) -> Result<$t, L> { - let mut success = unsafe { mem::uninitialized() }; - let val = unsafe { ffi::lua_tointegerx(lua.as_lua().0, index, &mut success) }; - match success { - 0 => Err(lua), - _ => Ok(val as $t) + unsafe { + let mut success = mem::MaybeUninit::uninit(); + let val = ffi::lua_tointegerx(lua.as_lua().0, index, success.as_mut_ptr()); + match success.assume_init() { + 0 => Err(lua), + _ => Ok(val as $t) + } } } } @@ -63,18 +65,20 @@ macro_rules! unsigned_impl( Ok(PushGuard { lua: lua, size: 1, raw_lua: raw_lua }) } } - + impl<'lua, L> PushOne for $t where L: AsMutLua<'lua> { } impl<'lua, L> LuaRead for $t where L: AsLua<'lua> { #[inline] fn lua_read_at_position(lua: L, index: i32) -> Result<$t, L> { - let mut success = unsafe { mem::uninitialized() }; - let val = unsafe { ffi::lua_tounsignedx(lua.as_lua().0, index, &mut success) }; - match success { - 0 => Err(lua), - _ => Ok(val as $t) + unsafe { + let mut success = mem::MaybeUninit::uninit(); + let val = ffi::lua_tounsignedx(lua.as_lua().0, index, success.as_mut_ptr()); + match success.assume_init() { + 0 => Err(lua), + _ => Ok(val as $t) + } } } } @@ -98,18 +102,20 @@ macro_rules! numeric_impl( Ok(PushGuard { lua: lua, size: 1, raw_lua: raw_lua }) } } - + impl<'lua, L> PushOne for $t where L: AsMutLua<'lua> { } impl<'lua, L> LuaRead for $t where L: AsLua<'lua> { #[inline] fn lua_read_at_position(lua: L, index: i32) -> Result<$t, L> { - let mut success = unsafe { mem::uninitialized() }; - let val = unsafe { ffi::lua_tonumberx(lua.as_lua().0, index, &mut success) }; - match success { - 0 => Err(lua), - _ => Ok(val as $t) + unsafe { + let mut success = mem::MaybeUninit::uninit(); + let val = ffi::lua_tonumberx(lua.as_lua().0, index, success.as_mut_ptr()); + match success.assume_init() { + 0 => Err(lua), + _ => Ok(val as $t) + } } } } @@ -120,16 +126,19 @@ numeric_impl!(f32); numeric_impl!(f64); impl<'lua, L> Push for String - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { - type Err = Void; // TODO: use `!` instead (https://github.com/rust-lang/rust/issues/35121) + type Err = Void; // TODO: use `!` instead (https://github.com/rust-lang/rust/issues/35121) #[inline] fn push_to_lua(self, mut lua: L) -> Result, (Void, L)> { unsafe { - ffi::lua_pushlstring(lua.as_mut_lua().0, - self.as_bytes().as_ptr() as *const _, - self.as_bytes().len() as libc::size_t); + ffi::lua_pushlstring( + lua.as_mut_lua().0, + self.as_bytes().as_ptr() as *const _, + self.as_bytes().len() as libc::size_t, + ); let raw_lua = lua.as_lua(); Ok(PushGuard { @@ -144,37 +153,43 @@ impl<'lua, L> Push for String impl<'lua, L> PushOne for String where L: AsMutLua<'lua> {} impl<'lua, L> LuaRead for String - where L: AsLua<'lua> +where + L: AsLua<'lua>, { #[inline] fn lua_read_at_position(lua: L, index: i32) -> Result { - let mut size: libc::size_t = unsafe { mem::uninitialized() }; - let c_str_raw = unsafe { ffi::lua_tolstring(lua.as_lua().0, index, &mut size) }; - if c_str_raw.is_null() { - return Err(lua); - } + unsafe { + let mut size: mem::MaybeUninit = mem::MaybeUninit::uninit(); + let c_str_raw = ffi::lua_tolstring(lua.as_lua().0, index, size.as_mut_ptr()); + if c_str_raw.is_null() { + return Err(lua); + } - let c_slice = unsafe { slice::from_raw_parts(c_str_raw as *const u8, size) }; - let maybe_string = String::from_utf8(c_slice.to_vec()); - match maybe_string { - Ok(string) => Ok(string), - Err(_) => Err(lua), + let c_slice = slice::from_raw_parts(c_str_raw as *const u8, size.assume_init()); + let maybe_string = String::from_utf8(c_slice.to_vec()); + match maybe_string { + Ok(string) => Ok(string), + Err(_) => Err(lua), + } } } } impl<'lua, L> Push for AnyLuaString - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { - type Err = Void; // TODO: use `!` instead (https://github.com/rust-lang/rust/issues/35121) + type Err = Void; // TODO: use `!` instead (https://github.com/rust-lang/rust/issues/35121) #[inline] fn push_to_lua(self, mut lua: L) -> Result, (Void, L)> { let AnyLuaString(v) = self; unsafe { - ffi::lua_pushlstring(lua.as_mut_lua().0, - v[..].as_ptr() as *const _, - v[..].len() as libc::size_t); + ffi::lua_pushlstring( + lua.as_mut_lua().0, + v[..].as_ptr() as *const _, + v[..].len() as libc::size_t, + ); let raw_lua = lua.as_lua(); Ok(PushGuard { @@ -187,32 +202,38 @@ impl<'lua, L> Push for AnyLuaString } impl<'lua, L> LuaRead for AnyLuaString - where L: AsLua<'lua> +where + L: AsLua<'lua>, { #[inline] fn lua_read_at_position(lua: L, index: i32) -> Result { - let mut size: libc::size_t = unsafe { mem::uninitialized() }; - let c_str_raw = unsafe { ffi::lua_tolstring(lua.as_lua().0, index, &mut size) }; - if c_str_raw.is_null() { - return Err(lua); - } + unsafe { + let mut size: mem::MaybeUninit = mem::MaybeUninit::uninit(); + let c_str_raw = ffi::lua_tolstring(lua.as_lua().0, index, size.as_mut_ptr()); + if c_str_raw.is_null() { + return Err(lua); + } - let c_slice = unsafe { slice::from_raw_parts(c_str_raw as *const u8, size) }; - Ok(AnyLuaString(c_slice.to_vec())) + let c_slice = slice::from_raw_parts(c_str_raw as *const u8, size.assume_init()); + Ok(AnyLuaString(c_slice.to_vec())) + } } } impl<'lua, 's, L> Push for &'s str - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { - type Err = Void; // TODO: use `!` instead (https://github.com/rust-lang/rust/issues/35121) + type Err = Void; // TODO: use `!` instead (https://github.com/rust-lang/rust/issues/35121) #[inline] fn push_to_lua(self, mut lua: L) -> Result, (Void, L)> { unsafe { - ffi::lua_pushlstring(lua.as_mut_lua().0, - self.as_bytes().as_ptr() as *const _, - self.as_bytes().len() as libc::size_t); + ffi::lua_pushlstring( + lua.as_mut_lua().0, + self.as_bytes().as_ptr() as *const _, + self.as_bytes().len() as libc::size_t, + ); let raw_lua = lua.as_lua(); Ok(PushGuard { @@ -250,27 +271,31 @@ pub struct StringInLua { } impl<'lua, L> LuaRead for StringInLua - where L: AsLua<'lua> +where + L: AsLua<'lua>, { #[inline] fn lua_read_at_position(lua: L, index: i32) -> Result, L> { - let mut size: libc::size_t = unsafe { mem::uninitialized() }; - let c_str_raw = unsafe { ffi::lua_tolstring(lua.as_lua().0, index, &mut size) }; - if c_str_raw.is_null() { - return Err(lua); - } + unsafe { + let mut size: mem::MaybeUninit = mem::MaybeUninit::uninit(); + let c_str_raw = ffi::lua_tolstring(lua.as_lua().0, index, size.as_mut_ptr()); + if c_str_raw.is_null() { + return Err(lua); + } - let c_slice = unsafe { slice::from_raw_parts(c_str_raw as *const u8, size) }; - match str::from_utf8(c_slice) { - Ok(_) => (), - Err(_) => return Err(lua) - }; + let size = size.assume_init(); + let c_slice = slice::from_raw_parts(c_str_raw as *const u8, size); + match str::from_utf8(c_slice) { + Ok(_) => (), + Err(_) => return Err(lua), + }; - Ok(StringInLua { - lua: lua, - c_str_raw: c_str_raw, - size: size, - }) + Ok(StringInLua { + lua: lua, + c_str_raw: c_str_raw, + size: size, + }) + } } } @@ -282,15 +307,16 @@ impl Deref for StringInLua { let c_slice = unsafe { slice::from_raw_parts(self.c_str_raw as *const u8, self.size) }; match str::from_utf8(c_slice) { Ok(s) => s, - Err(_) => unreachable!() // Checked earlier + Err(_) => unreachable!(), // Checked earlier } } } impl<'lua, L> Push for bool - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { - type Err = Void; // TODO: use `!` instead (https://github.com/rust-lang/rust/issues/35121) + type Err = Void; // TODO: use `!` instead (https://github.com/rust-lang/rust/issues/35121) #[inline] fn push_to_lua(self, mut lua: L) -> Result, (Void, L)> { @@ -307,7 +333,8 @@ impl<'lua, L> Push for bool impl<'lua, L> PushOne for bool where L: AsMutLua<'lua> {} impl<'lua, L> LuaRead for bool - where L: AsLua<'lua> +where + L: AsLua<'lua>, { #[inline] fn lua_read_at_position(lua: L, index: i32) -> Result { @@ -320,9 +347,10 @@ impl<'lua, L> LuaRead for bool } impl<'lua, L> Push for () - where L: AsMutLua<'lua> +where + L: AsMutLua<'lua>, { - type Err = Void; // TODO: use `!` instead (https://github.com/rust-lang/rust/issues/35121) + type Err = Void; // TODO: use `!` instead (https://github.com/rust-lang/rust/issues/35121) #[inline] fn push_to_lua(self, lua: L) -> Result, (Void, L)> { @@ -337,7 +365,8 @@ impl<'lua, L> Push for () } impl<'lua, L> LuaRead for () - where L: AsLua<'lua> +where + L: AsLua<'lua>, { #[inline] fn lua_read_at_position(_: L, _: i32) -> Result<(), L> { @@ -346,8 +375,9 @@ impl<'lua, L> LuaRead for () } impl<'lua, L, T, E> Push for Option -where T: Push, - L: AsMutLua<'lua> +where + T: Push, + L: AsMutLua<'lua>, { type Err = E; @@ -361,15 +391,16 @@ where T: Push, } impl<'lua, L, T, E> PushOne for Option -where T: PushOne, - L: AsMutLua<'lua> +where + T: PushOne, + L: AsMutLua<'lua>, { } #[cfg(test)] mod tests { - use AnyLuaValue; use AnyLuaString; + use AnyLuaValue; use Lua; use StringInLua; @@ -465,9 +496,23 @@ mod tests { assert_eq!(lua.execute::("return 'abc'").unwrap(), "abc"); assert_eq!(lua.execute::("return #'abc'").unwrap(), 3); assert_eq!(lua.execute::("return #'a\\x00c'").unwrap(), 3); - assert_eq!(lua.execute::("return 'a\\x00c'").unwrap().0, vec!(97, 0, 99)); - assert_eq!(lua.execute::("return 'a\\x00c'").unwrap().0.len(), 3); - assert_eq!(lua.execute::("return '\\x01\\xff'").unwrap().0, vec!(1, 255)); + assert_eq!( + lua.execute::("return 'a\\x00c'").unwrap().0, + vec!(97, 0, 99) + ); + assert_eq!( + lua.execute::("return 'a\\x00c'") + .unwrap() + .0 + .len(), + 3 + ); + assert_eq!( + lua.execute::("return '\\x01\\xff'") + .unwrap() + .0, + vec!(1, 255) + ); lua.execute::("return 'a\\x00\\xc0'").unwrap_err(); } @@ -504,7 +549,7 @@ mod tests { let x: StringInLua<_> = lua.get("a").unwrap(); assert_eq!(&*x, "aaa"); } - + lua.set("a", 18); { let x: StringInLua<_> = lua.get("a").unwrap(); diff --git a/hlua/tests/userdata.rs b/hlua/tests/userdata.rs index eba6a55c..0dfe430e 100644 --- a/hlua/tests/userdata.rs +++ b/hlua/tests/userdata.rs @@ -5,7 +5,8 @@ fn readwrite() { #[derive(Clone)] struct Foo; impl<'lua, L> hlua::Push for Foo - where L: hlua::AsMutLua<'lua> + where + L: hlua::AsMutLua<'lua>, { type Err = hlua::Void; fn push_to_lua(self, lua: L) -> Result, (hlua::Void, L)> { @@ -14,7 +15,8 @@ fn readwrite() { } impl<'lua, L> hlua::PushOne for Foo where L: hlua::AsMutLua<'lua> {} impl<'lua, L> hlua::LuaRead for Foo - where L: hlua::AsMutLua<'lua> + where + L: hlua::AsMutLua<'lua>, { fn lua_read_at_position(lua: L, index: i32) -> Result { let val: Result, _> = @@ -47,7 +49,8 @@ fn destructor_called() { } impl<'lua, L> hlua::Push for Foo - where L: hlua::AsMutLua<'lua> + where + L: hlua::AsMutLua<'lua>, { type Err = hlua::Void; fn push_to_lua(self, lua: L) -> Result, (hlua::Void, L)> { @@ -58,7 +61,12 @@ fn destructor_called() { { let mut lua = hlua::Lua::new(); - lua.set("a", Foo { called: called.clone() }); + lua.set( + "a", + Foo { + called: called.clone(), + }, + ); } let locked = called.lock().unwrap(); @@ -70,7 +78,8 @@ fn type_check() { #[derive(Clone)] struct Foo; impl<'lua, L> hlua::Push for Foo - where L: hlua::AsMutLua<'lua> + where + L: hlua::AsMutLua<'lua>, { type Err = hlua::Void; fn push_to_lua(self, lua: L) -> Result, (hlua::Void, L)> { @@ -79,7 +88,8 @@ fn type_check() { } impl<'lua, L> hlua::PushOne for Foo where L: hlua::AsMutLua<'lua> {} impl<'lua, L> hlua::LuaRead for Foo - where L: hlua::AsMutLua<'lua> + where + L: hlua::AsMutLua<'lua>, { fn lua_read_at_position(lua: L, index: i32) -> Result { let val: Result, _> = @@ -91,7 +101,8 @@ fn type_check() { #[derive(Clone)] struct Bar; impl<'lua, L> hlua::Push for Bar - where L: hlua::AsMutLua<'lua> + where + L: hlua::AsMutLua<'lua>, { type Err = hlua::Void; fn push_to_lua(self, lua: L) -> Result, (hlua::Void, L)> { @@ -100,7 +111,8 @@ fn type_check() { } impl<'lua, L> hlua::PushOne for Bar where L: hlua::AsMutLua<'lua> {} impl<'lua, L> hlua::LuaRead for Bar - where L: hlua::AsMutLua<'lua> + where + L: hlua::AsMutLua<'lua>, { fn lua_read_at_position(lua: L, index: i32) -> Result { let val: Result, _> = @@ -122,13 +134,16 @@ fn metatables() { #[derive(Clone)] struct Foo; impl<'lua, L> hlua::Push for Foo - where L: hlua::AsMutLua<'lua> + where + L: hlua::AsMutLua<'lua>, { type Err = hlua::Void; fn push_to_lua(self, lua: L) -> Result, (hlua::Void, L)> { Ok(hlua::push_userdata(self, lua, |mut table| { - table.set("__index".to_string(), - vec![("test".to_string(), hlua::function0(|| 5))]); + table.set( + "__index".to_string(), + vec![("test".to_string(), hlua::function0(|| 5))], + ); })) } } @@ -147,16 +162,18 @@ fn multiple_userdata() { #[derive(Clone)] struct Integer(u32); impl<'lua, L> hlua::Push for Integer - where L: hlua::AsMutLua<'lua> + where + L: hlua::AsMutLua<'lua>, { type Err = hlua::Void; fn push_to_lua(self, lua: L) -> Result, (hlua::Void, L)> { - Ok(hlua::push_userdata(self, lua, |_| { })) + Ok(hlua::push_userdata(self, lua, |_| {})) } } impl<'lua, L> hlua::PushOne for Integer where L: hlua::AsMutLua<'lua> {} impl<'lua, L> hlua::LuaRead for Integer - where L: hlua::AsMutLua<'lua> + where + L: hlua::AsMutLua<'lua>, { fn lua_read_at_position(lua: L, index: i32) -> Result { let val: Result, _> = @@ -168,16 +185,18 @@ fn multiple_userdata() { #[derive(Debug, Clone, PartialEq, Eq)] struct BigInteger(u32, u32, u32, u32); impl<'lua, L> hlua::Push for BigInteger - where L: hlua::AsMutLua<'lua> + where + L: hlua::AsMutLua<'lua>, { type Err = hlua::Void; fn push_to_lua(self, lua: L) -> Result, (hlua::Void, L)> { - Ok(hlua::push_userdata(self, lua, |_| { })) + Ok(hlua::push_userdata(self, lua, |_| {})) } } impl<'lua, L> hlua::PushOne for BigInteger where L: hlua::AsMutLua<'lua> {} impl<'lua, L> hlua::LuaRead for BigInteger - where L: hlua::AsMutLua<'lua> + where + L: hlua::AsMutLua<'lua>, { fn lua_read_at_position(lua: L, index: i32) -> Result { let val: Result, _> = @@ -188,37 +207,71 @@ fn multiple_userdata() { let axpy_float = |a: f64, x: Integer, y: Integer| a * x.0 as f64 + y.0 as f64; let axpy_float_2 = |a: f64, x: Integer, y: f64| a * x.0 as f64 + y; - let broadcast_mul = |k: Integer, v: BigInteger| - BigInteger(k.0 * v.0, k.0 * v.1, k.0 * v.2, k.0 * v.3); - let collapse = |a: f32, k: Integer, v: BigInteger| - (k.0 * v.0) as f32 * a + (k.0 * v.1) as f32 * a + (k.0 * v.2) as f32 * a + (k.0 * v.3) as f32 * a; + let broadcast_mul = + |k: Integer, v: BigInteger| BigInteger(k.0 * v.0, k.0 * v.1, k.0 * v.2, k.0 * v.3); + let collapse = |a: f32, k: Integer, v: BigInteger| { + (k.0 * v.0) as f32 * a + + (k.0 * v.1) as f32 * a + + (k.0 * v.2) as f32 * a + + (k.0 * v.3) as f32 * a + }; let mut lua = hlua::Lua::new(); - let big_integer = BigInteger(531,246,1,953); + let big_integer = BigInteger(531, 246, 1, 953); lua.set("a", Integer(19)); lua.set("b", Integer(114)); lua.set("c", Integer(96)); lua.set("d", Integer(313)); lua.set("v", big_integer.clone()); - lua.set("add", hlua::function2(|x: Integer, y: Integer| Integer(x.0 + y.0))); - lua.set("axpy", hlua::function3(|a: Integer, x: Integer, y: Integer| - Integer(a.0 * x.0 + y.0))); + lua.set( + "add", + hlua::function2(|x: Integer, y: Integer| Integer(x.0 + y.0)), + ); + lua.set( + "axpy", + hlua::function3(|a: Integer, x: Integer, y: Integer| Integer(a.0 * x.0 + y.0)), + ); lua.set("axpy_float", hlua::function3(&axpy_float)); lua.set("axpy_float_2", hlua::function3(&axpy_float_2)); lua.set("broadcast_mul", hlua::function2(&broadcast_mul)); lua.set("collapse", hlua::function3(&collapse)); - assert_eq!(lua.execute::("return add(a, b)").unwrap().0, 19 + 114); - assert_eq!(lua.execute::("return add(b, c)").unwrap().0, 114 + 96); - assert_eq!(lua.execute::("return add(c, d)").unwrap().0, 96 + 313); - assert_eq!(lua.execute::("return axpy(a, b, c)").unwrap().0, 19 * 114 + 96); - assert_eq!(lua.execute::("return axpy(b, c, d)").unwrap().0, 114 * 96 + 313); - assert_eq!(lua.execute::("return axpy_float(2.5, c, d)").unwrap(), - axpy_float(2.5, Integer(96), Integer(313))); - assert_eq!(lua.execute::("return broadcast_mul(a, v)").unwrap(), - broadcast_mul(Integer(19), big_integer.clone())); - assert_eq!(lua.execute::("return broadcast_mul(b, v)").unwrap(), - broadcast_mul(Integer(114), big_integer.clone())); - assert_eq!(lua.execute::("return collapse(19.25, c, v)").unwrap(), - collapse(19.25, Integer(96), big_integer.clone())); + assert_eq!( + lua.execute::("return add(a, b)").unwrap().0, + 19 + 114 + ); + assert_eq!( + lua.execute::("return add(b, c)").unwrap().0, + 114 + 96 + ); + assert_eq!( + lua.execute::("return add(c, d)").unwrap().0, + 96 + 313 + ); + assert_eq!( + lua.execute::("return axpy(a, b, c)").unwrap().0, + 19 * 114 + 96 + ); + assert_eq!( + lua.execute::("return axpy(b, c, d)").unwrap().0, + 114 * 96 + 313 + ); + assert_eq!( + lua.execute::("return axpy_float(2.5, c, d)").unwrap(), + axpy_float(2.5, Integer(96), Integer(313)) + ); + assert_eq!( + lua.execute::("return broadcast_mul(a, v)") + .unwrap(), + broadcast_mul(Integer(19), big_integer.clone()) + ); + assert_eq!( + lua.execute::("return broadcast_mul(b, v)") + .unwrap(), + broadcast_mul(Integer(114), big_integer.clone()) + ); + assert_eq!( + lua.execute::("return collapse(19.25, c, v)").unwrap(), + collapse(19.25, Integer(96), big_integer.clone()) + ); } diff --git a/lua52-sys/build.rs b/lua52-sys/build.rs index 5b762d8b..069603f8 100644 --- a/lua52-sys/build.rs +++ b/lua52-sys/build.rs @@ -1,5 +1,5 @@ -extern crate pkg_config; extern crate cc; +extern crate pkg_config; use std::env; diff --git a/lua52-sys/src/lib.rs b/lua52-sys/src/lib.rs index 64a40e45..a2975c2a 100644 --- a/lua52-sys/src/lib.rs +++ b/lua52-sys/src/lib.rs @@ -10,7 +10,7 @@ use std::{default, ptr}; pub const MULTRET: c_int = -1; -pub const LUAI_MAXSTACK: c_int = 1000000; // or 15000 with 32b // TODO: +pub const LUAI_MAXSTACK: c_int = 1000000; // or 15000 with 32b // TODO: pub const LUAI_FIRSTPSEUDOIDX: c_int = (-LUAI_MAXSTACK - 1000); pub const LUA_REGISTRYINDEX: c_int = LUAI_FIRSTPSEUDOIDX; @@ -28,14 +28,27 @@ pub struct lua_State; pub type lua_CFunction = extern "C" fn(L: *mut lua_State) -> c_int; -pub type lua_Reader = extern "C" fn(L: *mut lua_State, ud: *mut libc::c_void, sz: *mut libc::size_t) -> *const libc::c_char; -pub type lua_Writer = extern "C" fn(L: *mut lua_State, p: *const libc::c_void, sz: libc::size_t, ud: *mut libc::c_void) -> libc::c_int; - -pub type lua_Alloc = extern "C" fn(ud: *mut libc::c_void, ptr: *mut libc::c_void, osize: libc::size_t, nsize: libc::size_t) -> *mut libc::c_void; +pub type lua_Reader = extern "C" fn( + L: *mut lua_State, + ud: *mut libc::c_void, + sz: *mut libc::size_t, +) -> *const libc::c_char; +pub type lua_Writer = extern "C" fn( + L: *mut lua_State, + p: *const libc::c_void, + sz: libc::size_t, + ud: *mut libc::c_void, +) -> libc::c_int; + +pub type lua_Alloc = extern "C" fn( + ud: *mut libc::c_void, + ptr: *mut libc::c_void, + osize: libc::size_t, + nsize: libc::size_t, +) -> *mut libc::c_void; pub type lua_Hook = extern "C" fn(L: *mut lua_State, ar: *mut lua_Debug); - pub const LUA_TNONE: c_int = -1; pub const LUA_TNIL: c_int = 0; @@ -111,7 +124,7 @@ pub struct lua_Debug { pub nparams: libc::c_uchar, pub isvararg: libc::c_char, pub istailcall: libc::c_char, - pub short_src: [libc::c_char ; 60], + pub short_src: [libc::c_char; 60], //i_ci: *CallInfo } @@ -147,7 +160,11 @@ extern "C" { pub fn lua_tointegerx(L: *mut lua_State, idx: c_int, isnum: *mut c_int) -> lua_Integer; pub fn lua_tounsignedx(L: *mut lua_State, idx: c_int, isnum: *mut c_int) -> lua_Unsigned; pub fn lua_toboolean(L: *mut lua_State, idx: c_int) -> c_int; - pub fn lua_tolstring(L: *mut lua_State, idx: c_int, len: *mut libc::size_t) -> *const libc::c_char; + pub fn lua_tolstring( + L: *mut lua_State, + idx: c_int, + len: *mut libc::size_t, + ) -> *const libc::c_char; pub fn lua_rawlen(L: *mut lua_State, idx: c_int) -> libc::size_t; pub fn lua_tocfunction(L: *mut lua_State, idx: c_int) -> Option; pub fn lua_touserdata(L: *mut lua_State, idx: c_int) -> *mut libc::c_void; @@ -165,7 +182,8 @@ extern "C" { pub fn lua_pushlstring(L: *mut lua_State, s: *const libc::c_char, l: libc::size_t); pub fn lua_pushstring(L: *mut lua_State, s: *const libc::c_char); // TODO: lua_pushvfstring() - pub fn lua_pushfstring(L: *mut lua_State, fmt: *const libc::c_char, ...) -> *const libc::c_char; + pub fn lua_pushfstring(L: *mut lua_State, fmt: *const libc::c_char, ...) + -> *const libc::c_char; pub fn lua_pushcclosure(L: *mut lua_State, f: lua_CFunction, n: c_int); pub fn lua_pushboolean(L: *mut lua_State, b: c_int); pub fn lua_pushlightuserdata(L: *mut lua_State, p: *mut libc::c_void); @@ -191,13 +209,37 @@ extern "C" { pub fn lua_setmetatable(L: *mut lua_State, objindex: c_int) -> c_int; pub fn lua_setfenv(L: *mut lua_State, idx: c_int) -> c_int; - pub fn lua_callk(L: *mut lua_State, nargs: c_int, nresults: c_int, ctx: c_int, k: Option); + pub fn lua_callk( + L: *mut lua_State, + nargs: c_int, + nresults: c_int, + ctx: c_int, + k: Option, + ); pub fn lua_getctx(L: *mut lua_State, ctx: c_int) -> c_int; - pub fn lua_pcallk(L: *mut lua_State, nargs: c_int, nresults: c_int, errfunc: c_int, ctx: c_int, k: Option) -> c_int; - pub fn lua_load(L: *mut lua_State, reader: lua_Reader, dt: *mut libc::c_void, chunkname: *const libc::c_char, mode: *const libc::c_char) -> c_int; + pub fn lua_pcallk( + L: *mut lua_State, + nargs: c_int, + nresults: c_int, + errfunc: c_int, + ctx: c_int, + k: Option, + ) -> c_int; + pub fn lua_load( + L: *mut lua_State, + reader: lua_Reader, + dt: *mut libc::c_void, + chunkname: *const libc::c_char, + mode: *const libc::c_char, + ) -> c_int; pub fn lua_dump(L: *mut lua_State, writer: lua_Writer, data: *mut libc::c_void) -> c_int; - pub fn lua_yieldk(L: *mut lua_State, nresults: c_int, ctx: c_int, k: Option) -> c_int; + pub fn lua_yieldk( + L: *mut lua_State, + nresults: c_int, + ctx: c_int, + k: Option, + ) -> c_int; pub fn lua_resume(L: *mut lua_State, from: *mut lua_State, narg: c_int) -> c_int; pub fn lua_status(L: *mut lua_State) -> c_int; @@ -264,7 +306,7 @@ pub unsafe fn lua_yield(L: *mut lua_State, nresults: c_int) -> c_int { #[inline(always)] pub unsafe fn lua_pop(L: *mut lua_State, n: c_int) { - lua_settop(L, -n-1) + lua_settop(L, -n - 1) } #[inline(always)] @@ -335,10 +377,9 @@ pub unsafe fn lua_tostring(L: *mut lua_State, i: c_int) -> *const libc::c_char { lua_tolstring(L, i, ptr::null_mut()) } - impl default::Default for lua_Debug { fn default() -> lua_Debug { - lua_Debug{ + lua_Debug { event: 0, name: ptr::null(), namewhat: ptr::null(), @@ -351,7 +392,7 @@ impl default::Default for lua_Debug { nparams: 0, isvararg: 0, istailcall: 0, - short_src: [0 ; 60] + short_src: [0; 60], } } } diff --git a/rust-hl-lua-modules/Cargo.toml b/rust-hl-lua-modules/Cargo.toml deleted file mode 100644 index e05ddbe5..00000000 --- a/rust-hl-lua-modules/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] - -name = "rust-hl-lua-modules" -version = "0.1.0" -authors = [ "pierre.krieger1708@gmail.com" ] - -[lib] -name = "rust_hl_lua_modules" -crate_type = ["dylib"] -plugin = true - -[dependencies.hlua] -path = "../hlua" diff --git a/rust-hl-lua-modules/README.md b/rust-hl-lua-modules/README.md deleted file mode 100644 index 9703647a..00000000 --- a/rust-hl-lua-modules/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Note - -This crate doesn't compile. - -In order to work it needs to use compiler plugins, which are still unstable in Rust. -In addition to this the crate hasn't been updated for more than a year, so even if you use a -nightly version of Rust it still won't compile. diff --git a/rust-hl-lua-modules/example/Cargo.toml b/rust-hl-lua-modules/example/Cargo.toml deleted file mode 100644 index d049327b..00000000 --- a/rust-hl-lua-modules/example/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] - -name = "modules-test" -version = "0.1.0" -authors = [ "pierre.krieger1708@gmail.com" ] - -[lib] -name = "mylib" -crate_type = ["dylib"] -path = "module_test.rs" - -[dependencies.rust-hl-lua-modules] -path = ".." diff --git a/rust-hl-lua-modules/example/module_test.rs b/rust-hl-lua-modules/example/module_test.rs deleted file mode 100644 index e9d8bf84..00000000 --- a/rust-hl-lua-modules/example/module_test.rs +++ /dev/null @@ -1,19 +0,0 @@ -#![crate_type = "dylib"] -#![feature(phase)] - -#[phase(plugin)] -extern crate "rust-hl-lua-modules" as lua; - -#[export_lua_module] -pub mod mylib { - static PI:f32 = 3.141592; - - fn function1(a: int, b: int) -> int { a + b } - - fn function2(a: int) -> int { a + 5 } - - #[lua_module_init] - fn init() { - println!("mylib is now loaded!") - } -} diff --git a/rust-hl-lua-modules/src/rust-hl-lua-modules.rs b/rust-hl-lua-modules/src/rust-hl-lua-modules.rs deleted file mode 100644 index ca0271ac..00000000 --- a/rust-hl-lua-modules/src/rust-hl-lua-modules.rs +++ /dev/null @@ -1,234 +0,0 @@ -#![crate_name = "rust-hl-lua-modules"] -#![feature(plugin_registrar)] -#![feature(quote)] - -extern crate rustc; -extern crate syntax; - -use syntax::ast; -use syntax::ast::Item; -use syntax::attr::AttrMetaMethods; -use syntax::codemap; -use syntax::ext::build::AstBuilder; -use syntax::ext::base; -use syntax::ext::quote::rt::ToSource; -use syntax::parse::token; -use syntax::ptr::P; - -#[plugin_registrar] -#[doc(hidden)] -pub fn plugin_registrar(reg: &mut ::rustc::plugin::Registry) { - reg.register_syntax_extension(token::intern("export_lua_module"), - base::Modifier(box expand_lua_module)); -} - -// handler for export_lua_module -pub fn expand_lua_module(ecx: &mut base::ExtCtxt, span: codemap::Span, - _: &ast::MetaItem, input_item: P) - -> P -{ - let ecx: &base::ExtCtxt = &*ecx; - - // checking that the input item is a module - // and creating the new item that will be returned by the function - let (module, mut new_item) = match input_item.node { - ast::ItemMod(ref module) => { - (module, module.clone()) - }, - _ => { - ecx.span_err(input_item.span, - "`export_lua_module` extension is only allowed on modules"); - return ecx.item_mod(span.clone(), span.clone(), ecx.ident_of("dummy"), vec![], - vec![], vec![]); - } - }; - - // cleaning the content of `new_item` - new_item.items.clear(); - - // creating an array of the statements to add to the main Lua entry point - let module_handler_body: Vec> = { - let mut module_handler_body = Vec::new(); - - // iterating over elements inside the module - for moditem in module.items.iter() { - let moditem_name = moditem.ident.to_source(); - - match moditem.node { - ast::ItemFn(ref decl, ref style, ref abi, ref generics, ref block) => { - let moditem_name_slice = moditem_name.as_slice(); - let moditem_name_item = ecx.ident_of(moditem_name_slice); - - module_handler_body.push( - quote_stmt!(&*ecx, - table.set($moditem_name_slice.to_string(), $moditem_name_item); - ) - ); - - new_item.items.push(ecx.item( - span.clone(), - moditem.ident.clone(), - moditem.attrs.clone(), - ast::ItemFn( - decl.clone(), - style.clone(), - abi.clone(), - generics.clone(), - ecx.block_expr( - quote_expr!(&*ecx, - { - let (tx, rx) = channel(); - native::start(0, core::ptr::null(), proc() { - tx.send({ - $block - }) - }); - rx.recv() - } - ) - ) - ) - )); - }, - - ast::ItemStatic(..) => { - let moditem_name_slice = moditem_name.as_slice(); - let moditem_name_item = ecx.ident_of(moditem_name_slice); - - module_handler_body.push( - quote_stmt!(&*ecx, - table.set($moditem_name_slice.to_string(), $moditem_name_item); - ) - ); - - new_item.items.push(moditem.clone()); - }, - - _ => { - ecx.span_warn(moditem.span, - format!("item `{}` is neiter a function nor a static - and will thus be ignored by `export_lua_module`", - moditem_name).as_slice()); - new_item.items.push(moditem.clone()); - continue; - } - }; - - // handling lua_module_init - if moditem.attrs.iter().find(|at| at.check_name("lua_module_init")).is_some() { - let moditem_name_item = ecx.ident_of(moditem.ident.to_source().as_slice()); - module_handler_body.push( - quote_stmt!(ecx, $moditem_name_item()) - ); - } - } - - module_handler_body - }; - - // adding extern crate declarations - { - let view_items = quote_item!(ecx, - mod x { - extern crate core; - extern crate "rust-hl-lua" as lua; - extern crate libc; - extern crate native; - } - ); - - let view_items = match view_items { - Some(a) => a, - None => { - ecx.span_err(input_item.span, - "internal error in the library (could not parse view items)"); - return ecx.item_mod(span.clone(), span.clone(), ecx.ident_of("dummy"), vec![], - vec![], vec![]); - } - }; - - // getting all the items - let view_items = match view_items.node { - ast::ItemMod(ref m) => m, - _ => { - ecx.span_err(span, "internal error in the library"); - return ecx.item_mod(span.clone(), span.clone(), ecx.ident_of("dummy"), vec![], - vec![], vec![]); - } - }; - - for i in view_items.view_items.iter() { - new_item.view_items.insert(0, i.clone()) - } - } - - // generating the function that we will add inside the module - { - let function_body = { - let mut function_body = Vec::new(); - - function_body.push(quote_stmt!(ecx, - let mut lua = self::lua::Lua::from_existing_state(lua, false); - )); - - function_body.push(quote_stmt!(ecx, - let mut table = lua.load_new_table(); - )); - - function_body.extend(module_handler_body.into_iter()); - - function_body.push(quote_stmt!(ecx, - ::std::mem::forget(table); - )); - - ecx.block(span.clone(), function_body, Some( - quote_expr!(ecx, 1) - )) - }; - - // identifier for "luaopen_mylib" - let luaopen_id = ecx.ident_of(format!("luaopen_{}", input_item.ident.to_source()) - .as_slice()); - - // building the function itself - let function = quote_item!(ecx, - #[no_mangle] - pub extern "C" fn $luaopen_id(lua: *mut self::libc::c_void) - -> self::libc::c_int { - unsafe { - $function_body - } - } - ); - - let function = match function { - Some(f) => f, - None => { - ecx.span_err(input_item.span, - "internal error in the library (could not parse function body)"); - return ecx.item_mod(span.clone(), span.clone(), ecx.ident_of("dummy"), vec![], - vec![], vec![]); - } - }; - - // adding the function to the module - new_item.items.push(function); - } - - // returning - ecx.item( - span.clone(), - input_item.ident.clone(), - input_item.attrs.clone(), - ast::ItemMod(new_item) - ).map(|mut item| { - item.vis = { - if input_item.vis != ast::Public { - ecx.span_warn(input_item.span, - "`export_lua_module` will turn the module into a public module"); - } - ast::Public - }; - item - }) -}