Skip to main content

mago_codex/ttype/
error.rs

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