mlua_codemp_patch/
error.rs

1use std::error::Error as StdError;
2use std::fmt;
3use std::io::Error as IoError;
4use std::net::AddrParseError;
5use std::result::Result as StdResult;
6use std::str::Utf8Error;
7use std::string::String as StdString;
8use std::sync::Arc;
9
10use crate::private::Sealed;
11
12/// Error type returned by `mlua` methods.
13#[derive(Debug, Clone)]
14#[non_exhaustive]
15pub enum Error {
16    /// Syntax error while parsing Lua source code.
17    SyntaxError {
18        /// The error message as returned by Lua.
19        message: StdString,
20        /// `true` if the error can likely be fixed by appending more input to the source code.
21        ///
22        /// This is useful for implementing REPLs as they can query the user for more input if this
23        /// is set.
24        incomplete_input: bool,
25    },
26    /// Lua runtime error, aka `LUA_ERRRUN`.
27    ///
28    /// The Lua VM returns this error when a builtin operation is performed on incompatible types.
29    /// Among other things, this includes invoking operators on wrong types (such as calling or
30    /// indexing a `nil` value).
31    RuntimeError(StdString),
32    /// Lua memory error, aka `LUA_ERRMEM`
33    ///
34    /// The Lua VM returns this error when the allocator does not return the requested memory, aka
35    /// it is an out-of-memory error.
36    MemoryError(StdString),
37    /// Lua garbage collector error, aka `LUA_ERRGCMM`.
38    ///
39    /// The Lua VM returns this error when there is an error running a `__gc` metamethod.
40    #[cfg(any(feature = "lua53", feature = "lua52", doc))]
41    #[cfg_attr(docsrs, doc(cfg(any(feature = "lua53", feature = "lua52"))))]
42    GarbageCollectorError(StdString),
43    /// Potentially unsafe action in safe mode.
44    SafetyError(StdString),
45    /// Setting memory limit is not available.
46    ///
47    /// This error can only happen when Lua state was not created by us and does not have the
48    /// custom allocator attached.
49    MemoryLimitNotAvailable,
50    /// A mutable callback has triggered Lua code that has called the same mutable callback again.
51    ///
52    /// This is an error because a mutable callback can only be borrowed mutably once.
53    RecursiveMutCallback,
54    /// Either a callback or a userdata method has been called, but the callback or userdata has
55    /// been destructed.
56    ///
57    /// This can happen either due to to being destructed in a previous __gc, or due to being
58    /// destructed from exiting a `Lua::scope` call.
59    CallbackDestructed,
60    /// Not enough stack space to place arguments to Lua functions or return values from callbacks.
61    ///
62    /// Due to the way `mlua` works, it should not be directly possible to run out of stack space
63    /// during normal use. The only way that this error can be triggered is if a `Function` is
64    /// called with a huge number of arguments, or a rust callback returns a huge number of return
65    /// values.
66    StackError,
67    /// Too many arguments to `Function::bind`.
68    BindError,
69    /// Bad argument received from Lua (usually when calling a function).
70    ///
71    /// This error can help to identify the argument that caused the error
72    /// (which is stored in the corresponding field).
73    BadArgument {
74        /// Function that was called.
75        to: Option<StdString>,
76        /// Argument position (usually starts from 1).
77        pos: usize,
78        /// Argument name.
79        name: Option<StdString>,
80        /// Underlying error returned when converting argument to a Lua value.
81        cause: Arc<Error>,
82    },
83    /// A Rust value could not be converted to a Lua value.
84    ToLuaConversionError {
85        /// Name of the Rust type that could not be converted.
86        from: &'static str,
87        /// Name of the Lua type that could not be created.
88        to: &'static str,
89        /// A message indicating why the conversion failed in more detail.
90        message: Option<StdString>,
91    },
92    /// A Lua value could not be converted to the expected Rust type.
93    FromLuaConversionError {
94        /// Name of the Lua type that could not be converted.
95        from: &'static str,
96        /// Name of the Rust type that could not be created.
97        to: &'static str,
98        /// A string containing more detailed error information.
99        message: Option<StdString>,
100    },
101    /// [`Thread::resume`] was called on an unresumable coroutine.
102    ///
103    /// A coroutine is unresumable if its main function has returned or if an error has occurred
104    /// inside the coroutine. Already running coroutines are also marked as unresumable.
105    ///
106    /// [`Thread::status`] can be used to check if the coroutine can be resumed without causing this
107    /// error.
108    ///
109    /// [`Thread::resume`]: crate::Thread::resume
110    /// [`Thread::status`]: crate::Thread::status
111    CoroutineUnresumable,
112    /// An [`AnyUserData`] is not the expected type in a borrow.
113    ///
114    /// This error can only happen when manually using [`AnyUserData`], or when implementing
115    /// metamethods for binary operators. Refer to the documentation of [`UserDataMethods`] for
116    /// details.
117    ///
118    /// [`AnyUserData`]: crate::AnyUserData
119    /// [`UserDataMethods`]: crate::UserDataMethods
120    UserDataTypeMismatch,
121    /// An [`AnyUserData`] borrow failed because it has been destructed.
122    ///
123    /// This error can happen either due to to being destructed in a previous __gc, or due to being
124    /// destructed from exiting a `Lua::scope` call.
125    ///
126    /// [`AnyUserData`]: crate::AnyUserData
127    UserDataDestructed,
128    /// An [`AnyUserData`] immutable borrow failed.
129    ///
130    /// This error can occur when a method on a [`UserData`] type calls back into Lua, which then
131    /// tries to call a method on the same [`UserData`] type. Consider restructuring your API to
132    /// prevent these errors.
133    ///
134    /// [`AnyUserData`]: crate::AnyUserData
135    /// [`UserData`]: crate::UserData
136    UserDataBorrowError,
137    /// An [`AnyUserData`] mutable borrow failed.
138    ///
139    /// This error can occur when a method on a [`UserData`] type calls back into Lua, which then
140    /// tries to call a method on the same [`UserData`] type. Consider restructuring your API to
141    /// prevent these errors.
142    ///
143    /// [`AnyUserData`]: crate::AnyUserData
144    /// [`UserData`]: crate::UserData
145    UserDataBorrowMutError,
146    /// A [`MetaMethod`] operation is restricted (typically for `__gc` or `__metatable`).
147    ///
148    /// [`MetaMethod`]: crate::MetaMethod
149    MetaMethodRestricted(StdString),
150    /// A [`MetaMethod`] (eg. `__index` or `__newindex`) has invalid type.
151    ///
152    /// [`MetaMethod`]: crate::MetaMethod
153    MetaMethodTypeError {
154        /// Name of the metamethod.
155        method: StdString,
156        /// Passed value type.
157        type_name: &'static str,
158        /// A string containing more detailed error information.
159        message: Option<StdString>,
160    },
161    /// A [`RegistryKey`] produced from a different Lua state was used.
162    ///
163    /// [`RegistryKey`]: crate::RegistryKey
164    MismatchedRegistryKey,
165    /// A Rust callback returned `Err`, raising the contained `Error` as a Lua error.
166    CallbackError {
167        /// Lua call stack backtrace.
168        traceback: StdString,
169        /// Original error returned by the Rust code.
170        cause: Arc<Error>,
171    },
172    /// A Rust panic that was previously resumed, returned again.
173    ///
174    /// This error can occur only when a Rust panic resumed previously was recovered
175    /// and returned again.
176    PreviouslyResumedPanic,
177    /// Serialization error.
178    #[cfg(feature = "serialize")]
179    #[cfg_attr(docsrs, doc(cfg(feature = "serialize")))]
180    SerializeError(StdString),
181    /// Deserialization error.
182    #[cfg(feature = "serialize")]
183    #[cfg_attr(docsrs, doc(cfg(feature = "serialize")))]
184    DeserializeError(StdString),
185    /// A custom error.
186    ///
187    /// This can be used for returning user-defined errors from callbacks.
188    ///
189    /// Returning `Err(ExternalError(...))` from a Rust callback will raise the error as a Lua
190    /// error. The Rust code that originally invoked the Lua code then receives a `CallbackError`,
191    /// from which the original error (and a stack traceback) can be recovered.
192    ExternalError(Arc<dyn StdError + Send + Sync>),
193    /// An error with additional context.
194    WithContext {
195        /// A string containing additional context.
196        context: StdString,
197        /// Underlying error.
198        cause: Arc<Error>,
199    },
200}
201
202/// A specialized `Result` type used by `mlua`'s API.
203pub type Result<T> = StdResult<T, Error>;
204
205#[cfg(not(tarpaulin_include))]
206impl fmt::Display for Error {
207    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
208        match *self {
209            Error::SyntaxError { ref message, .. } => write!(fmt, "syntax error: {message}"),
210            Error::RuntimeError(ref msg) => write!(fmt, "runtime error: {msg}"),
211            Error::MemoryError(ref msg) => {
212                write!(fmt, "memory error: {msg}")
213            }
214            #[cfg(any(feature = "lua53", feature = "lua52"))]
215            Error::GarbageCollectorError(ref msg) => {
216                write!(fmt, "garbage collector error: {msg}")
217            }
218            Error::SafetyError(ref msg) => {
219                write!(fmt, "safety error: {msg}")
220            },
221            Error::MemoryLimitNotAvailable => {
222                write!(fmt, "setting memory limit is not available")
223            }
224            Error::RecursiveMutCallback => write!(fmt, "mutable callback called recursively"),
225            Error::CallbackDestructed => write!(
226                fmt,
227                "a destructed callback or destructed userdata method was called"
228            ),
229            Error::StackError => write!(
230                fmt,
231                "out of Lua stack, too many arguments to a Lua function or too many return values from a callback"
232            ),
233            Error::BindError => write!(
234                fmt,
235                "too many arguments to Function::bind"
236            ),
237            Error::BadArgument { ref to, pos, ref name, ref cause } => {
238                if let Some(name) = name {
239                    write!(fmt, "bad argument `{name}`")?;
240                } else {
241                    write!(fmt, "bad argument #{pos}")?;
242                }
243                if let Some(to) = to {
244                    write!(fmt, " to `{to}`")?;
245                }
246                write!(fmt, ": {cause}")
247            },
248            Error::ToLuaConversionError { from, to, ref message } => {
249                write!(fmt, "error converting {from} to Lua {to}")?;
250                match *message {
251                    None => Ok(()),
252                    Some(ref message) => write!(fmt, " ({message})"),
253                }
254            }
255            Error::FromLuaConversionError { from, to, ref message } => {
256                write!(fmt, "error converting Lua {from} to {to}")?;
257                match *message {
258                    None => Ok(()),
259                    Some(ref message) => write!(fmt, " ({message})"),
260                }
261            }
262            Error::CoroutineUnresumable => write!(fmt, "coroutine is non-resumable"),
263            Error::UserDataTypeMismatch => write!(fmt, "userdata is not expected type"),
264            Error::UserDataDestructed => write!(fmt, "userdata has been destructed"),
265            Error::UserDataBorrowError => write!(fmt, "error borrowing userdata"),
266            Error::UserDataBorrowMutError => write!(fmt, "error mutably borrowing userdata"),
267            Error::MetaMethodRestricted(ref method) => write!(fmt, "metamethod {method} is restricted"),
268            Error::MetaMethodTypeError { ref method, type_name, ref message } => {
269                write!(fmt, "metamethod {method} has unsupported type {type_name}")?;
270                match *message {
271                    None => Ok(()),
272                    Some(ref message) => write!(fmt, " ({message})"),
273                }
274            }
275            Error::MismatchedRegistryKey => {
276                write!(fmt, "RegistryKey used from different Lua state")
277            }
278            Error::CallbackError { ref cause, ref traceback } => {
279                // Trace errors down to the root
280                let (mut cause, mut full_traceback) = (cause, None);
281                while let Error::CallbackError { cause: ref cause2, traceback: ref traceback2 } = **cause {
282                    cause = cause2;
283                    full_traceback = Some(traceback2);
284                }
285                writeln!(fmt, "{cause}")?;
286                if let Some(full_traceback) = full_traceback {
287                    let traceback = traceback.trim_start_matches("stack traceback:");
288                    let traceback = traceback.trim_start().trim_end();
289                    // Try to find local traceback within the full traceback
290                    if let Some(pos) = full_traceback.find(traceback) {
291                        write!(fmt, "{}", &full_traceback[..pos])?;
292                        writeln!(fmt, ">{}", &full_traceback[pos..].trim_end())?;
293                    } else {
294                        writeln!(fmt, "{}", full_traceback.trim_end())?;
295                    }
296                } else {
297                    writeln!(fmt, "{}", traceback.trim_end())?;
298                }
299                Ok(())
300            }
301            Error::PreviouslyResumedPanic => {
302                write!(fmt, "previously resumed panic returned again")
303            }
304            #[cfg(feature = "serialize")]
305            Error::SerializeError(ref err) => {
306                write!(fmt, "serialize error: {err}")
307            },
308            #[cfg(feature = "serialize")]
309            Error::DeserializeError(ref err) => {
310                write!(fmt, "deserialize error: {err}")
311            },
312            Error::ExternalError(ref err) => write!(fmt, "{err}"),
313            Error::WithContext { ref context, ref cause } => {
314                writeln!(fmt, "{context}")?;
315                write!(fmt, "{cause}")
316            }
317        }
318    }
319}
320
321impl StdError for Error {
322    fn source(&self) -> Option<&(dyn StdError + 'static)> {
323        match *self {
324            // An error type with a source error should either return that error via source or
325            // include that source's error message in its own Display output, but never both.
326            // https://blog.rust-lang.org/inside-rust/2021/07/01/What-the-error-handling-project-group-is-working-towards.html
327            // Given that we include source to fmt::Display implementation for `CallbackError`, this call
328            // returns nothing.
329            Error::CallbackError { .. } => None,
330            Error::ExternalError(ref err) => err.source(),
331            Error::WithContext { ref cause, .. } => match cause.as_ref() {
332                Error::ExternalError(err) => err.source(),
333                _ => None,
334            },
335            _ => None,
336        }
337    }
338}
339
340impl Error {
341    /// Creates a new `RuntimeError` with the given message.
342    #[inline]
343    pub fn runtime<S: fmt::Display>(message: S) -> Self {
344        Error::RuntimeError(message.to_string())
345    }
346
347    /// Wraps an external error object.
348    #[inline]
349    pub fn external<T: Into<Box<dyn StdError + Send + Sync>>>(err: T) -> Self {
350        Error::ExternalError(err.into().into())
351    }
352
353    /// Attempts to downcast the external error object to a concrete type by reference.
354    pub fn downcast_ref<T>(&self) -> Option<&T>
355    where
356        T: StdError + 'static,
357    {
358        match self {
359            Error::ExternalError(err) => err.downcast_ref(),
360            Error::WithContext { cause, .. } => match cause.as_ref() {
361                Error::ExternalError(err) => err.downcast_ref(),
362                _ => None,
363            },
364            _ => None,
365        }
366    }
367
368    pub(crate) fn bad_self_argument(to: &str, cause: Error) -> Self {
369        Error::BadArgument {
370            to: Some(to.to_string()),
371            pos: 1,
372            name: Some("self".to_string()),
373            cause: Arc::new(cause),
374        }
375    }
376
377    pub(crate) fn from_lua_conversion<'a>(
378        from: &'static str,
379        to: &'static str,
380        message: impl Into<Option<&'a str>>,
381    ) -> Self {
382        Error::FromLuaConversionError {
383            from,
384            to,
385            message: message.into().map(|s| s.into()),
386        }
387    }
388}
389
390/// Trait for converting [`std::error::Error`] into Lua [`Error`].
391pub trait ExternalError {
392    fn into_lua_err(self) -> Error;
393}
394
395impl<E: Into<Box<dyn StdError + Send + Sync>>> ExternalError for E {
396    fn into_lua_err(self) -> Error {
397        Error::external(self)
398    }
399}
400
401/// Trait for converting [`std::result::Result`] into Lua [`Result`].
402pub trait ExternalResult<T> {
403    fn into_lua_err(self) -> Result<T>;
404}
405
406impl<T, E> ExternalResult<T> for StdResult<T, E>
407where
408    E: ExternalError,
409{
410    fn into_lua_err(self) -> Result<T> {
411        self.map_err(|e| e.into_lua_err())
412    }
413}
414
415/// Provides the `context` method for [`Error`] and `Result<T, Error>`.
416pub trait ErrorContext: Sealed {
417    /// Wraps the error value with additional context.
418    fn context<C: fmt::Display>(self, context: C) -> Self;
419
420    /// Wrap the error value with additional context that is evaluated lazily
421    /// only once an error does occur.
422    fn with_context<C: fmt::Display>(self, f: impl FnOnce(&Error) -> C) -> Self;
423}
424
425impl ErrorContext for Error {
426    fn context<C: fmt::Display>(self, context: C) -> Self {
427        let context = context.to_string();
428        match self {
429            Error::WithContext { cause, .. } => Error::WithContext { context, cause },
430            _ => Error::WithContext {
431                context,
432                cause: Arc::new(self),
433            },
434        }
435    }
436
437    fn with_context<C: fmt::Display>(self, f: impl FnOnce(&Error) -> C) -> Self {
438        let context = f(&self).to_string();
439        match self {
440            Error::WithContext { cause, .. } => Error::WithContext { context, cause },
441            _ => Error::WithContext {
442                context,
443                cause: Arc::new(self),
444            },
445        }
446    }
447}
448
449impl<T> ErrorContext for StdResult<T, Error> {
450    fn context<C: fmt::Display>(self, context: C) -> Self {
451        self.map_err(|err| err.context(context))
452    }
453
454    fn with_context<C: fmt::Display>(self, f: impl FnOnce(&Error) -> C) -> Self {
455        self.map_err(|err| err.with_context(f))
456    }
457}
458
459impl From<AddrParseError> for Error {
460    fn from(err: AddrParseError) -> Self {
461        Error::external(err)
462    }
463}
464
465impl From<IoError> for Error {
466    fn from(err: IoError) -> Self {
467        Error::external(err)
468    }
469}
470
471impl From<Utf8Error> for Error {
472    fn from(err: Utf8Error) -> Self {
473        Error::external(err)
474    }
475}
476
477#[cfg(feature = "serialize")]
478impl serde::ser::Error for Error {
479    fn custom<T: fmt::Display>(msg: T) -> Self {
480        Self::SerializeError(msg.to_string())
481    }
482}
483
484#[cfg(feature = "serialize")]
485impl serde::de::Error for Error {
486    fn custom<T: fmt::Display>(msg: T) -> Self {
487        Self::DeserializeError(msg.to_string())
488    }
489}