Skip to main content

cfs_synapse/
errors.rs

1use std::{error::Error as StdError, fmt};
2
3/// Error type returned by the Synapse library facade.
4#[derive(Debug)]
5pub enum Error {
6    Io(std::io::Error),
7    Parse(Box<pest::error::Error<synapse_parser::synapse::Rule>>),
8    Codegen(synapse_codegen_cfs::CodegenError),
9    Import(String),
10    Mission(String),
11}
12
13impl fmt::Display for Error {
14    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15        match self {
16            Error::Io(_) | Error::Parse(_) | Error::Codegen(_) => fmt_source_error(self, f),
17            Error::Import(_) | Error::Mission(_) => fmt_message_error(self, f),
18        }
19    }
20}
21
22fn fmt_source_error(error: &Error, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23    match error {
24        Error::Io(e) => write!(f, "{e}"),
25        Error::Parse(e) => write!(f, "{e}"),
26        Error::Codegen(e) => write!(f, "{e}"),
27        Error::Import(_) | Error::Mission(_) => unreachable!("non-source error"),
28    }
29}
30
31fn fmt_message_error(error: &Error, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32    match error {
33        Error::Import(e) | Error::Mission(e) => write!(f, "{e}"),
34        Error::Io(_) | Error::Parse(_) | Error::Codegen(_) => unreachable!("non-message error"),
35    }
36}
37
38impl StdError for Error {
39    fn source(&self) -> Option<&(dyn StdError + 'static)> {
40        match self {
41            Error::Io(e) => Some(e),
42            Error::Parse(e) => Some(e),
43            Error::Codegen(e) => Some(e),
44            Error::Import(_) | Error::Mission(_) => None,
45        }
46    }
47}
48
49impl From<std::io::Error> for Error {
50    fn from(value: std::io::Error) -> Self {
51        Error::Io(value)
52    }
53}
54
55impl From<pest::error::Error<synapse_parser::synapse::Rule>> for Error {
56    fn from(value: pest::error::Error<synapse_parser::synapse::Rule>) -> Self {
57        Error::Parse(Box::new(value))
58    }
59}
60
61impl From<synapse_codegen_cfs::CodegenError> for Error {
62    fn from(value: synapse_codegen_cfs::CodegenError) -> Self {
63        Error::Codegen(value)
64    }
65}