Skip to main content

harn_parser/parser/
error.rs

1use harn_lexer::Span;
2use std::fmt;
3
4/// The retired range keyword, kept for diagnostics and the migration.
5pub const REMOVED_RANGE_KEYWORD: &str = "to";
6
7/// Parser errors.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub enum ParserError {
10    Unexpected {
11        got: String,
12        expected: String,
13        span: Span,
14    },
15    UnexpectedEof {
16        expected: String,
17        span: Span,
18    },
19    /// The retired `start to end [exclusive]` range spelling. `span` covers
20    /// the `to` keyword.
21    RemovedRangeSyntax {
22        span: Span,
23    },
24}
25
26impl ParserError {
27    /// The source span the error points at.
28    #[must_use]
29    pub fn span(&self) -> Span {
30        match self {
31            ParserError::Unexpected { span, .. }
32            | ParserError::UnexpectedEof { span, .. }
33            | ParserError::RemovedRangeSyntax { span } => *span,
34        }
35    }
36}
37
38impl fmt::Display for ParserError {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        match self {
41            ParserError::Unexpected {
42                got,
43                expected,
44                span,
45            } => write!(
46                f,
47                "Expected {expected}, got {got} at {}:{}",
48                span.line, span.column
49            ),
50            ParserError::UnexpectedEof { expected, .. } => {
51                write!(f, "Unexpected end of file, expected {expected}")
52            }
53            ParserError::RemovedRangeSyntax { span } => write!(
54                f,
55                "`{REMOVED_RANGE_KEYWORD}` ranges were removed; write `start..=end` (or `start..end` for `exclusive`) at {}:{}",
56                span.line, span.column
57            ),
58        }
59    }
60}
61
62impl std::error::Error for ParserError {}