rquickjs-core 0.1.7

High level bindings to the QuickJS javascript engine
Documentation
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
use crate::{
    get_exception, handle_exception, qjs, Atom, Context, Ctx, Error, FromAtom, FromJs, IntoJs,
    Result, Value,
};
use std::{
    ffi::{CStr, CString},
    marker::PhantomData,
    mem::MaybeUninit,
    ptr::null_mut,
    slice::from_raw_parts,
};

/// The marker for the module which is created from text source
pub struct Script;

/// The marker for the module which is created using [`ModuleDef`]
pub struct Native;

/// The marker for the module which is created but not loaded yet
pub struct Created;

/// The marker for the module which is loaded but not evaluated yet
pub struct Loaded<S = ()>(S);

/// The marker for the module which is already loaded and evaluated
pub struct Evaluated;

/// Module definition trait
pub trait ModuleDef {
    /// The exports should be added here
    fn load<'js>(_ctx: Ctx<'js>, _module: &Module<'js, Created>) -> Result<()> {
        Ok(())
    }

    /// The exports should be set here
    fn eval<'js>(_ctx: Ctx<'js>, _module: &Module<'js, Loaded<Native>>) -> Result<()> {
        Ok(())
    }
}

macro_rules! module_def_impls {
    ($($($t:ident)*,)*) => {
        $(
            impl<$($t),*> ModuleDef for ($($t,)*)
            where
                $($t: ModuleDef,)*
            {
                fn load<'js>(_ctx: Ctx<'js>, _module: &Module<'js, Created>) -> Result<()> {
                    $($t::load(_ctx, _module)?;)*
                    Ok(())
                }

                fn eval<'js>(_ctx: Ctx<'js>, _module: &Module<'js, Loaded<Native>>) -> Result<()> {
                    $($t::eval(_ctx, _module)?;)*
                    Ok(())
                }
            }
        )*
    };
}

module_def_impls! {
    ,
    A,
    A B,
    A B C,
    A B C D,
    A B C D E,
    A B C D E F,
    A B C D E F G,
    A B C D E F G H,
    A B C D E F G H I,
    A B C D E F G H I J,
    A B C D E F G H I J K,
    A B C D E F G H I J K L,
    A B C D E F G H I J K L M,
    A B C D E F G H I J K L M N,
    A B C D E F G H I J K L M N O,
    A B C D E F G H I J K L M N O P,
}

/// Javascript module with certain exports and imports
#[derive(Debug, PartialEq)]
pub struct Module<'js, S = Evaluated>(pub(crate) Value<'js>, pub(crate) PhantomData<S>);

impl<'js, S> Clone for Module<'js, S> {
    fn clone(&self) -> Self {
        Module(self.0.clone(), PhantomData)
    }
}

impl<'js, S> Module<'js, S> {
    pub(crate) unsafe fn from_module_def(ctx: Ctx<'js>, ptr: *mut qjs::JSModuleDef) -> Self {
        Self(
            Value::new_ptr(ctx, qjs::JS_TAG_MODULE, ptr as _),
            PhantomData,
        )
    }

    pub(crate) unsafe fn from_module_def_const(ctx: Ctx<'js>, ptr: *mut qjs::JSModuleDef) -> Self {
        Self(
            Value::new_ptr_const(ctx, qjs::JS_TAG_MODULE, ptr as _),
            PhantomData,
        )
    }

    pub(crate) fn as_module_def(&self) -> *mut qjs::JSModuleDef {
        unsafe { self.0.get_ptr() as _ }
    }

    pub(crate) fn into_module_def(self) -> *mut qjs::JSModuleDef {
        unsafe { self.0.into_ptr() as _ }
    }
}

impl<'js> Module<'js> {
    /// Returns the name of the module
    pub fn name<N>(&self) -> Result<N>
    where
        N: FromAtom<'js>,
    {
        let ctx = self.0.ctx;
        let name = unsafe {
            Atom::from_atom_val(ctx, qjs::JS_GetModuleName(ctx.ctx, self.as_module_def()))
        };
        N::from_atom(name)
    }

    /// Return the `import.meta` object of a module
    pub fn meta<T>(&self) -> Result<T>
    where
        T: FromJs<'js>,
    {
        let ctx = self.0.ctx;
        let meta = unsafe {
            Value::from_js_value(
                ctx,
                handle_exception(ctx, qjs::JS_GetImportMeta(ctx.ctx, self.as_module_def()))?,
            )
        };
        T::from_js(ctx, meta)
    }
}

/// Helper macro to provide module init function
///
/// ```
/// use rquickjs::{ModuleDef, module_init};
///
/// struct MyModule;
/// impl ModuleDef for MyModule {}
///
/// module_init!(MyModule);
/// // or
/// module_init!(js_init_my_module: MyModule);
/// ```
#[macro_export]
macro_rules! module_init {
    ($type:ty) => {
        $crate::module_init!(js_init_module: $type);
    };

    ($name:ident: $type:ty) => {
        #[no_mangle]
        pub unsafe extern "C" fn $name(
            ctx: *mut $crate::qjs::JSContext,
            module_name: *const $crate::qjs::c_char,
        ) -> *mut $crate::qjs::JSModuleDef {
            $crate::Module::init_raw::<$type>(ctx, module_name)
        }
    };
}

/// The raw module load function (`js_module_init`)
pub type ModuleLoadFn =
    unsafe extern "C" fn(*mut qjs::JSContext, *const qjs::c_char) -> *mut qjs::JSModuleDef;

impl<'js> Module<'js> {
    /// Create module from JS source
    #[allow(clippy::new_ret_no_self)]
    pub fn new<N, S>(ctx: Ctx<'js>, name: N, source: S) -> Result<Module<'js, Loaded<Script>>>
    where
        N: Into<Vec<u8>>,
        S: Into<Vec<u8>>,
    {
        let name = CString::new(name)?;
        let flag =
            qjs::JS_EVAL_TYPE_MODULE | qjs::JS_EVAL_FLAG_STRICT | qjs::JS_EVAL_FLAG_COMPILE_ONLY;
        Ok(Module(
            unsafe {
                let value = Value::from_js_value_const(
                    ctx,
                    ctx.eval_raw(source, name.as_c_str(), flag as _)?,
                );
                debug_assert!(value.is_module());
                value
            },
            PhantomData,
        ))
    }

    /// Create native JS module using [`ModuleDef`]
    #[allow(clippy::new_ret_no_self)]
    pub fn new_def<D, N>(ctx: Ctx<'js>, name: N) -> Result<Module<'js, Loaded<Native>>>
    where
        D: ModuleDef,
        N: Into<Vec<u8>>,
    {
        let name = CString::new(name)?;
        let ptr = unsafe {
            qjs::JS_NewCModule(
                ctx.ctx,
                name.as_ptr(),
                Some(Module::<Loaded<Native>>::eval_fn::<D>),
            )
        };
        if ptr.is_null() {
            return Err(Error::Allocation);
        }
        let module = unsafe { Module::<Created>::from_module_def_const(ctx, ptr) };
        D::load(ctx, &module)?;
        Ok(Module(module.0, PhantomData))
    }

    /// Create native JS module by calling init function (like `js_module_init`)
    ///
    /// # Safety
    /// The `load` function should not crash. But it can throw exception and return null pointer in that case.
    #[allow(clippy::new_ret_no_self)]
    pub unsafe fn new_raw<N>(
        ctx: Ctx<'js>,
        name: N,
        load: ModuleLoadFn,
    ) -> Result<Module<'js, Loaded<Native>>>
    where
        N: Into<Vec<u8>>,
    {
        let name = CString::new(name)?;
        let ptr = load(ctx.ctx, name.as_ptr());

        if ptr.is_null() {
            Err(Error::Unknown)
        } else {
            Ok(Module::from_module_def(ctx, ptr))
        }
    }

    /// The function for loading native JS module
    ///
    /// # Safety
    /// This function should only be called from `js_module_init` function.
    pub unsafe extern "C" fn init_raw<D>(
        ctx: *mut qjs::JSContext,
        name: *const qjs::c_char,
    ) -> *mut qjs::JSModuleDef
    where
        D: ModuleDef,
    {
        Context::init_raw(ctx);
        let ctx = Ctx::from_ptr(ctx);
        let name = CStr::from_ptr(name);
        match Self::_init::<D>(ctx, name) {
            Ok(module) => module.into_module_def(),
            Err(error) => {
                error.throw(ctx);
                null_mut() as _
            }
        }
    }

    fn _init<D>(ctx: Ctx<'js>, name: &CStr) -> Result<Module<'js, Loaded>>
    where
        D: ModuleDef,
    {
        let name = name.to_str()?;
        Ok(Module::new_def::<D, _>(ctx, name)?.into_loaded())
    }
}

impl<'js> Module<'js, Loaded<Script>> {
    /// Load module from bytecode
    pub fn read_object<B: AsRef<[u8]>>(ctx: Ctx<'js>, buf: B) -> Result<Self> {
        Self::read_object_raw(ctx, buf.as_ref(), qjs::JS_READ_OBJ_BYTECODE as _)
    }

    /// Load module from bytecode (static const)
    pub fn read_object_const(ctx: Ctx<'js>, buf: &'static [u8]) -> Result<Self> {
        Self::read_object_raw(
            ctx,
            buf,
            (qjs::JS_READ_OBJ_BYTECODE | qjs::JS_READ_OBJ_ROM_DATA) as _,
        )
    }

    fn read_object_raw(ctx: Ctx<'js>, buf: &[u8], flags: qjs::c_int) -> Result<Self> {
        let value = unsafe {
            Value::from_js_value(
                ctx,
                handle_exception(
                    ctx,
                    qjs::JS_ReadObject(ctx.ctx, buf.as_ptr(), buf.len() as _, flags),
                )?,
            )
        };
        Ok(Self(value, PhantomData))
    }

    /// Write bytecode of loaded module
    pub fn write_object(&self, byte_swap: bool) -> Result<Vec<u8>> {
        let ctx = self.0.ctx;
        let mut len = MaybeUninit::uninit();
        let mut flags = qjs::JS_WRITE_OBJ_BYTECODE;
        if byte_swap {
            flags |= qjs::JS_WRITE_OBJ_BSWAP;
        }
        let buf = unsafe {
            qjs::JS_WriteObject(ctx.ctx, len.as_mut_ptr(), self.0.as_js_value(), flags as _)
        };
        if buf.is_null() {
            return Err(unsafe { get_exception(ctx) });
        }
        let len = unsafe { len.assume_init() };
        let obj = unsafe { from_raw_parts(buf, len as _) };
        let obj = Vec::from(obj);
        unsafe { qjs::js_free(ctx.ctx, buf as _) };
        Ok(obj)
    }
}

impl<'js> Module<'js, Loaded<Native>> {
    /// Set exported entry by name
    ///
    /// NOTE: Exported entries should be added before module instantiating using [Module::add].
    pub fn set<N, T>(&self, name: N, value: T) -> Result<()>
    where
        N: AsRef<str>,
        T: IntoJs<'js>,
    {
        let name = CString::new(name.as_ref())?;
        let ctx = self.0.ctx;
        let value = value.into_js(ctx)?;
        let value = unsafe { qjs::JS_DupValue(value.as_js_value()) };
        if unsafe { qjs::JS_SetModuleExport(ctx.ctx, self.as_module_def(), name.as_ptr(), value) }
            < 0
        {
            unsafe { qjs::JS_FreeValue(ctx.ctx, value) };
            return Err(unsafe { get_exception(ctx) });
        }
        Ok(())
    }

    unsafe extern "C" fn eval_fn<D>(
        ctx: *mut qjs::JSContext,
        ptr: *mut qjs::JSModuleDef,
    ) -> qjs::c_int
    where
        D: ModuleDef,
    {
        let ctx = Ctx::from_ptr(ctx);
        let module = Self::from_module_def_const(ctx, ptr);
        match D::eval(ctx, &module) {
            Ok(_) => 0,
            Err(error) => {
                error.throw(ctx);
                -1
            }
        }
    }
}

impl<'js, S> Module<'js, Loaded<S>> {
    /// Evaluate a loaded module
    ///
    /// To get access to module exports it should be evaluated first, in particular when you create module manually via [`Module::new`].
    pub fn eval(self) -> Result<Module<'js, Evaluated>> {
        let ctx = self.0.ctx;
        unsafe {
            let ret = qjs::JS_EvalFunction(ctx.ctx, qjs::JS_DupValue(self.0.value));
            handle_exception(ctx, ret)?;
        }
        Ok(Module(self.0, PhantomData))
    }

    /// Cast the specific loaded module to generic one
    pub fn into_loaded(self) -> Module<'js, Loaded> {
        Module(self.0, PhantomData)
    }
}

impl<'js> Module<'js, Created> {
    /// Add entry to module exports
    ///
    /// NOTE: Added entries should be set after module instantiating using [Module::set].
    pub fn add<N>(&self, name: N) -> Result<()>
    where
        N: AsRef<str>,
    {
        let ctx = self.0.ctx;
        let name = CString::new(name.as_ref())?;
        unsafe {
            qjs::JS_AddModuleExport(ctx.ctx, self.as_module_def(), name.as_ptr());
        }
        Ok(())
    }
}

#[cfg(feature = "exports")]
impl<'js> Module<'js> {
    /// Return exported value by name
    pub fn get<N, T>(&self, name: N) -> Result<T>
    where
        N: AsRef<str>,
        T: FromJs<'js>,
    {
        let ctx = self.0.ctx;
        let name = CString::new(name.as_ref())?;
        let value = unsafe {
            Value::from_js_value(
                ctx,
                handle_exception(
                    ctx,
                    qjs::JS_GetModuleExport(ctx.ctx, self.as_module_def(), name.as_ptr()),
                )?,
            )
        };
        T::from_js(ctx, value)
    }

    /// Returns a iterator over the exported names of the module export.
    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "exports")))]
    pub fn names<N>(&self) -> ExportNamesIter<'js, N>
    where
        N: FromAtom<'js>,
    {
        ExportNamesIter {
            module: self.clone(),
            count: unsafe { qjs::JS_GetModuleExportEntriesCount(self.as_module_def()) },
            index: 0,
            marker: PhantomData,
        }
    }

    /// Returns a iterator over the items the module export.
    #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "exports")))]
    pub fn entries<N, T>(&self) -> ExportEntriesIter<'js, N, T>
    where
        N: FromAtom<'js>,
        T: FromJs<'js>,
    {
        ExportEntriesIter {
            module: self.clone(),
            count: unsafe { qjs::JS_GetModuleExportEntriesCount(self.as_module_def()) },
            index: 0,
            marker: PhantomData,
        }
    }

    #[doc(hidden)]
    pub unsafe fn dump_exports(&self) {
        let ctx = self.0.ctx;
        let ptr = self.as_module_def();
        let count = qjs::JS_GetModuleExportEntriesCount(ptr);
        for i in 0..count {
            let atom_name =
                Atom::from_atom_val(ctx, qjs::JS_GetModuleExportEntryName(ctx.ctx, ptr, i));
            println!("{}", atom_name.to_string().unwrap());
        }
    }
}

/// An iterator over the items exported out a module
#[cfg(feature = "exports")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "exports")))]
pub struct ExportNamesIter<'js, N> {
    module: Module<'js>,
    count: i32,
    index: i32,
    marker: PhantomData<N>,
}

#[cfg(feature = "exports")]
impl<'js, N> Iterator for ExportNamesIter<'js, N>
where
    N: FromAtom<'js>,
{
    type Item = Result<N>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index == self.count {
            return None;
        }
        let ctx = self.module.0.ctx;
        let ptr = self.module.as_module_def();
        let atom = unsafe {
            let atom_val = qjs::JS_GetModuleExportEntryName(ctx.ctx, ptr, self.index);
            Atom::from_atom_val(ctx, atom_val)
        };
        self.index += 1;
        Some(N::from_atom(atom))
    }
}

/// An iterator over the items exported out a module
#[cfg(feature = "exports")]
#[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "exports")))]
pub struct ExportEntriesIter<'js, N, T> {
    module: Module<'js>,
    count: i32,
    index: i32,
    marker: PhantomData<(N, T)>,
}

#[cfg(feature = "exports")]
impl<'js, N, T> Iterator for ExportEntriesIter<'js, N, T>
where
    N: FromAtom<'js>,
    T: FromJs<'js>,
{
    type Item = Result<(N, T)>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.index == self.count {
            return None;
        }
        let ctx = self.module.0.ctx;
        let ptr = self.module.as_module_def();
        let name = unsafe {
            let atom_val = qjs::JS_GetModuleExportEntryName(ctx.ctx, ptr, self.index);
            Atom::from_atom_val(ctx, atom_val)
        };
        let value = unsafe {
            let js_val = qjs::JS_GetModuleExportEntry(ctx.ctx, ptr, self.index);
            Value::from_js_value(ctx, js_val)
        };
        self.index += 1;
        Some(N::from_atom(name).and_then(|name| T::from_js(ctx, value).map(|value| (name, value))))
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::*;

    pub struct RustModule;

    impl ModuleDef for RustModule {
        fn load<'js>(_ctx: Ctx<'js>, _module: &Module<'js, Created>) -> Result<()> {
            Ok(())
        }
        fn eval<'js>(_ctx: Ctx<'js>, _module: &Module<'js, Loaded<Native>>) -> Result<()> {
            Ok(())
        }
    }

    #[test]
    fn from_rust_def() {
        test_with(|ctx| {
            Module::new_def::<RustModule, _>(ctx, "rust_mod").unwrap();
        })
    }

    #[test]
    fn from_javascript() {
        test_with(|ctx| {
            let module: Module = ctx
                .compile(
                    "Test",
                    r#"
            export var a = 2;
            export function foo(){ return "bar"}
            export class Baz{
                quel = 3;
                constructor(){
                }
            }
                "#,
                )
                .unwrap();

            assert_eq!(module.name::<StdString>().unwrap(), "Test");
            let _ = module.meta::<Object>().unwrap();

            #[cfg(feature = "exports")]
            {
                let names = module.names().collect::<Result<Vec<StdString>>>().unwrap();

                assert_eq!(names[0], "a");
                assert_eq!(names[1], "foo");
                assert_eq!(names[2], "Baz");

                let entries = module
                    .entries()
                    .collect::<Result<Vec<(StdString, Value)>>>()
                    .unwrap();

                assert_eq!(entries[0].0, "a");
                assert_eq!(i32::from_js(ctx, entries[0].1.clone()).unwrap(), 2);
                assert_eq!(entries[1].0, "foo");
                assert_eq!(entries[2].0, "Baz");
            }
        });
    }
}