Skip to main content

xidl_parser/
error.rs

1use std::error::Error;
2use std::fmt;
3
4/// Errors raised while turning IDL source into a typed AST.
5#[derive(Debug, Clone)]
6pub enum ParseError {
7    /// Free-form parse failure.
8    Message(String),
9    /// Source bytes that are not valid UTF-8.
10    Utf8Error(std::str::Utf8Error),
11    /// A tree-sitter node that did not match the expected grammar shape.
12    UnexpectedNode(String),
13    /// Failure reported by tree-sitter itself.
14    TreeSitterError(String),
15}
16
17impl fmt::Display for ParseError {
18    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19        match self {
20            Self::Message(message) => f.write_str(message),
21            Self::Utf8Error(err) => write!(f, "{err}"),
22            Self::UnexpectedNode(node) => write!(f, "Unexpected node: {node}"),
23            Self::TreeSitterError(message) => write!(f, "TreeSitterError: {message}"),
24        }
25    }
26}
27
28impl Error for ParseError {
29    fn source(&self) -> Option<&(dyn Error + 'static)> {
30        match self {
31            Self::Utf8Error(err) => Some(err),
32            _ => None,
33        }
34    }
35}
36
37impl From<std::str::Utf8Error> for ParseError {
38    fn from(err: std::str::Utf8Error) -> Self {
39        Self::Utf8Error(err)
40    }
41}
42
43/// Result type for parser operations.
44pub type ParserResult<T> = Result<T, ParseError>;