Skip to main content

ratex_parser/
error.rs

1use ratex_lexer::token::{SourceLocation, Token};
2
3/// Error type for the parser, modeled after KaTeX's ParseError.
4#[derive(Debug, Clone)]
5pub struct ParseError {
6    pub message: String,
7    pub loc: Option<SourceLocation>,
8}
9
10impl ParseError {
11    pub fn new(message: impl Into<String>, token: Option<&Token>) -> Self {
12        Self {
13            message: message.into(),
14            loc: token.map(|t| t.loc.clone()),
15        }
16    }
17
18    pub fn msg(message: impl Into<String>) -> Self {
19        Self {
20            message: message.into(),
21            loc: None,
22        }
23    }
24
25    pub fn at(message: impl Into<String>, loc: SourceLocation) -> Self {
26        Self {
27            message: message.into(),
28            loc: Some(loc),
29        }
30    }
31}
32
33impl std::fmt::Display for ParseError {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        if let Some(ref loc) = self.loc {
36            write!(f, "ParseError at position {}: {}", loc.start, self.message)
37        } else {
38            write!(f, "ParseError: {}", self.message)
39        }
40    }
41}
42
43impl std::error::Error for ParseError {}
44
45pub type ParseResult<T> = Result<T, ParseError>;