Skip to main content

bluejay_parser/lexer/
lex_error.rs

1use crate::error::{Annotation, Error};
2use crate::Span;
3
4#[derive(Debug, PartialEq, Clone, Default)]
5pub enum LexError {
6    #[default]
7    UnrecognizedToken,
8    IntegerValueTooLarge,
9    FloatValueTooLarge,
10    StringValueInvalid(Vec<StringValueLexError>),
11    MaxTokensExceeded {
12        limit: usize,
13    },
14}
15
16impl From<Vec<StringValueLexError>> for LexError {
17    fn from(errors: Vec<StringValueLexError>) -> Self {
18        Self::StringValueInvalid(errors)
19    }
20}
21
22#[derive(Debug, PartialEq, Clone)]
23pub enum StringValueLexError {
24    InvalidUnicodeEscapeSequence(Span),
25    InvalidCharacters(Span),
26}
27
28impl From<(LexError, Span)> for Error {
29    fn from((error, span): (LexError, Span)) -> Self {
30        match error {
31            LexError::UnrecognizedToken => Self::new(
32                "Unrecognized token",
33                Some(Annotation::new("Unable to parse", span)),
34                Vec::new(),
35            ),
36            LexError::IntegerValueTooLarge => Self::new(
37                "Value too large to fit in a 32-bit signed integer",
38                Some(Annotation::new("Integer too large", span)),
39                Vec::new(),
40            ),
41            LexError::FloatValueTooLarge => Self::new(
42                "Value too large to fit in a 64-bit float",
43                Some(Annotation::new("Float too large", span)),
44                Vec::new(),
45            ),
46            LexError::StringValueInvalid(errors) => Self::new(
47                "String value invalid",
48                Some(Annotation::new("String value invalid", span)),
49                errors
50                    .into_iter()
51                    .map(|error| {
52                        let (message, span) = match error {
53                            StringValueLexError::InvalidUnicodeEscapeSequence(span) => {
54                                ("Invalid unicode escape sequence", span)
55                            }
56                            StringValueLexError::InvalidCharacters(span) => {
57                                ("Invalid characters", span)
58                            }
59                        };
60                        Annotation::new(message, span)
61                    })
62                    .collect(),
63            ),
64            LexError::MaxTokensExceeded { limit } => Self::new(
65                "Max tokens exceeded",
66                Some(Annotation::new(
67                    format!("Maximum token limit of {limit} exceeded"),
68                    span,
69                )),
70                Vec::new(),
71            ),
72        }
73    }
74}