use std::fmt;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum IsleError {
#[error("isle shut down")]
Shutdown,
#[error("cancelled")]
Cancelled,
#[error("lua error: {0}")]
Lua(LuaFailure),
#[error("init error: {0}")]
Init(LuaFailure),
#[error("function '{0}' not found")]
NotFound(String),
#[error("lua thread panicked{}", .0.as_deref().map(|m| format!(": {m}")).unwrap_or_default())]
ThreadPanic(Option<String>),
#[cfg(feature = "tokio")]
#[error("channel full (backpressure)")]
ChannelFull,
#[error("recv failed")]
RecvFailed,
#[cfg(feature = "pool")]
#[error("pool exhausted (max_size={0})")]
PoolExhausted(usize),
#[cfg(feature = "pool")]
#[error("pool lock poisoned: {0}")]
PoolPoisoned(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LuaErrorKind {
Runtime,
Syntax,
Memory,
Callback,
External,
Conversion,
Other,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct LuaFailure {
pub kind: LuaErrorKind,
pub message: String,
pub traceback: Option<String>,
#[cfg(feature = "serde")]
pub value: Option<serde_json::Value>,
}
impl LuaFailure {
pub fn new(kind: LuaErrorKind, message: impl Into<String>) -> Self {
Self {
kind,
message: message.into(),
traceback: None,
#[cfg(feature = "serde")]
value: None,
}
}
pub fn from_mlua(e: &mlua::Error) -> Self {
match e {
mlua::Error::CallbackError { traceback, cause } => {
let (mut cause, mut traceback) = (cause, traceback);
while let mlua::Error::CallbackError {
cause: inner,
traceback: inner_tb,
} = &**cause
{
cause = inner;
traceback = inner_tb;
}
let inner = Self::from_mlua(cause);
let mut f = Self::new(LuaErrorKind::Callback, inner.message);
f.traceback = Some(traceback.clone())
.filter(|t| !t.is_empty())
.or(inner.traceback);
f
}
mlua::Error::WithContext { context, cause } => {
let mut f = Self::from_mlua(cause);
f.message = format!("{context}\n{}", f.message);
f
}
mlua::Error::RuntimeError(msg) => {
let (message, traceback) = split_traceback(msg);
let mut f = Self::new(LuaErrorKind::Runtime, message);
f.traceback = traceback;
f
}
mlua::Error::SyntaxError { message, .. } => {
Self::new(LuaErrorKind::Syntax, message.clone())
}
mlua::Error::MemoryError(msg) => Self::new(LuaErrorKind::Memory, msg.clone()),
mlua::Error::ExternalError(_) => Self::new(LuaErrorKind::External, e.to_string()),
mlua::Error::FromLuaConversionError { .. } | mlua::Error::BadArgument { .. } => {
Self::new(LuaErrorKind::Conversion, e.to_string())
}
#[cfg(feature = "serde")]
mlua::Error::SerializeError(_) | mlua::Error::DeserializeError(_) => {
Self::new(LuaErrorKind::Conversion, e.to_string())
}
_ => Self::new(LuaErrorKind::Other, e.to_string()),
}
}
}
impl fmt::Display for LuaFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl From<mlua::Error> for LuaFailure {
fn from(e: mlua::Error) -> Self {
Self::from_mlua(&e)
}
}
fn split_traceback(msg: &str) -> (String, Option<String>) {
match msg.find("\nstack traceback:") {
Some(pos) => (msg[..pos].to_string(), Some(msg[pos + 1..].to_string())),
None => (msg.to_string(), None),
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Cancelled;
impl fmt::Display for Cancelled {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("cancelled")
}
}
impl std::error::Error for Cancelled {}
pub(crate) fn is_cancel(e: &mlua::Error) -> bool {
e.downcast_ref::<Cancelled>().is_some()
|| matches!(e.downcast_ref::<IsleError>(), Some(IsleError::Cancelled))
}
pub(crate) fn cancel_error() -> mlua::Error {
mlua::Error::external(Cancelled)
}
impl From<mlua::Error> for IsleError {
fn from(e: mlua::Error) -> Self {
if is_cancel(&e) {
Self::Cancelled
} else {
Self::Lua(LuaFailure::from_mlua(&e))
}
}
}
impl From<IsleError> for mlua::Error {
fn from(e: IsleError) -> Self {
match e {
IsleError::Cancelled => cancel_error(),
e => mlua::Error::external(e),
}
}
}
pub(crate) fn panic_message(payload: &(dyn std::any::Any + Send)) -> Option<String> {
payload
.downcast_ref::<&str>()
.map(|s| s.to_string())
.or_else(|| payload.downcast_ref::<String>().cloned())
}
#[cfg(test)]
mod tests {
use super::*;
fn assert_send_sync<T: Send + Sync + 'static>() {}
#[test]
fn error_types_are_send_sync() {
assert_send_sync::<IsleError>();
assert_send_sync::<LuaFailure>();
assert_send_sync::<Cancelled>();
}
#[test]
#[allow(clippy::arc_with_non_send_sync)]
fn cancel_is_found_through_callback_error() {
let wrapped = mlua::Error::CallbackError {
traceback: String::new(),
cause: std::sync::Arc::new(cancel_error()),
};
assert!(matches!(IsleError::from(wrapped), IsleError::Cancelled));
assert!(matches!(
IsleError::from(mlua::Error::runtime("__isle_cancelled__")),
IsleError::Lua(_)
));
}
#[test]
#[allow(clippy::arc_with_non_send_sync)]
fn nested_messages_carry_no_traceback() {
let inner = mlua::Error::runtime("x:1: boom\nstack traceback:\n\t[C]: in ?");
let cb = mlua::Error::CallbackError {
traceback: "stack traceback:\n\t[C]: in f".into(),
cause: std::sync::Arc::new(inner.clone()),
};
let f = LuaFailure::from_mlua(&cb);
assert_eq!(f.kind, LuaErrorKind::Callback);
assert_eq!(f.message, "x:1: boom");
assert_eq!(
f.traceback.as_deref(),
Some("stack traceback:\n\t[C]: in f")
);
let ctx = mlua::Error::WithContext {
context: "while loading".into(),
cause: std::sync::Arc::new(inner),
};
let f = LuaFailure::from_mlua(&ctx);
assert_eq!(f.kind, LuaErrorKind::Runtime);
assert_eq!(f.message, "while loading\nx:1: boom");
assert!(f.traceback.is_some());
}
#[test]
fn runtime_error_traceback_is_split() {
let f = LuaFailure::from_mlua(&mlua::Error::runtime(
"x:1: boom\nstack traceback:\n\t[C]: in ?",
));
assert_eq!(f.kind, LuaErrorKind::Runtime);
assert_eq!(f.message, "x:1: boom");
assert_eq!(
f.traceback.as_deref(),
Some("stack traceback:\n\t[C]: in ?")
);
}
}