Skip to main content

rdom_parser/
error.rs

1//! `ParseError` — human-friendly error reporting for malformed templates.
2
3use std::fmt;
4
5/// Parse error with position + optional hint.
6#[derive(Debug, Clone, PartialEq, Eq)]
7#[non_exhaustive]
8pub struct ParseError {
9    /// Human-readable error message.
10    pub msg: String,
11    /// 1-indexed line number where the error was detected.
12    pub line: u32,
13    /// 1-indexed column number (in bytes, not graphemes — sufficient
14    /// for source-error purposes; human debugging uses the source text).
15    pub col: u32,
16    /// Byte offset into the input for tooling.
17    pub pos: usize,
18    /// Optional suggestion for how to fix.
19    pub hint: Option<String>,
20}
21
22impl ParseError {
23    pub fn new(msg: impl Into<String>, line: u32, col: u32, pos: usize) -> Self {
24        Self {
25            msg: msg.into(),
26            line,
27            col,
28            pos,
29            hint: None,
30        }
31    }
32
33    pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
34        self.hint = Some(hint.into());
35        self
36    }
37}
38
39impl fmt::Display for ParseError {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        write!(
42            f,
43            "parse error at line {}, col {}: {}",
44            self.line, self.col, self.msg
45        )?;
46        if let Some(hint) = &self.hint {
47            write!(f, " (hint: {})", hint)?;
48        }
49        Ok(())
50    }
51}
52
53impl std::error::Error for ParseError {}
54
55/// `Result` alias for parser operations.
56pub type Result<T> = std::result::Result<T, ParseError>;