ogma_libs/vm/
trap.rs

1use alloc::string::{String, ToString};
2use core::fmt;
3
4/// An error which may occur during running a function
5#[derive(Debug)]
6pub enum Trap {
7    /// The type of the global differs than the requested type
8    DowncastError(&'static str),
9    /// The script could not execute the given function
10    ScriptOutOfBounds,
11    /// A variable is missing
12    MissingGlobal(String),
13    /// Another custom runtime error
14    Runtime(String),
15}
16
17impl Trap {
18    /// Create a runtime error
19    pub fn runtime(err: impl ToString) -> Trap {
20        Trap::Runtime(err.to_string())
21    }
22}
23
24impl fmt::Display for Trap {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        match self {
27            Self::DowncastError(ty_name) => {
28                f.write_fmt(format_args!("could not convert to type: {}", ty_name))
29            }
30            Self::ScriptOutOfBounds => f.write_str("script out of bounds"),
31            Self::MissingGlobal(global_name) => f.write_fmt(format_args!(
32                "could not find global variable: {}",
33                global_name
34            )),
35            Self::Runtime(err) => f.write_str(err),
36        }
37    }
38}
39
40#[cfg(feature = "std")]
41impl std::error::Error for Trap {}