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
use std::fmt;

use crate::eval::EnvRef;
use crate::objects::Object;
use crate::tokenstream::Span;

trait LineIndices {
    // FIXME: learn to implement iterators
    fn line_indices(&self) -> Vec<(usize, &str)>;
}

impl LineIndices for str {
    fn line_indices(&self) -> Vec<(usize, &str)> {
        let mut all = Vec::new();
        let mut start: usize = 0;
        while start < self.len() {
            if let Some(newline0) = self[start..].find("\n") {
                let newline = newline0 + start;
                // Check for preceding carriage return.
                let end = if newline > 0 && &self[newline - 1..newline] == "\r" {
                    newline - 1
                } else {
                    newline
                };
                all.push((start, &self[start..end]));
                start = newline + 1;
            } else {
                all.push((start, &self[start..]));
                start = self.len();
            }
        }
        all
    }
}

#[derive(PartialEq, Debug)]
pub enum Unwind {
    Exception(Error, Location),
    ReturnFrom(EnvRef, Object),
}

#[derive(PartialEq, Debug)]
pub enum Error {
    MessageError(MessageError),
    SimpleError(SimpleError),
    TypeError(TypeError),
    EofError(SimpleError),
}

// FIXME: This might break encapsulation too badly?
#[derive(PartialEq, Debug)]
pub struct MessageError {
    pub message: String,
    pub receiver: Object,
    pub arguments: Vec<Object>,
}

#[derive(PartialEq, Debug)]
pub struct SimpleError {
    pub what: String,
}

#[derive(PartialEq, Debug)]
pub struct TypeError {
    pub value: Object,
    pub expected: String,
}

#[derive(PartialEq, Debug)]
pub struct Location {
    pub span: Option<Span>,
    pub context: Option<String>,
}

impl fmt::Display for Unwind {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Unwind::Exception(error, location) => {
                write!(f, "ERROR: {}\n{}", error.what(), location.context())
            }
            Unwind::ReturnFrom(_, object) => write!(f, "#<Return {}>", object),
        }
    }
}

impl Unwind {
    // FIXME: The vtable as expected, extract name here.
    pub fn type_error<T>(value: Object, expected: String) -> Result<T, Unwind> {
        Err(Unwind::Exception(
            Error::TypeError(TypeError {
                value,
                expected,
            }),
            Location::none(),
        ))
    }

    pub fn type_error_at<T>(span: Span, value: Object, expected: String) -> Result<T, Unwind> {
        Err(Unwind::Exception(
            Error::TypeError(TypeError {
                value,
                expected,
            }),
            Location::new(span),
        ))
    }

    pub fn message_error<T>(
        receiver: &Object,
        message: &str,
        args: &[Object],
    ) -> Result<T, Unwind> {
        Err(Unwind::Exception(
            Error::MessageError(MessageError {
                receiver: receiver.clone(),
                message: message.to_string(),
                arguments: args.to_vec(),
            }),
            Location::none(),
        ))
    }

    pub fn eof_error_at<T>(span: Span, what: &str) -> Result<T, Unwind> {
        Err(Unwind::Exception(
            Error::EofError(SimpleError {
                what: what.to_string(),
            }),
            Location::new(span),
        ))
    }

    pub fn error<T>(what: &str) -> Result<T, Unwind> {
        Err(Unwind::Exception(
            Error::SimpleError(SimpleError {
                what: what.to_string(),
            }),
            Location::none(),
        ))
    }

    pub fn error_at<T>(span: Span, what: &str) -> Result<T, Unwind> {
        Err(Unwind::Exception(
            Error::SimpleError(SimpleError {
                what: what.to_string(),
            }),
            Location::new(span),
        ))
    }

    pub fn return_from<T>(env: EnvRef, value: Object) -> Result<T, Unwind> {
        Err(Unwind::ReturnFrom(env, value))
    }

    pub fn add_span(&mut self, span: &Span) {
        if let Unwind::Exception(_, location) = self {
            location.add_span(span)
        }
    }

    pub fn shift_span(self, offset: usize) -> Self {
        match self {
            Unwind::Exception(
                err,
                Location {
                    span: Some(s),
                    context,
                },
            ) => Unwind::Exception(
                err,
                Location {
                    span: Some((s.start + offset)..(s.end + offset)),
                    context,
                },
            ),
            _ => self,
        }
    }

    pub fn with_context(mut self, source: &str) -> Unwind {
        if let Unwind::Exception(error, location) = &mut self {
            location.add_context(source, error.what());
        }
        self
    }
}

impl Error {
    pub fn what(&self) -> String {
        match self {
            Error::MessageError(e) => e.what(),
            Error::SimpleError(e) => e.what(),
            Error::TypeError(e) => e.what(),
            Error::EofError(e) => e.what(),
        }
    }
}

impl MessageError {
    pub fn what(&self) -> String {
        format!("{:?} does not understand: {} {:?}", self.receiver, self.message, self.arguments)
    }
}

impl SimpleError {
    pub fn what(&self) -> String {
        self.what.clone()
    }
}

impl TypeError {
    pub fn what(&self) -> String {
        format!(
            "{} expected, got: {} {}",
            self.expected,
            self.value.vtable.name.clone(),
            self.value
        )
    }
}

impl Location {
    fn new(span: Span) -> Location {
        Location {
            span: Some(span),
            context: None,
        }
    }

    fn none() -> Location {
        Location {
            span: None,
            context: None,
        }
    }

    pub fn context(&self) -> String {
        match &self.context {
            None => "".to_string(),
            Some(ctx) => ctx.clone(),
        }
    }

    fn start(&self) -> usize {
        if let Some(span) = &self.span {
            span.start
        } else {
            panic!("Expected Location with span")
        }
    }

    fn end(&self) -> usize {
        if let Some(span) = &self.span {
            span.end
        } else {
            panic!("Expected Location with span")
        }
    }

    fn add_span(&mut self, span: &Span) {
        assert!(self.span.is_none());
        self.span = Some(span.clone())
    }

    fn add_context(&mut self, source: &str, what: String) {
        if self.context.is_some() {
            return;
        }
        if self.span.is_none() {
            return;
        }
        assert!(self.context.is_none());
        let mut context = String::new();
        let mut prev = "";
        let mut lineno = 1;
        for (start, line) in source.line_indices() {
            if start >= self.end() {
                // Line after the problem -- done.
                _append_context_line(&mut context, lineno, line);
                break;
            }
            let end = start + line.len();
            if end > self.start() {
                // Previous line if there is one.
                if lineno > 1 {
                    _append_context_line(&mut context, lineno - 1, prev);
                }
                // Line with the problem.
                _append_context_line(&mut context, lineno, line);
                let mut mark = if self.start() > start {
                    String::from_utf8(vec![b' '; self.start() - start]).unwrap()
                } else {
                    "".to_string()
                };
                mark.push_str(
                    String::from_utf8(vec![b'^'; self.end() - self.start()]).unwrap().as_str(),
                );
                mark.push_str(" ");
                mark.push_str(what.as_str());
                _append_context_line(&mut context, 0, mark.as_str());
            }
            prev = line;
            lineno += 1;
        }
        self.context = Some(context);
    }
}

fn _append_context_line(context: &mut String, lineno: usize, line: &str) {
    if lineno == 0 {
        context.push_str(format!("    {}\n", line).as_str());
    } else {
        context.push_str(format!("{:03} {}\n", lineno, line).as_str());
    }
}