~starkingdoms/starkingdoms

ref: db1274d4c9c6a4e78cce2f225e1894a85d76c5ac starkingdoms/kabel/src/error.rs -rw-r--r-- 1.8 KiB
db1274d4 — ghostlyzsh array, subscript 1 year, 4 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
#[derive(Debug, Clone)]
pub struct KabelError {
    pub kind: ErrorKind,
    pub message: String,
    pub line: usize,
    pub column: usize,
    pub code: String,
}

impl KabelError {
    pub fn new(kind: ErrorKind, message: String, line: usize, column: usize, code: String) -> Self {
        Self {
            kind,
            message,
            line,
            column,
            code,
        }
    }
}

impl std::fmt::Display for KabelError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let caret_space: String = vec![' '; self.column - 1].iter().collect();
        f.write_str(&format!(
            "Error {:0>4}: {1} at line {2}, column {3}\n\
                    {4}\n\
                    {5}^",
            self.kind.clone() as usize,
            self.message,
            self.line + 1,
            self.column,
            self.code,
            caret_space
        ))
    }
}

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

#[derive(Debug, Clone)]
pub enum ErrorKind {
    UnexpectedEof,
    UnexpectedCharacter,
    UnexpectedToken,
    MissingDelimiter,
}

impl std::fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use ErrorKind::*;
        match self {
            UnexpectedEof => f.write_str("Unexpected End of File"),
            UnexpectedCharacter => f.write_str("Unrecognized Charcter"),
            UnexpectedToken => f.write_str("Unrecognized Token"),
            MissingDelimiter => f.write_str("Missing delimiter"),
        }
    }
}

impl From<ErrorKind> for usize {
    fn from(value: ErrorKind) -> Self {
        use ErrorKind::*;
        match value {
            UnexpectedEof => 0x00,
            UnexpectedCharacter => 0x01,
            UnexpectedToken => 0x02,
            MissingDelimiter => 0x03,
        }
    }
}