diff --git a/Cargo.lock b/Cargo.lock index 57241c02b..7110014ef 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -277,6 +277,15 @@ dependencies = [ "alloc-stdlib", ] +[[package]] +name = "bstr" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "502ae1441a0a5adb8fbd38a5955a6416b9493e92b465de5e4a9bde6a539c2c48" +dependencies = [ + "memchr", +] + [[package]] name = "bumpalo" version = "3.2.0" @@ -1419,6 +1428,24 @@ dependencies = [ "hashbrown 0.6.3", ] +[[package]] +name = "lua-src" +version = "535.0.1+540b" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d7c4f629087ac894e7b542b4049fb527472f2458c823900f79a0bde0b202e62" +dependencies = [ + "cc", +] + +[[package]] +name = "luajit-src" +version = "210.0.0+694d69a" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d84f30aba8908dba49f46e6d2470c7018e5f60418edf3fc91a4f251238b20c" +dependencies = [ + "cc", +] + [[package]] name = "lyon_geom" version = "0.14.1" @@ -1615,6 +1642,20 @@ dependencies = [ "winapi 0.3.8", ] +[[package]] +name = "mlua" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "869c35a04c6b414eee44268afb7c75a4904ffeb31cf3b27a5c7bc10d1fe62cca" +dependencies = [ + "bstr", + "cc", + "lua-src", + "luajit-src", + "num-traits 0.2.11", + "pkg-config", +] + [[package]] name = "net2" version = "0.2.33" @@ -3448,6 +3489,7 @@ dependencies = [ "log", "lru", "metrics", + "mlua", "notify", "notify-rust", "open", diff --git a/Cargo.toml b/Cargo.toml index b07d8d5fa..700282fea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,6 +40,7 @@ log = "0.4" lru = "0.4" open = "1.2" metrics = { version="0.12", features=["std"]} +mlua = {version="0.2", features=["vendored"]} hdrhistogram = "6.3" openssl = "0.10" # file change notification diff --git a/src/config/mod.rs b/src/config/mod.rs index 8ebd5bde1..b7fcbd110 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -43,7 +43,7 @@ pub use tls::*; pub use unix::*; lazy_static! { - static ref HOME_DIR: PathBuf = dirs::home_dir().expect("can't find HOME dir"); + pub static ref HOME_DIR: PathBuf = dirs::home_dir().expect("can't find HOME dir"); static ref RUNTIME_DIR: PathBuf = compute_runtime_dir().unwrap(); static ref CONFIG: Configuration = Configuration::new(); } @@ -549,10 +549,12 @@ impl Config { // multiple. In addition, it spawns a lot of subprocesses, // so we do this bit "by-hand" let mut paths = vec![ + HOME_DIR.join(".config").join("wezterm").join("wezterm.lua"), HOME_DIR .join(".config") .join("wezterm") .join("wezterm.toml"), + HOME_DIR.join(".wezterm.lua"), HOME_DIR.join(".wezterm.toml"), ]; if cfg!(windows) { @@ -566,7 +568,8 @@ impl Config { // dir as the executable that will take precedence. if let Ok(exe_name) = std::env::current_exe() { if let Some(exe_dir) = exe_name.parent() { - paths.insert(0, exe_dir.join("wezterm.toml")); + paths.insert(0, exe_dir.join("wezterm.lua")); + paths.insert(1, exe_dir.join("wezterm.toml")); } } } @@ -587,8 +590,26 @@ impl Config { let mut s = String::new(); file.read_to_string(&mut s)?; - let cfg: Self = toml::from_str(&s) - .with_context(|| format!("Error parsing TOML from {}", p.display()))?; + let cfg: Self; + + if p.extension() == Some(OsStr::new("toml")) { + cfg = toml::from_str(&s) + .with_context(|| format!("Error parsing TOML from {}", p.display()))?; + } else if p.extension() == Some(OsStr::new("lua")) { + let lua = crate::scripting::make_lua_context(p)?; + let config: mlua::Value = lua + .load(&s) + .set_name(p.to_string_lossy().as_bytes())? + .eval()?; + cfg = crate::scripting::from_lua_value(config).with_context(|| { + format!( + "Error converting lua value returned by script {} to Config struct", + p.display() + ) + })?; + } else { + unreachable!(); + } // Compute but discard the key bindings here so that we raise any // problems earlier than we use them. diff --git a/src/main.rs b/src/main.rs index 00aad28c4..affe0726a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -25,6 +25,7 @@ mod keyassignment; mod localtab; mod mux; mod ratelim; +mod scripting; mod server; mod ssh; mod stats; diff --git a/src/scripting/mod.rs b/src/scripting/mod.rs new file mode 100644 index 000000000..1430ca6ff --- /dev/null +++ b/src/scripting/mod.rs @@ -0,0 +1,96 @@ +use anyhow::anyhow; +use mlua::{Lua, Table}; +use std::path::Path; + +mod serde_lua; + +pub use serde_lua::from_lua_value; + +/// Set up a lua context for executing some code. +/// The path to the directory containing the configuration is +/// passed in and is used to pre-set some global values in +/// the environment. +/// +/// The `package.path` is configured to search the user's +/// wezterm specific config paths for lua modules, should +/// they choose to `require` additional code from their config. +/// +/// A `wezterm` module is registered so that the script can +/// `require "wezterm"` and call into functions provided by +/// wezterm. The wezterm module contains: +/// * `executable_dir` - the directory containing the wezterm +/// executable. This is potentially useful for portable +/// installs on Windows. +/// * `config_dir` - the directory containing the wezterm +/// configuration. +/// * `log_error` - a function that logs to stderr (or the server +/// log file for daemonized wezterm). +/// * `target_triple` - the rust compilation target triple. +/// * `version` - the version of the running wezterm instance. +/// * `home_dir` - the path to the user's home directory +/// +/// In addition to this, the lua standard library, except for +/// the `debug` module, is also available to the script. +pub fn make_lua_context(config_dir: &Path) -> anyhow::Result { + let lua = Lua::new(); + + { + let globals = lua.globals(); + // This table will be the `wezterm` module in the script + let wezterm_mod = lua.create_table()?; + + let package: Table = globals.get("package")?; + let package_path: String = package.get("path")?; + let mut path_array: Vec = package_path.split(";").map(|s| s.to_owned()).collect(); + + fn prefix_path(array: &mut Vec, path: &Path) { + array.insert(0, format!("{}/?.lua", path.display())); + array.insert(1, format!("{}/?/init.lua", path.display())); + } + + prefix_path(&mut path_array, &crate::config::HOME_DIR.join(".wezterm")); + prefix_path( + &mut path_array, + &crate::config::HOME_DIR.join(".config").join("wezterm"), + ); + if let Ok(exe) = std::env::current_exe() { + if let Some(path) = exe.parent() { + wezterm_mod.set( + "executable_dir", + path.to_str().ok_or_else(|| anyhow!("path is not UTF-8"))?, + )?; + if cfg!(windows) { + // For a portable windows install, force in this path ahead + // of the rest + prefix_path(&mut path_array, &path.join("wezterm_modules")); + } + } + } + + wezterm_mod.set( + "config_dir", + config_dir + .to_str() + .ok_or_else(|| anyhow!("config dir path is not UTF-8"))?, + )?; + + wezterm_mod.set("target_triple", env!("VERGEN_TARGET_TRIPLE"))?; + wezterm_mod.set("version", crate::wezterm_version())?; + wezterm_mod.set("home_dir", crate::config::HOME_DIR.to_str())?; + + wezterm_mod.set( + "log_error", + lua.create_function(|_, msg: String| { + log::error!("lua: {}", msg); + Ok(()) + })?, + )?; + + package.set("path", path_array.join(";"))?; + + let loaded: Table = package.get("loaded")?; + loaded.set("wezterm", wezterm_mod)?; + } + + Ok(lua) +} diff --git a/src/scripting/serde_lua.rs b/src/scripting/serde_lua.rs new file mode 100644 index 000000000..e9b70a36c --- /dev/null +++ b/src/scripting/serde_lua.rs @@ -0,0 +1,699 @@ +use mlua::{Table, Value}; +use serde::de::value::{MapDeserializer, SeqDeserializer}; +use serde::de::{ + DeserializeOwned, DeserializeSeed, Deserializer, EnumAccess, Error as SerdeDeError, + IntoDeserializer, Unexpected, VariantAccess, Visitor, +}; +use serde::{serde_if_integer128, Deserialize}; +use std::convert::TryInto; +use thiserror::*; + +/// This is the key function from this module; it uses serde to +/// "parse" a lua value into a Rust type that implements Deserialize. +pub fn from_lua_value(value: Value) -> Result +where + T: DeserializeOwned, +{ + T::deserialize(ValueWrapper(value)) +} + +fn unexpected<'lua>(v: &'lua Value<'lua>) -> Unexpected<'lua> { + match v { + Value::Nil => Unexpected::Other("lua nil"), + Value::Boolean(b) => Unexpected::Bool(*b), + Value::LightUserData(_) => Unexpected::Other("lua lightuserdata"), + Value::Integer(i) => Unexpected::Signed(*i), + Value::Number(n) => Unexpected::Float(*n), + Value::String(s) => match s.to_str() { + Ok(s) => Unexpected::Str(s), + Err(_) => Unexpected::Bytes(s.as_bytes()), + }, + Value::Table(t) => match t.contains_key(1) { + Ok(true) => Unexpected::Other("lua array-like table"), + Ok(false) => Unexpected::Other("lua map-like table"), + Err(_) => Unexpected::Other( + "lua table (but encountered an error while testing if it is array- or map-like)", + ), + }, + Value::Function(_) => Unexpected::Other("lua function"), + Value::Thread(_) => Unexpected::Other("lua thread"), + Value::UserData(_) => Unexpected::Other("lua userdata"), + Value::Error(_) => Unexpected::Other("lua error"), + } +} + +#[derive(Debug, Error)] +pub enum Error { + #[error("{:?}", msg)] + Custom { msg: String }, +} + +impl SerdeDeError for Error { + fn custom(msg: T) -> Self { + Error::Custom { + msg: msg.to_string(), + } + } +} + +#[derive(Debug)] +struct ValueWrapper<'lua>(Value<'lua>); + +impl<'de, 'lua> IntoDeserializer<'de, Error> for ValueWrapper<'lua> { + type Deserializer = Self; + + fn into_deserializer(self) -> Self { + self + } +} + +fn visit_table<'de, 'lua, V>(table: Table<'lua>, visitor: V) -> Result +where + V: Visitor<'de>, +{ + // First we need to determine whether this table looks like an array + // or whether it looks like a map. Lua allows for either or both in + // the same table. + // Since array like tables start with index 1 we look for that key + // and assume that if it has that that it is an array. + if let Ok(true) = table.contains_key(1) { + // Treat it as an array + let mut values = vec![]; + for value in table.sequence_values() { + match value { + Ok(value) => values.push(ValueWrapper(value)), + Err(err) => { + return Err(Error::custom(format!( + "while retrieving an array element: {}", + err + ))) + } + } + } + + let mut deser = SeqDeserializer::new(values.into_iter()); + let seq = match visitor.visit_seq(&mut deser) { + Ok(seq) => seq, + Err(err) => return Err(err), + }; + + deser.end()?; + Ok(seq) + } else { + // Treat it as a map + let mut pairs = vec![]; + for pair in table.pairs::() { + match pair { + Ok(pair) => pairs.push((pair.0, ValueWrapper(pair.1))), + Err(err) => { + return Err(Error::custom(format!( + "while retrieving map element: {}", + err + ))) + } + } + } + let mut deser = MapDeserializer::new(pairs.into_iter()); + let seq = match visitor.visit_map(&mut deser) { + Ok(seq) => seq, + Err(err) => return Err(err), + }; + + deser.end()?; + Ok(seq) + } +} + +macro_rules! int { + ($name:ident, $ty:ty, $visit:ident) => { + fn $name(self, v: V) -> Result + where + V: Visitor<'de>, + { + match self.0 { + Value::Integer(i) => { + v.$visit(i .try_into().map_err(|e| { + Error::custom(format!( + "lua Integer value {} doesn't fit \ + in specified type: {}", i, e)) + })?) + } + _ => Err(serde::de::Error::invalid_type(unexpected(&self.0), &"integer")), + } + } + } +} + +impl<'de, 'lua> Deserializer<'de> for ValueWrapper<'lua> { + type Error = Error; + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.0 { + Value::Nil => visitor.visit_unit(), + Value::Boolean(v) => visitor.visit_bool(v), + Value::Integer(i) => visitor.visit_i64(i), + Value::Number(n) => visitor.visit_f64(n), + Value::String(s) => match s.to_str() { + Ok(s) => visitor.visit_str(s), + Err(_) => visitor.visit_bytes(s.as_bytes()), + }, + Value::Table(t) => visit_table(t, visitor), + Value::UserData(_) | Value::LightUserData(_) => Err(Error::custom( + "cannot represent userdata in the serde data model", + )), + Value::Thread(_) => Err(Error::custom( + "cannot represent thread in the serde data model", + )), + Value::Function(_) => Err(Error::custom( + "cannot represent lua function in the serde data model", + )), + Value::Error(e) => Err(Error::custom(format!( + "cannot represent lua error {} in the serde data model", + e + ))), + } + } + + fn deserialize_bool(self, v: V) -> Result + where + V: Visitor<'de>, + { + match self.0 { + Value::Boolean(b) => v.visit_bool(b), + _ => Err(serde::de::Error::invalid_type(unexpected(&self.0), &"bool")), + } + } + + fn deserialize_option(self, v: V) -> Result + where + V: Visitor<'de>, + { + match self.0 { + Value::Nil => v.visit_none(), + _ => v.visit_some(self), + } + } + + fn deserialize_unit(self, v: V) -> Result + where + V: Visitor<'de>, + { + match self.0 { + Value::Nil => v.visit_unit(), + _ => v.visit_some(self), + } + } + + fn deserialize_ignored_any(self, v: V) -> Result + where + V: Visitor<'de>, + { + v.visit_unit() + } + + fn deserialize_unit_struct(self, _name: &str, v: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_unit(v) + } + + fn deserialize_newtype_struct(self, _name: &str, v: V) -> Result + where + V: Visitor<'de>, + { + v.visit_newtype_struct(self) + } + + fn deserialize_char(self, v: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_string(v) + } + + fn deserialize_str(self, v: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_string(v) + } + + fn deserialize_identifier(self, v: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_string(v) + } + + fn deserialize_string(self, v: V) -> Result + where + V: Visitor<'de>, + { + match self.0 { + Value::String(s) => match s.to_str() { + Ok(s) => v.visit_str(s), + Err(_) => Err(Error::custom( + "expected String but found a non-UTF8 lua string", + )), + }, + _ => Err(serde::de::Error::invalid_type( + unexpected(&self.0), + &"string", + )), + } + } + + fn deserialize_bytes(self, v: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_byte_buf(v) + } + + fn deserialize_byte_buf(self, v: V) -> Result + where + V: Visitor<'de>, + { + match self.0 { + Value::String(s) => match s.to_str() { + Ok(s) => v.visit_str(s), + Err(_) => v.visit_bytes(s.as_bytes()), + }, + _ => Err(serde::de::Error::invalid_type( + unexpected(&self.0), + &"bytes", + )), + } + } + + fn deserialize_seq(self, v: V) -> Result + where + V: Visitor<'de>, + { + match self.0 { + Value::Table(t) => visit_table(t, v), + _ => Err(serde::de::Error::invalid_type( + unexpected(&self.0), + &"sequence/array", + )), + } + } + + fn deserialize_tuple(self, _len: usize, v: V) -> Result + where + V: Visitor<'de>, + { + self.deserialize_seq(v) + } + + fn deserialize_tuple_struct( + self, + _name: &'static str, + _len: usize, + v: V, + ) -> Result + where + V: Visitor<'de>, + { + self.deserialize_seq(v) + } + + int!(deserialize_i8, i8, visit_i8); + int!(deserialize_u8, u8, visit_u8); + int!(deserialize_i16, i16, visit_i16); + int!(deserialize_u16, u16, visit_u16); + int!(deserialize_i32, i32, visit_i32); + int!(deserialize_u32, u32, visit_u32); + int!(deserialize_i64, i64, visit_i64); + int!(deserialize_u64, u64, visit_u64); + + serde_if_integer128! { + int!(deserialize_i128, i128, visit_i128); + int!(deserialize_u128, u128, visit_u128); + } + + fn deserialize_f64(self, v: V) -> Result + where + V: Visitor<'de>, + { + match self.0 { + Value::Number(i) => v.visit_f64(i), + _ => Err(serde::de::Error::invalid_type( + unexpected(&self.0), + &"floating point number", + )), + } + } + + fn deserialize_f32(self, v: V) -> Result + where + V: Visitor<'de>, + { + match self.0 { + Value::Number(i) => v.visit_f32(i as f32), + _ => Err(serde::de::Error::invalid_type( + unexpected(&self.0), + &"floating point number", + )), + } + } + + fn deserialize_enum( + self, + _name: &str, + _variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + let (variant, value) = match self.0 { + Value::Table(t) => { + let mut iter = t.pairs::(); + let (variant, value) = match iter.next() { + Some(Ok(v)) => v, + Some(Err(e)) => { + return Err(Error::custom(format!( + "failed to retrieve enum pair from map: {}", + e + ))); + } + None => { + return Err(serde::de::Error::invalid_value( + Unexpected::Map, + &"map with a single key", + )); + } + }; + + // enums are encoded in serde_json as maps with a single + // key:value pair, so we mirror that here + if iter.next().is_some() { + return Err(serde::de::Error::invalid_value( + Unexpected::Map, + &"map with a single key", + )); + } + (variant, Some(value)) + } + Value::String(s) => match s.to_str() { + Ok(s) => (s.to_owned(), None), + Err(_) => { + return Err(serde::de::Error::invalid_value( + Unexpected::Bytes(s.as_bytes()), + &"UTF-8 string key", + )) + } + }, + _ => { + return Err(serde::de::Error::invalid_type( + Unexpected::Other("?"), + &"string or map", + )); + } + }; + + visitor.visit_enum(EnumDeserializer { variant, value }) + } + + fn deserialize_map(self, v: V) -> Result + where + V: Visitor<'de>, + { + match self.0 { + Value::Table(t) => visit_table(t, v), + _ => Err(serde::de::Error::invalid_type( + unexpected(&self.0), + &"a map", + )), + } + } + + fn deserialize_struct( + self, + name: &'static str, + fields: &'static [&'static str], + v: V, + ) -> Result + where + V: Visitor<'de>, + { + match self.0 { + Value::Table(t) => match visit_table(t, v) { + Ok(v) => Ok(v), + Err(err) => Err(Error::custom(format!( + "{} (while processing a struct of type {} and fields named {:?})", + err, name, fields + ))), + }, + _ => Err(serde::de::Error::invalid_type( + unexpected(&self.0), + &"a map", + )), + } + } +} + +struct EnumDeserializer<'lua> { + variant: String, + value: Option>, +} + +impl<'de, 'lua> EnumAccess<'de> for EnumDeserializer<'lua> { + type Error = Error; + type Variant = VariantDeserializer<'lua>; + + fn variant_seed(self, seed: V) -> Result<(V::Value, VariantDeserializer<'lua>), Error> + where + V: DeserializeSeed<'de>, + { + let variant = self.variant.into_deserializer(); + let visitor = VariantDeserializer { value: self.value }; + seed.deserialize(variant).map(|v| (v, visitor)) + } +} + +struct VariantDeserializer<'lua> { + value: Option>, +} + +impl<'de, 'lua> VariantAccess<'de> for VariantDeserializer<'lua> { + type Error = Error; + + fn unit_variant(self) -> Result<(), Error> { + match self.value { + Some(value) => Deserialize::deserialize(ValueWrapper(value)), + None => Ok(()), + } + } + + fn newtype_variant_seed(self, seed: T) -> Result + where + T: DeserializeSeed<'de>, + { + match self.value { + Some(value) => seed.deserialize(ValueWrapper(value)), + None => Err(serde::de::Error::invalid_type( + Unexpected::UnitVariant, + &"newtype variant", + )), + } + } + + fn tuple_variant(self, _len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + match self.value { + Some(Value::Table(table)) => { + if let Ok(true) = table.contains_key(1) { + let mut values = vec![]; + for value in table.sequence_values() { + match value { + Ok(value) => values.push(ValueWrapper(value)), + Err(err) => { + return Err(Error::custom(format!( + "while retrieving an array element: {}", + err + ))) + } + } + } + + let deser = SeqDeserializer::new(values.into_iter()); + serde::Deserializer::deserialize_any(deser, visitor) + } else { + Err(serde::de::Error::invalid_type( + Unexpected::Map, + &"tuple variant", + )) + } + } + Some(v) => Err(serde::de::Error::invalid_type( + unexpected(&v), + &"tuple variant", + )), + None => Err(serde::de::Error::invalid_type( + Unexpected::UnitVariant, + &"tuple variant", + )), + } + } + + fn struct_variant( + self, + _fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + match self.value { + Some(Value::Table(table)) => { + if let Ok(false) = table.contains_key(1) { + let mut pairs = vec![]; + for pair in table.pairs::() { + match pair { + Ok(pair) => pairs.push((pair.0, ValueWrapper(pair.1))), + Err(err) => { + return Err(Error::custom(format!( + "while retrieving map element: {}", + err + ))) + } + } + } + let deser = MapDeserializer::new(pairs.into_iter()); + serde::Deserializer::deserialize_any(deser, visitor) + } else { + Err(serde::de::Error::invalid_type( + Unexpected::Seq, + &"struct variant", + )) + } + } + Some(v) => Err(serde::de::Error::invalid_type( + unexpected(&v), + &"struct variant", + )), + _ => Err(serde::de::Error::invalid_type( + Unexpected::UnitVariant, + &"struct variant", + )), + } + } +} + +#[cfg(test)] +mod test { + use super::*; + use mlua::Lua; + + #[test] + fn test_bool() { + let lua = Lua::new(); + let res: bool = from_lua_value(lua.load("true").eval().unwrap()).unwrap(); + assert_eq!(res, true); + + let res: bool = from_lua_value(lua.load("false").eval().unwrap()).unwrap(); + assert_eq!(res, false); + } + + #[test] + fn test_nil() { + let lua = Lua::new(); + let _res: () = from_lua_value(lua.load("nil").eval().unwrap()).unwrap(); + } + + #[test] + fn test_int() { + let lua = Lua::new(); + let res: i64 = from_lua_value(lua.load("123").eval().unwrap()).unwrap(); + assert_eq!(res, 123); + + let res: i32 = from_lua_value(lua.load("123").eval().unwrap()).unwrap(); + assert_eq!(res, 123); + + let res: i16 = from_lua_value(lua.load("123").eval().unwrap()).unwrap(); + assert_eq!(res, 123); + + let res: i8 = from_lua_value(lua.load("123").eval().unwrap()).unwrap(); + assert_eq!(res, 123); + } + + #[test] + fn test_float() { + let lua = Lua::new(); + let res: f64 = from_lua_value(lua.load("123.5").eval().unwrap()).unwrap(); + assert_eq!(res, 123.5); + } + + #[test] + fn test_string() { + let lua = Lua::new(); + let res: String = from_lua_value(lua.load("\"hello\"").eval().unwrap()).unwrap(); + assert_eq!(res, "hello"); + } + + #[test] + fn test_array_table() { + let lua = Lua::new(); + let res: Vec = from_lua_value(lua.load("{1, 2, 3}").eval().unwrap()).unwrap(); + assert_eq!(res, vec![1, 2, 3]); + } + + #[test] + fn test_map_table() { + let lua = Lua::new(); + + #[derive(Deserialize, Debug, Eq, PartialEq)] + struct MyMap { + hello: String, + age: usize, + }; + + let res: MyMap = + from_lua_value(lua.load("{hello=\"hello\", age=42}").eval().unwrap()).unwrap(); + assert_eq!( + res, + MyMap { + hello: "hello".to_owned(), + age: 42 + } + ); + + let err = from_lua_value::(lua.load("{hello=\"hello\", age=true}").eval().unwrap()) + .unwrap_err(); + assert_eq!( + err.to_string(), + "\"\\\"invalid type: boolean `true`, expected integer\\\" (\ + while processing a struct of type MyMap and fields \ + named [\\\"hello\\\", \\\"age\\\"])\"" + ); + } + + #[test] + fn test_enum() { + #[derive(Deserialize, Debug, Eq, PartialEq)] + enum MyEnum { + Foo, + Bar, + }; + let lua = Lua::new(); + let res: MyEnum = from_lua_value(lua.load("\"Foo\"").eval().unwrap()).unwrap(); + assert_eq!(res, MyEnum::Foo); + + let res: MyEnum = from_lua_value(lua.load("\"Bar\"").eval().unwrap()).unwrap(); + assert_eq!(res, MyEnum::Bar); + + let err = from_lua_value::(lua.load("\"Invalid\"").eval().unwrap()).unwrap_err(); + assert_eq!( + err.to_string(), + "\"unknown variant `Invalid`, expected `Foo` or `Bar`\"" + ); + } +}