Skip to main content

rquickjs_core/
class.rs

1//! JavaScript classes defined from Rust.
2
3use crate::{
4    function::Params,
5    qjs::{self},
6    value::Constructor,
7    Atom, Ctx, Error, FromJs, IntoJs, JsLifetime, Object, Result, Value,
8};
9use alloc::boxed::Box;
10use alloc::vec::Vec;
11use core::{hash::Hash, marker::PhantomData, mem, ops::Deref, ptr::NonNull};
12
13mod cell;
14mod trace;
15
16pub(crate) mod ffi;
17
18pub use cell::{
19    Borrow, BorrowMut, JsCell, Mutability, OwnedBorrow, OwnedBorrowMut, Readable, Writable,
20};
21use ffi::{ClassCell, VTable};
22pub use trace::{Trace, Tracer};
23#[doc(hidden)]
24pub mod impl_;
25
26#[cfg(test)]
27mod test;
28
29/// The kind of a JavaScript class.
30///
31/// A class can't be both callable and exotic, so this enum encodes that constraint.
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum ClassKind {
34    /// A regular class.
35    Plain,
36    /// A callable class (i.e. can be used as a function).
37    Callable,
38    /// An exotic class (i.e. has custom property access behavior).
39    Exotic,
40}
41
42/// A JavaScript property descriptor returned from [`JsClass::exotic_get_own_property`].
43pub struct PropertyDescriptor<'js> {
44    /// The property value (for data descriptors).
45    pub value: Value<'js>,
46    /// The getter function (for accessor descriptors).
47    pub getter: Value<'js>,
48    /// The setter function (for accessor descriptors).
49    pub setter: Value<'js>,
50    /// Whether the property is configurable.
51    pub configurable: bool,
52    /// Whether the property is enumerable.
53    pub enumerable: bool,
54    /// Whether the property is writable (data descriptors only).
55    pub writable: bool,
56    /// Whether this is a getter/setter descriptor.
57    pub is_getset: bool,
58}
59
60impl<'js> PropertyDescriptor<'js> {
61    /// Create a simple value property descriptor.
62    pub fn new_value(
63        value: Value<'js>,
64        configurable: bool,
65        enumerable: bool,
66        writable: bool,
67    ) -> Self {
68        let ctx = value.ctx().clone();
69        PropertyDescriptor {
70            value,
71            getter: Value::new_undefined(ctx.clone()),
72            setter: Value::new_undefined(ctx),
73            configurable,
74            enumerable,
75            writable,
76            is_getset: false,
77        }
78    }
79}
80
81/// A property name entry returned from [`JsClass::exotic_get_own_property_names`].
82pub struct PropertyName<'js> {
83    /// The atom identifying the property.
84    pub atom: Atom<'js>,
85    /// Whether this property is enumerable.
86    pub is_enumerable: bool,
87}
88
89/// The trait which allows Rust types to be used from JavaScript.
90pub trait JsClass<'js>: Trace<'js> + JsLifetime<'js> + Sized {
91    /// The name the constructor has in JavaScript
92    const NAME: &'static str;
93
94    /// The kind of this class (plain, callable, or exotic).
95    const KIND: ClassKind = ClassKind::Plain;
96
97    /// Can the type be mutated while a JavaScript value.
98    ///
99    /// This should either be [`Readable`] or [`Writable`].
100    type Mutable: Mutability;
101
102    /// Returns the class prototype,
103    fn prototype(ctx: &Ctx<'js>) -> Result<Option<Object<'js>>> {
104        Object::new(ctx.clone()).map(Some)
105    }
106
107    /// Returns a predefined constructor for this specific class type if there is one.
108    fn constructor(ctx: &Ctx<'js>) -> Result<Option<Constructor<'js>>>;
109
110    /// The function which will be called if [`Self::KIND`] is [`ClassKind::Callable`] and an object with this
111    /// class is called as if it is a function.
112    fn call<'a>(this: &JsCell<'js, Self>, params: Params<'a, 'js>) -> Result<Value<'js>> {
113        let _ = this;
114        Ok(Value::new_undefined(params.ctx().clone()))
115    }
116
117    /// The function which will be called if a get property is performed on an object with this class
118    fn exotic_get_property(
119        this: &JsCell<'js, Self>,
120        ctx: &Ctx<'js>,
121        _atom: Atom<'js>,
122        _receiver: Value<'js>,
123    ) -> Result<Value<'js>> {
124        let _ = this;
125        Ok(Value::new_undefined(ctx.clone()))
126    }
127
128    /// The function which will be called if a set property is performed on an object with this class
129    fn exotic_set_property(
130        this: &JsCell<'js, Self>,
131        _ctx: &Ctx<'js>,
132        _atom: Atom<'js>,
133        _receiver: Value<'js>,
134        _value: Value<'js>,
135    ) -> Result<bool> {
136        let _ = this;
137        Ok(false)
138    }
139
140    /// The function which will be called if a delete property is performed on an object with this class
141    fn exotic_delete_property(
142        this: &JsCell<'js, Self>,
143        _ctx: &Ctx<'js>,
144        _atom: Atom<'js>,
145    ) -> Result<bool> {
146        let _ = this;
147        Ok(false)
148    }
149
150    /// The function which will be called if has property or similar is called on an object with this class
151    fn exotic_has_property(
152        this: &JsCell<'js, Self>,
153        _ctx: &Ctx<'js>,
154        _atom: Atom<'js>,
155    ) -> Result<bool> {
156        let _ = this;
157        Ok(false)
158    }
159
160    /// Called to get the own property descriptor for a given property name.
161    ///
162    /// Return `Ok(Some(descriptor))` if the property exists, `Ok(None)` if it doesn't.
163    fn exotic_get_own_property(
164        this: &JsCell<'js, Self>,
165        _ctx: &Ctx<'js>,
166        _atom: Atom<'js>,
167    ) -> Result<Option<PropertyDescriptor<'js>>> {
168        let _ = this;
169        Ok(None)
170    }
171
172    /// Called to enumerate the own property names of this object.
173    ///
174    /// Return a list of property names.
175    fn exotic_get_own_property_names(
176        this: &JsCell<'js, Self>,
177        _ctx: &Ctx<'js>,
178    ) -> Result<Vec<PropertyName<'js>>> {
179        let _ = this;
180        Ok(Vec::new())
181    }
182}
183
184/// A object which is instance of a Rust class.
185#[repr(transparent)]
186pub struct Class<'js, C: JsClass<'js>>(pub(crate) Object<'js>, PhantomData<C>);
187
188impl<'js, C: JsClass<'js>> Clone for Class<'js, C> {
189    fn clone(&self) -> Self {
190        Class(self.0.clone(), PhantomData)
191    }
192}
193
194impl<'js, C: JsClass<'js>> PartialEq for Class<'js, C> {
195    fn eq(&self, other: &Self) -> bool {
196        self.0 == other.0
197    }
198}
199
200impl<'js, C: JsClass<'js>> Eq for Class<'js, C> {}
201
202impl<'js, C: JsClass<'js>> Hash for Class<'js, C> {
203    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
204        self.0.hash(state)
205    }
206}
207
208unsafe impl<'js, C> JsLifetime<'js> for Class<'js, C>
209where
210    C: JsClass<'js> + JsLifetime<'js>,
211    for<'to> C::Changed<'to>: JsClass<'to>,
212{
213    type Changed<'to> = Class<'to, C::Changed<'to>>;
214}
215
216impl<'js, C: JsClass<'js>> Deref for Class<'js, C> {
217    type Target = Object<'js>;
218
219    fn deref(&self) -> &Self::Target {
220        &self.0
221    }
222}
223
224impl<'js, C: JsClass<'js>> Class<'js, C> {
225    /// Create a class from a Rust object.
226    pub fn instance(ctx: Ctx<'js>, value: C) -> Result<Class<'js, C>> {
227        let id = unsafe { class_id::<C>(&ctx)? };
228
229        let prototype = Self::prototype(&ctx)?;
230
231        let prototype = prototype.map(|x| x.as_js_value()).unwrap_or(qjs::JS_NULL);
232        let val = unsafe {
233            ctx.handle_exception(qjs::JS_NewObjectProtoClass(ctx.as_ptr(), prototype, id))?
234        };
235
236        let ptr = Box::into_raw(Box::new(ClassCell::new(value)));
237        unsafe { qjs::JS_SetOpaque(val, ptr.cast()) };
238        Ok(Self(
239            unsafe { Object::from_js_value(ctx, val) },
240            PhantomData,
241        ))
242    }
243
244    /// Create a class from a Rust object with a given prototype.
245    pub fn instance_proto(value: C, proto: Object<'js>) -> Result<Class<'js, C>> {
246        let id = unsafe { class_id::<C>(proto.ctx())? };
247
248        let val = unsafe {
249            proto.ctx.handle_exception(qjs::JS_NewObjectProtoClass(
250                proto.ctx().as_ptr(),
251                proto.0.as_js_value(),
252                id,
253            ))?
254        };
255        let ptr = Box::into_raw(Box::new(ClassCell::new(value)));
256        unsafe { qjs::JS_SetOpaque(val, ptr.cast()) };
257        Ok(Self(
258            unsafe { Object::from_js_value(proto.ctx.clone(), val) },
259            PhantomData,
260        ))
261    }
262
263    /// Returns the prototype for the class.
264    ///
265    /// Returns `None` if the class is not yet registered or if the class doesn't have a prototype.
266    pub fn prototype(ctx: &Ctx<'js>) -> Result<Option<Object<'js>>> {
267        unsafe { ctx.get_context_opaque().get_or_insert_prototype::<C>(ctx) }
268    }
269
270    /// Create a constructor for the current class using its definition.
271    pub fn create_constructor(ctx: &Ctx<'js>) -> Result<Option<Constructor<'js>>> {
272        C::constructor(ctx)
273    }
274
275    /// Defines the predefined constructor of this class, if there is one, onto the given object.
276    pub fn define(object: &Object<'js>) -> Result<()> {
277        if let Some(constructor) = Self::create_constructor(object.ctx())? {
278            object.set(C::NAME, constructor)?;
279        }
280        Ok(())
281    }
282
283    /// Returns a reference to the underlying object contained in a cell.
284    #[inline]
285    pub(crate) fn get_class_cell<'a>(&'a self) -> &'a ClassCell<JsCell<'js, C>> {
286        unsafe { self.get_class_ptr().as_ref() }
287    }
288
289    /// Returns a reference to the underlying object contained in a cell.
290    #[inline]
291    pub fn get_cell<'a>(&'a self) -> &'a JsCell<'js, C> {
292        &self.get_class_cell().data
293    }
294
295    /// Borrow the Rust class type.
296    ///
297    /// JavaScript classes behave similar to [`Rc`](std::rc::Rc) in Rust, you can essentially think
298    /// of a class object as a `Rc<RefCell<C>>` and with similar borrowing functionality.
299    ///
300    /// # Panic
301    /// This function panics if the class is already borrowed mutably.
302    #[inline]
303    pub fn borrow<'a>(&'a self) -> Borrow<'a, 'js, C> {
304        self.get_cell().borrow()
305    }
306
307    /// Borrow the Rust class type mutably.
308    ///
309    /// JavaScript classes behave similar to [`Rc`](std::rc::Rc) in Rust, you can essentially think
310    /// of a class object as a `Rc<RefCell<C>>` and with similar borrowing functionality.
311    ///
312    /// # Panic
313    /// This function panics if the class is already borrowed mutably or immutably, or the Class
314    /// can't be borrowed mutably.
315    #[inline]
316    pub fn borrow_mut<'a>(&'a self) -> BorrowMut<'a, 'js, C> {
317        self.get_cell().borrow_mut()
318    }
319
320    /// Try to borrow the Rust class type.
321    ///
322    /// JavaScript classes behave similar to [`Rc`](std::rc::Rc) in Rust, you can essentially think
323    /// of a class object as a `Rc<RefCell<C>>` and with similar borrowing functionality.
324    ///
325    /// This returns an error when the class is already borrowed mutably.
326    #[inline]
327    pub fn try_borrow<'a>(&'a self) -> Result<Borrow<'a, 'js, C>> {
328        self.get_cell().try_borrow().map_err(Error::ClassBorrow)
329    }
330
331    /// Try to borrow the Rust class type mutably.
332    ///
333    /// JavaScript classes behave similar to [`Rc`](std::rc::Rc) in Rust, you can essentially think
334    /// of a class object as a `Rc<RefCell<C>>` and with similar borrowing functionality.
335    ///
336    /// This returns an error when the class is already borrowed mutably, immutably or the class
337    /// can't be borrowed mutably.
338    #[inline]
339    pub fn try_borrow_mut<'a>(&'a self) -> Result<BorrowMut<'a, 'js, C>> {
340        self.get_cell().try_borrow_mut().map_err(Error::ClassBorrow)
341    }
342
343    /// returns a pointer to the class object.
344    #[inline]
345    pub(crate) fn get_class_ptr(&self) -> NonNull<ClassCell<JsCell<'js, C>>> {
346        let id = unsafe { class_id::<C>(&self.ctx).expect("invalid class") };
347
348        let ptr = unsafe { qjs::JS_GetOpaque2(self.0.ctx.as_ptr(), self.0 .0.as_js_value(), id) };
349
350        NonNull::new(ptr.cast()).expect("invalid class object, object didn't have opaque value")
351    }
352
353    /// Turns the class back into a generic object.
354    #[inline]
355    pub fn into_inner(self) -> Object<'js> {
356        self.0
357    }
358
359    /// Turns the class back into a generic object.
360    #[inline]
361    pub fn as_inner(&self) -> &Object<'js> {
362        &self.0
363    }
364
365    /// Convert from value.
366    #[inline]
367    pub fn from_value(value: &Value<'js>) -> Result<Self> {
368        if let Some(cls) = value.as_object().and_then(Self::from_object) {
369            return Ok(cls);
370        }
371        Err(Error::FromJs {
372            from: value.type_name(),
373            to: C::NAME,
374            message: None,
375        })
376    }
377
378    /// Turn the class into a value.
379    #[inline]
380    pub fn into_value(self) -> Value<'js> {
381        self.0.into_value()
382    }
383
384    /// Converts a generic object into a class if the object is of the right class.
385    #[inline]
386    pub fn from_object(object: &Object<'js>) -> Option<Self> {
387        object.into_class().ok()
388    }
389}
390
391impl<'js> Object<'js> {
392    /// Returns if the object is of a certain Rust class.
393    pub fn instance_of<C: JsClass<'js>>(&self) -> bool {
394        let Ok(id) = (unsafe { class_id::<C>(&self.ctx) }) else {
395            return false;
396        };
397
398        // This checks if the class is of the right class id.
399        let Some(x) = NonNull::new(unsafe {
400            qjs::JS_GetOpaque2(self.0.ctx.as_ptr(), self.0.as_js_value(), id)
401        }) else {
402            // `JS_GetOpaque2` throws a `TypeError` internally whenever the class id
403            // doesn't match, leaving it pending on the runtime even though a
404            // negative result here is an ordinary, expected outcome. Clear it so a
405            // failed `instance_of` can't be mistaken for a real exception by code
406            // that later checks `Ctx::has_exception`/`Ctx::catch` for something
407            // unrelated (e.g. a pending `Promise`).
408            self.ctx.catch();
409            return false;
410        };
411
412        let v_table = unsafe { x.cast::<ClassCell<()>>().as_ref().v_table };
413
414        // If the pointer is equal it must be of the right type, as the inclusion of a call to
415        // generate a TypeId means that each type must have a unique v table.
416        // however if it is not equal then it can still be the right type if the v_table is
417        // duplicated, which is possible when compilation with multiple code-gen units.
418        //
419        // Doing check avoids a lookup and an dynamic function call in some cases.
420        if core::ptr::eq(v_table, VTable::get::<C>()) {
421            return true;
422        }
423
424        v_table.is_of_class::<C>()
425    }
426
427    /// Turn the object into the class if it is an instance of that class.
428    pub fn into_class<C: JsClass<'js>>(&self) -> core::result::Result<Class<'js, C>, &Self> {
429        if self.instance_of::<C>() {
430            Ok(Class(self.clone(), PhantomData))
431        } else {
432            Err(self)
433        }
434    }
435
436    /// Turn the object into the class if it is an instance of that class.
437    pub fn as_class<C: JsClass<'js>>(&self) -> Option<&Class<'js, C>> {
438        if self.instance_of::<C>() {
439            // SAFETY:
440            // Safe because class is a transparent wrapper
441            unsafe { Some(mem::transmute::<&Object<'js>, &Class<'js, C>>(self)) }
442        } else {
443            None
444        }
445    }
446}
447
448impl<'js, C: JsClass<'js>> FromJs<'js> for Class<'js, C> {
449    fn from_js(_ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
450        Self::from_value(&value)
451    }
452}
453
454impl<'js, C: JsClass<'js>> IntoJs<'js> for Class<'js, C> {
455    fn into_js(self, _ctx: &Ctx<'js>) -> Result<Value<'js>> {
456        Ok(self.0 .0)
457    }
458}
459
460unsafe fn class_id<'js, C: JsClass<'js>>(ctx: &Ctx<'js>) -> Result<qjs::JSClassID> {
461    match C::KIND {
462        ClassKind::Plain => Ok(ctx.get_runtime_opaque().get_class_id()),
463        ClassKind::Callable => Ok(ctx.get_runtime_opaque().get_callable_id()),
464        ClassKind::Exotic => Ok(ctx.get_runtime_opaque().get_exotic_id()),
465    }
466}