mago_type_syntax/
error.rs

1use serde::Serialize;
2
3use mago_database::file::FileId;
4use mago_span::HasSpan;
5use mago_span::Position;
6use mago_span::Span;
7
8use crate::token::TypeTokenKind;
9
10#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize)]
11pub enum SyntaxError {
12    UnexpectedToken(FileId, u8, Position),
13    UnrecognizedToken(FileId, u8, Position),
14    UnexpectedEndOfFile(FileId, Position),
15}
16
17#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
18pub enum ParseError {
19    SyntaxError(SyntaxError),
20    UnexpectedEndOfFile(FileId, Vec<TypeTokenKind>, Position),
21    UnexpectedToken(Vec<TypeTokenKind>, TypeTokenKind, Span),
22    UnclosedLiteralString(Span),
23}
24
25impl ParseError {
26    /// Provides a detailed, user-friendly note explaining the context of the parse error.
27    pub fn note(&self) -> String {
28        match self {
29            ParseError::SyntaxError(SyntaxError::UnrecognizedToken(_, _, _)) => {
30                "An invalid character was found that is not part of any valid type syntax.".to_string()
31            }
32            ParseError::SyntaxError(_) => {
33                "A low-level syntax error occurred while parsing the type string.".to_string()
34            }
35            ParseError::UnexpectedEndOfFile(_, expected, _) => {
36                if expected.is_empty() {
37                    "The type declaration ended prematurely.".to_string()
38                } else {
39                    let expected_str = expected.iter().map(|t| format!("`{t}`")).collect::<Vec<_>>().join(" or ");
40                    format!("The parser reached the end of the input but expected one of: {expected_str}.")
41                }
42            }
43            ParseError::UnexpectedToken(expected, _, _) => {
44                if expected.is_empty() {
45                    "The parser encountered a token that was not expected at this position.".to_string()
46                } else {
47                    let expected_str = expected.iter().map(|t| format!("`{t}`")).collect::<Vec<_>>().join(" or ");
48                    format!("The parser expected one of the following here: {expected_str}.")
49                }
50            }
51            ParseError::UnclosedLiteralString(_) => {
52                "String literals within type declarations must be closed with a matching quote.".to_string()
53            }
54        }
55    }
56
57    /// Provides a concise, actionable help message suggesting a fix for the error.
58    pub fn help(&self) -> String {
59        match self {
60            ParseError::SyntaxError(SyntaxError::UnrecognizedToken(_, _, _)) => {
61                "Remove or replace the invalid character.".to_string()
62            }
63            ParseError::SyntaxError(_) => "Review the syntax of the type declaration for errors.".to_string(),
64            ParseError::UnexpectedEndOfFile(_, _, _) => {
65                "Complete the type declaration. Check for unclosed parentheses `()`, angle brackets `<>`, or curly braces `{}`.".to_string()
66            }
67            ParseError::UnexpectedToken(_, _, _) => {
68                "Review the type syntax near the unexpected token.".to_string()
69            }
70            ParseError::UnclosedLiteralString(_) => {
71                "Add a closing quote (`'` or `\"`) to complete the string literal.".to_string()
72            }
73        }
74    }
75}
76
77impl HasSpan for SyntaxError {
78    fn span(&self) -> Span {
79        let (file_id, position) = match self {
80            SyntaxError::UnexpectedToken(file_id, _, position) => (*file_id, *position),
81            SyntaxError::UnrecognizedToken(file_id, _, position) => (*file_id, *position),
82            SyntaxError::UnexpectedEndOfFile(file_id, position) => (*file_id, *position),
83        };
84
85        Span::new(file_id, position, position)
86    }
87}
88
89impl HasSpan for ParseError {
90    fn span(&self) -> Span {
91        match self {
92            ParseError::SyntaxError(error) => error.span(),
93            ParseError::UnexpectedEndOfFile(file_id, _, position) => Span::new(*file_id, *position, *position),
94            ParseError::UnexpectedToken(_, _, span) => *span,
95            ParseError::UnclosedLiteralString(span) => *span,
96        }
97    }
98}
99
100impl std::fmt::Display for SyntaxError {
101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102        match self {
103            SyntaxError::UnexpectedToken(_, token, _) => {
104                write!(f, "Unexpected character '{}'", *token as char)
105            }
106            SyntaxError::UnrecognizedToken(_, token, _) => {
107                write!(f, "Unrecognized character '{}'", *token as char)
108            }
109            SyntaxError::UnexpectedEndOfFile(_, _) => {
110                write!(f, "Unexpected end of input")
111            }
112        }
113    }
114}
115
116impl std::fmt::Display for ParseError {
117    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
118        match self {
119            ParseError::SyntaxError(err) => write!(f, "{err}"),
120            ParseError::UnexpectedEndOfFile(_, _, _) => {
121                write!(f, "Unexpected end of type declaration")
122            }
123            ParseError::UnexpectedToken(_, token, _) => {
124                write!(f, "Unexpected token `{token}`")
125            }
126            ParseError::UnclosedLiteralString(_) => {
127                write!(f, "Unclosed string literal in type")
128            }
129        }
130    }
131}
132
133impl std::error::Error for SyntaxError {
134    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
135        None
136    }
137}
138
139impl std::error::Error for ParseError {
140    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
141        match self {
142            ParseError::SyntaxError(err) => Some(err),
143            _ => None,
144        }
145    }
146}
147
148impl From<SyntaxError> for ParseError {
149    fn from(error: SyntaxError) -> Self {
150        ParseError::SyntaxError(error)
151    }
152}