1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
//! Errors generated by the compiler.
use itertools::Itertools;

use crate::{GPosIdx, Id, WithPos};

/// Convience wrapper to represent success or meaningul compiler error.
pub type CalyxResult<T> = std::result::Result<T, Error>;

/// Errors generated by the compiler
#[derive(Clone)]
pub struct Error {
    kind: Box<ErrorKind>,
    pos: GPosIdx,
    annotations: Vec<(GPosIdx, String)>,
    post_msg: Option<String>,
}

/// A collection of errors generated by the compiler
pub struct MultiError {
    errors: Vec<Error>,
}

impl From<Vec<Error>> for MultiError {
    fn from(errors: Vec<Error>) -> Self {
        MultiError { errors }
    }
}

impl std::fmt::Debug for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.pos == GPosIdx::UNKNOWN {
            write!(f, "{}", self.kind)?
        } else {
            write!(f, "{}", self.pos.format(self.kind.to_string()))?;
            for (other_pos, msg) in &self.annotations {
                write!(f, "\n...\n{}", other_pos.format_raw(msg))?;
            }
        }
        if let Some(post) = &self.post_msg {
            write!(f, "\n{}", post)?;
        }
        Ok(())
    }
}

impl std::fmt::Debug for MultiError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let errors = self.errors.iter().map(|e| format!("{e:?}")).join("\n\n");
        write!(f, "{errors}")
    }
}

impl Error {
    pub fn with_pos<T: WithPos>(mut self, pos: &T) -> Self {
        self.pos = pos.copy_span();
        self
    }

    pub fn with_annotation<T: WithPos, S: ToString>(
        mut self,
        pos: &T,
        msg: S,
    ) -> Self {
        self.annotations.push((pos.copy_span(), msg.to_string()));
        self
    }

    pub fn with_annotations<T: WithPos, S: ToString>(
        mut self,
        pos_iter: impl Iterator<Item = (T, S)>,
    ) -> Self {
        self.annotations.extend(
            pos_iter.map(|(pos, msg)| (pos.copy_span(), msg.to_string())),
        );
        self
    }

    pub fn with_post_msg(mut self, msg: Option<String>) -> Self {
        self.post_msg = msg;
        self
    }

    pub fn reserved_name(name: Id) -> Self {
        Self {
            kind: Box::new(ErrorKind::ReservedName(name)),
            pos: GPosIdx::UNKNOWN,
            annotations: vec![],
            post_msg: None,
        }
    }
    pub fn malformed_control<S: ToString>(msg: S) -> Self {
        Self {
            kind: Box::new(ErrorKind::MalformedControl(msg.to_string())),
            pos: GPosIdx::UNKNOWN,
            annotations: vec![],
            post_msg: None,
        }
    }
    pub fn malformed_structure<S: ToString>(msg: S) -> Self {
        Self {
            kind: Box::new(ErrorKind::MalformedStructure(msg.to_string())),
            pos: GPosIdx::UNKNOWN,
            annotations: vec![],
            post_msg: None,
        }
    }
    pub fn pass_assumption<S: ToString, M: ToString>(pass: S, msg: M) -> Self {
        Self {
            kind: Box::new(ErrorKind::PassAssumption(
                pass.to_string(),
                msg.to_string(),
            )),
            pos: GPosIdx::UNKNOWN,
            annotations: vec![],
            post_msg: None,
        }
    }
    pub fn undefined<S: ToString>(name: Id, typ: S) -> Self {
        Self {
            kind: Box::new(ErrorKind::Undefined(name, typ.to_string())),
            pos: GPosIdx::UNKNOWN,
            annotations: vec![],
            post_msg: None,
        }
    }
    pub fn already_bound<S: ToString>(name: Id, typ: S) -> Self {
        Self {
            kind: Box::new(ErrorKind::AlreadyBound(name, typ.to_string())),
            pos: GPosIdx::UNKNOWN,
            annotations: vec![],
            post_msg: None,
        }
    }
    pub fn unused<S: ToString>(group: Id, typ: S) -> Self {
        Self {
            kind: Box::new(ErrorKind::Unused(group, typ.to_string())),
            pos: GPosIdx::UNKNOWN,
            annotations: vec![],
            post_msg: None,
        }
    }
    pub fn papercut<S: ToString>(msg: S) -> Self {
        Self {
            kind: Box::new(ErrorKind::Papercut(msg.to_string())),
            pos: GPosIdx::UNKNOWN,
            annotations: vec![],
            post_msg: None,
        }
    }
    pub fn misc<S: ToString>(msg: S) -> Self {
        Self {
            kind: Box::new(ErrorKind::Misc(msg.to_string())),
            pos: GPosIdx::UNKNOWN,
            annotations: vec![],
            post_msg: None,
        }
    }
    pub fn parse_error<S: ToString>(msg: S) -> Self {
        Self {
            kind: Box::new(ErrorKind::Parse),
            pos: GPosIdx::UNKNOWN,
            annotations: vec![],
            post_msg: Some(msg.to_string()),
        }
    }
    pub fn invalid_file<S: ToString>(msg: S) -> Self {
        Self {
            kind: Box::new(ErrorKind::InvalidFile(msg.to_string())),
            pos: GPosIdx::UNKNOWN,
            annotations: vec![],
            post_msg: None,
        }
    }
    pub fn write_error<S: ToString>(msg: S) -> Self {
        Self {
            kind: Box::new(ErrorKind::WriteError(msg.to_string())),
            pos: GPosIdx::UNKNOWN,
            annotations: vec![],
            post_msg: None,
        }
    }
    pub fn location(&self) -> (&str, usize, usize) {
        self.pos.get_location()
    }
    pub fn message(&self) -> String {
        self.kind.to_string()
    }
    pub fn annotations(&self) -> Vec<(String, usize, usize)> {
        self.annotations
            .iter()
            .map(|(pos, msg)| {
                let (_, s, e) = pos.get_location();
                (msg.to_string(), s, e)
            })
            .collect()
    }
}

/// Standard error type for Calyx errors.
#[derive(Clone)]
enum ErrorKind {
    /// Using a reserved keyword as a program identifier.
    ReservedName(Id),

    /// The control program is malformed.
    MalformedControl(String),
    /// The connections are malformed.
    MalformedStructure(String),

    /// Requirement of a pass was not satisfied
    PassAssumption(String, String),

    /// The name has not been bound
    Undefined(Id, String),
    /// The name has already been bound.
    AlreadyBound(Id, String),

    /// The group was not used in the program.
    Unused(Id, String),

    /// Papercut error: signals a commonly made mistake in Calyx program.
    Papercut(String),

    // =========== Frontend Errors ===============
    /// Parse error
    Parse,
    /// Miscellaneous error message
    Misc(String),
    /// The input file is invalid (does not exist).
    InvalidFile(String),
    /// Failed to write the output
    WriteError(String),
}

impl std::fmt::Display for ErrorKind {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        use ErrorKind::*;
        match self {
            Papercut(msg) => {
                write!(f, "[Papercut] {}", msg)
            }
            Unused(name, typ) => {
                write!(f, "Unused {typ} `{name}'")
            }
            AlreadyBound(name, bound_by) => {
                write!(f, "Name `{name}' already bound by {bound_by}")
            }
            ReservedName(name) => {
                write!(f, "Use of reserved keyword: {name}")
            }
            Undefined(name, typ) => {
                write!(f, "Undefined {typ} name: {name}")
            }
            MalformedControl(msg) => write!(f, "Malformed Control: {msg}"),
            PassAssumption(pass, msg) => {
                write!(f, "Pass `{pass}` assumption violated: {msg}")
            }
            MalformedStructure(msg) => {
                write!(f, "Malformed Structure: {msg}")
            }
            Parse => {
                write!(f, "Parse error")
            }
            InvalidFile(msg) | WriteError(msg) | Misc(msg) => {
                write!(f, "{msg}")
            }
        }
    }
}

// Conversions from other error types to our error type so that
// we can use `?` in all the places.
impl From<std::str::Utf8Error> for Error {
    fn from(err: std::str::Utf8Error) -> Self {
        Error::invalid_file(err.to_string())
    }
}

impl From<std::io::Error> for Error {
    fn from(e: std::io::Error) -> Self {
        Error::write_error(format!("IO Error: {}", e))
    }
}

impl From<serde_json::Error> for Error {
    fn from(e: serde_json::Error) -> Self {
        Error::write_error(format!("serde_json Error: {}", e))
    }
}

impl From<std::str::Utf8Error> for MultiError {
    fn from(value: std::str::Utf8Error) -> Self {
        MultiError {
            errors: vec![value.into()],
        }
    }
}

impl From<std::io::Error> for MultiError {
    fn from(value: std::io::Error) -> Self {
        MultiError {
            errors: vec![value.into()],
        }
    }
}

impl From<serde_json::Error> for MultiError {
    fn from(value: serde_json::Error) -> Self {
        MultiError {
            errors: vec![value.into()],
        }
    }
}

impl From<Error> for MultiError {
    fn from(value: Error) -> Self {
        MultiError {
            errors: vec![value],
        }
    }
}