ziyy_core/
error.rs

1use crate::Span;
2
3/// Represents the various types of errors that can occur.
4#[derive(Debug)]
5#[non_exhaustive]
6pub enum ErrorType {
7    /// Indicates an invalid tag was encountered.
8    InvalidTag,
9    /// Indicates an invalid tag name was encountered.
10    InvalidTagName,
11    /// Indicates an invalid value for a tag property was encountered.
12    InvalidTagAttributeValue,
13    /// Indicates an invalid number was encountered.
14    InvalidNumber,
15    /// Indicates an invalid color was encountered.
16    InvalidColor,
17    /// Indicates an unexpected token was encountered.
18    UnexpectedToken,
19    /// Indicates the end of input was reached unexpectedly.
20    UnexpectedEof,
21    /// Indicates an unterminated string literal.
22    UnterminatedString,
23}
24
25/// Represents an error with additional context such as its type, message, and location.
26pub struct Error {
27    /// The type of the error.
28    pub r#type: ErrorType,
29    /// A descriptive message providing more details about the error.
30    pub message: String,
31    /// The span in the source where the error occurred.
32    pub span: Span,
33}
34
35impl Error {
36    /// Creates a new Error.
37    pub fn new(r#type: ErrorType, message: String, span: Span) -> Self {
38        Self {
39            r#type,
40            message,
41            span,
42        }
43    }
44
45    #[allow(dead_code)]
46    pub(crate) fn invalid_tag(s: String, span: Span) -> Self {
47        Self {
48            r#type: ErrorType::InvalidTag,
49            message: s,
50            span,
51        }
52    }
53}
54
55impl std::fmt::Display for Error {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        write!(f, "Error: {} at span {:?}", self.message, self.span)
58    }
59}
60
61impl std::error::Error for Error {
62    fn description(&self) -> &str {
63        &self.message
64    }
65}
66
67impl std::fmt::Debug for Error {
68    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
69        write!(
70            f,
71            "Error: {:?} at line {:?}: {}",
72            self.r#type, self.span, self.message
73        )
74    }
75}
76
77impl std::fmt::Display for ErrorType {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        write!(f, "{self:?}")
80    }
81}
82
83/// A type alias for results that return an `Error` on failure.
84pub type Result<T> = std::result::Result<T, Error>;