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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
//! Error traits and error kinds

#[cfg(doc)]
use super::*;

use std::borrow::Cow;
use std::error::Error;
use std::fmt;
use std::ops::{Deref, DerefMut};

/// Kinds of [`MachineError`]s
#[derive(Copy, Clone, PartialEq, Eq, Hash, Default, Debug)]
pub enum MachineErrorKind {
    /// Out-of-memory error
    Memory,
    /// Syntax error during compilation (see [`Compile::compile`])
    Syntax,
    /// Execution limit error
    ExecLimit,
    /// Generic runtime error (see [`Function::call`])
    Runtime,
    /// Unexpected value(s) (e.g. wrong type or wrong count of return values)
    Data,
    /// Error kind unknown
    #[default]
    Unknown,
}

/// Unboxed version of [`MachineError`]
///
/// All fields of this struct may be accessed through `MachineError` as well
/// (due to [`Deref`] and [`DerefMut`] implementation by `MachineError).
#[derive(Clone, Default)]
#[non_exhaustive]
pub struct MachineErrorUnboxed {
    /// Kind of runtime error
    pub kind: MachineErrorKind,
    /// Error message
    pub message: Option<String>,
    /// Backtrace (multiple lines, without trailing newline)
    pub machine_backtrace: Option<String>,
    /// Chunk name already included in message?
    pub message_incl_chunk_name: bool,
    /// Chunk name
    pub chunk_name: Option<String>,
    /// Position already included in message?
    pub message_incl_pos: bool,
    /// Line number
    pub line: Option<usize>,
    /// Column number (in UTF-8 codepoints)
    pub column: Option<usize>,
    /// Byte position
    pub position: Option<usize>,
}

/// Runtime or compiler errors that may refer to a specific position in code
#[derive(Clone, Default)]
pub struct MachineError {
    /// Boxed struct containing all fields
    /// (accessible through [`Deref`] and [`DerefMut`])
    pub boxed: Box<MachineErrorUnboxed>,
}

impl Deref for MachineError {
    type Target = MachineErrorUnboxed;
    fn deref(&self) -> &Self::Target {
        &self.boxed
    }
}

impl DerefMut for MachineError {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.boxed
    }
}

impl MachineError {
    /// Creates a new `MachineError` that may also be used as a builder
    pub fn new() -> Self {
        Default::default()
    }
    /// Builder-style method to set the [`MachineErrorKind`]
    pub fn set_kind(mut self, kind: MachineErrorKind) -> Self {
        self.kind = kind;
        self
    }
    /// Builder-style method to set an error [`message`]
    ///
    /// [`message`]: MachineErrorUnboxed::message
    pub fn set_message(mut self, message: String) -> Self {
        self.message = Some(message);
        self
    }
    /// Builder-style method to set an error [`message`] using a `str` slice
    ///
    /// [`message`]: MachineErrorUnboxed::message
    pub fn set_message_str(mut self, message: &str) -> Self {
        self.message = Some(message.to_owned());
        self
    }
    /// Builder-style method to set an error [`message`] [option]
    ///
    /// [`message`]: MachineErrorUnboxed::message
    /// [option]: Option
    pub fn set_message_opt(mut self, message: Option<String>) -> Self {
        self.message = message;
        self
    }
    /// Builder-style method to set [`machine_backtrace`]
    ///
    /// [`machine_backtrace`]: MachineErrorUnboxed::machine_backtrace
    pub fn set_machine_backtrace(mut self, machine_backtrace: String) -> Self {
        self.machine_backtrace = Some(machine_backtrace);
        self
    }
    /// Builder-style method to set a [`machine_backtrace`] [option]
    ///
    /// [`machine_backtrace`]: MachineErrorUnboxed::machine_backtrace
    /// [option]: Option
    pub fn set_machine_backtrace_opt(mut self, machine_backtrace: Option<String>) -> Self {
        self.machine_backtrace = machine_backtrace;
        self
    }
    /// Builder-style method to set [`message_incl_chunk_name`] to `true`
    ///
    /// [`message_incl_chunk_name`]: MachineErrorUnboxed::message_incl_chunk_name
    pub fn set_message_incl_chunk_name(mut self) -> Self {
        self.message_incl_chunk_name = true;
        self
    }
    /// Builder-style method to set [`message_incl_chunk_name`] to `bool`
    ///
    /// [`message_incl_chunk_name`]: MachineErrorUnboxed::message_incl_chunk_name
    pub fn set_message_incl_chunk_name_bool(mut self, message_incl_chunk_name: bool) -> Self {
        self.message_incl_chunk_name = message_incl_chunk_name;
        self
    }
    /// Builder-style method to set [`chunk_name`]
    ///
    /// [`chunk_name`]: MachineErrorUnboxed::chunk_name
    pub fn set_chunk_name(mut self, chunk_name: String) -> Self {
        self.chunk_name = Some(chunk_name);
        self
    }
    /// Builder-style method to set [`chunk_name`] [option]
    ///
    /// [`chunk_name`]: MachineErrorUnboxed::chunk_name
    /// [option]: Option
    pub fn set_chunk_name_opt(mut self, chunk_name: Option<String>) -> Self {
        self.chunk_name = chunk_name;
        self
    }
    /// Builder-style method to set [`message_incl_pos`] to `true`
    ///
    /// [`message_incl_pos`]: MachineErrorUnboxed::message_incl_pos
    pub fn set_message_incl_pos(mut self) -> Self {
        self.message_incl_pos = true;
        self
    }
    /// Builder-style method to set [`message_incl_pos`] to a `bool`
    ///
    /// [`message_incl_pos`]: MachineErrorUnboxed::message_incl_pos
    pub fn set_message_incl_pos_bool(mut self, message_incl_pos: bool) -> Self {
        self.message_incl_pos = message_incl_pos;
        self
    }
    /// Builder-style method to set [`line`]
    ///
    /// [`line`]: MachineErrorUnboxed::line
    pub fn set_line(mut self, line: usize) -> Self {
        self.line = Some(line);
        self
    }
    /// Builder-style method to set [`line`] [option]
    ///
    /// [`line`]: MachineErrorUnboxed::line
    /// [option]: Option
    pub fn set_line_opt(mut self, line: Option<usize>) -> Self {
        self.line = line;
        self
    }
    /// Builder-style method to set [`column`]
    ///
    /// [`column`]: MachineErrorUnboxed::column
    pub fn set_column(mut self, column: usize) -> Self {
        self.column = Some(column);
        self
    }
    /// Builder-style method to set [`column`] [option]
    ///
    /// [`column`]: MachineErrorUnboxed::column
    /// [option]: Option
    pub fn set_column_opt(mut self, column: Option<usize>) -> Self {
        self.column = column;
        self
    }
    /// Builder-style method to set [`position`]
    ///
    /// [`position`]: MachineErrorUnboxed::position
    pub fn set_position(mut self, position: usize) -> Self {
        self.position = Some(position);
        self
    }
    /// Builder-style method to set [`position`] [option]
    ///
    /// [`position`]: MachineErrorUnboxed::position
    /// [option]: Option
    pub fn set_position_opt(mut self, position: Option<usize>) -> Self {
        self.position = position;
        self
    }
}

impl Error for MachineError {}

impl fmt::Display for MachineError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.kind {
            MachineErrorKind::Memory => write!(f, "VM memory exhausted")?,
            MachineErrorKind::Syntax => write!(f, "syntax error in code for VM")?,
            MachineErrorKind::ExecLimit => write!(f, "VM execution limit exhausted")?,
            MachineErrorKind::Runtime => write!(f, "runtime error in VM")?,
            MachineErrorKind::Data => write!(f, "unexpected data from VM")?,
            _ => write!(f, "VM error")?,
        }
        let mut chunk_name_written = false;
        if !self.message_incl_chunk_name {
            if let Some(ref chunk_name) = self.chunk_name {
                write!(f, " in chunk \"{}\"", chunk_name)?;
                chunk_name_written = true;
            }
        }
        if !self.message_incl_pos {
            if let Some(line) = self.line {
                write!(
                    f,
                    "{} line {}",
                    if chunk_name_written { ", " } else { " in" },
                    line
                )?;
                if let Some(column) = self.column {
                    write!(f, ", column {}", column)?;
                }
            } else if let Some(position) = self.position {
                write!(f, ", at byte position {}", position)?;
            }
        }
        if let Some(msg) = &self.message {
            write!(f, ": {}", msg)?;
        }
        Ok(())
    }
}

impl fmt::Debug for MachineError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("MachineError")
            .field("kind", &self.kind)
            .field("message", &self.message)
            .field("message_incl_pos", &self.message_incl_pos)
            .field("chunk_name", &self.chunk_name)
            .field("line", &self.line)
            .field("column", &self.column)
            .field("position", &self.position)
            .finish_non_exhaustive()
    }
}

/// Error indicating that [`Machine::Datum`] had an unexpected (dynamic) type
///
/// See also [`types`] module.
///
/// For convenience, this error type can be converted into a [`MachineError`].
#[derive(Debug)]
pub struct TypeMismatch {
    /// Error description
    message: Cow<'static, str>,
}

impl TypeMismatch {
    /// Create new `TypeMismatch` without specific message
    pub const fn new() -> Self {
        TypeMismatch {
            message: Cow::Borrowed("dynamic type mismatch (no details available)"),
        }
    }
    /// Create new `TypeMismatch` from owned [`String`]
    pub fn with_msg(message: String) -> Self {
        TypeMismatch {
            message: Cow::Owned(message),
        }
    }
    /// Create new `TypeMismatch` with static error message
    pub const fn with_static_msg(message: &'static str) -> Self {
        TypeMismatch {
            message: Cow::Borrowed(message),
        }
    }
}

impl fmt::Display for TypeMismatch {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(&self.message)
    }
}

impl Error for TypeMismatch {}

impl From<TypeMismatch> for MachineError {
    fn from(datum_err: TypeMismatch) -> Self {
        MachineError::new()
            .set_kind(MachineErrorKind::Data)
            .set_message(datum_err.to_string())
    }
}

/// Error type when using [`TryFrom`]/[`TryInto`] to convert a
/// [`Machine::Datum`] into a particular type
///
/// See also [`types`] module.
///
/// Since this type contains the original `Datum`, it might not be
/// `Send + Sync + 'static`. `DatumConversionFailure` also does not implement
/// [`std::error::Error`]. You can convert this error into [`TypeMismatch`]
/// (or extract the [`error`] field), which implements `std::error::Error` and
/// is `Send + Sync + 'static`.
///
/// For convenience, values of this type can also be directly converted into a
/// [`MachineError`].
///
/// [`error`]: DatumConversionFailure::error
pub struct DatumConversionFailure<D> {
    /// Original datum that could not be converted
    pub original: D,
    /// Error description
    pub error: TypeMismatch,
}

impl<D> DatumConversionFailure<D> {
    /// Create new `DatumConversionFailure` with given [`TypeMismatch`] error
    pub fn new(original: D, error: TypeMismatch) -> Self {
        DatumConversionFailure { original, error }
    }
    /// Create new `DatumConversionFailure` with owned [`String`] error message
    pub fn with_msg(original: D, message: String) -> Self {
        DatumConversionFailure::new(original, TypeMismatch::with_msg(message))
    }
    /// Create new `DatumConversionFailure` with static error message
    pub fn with_static_msg(original: D, message: &'static str) -> Self {
        DatumConversionFailure::new(original, TypeMismatch::with_static_msg(message))
    }
}

impl<D> fmt::Debug for DatumConversionFailure<D> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("DatumConversionFailure")
            .field("error", &self.error)
            .finish_non_exhaustive()
    }
}

impl<D> From<DatumConversionFailure<D>> for TypeMismatch {
    fn from(failure: DatumConversionFailure<D>) -> Self {
        failure.error
    }
}
impl<D> From<DatumConversionFailure<D>> for MachineError {
    fn from(failure: DatumConversionFailure<D>) -> Self {
        MachineError::new()
            .set_kind(MachineErrorKind::Data)
            .set_message(TypeMismatch::from(failure).to_string())
    }
}