tabled_derive/
error.rs

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
use proc_macro2::Span;

#[derive(Debug, Clone)]
pub enum Error {
    Syn(syn::Error),
    Custom {
        span: Span,
        error: String,
        help: Option<String>,
    },
}

impl Error {
    pub fn new<E>(error: E, span: Span, help: Option<String>) -> Self
    where
        E: Into<String>,
    {
        let error = error.into();
        Self::Custom { error, help, span }
    }

    pub fn message<E>(error: E) -> Self
    where
        E: Into<String>,
    {
        let error = error.into();

        Self::Custom {
            error,
            help: None,
            span: Span::call_site(),
        }
    }
}

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

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::Syn(err) => err.fmt(f),
            Error::Custom { error, .. } => {
                write!(f, "a custom error: {}", error)
            }
        }
    }
}

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

pub fn abort(err: Error) -> ! {
    match err {
        Error::Syn(err) => {
            proc_macro_error::abort! {err.span(), "{}", err}
        }
        Error::Custom { span, error, help } => match help {
            Some(help) => {
                proc_macro_error::abort! {span, "{}",  error; help="{}", help}
            }
            None => {
                proc_macro_error::abort! {span, "{}",  error}
            }
        },
    }
}