slvm/
error.rs

1use crate::{GVm, Value};
2use std::error::Error;
3use std::fmt;
4use std::io;
5
6#[derive(Clone, Debug)]
7pub enum VMErrorObj {
8    Message(String),
9    Object(Value),
10}
11
12#[derive(Clone, Debug)]
13pub struct VMError {
14    pub key: &'static str,
15    pub obj: VMErrorObj,
16}
17
18impl Error for VMError {}
19
20impl fmt::Display for VMError {
21    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
22        match &self.obj {
23            VMErrorObj::Message(msg) => write!(f, "[{}]: {}", self.key, msg),
24            VMErrorObj::Object(val) => write!(f, "[{}]: {:?}", self.key, val),
25        }
26    }
27}
28
29impl From<io::Error> for VMError {
30    fn from(item: io::Error) -> Self {
31        VMError::new("io", item.to_string())
32    }
33}
34
35impl VMError {
36    pub fn new<S: Into<String>>(key: &'static str, reason: S) -> Self {
37        let reason: String = reason.into();
38        VMError {
39            key,
40            obj: VMErrorObj::Message(reason),
41        }
42    }
43
44    pub fn display<ENV>(&self, vm: &GVm<ENV>) -> String {
45        match &self.obj {
46            VMErrorObj::Message(msg) => format!("[{}]: {}", self.key, msg),
47            VMErrorObj::Object(val) => format!("[{}]: {}", self.key, val.pretty_value(vm)),
48        }
49    }
50
51    pub fn new_conversion<S: Into<String>>(reason: S) -> Self {
52        VMError::new("conversion", reason)
53    }
54
55    pub fn new_string_conversion<S: Into<String>>(reason: S) -> Self {
56        VMError::new("string_conversion", reason)
57    }
58
59    pub fn new_vm<S: Into<String>>(reason: S) -> Self {
60        VMError::new("rt", reason)
61    }
62
63    pub fn new_chunk<S: Into<String>>(reason: S) -> Self {
64        VMError::new("rt", reason)
65    }
66
67    pub fn new_heap<S: Into<String>>(reason: S) -> Self {
68        VMError::new("mem", reason)
69    }
70
71    pub fn new_value<S: Into<String>>(reason: S) -> Self {
72        VMError::new("rt", reason)
73    }
74
75    pub fn new_compile<S: Into<String>>(reason: S) -> Self {
76        VMError::new("compile", reason)
77    }
78
79    pub fn new_other<S: Into<String>>(reason: S) -> Self {
80        VMError::new("error", reason)
81    }
82}
83
84pub type VMResult<T> = Result<T, VMError>;