dampen_core/parser/
error.rs

1use crate::ir::span::Span;
2use proc_macro2::TokenStream;
3use quote::quote;
4
5/// Error during parsing
6#[derive(Debug, Clone, PartialEq)]
7pub struct ParseError {
8    pub kind: ParseErrorKind,
9    pub message: String,
10    pub span: Span,
11    pub suggestion: Option<String>,
12}
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum ParseErrorKind {
16    XmlSyntax,
17    UnknownWidget,
18    UnknownAttribute,
19    InvalidValue,
20    InvalidExpression,
21    UnclosedBinding,
22    MissingAttribute,
23    /// Schema version is newer than the framework supports
24    UnsupportedVersion,
25}
26
27impl std::fmt::Display for ParseError {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        write!(
30            f,
31            "error[{}]: {} at line {}, column {}",
32            self.kind as u8, self.message, self.span.line, self.span.column
33        )?;
34        if let Some(suggestion) = &self.suggestion {
35            write!(f, "\n  help: {}", suggestion)?;
36        }
37        Ok(())
38    }
39}
40
41impl ParseError {
42    /// Convert this error into a compile_error! macro invocation.
43    ///
44    /// This is used by procedural macros to emit compile-time errors
45    /// with proper location information and helpful suggestions.
46    ///
47    /// # Returns
48    ///
49    /// A `TokenStream` containing a `compile_error!` macro invocation.
50    pub fn to_compile_error(&self) -> TokenStream {
51        let message = format!(
52            "Dampen parsing error: {}\n  at line {}, column {}",
53            self.message, self.span.line, self.span.column
54        );
55
56        let mut tokens = quote! {
57            compile_error!(#message);
58        };
59
60        if let Some(ref suggestion) = self.suggestion {
61            let help = format!("help: {}", suggestion);
62            tokens.extend(quote! {
63                compile_error!(#help);
64            });
65        }
66
67        tokens
68    }
69}