Skip to main content

rquickjs_core/context/
base.rs

1use super::{intrinsic, owner::ContextOwner, ContextBuilder, Intrinsic};
2use crate::{context::opaque::ContextOpaque, qjs, Ctx, Error, Result, Runtime};
3use core::{mem, ptr::NonNull};
4
5/// A single execution context with its own global variables and stack.
6///
7/// Can share objects with other contexts of the same runtime.
8#[derive(Clone)]
9pub struct Context(pub(crate) ContextOwner<Runtime>);
10
11impl Context {
12    /// Create a unused context from a raw context pointer.
13    ///
14    /// # Safety
15    /// Pointer must point to a context from the given runtime.
16    /// The context must also have valid reference count, one which can be decremented when this
17    /// object is dropped without going negative.
18    pub unsafe fn from_raw(ctx: NonNull<qjs::JSContext>, rt: Runtime) -> Self {
19        Context(ContextOwner::from_raw(ctx, rt))
20    }
21
22    pub fn as_raw(&self) -> NonNull<qjs::JSContext> {
23        self.0.ctx()
24    }
25
26    /// Creates a base context with only the required functions registered.
27    /// If additional functions are required use [`Context::custom`],
28    /// [`Context::builder`] or [`Context::full`].
29    pub fn base(runtime: &Runtime) -> Result<Self> {
30        Self::custom::<intrinsic::None>(runtime)
31    }
32
33    /// Creates a context with only the required intrinsics registered.
34    /// If additional functions are required use [`Context::custom`],
35    /// [`Context::builder`] or [`Context::full`].
36    pub fn custom<I: Intrinsic>(runtime: &Runtime) -> Result<Self> {
37        let guard = runtime.inner.lock();
38        let ctx = NonNull::new(unsafe { qjs::JS_NewContextRaw(guard.rt.as_ptr()) })
39            .ok_or(Error::Allocation)?;
40        // rquickjs assumes the base objects exist, so we allways need to add this.
41        unsafe { qjs::JS_AddIntrinsicBaseObjects(ctx.as_ptr()) };
42        unsafe { I::add_intrinsic(ctx) };
43        let res = unsafe { ContextOwner::new(ctx, ContextOpaque::new(), runtime.clone()) };
44        mem::drop(guard);
45
46        Ok(Context(res))
47    }
48
49    /// Creates a context with all standard available intrinsics registered.
50    /// If precise control is required of which functions are available use
51    /// [`Context::custom`] or [`Context::builder`].
52    pub fn full(runtime: &Runtime) -> Result<Self> {
53        let guard = runtime.inner.lock();
54        let ctx = NonNull::new(unsafe { qjs::JS_NewContext(guard.rt.as_ptr()) })
55            .ok_or(Error::Allocation)?;
56        let res = unsafe { ContextOwner::new(ctx, ContextOpaque::new(), runtime.clone()) };
57        // Explicitly drop the guard to ensure it is valid during the entire use of runtime
58        mem::drop(guard);
59
60        Ok(Context(res))
61    }
62
63    /// Create a context builder for creating a context with a specific set of intrinsics
64    pub fn builder() -> ContextBuilder<()> {
65        ContextBuilder::default()
66    }
67
68    /// Returns the associated runtime
69    pub fn runtime(&self) -> &Runtime {
70        self.0.rt()
71    }
72
73    #[allow(dead_code)]
74    pub fn get_runtime_ptr(&self) -> *mut qjs::JSRuntime {
75        unsafe { qjs::JS_GetRuntime(self.0.ctx().as_ptr()) }
76    }
77
78    /// A entry point for manipulating and using JavaScript objects and scripts.
79    /// The api is structured this way to avoid repeated locking the runtime when ever
80    /// any function is called. This way the runtime is locked once before executing the callback.
81    /// Furthermore, this way it is impossible to use values from different runtimes in this
82    /// context which would otherwise be undefined behavior.
83    ///
84    ///
85    /// This is the only way to get a [`Ctx`] object.
86    pub fn with<F, R>(&self, f: F) -> R
87    where
88        F: FnOnce(Ctx) -> R,
89    {
90        let guard = self.0.rt().inner.lock();
91        guard.update_stack_top();
92        let ctx = unsafe { Ctx::new(self) };
93        f(ctx)
94    }
95}
96
97// Since the reference to runtime is behind a Arc this object is send
98//
99#[cfg(feature = "parallel")]
100unsafe impl Send for Context {}
101
102// Since all functions lock the global runtime lock access is synchronized so
103// this object is sync
104#[cfg(feature = "parallel")]
105unsafe impl Sync for Context {}
106
107#[cfg(test)]
108mod test {
109    use super::*;
110    use crate::*;
111
112    #[test]
113    fn basic() {
114        test_with(|ctx| {
115            let val: Value = ctx.eval(r#"1+1"#).unwrap();
116
117            assert_eq!(val.type_of(), Type::Int);
118            assert_eq!(i32::from_js(&ctx, val).unwrap(), 2);
119            println!("{:?}", ctx.globals());
120        });
121    }
122
123    #[test]
124    fn minimal() {
125        let rt = Runtime::new().unwrap();
126        let ctx = Context::builder()
127            .with::<intrinsic::Eval>()
128            .build(&rt)
129            .unwrap();
130        ctx.with(|ctx| {
131            let val: i32 = ctx.eval(r#"1+1"#).unwrap();
132
133            assert_eq!(val, 2);
134            println!("{:?}", ctx.globals());
135        });
136    }
137
138    #[test]
139    fn base() {
140        let rt = Runtime::new().unwrap();
141        let _ = Context::base(&rt).unwrap();
142    }
143
144    #[test]
145    fn module() {
146        test_with(|ctx| {
147            Module::evaluate(
148                ctx,
149                "test_mod",
150                r#"
151                    let t = "3";
152                    let b = (a) => a + 3;
153                    export { b, t}
154                "#,
155            )
156            .unwrap()
157            .finish::<()>()
158            .unwrap();
159        });
160    }
161
162    #[test]
163    fn clone_ctx() {
164        let rt = Runtime::new().unwrap();
165        let ctx = Context::builder()
166            .with::<intrinsic::Eval>()
167            .build(&rt)
168            .unwrap();
169
170        let ctx_clone = ctx.clone();
171
172        ctx.with(|ctx| {
173            let val: i32 = ctx.eval(r#"1+1"#).unwrap();
174
175            assert_eq!(val, 2);
176            println!("{:?}", ctx.globals());
177        });
178
179        ctx_clone.with(|ctx| {
180            let val: i32 = ctx.eval(r#"1+1"#).unwrap();
181
182            assert_eq!(val, 2);
183            println!("{:?}", ctx.globals());
184        });
185    }
186
187    #[test]
188    #[cfg(feature = "parallel")]
189    fn parallel() {
190        use std::thread;
191
192        let rt = Runtime::new().unwrap();
193        let ctx = Context::full(&rt).unwrap();
194        ctx.with(|ctx| {
195            let _: () = ctx.eval("this.foo = 42").unwrap();
196        });
197        thread::spawn(move || {
198            ctx.with(|ctx| {
199                let i: i32 = ctx.eval("foo + 8").unwrap();
200                assert_eq!(i, 50);
201            });
202        })
203        .join()
204        .unwrap();
205    }
206
207    #[test]
208    #[cfg(feature = "parallel")]
209    fn parallel_drop() {
210        use std::{
211            sync::{Arc, Barrier},
212            thread,
213        };
214
215        let wait_for_entry = Arc::new(Barrier::new(2));
216
217        let rt = Runtime::new().unwrap();
218        let ctx_1 = Context::full(&rt).unwrap();
219        let ctx_2 = Context::full(&rt).unwrap();
220        let wait_for_entry_c = wait_for_entry.clone();
221        thread::spawn(move || {
222            wait_for_entry_c.wait();
223            std::mem::drop(ctx_1);
224            println!("done");
225        });
226
227        ctx_2.with(|ctx| {
228            wait_for_entry.wait();
229            let i: i32 = ctx.eval("2 + 8").unwrap();
230            assert_eq!(i, 10);
231        });
232        println!("done");
233    }
234
235    #[test]
236    #[should_panic(
237        expected = "Error: invalid first character of private name\n    at eval_script:1:5\n"
238    )]
239    fn exception() {
240        test_with(|ctx| {
241            let val = ctx.eval::<(), _>("bla?#@!@ ").catch(&ctx);
242            if let Err(e) = val {
243                assert!(e.is_exception());
244                panic!("{}", e);
245            }
246        });
247    }
248}