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
use std::{error::Error, fmt};

// ParseError
#[derive(Debug, Clone)]
pub struct ParseError {
    message: String,
    pub pos: usize,
    line: usize,
}

impl ParseError {
    pub fn new(pos: usize, line: usize, message: String) -> Self {
        ParseError { pos, line, message }
    }
}

impl Error for ParseError {}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{} at line {} position {}",
            self.message, self.line, self.pos
        )
    }
}

// ValueError
#[derive(Debug)]
pub struct ValueError {}

impl Error for ValueError {}

impl fmt::Display for ValueError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Bad character range")
    }
}

/// Defines Gura error with Display method
macro_rules! gura_error {
    ($error_name:ident) => {
        #[derive(Debug, Clone)]
        pub struct $error_name {
            msg: String,
        }

        impl $error_name {
            pub fn new(msg: String) -> Self {
                $error_name { msg }
            }
        }

        impl fmt::Display for $error_name {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                write!(f, "{}", self.msg)
            }
        }

        impl Error for $error_name {}
    };
}

// Define extra common errors
gura_error!(VariableNotDefinedError);

gura_error!(InvalidIndentationError);

gura_error!(DuplicatedVariableError);

gura_error!(DuplicatedKeyError);

gura_error!(FileNotFoundError);

gura_error!(DuplicatedImportError);