mago_codex/ttype/
error.rs

1use mago_span::HasSpan;
2use mago_span::Span;
3use serde::Serialize;
4
5use mago_type_syntax::error::ParseError;
6
7#[derive(Debug, Clone, Eq, PartialEq, Serialize)]
8pub enum TypeError {
9    ParseError(ParseError),
10    UnsupportedType(String, Span),
11    InvalidType(String, String, Span),
12}
13
14impl std::fmt::Display for TypeError {
15    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16        match self {
17            TypeError::ParseError(err) => write!(f, "{err}"),
18            TypeError::UnsupportedType(ty, _) => {
19                write!(f, "The type `{ty}` is not supported.")
20            }
21            TypeError::InvalidType(_, message, _) => {
22                write!(f, "{message}")
23            }
24        }
25    }
26}
27
28impl TypeError {
29    pub fn note(&self) -> String {
30        match self {
31            TypeError::ParseError(err) => err.note(),
32            TypeError::UnsupportedType(ty, _) => {
33                format!("The type `{ty}` is syntactically valid but is not yet supported.")
34            }
35            TypeError::InvalidType(ty, _, _) => {
36                format!("The type declaration `{ty}` is not valid or could not be resolved.")
37            }
38        }
39    }
40
41    pub fn help(&self) -> String {
42        match self {
43            TypeError::ParseError(err) => err.help(),
44            TypeError::UnsupportedType(_, _) => "Try using a simpler or more standard type declaration.".to_string(),
45            TypeError::InvalidType(_, _, _) => {
46                "Check for typos or ensure the type is a valid class, interface, or built-in type.".to_string()
47            }
48        }
49    }
50}
51
52// Ensure HasSpan is implemented for TypeError to get the location of the error
53impl HasSpan for TypeError {
54    fn span(&self) -> Span {
55        match self {
56            TypeError::ParseError(err) => err.span(),
57            TypeError::UnsupportedType(_, span) | TypeError::InvalidType(_, _, span) => *span,
58        }
59    }
60}
61
62impl From<ParseError> for TypeError {
63    fn from(err: ParseError) -> Self {
64        TypeError::ParseError(err)
65    }
66}