Skip to main content

gql_parser/
error.rs

1use std::fmt;
2
3use crate::token::TokenKind;
4
5pub type Result<T> = std::result::Result<T, Error>;
6
7#[derive(Clone, Debug, PartialEq, Eq)]
8pub enum Error {
9    UnrecognizedToken {
10        offset: usize,
11        token_text: String,
12    },
13    UnterminatedString {
14        offset: usize,
15        token_text: String,
16    },
17    UnterminatedBlockComment {
18        offset: usize,
19        token_text: String,
20    },
21    BadNumber {
22        offset: usize,
23        token_text: String,
24    },
25    UnexpectedEof,
26    UnexpectedToken {
27        offset: usize,
28        expected: Vec<TokenKind>,
29        got: TokenKind,
30        token_text: String,
31    },
32    Message {
33        offset: usize,
34        message: String,
35    },
36}
37
38impl Error {
39    pub(crate) fn expected(
40        offset: usize,
41        expected: impl Into<Vec<TokenKind>>,
42        got: TokenKind,
43        token_text: impl Into<String>,
44    ) -> Self {
45        Self::UnexpectedToken {
46            offset,
47            expected: expected.into(),
48            got,
49            token_text: token_text.into(),
50        }
51    }
52}
53
54impl fmt::Display for Error {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        match self {
57            Self::UnrecognizedToken { offset, token_text } => {
58                write!(f, "unrecognized token '{token_text}' at offset {offset}")
59            }
60            Self::UnterminatedString { offset, token_text } => {
61                write!(f, "unterminated string '{token_text}' at offset {offset}")
62            }
63            Self::UnterminatedBlockComment { offset, token_text } => {
64                write!(
65                    f,
66                    "unterminated block comment '{token_text}' at offset {offset}"
67                )
68            }
69            Self::BadNumber { offset, token_text } => {
70                write!(f, "bad number '{token_text}' at offset {offset}")
71            }
72            Self::UnexpectedEof => write!(f, "incomplete input"),
73            Self::UnexpectedToken {
74                offset,
75                expected,
76                got,
77                token_text,
78            } => write!(
79                f,
80                "near '{token_text}' at offset {offset}: expected {expected:?}, got {got:?}"
81            ),
82            Self::Message { offset, message } => write!(f, "{message} at offset {offset}"),
83        }
84    }
85}
86
87impl std::error::Error for Error {}