Skip to main content

shape_ast/error/
conversions.rs

1//! Type conversions for ShapeError
2//!
3//! This module contains From trait implementations for converting
4//! various error types into ShapeError.
5
6use super::types::{ShapeError, SourceLocation};
7use std::io;
8
9/// Convert from pest::error::Error to ShapeError for parser Rule
10impl From<pest::error::Error<crate::parser::Rule>> for ShapeError {
11    fn from(err: pest::error::Error<crate::parser::Rule>) -> Self {
12        let location = match err.line_col {
13            pest::error::LineColLocation::Pos((line, col)) => Some(SourceLocation::new(line, col)),
14            pest::error::LineColLocation::Span((line, col), _) => {
15                Some(SourceLocation::new(line, col))
16            }
17        };
18
19        ShapeError::ParseError {
20            message: format!("{}", err),
21            location,
22        }
23    }
24}
25
26/// Convert from anyhow::Error to ShapeError
27impl From<anyhow::Error> for ShapeError {
28    fn from(err: anyhow::Error) -> Self {
29        // Try to downcast to known error types
30        if let Some(shape_err) = err.downcast_ref::<ShapeError>() {
31            return shape_err.clone();
32        }
33
34        if let Some(io_err) = err.downcast_ref::<io::Error>() {
35            return ShapeError::IoError(io::Error::new(io_err.kind(), io_err.to_string()));
36        }
37
38        // Default to custom error with the error message
39        ShapeError::Custom(err.to_string())
40    }
41}
42
43/// Convert from serde_json::Error to ShapeError
44impl From<serde_json::Error> for ShapeError {
45    fn from(err: serde_json::Error) -> Self {
46        ShapeError::Custom(format!("JSON error: {}", err))
47    }
48}