mozjs/gc/
root.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
use std::marker::PhantomData;
use std::mem::MaybeUninit;
use std::ops::{Deref, DerefMut};
use std::ptr;

use crate::jsapi::{jsid, JSContext, JSFunction, JSObject, JSScript, JSString, Symbol, Value, JS};
use mozjs_sys::jsgc::{RootKind, Rooted};

use crate::jsapi::Handle as RawHandle;
use crate::jsapi::HandleValue as RawHandleValue;
use crate::jsapi::MutableHandle as RawMutableHandle;
use mozjs_sys::jsgc::IntoHandle as IntoRawHandle;
use mozjs_sys::jsgc::IntoMutableHandle as IntoRawMutableHandle;
use mozjs_sys::jsgc::ValueArray;

/// Rust API for keeping a Rooted value in the context's root stack.
/// Example usage: `rooted!(in(cx) let x = UndefinedValue());`.
/// `RootedGuard::new` also works, but the macro is preferred.
#[cfg_attr(
    feature = "crown",
    crown::unrooted_must_root_lint::allow_unrooted_interior
)]
pub struct RootedGuard<'a, T: 'a + RootKind> {
    root: *mut Rooted<T>,
    anchor: PhantomData<&'a mut Rooted<T>>,
}

impl<'a, T: 'a + RootKind> RootedGuard<'a, T> {
    pub fn new(cx: *mut JSContext, root: &'a mut Rooted<T>, initial: T) -> Self {
        root.ptr.write(initial);
        unsafe {
            let root: *mut Rooted<T> = root;
            Rooted::add_to_root_stack(root, cx);
            RootedGuard {
                root,
                anchor: PhantomData,
            }
        }
    }

    pub fn handle(&'a self) -> Handle<'a, T> {
        Handle::new(&self)
    }

    pub fn handle_mut(&mut self) -> MutableHandle<T> {
        unsafe { MutableHandle::from_marked_location(self.as_ptr()) }
    }

    pub fn as_ptr(&self) -> *mut T {
        // SAFETY: self.root points to an inbounds allocation
        unsafe { (&raw mut (*self.root).ptr).cast() }
    }

    /// Safety: GC must not run during the lifetime of the returned reference.
    pub unsafe fn as_mut<'b>(&'b mut self) -> &'b mut T
    where
        'a: 'b,
    {
        &mut *(self.as_ptr())
    }

    pub fn get(&self) -> T
    where
        T: Copy,
    {
        // SAFETY: The rooted value is initialized as long as we exist
        unsafe { (*self.root).ptr.assume_init() }
    }

    pub fn set(&mut self, v: T) {
        // SAFETY: The rooted value is initialized as long as we exist
        unsafe {
            // Make sure the drop impl for T is called
            (*self.root).ptr.assume_init_drop();
            (*self.root).ptr.write(v);
        }
    }
}

impl<'a, T> RootedGuard<'a, Option<T>>
where
    Option<T>: RootKind,
{
    pub fn take(&mut self) -> Option<T> {
        // Safety: No GC occurs during take call
        unsafe { self.as_mut().take() }
    }
}

impl<'a, T: 'a + RootKind> Deref for RootedGuard<'a, T> {
    type Target = T;
    fn deref(&self) -> &T {
        // SAFETY: The rooted value is initialized as long as we exist
        unsafe { (*self.root).ptr.assume_init_ref() }
    }
}

impl<'a, T: 'a + RootKind> Drop for RootedGuard<'a, T> {
    fn drop(&mut self) {
        // SAFETY: The rooted value is initialized as long as we exist
        unsafe {
            // Make sure the drop impl for T is called
            (*self.root).ptr.assume_init_drop();
            (*self.root).ptr = MaybeUninit::zeroed();
        }

        unsafe {
            (*self.root).remove_from_root_stack();
        }
    }
}

impl<'a, const N: usize> From<&RootedGuard<'a, ValueArray<N>>> for JS::HandleValueArray {
    fn from(array: &RootedGuard<'a, ValueArray<N>>) -> JS::HandleValueArray {
        JS::HandleValueArray::from(unsafe { &*array.root })
    }
}

pub struct Handle<'a, T: 'a> {
    pub(crate) ptr: &'a T,
}

impl<T> Clone for Handle<'_, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for Handle<'_, T> {}

#[cfg_attr(
    feature = "crown",
    crown::unrooted_must_root_lint::allow_unrooted_interior
)]
pub struct MutableHandle<'a, T: 'a> {
    pub(crate) ptr: *mut T,
    anchor: PhantomData<&'a mut T>,
}

pub type HandleFunction<'a> = Handle<'a, *mut JSFunction>;
pub type HandleId<'a> = Handle<'a, jsid>;
pub type HandleObject<'a> = Handle<'a, *mut JSObject>;
pub type HandleScript<'a> = Handle<'a, *mut JSScript>;
pub type HandleString<'a> = Handle<'a, *mut JSString>;
pub type HandleSymbol<'a> = Handle<'a, *mut Symbol>;
pub type HandleValue<'a> = Handle<'a, Value>;

pub type MutableHandleFunction<'a> = MutableHandle<'a, *mut JSFunction>;
pub type MutableHandleId<'a> = MutableHandle<'a, jsid>;
pub type MutableHandleObject<'a> = MutableHandle<'a, *mut JSObject>;
pub type MutableHandleScript<'a> = MutableHandle<'a, *mut JSScript>;
pub type MutableHandleString<'a> = MutableHandle<'a, *mut JSString>;
pub type MutableHandleSymbol<'a> = MutableHandle<'a, *mut Symbol>;
pub type MutableHandleValue<'a> = MutableHandle<'a, Value>;

impl<'a, T> Handle<'a, T> {
    pub fn get(&self) -> T
    where
        T: Copy,
    {
        *self.ptr
    }

    pub(crate) fn new(ptr: &'a T) -> Self {
        Handle { ptr }
    }

    pub unsafe fn from_marked_location(ptr: *const T) -> Self {
        Handle::new(&*ptr)
    }

    pub unsafe fn from_raw(handle: RawHandle<T>) -> Self {
        Handle::from_marked_location(handle.ptr)
    }
}

impl<'a, T> IntoRawHandle for Handle<'a, T> {
    type Target = T;
    fn into_handle(self) -> RawHandle<T> {
        unsafe { RawHandle::from_marked_location(self.ptr) }
    }
}

impl<'a, T> IntoRawHandle for MutableHandle<'a, T> {
    type Target = T;
    fn into_handle(self) -> RawHandle<T> {
        unsafe { RawHandle::from_marked_location(self.ptr) }
    }
}

impl<'a, T> IntoRawMutableHandle for MutableHandle<'a, T> {
    fn into_handle_mut(self) -> RawMutableHandle<T> {
        unsafe { RawMutableHandle::from_marked_location(self.ptr) }
    }
}

impl<'a, T> Deref for Handle<'a, T> {
    type Target = T;

    fn deref(&self) -> &T {
        self.ptr
    }
}

impl<'a, T> MutableHandle<'a, T> {
    pub unsafe fn from_marked_location(ptr: *mut T) -> Self {
        MutableHandle::new(&mut *ptr)
    }

    pub unsafe fn from_raw(handle: RawMutableHandle<T>) -> Self {
        MutableHandle::from_marked_location(handle.ptr)
    }

    pub fn handle(&self) -> Handle<T> {
        unsafe { Handle::new(&*self.ptr) }
    }

    pub(crate) fn new(ptr: &'a mut T) -> Self {
        Self {
            ptr,
            anchor: PhantomData,
        }
    }

    pub fn get(&self) -> T
    where
        T: Copy,
    {
        unsafe { *self.ptr }
    }

    pub fn set(&mut self, v: T)
    where
        T: Copy,
    {
        unsafe { *self.ptr = v }
    }

    /// Safety: GC must not run during the lifetime of the returned reference.
    pub unsafe fn as_mut<'b>(&'b mut self) -> &'b mut T
    where
        'a: 'b,
    {
        &mut *(self.ptr)
    }

    /// Creates a copy of this object, with a shorter lifetime, that holds a
    /// mutable borrow on the original object. When you write code that wants
    /// to use a `MutableHandle` more than once, you will typically need to
    /// call `reborrow` on all but the last usage. The same way that you might
    /// naively clone a type to allow it to be passed to multiple functions.
    ///
    /// This is the same thing that happens with regular mutable references,
    /// except there the compiler implicitly inserts the reborrow calls. Until
    /// rust gains a feature to implicitly reborrow other types, we have to do
    /// it by hand.
    pub fn reborrow<'b>(&'b mut self) -> MutableHandle<'b, T>
    where
        'a: 'b,
    {
        MutableHandle {
            ptr: self.ptr,
            anchor: PhantomData,
        }
    }

    pub(crate) fn raw(&mut self) -> RawMutableHandle<T> {
        unsafe { RawMutableHandle::from_marked_location(self.ptr) }
    }
}

impl<'a, T> MutableHandle<'a, Option<T>> {
    pub fn take(&mut self) -> Option<T> {
        // Safety: No GC occurs during take call
        unsafe { self.as_mut().take() }
    }
}

impl<'a, T> Deref for MutableHandle<'a, T> {
    type Target = T;

    fn deref(&self) -> &T {
        unsafe { &*self.ptr }
    }
}

impl HandleValue<'static> {
    pub fn null() -> Self {
        unsafe { Self::from_raw(RawHandleValue::null()) }
    }

    pub fn undefined() -> Self {
        unsafe { Self::from_raw(RawHandleValue::undefined()) }
    }
}

const ConstNullValue: *mut JSObject = ptr::null_mut();

impl<'a> HandleObject<'a> {
    pub fn null() -> Self {
        unsafe { HandleObject::from_marked_location(&ConstNullValue) }
    }
}