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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
use crate::{qjs, Ctx, FromJs, IntoJs, Object, StdResult, StdString, Type, Value};

use std::{
    error::Error as StdError,
    ffi::{CString, NulError},
    fmt::{Display, Formatter, Result as FmtResult},
    io::Error as IoError,
    ops::Range,
    panic,
    panic::UnwindSafe,
    str::{FromStr, Utf8Error},
    string::FromUtf8Error,
};

/// Result type used throught the library.
pub type Result<T> = StdResult<T, Error>;

/// Error type of the library.
#[derive(Debug)]
pub enum Error {
    /// Could not allocate memory
    /// This is generally only triggered when out of memory.
    Allocation,
    /// Found a string with a internal null byte while converting
    /// to C string.
    InvalidString(NulError),
    /// String from rquickjs was not UTF-8
    Utf8(Utf8Error),
    /// An io error
    Io(IoError),
    /// An exception raised by quickjs itself.
    Exception {
        message: StdString,
        file: StdString,
        line: i32,
        stack: StdString,
    },
    /// Error converting from javascript to a rust type.
    FromJs {
        from: &'static str,
        to: &'static str,
        message: Option<StdString>,
    },
    /// Error converting to javascript from a rust type.
    IntoJs {
        from: &'static str,
        to: &'static str,
        message: Option<StdString>,
    },
    /// Error matching of function arguments
    NumArgs {
        expected: Range<usize>,
        given: usize,
    },
    #[cfg(feature = "loader")]
    /// Error when resolving js module
    Resolving {
        base: StdString,
        name: StdString,
        message: Option<StdString>,
    },
    #[cfg(feature = "loader")]
    /// Error when loading js module
    Loading {
        name: StdString,
        message: Option<StdString>,
    },
    /// An error from quickjs from which the specifics are unknown.
    /// Should eventually be removed as development progresses.
    Unknown,
}

impl Error {
    #[cfg(feature = "loader")]
    /// Create resolving error
    pub fn new_resolving<B, N>(base: B, name: N) -> Self
    where
        StdString: From<B> + From<N>,
    {
        Error::Resolving {
            base: base.into(),
            name: name.into(),
            message: None,
        }
    }

    #[cfg(feature = "loader")]
    /// Create resolving error with message
    pub fn new_resolving_message<B, N, M>(base: B, name: N, msg: M) -> Self
    where
        StdString: From<B> + From<N> + From<M>,
    {
        Error::Resolving {
            base: base.into(),
            name: name.into(),
            message: Some(msg.into()),
        }
    }

    #[cfg(feature = "loader")]
    /// Returns whether the error is a resolving error
    pub fn is_resolving(&self) -> bool {
        matches!(self, Error::Resolving { .. })
    }

    #[cfg(feature = "loader")]
    /// Create loading error
    pub fn new_loading<N>(name: N) -> Self
    where
        StdString: From<N>,
    {
        Error::Loading {
            name: name.into(),
            message: None,
        }
    }

    #[cfg(feature = "loader")]
    /// Create loading error
    pub fn new_loading_message<N, M>(name: N, msg: M) -> Self
    where
        StdString: From<N> + From<M>,
    {
        Error::Loading {
            name: name.into(),
            message: Some(msg.into()),
        }
    }

    #[cfg(feature = "loader")]
    /// Returns whether the error is a loading error
    pub fn is_loading(&self) -> bool {
        matches!(self, Error::Loading { .. })
    }

    /// Returns whether the error is a quickjs generated exception.
    pub fn is_exception(&self) -> bool {
        matches!(self, Error::Exception{..})
    }

    /// Create from JS conversion error
    pub fn new_from_js(from: &'static str, to: &'static str) -> Self {
        Error::FromJs {
            from,
            to,
            message: None,
        }
    }

    /// Create from JS conversion error with message
    pub fn new_from_js_message<M>(from: &'static str, to: &'static str, msg: M) -> Self
    where
        StdString: From<M>,
    {
        Error::FromJs {
            from,
            to,
            message: Some(msg.into()),
        }
    }

    /// Create into JS conversion error
    pub fn new_into_js(from: &'static str, to: &'static str) -> Self {
        Error::IntoJs {
            from,
            to,
            message: None,
        }
    }

    /// Create into JS conversion error with message
    pub fn new_into_js_message<M>(from: &'static str, to: &'static str, msg: M) -> Self
    where
        StdString: From<M>,
    {
        Error::IntoJs {
            from,
            to,
            message: Some(msg.into()),
        }
    }

    /// Returns whether the error is a from JS conversion error
    pub fn is_from_js(&self) -> bool {
        matches!(self, Self::FromJs { .. })
    }

    /// Returns whether the error is a from JS to JS type conversion error
    pub fn is_from_js_to_js(&self) -> bool {
        matches!(self, Self::FromJs { to, .. } if Type::from_str(*to).is_ok())
    }

    /// Returns whether the error is an into JS conversion error
    pub fn is_into_js(&self) -> bool {
        matches!(self, Self::IntoJs { .. })
    }

    /// Create function args mismatch error
    pub fn new_num_args(expected: Range<usize>, given: usize) -> Self {
        Self::NumArgs { expected, given }
    }

    /// Return whether the error is an function args mismatch error
    pub fn is_num_args(&self) -> bool {
        matches!(self, Self::NumArgs { .. })
    }

    /// Optimized conversion to CString
    pub(crate) fn to_cstring(&self) -> CString {
        // stringify error with NUL at end
        let mut message = format!("{}\0", self).into_bytes();

        message.pop(); // pop last NUL because CString add this later

        // TODO: Replace by `CString::from_vec_with_nul_unchecked` later when it will be stabilized
        unsafe { CString::from_vec_unchecked(message) }
    }

    /// Throw an exception
    pub(crate) fn throw(&self, ctx: Ctx) -> qjs::JSValue {
        use Error::*;
        match self {
            Allocation => unsafe { qjs::JS_ThrowOutOfMemory(ctx.ctx) },
            InvalidString(_) | Utf8(_) | FromJs { .. } | IntoJs { .. } | NumArgs { .. } => {
                let message = self.to_cstring();
                unsafe { qjs::JS_ThrowTypeError(ctx.ctx, message.as_ptr()) }
            }
            #[cfg(feature = "loader")]
            Resolving { .. } | Loading { .. } => {
                let message = self.to_cstring();
                unsafe { qjs::JS_ThrowReferenceError(ctx.ctx, message.as_ptr()) }
            }
            Unknown => {
                let message = self.to_cstring();
                unsafe { qjs::JS_ThrowInternalError(ctx.ctx, message.as_ptr()) }
            }
            _ => {
                let value = self.into_js(ctx).unwrap();
                unsafe { qjs::JS_Throw(ctx.ctx, value.into_js_value()) }
            }
        }
    }
}

impl StdError for Error {}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter) -> FmtResult {
        use Error::*;

        match self {
            Allocation => "Allocation failed while creating object".fmt(f)?,
            InvalidString(error) => {
                "String contained internal null bytes: ".fmt(f)?;
                error.fmt(f)?;
            }
            Utf8(error) => {
                "Conversion from string failed: ".fmt(f)?;
                error.fmt(f)?;
            }
            Unknown => "quickjs library created a unknown error".fmt(f)?,
            Exception {
                file,
                line,
                message,
                stack,
            } => {
                "Exception generated by quickjs: ".fmt(f)?;
                if !file.is_empty() {
                    '['.fmt(f)?;
                    file.fmt(f)?;
                    ']'.fmt(f)?;
                }
                if *line >= 0 {
                    ':'.fmt(f)?;
                    line.fmt(f)?;
                }
                if !message.is_empty() {
                    ' '.fmt(f)?;
                    message.fmt(f)?;
                }
                if !stack.is_empty() {
                    '\n'.fmt(f)?;
                    stack.fmt(f)?;
                }
            }
            FromJs { from, to, message } => {
                "Error converting from js '".fmt(f)?;
                from.fmt(f)?;
                "' into type '".fmt(f)?;
                to.fmt(f)?;
                "'".fmt(f)?;
                if let Some(message) = message {
                    if !message.is_empty() {
                        ": ".fmt(f)?;
                        message.fmt(f)?;
                    }
                }
            }
            IntoJs { from, to, message } => {
                "Error converting from '".fmt(f)?;
                from.fmt(f)?;
                "' into js '".fmt(f)?;
                to.fmt(f)?;
                "'".fmt(f)?;
                if let Some(message) = message {
                    if !message.is_empty() {
                        ": ".fmt(f)?;
                        message.fmt(f)?;
                    }
                }
            }
            NumArgs { expected, given } => {
                "Error calling function with ".fmt(f)?;
                given.fmt(f)?;
                " argument(s) while ".fmt(f)?;
                expected.start.fmt(f)?;
                "..".fmt(f)?;
                if expected.end < usize::MAX {
                    expected.end.fmt(f)?;
                }
                " expected".fmt(f)?;
            }
            #[cfg(feature = "loader")]
            Resolving {
                base,
                name,
                message,
            } => {
                "Error resolving module '".fmt(f)?;
                name.fmt(f)?;
                "' from '".fmt(f)?;
                base.fmt(f)?;
                "'".fmt(f)?;
                if let Some(message) = message {
                    if !message.is_empty() {
                        ": ".fmt(f)?;
                        message.fmt(f)?;
                    }
                }
            }
            #[cfg(feature = "loader")]
            Loading { name, message } => {
                "Error loading module '".fmt(f)?;
                name.fmt(f)?;
                "'".fmt(f)?;
                if let Some(message) = message {
                    if !message.is_empty() {
                        ": ".fmt(f)?;
                        message.fmt(f)?;
                    }
                }
            }
            Io(error) => {
                "IO Error: ".fmt(f)?;
                error.fmt(f)?;
            }
        }
        Ok(())
    }
}

macro_rules! from_impls {
    ($($type:ty => $variant:ident,)*) => {
        $(
            impl From<$type> for Error {
                fn from(error: $type) -> Self {
                    Error::$variant(error)
                }
            }
        )*
    };
}

from_impls! {
    NulError => InvalidString,
    Utf8Error => Utf8,
    IoError => Io,
}

impl From<FromUtf8Error> for Error {
    fn from(error: FromUtf8Error) -> Self {
        Error::Utf8(error.utf8_error())
    }
}

impl<'js> FromJs<'js> for Error {
    fn from_js(ctx: Ctx<'js>, value: Value<'js>) -> Result<Self> {
        let obj = Object::from_js(ctx, value)?;
        if obj.is_error() {
            Ok(Error::Exception {
                message: obj.get("message").unwrap_or_else(|_| "".into()),
                file: obj.get("fileName").unwrap_or_else(|_| "".into()),
                line: obj.get("lineNumber").unwrap_or(-1),
                stack: obj.get("stack").unwrap_or_else(|_| "".into()),
            })
        } else {
            Err(Error::new_from_js("object", "error"))
        }
    }
}

impl<'js> IntoJs<'js> for &Error {
    fn into_js(self, ctx: Ctx<'js>) -> Result<Value<'js>> {
        use Error::*;
        let value = unsafe {
            Object::from_js_value(ctx, handle_exception(ctx, qjs::JS_NewError(ctx.ctx))?)
        };
        match self {
            Exception {
                message,
                file,
                line,
                stack,
            } => {
                if !message.is_empty() {
                    value.set("message", message)?;
                }
                if !file.is_empty() {
                    value.set("fileName", file)?;
                }
                if *line >= 0 {
                    value.set("lineNumber", *line)?;
                }
                if !stack.is_empty() {
                    value.set("stack", stack)?;
                }
            }
            error => {
                value.set("message", error.to_string())?;
            }
        }
        Ok(value.0)
    }
}

pub(crate) fn handle_panic<F: FnOnce() -> qjs::JSValue + UnwindSafe>(
    ctx: *mut qjs::JSContext,
    f: F,
) -> qjs::JSValue {
    unsafe {
        match panic::catch_unwind(f) {
            Ok(x) => x,
            Err(e) => {
                Ctx::from_ptr(ctx).get_opaque().panic = Some(e);
                qjs::JS_Throw(ctx, qjs::JS_MKVAL(qjs::JS_TAG_EXCEPTION, 0))
            }
        }
    }
}

/// Handle possible exceptions in JSValue's and turn them into errors
/// Will return the JSValue if it is not an exception
///
/// # Safety
/// Assumes to have ownership of the JSValue
pub(crate) unsafe fn handle_exception<'js>(
    ctx: Ctx<'js>,
    js_val: qjs::JSValue,
) -> Result<qjs::JSValue> {
    if qjs::JS_VALUE_GET_NORM_TAG(js_val) != qjs::JS_TAG_EXCEPTION {
        Ok(js_val)
    } else {
        Err(get_exception(ctx))
    }
}

pub(crate) unsafe fn get_exception<'js>(ctx: Ctx<'js>) -> Error {
    let exception_val = qjs::JS_GetException(ctx.ctx);

    if let Some(x) = ctx.get_opaque().panic.take() {
        panic::resume_unwind(x);
    }

    let exception = Value::from_js_value(ctx, exception_val);
    Error::from_js(ctx, exception).unwrap()
}