1
pub use conjure_cp_core::error::Error as ConjureParseError;
2
use conjure_cp_core::error::Error;
3
use serde_json::Error as JsonError;
4
use thiserror::Error as ThisError;
5

            
6
#[derive(Debug, ThisError)]
7
pub enum FatalParseError {
8
    #[error("Could not parse Essence AST: {0}")]
9
    TreeSitterError(String),
10
    #[error("Error running `conjure pretty`: {0}")]
11
    ConjurePrettyError(String),
12
    #[error("Internal parser error: {msg}{}\nThis indicates a bug in the parser or syntax validator. Please report this issue.",
13
        match range {
14
            Some(range) => format!(" at {}-{}", range.start_point, range.end_point),
15
            None => "".to_string(),
16
        }
17
    )]
18
    InternalError {
19
        msg: String,
20
        range: Option<tree_sitter::Range>,
21
    },
22
    #[error("JSON Error: {0}")]
23
    JsonError(#[from] JsonError),
24
    #[error("Error: {0} is not yet implemented.")]
25
    NotImplemented(String),
26
    #[error("Error: {0}")]
27
    Other(Error),
28
}
29

            
30
impl FatalParseError {
31
58105
    pub fn internal_error(msg: String, range: Option<tree_sitter::Range>) -> Self {
32
58105
        FatalParseError::InternalError { msg, range }
33
58105
    }
34
}
35

            
36
impl From<ConjureParseError> for FatalParseError {
37
37
    fn from(value: ConjureParseError) -> Self {
38
37
        match value {
39
37
            Error::Parse(msg) => FatalParseError::internal_error(msg, None),
40
            Error::NotImplemented(msg) => FatalParseError::NotImplemented(msg),
41
            Error::Json(err) => FatalParseError::JsonError(err),
42
            Error::Other(err) => FatalParseError::Other(err.into()),
43
        }
44
37
    }
45
}
46

            
47
#[derive(Debug)]
48
pub struct RecoverableParseError {
49
    pub msg: String,
50
    pub range: Option<tree_sitter::Range>,
51
    pub file_name: Option<String>,
52
    pub source_code: Option<String>,
53
}
54

            
55
impl RecoverableParseError {
56
2789
    pub fn new(msg: String, range: Option<tree_sitter::Range>) -> Self {
57
2789
        Self {
58
2789
            msg,
59
2789
            range,
60
2789
            file_name: None,
61
2789
            source_code: None,
62
2789
        }
63
2789
    }
64

            
65
1556
    pub fn enrich(mut self, file_name: Option<String>, source_code: Option<String>) -> Self {
66
1556
        self.file_name = file_name;
67
1556
        self.source_code = source_code;
68
1556
        self
69
1556
    }
70
}
71

            
72
impl std::fmt::Display for RecoverableParseError {
73
1556
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
74
        // If we have all the info, format nicely with source context
75
1556
        if let (Some(range), Some(file_name), Some(source_code)) =
76
1556
            (&self.range, &self.file_name, &self.source_code)
77
        {
78
1556
            let line_num = range.start_point.row + 1; // tree-sitter uses 0-indexed rows
79
1556
            let col_num = range.start_point.column + 1; // tree-sitter uses 0-indexed columns
80

            
81
            // Get the specific line from source code
82
1556
            let lines: Vec<&str> = source_code.lines().collect();
83
1556
            let line_content = lines.get(range.start_point.row).unwrap_or(&"");
84

            
85
            // Build the pointer line (spaces + ^)
86
1556
            let pointer = " ".repeat(range.start_point.column) + "^";
87

            
88
1556
            write!(
89
1556
                f,
90
                "{}:{}:{}:\n  |\n{} | {}\n  | {}\n{}",
91
                file_name, line_num, col_num, line_num, line_content, pointer, self.msg
92
            )
93
        } else {
94
            // Fall back to simple format without context
95
            write!(f, "Essence syntax error: {}", self.msg)?;
96
            if let Some(range) = &self.range {
97
                write!(f, " at {}-{}", range.start_point, range.end_point)?;
98
            }
99
            Ok(())
100
        }
101
1556
    }
102
}
103

            
104
/// Collection of parse errors
105
#[derive(Debug)]
106
pub enum ParseErrorCollection {
107
    /// A single fatal error that stops parsing entirely
108
    Fatal(FatalParseError),
109
    /// Multiple recoverable errors accumulated during parsing
110
    Multiple { errors: Vec<RecoverableParseError> },
111
}
112

            
113
impl ParseErrorCollection {
114
    /// Create a fatal error collection from a single fatal error
115
1142
    pub fn fatal(error: FatalParseError) -> Self {
116
1142
        ParseErrorCollection::Fatal(error)
117
1142
    }
118

            
119
    /// Create a multiple error collection from recoverable errors
120
    /// This enriches all errors with file_name and source_code
121
1240
    pub fn multiple(
122
1240
        errors: Vec<RecoverableParseError>,
123
1240
        source_code: Option<String>,
124
1240
        file_name: Option<String>,
125
1240
    ) -> Self {
126
1240
        let enriched_errors = errors
127
1240
            .into_iter()
128
1556
            .map(|err| err.enrich(file_name.clone(), source_code.clone()))
129
1240
            .collect();
130
1240
        ParseErrorCollection::Multiple {
131
1240
            errors: enriched_errors,
132
1240
        }
133
1240
    }
134
}
135

            
136
impl std::fmt::Display for ParseErrorCollection {
137
2382
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138
2382
        match self {
139
1142
            ParseErrorCollection::Fatal(error) => write!(f, "{}", error),
140
1240
            ParseErrorCollection::Multiple { errors } => {
141
                // Create indices sorted by line and column
142
1240
                let mut indices: Vec<usize> = (0..errors.len()).collect();
143
1240
                indices.sort_by(|&a, &b| {
144
316
                    match (&errors[a], &errors[b]) {
145
                        (
146
                            RecoverableParseError {
147
316
                                range: Some(r1), ..
148
                            },
149
                            RecoverableParseError {
150
316
                                range: Some(r2), ..
151
                            },
152
                        ) => {
153
                            // Compare by row first, then by column
154
316
                            match r1.start_point.row.cmp(&r2.start_point.row) {
155
                                std::cmp::Ordering::Equal => {
156
34
                                    r1.start_point.column.cmp(&r2.start_point.column)
157
                                }
158
282
                                other => other,
159
                            }
160
                        }
161
                        // Errors without ranges go last
162
                        (RecoverableParseError { range: Some(_), .. }, _) => {
163
                            std::cmp::Ordering::Less
164
                        }
165
                        (_, RecoverableParseError { range: Some(_), .. }) => {
166
                            std::cmp::Ordering::Greater
167
                        }
168
                        _ => std::cmp::Ordering::Equal,
169
                    }
170
316
                });
171

            
172
                // Print out each error using Display
173
1556
                for (i, &idx) in indices.iter().enumerate() {
174
1556
                    if i > 0 {
175
316
                        write!(f, "\n\n")?;
176
1240
                    }
177
1556
                    write!(f, "{}", errors[idx])?;
178
                }
179
1240
                Ok(())
180
            }
181
        }
182
2382
    }
183
}
184

            
185
impl std::error::Error for ParseErrorCollection {}