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
use ffi;
use std::any::TypeId;
use std::error::Error as StdError;
use std::{fmt, result};

pub type Result<T> = result::Result<T, Error>;

#[derive(Debug)]
pub struct Error {
    /// The underlying type of error.
    pub kind: ErrorKind,
    /// An optional list of context messages describing the error. This corresponds to the
    /// JavaScript `Error`'s `message` property.
    pub context: Vec<String>,
}

#[derive(Debug)]
pub enum ErrorKind {
    /// A Rust value could not be converted to a JavaScript value.
    ToJsConversionError {
        /// Name of the Rust type that could not be converted.
        from: &'static str,
        /// Name of the JavaScript type that could not be created.
        to: &'static str,
    },
    /// A JavaScript value could not be converted to the expected Rust type.
    FromJsConversionError {
        /// Name of the JavaScript type that could not be converted.
        from: &'static str,
        /// Name of the Rust type that could not be created.
        to: &'static str,
    },
    /// An error that occurred within the scripting environment.
    RuntimeError {
        /// A code representing what type of error occurred.
        code: RuntimeErrorCode,
        /// A string representation of the type of error.
        name: String,
    },
    /// A mutable callback has triggered JavaScript code that has called the same mutable callback
    /// again.
    ///
    /// This is an error because a mutable callback can only be borrowed mutably once.
    RecursiveMutCallback,
    /// A custom error that occurs during runtime.
    ///
    /// This can be used for returning user-defined errors from callbacks.
    ExternalError(Box<dyn RuntimeError + 'static>),
    /// An error specifying the variable that was called as a function was not a function.
    NotAFunction,
}

impl Error {
    /// Creates an `Error` from any type that implements `RuntimeError`.
    pub fn external<T: RuntimeError + 'static>(error: T) -> Error {
        Error {
            kind: ErrorKind::ExternalError(Box::new(error)),
            context: vec![],
        }
    }

    pub fn from_js_conversion(from: &'static str, to: &'static str) -> Error {
        Error {
            kind: ErrorKind::FromJsConversionError { from, to },
            context: vec![],
        }
    }

    pub fn to_js_conversion(from: &'static str, to: &'static str) -> Error {
        Error {
            kind: ErrorKind::ToJsConversionError { from, to },
            context: vec![],
        }
    }

    pub fn recursive_mut_callback() -> Error {
        Error { kind: ErrorKind::RecursiveMutCallback, context: vec![] }
    }

    pub fn not_a_function() -> Error {
        Error { kind: ErrorKind::NotAFunction, context: vec![] }
    }

    pub(crate) fn into_runtime_error_desc(self) -> RuntimeErrorDesc {
        RuntimeErrorDesc {
            code: self.runtime_code(),
            name: self.runtime_name(),
            message: self.runtime_message(),
            cause: Box::new(self),
        }
    }

    fn runtime_code(&self) -> RuntimeErrorCode {
        match &self.kind {
            ErrorKind::ToJsConversionError { .. } => RuntimeErrorCode::TypeError,
            ErrorKind::FromJsConversionError { .. } => RuntimeErrorCode::TypeError,
            ErrorKind::NotAFunction => RuntimeErrorCode::TypeError,
            ErrorKind::ExternalError(err) => err.code(),
            _ => RuntimeErrorCode::Error
        }
    }

    fn runtime_name(&self) -> String {
        match &self.kind {
            ErrorKind::ExternalError(err) => err.name(),
            _ => self.runtime_code().to_string()
        }
    }

    fn runtime_message(&self) -> Option<String> {
        let mut message = String::new();

        for context in self.context.iter().rev() {
            if !message.is_empty() {
                message.push_str(": ");
            }

            message.push_str(context);
        }

        if let ErrorKind::ExternalError(ref error) = self.kind {
            if let Some(ref ext_message) = error.message() {
                if !message.is_empty() {
                    message.push_str(": ");
                }

                message.push_str(ext_message);
            }
        }

        if !message.is_empty() {
            Some(message)
        } else {
            None
        }
    }
}

impl StdError for Error {
    fn description(&self) -> &'static str {
        "JavaScript execution error"
    }
}

impl fmt::Display for Error {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        for context in self.context.iter().rev() {
            write!(fmt, "{}: ", context)?;
        }

        match self.kind {
            ErrorKind::ToJsConversionError { from, to } => {
                write!(fmt, "error converting {} to JavaScript {}", from, to)
            },
            ErrorKind::FromJsConversionError { from, to } => {
                write!(fmt, "error converting JavaScript {} to {}", from, to)
            },
            ErrorKind::RuntimeError { ref name, .. } => {
                write!(fmt, "JavaScript runtime error ({})", name)
            },
            ErrorKind::RecursiveMutCallback => write!(fmt, "mutable callback called recursively"),
            ErrorKind::NotAFunction => write!(fmt, "tried to a call a non-function"),
            ErrorKind::ExternalError(ref err) => err.fmt(fmt),
        }
    }
}

pub trait ResultExt {
    fn js_err_context<D: fmt::Display>(self, context: D) -> Self;
    fn js_err_context_with<D: fmt::Display, F: FnOnce(&Error) -> D>(self, op: F) -> Self;
}

impl<T> ResultExt for result::Result<T, Error> {
    fn js_err_context<D: fmt::Display>(self, context: D) -> Self {
        match self {
            Err(mut err) => {
                err.context.push(context.to_string());
                Err(err)
            },
            result => result,
        }
    }

    fn js_err_context_with<D: fmt::Display, F: FnOnce(&Error) -> D>(self, op: F) -> Self {
        match self {
            Err(mut err) => {
                let context = op(&err).to_string();
                err.context.push(context);
                Err(err)
            },
            result => result,
        }
    }
}

impl ResultExt for Error {
    fn js_err_context<D: fmt::Display>(mut self, context: D) -> Self {
        self.context.push(context.to_string());
        self
    }

    fn js_err_context_with<D: fmt::Display, F: FnOnce(&Error) -> D>(mut self, op: F) -> Self {
        let context = op(&self).to_string();
        self.context.push(context);
        self
    }
}

pub(crate) struct RuntimeErrorDesc {
    pub code: RuntimeErrorCode,
    pub name: String,
    pub message: Option<String>,
    pub cause: Box<Error>,
}

/// Represents the various types of JavaScript errors that can occur. This corresponds to the
/// `prototype` of the JavaScript error object, and the `name` field is typically derived from it.
#[derive(Clone, Debug, PartialEq)]
pub enum RuntimeErrorCode {
    Error,
    EvalError,
    RangeError,
    ReferenceError,
    SyntaxError,
    TypeError,
    UriError,
}

impl RuntimeErrorCode {
    pub(crate) fn from_duk_errcode(code: ffi::duk_errcode_t) -> RuntimeErrorCode {
        match code as u32 {
            ffi::DUK_ERR_ERROR => RuntimeErrorCode::Error,
            ffi::DUK_ERR_EVAL_ERROR => RuntimeErrorCode::EvalError,
            ffi::DUK_ERR_RANGE_ERROR => RuntimeErrorCode::RangeError,
            ffi::DUK_ERR_REFERENCE_ERROR => RuntimeErrorCode::ReferenceError,
            ffi::DUK_ERR_SYNTAX_ERROR => RuntimeErrorCode::SyntaxError,
            ffi::DUK_ERR_TYPE_ERROR => RuntimeErrorCode::TypeError,
            ffi::DUK_ERR_URI_ERROR => RuntimeErrorCode::UriError,
            _ => RuntimeErrorCode::Error,
        }
    }

    pub(crate) fn to_duk_errcode(&self) -> ffi::duk_errcode_t {
        (match *self {
            RuntimeErrorCode::Error => ffi::DUK_ERR_ERROR,
            RuntimeErrorCode::EvalError => ffi::DUK_ERR_EVAL_ERROR,
            RuntimeErrorCode::RangeError => ffi::DUK_ERR_RANGE_ERROR,
            RuntimeErrorCode::ReferenceError => ffi::DUK_ERR_REFERENCE_ERROR,
            RuntimeErrorCode::SyntaxError => ffi::DUK_ERR_SYNTAX_ERROR,
            RuntimeErrorCode::TypeError => ffi::DUK_ERR_TYPE_ERROR,
            RuntimeErrorCode::UriError => ffi::DUK_ERR_URI_ERROR,
        }) as ffi::duk_errcode_t
    }
}

impl fmt::Display for RuntimeErrorCode {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            RuntimeErrorCode::Error => write!(f, "Error"),
            RuntimeErrorCode::EvalError => write!(f, "EvalError"),
            RuntimeErrorCode::RangeError => write!(f, "RangeError"),
            RuntimeErrorCode::ReferenceError => write!(f, "ReferenceError"),
            RuntimeErrorCode::SyntaxError => write!(f, "SyntaxError"),
            RuntimeErrorCode::TypeError => write!(f, "TypeError"),
            RuntimeErrorCode::UriError => write!(f, "URIError"),
        }
    }
}

/// A Rust error that can be transformed into a JavaScript error.
pub trait RuntimeError: fmt::Debug {
    /// The prototypical JavaScript error code.
    ///
    /// By default, this method returns `RuntimeErrorCode::Error`.
    fn code(&self) -> RuntimeErrorCode {
        RuntimeErrorCode::Error
    }

    /// The name of the error corresponding to the JavaScript error's `name` property.
    ///
    /// By default, this method returns the string name corresponding to this object's `code()`
    /// return value.
    fn name(&self) -> String {
        self.code().to_string()
    }

    /// An optional message that is set on the JavaScript error's `message` property. This is
    /// automatically appended to the parent `Error`'s `context` field.
    ///
    /// By default, this method returns `None`.
    fn message(&self) -> Option<String> {
        None
    }

    // TODO: Should we support modifying the error object?
    // fn customize<'ducc>(&self, ducc: &'ducc Ducc, object: &'ducc Object<'ducc>) {
    //     let _ = ducc;
    //     let _ = object;
    // }

    #[doc(hidden)]
    fn __private_get_type_id__(&self) -> TypeId where Self: 'static {
        TypeId::of::<Self>()
    }
}

impl dyn RuntimeError {
    /// Attempts to downcast this failure to a concrete type by reference.
    ///
    /// If the underlying error is not of type `T`, this will return `None`.
    pub fn downcast_ref<T: RuntimeError + 'static>(&self) -> Option<&T> {
        if self.__private_get_type_id__() == TypeId::of::<T>() {
            unsafe { Some(&*(self as *const dyn RuntimeError as *const T)) }
        } else {
            None
        }
    }
}

impl RuntimeError for () {
}

impl RuntimeError for String {
    fn message(&self) -> Option<String> {
        Some(self.clone())
    }
}

impl<'a> RuntimeError for &'a str {
    fn message(&self) -> Option<String> {
        Some(self.to_string())
    }
}

impl<T: RuntimeError + 'static> From<T> for Error {
    fn from(error: T) -> Error {
        Error::external(error)
    }
}

impl From<ErrorKind> for Error {
    fn from(error: ErrorKind) -> Error {
        Error {
            kind: error,
            context: vec![],
        }
    }
}