1use alloc::{ffi::CString, vec::Vec};
4use core::{
5 ffi::CStr,
6 marker::PhantomData,
7 mem::MaybeUninit,
8 ptr::{self, null_mut, NonNull},
9 slice,
10};
11
12use crate::{
13 atom::PredefinedAtom, qjs, Atom, Ctx, Error, FromAtom, FromJs, IntoAtom, IntoJs, Object,
14 Promise, Result, Value,
15};
16
17#[derive(Default)]
18pub enum WriteOptionsEndianness {
19 #[default]
21 Native,
22 Little,
24 Big,
26 Swap,
28}
29
30#[derive(Default)]
32pub struct WriteOptions {
33 pub endianness: WriteOptionsEndianness,
35 pub allow_shared_array_buffer: bool,
37 pub object_reference: bool,
39 pub strip_source: bool,
41 pub strip_debug: bool,
43}
44
45impl WriteOptions {
46 pub fn to_flag(&self) -> i32 {
47 let mut flag = qjs::JS_WRITE_OBJ_BYTECODE;
48
49 let should_swap = match &self.endianness {
50 WriteOptionsEndianness::Native => false,
51 WriteOptionsEndianness::Little => cfg!(target_endian = "big"),
52 WriteOptionsEndianness::Big => cfg!(target_endian = "little"),
53 WriteOptionsEndianness::Swap => true,
54 };
55 if should_swap {
56 flag |= qjs::JS_WRITE_OBJ_BSWAP;
57 }
58
59 if self.allow_shared_array_buffer {
60 flag |= qjs::JS_WRITE_OBJ_SAB;
61 }
62
63 if self.object_reference {
64 flag |= qjs::JS_WRITE_OBJ_REFERENCE;
65 }
66
67 if self.strip_source {
68 flag |= qjs::JS_WRITE_OBJ_STRIP_SOURCE;
69 }
70
71 if self.strip_debug {
72 flag |= qjs::JS_WRITE_OBJ_STRIP_DEBUG;
73 }
74
75 flag as i32
76 }
77}
78
79#[macro_export]
92macro_rules! module_init {
93 ($type:ty) => {
94 $crate::module_init!(js_init_module: $type);
95 };
96
97 ($name:ident: $type:ty) => {
98 #[no_mangle]
99 pub unsafe extern "C" fn $name(
100 ctx: *mut $crate::qjs::JSContext,
101 module_name: *const $crate::qjs::c_char,
102 ) -> *mut $crate::qjs::JSModuleDef {
103 $crate::Module::init_raw::<$type>(ctx, module_name)
104 }
105 };
106}
107
108pub type ModuleLoadFn =
110 unsafe extern "C" fn(*mut qjs::JSContext, *const qjs::c_char) -> *mut qjs::JSModuleDef;
111
112pub trait ModuleDef {
114 fn declare<'js>(decl: &Declarations<'js>) -> Result<()> {
115 let _ = decl;
116 Ok(())
117 }
118
119 fn evaluate<'js>(ctx: &Ctx<'js>, exports: &Exports<'js>) -> Result<()> {
120 let _ = (exports, ctx);
121 Ok(())
122 }
123}
124
125pub struct Declarations<'js>(Module<'js, Declared>);
127
128impl<'js> Declarations<'js> {
129 pub fn declare<N>(&self, name: N) -> Result<&Self>
131 where
132 N: Into<Vec<u8>>,
133 {
134 let name = CString::new(name)?;
135 self.declare_c_str(name.as_c_str())
136 }
137
138 pub fn declare_c_str(&self, name: &CStr) -> Result<&Self> {
143 unsafe { qjs::JS_AddModuleExport(self.0.ctx.as_ptr(), self.0.as_ptr(), name.as_ptr()) };
144 Ok(self)
145 }
146
147 pub fn module(&self) -> &Module<'js, Declared> {
149 &self.0
150 }
151}
152
153pub struct Exports<'js>(Module<'js, Declared>);
155
156impl<'js> Exports<'js> {
157 pub fn export<N: Into<Vec<u8>>, T: IntoJs<'js>>(&self, name: N, value: T) -> Result<&Self> {
159 let name = CString::new(name.into())?;
160 self.export_c_str(name.as_c_str(), value)
161 }
162
163 pub fn export_c_str<T: IntoJs<'js>>(&self, name: &CStr, value: T) -> Result<&Self> {
167 let value = value.into_js(&self.0.ctx)?;
168 let res = unsafe {
169 qjs::JS_SetModuleExport(
170 self.0.ctx.as_ptr(),
171 self.0.as_ptr(),
172 name.as_ptr(),
173 value.into_js_value(),
174 )
175 };
176 if res < 0 {
177 return Err(Error::InvalidExport);
178 }
179
180 Ok(self)
181 }
182
183 pub fn module(&self) -> &Module<'js, Declared> {
185 &self.0
186 }
187}
188
189#[derive(Clone, Copy, Debug)]
191pub struct Declared;
192#[derive(Clone, Copy, Debug)]
194pub struct Evaluated;
195
196#[derive(Clone, Debug)]
198pub struct Module<'js, T = Declared> {
199 ptr: NonNull<qjs::JSModuleDef>,
200 ctx: Ctx<'js>,
201 _type_marker: PhantomData<T>,
202}
203
204impl<'js, T> Module<'js, T> {
205 pub(crate) fn as_ptr(&self) -> *mut qjs::JSModuleDef {
206 self.ptr.as_ptr()
207 }
208
209 pub(crate) unsafe fn from_ptr(ctx: Ctx<'js>, ptr: NonNull<qjs::JSModuleDef>) -> Module<'js, T> {
210 Module {
211 ptr,
212 ctx,
213 _type_marker: PhantomData,
214 }
215 }
216
217 unsafe extern "C" fn eval_fn<D>(
218 ctx: *mut qjs::JSContext,
219 ptr: *mut qjs::JSModuleDef,
220 ) -> qjs::c_int
221 where
222 D: ModuleDef,
223 {
224 let ctx = Ctx::from_ptr(ctx);
225 let ptr = NonNull::new(ptr).unwrap();
227 let module = unsafe { Module::from_ptr(ctx.clone(), ptr) };
228 let exports = Exports(module);
229 match D::evaluate(&ctx, &exports) {
230 Ok(_) => 0,
231 Err(error) => {
232 error.throw(&ctx);
233 -1
234 }
235 }
236 }
237
238 pub fn name<N>(&self) -> Result<N>
240 where
241 N: FromAtom<'js>,
242 {
243 let name = unsafe {
244 Atom::from_atom_val(
245 self.ctx.clone(),
246 qjs::JS_GetModuleName(self.ctx.as_ptr(), self.as_ptr()),
247 )
248 };
249 N::from_atom(name)
250 }
251
252 pub fn ctx(&self) -> &Ctx<'js> {
254 &self.ctx
255 }
256}
257
258impl<'js> Module<'js, Declared> {
259 pub fn declare<N, S>(ctx: Ctx<'js>, name: N, source: S) -> Result<Module<'js, Declared>>
261 where
262 N: Into<Vec<u8>>,
263 S: Into<Vec<u8>>,
264 {
265 let name = CString::new(name)?;
266 let flag =
267 qjs::JS_EVAL_TYPE_MODULE | qjs::JS_EVAL_FLAG_STRICT | qjs::JS_EVAL_FLAG_COMPILE_ONLY;
268
269 let module_val = unsafe { ctx.eval_raw(source, name.as_c_str(), flag as i32)? };
270 let module_val = unsafe { ctx.handle_exception(module_val)? };
271 debug_assert_eq!(qjs::JS_TAG_MODULE, unsafe {
272 qjs::JS_VALUE_GET_TAG(module_val)
273 });
274 let module_ptr = unsafe {
275 NonNull::new(qjs::JS_VALUE_GET_PTR(module_val).cast()).ok_or_else(|| {
276 qjs::JS_FreeValue(ctx.as_ptr(), module_val);
277 Error::Unknown
278 })?
279 };
280 unsafe { qjs::JS_FreeValue(ctx.as_ptr(), module_val) };
283 unsafe { Ok(Module::from_ptr(ctx, module_ptr)) }
284 }
285
286 pub fn declare_def<D, N>(ctx: Ctx<'js>, name: N) -> Result<Module<'js, Declared>>
288 where
289 N: Into<Vec<u8>>,
290 D: ModuleDef,
291 {
292 let name = CString::new(name)?;
293 let ptr =
294 unsafe { qjs::JS_NewCModule(ctx.as_ptr(), name.as_ptr(), Some(Self::eval_fn::<D>)) };
295 let ptr = NonNull::new(ptr).ok_or(Error::Unknown)?;
296 let m = unsafe { Module::from_ptr(ctx, ptr) };
297
298 let decl = Declarations(m);
299 D::declare(&decl)?;
300
301 Ok(decl.0)
302 }
304
305 pub fn evaluate<N, S>(ctx: Ctx<'js>, name: N, source: S) -> Result<Promise<'js>>
315 where
316 N: Into<Vec<u8>>,
317 S: Into<Vec<u8>>,
318 {
319 let name = CString::new(name)?;
320 let flag = qjs::JS_EVAL_TYPE_MODULE | qjs::JS_EVAL_FLAG_STRICT;
321
322 let module_val = unsafe { ctx.eval_raw(source, name.as_c_str(), flag as i32)? };
323 let module_val = unsafe { ctx.handle_exception(module_val)? };
324 let v = unsafe { Value::from_js_value(ctx, module_val) };
325 Ok(v.into_promise().expect("evaluate should return a promise"))
326 }
327
328 pub fn evaluate_def<D, N>(
330 ctx: Ctx<'js>,
331 name: N,
332 ) -> Result<(Module<'js, Evaluated>, Promise<'js>)>
333 where
334 N: Into<Vec<u8>>,
335 D: ModuleDef,
336 {
337 let module = Self::declare_def::<D, N>(ctx, name)?;
338 module.eval()
339 }
340
341 pub unsafe fn load(ctx: Ctx<'js>, bytes: &[u8]) -> Result<Module<'js, Declared>> {
346 let module = unsafe {
347 qjs::JS_ReadObject(
348 ctx.as_ptr(),
349 bytes.as_ptr(),
350 bytes.len() as _,
351 (qjs::JS_READ_OBJ_BYTECODE | qjs::JS_READ_OBJ_ROM_DATA) as i32,
352 )
353 };
354 let module = ctx.handle_exception(module)?;
355 debug_assert_eq!(qjs::JS_TAG_MODULE, unsafe { qjs::JS_VALUE_GET_TAG(module) });
356 let module_ptr = unsafe {
357 NonNull::new(qjs::JS_VALUE_GET_PTR(module).cast()).ok_or_else(|| {
358 qjs::JS_FreeValue(ctx.as_ptr(), module);
359 Error::Unknown
360 })?
361 };
362 unsafe { qjs::JS_FreeValue(ctx.as_ptr(), module) };
365 unsafe { Ok(Module::from_ptr(ctx, module_ptr)) }
366 }
367
368 pub unsafe fn from_load_fn<N>(
374 ctx: Ctx<'js>,
375 name: N,
376 load_fn: ModuleLoadFn,
377 ) -> Result<Module<'js, Declared>>
378 where
379 N: Into<Vec<u8>>,
380 {
381 let name = CString::new(name)?;
382 let ptr = (load_fn)(ctx.as_ptr(), name.as_ptr().cast());
383 let ptr = NonNull::new(ptr).ok_or(Error::Exception)?;
384 unsafe { Ok(Module::from_ptr(ctx, ptr)) }
385 }
386
387 pub fn eval(self) -> Result<(Module<'js, Evaluated>, Promise<'js>)> {
392 let ret = unsafe {
393 #[cfg(feature = "parallel")]
394 qjs::JS_UpdateStackTop(qjs::JS_GetRuntime(self.ctx.as_ptr()));
395
396 let v = qjs::JS_MKPTR(qjs::JS_TAG_MODULE, self.ptr.as_ptr().cast());
398 qjs::JS_DupValue(self.ctx.as_ptr(), v);
399 qjs::JS_EvalFunction(self.ctx.as_ptr(), v)
400 };
401 let ret = unsafe { self.ctx.handle_exception(ret)? };
402 let promise = unsafe { Promise::from_js_value(self.ctx.clone(), ret) };
403 Ok((
404 Module {
405 ptr: self.ptr,
406 ctx: self.ctx,
407 _type_marker: PhantomData,
408 },
409 promise,
410 ))
411 }
412
413 pub unsafe extern "C" fn init_raw<D>(
419 ctx: *mut qjs::JSContext,
420 name: *const qjs::c_char,
421 ) -> *mut qjs::JSModuleDef
422 where
423 D: ModuleDef,
424 {
425 let ctx = Ctx::from_ptr(ctx);
426 let name = CStr::from_ptr(name).to_bytes();
427 match Self::declare_def::<D, _>(ctx.clone(), name) {
428 Ok(module) => module.as_ptr(),
429 Err(error) => {
430 error.throw(&ctx);
431 ptr::null_mut()
432 }
433 }
434 }
435
436 pub fn import<S: Into<Vec<u8>>>(ctx: &Ctx<'js>, specifier: S) -> Result<Promise<'js>> {
440 let specifier = CString::new(specifier)?;
441 unsafe {
442 let base_name = ctx
443 .script_or_module_name(1)
444 .unwrap_or_else(|| Atom::from_predefined(ctx.clone(), PredefinedAtom::Empty));
445
446 let base_name_c_str =
447 qjs::JS_AtomToCStringLen(ctx.as_ptr(), null_mut(), base_name.atom);
448
449 let res = qjs::JS_LoadModule(
450 ctx.as_ptr(),
451 base_name_c_str,
452 specifier.as_ptr(),
453 qjs::JS_UNDEFINED,
454 );
455
456 qjs::JS_FreeCString(ctx.as_ptr(), base_name_c_str);
457
458 let res = ctx.handle_exception(res)?;
459
460 Ok(Promise::from_js_value(ctx.clone(), res))
461 }
462 }
463}
464
465impl<'js, Evaluated> Module<'js, Evaluated> {
466 pub fn write(&self, options: WriteOptions) -> Result<Vec<u8>> {
488 let ctx = &self.ctx;
489 let mut len = MaybeUninit::uninit();
490 let buf = unsafe {
491 qjs::JS_WriteObject(
492 ctx.as_ptr(),
493 len.as_mut_ptr(),
494 qjs::JS_MKPTR(qjs::JS_TAG_MODULE, self.ptr.as_ptr().cast()),
495 options.to_flag(),
496 )
497 };
498 if buf.is_null() {
499 return Err(ctx.raise_exception());
500 }
501 let len = unsafe { len.assume_init() };
502 let obj = unsafe { slice::from_raw_parts(buf, len as _) };
503 let obj = Vec::from(obj);
504 unsafe { qjs::js_free(ctx.as_ptr(), buf as _) };
505 Ok(obj)
506 }
507
508 pub fn meta(&self) -> Result<Object<'js>> {
510 unsafe {
511 Ok(Object::from_js_value(
512 self.ctx.clone(),
513 self.ctx
514 .handle_exception(qjs::JS_GetImportMeta(self.ctx.as_ptr(), self.as_ptr()))?,
515 ))
516 }
517 }
518
519 pub fn namespace(&self) -> Result<Object<'js>> {
521 unsafe {
522 let v = qjs::JS_GetModuleNamespace(self.ctx.as_ptr(), self.as_ptr());
523 let v = self.ctx.handle_exception(v)?;
524 Ok(Object::from_js_value(self.ctx.clone(), v))
525 }
526 }
527
528 pub fn get<N, T>(&self, name: N) -> Result<T>
530 where
531 N: IntoAtom<'js>,
532 T: FromJs<'js>,
533 {
534 self.namespace()?.get(name)
535 }
536
537 pub fn into_declared(self) -> Module<'js, Declared> {
541 Module {
542 ptr: self.ptr,
543 ctx: self.ctx,
544 _type_marker: PhantomData,
545 }
546 }
547}
548
549#[cfg(test)]
550mod test {
551
552 use super::*;
553 use crate::*;
554
555 pub struct RustModule;
556
557 impl ModuleDef for RustModule {
558 fn declare(define: &Declarations) -> Result<()> {
559 define.declare_c_str(c"hello")?;
560 Ok(())
561 }
562
563 fn evaluate<'js>(_ctx: &Ctx<'js>, exports: &Exports<'js>) -> Result<()> {
564 exports.export_c_str(c"hello", "world")?;
565 Ok(())
566 }
567 }
568
569 pub struct CrashingRustModule;
570
571 impl ModuleDef for CrashingRustModule {
572 fn declare(_: &Declarations) -> Result<()> {
573 Ok(())
574 }
575
576 fn evaluate<'js>(ctx: &Ctx<'js>, _exports: &Exports<'js>) -> Result<()> {
577 ctx.eval::<(), _>(r#"throw new Error("kaboom")"#)?;
578 Ok(())
579 }
580 }
581
582 #[test]
583 fn from_rust_def() {
584 test_with(|ctx| {
585 Module::declare_def::<RustModule, _>(ctx, "rust_mod").unwrap();
586 })
587 }
588
589 #[test]
590 fn from_rust_def_eval() {
591 test_with(|ctx| {
592 let _ = Module::evaluate_def::<RustModule, _>(ctx, "rust_mod").unwrap();
593 })
594 }
595
596 #[test]
597 fn import_native() {
598 test_with(|ctx| {
599 Module::declare_def::<RustModule, _>(ctx.clone(), "rust_mod").unwrap();
600 Module::evaluate(
601 ctx.clone(),
602 "test",
603 r#"
604 import { hello } from "rust_mod";
605
606 globalThis.hello = hello;
607 "#,
608 )
609 .unwrap()
610 .finish::<()>()
611 .unwrap();
612 let text = ctx
613 .globals()
614 .get::<_, String>("hello")
615 .unwrap()
616 .to_string()
617 .unwrap();
618 assert_eq!(text.as_str(), "world");
619 })
620 }
621
622 #[test]
623 fn import_async() {
624 test_with(|ctx| {
625 Module::declare(
626 ctx.clone(),
627 "rust_mod",
628 "
629 async function foo(){
630 return 'world';
631 };
632 export let hello = await foo();
633 ",
634 )
635 .unwrap();
636 Module::evaluate(
637 ctx.clone(),
638 "test",
639 r#"
640 import { hello } from "rust_mod";
641 globalThis.hello = hello;
642 "#,
643 )
644 .unwrap()
645 .finish::<()>()
646 .unwrap();
647 let text = ctx
648 .globals()
649 .get::<_, String>("hello")
650 .unwrap()
651 .to_string()
652 .unwrap();
653 assert_eq!(text.as_str(), "world");
654 })
655 }
656
657 #[test]
658 fn import() {
659 test_with(|ctx| {
660 Module::declare_def::<RustModule, _>(ctx.clone(), "rust_mod").unwrap();
661 let val: Object = Module::import(&ctx, "rust_mod").unwrap().finish().unwrap();
662 let hello: StdString = val.get("hello").unwrap();
663
664 assert_eq!(&hello, "world");
665 })
666 }
667
668 #[test]
669 #[should_panic(expected = "kaboom")]
670 fn import_crashing() {
671 use crate::{CatchResultExt, Context, Runtime};
672
673 let runtime = Runtime::new().unwrap();
674 let ctx = Context::full(&runtime).unwrap();
675 ctx.with(|ctx| {
676 Module::declare_def::<CrashingRustModule, _>(ctx.clone(), "bad_rust_mod").unwrap();
677 let _: Value = Module::import(&ctx, "bad_rust_mod")
678 .catch(&ctx)
679 .unwrap()
680 .finish()
681 .catch(&ctx)
682 .unwrap();
683 });
684 }
685
686 #[test]
687 fn eval_crashing_module_inside_module() {
688 let runtime = Runtime::new().unwrap();
689 let ctx = Context::full(&runtime).unwrap();
690
691 ctx.with(|ctx| {
692 let globals = ctx.globals();
693 let eval_crashing = |ctx: Ctx| {
694 Module::evaluate(ctx, "test2", "throw new Error(1)").map(|x| x.finish::<()>())
695 };
696 let function = Function::new(ctx.clone(), eval_crashing).unwrap();
697 globals.set("eval_crashing", function).unwrap();
698
699 let res = Module::evaluate(ctx, "test", " eval_crashing(); ")
700 .unwrap()
701 .finish::<()>();
702 assert!(res.is_err())
703 });
704 }
705
706 #[test]
707 fn access_before_fully_evaluating_module() {
708 let runtime = Runtime::new().unwrap();
709 let ctx = Context::full(&runtime).unwrap();
710
711 ctx.with(|ctx| {
712 let decl = Module::declare(
713 ctx,
714 "test",
715 r#"
716 async function async_res(){
717 return await (async () => {
718 return "OK"
719 })()
720 };
721
722 export let res = await async_res()
723 "#,
724 )
725 .unwrap();
726
727 let (decl, promise) = decl.eval().unwrap();
728
729 let ns = decl.namespace().unwrap();
730 ns.get::<_, ()>("res").unwrap_err();
731
732 promise.finish::<()>().unwrap();
733
734 assert_eq!(ns.get::<_, std::string::String>("res").unwrap(), "OK");
735 });
736 }
737
738 #[test]
739 fn from_javascript() {
740 test_with(|ctx| {
741 let (module, promise) = Module::declare(
742 ctx.clone(),
743 "Test",
744 r#"
745 export var a = 2;
746 export function foo(){ return "bar"}
747 export class Baz{
748 quel = 3;
749 constructor(){
750 }
751 }
752 "#,
753 )
754 .unwrap()
755 .eval()
756 .unwrap();
757
758 promise.finish::<()>().unwrap();
759
760 assert_eq!(module.name::<StdString>().unwrap(), "Test");
761 let _ = module.meta().unwrap();
762
763 let ns = module.namespace().unwrap();
764
765 assert!(ns.contains_key("a").unwrap());
766 assert!(ns.contains_key("foo").unwrap());
767 assert!(ns.contains_key("Baz").unwrap());
768
769 assert_eq!(ns.get::<_, u32>("a").unwrap(), 2u32);
770 });
771 }
772}