sentience_tokenize/
error.rs1use crate::Span;
2use std::fmt;
3
4#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub enum LexErrorKind {
7 UnexpectedChar,
8 UnterminatedString,
9 UnterminatedEscape,
10 InvalidNumber,
11 InvalidEscape,
12}
13
14#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct LexError {
17 pub kind: LexErrorKind,
18 pub span: Span,
19}
20
21impl LexError {
22 pub fn new(kind: LexErrorKind, span: Span) -> Self {
23 Self { kind, span }
24 }
25}
26
27impl LexErrorKind {
28 pub fn as_str(&self) -> &'static str {
29 match self {
30 LexErrorKind::UnexpectedChar => "unexpected character",
31 LexErrorKind::UnterminatedString => "unterminated string",
32 LexErrorKind::UnterminatedEscape => "unterminated escape",
33 LexErrorKind::InvalidNumber => "invalid number",
34 LexErrorKind::InvalidEscape => "invalid escape sequence",
35 }
36 }
37}
38
39impl fmt::Display for LexError {
40 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41 let msg = match self.kind {
42 LexErrorKind::UnexpectedChar => "unexpected char",
43 LexErrorKind::UnterminatedString => "unterminated string",
44 LexErrorKind::UnterminatedEscape => "unterminated escape",
45 LexErrorKind::InvalidNumber => "invalid number",
46 LexErrorKind::InvalidEscape => "invalid escape",
47 };
48 write!(f, "{} at {}..{}", msg, self.span.start, self.span.end)
49 }
50}
51
52impl std::error::Error for LexError {}