~starkingdoms/starkingdoms

ref: 87db7538d05166cb8cdb701886b38b32de9bc708 starkingdoms/crates/kabel/src/runtime_error.rs -rw-r--r-- 1.9 KiB
87db7538 — core cargo fmt 8 months ago
                                                                                
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#[derive(Debug, Clone)]
pub struct KabelRuntimeError {
    pub kind: RuntimeErrorKind,
    pub message: String,
    pub hint: Option<String>,
    pub line: usize,
    pub code: String,
}

impl KabelRuntimeError {
    pub fn new(
        kind: RuntimeErrorKind,
        message: String,
        hint: Option<String>,
        line: usize,
        code: String,
    ) -> Self {
        Self {
            kind,
            message,
            hint,
            line,
            code,
        }
    }
}

impl std::fmt::Display for KabelRuntimeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&format!(
            "Error {:0>4}: {1} at line {2}\n\
                    {3}\n",
            self.kind.clone() as usize,
            self.message,
            self.line + 1,
            self.code,
        ))?;
        if let Some(ref hint) = self.hint {
            f.write_str(&format!("\n{0}", hint))?;
        }
        Ok(())
    }
}

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

#[derive(Debug, Clone)]
pub enum RuntimeErrorKind {
    MismatchedTypes,
    WrongType,
    IncorrectArity,
    ArrayOutOfBounds,
}

impl std::fmt::Display for RuntimeErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use RuntimeErrorKind::*;
        match self {
            MismatchedTypes => f.write_str("Mismatched types"),
            WrongType => f.write_str("Wrong type"),
            IncorrectArity => f.write_str("Incorrect arity"),
            ArrayOutOfBounds => f.write_str("Array out of bounds"),
        }
    }
}

impl From<RuntimeErrorKind> for usize {
    fn from(value: RuntimeErrorKind) -> Self {
        use RuntimeErrorKind::*;
        match value {
            MismatchedTypes => 0x00,
            WrongType => 0x01,
            IncorrectArity => 0x02,
            ArrayOutOfBounds => 0x03,
        }
    }
}