1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum ClassKind {
34 Plain,
36 Callable,
38 Exotic,
40}
41
42pub struct PropertyDescriptor<'js> {
44 pub value: Value<'js>,
46 pub getter: Value<'js>,
48 pub setter: Value<'js>,
50 pub configurable: bool,
52 pub enumerable: bool,
54 pub writable: bool,
56 pub is_getset: bool,
58}
59
60impl<'js> PropertyDescriptor<'js> {
61 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
81pub struct PropertyName<'js> {
83 pub atom: Atom<'js>,
85 pub is_enumerable: bool,
87}
88
89pub trait JsClass<'js>: Trace<'js> + JsLifetime<'js> + Sized {
91 const NAME: &'static str;
93
94 const KIND: ClassKind = ClassKind::Plain;
96
97 type Mutable: Mutability;
101
102 fn prototype(ctx: &Ctx<'js>) -> Result<Option<Object<'js>>> {
104 Object::new(ctx.clone()).map(Some)
105 }
106
107 fn constructor(ctx: &Ctx<'js>) -> Result<Option<Constructor<'js>>>;
109
110 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 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 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 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 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 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 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#[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 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 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 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 pub fn create_constructor(ctx: &Ctx<'js>) -> Result<Option<Constructor<'js>>> {
272 C::constructor(ctx)
273 }
274
275 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 #[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 #[inline]
291 pub fn get_cell<'a>(&'a self) -> &'a JsCell<'js, C> {
292 &self.get_class_cell().data
293 }
294
295 #[inline]
303 pub fn borrow<'a>(&'a self) -> Borrow<'a, 'js, C> {
304 self.get_cell().borrow()
305 }
306
307 #[inline]
316 pub fn borrow_mut<'a>(&'a self) -> BorrowMut<'a, 'js, C> {
317 self.get_cell().borrow_mut()
318 }
319
320 #[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 #[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 #[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 #[inline]
355 pub fn into_inner(self) -> Object<'js> {
356 self.0
357 }
358
359 #[inline]
361 pub fn as_inner(&self) -> &Object<'js> {
362 &self.0
363 }
364
365 #[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 #[inline]
380 pub fn into_value(self) -> Value<'js> {
381 self.0.into_value()
382 }
383
384 #[inline]
386 pub fn from_object(object: &Object<'js>) -> Option<Self> {
387 object.into_class().ok()
388 }
389}
390
391impl<'js> Object<'js> {
392 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 let Some(x) = NonNull::new(unsafe {
400 qjs::JS_GetOpaque2(self.0.ctx.as_ptr(), self.0.as_js_value(), id)
401 }) else {
402 self.ctx.catch();
409 return false;
410 };
411
412 let v_table = unsafe { x.cast::<ClassCell<()>>().as_ref().v_table };
413
414 if core::ptr::eq(v_table, VTable::get::<C>()) {
421 return true;
422 }
423
424 v_table.is_of_class::<C>()
425 }
426
427 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 pub fn as_class<C: JsClass<'js>>(&self) -> Option<&Class<'js, C>> {
438 if self.instance_of::<C>() {
439 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}