script_bindings/script_runtime.rs
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use std::cell::Cell;
6use std::marker::PhantomData;
7use std::ops::Deref;
8
9use js::jsapi::JSContext as RawJSContext;
10
11#[derive(Clone, Copy)]
12#[repr(transparent)]
13pub struct JSContext(*mut RawJSContext);
14
15#[expect(unsafe_code)]
16impl JSContext {
17 /// Create a new [`JSContext`] object from the given raw pointer.
18 ///
19 /// # Safety
20 ///
21 /// The `RawJSContext` argument must point to a valid `RawJSContext` in memory.
22 pub unsafe fn from_ptr(raw_js_context: *mut RawJSContext) -> Self {
23 JSContext(raw_js_context)
24 }
25
26 /// For compatibility with [js::context::JSContext]
27 pub fn raw_cx(&self) -> *mut RawJSContext {
28 self.0
29 }
30
31 /// For compatibility with [js::context::JSContext]
32 pub fn raw_cx_no_gc(&self) -> *mut RawJSContext {
33 self.0
34 }
35}
36
37impl Deref for JSContext {
38 type Target = *mut RawJSContext;
39
40 fn deref(&self) -> &Self::Target {
41 &self.0
42 }
43}
44
45thread_local!(
46 static THREAD_ACTIVE: Cell<bool> = const { Cell::new(true) };
47);
48
49pub fn runtime_is_alive() -> bool {
50 THREAD_ACTIVE.with(|t| t.get())
51}
52
53pub fn mark_runtime_dead() {
54 THREAD_ACTIVE.with(|t| t.set(false));
55}
56
57#[derive(Clone, Copy, Debug)]
58/// A compile-time marker that there are operations that could trigger a JS garbage collection
59/// operation within the current stack frame. It is trivially copyable, so it should be passed
60/// as a function argument and reused when calling other functions whenever possible. Since it
61/// is only meaningful within the current stack frame, it is impossible to move it to a different
62/// thread or into a task that will execute asynchronously.
63pub struct CanGc(PhantomData<*mut ()>);
64
65impl CanGc {
66 /// Create a new CanGc value, representing that a GC operation is possible within the
67 /// current stack frame.
68 pub fn note() -> CanGc {
69 CanGc(PhantomData)
70 }
71}