keon/
error.rs

1use std::{fmt, io, num::NonZeroU32};
2
3pub type Result<T> = core::result::Result<T, Error>;
4
5#[derive(Debug, Default, Clone, PartialEq, Eq)]
6pub struct Error {
7    pub line: Option<NonZeroU32>,
8    pub col: Option<NonZeroU32>,
9    pub kind: ErrorKind,
10}
11impl Error {
12    pub(crate) fn new(kind: ErrorKind) -> Self {
13        Self {
14            line: None,
15            col: None,
16            kind,
17        }
18    }
19    pub(crate) fn raise<T>(kind: ErrorKind) -> Result<T> {
20        Err(Self::new(kind))
21    }
22}
23impl std::error::Error for Error {}
24impl serde::ser::Error for Error {
25    fn custom<T: fmt::Display>(msg: T) -> Self {
26        Error::new(ErrorKind::Serialize(msg.to_string()))
27    }
28}
29impl serde::de::Error for Error {
30    fn custom<T: fmt::Display>(msg: T) -> Self {
31        Error::new(ErrorKind::Deserialize(msg.to_string()))
32    }
33}
34impl fmt::Display for Error {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        let Error { line, col, kind } = self;
37        if let Some(n) = line {
38            write!(f, ":{}", n)?;
39            match col {
40                Some(m) => write!(f, ":{} ", m)?,
41                None => write!(f, ":-1 ")?,
42            }
43        }
44        write!(f, "{}", kind)
45    }
46}
47impl From<io::Error> for Error {
48    fn from(e: io::Error) -> Self {
49        Error::new(ErrorKind::Io(e.to_string()))
50    }
51}
52
53#[non_exhaustive]
54#[derive(Debug, Default, Clone, PartialEq, Eq)]
55pub enum ErrorKind {
56    UnexpectedEof,
57    #[default]
58    UnexpectedToken,
59    UnexpectedNewline,
60    UnexpectedNonAscii,
61    UnexpectedUnicodeEscape,
62    UnbalancedLiteralClose,
63    InvalidNumber(lexical_core::Error),
64    InvalidCharacterTooLess,
65    InvalidCharacterTooMany,
66    InvalidBytesEncoding(data_encoding::DecodeError),
67    InvalidEscape,
68    InvalidAsciiEscape,
69    InvalidUnicodeEscape,
70
71    ExpectedComma,
72    ExpectedFatArrow,
73    ExpectedNonUnitStruct,
74    ExpectedVariant,
75    ExpectedUnitVariant,
76    ExpectedNewtypeVariant,
77    ExpectedTupleVariant,
78    ExpectedStructVariant,
79    ExpectedEof,
80
81    Io(String),
82    Serialize(String),
83    Deserialize(String),
84
85    ExceededRecursionLimit,
86}
87impl fmt::Display for ErrorKind {
88    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
89        use ErrorKind::*;
90        match self {
91            UnexpectedEof => write!(f, "unexpected EOF"),
92            UnexpectedToken => write!(f, "unexpected token"),
93            UnexpectedNewline => write!(f, "this literal does not allow break, use `\\n` instead"),
94            UnexpectedNonAscii => write!(f, "unexpected non ascii in byte string"),
95            UnexpectedUnicodeEscape => write!(f, "unexpected unicode escape in byte string"),
96            UnbalancedLiteralClose => write!(f, "unbalanced literal close"),
97            InvalidNumber(e) => write!(f, "{}", e),
98            InvalidCharacterTooLess => write!(f, "character literal must contain one codepoint"),
99            InvalidCharacterTooMany => write!(f, "character literal may only contain one codepoint"),
100            InvalidBytesEncoding(e) => write!(f, "{}", e),
101            InvalidEscape => write!(f, "invalid escape"),
102            InvalidAsciiEscape => write!(f, "ASCII hex escape code must be at most 0x7F"),
103            InvalidUnicodeEscape => write!(f, "Unicode escape code muse be at most 10FFFF"),
104
105            ExpectedComma => write!(f, "expected comma"),
106            ExpectedFatArrow => write!(f, "expected fat arrow"),
107            ExpectedNonUnitStruct => write!(f, "expected non-unit struct (newtype, tuple or map)"),
108            ExpectedVariant => write!(f, "expected variant (an identifier)"),
109            ExpectedUnitVariant => write!(f, "expected unit variant"),
110            ExpectedNewtypeVariant => write!(f, "expected newtype variant"),
111            ExpectedTupleVariant => write!(f, "expected tuple variant"),
112            ExpectedStructVariant => write!(f, "expected struct variant"),
113            ExpectedEof => write!(f, "expected EOF"),
114
115            Io(e) => write!(f, "(IO) {}", e),
116            Serialize(e) => write!(f, "(serialize) {}", e),
117            Deserialize(e) => write!(f, "(deserialize) {}", e),
118
119            ExceededRecursionLimit => write!(f, "exceeded recursion limit"),
120        }
121    }
122}