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 RecursionLimitExceeded(Span),
24}
25
26impl ParseError {
27 #[must_use]
29 pub fn note(&self) -> String {
30 match self {
31 ParseError::SyntaxError(SyntaxError::UnrecognizedToken(_, _, _)) => {
32 "An invalid character was found that is not part of any valid type syntax.".to_string()
33 }
34 ParseError::SyntaxError(_) => {
35 "A low-level syntax error occurred while parsing the type string.".to_string()
36 }
37 ParseError::UnexpectedEndOfFile(_, expected, _) => {
38 if expected.is_empty() {
39 "The type declaration ended prematurely.".to_string()
40 } else {
41 let expected_str = expected.iter().map(|t| format!("`{t}`")).collect::<Vec<_>>().join(" or ");
42 format!("The parser reached the end of the input but expected one of: {expected_str}.")
43 }
44 }
45 ParseError::UnexpectedToken(expected, _, _) => {
46 if expected.is_empty() {
47 "The parser encountered a token that was not expected at this position.".to_string()
48 } else {
49 let expected_str = expected.iter().map(|t| format!("`{t}`")).collect::<Vec<_>>().join(" or ");
50 format!("The parser expected one of the following here: {expected_str}.")
51 }
52 }
53 ParseError::UnclosedLiteralString(_) => {
54 "String literals within type declarations must be closed with a matching quote.".to_string()
55 }
56 ParseError::RecursionLimitExceeded(_) => {
57 "The type is nested too deeply for the parser to process.".to_string()
58 }
59 }
60 }
61
62 #[must_use]
64 pub fn help(&self) -> String {
65 match self {
66 ParseError::SyntaxError(SyntaxError::UnrecognizedToken(_, _, _)) => {
67 "Remove or replace the invalid character.".to_string()
68 }
69 ParseError::SyntaxError(_) => "Review the syntax of the type declaration for errors.".to_string(),
70 ParseError::UnexpectedEndOfFile(_, _, _) => {
71 "Complete the type declaration. Check for unclosed parentheses `()`, angle brackets `<>`, or curly braces `{}`.".to_string()
72 }
73 ParseError::UnexpectedToken(_, _, _) => {
74 "Review the type syntax near the unexpected token.".to_string()
75 }
76 ParseError::UnclosedLiteralString(_) => {
77 "Add a closing quote (`'` or `\"`) to complete the string literal.".to_string()
78 }
79 ParseError::RecursionLimitExceeded(_) => {
80 "Simplify the type by reducing how deeply it is nested.".to_string()
81 }
82 }
83 }
84}
85
86impl HasSpan for SyntaxError {
87 fn span(&self) -> Span {
88 let (file_id, position) = match self {
89 SyntaxError::UnexpectedToken(file_id, _, position) => (*file_id, *position),
90 SyntaxError::UnrecognizedToken(file_id, _, position) => (*file_id, *position),
91 SyntaxError::UnexpectedEndOfFile(file_id, position) => (*file_id, *position),
92 };
93
94 Span::new(file_id, position, position)
95 }
96}
97
98impl HasSpan for ParseError {
99 fn span(&self) -> Span {
100 match self {
101 ParseError::SyntaxError(error) => error.span(),
102 ParseError::UnexpectedEndOfFile(file_id, _, position) => Span::new(*file_id, *position, *position),
103 ParseError::UnexpectedToken(_, _, span) => *span,
104 ParseError::UnclosedLiteralString(span) => *span,
105 ParseError::RecursionLimitExceeded(span) => *span,
106 }
107 }
108}
109
110impl std::fmt::Display for SyntaxError {
111 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112 match self {
113 SyntaxError::UnexpectedToken(_, token, _) => {
114 write!(f, "Unexpected character '{}'", *token as char)
115 }
116 SyntaxError::UnrecognizedToken(_, token, _) => {
117 write!(f, "Unrecognized character '{}'", *token as char)
118 }
119 SyntaxError::UnexpectedEndOfFile(_, _) => {
120 write!(f, "Unexpected end of input")
121 }
122 }
123 }
124}
125
126impl std::fmt::Display for ParseError {
127 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128 match self {
129 ParseError::SyntaxError(err) => write!(f, "{err}"),
130 ParseError::UnexpectedEndOfFile(_, _, _) => {
131 write!(f, "Unexpected end of type declaration")
132 }
133 ParseError::UnexpectedToken(_, token, _) => {
134 write!(f, "Unexpected token `{token}`")
135 }
136 ParseError::UnclosedLiteralString(_) => {
137 write!(f, "Unclosed string literal in type")
138 }
139 ParseError::RecursionLimitExceeded(_) => {
140 write!(f, "Maximum recursion depth exceeded")
141 }
142 }
143 }
144}
145
146impl std::error::Error for SyntaxError {
147 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
148 None
149 }
150}
151
152impl std::error::Error for ParseError {
153 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
154 match self {
155 ParseError::SyntaxError(err) => Some(err),
156 _ => None,
157 }
158 }
159}
160
161impl From<SyntaxError> for ParseError {
162 fn from(error: SyntaxError) -> Self {
163 ParseError::SyntaxError(error)
164 }
165}