Skip to main content

linkrs_query/parser/lexing/
error.rs

1pub use super::lexer::Lexer;
2pub use crate::parser::{Token, TokenKind};
3
4use std::fmt;
5
6use linkrs_core::types::Position;
7
8#[derive(Debug, Clone, PartialEq)]
9pub struct LexError {
10    pub message: Box<str>,
11    pub position: Position,
12    pub offset: Option<usize>,
13}
14
15impl LexError {
16    pub fn new(message: impl Into<Box<str>>, position: Position) -> Self {
17        LexError {
18            message: message.into(),
19            position,
20            offset: None,
21        }
22    }
23
24    pub fn with_offset(mut self, offset: usize) -> Self {
25        self.offset = Some(offset);
26        self
27    }
28
29    pub fn unterminated_string(position: Position) -> Self {
30        LexError::new("Unterminated string literal", position)
31    }
32
33    pub fn unterminated_comment(position: Position) -> Self {
34        LexError::new("Unterminated multi-line comment", position)
35    }
36
37    pub fn invalid_number<T: fmt::Display>(message: T, position: Position) -> Self {
38        LexError::new(format!("Invalid number: {}", message), position)
39    }
40
41    pub fn invalid_escape_sequence<T: fmt::Display>(sequence: T, position: Position) -> Self {
42        LexError::new(format!("Invalid escape sequence: \\{}", sequence), position)
43    }
44
45    pub fn unexpected_character(ch: char, position: Position) -> Self {
46        LexError::new(format!("Unexpected character: '{}'", ch), position)
47    }
48
49    pub fn unexpected_end_of_input(position: Position) -> Self {
50        LexError::new("Unexpected end of input", position)
51    }
52}
53
54impl std::fmt::Display for LexError {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        write!(
57            f,
58            "Lex error at line {}, column {}: {}",
59            self.position.line, self.position.column, self.message
60        )
61    }
62}
63
64impl std::error::Error for LexError {}