1#[cfg(feature = "futures")]
2use core::future::Future;
3
4use alloc::{boxed::Box, ffi::CString, vec::Vec};
5use core::{
6 any::Any,
7 ffi::CStr,
8 mem::{self, MaybeUninit},
9 ptr::NonNull,
10 result::Result as StdResult,
11};
12
13#[cfg(feature = "std")]
14use std::{fs, path::Path, string::String as StdString};
15
16#[cfg(feature = "futures")]
17use crate::AsyncContext;
18use crate::{
19 markers::Invariant,
20 qjs,
21 runtime::{opaque::Opaque, UserDataError, UserDataGuard},
22 Atom, Error, FromJs, Function, IntoJs, JsLifetime, Object, Promise, Result, String, Value,
23};
24
25use super::Context;
26
27#[non_exhaustive]
29pub struct EvalOptions {
30 pub global: bool,
32 pub strict: bool,
34 pub backtrace_barrier: bool,
36 pub promise: bool,
38 #[cfg(feature = "std")]
40 pub filename: Option<StdString>,
41}
42
43impl EvalOptions {
44 fn to_flag(&self) -> i32 {
45 let mut flag = if self.global {
46 qjs::JS_EVAL_TYPE_GLOBAL
47 } else {
48 qjs::JS_EVAL_TYPE_MODULE
49 };
50
51 if self.strict {
52 flag |= qjs::JS_EVAL_FLAG_STRICT;
53 }
54
55 if self.backtrace_barrier {
56 flag |= qjs::JS_EVAL_FLAG_BACKTRACE_BARRIER;
57 }
58
59 if self.promise {
60 flag |= qjs::JS_EVAL_FLAG_ASYNC;
61 }
62
63 flag as i32
64 }
65}
66
67impl Default for EvalOptions {
68 fn default() -> Self {
69 EvalOptions {
70 global: true,
71 strict: true,
72 backtrace_barrier: false,
73 promise: false,
74 #[cfg(feature = "std")]
75 filename: None,
76 }
77 }
78}
79
80#[derive(Debug)]
82pub struct Ctx<'js> {
83 ctx: NonNull<qjs::JSContext>,
84 _marker: Invariant<'js>,
85}
86
87impl<'js> Clone for Ctx<'js> {
88 fn clone(&self) -> Self {
89 unsafe { qjs::JS_DupContext(self.ctx.as_ptr()) };
90 Ctx {
91 ctx: self.ctx,
92 _marker: self._marker,
93 }
94 }
95}
96
97impl<'js> Drop for Ctx<'js> {
98 fn drop(&mut self) {
99 unsafe { qjs::JS_FreeContext(self.ctx.as_ptr()) };
100 }
101}
102
103unsafe impl Send for Ctx<'_> {}
104
105impl<'js> Ctx<'js> {
106 pub(crate) fn as_ptr(&self) -> *mut qjs::JSContext {
107 self.ctx.as_ptr()
108 }
109
110 pub(crate) unsafe fn from_ptr(ctx: *mut qjs::JSContext) -> Self {
111 unsafe { qjs::JS_DupContext(ctx) };
112 let ctx = NonNull::new_unchecked(ctx);
113 Ctx {
114 ctx,
115 _marker: Invariant::new(),
116 }
117 }
118
119 pub(crate) unsafe fn new(ctx: &'js Context) -> Self {
120 unsafe { qjs::JS_DupContext(ctx.0.ctx().as_ptr()) };
121 Ctx {
122 ctx: ctx.0.ctx(),
123 _marker: Invariant::new(),
124 }
125 }
126
127 #[cfg(feature = "futures")]
128 pub(crate) unsafe fn new_async(ctx: &'js AsyncContext) -> Self {
129 unsafe { qjs::JS_DupContext(ctx.0.ctx().as_ptr()) };
130 Ctx {
131 ctx: ctx.0.ctx(),
132 _marker: Invariant::new(),
133 }
134 }
135
136 pub(crate) unsafe fn eval_raw<S: Into<Vec<u8>>>(
137 &self,
138 source: S,
139 file_name: &CStr,
140 flag: i32,
141 ) -> Result<qjs::JSValue> {
142 let src = source.into();
143 let len = src.len();
144 let src = CString::new(src)?;
145
146 #[cfg(feature = "parallel")]
147 qjs::JS_UpdateStackTop(qjs::JS_GetRuntime(self.ctx.as_ptr()));
148
149 let val = qjs::JS_Eval(
150 self.ctx.as_ptr(),
151 src.as_ptr(),
152 len as _,
153 file_name.as_ptr(),
154 flag,
155 );
156 self.handle_exception(val)
157 }
158
159 pub fn eval<V: FromJs<'js>, S: Into<Vec<u8>>>(&self, source: S) -> Result<V> {
161 self.eval_with_options(source, Default::default())
162 }
163
164 pub fn compile<S: Into<Vec<u8>>, N: Into<Vec<u8>>>(
169 &self,
170 source: S,
171 filename: N,
172 strict: bool,
173 ) -> Result<()> {
174 let filename = CString::new(filename)?;
175 let mut flags = qjs::JS_EVAL_TYPE_GLOBAL | qjs::JS_EVAL_FLAG_COMPILE_ONLY;
176 if strict {
177 flags |= qjs::JS_EVAL_FLAG_STRICT;
178 }
179 let value = unsafe { self.eval_raw(source, filename.as_c_str(), flags as i32)? };
180 unsafe { qjs::JS_FreeValue(self.as_ptr(), value) };
181 Ok(())
182 }
183
184 pub fn eval_promise<S: Into<Vec<u8>>>(&self, source: S) -> Result<Promise<'js>> {
189 self.eval_with_options(
190 source,
191 EvalOptions {
192 promise: true,
193 ..Default::default()
194 },
195 )
196 }
197
198 pub fn eval_with_options<V: FromJs<'js>, S: Into<Vec<u8>>>(
200 &self,
201 source: S,
202 options: EvalOptions,
203 ) -> Result<V> {
204 #[cfg(feature = "std")]
205 let file_name = {
206 if let Some(filename) = &options.filename {
207 &CString::new(filename.clone())?
208 } else {
209 c"eval_script"
210 }
211 };
212
213 #[cfg(not(feature = "std"))]
214 let file_name = c"eval_script";
215
216 V::from_js(self, unsafe {
217 let val = self.eval_raw(source, file_name, options.to_flag())?;
218 Value::from_js_value(self.clone(), val)
219 })
220 }
221
222 #[cfg(feature = "std")]
223 pub fn eval_file<V: FromJs<'js>, P: AsRef<Path>>(&self, path: P) -> Result<V> {
225 self.eval_file_with_options(path, Default::default())
226 }
227
228 #[cfg(feature = "std")]
229 pub fn eval_file_with_options<V: FromJs<'js>, P: AsRef<Path>>(
230 &self,
231 path: P,
232 options: EvalOptions,
233 ) -> Result<V> {
234 let buffer = fs::read(path.as_ref())?;
235 let file_name = CString::new(
236 path.as_ref()
237 .file_name()
238 .unwrap()
239 .to_string_lossy()
240 .into_owned(),
241 )?;
242
243 V::from_js(self, unsafe {
244 let val = self.eval_raw(buffer, file_name.as_c_str(), options.to_flag())?;
245 Value::from_js_value(self.clone(), val)
246 })
247 }
248
249 pub fn globals(&self) -> Object<'js> {
251 unsafe {
252 let v = qjs::JS_GetGlobalObject(self.ctx.as_ptr());
253 Object::from_js_value(self.clone(), v)
254 }
255 }
256
257 pub fn catch(&self) -> Value<'js> {
273 unsafe {
274 let v = qjs::JS_GetException(self.ctx.as_ptr());
275 Value::from_js_value(self.clone(), v)
276 }
277 }
278
279 pub fn has_exception(&self) -> bool {
281 unsafe { qjs::JS_HasException(self.ctx.as_ptr()) }
282 }
283
284 pub fn throw(&self, value: Value<'js>) -> Error {
287 unsafe {
288 let v = value.into_js_value();
289 qjs::JS_Throw(self.ctx.as_ptr(), v);
290 }
291 Error::Exception
292 }
293
294 pub fn json_parse<S>(&self, json: S) -> Result<Value<'js>>
296 where
297 S: Into<Vec<u8>>,
298 {
299 let src = json.into();
300 let len = src.len();
301 let src = CString::new(src)?;
302 unsafe {
303 let name = b"<input>\0";
304 let v = qjs::JS_ParseJSON(
305 self.as_ptr(),
306 src.as_ptr().cast(),
307 len.try_into().expect(qjs::SIZE_T_ERROR),
308 name.as_ptr().cast(),
309 );
310 self.handle_exception(v)?;
311 Ok(Value::from_js_value(self.clone(), v))
312 }
313 }
314
315 pub fn json_stringify<V>(&self, value: V) -> Result<Option<String<'js>>>
317 where
318 V: IntoJs<'js>,
319 {
320 self.json_stringify_inner(&value.into_js(self)?, qjs::JS_UNDEFINED, qjs::JS_UNDEFINED)
321 }
322
323 pub fn json_stringify_replacer<V, R>(
328 &self,
329 value: V,
330 replacer: R,
331 ) -> Result<Option<String<'js>>>
332 where
333 V: IntoJs<'js>,
334 R: IntoJs<'js>,
335 {
336 let replacer = replacer.into_js(self)?;
337
338 self.json_stringify_inner(
339 &value.into_js(self)?,
340 replacer.as_js_value(),
341 qjs::JS_UNDEFINED,
342 )
343 }
344
345 pub fn json_stringify_replacer_space<V, R, S>(
355 &self,
356 value: V,
357 replacer: R,
358 space: S,
359 ) -> Result<Option<String<'js>>>
360 where
361 V: IntoJs<'js>,
362 R: IntoJs<'js>,
363 S: IntoJs<'js>,
364 {
365 let replacer = replacer.into_js(self)?;
366 let space = space.into_js(self)?;
367
368 self.json_stringify_inner(
369 &value.into_js(self)?,
370 replacer.as_js_value(),
371 space.as_js_value(),
372 )
373 }
374
375 fn json_stringify_inner(
377 &self,
378 value: &Value<'js>,
379 replacer: qjs::JSValueConst,
380 space: qjs::JSValueConst,
381 ) -> Result<Option<String<'js>>> {
382 unsafe {
383 let res = qjs::JS_JSONStringify(self.as_ptr(), value.as_js_value(), replacer, space);
384 self.handle_exception(res)?;
385 let v = Value::from_js_value(self.clone(), res);
386 if v.is_undefined() {
387 Ok(None)
388 } else {
389 let v = v.into_string().expect(
390 "JS_JSONStringify did not return either an exception, undefined, or a string",
391 );
392 Ok(Some(v))
393 }
394 }
395 }
396
397 pub fn promise(&self) -> Result<(Promise<'js>, Function<'js>, Function<'js>)> {
399 let mut funcs = mem::MaybeUninit::<[qjs::JSValue; 2]>::uninit();
400
401 Ok(unsafe {
402 let promise = self.handle_exception(qjs::JS_NewPromiseCapability(
403 self.ctx.as_ptr(),
404 funcs.as_mut_ptr() as _,
405 ))?;
406 let [resolve, reject] = funcs.assume_init();
407 (
408 Promise::from_js_value(self.clone(), promise),
409 Function::from_js_value(self.clone(), resolve),
410 Function::from_js_value(self.clone(), reject),
411 )
412 })
413 }
414
415 pub fn execute_pending_job(&self) -> bool {
420 let mut ptr = MaybeUninit::<*mut qjs::JSContext>::uninit();
421 let rt = unsafe { qjs::JS_GetRuntime(self.ctx.as_ptr()) };
422 let res = unsafe { qjs::JS_ExecutePendingJob(rt, ptr.as_mut_ptr()) };
423 if res < 0 {
424 let ctx = unsafe { Self::from_ptr(ptr.assume_init()) };
431 ctx.catch();
432 }
433 res != 0
434 }
435
436 pub(crate) unsafe fn get_opaque(&self) -> &Opaque<'js> {
437 Opaque::from_runtime_ptr(qjs::JS_GetRuntime(self.ctx.as_ptr()))
438 }
439
440 #[cfg(feature = "futures")]
442 #[cfg_attr(feature = "doc-cfg", doc(cfg(feature = "futures")))]
443 pub fn spawn<F>(&self, future: F)
444 where
445 F: Future<Output = ()> + 'js,
446 {
447 unsafe { self.get_opaque().push(future) }
448 }
449
450 pub unsafe fn from_raw_invariant(ctx: NonNull<qjs::JSContext>, inv: Invariant<'js>) -> Self {
457 unsafe { qjs::JS_DupContext(ctx.as_ptr()) };
458 Ctx { ctx, _marker: inv }
459 }
460
461 pub unsafe fn from_raw(ctx: NonNull<qjs::JSContext>) -> Self {
468 unsafe { qjs::JS_DupContext(ctx.as_ptr()) };
469 Ctx {
470 ctx,
471 _marker: Invariant::new(),
472 }
473 }
474
475 pub fn script_or_module_name(&self, stack_level: isize) -> Option<Atom<'js>> {
481 let stack_level = core::ffi::c_int::try_from(stack_level).unwrap();
482 let atom = unsafe { qjs::JS_GetScriptOrModuleName(self.as_ptr(), stack_level) };
483 #[allow(clippy::useless_conversion)] if qjs::__JS_ATOM_NULL == atom.try_into().unwrap() {
485 unsafe { qjs::JS_FreeAtom(self.as_ptr(), atom) };
486 return None;
487 }
488 unsafe { Some(Atom::from_atom_val(self.clone(), atom)) }
489 }
490
491 pub fn run_gc(&self) {
497 unsafe { qjs::JS_RunGC(qjs::JS_GetRuntime(self.ctx.as_ptr())) }
498 }
499
500 pub fn store_userdata<U>(&self, data: U) -> StdResult<Option<Box<U>>, UserDataError<U>>
506 where
507 U: JsLifetime<'js>,
508 U::Changed<'static>: Any,
509 {
510 unsafe { self.get_opaque().insert_userdata(data) }
511 }
512
513 pub fn remove_userdata<U>(&self) -> StdResult<Option<Box<U>>, UserDataError<()>>
518 where
519 U: JsLifetime<'js>,
520 U::Changed<'static>: Any,
521 {
522 unsafe { self.get_opaque().remove_userdata() }
523 }
524
525 pub fn userdata<U>(&self) -> Option<UserDataGuard<U>>
529 where
530 U: JsLifetime<'js>,
531 U::Changed<'static>: Any,
532 {
533 unsafe { self.get_opaque().get_userdata() }
534 }
535
536 pub fn as_raw(&self) -> NonNull<qjs::JSContext> {
538 self.ctx
539 }
540}
541
542#[cfg(test)]
543mod test {
544 use crate::{CatchResultExt, JsLifetime};
545
546 #[test]
547 fn exports() {
548 use crate::{context::intrinsic, Context, Function, Module, Promise, Runtime};
549
550 let runtime = Runtime::new().unwrap();
551 let ctx = Context::custom::<(intrinsic::Promise, intrinsic::Eval)>(&runtime).unwrap();
552 ctx.with(|ctx| {
553 let (module, promise) = Module::declare(ctx, "test", "export default async () => 1;")
554 .unwrap()
555 .eval()
556 .unwrap();
557 promise.finish::<()>().unwrap();
558 let func: Function = module.get("default").unwrap();
559 func.call::<(), Promise>(()).unwrap();
560 });
561 }
562
563 #[test]
564 fn execute_pending_job_clears_exception_from_failed_job() {
565 use crate::{Context, Runtime};
566
567 let runtime = Runtime::new().unwrap();
568 let ctx = Context::full(&runtime).unwrap();
569 ctx.with(|ctx| {
570 ctx.eval::<(), _>("queueMicrotask(() => { throw new Error('boom'); });")
572 .unwrap();
573
574 while ctx.execute_pending_job() {}
577
578 assert!(!ctx.has_exception());
579
580 let sum: i32 = ctx.eval("1 + 1").unwrap();
582 assert_eq!(sum, 2);
583 })
584 }
585
586 #[test]
587 fn eval() {
588 use crate::{Context, Runtime};
589
590 let runtime = Runtime::new().unwrap();
591 let ctx = Context::full(&runtime).unwrap();
592 ctx.with(|ctx| {
593 let res: String = ctx
594 .eval(
595 r#"
596 function test() {
597 var foo = "bar";
598 return foo;
599 }
600
601 test()
602 "#,
603 )
604 .unwrap();
605
606 assert_eq!("bar".to_string(), res);
607 })
608 }
609
610 #[test]
611 fn eval_minimal_test() {
612 use crate::{Context, Runtime};
613
614 let runtime = Runtime::new().unwrap();
615 let ctx = Context::full(&runtime).unwrap();
616 ctx.with(|ctx| {
617 let res: i32 = ctx.eval(" 1 + 1 ").unwrap();
618 assert_eq!(2, res);
619 })
620 }
621
622 #[test]
623 #[should_panic(expected = "foo is not defined")]
624 fn eval_with_sloppy_code() {
625 use crate::{CatchResultExt, Context, Runtime};
626
627 let runtime = Runtime::new().unwrap();
628 let ctx = Context::full(&runtime).unwrap();
629 ctx.with(|ctx| {
630 let _: String = ctx
631 .eval(
632 r#"
633 function test() {
634 foo = "bar";
635 return foo;
636 }
637
638 test()
639 "#,
640 )
641 .catch(&ctx)
642 .unwrap();
643 })
644 }
645
646 #[test]
647 fn eval_with_options_no_strict_sloppy_code() {
648 use crate::{context::EvalOptions, Context, Runtime};
649
650 let runtime = Runtime::new().unwrap();
651 let ctx = Context::full(&runtime).unwrap();
652 ctx.with(|ctx| {
653 let res: String = ctx
654 .eval_with_options(
655 r#"
656 function test() {
657 foo = "bar";
658 return foo;
659 }
660
661 test()
662 "#,
663 EvalOptions {
664 strict: false,
665 ..Default::default()
666 },
667 )
668 .unwrap();
669
670 assert_eq!("bar".to_string(), res);
671 })
672 }
673
674 #[test]
675 #[should_panic(expected = "foo is not defined")]
676 fn eval_with_options_strict_sloppy_code() {
677 use crate::{context::EvalOptions, CatchResultExt, Context, Runtime};
678
679 let runtime = Runtime::new().unwrap();
680 let ctx = Context::full(&runtime).unwrap();
681 ctx.with(|ctx| {
682 let _: String = ctx
683 .eval_with_options(
684 r#"
685 function test() {
686 foo = "bar";
687 return foo;
688 }
689
690 test()
691 "#,
692 EvalOptions {
693 strict: true,
694 ..Default::default()
695 },
696 )
697 .catch(&ctx)
698 .unwrap();
699 })
700 }
701
702 #[test]
703 fn json_parse() {
704 use crate::{Array, Context, Object, Runtime};
705
706 let runtime = Runtime::new().unwrap();
707 let ctx = Context::full(&runtime).unwrap();
708 ctx.with(|ctx| {
709 let v = ctx
710 .json_parse(r#"{ "a": { "b": 1, "c": true }, "d": [0,"foo"] }"#)
711 .unwrap();
712 let obj = v.into_object().unwrap();
713 let inner_obj: Object = obj.get("a").unwrap();
714 assert_eq!(inner_obj.get::<_, i32>("b").unwrap(), 1);
715 assert!(inner_obj.get::<_, bool>("c").unwrap());
716 let inner_array: Array = obj.get("d").unwrap();
717 assert_eq!(inner_array.get::<i32>(0).unwrap(), 0);
718 assert_eq!(inner_array.get::<String>(1).unwrap(), "foo".to_string());
719 })
720 }
721
722 #[test]
723 fn json_stringify() {
724 use crate::{Array, Context, Object, Runtime};
725
726 let runtime = Runtime::new().unwrap();
727 let ctx = Context::full(&runtime).unwrap();
728 ctx.with(|ctx| {
729 let obj_inner = Object::new(ctx.clone()).unwrap();
730 obj_inner.set("b", 1).unwrap();
731 obj_inner.set("c", true).unwrap();
732
733 let array_inner = Array::new(ctx.clone()).unwrap();
734 array_inner.set(0, 0).unwrap();
735 array_inner.set(1, "foo").unwrap();
736
737 let obj = Object::new(ctx.clone()).unwrap();
738 obj.set("a", obj_inner).unwrap();
739 obj.set("d", array_inner).unwrap();
740
741 let str = ctx
742 .json_stringify(obj)
743 .unwrap()
744 .unwrap()
745 .to_string()
746 .unwrap();
747
748 assert_eq!(str, r#"{"a":{"b":1,"c":true},"d":[0,"foo"]}"#);
749 })
750 }
751
752 #[test]
753 fn userdata() {
754 use crate::{Context, Function, Runtime};
755
756 pub struct MyUserData<'js> {
757 base: Function<'js>,
758 }
759
760 unsafe impl<'js> JsLifetime<'js> for MyUserData<'js> {
761 type Changed<'to> = MyUserData<'to>;
762 }
763
764 let rt = Runtime::new().unwrap();
765 let ctx = Context::full(&rt).unwrap();
766
767 ctx.with(|ctx| {
768 let func = ctx.eval("() => 42").catch(&ctx).unwrap();
769 ctx.store_userdata(MyUserData { base: func }).unwrap();
770 });
771
772 ctx.with(|ctx| {
773 let userdata = ctx.userdata::<MyUserData>().unwrap();
774
775 assert!(ctx.remove_userdata::<MyUserData>().is_err());
776
777 let r: usize = userdata.base.call(()).unwrap();
778 assert_eq!(r, 42)
779 });
780
781 ctx.with(|ctx| {
782 ctx.remove_userdata::<MyUserData>().unwrap().unwrap();
783 })
784 }
785}