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
//! Errors generated by the compiler.
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
pub struct Error {
    kind: Box<ErrorKind>,
    pos: GPosIdx,
    post_msg: Option<String>,
}

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()))?
        }
        if let Some(post) = &self.post_msg {
            write!(f, "\n{}", post)?;
        }
        Ok(())
    }
}

impl Error {
    pub fn with_pos<T: WithPos>(mut self, pos: &T) -> Self {
        self.pos = pos.copy_span();
        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,
            post_msg: None,
        }
    }
    pub fn malformed_control(msg: String) -> Self {
        Self {
            kind: Box::new(ErrorKind::MalformedControl(msg)),
            pos: GPosIdx::UNKNOWN,
            post_msg: None,
        }
    }
    pub fn malformed_structure<S: ToString>(msg: S) -> Self {
        Self {
            kind: Box::new(ErrorKind::MalformedStructure(msg.to_string())),
            pos: GPosIdx::UNKNOWN,
            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,
            post_msg: None,
        }
    }
    pub fn undefined(name: Id, typ: String) -> Self {
        Self {
            kind: Box::new(ErrorKind::Undefined(name, typ)),
            pos: GPosIdx::UNKNOWN,
            post_msg: None,
        }
    }
    pub fn already_bound(name: Id, typ: String) -> Self {
        Self {
            kind: Box::new(ErrorKind::AlreadyBound(name, typ)),
            pos: GPosIdx::UNKNOWN,
            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,
            post_msg: None,
        }
    }
    pub fn papercut(msg: String) -> Self {
        Self {
            kind: Box::new(ErrorKind::Papercut(msg)),
            pos: GPosIdx::UNKNOWN,
            post_msg: None,
        }
    }
    pub fn misc(msg: String) -> Self {
        Self {
            kind: Box::new(ErrorKind::Misc(msg)),
            pos: GPosIdx::UNKNOWN,
            post_msg: None,
        }
    }
    pub fn invalid_file(msg: String) -> Self {
        Self {
            kind: Box::new(ErrorKind::InvalidFile(msg)),
            pos: GPosIdx::UNKNOWN,
            post_msg: None,
        }
    }
    pub fn write_error(msg: String) -> Self {
        Self {
            kind: Box::new(ErrorKind::WriteError(msg)),
            pos: GPosIdx::UNKNOWN,
            post_msg: None,
        }
    }
}

/// Standard error type for Calyx errors.
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 ===============
    /// 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}")
            }
            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))
    }
}