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
27impl Deref for JSContext {
28    type Target = *mut RawJSContext;
29
30    fn deref(&self) -> &Self::Target {
31        &self.0
32    }
33}
34
35thread_local!(
36    static THREAD_ACTIVE: Cell<bool> = const { Cell::new(true) };
37);
38
39pub fn runtime_is_alive() -> bool {
40    THREAD_ACTIVE.with(|t| t.get())
41}
42
43pub fn mark_runtime_dead() {
44    THREAD_ACTIVE.with(|t| t.set(false));
45}
46
47#[derive(Clone, Copy, Debug)]
48/// A compile-time marker that there are operations that could trigger a JS garbage collection
49/// operation within the current stack frame. It is trivially copyable, so it should be passed
50/// as a function argument and reused when calling other functions whenever possible. Since it
51/// is only meaningful within the current stack frame, it is impossible to move it to a different
52/// thread or into a task that will execute asynchronously.
53pub struct CanGc(PhantomData<*mut ()>);
54
55impl CanGc {
56    /// Create a new CanGc value, representing that a GC operation is possible within the
57    /// current stack frame.
58    pub fn note() -> CanGc {
59        CanGc(PhantomData)
60    }
61}