1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use std::fmt::{Debug, Display};

use wasm_bindgen::{JsValue, JsError};

#[derive(Debug)]
pub enum Error {
    InvalidWatText(String),
    ExportedFnNotFound(String),
    IncorrectNumOfArgs(String, u32, u32), // Name, expected, actual
    JsError(JsValue),
    // Other(String),
}

impl From<JsValue> for Error {
    fn from(value: JsValue) -> Self {
        Self::JsError(value)
    }
}

impl From<JsError> for Error {
    fn from(value: JsError) -> Self {
        Self::JsError(value.into())
    }
}

// impl From<String> for Error {
//     fn from(value: String) -> Self {
//         Self::Other(value)
//     }
// }

impl std::error::Error for Error {}

impl Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::InvalidWatText(err) => write!(
                f,
                "Module bytes are valid text, but parsing it in wat format gave error: {err}"
            ),
            Error::ExportedFnNotFound(name) => {
                write!(f, "Exported fn `{name}` not found in the module")
            }
            Error::IncorrectNumOfArgs(name, expected, actual) => write!(
                f,
                "Expected `{name}` to have {expected} arguments, but it has {actual} instead"
            ),
            Error::JsError(value) => write!(f, "{value:?}"),
            // Error::Other(value) => write!(f, "Other error: {value:?}"),
        }
    }
}

pub type Result<T, E = Error> = std::result::Result<T, E>;