1use std::cell::UnsafeCell;
6use std::hash::{Hash, Hasher};
7use std::ops::Deref;
8use std::rc::Rc;
9use std::{fmt, mem, ptr};
10
11use js::context::NoGC;
12use js::gc::{Handle, Traceable as JSTraceable};
13use js::jsapi::{Heap, JSObject, JSTracer};
14use js::rust::GCMethods;
15use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
16
17use crate::assert::assert_in_script;
18use crate::conversions::DerivedFrom;
19use crate::dom::UnrootedDom;
20use crate::inheritance::Castable;
21use crate::reflector::{DomObject, HasPrototype, MutDomObject, PrototypeInitializer};
22use crate::trace::trace_reflector;
23
24#[cfg_attr(crown, crown::unrooted_must_root_lint::allow_unrooted_interior)]
26pub struct Root<T: StableTraceObject> {
27 value: T,
29 root_list: *const RootCollection,
31}
32
33impl<T> Root<T>
34where
35 T: StableTraceObject + 'static,
36{
37 pub unsafe fn new(value: T) -> Self {
43 unsafe fn add_to_root_list(object: *const dyn JSTraceable) -> *const RootCollection {
44 assert_in_script();
45 STACK_ROOTS.with(|root_list| {
46 unsafe { root_list.root(object) };
47 root_list as *const _
48 })
49 }
50
51 let root_list = unsafe { add_to_root_list(value.stable_trace_object()) };
52 Root { value, root_list }
53 }
54}
55
56pub unsafe trait StableTraceObject {
67 fn stable_trace_object(&self) -> *const dyn JSTraceable;
70}
71
72unsafe impl<T> StableTraceObject for Dom<T>
73where
74 T: DomObject,
75{
76 fn stable_trace_object(&self) -> *const dyn JSTraceable {
77 self.reflector()
78 }
79}
80
81unsafe impl<T> StableTraceObject for MaybeUnreflectedDom<T>
82where
83 T: DomObject,
84{
85 fn stable_trace_object(&self) -> *const dyn JSTraceable {
86 #[repr(transparent)]
92 struct MaybeUnreflectedStackRoot<T>(T);
93 unsafe impl<T> JSTraceable for MaybeUnreflectedStackRoot<T>
94 where
95 T: DomObject,
96 {
97 unsafe fn trace(&self, tracer: *mut JSTracer) {
98 if self.0.reflector().get_jsobject().is_null() {
99 unsafe { self.0.trace(tracer) };
100 } else {
101 unsafe { self.0.reflector().trace(tracer) }
102 }
103 }
104 }
105 unsafe { &*(self.ptr.as_ptr() as *const T as *const MaybeUnreflectedStackRoot<T>) }
106 }
107}
108
109impl<T> Deref for Root<T>
110where
111 T: Deref + StableTraceObject,
112{
113 type Target = <T as Deref>::Target;
114
115 fn deref(&self) -> &Self::Target {
116 assert_in_script();
117 &self.value
118 }
119}
120
121impl<T> Drop for Root<T>
122where
123 T: StableTraceObject,
124{
125 fn drop(&mut self) {
126 unsafe {
127 (*self.root_list).unroot(self.value.stable_trace_object());
128 }
129 }
130}
131
132impl<T: fmt::Debug + StableTraceObject> fmt::Debug for Root<T> {
133 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
134 self.value.fmt(f)
135 }
136}
137
138impl<T: fmt::Debug + DomObject> fmt::Debug for Dom<T> {
139 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
140 (**self).fmt(f)
141 }
142}
143
144#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
152#[repr(transparent)]
153pub struct Dom<T> {
154 ptr: ptr::NonNull<T>,
155}
156
157impl<T> MallocSizeOf for Dom<T> {
160 fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
161 0
162 }
163}
164
165impl<T> PartialEq for Dom<T> {
167 fn eq(&self, other: &Dom<T>) -> bool {
168 self.ptr.as_ptr() == other.ptr.as_ptr()
169 }
170}
171
172impl<'a, T: DomObject> PartialEq<&'a T> for Dom<T> {
174 fn eq(&self, other: &&'a T) -> bool {
175 *self == Dom::from_ref(*other)
176 }
177}
178
179impl<T> Eq for Dom<T> {}
180
181impl<T> Hash for Dom<T> {
183 fn hash<H: Hasher>(&self, state: &mut H) {
184 self.ptr.as_ptr().hash(state)
185 }
186}
187
188impl<T> Clone for Dom<T> {
189 #[inline]
190 fn clone(&self) -> Self {
191 assert_in_script();
192 Dom { ptr: self.ptr }
193 }
194}
195
196impl<T: DomObject> Dom<T> {
197 pub fn from_ref(obj: &T) -> Dom<T> {
199 assert_in_script();
200 Dom {
201 ptr: ptr::NonNull::from(obj),
202 }
203 }
204
205 pub fn as_rooted(&self) -> DomRoot<T> {
207 DomRoot::from_ref(self)
208 }
209
210 pub fn as_unrooted<'no_gc>(&self, no_gc: &'no_gc NoGC) -> UnrootedDom<'no_gc, T> {
213 UnrootedDom::from_dom(self.clone(), no_gc)
214 }
215
216 pub fn as_ptr(&self) -> *const T {
217 self.ptr.as_ptr()
218 }
219}
220
221impl<T: DomObject> Deref for Dom<T> {
222 type Target = T;
223
224 fn deref(&self) -> &T {
225 assert_in_script();
226 unsafe { &*self.ptr.as_ptr() }
229 }
230}
231
232unsafe impl<T: DomObject> JSTraceable for Dom<T> {
233 unsafe fn trace(&self, tracer: *mut JSTracer) {
234 let trace_info = if cfg!(debug_assertions) {
235 std::any::type_name::<T>()
236 } else {
237 "DOM object on heap"
238 };
239 unsafe {
240 trace_reflector(tracer, trace_info, (*self.ptr.as_ptr()).reflector());
241 }
242 }
243}
244
245#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
247pub struct MaybeUnreflectedDom<T> {
248 ptr: ptr::NonNull<T>,
249}
250
251impl<T> MaybeUnreflectedDom<T>
252where
253 T: DomObject + PrototypeInitializer + HasPrototype,
254{
255 pub fn from_box(mut value: Box<T>) -> Self {
257 value.set_proto_id(T::PROTOTYPE_ID);
258 Self {
259 ptr: Box::leak(value).into(),
260 }
261 }
262
263 pub fn from_rc(mut value: Rc<T>) -> Self {
265 Rc::get_mut(&mut value)
266 .expect("Could not set reflector")
267 .set_proto_id(T::PROTOTYPE_ID);
268 Self {
269 ptr: ptr::NonNull::new(Rc::into_raw(value) as *mut T).unwrap(),
270 }
271 }
272}
273
274impl<T> Root<MaybeUnreflectedDom<T>>
275where
276 T: DomObject,
277{
278 pub fn as_ptr(&self) -> *const T {
279 self.value.ptr.as_ptr()
280 }
281}
282
283impl<T> Root<MaybeUnreflectedDom<T>>
284where
285 T: MutDomObject,
286{
287 pub unsafe fn reflect_with(self, obj: *mut JSObject) -> DomRoot<T> {
292 let ptr = self.as_ptr();
293 drop(self);
294 let root = DomRoot::from_ref(unsafe { &*ptr });
295 unsafe { root.init_reflector::<T>(obj) };
296 root
297 }
298}
299
300pub type DomRoot<T> = Root<Dom<T>>;
302
303impl<T: Castable> DomRoot<T> {
304 pub fn upcast<U>(root: DomRoot<T>) -> DomRoot<U>
306 where
307 U: Castable,
308 T: DerivedFrom<U>,
309 {
310 unsafe { mem::transmute::<DomRoot<T>, DomRoot<U>>(root) }
311 }
312
313 pub fn downcast<U>(root: DomRoot<T>) -> Option<DomRoot<U>>
315 where
316 U: DerivedFrom<T>,
317 {
318 if root.is::<U>() {
319 Some(unsafe { mem::transmute::<DomRoot<T>, DomRoot<U>>(root) })
320 } else {
321 None
322 }
323 }
324}
325
326impl<T: DomObject> DomRoot<T> {
327 pub fn from_ref(unrooted: &T) -> DomRoot<T> {
329 unsafe { DomRoot::new(Dom::from_ref(unrooted)) }
330 }
331
332 pub fn as_traced(&self) -> Dom<T> {
339 Dom::from_ref(self)
340 }
341
342 pub fn as_unrooted<'no_gc>(&self, no_gc: &'no_gc NoGC) -> UnrootedDom<'no_gc, T> {
345 self.value.as_unrooted(no_gc)
346 }
347}
348
349impl<T> MallocSizeOf for DomRoot<T>
350where
351 T: DomObject + MallocSizeOf,
352{
353 fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
354 0
355 }
356}
357
358impl<T> PartialEq for DomRoot<T>
359where
360 T: DomObject,
361{
362 fn eq(&self, other: &Self) -> bool {
363 self.value == other.value
364 }
365}
366
367impl<T: DomObject> Eq for DomRoot<T> {}
368
369impl<T: DomObject> Hash for DomRoot<T> {
370 fn hash<H: Hasher>(&self, state: &mut H) {
371 self.value.hash(state);
372 }
373}
374
375impl<T> Clone for DomRoot<T>
376where
377 T: DomObject,
378{
379 fn clone(&self) -> DomRoot<T> {
380 DomRoot::from_ref(self)
381 }
382}
383
384unsafe impl<T> JSTraceable for DomRoot<T>
385where
386 T: DomObject,
387{
388 unsafe fn trace(&self, _: *mut JSTracer) {
389 }
391}
392
393pub struct RootCollection {
400 roots: UnsafeCell<Vec<*const dyn JSTraceable>>,
401}
402
403impl RootCollection {
404 #[expect(clippy::new_without_default)]
406 pub fn new() -> RootCollection {
407 RootCollection {
408 roots: UnsafeCell::new(Vec::with_capacity(256)),
409 }
410 }
411
412 unsafe fn root(&self, object: *const dyn JSTraceable) {
414 assert_in_script();
415 unsafe { (*self.roots.get()).push(object) };
416 }
417
418 unsafe fn unroot(&self, object: *const dyn JSTraceable) {
420 assert_in_script();
421 let roots = unsafe { &mut *self.roots.get() };
422 match roots
423 .iter()
424 .rposition(|r| std::ptr::addr_eq(*r as *const (), object as *const ()))
425 {
426 Some(idx) => {
427 unsafe {
431 let len = roots.len() - 1;
432 if len != idx {
433 let base_ptr = roots.as_mut_ptr();
434 ptr::copy_nonoverlapping(base_ptr.add(len), base_ptr.add(idx), 1);
435 }
436 roots.set_len(len);
437 }
438 },
439 None => panic!("Can't remove a root that was never rooted!"),
440 }
441 }
442}
443
444thread_local!(static STACK_ROOTS: RootCollection = RootCollection::new());
445
446pub unsafe fn trace_roots(tracer: *mut JSTracer) {
451 trace!("tracing stack roots");
452 STACK_ROOTS.with(|collection| {
453 let collection = unsafe { &*collection.roots.get() };
454 for root in collection {
455 unsafe {
456 (**root).trace(tracer);
457 }
458 }
459 });
460}
461
462pub trait DomSlice<T>
464where
465 T: JSTraceable + DomObject,
466{
467 fn as_ref_slice(&self) -> &[&T];
469}
470
471impl<T> DomSlice<T> for [Dom<T>]
472where
473 T: JSTraceable + DomObject,
474{
475 #[inline]
476 fn as_ref_slice(&self) -> &[&T] {
477 let _ = mem::transmute::<Dom<T>, &T>;
478 unsafe { &*(self as *const [Dom<T>] as *const [&T]) }
479 }
480}
481
482pub fn rooted_heap_handle<'a, T: DomObject, U: GCMethods + Copy>(
487 object: &'a T,
488 f: impl Fn(&'a T) -> &'a Heap<U>,
489) -> Handle<'a, U> {
490 unsafe { Handle::from_raw(f(object).handle()) }
494}