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

use proc_macro2::TokenStream;
use quote::quote;

pub(crate) type StdResult<T, E> = result::Result<T, E>;
pub type Result<T> = StdResult<T, Error>;

pub fn compile_err(msg: &str) -> TokenStream {
    quote!(compile_error!(#msg);)
}

#[derive(Debug)]
pub enum Error {
    /// `syn::Error`.
    Syn(syn::Error),
    /// other error.
    Other(String),
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::Syn(e) => write!(f, "{}", e),
            Error::Other(s) => write!(f, "{}", s),
        }
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match self {
            Error::Syn(e) => e.description(),
            Error::Other(s) => s,
        }
    }
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self {
            Error::Syn(e) => e.source(),
            Error::Other(_) => None,
        }
    }
}

impl From<String> for Error {
    fn from(s: String) -> Self {
        Error::Other(s)
    }
}

impl<'a> From<&'a str> for Error {
    fn from(s: &'a str) -> Self {
        Error::Other(s.into())
    }
}

impl From<syn::Error> for Error {
    fn from(e: syn::Error) -> Self {
        Error::Syn(e)
    }
}