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
use std::fmt::{self, Debug, Display, Formatter};

use crate::Rule;

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

#[derive(Debug)]
pub struct InputResolveError(pub String);
#[derive(Debug)]
pub struct FileReadError(pub String);
#[derive(Debug)]
pub struct SerializationError(pub String);
#[derive(Debug)]
pub struct DeserializationError(pub String);

#[derive(Debug)]
pub enum Error {
    /// Error while parsing the file
    ParserError(Box<pest::error::Error<Rule>>),
    /// Error while looking up a referenced an input
    InputResolveError(InputResolveError),
    DeserializationError(DeserializationError),
}

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

impl From<InputResolveError> for Error {
    fn from(err: InputResolveError) -> Self {
        Self::InputResolveError(err)
    }
}

impl From<pest::error::Error<Rule>> for Error {
    fn from(err: pest::error::Error<Rule>) -> Self {
        Self::ParserError(Box::new(err))
    }
}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Error::ParserError(_) => writeln!(f, "An error while parsing the input file."),
            Error::InputResolveError(err) => {
                write!(f, "Input `{}` was used but not declared", err.0)
            }
            Error::DeserializationError(err) => {
                write!(f, "An error occurred when deserializing: {}", err.0)
            }
        }
    }
}

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

impl Display for DeserializationError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "An error occurred when deserializing: {}", self.0)
    }
}

impl serde::de::Error for DeserializationError {
    fn custom<T>(msg: T) -> Self
    where
        T: Display,
    {
        DeserializationError(msg.to_string())
    }
}