script_bindings/
reflector.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;
6
7use js::jsapi::{AddAssociatedMemory, Heap, JSObject, MemoryUse, RemoveAssociatedMemory};
8use js::rust::HandleObject;
9use malloc_size_of_derive::MallocSizeOf;
10
11use crate::interfaces::GlobalScopeHelpers;
12use crate::iterable::{Iterable, IterableIterator};
13use crate::realms::InRealm;
14use crate::root::{Dom, DomRoot, Root};
15use crate::{DomTypes, JSTraceable};
16
17pub trait AssociatedMemorySize: Default {
18    fn size(&self) -> usize;
19}
20
21impl AssociatedMemorySize for () {
22    fn size(&self) -> usize {
23        0
24    }
25}
26
27#[derive(Default, MallocSizeOf)]
28pub struct AssociatedMemory(Cell<usize>);
29
30impl AssociatedMemorySize for AssociatedMemory {
31    fn size(&self) -> usize {
32        self.0.get()
33    }
34}
35
36/// A struct to store a reference to the reflector of a DOM object.
37#[derive(MallocSizeOf)]
38#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
39// If you're renaming or moving this field, update the path in plugins::reflector as well
40pub struct Reflector<T = ()> {
41    #[ignore_malloc_size_of = "defined and measured in rust-mozjs"]
42    object: Heap<*mut JSObject>,
43    /// Associated memory size (of rust side). Used for memory reporting to SM.
44    size: T,
45}
46
47unsafe impl<T> js::gc::Traceable for Reflector<T> {
48    unsafe fn trace(&self, _: *mut js::jsapi::JSTracer) {}
49}
50
51impl<T> PartialEq for Reflector<T> {
52    fn eq(&self, other: &Reflector<T>) -> bool {
53        self.object.get() == other.object.get()
54    }
55}
56
57impl<T> Reflector<T> {
58    /// Get the reflector.
59    #[inline]
60    pub fn get_jsobject(&self) -> HandleObject<'_> {
61        // We're rooted, so it's safe to hand out a handle to object in Heap
62        unsafe { HandleObject::from_raw(self.object.handle()) }
63    }
64
65    /// Initialize the reflector. (May be called only once.)
66    ///
67    /// # Safety
68    ///
69    /// The provided [`JSObject`] pointer must point to a valid [`JSObject`].
70    unsafe fn set_jsobject(&self, object: *mut JSObject) {
71        assert!(self.object.get().is_null());
72        assert!(!object.is_null());
73        self.object.set(object);
74    }
75
76    /// Return a pointer to the memory location at which the JS reflector
77    /// object is stored. Used to root the reflector, as
78    /// required by the JSAPI rooting APIs.
79    pub fn rootable(&self) -> &Heap<*mut JSObject> {
80        &self.object
81    }
82}
83
84impl<T: AssociatedMemorySize> Reflector<T> {
85    /// Create an uninitialized `Reflector`.
86    // These are used by the bindings and do not need `default()` functions.
87    #[expect(clippy::new_without_default)]
88    pub fn new() -> Reflector<T> {
89        Reflector {
90            object: Heap::default(),
91            size: T::default(),
92        }
93    }
94
95    pub fn rust_size<D>(&self, _: &D) -> usize {
96        size_of::<D>() + size_of::<Box<D>>() + self.size.size()
97    }
98
99    /// This function should be called from finalize of the DOM objects
100    pub fn drop_memory<D>(&self, d: &D) {
101        unsafe {
102            RemoveAssociatedMemory(self.object.get(), self.rust_size(d), MemoryUse::DOMBinding);
103        }
104    }
105}
106
107impl Reflector<AssociatedMemory> {
108    /// Update the associated memory size.
109    pub fn update_memory_size<D>(&self, d: &D, new_size: usize) {
110        if self.size.size() == new_size {
111            return;
112        }
113        unsafe {
114            RemoveAssociatedMemory(self.object.get(), self.rust_size(d), MemoryUse::DOMBinding);
115            self.size.0.set(new_size);
116            AddAssociatedMemory(self.object.get(), self.rust_size(d), MemoryUse::DOMBinding);
117        }
118    }
119}
120
121/// A trait to provide access to the `Reflector` for a DOM object.
122pub trait DomObject: js::gc::Traceable + 'static {
123    type ReflectorType: AssociatedMemorySize;
124    /// Returns the receiver's reflector.
125    fn reflector(&self) -> &Reflector<Self::ReflectorType>;
126}
127
128impl DomObject for Reflector<()> {
129    type ReflectorType = ();
130
131    fn reflector(&self) -> &Reflector<Self::ReflectorType> {
132        self
133    }
134}
135
136impl DomObject for Reflector<AssociatedMemory> {
137    type ReflectorType = AssociatedMemory;
138
139    fn reflector(&self) -> &Reflector<Self::ReflectorType> {
140        self
141    }
142}
143
144/// A trait to initialize the `Reflector` for a DOM object.
145pub trait MutDomObject: DomObject {
146    /// Initializes the Reflector
147    ///
148    /// # Safety
149    ///
150    /// The provided [`JSObject`] pointer must point to a valid [`JSObject`].
151    unsafe fn init_reflector<D>(&self, obj: *mut JSObject);
152}
153
154impl MutDomObject for Reflector<()> {
155    unsafe fn init_reflector<D>(&self, obj: *mut JSObject) {
156        unsafe {
157            js::jsapi::AddAssociatedMemory(
158                obj,
159                size_of::<D>() + size_of::<Box<D>>(),
160                MemoryUse::DOMBinding,
161            );
162            self.set_jsobject(obj);
163        }
164    }
165}
166
167impl MutDomObject for Reflector<AssociatedMemory> {
168    unsafe fn init_reflector<D>(&self, obj: *mut JSObject) {
169        unsafe {
170            js::jsapi::AddAssociatedMemory(
171                obj,
172                size_of::<D>() + size_of::<Box<D>>(),
173                MemoryUse::DOMBinding,
174            );
175            self.set_jsobject(obj);
176        }
177    }
178}
179
180pub trait DomGlobalGeneric<D: DomTypes>: DomObject {
181    /// Returns the [`GlobalScope`] of the realm that the [`DomObject`] was created in.  If this
182    /// object is a `Node`, this will be different from it's owning `Document` if adopted by. For
183    /// `Node`s it's almost always better to use `NodeTraits::owning_global`.
184    fn global_(&self, realm: InRealm) -> DomRoot<D::GlobalScope>
185    where
186        Self: Sized,
187    {
188        D::GlobalScope::from_reflector(self, realm)
189    }
190}
191
192impl<D: DomTypes, T: DomObject> DomGlobalGeneric<D> for T {}
193
194/// A trait to provide a function pointer to wrap function for DOM objects.
195pub trait DomObjectWrap<D: DomTypes>: Sized + DomObject + DomGlobalGeneric<D> {
196    /// Function pointer to the general wrap function type
197    #[expect(clippy::type_complexity)]
198    const WRAP: unsafe fn(
199        &mut js::context::JSContext,
200        &D::GlobalScope,
201        Option<HandleObject>,
202        Box<Self>,
203    ) -> Root<Dom<Self>>;
204}
205
206/// A trait to provide a function pointer to wrap function for
207/// DOM iterator interfaces.
208pub trait DomObjectIteratorWrap<D: DomTypes>: DomObjectWrap<D> + JSTraceable + Iterable {
209    /// Function pointer to the wrap function for `IterableIterator<T>`
210    #[expect(clippy::type_complexity)]
211    const ITER_WRAP: unsafe fn(
212        &mut js::context::JSContext,
213        &D::GlobalScope,
214        Option<HandleObject>,
215        Box<IterableIterator<D, Self>>,
216    ) -> Root<Dom<IterableIterator<D, Self>>>;
217}