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