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    pub fn recursion_limit_exceeded() -> Self {
33        Self::msg("Recursion limit exceeded")
34    }
35}
36
37impl std::fmt::Display for ParseError {
38    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39        if let Some(ref loc) = self.loc {
40            write!(f, "ParseError at position {}: {}", loc.start, self.message)
41        } else {
42            write!(f, "ParseError: {}", self.message)
43        }
44    }
45}
46
47impl std::error::Error for ParseError {}
48
49pub type ParseResult<T> = Result<T, ParseError>;