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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub enum ClassKind {
31 Plain,
33 Callable,
35 Exotic,
37}
38
39pub struct PropertyDescriptor<'js> {
41 pub value: Value<'js>,
43 pub getter: Value<'js>,
45 pub setter: Value<'js>,
47 pub configurable: bool,
49 pub enumerable: bool,
51 pub writable: bool,
53 pub is_getset: bool,
55}
56
57impl<'js> PropertyDescriptor<'js> {
58 pub fn new_value(
60 value: Value<'js>,
61 configurable: bool,
62 enumerable: bool,
63 writable: bool,
64 ) -> Self {
65 let ctx = value.ctx().clone();
66 PropertyDescriptor {
67 value,
68 getter: Value::new_undefined(ctx.clone()),
69 setter: Value::new_undefined(ctx),
70 configurable,
71 enumerable,
72 writable,
73 is_getset: false,
74 }
75 }
76}
77
78pub struct PropertyName<'js> {
80 pub atom: Atom<'js>,
82 pub is_enumerable: bool,
84}
85
86pub trait JsClass<'js>: Trace<'js> + JsLifetime<'js> + Sized {
88 const NAME: &'static str;
90
91 const KIND: ClassKind = ClassKind::Plain;
93
94 type Mutable: Mutability;
98
99 fn prototype(ctx: &Ctx<'js>) -> Result<Option<Object<'js>>> {
101 Object::new(ctx.clone()).map(Some)
102 }
103
104 fn constructor(ctx: &Ctx<'js>) -> Result<Option<Constructor<'js>>>;
106
107 fn call<'a>(this: &JsCell<'js, Self>, params: Params<'a, 'js>) -> Result<Value<'js>> {
110 let _ = this;
111 Ok(Value::new_undefined(params.ctx().clone()))
112 }
113
114 fn exotic_get_property(
116 this: &JsCell<'js, Self>,
117 ctx: &Ctx<'js>,
118 _atom: Atom<'js>,
119 _receiver: Value<'js>,
120 ) -> Result<Value<'js>> {
121 let _ = this;
122 Ok(Value::new_undefined(ctx.clone()))
123 }
124
125 fn exotic_set_property(
127 this: &JsCell<'js, Self>,
128 _ctx: &Ctx<'js>,
129 _atom: Atom<'js>,
130 _receiver: Value<'js>,
131 _value: Value<'js>,
132 ) -> Result<bool> {
133 let _ = this;
134 Ok(false)
135 }
136
137 fn exotic_delete_property(
139 this: &JsCell<'js, Self>,
140 _ctx: &Ctx<'js>,
141 _atom: Atom<'js>,
142 ) -> Result<bool> {
143 let _ = this;
144 Ok(false)
145 }
146
147 fn exotic_has_property(
149 this: &JsCell<'js, Self>,
150 _ctx: &Ctx<'js>,
151 _atom: Atom<'js>,
152 ) -> Result<bool> {
153 let _ = this;
154 Ok(false)
155 }
156
157 fn exotic_get_own_property(
161 this: &JsCell<'js, Self>,
162 _ctx: &Ctx<'js>,
163 _atom: Atom<'js>,
164 ) -> Result<Option<PropertyDescriptor<'js>>> {
165 let _ = this;
166 Ok(None)
167 }
168
169 fn exotic_get_own_property_names(
173 this: &JsCell<'js, Self>,
174 _ctx: &Ctx<'js>,
175 ) -> Result<Vec<PropertyName<'js>>> {
176 let _ = this;
177 Ok(Vec::new())
178 }
179}
180
181#[repr(transparent)]
183pub struct Class<'js, C: JsClass<'js>>(pub(crate) Object<'js>, PhantomData<C>);
184
185impl<'js, C: JsClass<'js>> Clone for Class<'js, C> {
186 fn clone(&self) -> Self {
187 Class(self.0.clone(), PhantomData)
188 }
189}
190
191impl<'js, C: JsClass<'js>> PartialEq for Class<'js, C> {
192 fn eq(&self, other: &Self) -> bool {
193 self.0 == other.0
194 }
195}
196
197impl<'js, C: JsClass<'js>> Eq for Class<'js, C> {}
198
199impl<'js, C: JsClass<'js>> Hash for Class<'js, C> {
200 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
201 self.0.hash(state)
202 }
203}
204
205unsafe impl<'js, C> JsLifetime<'js> for Class<'js, C>
206where
207 C: JsClass<'js> + JsLifetime<'js>,
208 for<'to> C::Changed<'to>: JsClass<'to>,
209{
210 type Changed<'to> = Class<'to, C::Changed<'to>>;
211}
212
213impl<'js, C: JsClass<'js>> Deref for Class<'js, C> {
214 type Target = Object<'js>;
215
216 fn deref(&self) -> &Self::Target {
217 &self.0
218 }
219}
220
221impl<'js, C: JsClass<'js>> Class<'js, C> {
222 pub fn instance(ctx: Ctx<'js>, value: C) -> Result<Class<'js, C>> {
224 let id = unsafe { class_id::<C>(&ctx)? };
225
226 let prototype = Self::prototype(&ctx)?;
227
228 let prototype = prototype.map(|x| x.as_js_value()).unwrap_or(qjs::JS_NULL);
229 let val = unsafe {
230 ctx.handle_exception(qjs::JS_NewObjectProtoClass(ctx.as_ptr(), prototype, id))?
231 };
232
233 let ptr = Box::into_raw(Box::new(ClassCell::new(value)));
234 unsafe { qjs::JS_SetOpaque(val, ptr.cast()) };
235 Ok(Self(
236 unsafe { Object::from_js_value(ctx, val) },
237 PhantomData,
238 ))
239 }
240
241 pub fn instance_proto(value: C, proto: Object<'js>) -> Result<Class<'js, C>> {
243 let id = unsafe { class_id::<C>(proto.ctx())? };
244
245 let val = unsafe {
246 proto.ctx.handle_exception(qjs::JS_NewObjectProtoClass(
247 proto.ctx().as_ptr(),
248 proto.0.as_js_value(),
249 id,
250 ))?
251 };
252 let ptr = Box::into_raw(Box::new(ClassCell::new(value)));
253 unsafe { qjs::JS_SetOpaque(val, ptr.cast()) };
254 Ok(Self(
255 unsafe { Object::from_js_value(proto.ctx.clone(), val) },
256 PhantomData,
257 ))
258 }
259
260 pub fn prototype(ctx: &Ctx<'js>) -> Result<Option<Object<'js>>> {
264 unsafe { ctx.get_opaque().get_or_insert_prototype::<C>(ctx) }
265 }
266
267 pub fn create_constructor(ctx: &Ctx<'js>) -> Result<Option<Constructor<'js>>> {
269 C::constructor(ctx)
270 }
271
272 pub fn define(object: &Object<'js>) -> Result<()> {
274 if let Some(constructor) = Self::create_constructor(object.ctx())? {
275 object.set(C::NAME, constructor)?;
276 }
277 Ok(())
278 }
279
280 #[inline]
282 pub(crate) fn get_class_cell<'a>(&'a self) -> &'a ClassCell<JsCell<'js, C>> {
283 unsafe { self.get_class_ptr().as_ref() }
284 }
285
286 #[inline]
288 pub fn get_cell<'a>(&'a self) -> &'a JsCell<'js, C> {
289 &self.get_class_cell().data
290 }
291
292 #[inline]
300 pub fn borrow<'a>(&'a self) -> Borrow<'a, 'js, C> {
301 self.get_cell().borrow()
302 }
303
304 #[inline]
313 pub fn borrow_mut<'a>(&'a self) -> BorrowMut<'a, 'js, C> {
314 self.get_cell().borrow_mut()
315 }
316
317 #[inline]
324 pub fn try_borrow<'a>(&'a self) -> Result<Borrow<'a, 'js, C>> {
325 self.get_cell().try_borrow().map_err(Error::ClassBorrow)
326 }
327
328 #[inline]
336 pub fn try_borrow_mut<'a>(&'a self) -> Result<BorrowMut<'a, 'js, C>> {
337 self.get_cell().try_borrow_mut().map_err(Error::ClassBorrow)
338 }
339
340 #[inline]
342 pub(crate) fn get_class_ptr(&self) -> NonNull<ClassCell<JsCell<'js, C>>> {
343 let id = unsafe { class_id::<C>(&self.ctx).expect("invalid class") };
344
345 let ptr = unsafe { qjs::JS_GetOpaque2(self.0.ctx.as_ptr(), self.0 .0.as_js_value(), id) };
346
347 NonNull::new(ptr.cast()).expect("invalid class object, object didn't have opaque value")
348 }
349
350 #[inline]
352 pub fn into_inner(self) -> Object<'js> {
353 self.0
354 }
355
356 #[inline]
358 pub fn as_inner(&self) -> &Object<'js> {
359 &self.0
360 }
361
362 #[inline]
364 pub fn from_value(value: &Value<'js>) -> Result<Self> {
365 if let Some(cls) = value.as_object().and_then(Self::from_object) {
366 return Ok(cls);
367 }
368 Err(Error::FromJs {
369 from: value.type_name(),
370 to: C::NAME,
371 message: None,
372 })
373 }
374
375 #[inline]
377 pub fn into_value(self) -> Value<'js> {
378 self.0.into_value()
379 }
380
381 #[inline]
383 pub fn from_object(object: &Object<'js>) -> Option<Self> {
384 object.into_class().ok()
385 }
386}
387
388impl<'js> Object<'js> {
389 pub fn instance_of<C: JsClass<'js>>(&self) -> bool {
391 let Ok(id) = (unsafe { class_id::<C>(&self.ctx) }) else {
392 return false;
393 };
394
395 let Some(x) = NonNull::new(unsafe {
397 qjs::JS_GetOpaque2(self.0.ctx.as_ptr(), self.0.as_js_value(), id)
398 }) else {
399 self.ctx.catch();
406 return false;
407 };
408
409 let v_table = unsafe { x.cast::<ClassCell<()>>().as_ref().v_table };
410
411 if core::ptr::eq(v_table, VTable::get::<C>()) {
418 return true;
419 }
420
421 v_table.is_of_class::<C>()
422 }
423
424 pub fn into_class<C: JsClass<'js>>(&self) -> core::result::Result<Class<'js, C>, &Self> {
426 if self.instance_of::<C>() {
427 Ok(Class(self.clone(), PhantomData))
428 } else {
429 Err(self)
430 }
431 }
432
433 pub fn as_class<C: JsClass<'js>>(&self) -> Option<&Class<'js, C>> {
435 if self.instance_of::<C>() {
436 unsafe { Some(mem::transmute::<&Object<'js>, &Class<'js, C>>(self)) }
439 } else {
440 None
441 }
442 }
443}
444
445impl<'js, C: JsClass<'js>> FromJs<'js> for Class<'js, C> {
446 fn from_js(_ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
447 Self::from_value(&value)
448 }
449}
450
451impl<'js, C: JsClass<'js>> IntoJs<'js> for Class<'js, C> {
452 fn into_js(self, _ctx: &Ctx<'js>) -> Result<Value<'js>> {
453 Ok(self.0 .0)
454 }
455}
456
457unsafe fn class_id<'js, C: JsClass<'js>>(ctx: &Ctx<'js>) -> Result<qjs::JSClassID> {
458 match C::KIND {
459 ClassKind::Plain => Ok(ctx.get_opaque().get_class_id()),
460 ClassKind::Callable => Ok(ctx.get_opaque().get_callable_id()),
461 ClassKind::Exotic => Ok(ctx.get_opaque().get_exotic_id()),
462 }
463}
464
465#[cfg(test)]
466mod test {
467 use core::sync::atomic::AtomicI32;
468 use std::sync::{
469 atomic::{AtomicBool, Ordering},
470 Arc,
471 };
472
473 use crate::{
474 class::{ClassKind, JsClass, Readable, Trace, Tracer, Writable},
475 function::This,
476 test_with,
477 value::Constructor,
478 CatchResultExt, Class, Context, FromIteratorJs, FromJs, Function, IntoJs, JsLifetime,
479 Object, Runtime,
480 };
481
482 #[test]
484 fn trace() {
485 pub struct Container<'js> {
486 inner: Vec<Class<'js, Container<'js>>>,
487 test: Arc<AtomicBool>,
488 }
489
490 impl<'js> Drop for Container<'js> {
491 fn drop(&mut self) {
492 self.test.store(true, Ordering::SeqCst);
493 }
494 }
495
496 impl<'js> Trace<'js> for Container<'js> {
497 fn trace<'a>(&self, tracer: Tracer<'a, 'js>) {
498 self.inner.iter().for_each(|x| x.trace(tracer))
499 }
500 }
501
502 unsafe impl<'js> JsLifetime<'js> for Container<'js> {
503 type Changed<'to> = Container<'to>;
504 }
505
506 impl<'js> JsClass<'js> for Container<'js> {
507 const NAME: &'static str = "Container";
508
509 type Mutable = Writable;
510
511 fn prototype(ctx: &crate::Ctx<'js>) -> crate::Result<Option<crate::Object<'js>>> {
512 Ok(Some(Object::new(ctx.clone())?))
513 }
514
515 fn constructor(
516 _ctx: &crate::Ctx<'js>,
517 ) -> crate::Result<Option<crate::value::Constructor<'js>>> {
518 Ok(None)
519 }
520 }
521
522 let rt = Runtime::new().unwrap();
523 let ctx = Context::full(&rt).unwrap();
524
525 let drop_test = Arc::new(AtomicBool::new(false));
526
527 ctx.with(|ctx| {
528 let cls = Class::instance(
529 ctx.clone(),
530 Container {
531 inner: Vec::new(),
532 test: drop_test.clone(),
533 },
534 )
535 .unwrap();
536
537 assert!(cls.instance_of::<Container>());
538
539 let cls_clone = cls.clone();
540 cls.borrow_mut().inner.push(cls_clone);
541 });
542 rt.run_gc();
543 assert!(drop_test.load(Ordering::SeqCst));
544 ctx.with(|ctx| {
545 let cls = Class::instance(
546 ctx.clone(),
547 Container {
548 inner: Vec::new(),
549 test: drop_test.clone(),
550 },
551 )
552 .unwrap();
553 let cls_clone = cls.clone();
554 cls.borrow_mut().inner.push(cls_clone);
555 ctx.globals().set("t", cls).unwrap();
556 });
557 }
558
559 #[test]
562 fn interrupt_inside_array_find_keeps_elements_alive() {
563 use std::sync::atomic::AtomicUsize;
564
565 static DROPPED: AtomicUsize = AtomicUsize::new(0);
566
567 pub struct Element;
568
569 impl Drop for Element {
570 fn drop(&mut self) {
571 DROPPED.fetch_add(1, Ordering::SeqCst);
572 }
573 }
574
575 impl<'js> Trace<'js> for Element {
576 fn trace<'a>(&self, _tracer: Tracer<'a, 'js>) {}
577 }
578
579 unsafe impl<'js> JsLifetime<'js> for Element {
580 type Changed<'to> = Element;
581 }
582
583 impl<'js> JsClass<'js> for Element {
584 const NAME: &'static str = "Element";
585
586 type Mutable = Readable;
587
588 fn prototype(ctx: &crate::Ctx<'js>) -> crate::Result<Option<crate::Object<'js>>> {
589 Ok(Some(Object::new(ctx.clone())?))
590 }
591
592 fn constructor(
593 _ctx: &crate::Ctx<'js>,
594 ) -> crate::Result<Option<crate::value::Constructor<'js>>> {
595 Ok(None)
596 }
597 }
598
599 let rt = Runtime::new().unwrap();
600 let stopping = Arc::new(AtomicBool::new(false));
601 let stop = stopping.clone();
602 rt.set_interrupt_handler(Some(Box::new(move || stop.load(Ordering::Relaxed))));
603 let ctx = Context::full(&rt).unwrap();
604 let methods = ["find", "findIndex", "findLast", "findLastIndex"];
605 ctx.with(|ctx| {
606 let kept = Object::new(ctx.clone()).unwrap();
607 for method in methods {
608 kept.set(method, Class::instance(ctx.clone(), Element).unwrap())
609 .unwrap();
610 }
611 ctx.globals().set("kept", kept).unwrap();
612 ctx.eval::<(), _>(
613 "globalThis.items = Object.values(kept).map((e) => new Array(100000).fill(e));",
614 )
615 .unwrap();
616 let interrupted = |source: String| {
617 assert!(ctx.eval::<(), _>(source.as_str()).is_err(), "{source}");
618 drop(ctx.catch());
619 };
620 stopping.store(true, Ordering::Relaxed);
627 for (i, method) in methods.into_iter().enumerate() {
628 for prefix in ["", "(() => {})(), "] {
629 interrupted("for (;;) {}".into());
630 interrupted(format!("{prefix}items[{i}].{method}(() => false)"));
631 }
632 }
633 stopping.store(false, Ordering::Relaxed);
634 ctx.eval::<(), _>("items = null;").unwrap();
635 });
636 rt.run_gc();
639 assert_eq!(DROPPED.load(Ordering::SeqCst), 0);
640 ctx.with(|ctx| ctx.eval::<(), _>("kept = null;").unwrap());
641 rt.run_gc();
642 assert_eq!(DROPPED.load(Ordering::SeqCst), methods.len());
643 }
644
645 #[derive(Clone, Copy)]
646 pub struct Vec3 {
647 x: f32,
648 y: f32,
649 z: f32,
650 }
651
652 impl Vec3 {
653 pub fn new(x: f32, y: f32, z: f32) -> Self {
654 Vec3 { x, y, z }
655 }
656
657 pub fn add(self, v: Vec3) -> Self {
658 Vec3 {
659 x: self.x + v.x,
660 y: self.y + v.y,
661 z: self.z + v.z,
662 }
663 }
664 }
665
666 impl<'js> Trace<'js> for Vec3 {
667 fn trace<'a>(&self, _tracer: Tracer<'a, 'js>) {}
668 }
669
670 impl<'js> FromJs<'js> for Vec3 {
671 fn from_js(ctx: &crate::Ctx<'js>, value: crate::Value<'js>) -> crate::Result<Self> {
672 Ok(*Class::<Vec3>::from_js(ctx, value)?.try_borrow()?)
673 }
674 }
675
676 impl<'js> IntoJs<'js> for Vec3 {
677 fn into_js(self, ctx: &crate::Ctx<'js>) -> crate::Result<crate::Value<'js>> {
678 Class::instance(ctx.clone(), self).into_js(ctx)
679 }
680 }
681
682 unsafe impl<'js> JsLifetime<'js> for Vec3 {
683 type Changed<'to> = Vec3;
684 }
685
686 impl<'js> JsClass<'js> for Vec3 {
687 const NAME: &'static str = "Vec3";
688
689 type Mutable = Writable;
690
691 fn prototype(ctx: &crate::Ctx<'js>) -> crate::Result<Option<crate::Object<'js>>> {
692 let proto = Object::new(ctx.clone())?;
693 let func = Function::new(ctx.clone(), |this: This<Vec3>, other: Vec3| this.add(other))?
694 .with_name("add")?;
695
696 proto.set("add", func)?;
697 Ok(Some(proto))
698 }
699
700 fn constructor(
701 ctx: &crate::Ctx<'js>,
702 ) -> crate::Result<Option<crate::value::Constructor<'js>>> {
703 let constr =
704 Constructor::new_class::<Vec3, _, _>(ctx.clone(), |x: f32, y: f32, z: f32| {
705 Vec3::new(x, y, z)
706 })?;
707
708 Ok(Some(constr))
709 }
710 }
711
712 #[test]
713 fn constructor() {
714 test_with(|ctx| {
715 Class::<Vec3>::define(&ctx.globals()).unwrap();
716
717 let v = ctx
718 .eval::<Vec3, _>(
719 r"
720 let a = new Vec3(1,2,3);
721 let b = new Vec3(4,2,8);
722 a.add(b)
723 ",
724 )
725 .catch(&ctx)
726 .unwrap();
727
728 approx::assert_abs_diff_eq!(v.x, 5.0);
729 approx::assert_abs_diff_eq!(v.y, 4.0);
730 approx::assert_abs_diff_eq!(v.z, 11.0);
731
732 let name: String = ctx.eval("new Vec3(1,2,3).constructor.name").unwrap();
733 assert_eq!(name, Vec3::NAME);
734 })
735 }
736
737 #[test]
738 fn extend_class() {
739 test_with(|ctx| {
740 Class::<Vec3>::define(&ctx.globals()).unwrap();
741
742 let v = ctx
743 .eval::<Vec3, _>(
744 r"
745 class Vec4 extends Vec3 {
746 w = 0;
747 constructor(x,y,z,w){
748 super(x,y,z);
749 this.w
750 }
751 }
752
753 new Vec4(1,2,3,4);
754 ",
755 )
756 .catch(&ctx)
757 .unwrap();
758
759 approx::assert_abs_diff_eq!(v.x, 1.0);
760 approx::assert_abs_diff_eq!(v.y, 2.0);
761 approx::assert_abs_diff_eq!(v.z, 3.0);
762 })
763 }
764
765 #[test]
766 fn get_prototype() {
767 pub struct X;
768
769 impl<'js> Trace<'js> for X {
770 fn trace<'a>(&self, _tracer: Tracer<'a, 'js>) {}
771 }
772
773 unsafe impl<'js> JsLifetime<'js> for X {
774 type Changed<'to> = X;
775 }
776
777 impl<'js> JsClass<'js> for X {
778 const NAME: &'static str = "X";
779
780 type Mutable = Readable;
781
782 fn prototype(ctx: &crate::Ctx<'js>) -> crate::Result<Option<Object<'js>>> {
783 let object = Object::new(ctx.clone())?;
784 object.set("foo", "bar")?;
785 Ok(Some(object))
786 }
787
788 fn constructor(_ctx: &crate::Ctx<'js>) -> crate::Result<Option<Constructor<'js>>> {
789 Ok(None)
790 }
791 }
792
793 test_with(|ctx| {
794 let proto = Class::<X>::prototype(&ctx).unwrap().unwrap();
795 assert_eq!(proto.get::<_, String>("foo").unwrap(), "bar")
796 })
797 }
798
799 #[test]
800 fn instance_of_non_class_object_does_not_leave_pending_exception() {
801 test_with(|ctx| {
802 let plain = Object::new(ctx.clone()).unwrap();
808
809 assert!(!plain.instance_of::<Vec3>());
810
811 assert!(!ctx.has_exception());
815
816 let sum: i32 = ctx.eval("1 + 1").unwrap();
818 assert_eq!(sum, 2);
819 })
820 }
821
822 #[test]
823 fn generic_types() {
824 pub struct DebugPrinter<D: std::fmt::Debug> {
825 d: D,
826 }
827
828 impl<'js, D: std::fmt::Debug> Trace<'js> for DebugPrinter<D> {
829 fn trace<'a>(&self, _tracer: Tracer<'a, 'js>) {}
830 }
831
832 unsafe impl<'js, D: std::fmt::Debug + 'static> JsLifetime<'js> for DebugPrinter<D> {
833 type Changed<'to> = DebugPrinter<D>;
834 }
835
836 impl<'js, D: std::fmt::Debug + 'static> JsClass<'js> for DebugPrinter<D> {
837 const NAME: &'static str = "DebugPrinter";
838
839 type Mutable = Readable;
840
841 fn prototype(ctx: &crate::Ctx<'js>) -> crate::Result<Option<Object<'js>>> {
842 let object = Object::new(ctx.clone())?;
843 object.set(
844 "to_debug_string",
845 Function::new(
846 ctx.clone(),
847 |this: This<Class<DebugPrinter<D>>>| -> crate::Result<String> {
848 Ok(format!("{:?}", this.0.borrow().d))
849 },
850 ),
851 )?;
852 Ok(Some(object))
853 }
854
855 fn constructor(_ctx: &crate::Ctx<'js>) -> crate::Result<Option<Constructor<'js>>> {
856 Ok(None)
857 }
858 }
859
860 test_with(|ctx| {
861 let a = Class::instance(ctx.clone(), DebugPrinter { d: 42usize });
862 let b = Class::instance(
863 ctx.clone(),
864 DebugPrinter {
865 d: "foo".to_string(),
866 },
867 );
868
869 ctx.globals().set("a", a).unwrap();
870 ctx.globals().set("b", b).unwrap();
871
872 assert_eq!(
873 ctx.eval::<String, _>(r#" a.to_debug_string() "#)
874 .catch(&ctx)
875 .unwrap(),
876 "42"
877 );
878 assert_eq!(
879 ctx.eval::<String, _>(r#" b.to_debug_string() "#)
880 .catch(&ctx)
881 .unwrap(),
882 "\"foo\""
883 );
884
885 if ctx
886 .globals()
887 .get::<_, Class<DebugPrinter<String>>>("a")
888 .is_ok()
889 {
890 panic!("Conversion should fail")
891 }
892 if ctx
893 .globals()
894 .get::<_, Class<DebugPrinter<usize>>>("b")
895 .is_ok()
896 {
897 panic!("Conversion should fail")
898 }
899
900 ctx.globals()
901 .get::<_, Class<DebugPrinter<usize>>>("a")
902 .unwrap();
903 ctx.globals()
904 .get::<_, Class<DebugPrinter<String>>>("b")
905 .unwrap();
906 })
907 }
908
909 #[test]
910 fn exotic() {
911 pub struct ExoticIterator {
912 curr_state: Arc<AtomicI32>,
913 }
914
915 impl<'js> Trace<'js> for ExoticIterator {
916 fn trace<'a>(&self, _tracer: Tracer<'a, 'js>) {}
917 }
918
919 unsafe impl<'js> JsLifetime<'js> for ExoticIterator {
920 type Changed<'to> = ExoticIterator;
921 }
922
923 impl<'js> JsClass<'js> for ExoticIterator {
924 const NAME: &'static str = "ExoticIterator";
925
926 type Mutable = Readable;
927
928 const KIND: ClassKind = ClassKind::Exotic;
929
930 fn prototype(ctx: &crate::Ctx<'js>) -> crate::Result<Option<crate::Object<'js>>> {
931 Ok(Some(crate::Object::new(ctx.clone())?))
932 }
933
934 fn constructor(
935 _ctx: &crate::Ctx<'js>,
936 ) -> crate::Result<Option<crate::value::Constructor<'js>>> {
937 Ok(None)
938 }
939
940 fn exotic_get_property(
941 this: &crate::class::JsCell<'js, Self>,
942 ctx: &crate::Ctx<'js>,
943 atom: crate::Atom<'js>,
944 _receiver: crate::Value<'js>,
945 ) -> crate::Result<crate::Value<'js>> {
946 println!("Get property [iter]: {}", atom.to_string()?);
947 if atom.to_string()? == "next" {
948 let state = this.borrow().curr_state.clone();
949 Ok(Function::new(ctx.clone(), move |ctx: crate::Ctx<'js>| {
950 if state.load(Ordering::SeqCst) <= 1 {
954 state.store(2, Ordering::SeqCst);
955
956 let val = crate::Object::from_iter_js(
957 &ctx,
958 [
959 ("done", false.into_js(&ctx)?),
960 ("value", vec!["hello", "1292"].into_js(&ctx)?),
961 ],
962 )?
963 .into_value();
964
965 Ok::<crate::Value<'_>, crate::Error>(val)
966 } else if state.load(Ordering::SeqCst) == 2 {
967 state.fetch_add(1, Ordering::SeqCst);
968
969 let val = crate::Object::from_iter_js(
970 &ctx,
971 [
972 ("done", false.into_js(&ctx)?),
973 (
974 "value",
975 vec!["i".into_js(&ctx)?, 43.into_js(&ctx)?]
976 .into_js(&ctx)?,
977 ),
978 ],
979 )?
980 .into_value();
981
982 Ok(val)
983 } else {
984 state.fetch_add(1, Ordering::SeqCst);
985
986 let val = crate::Object::from_iter_js(
987 &ctx,
988 [
989 ("done", true.into_js(&ctx)?),
990 ("value", crate::Value::new_undefined(ctx.clone())),
991 ],
992 )?
993 .into_value();
994
995 Ok(val)
996 }
997 })?
998 .into_value())
999 } else {
1000 Ok(crate::Value::new_undefined(ctx.clone()))
1001 }
1002 }
1003
1004 fn exotic_has_property(
1005 this: &super::JsCell<'js, Self>,
1006 _ctx: &crate::Ctx<'js>,
1007 atom: crate::Atom<'js>,
1008 ) -> crate::Result<bool> {
1009 let _ = this;
1010 Ok(atom.to_string()? == "next")
1011 }
1012 }
1013
1014 #[derive(Clone)]
1015 pub struct Exotic {
1016 pub i: i32,
1017 }
1018
1019 impl<'js> Trace<'js> for Exotic {
1020 fn trace<'a>(&self, _tracer: Tracer<'a, 'js>) {}
1021 }
1022
1023 unsafe impl<'js> JsLifetime<'js> for Exotic {
1024 type Changed<'to> = Exotic;
1025 }
1026
1027 impl<'js> JsClass<'js> for Exotic {
1028 const NAME: &'static str = "Exotic";
1029
1030 type Mutable = Writable;
1031
1032 const KIND: ClassKind = ClassKind::Exotic;
1033
1034 fn prototype(ctx: &crate::Ctx<'js>) -> crate::Result<Option<crate::Object<'js>>> {
1035 Ok(Some(crate::Object::new(ctx.clone())?))
1036 }
1037
1038 fn constructor(
1039 _ctx: &crate::Ctx<'js>,
1040 ) -> crate::Result<Option<crate::value::Constructor<'js>>> {
1041 Ok(None)
1042 }
1043
1044 fn exotic_get_property(
1045 this: &crate::class::JsCell<'js, Self>,
1046 ctx: &crate::Ctx<'js>,
1047 atom: crate::Atom<'js>,
1048 _receiver: crate::Value<'js>,
1049 ) -> crate::Result<crate::Value<'js>> {
1050 let symbol_iterator = crate::Atom::from_predefined(
1051 ctx.clone(),
1052 crate::atom::PredefinedAtom::SymbolIterator,
1053 );
1054 println!("Get property: {}", atom.to_string()?);
1055 if atom.to_string()? == "hello" {
1056 assert!(this.borrow().i == 42);
1057 Ok("world".into_js(ctx)?)
1058 } else if atom.to_string()? == "toString" {
1059 Ok(Function::new(ctx.clone(), || {
1060 let f = "class Exotic { [native code] }";
1061 Ok::<&'static str, crate::Error>(f)
1062 })?
1063 .into_value())
1064 } else if atom == symbol_iterator {
1065 println!("Getting iterator");
1066 let exotic = Class::<ExoticIterator>::instance(
1067 ctx.clone(),
1068 ExoticIterator {
1069 curr_state: Arc::default(),
1070 },
1071 )?;
1072 println!("Returning ExoticIterator");
1073 Ok(Function::new(ctx.clone(), move || {
1074 Ok::<crate::Value<'_>, crate::Error>(exotic.clone().into_value())
1075 })?
1076 .into_value())
1077 } else {
1078 Ok(crate::Value::new_null(ctx.clone()))
1079 }
1080 }
1081
1082 fn exotic_set_property(
1083 this: &super::JsCell<'js, Self>,
1084 ctx: &crate::Ctx<'js>,
1085 atom: crate::Atom<'js>,
1086 _receiver: crate::Value<'js>,
1087 _value: crate::Value<'js>,
1088 ) -> crate::Result<bool> {
1089 let _ = this;
1090 if atom.to_string()? == "i" {
1091 let Some(new_i) = _value.as_int() else {
1092 let err_val = crate::String::from_str(ctx.clone(), "i must be an integer")?
1093 .into_value();
1094 return Err(ctx.throw(err_val));
1095 };
1096 this.borrow_mut().i = new_i;
1097 return Ok(true);
1098 }
1099 let err_val =
1100 crate::String::from_str(ctx.clone(), "Properties are read-only")?.into_value();
1101 Err(ctx.throw(err_val))
1102 }
1103
1104 fn exotic_has_property(
1105 this: &super::JsCell<'js, Self>,
1106 _ctx: &crate::Ctx<'js>,
1107 atom: crate::Atom<'js>,
1108 ) -> crate::Result<bool> {
1109 let _ = this;
1110 let atom = atom.to_string()?;
1111 println!("Got atom: {atom}");
1112 Ok(matches!(atom.as_str(), "hello" | "i" | "toString"))
1113 }
1114
1115 fn exotic_delete_property(
1116 _this: &super::JsCell<'js, Self>,
1117 ctx: &crate::Ctx<'js>,
1118 _atom: crate::Atom<'js>,
1119 ) -> crate::Result<bool> {
1120 let err_val = crate::String::from_str(ctx.clone(), "Properties cannot be deleted")?
1121 .into_value();
1122 Err(ctx.throw(err_val))
1123 }
1124
1125 fn exotic_get_own_property(
1126 this: &super::JsCell<'js, Self>,
1127 ctx: &crate::Ctx<'js>,
1128 atom: crate::Atom<'js>,
1129 ) -> crate::Result<Option<super::PropertyDescriptor<'js>>> {
1130 let name = atom.to_string()?;
1131 if name == "hello" || name == "i" {
1132 let value = if name == "hello" {
1133 "world".into_js(ctx)?
1134 } else {
1135 this.borrow().i.into_js(ctx)?
1136 };
1137 Ok(Some(super::PropertyDescriptor::new_value(
1138 value, true, true, false,
1139 )))
1140 } else {
1141 Ok(None)
1142 }
1143 }
1144
1145 fn exotic_get_own_property_names(
1146 _this: &super::JsCell<'js, Self>,
1147 ctx: &crate::Ctx<'js>,
1148 ) -> crate::Result<Vec<super::PropertyName<'js>>> {
1149 Ok(vec![
1150 super::PropertyName {
1151 atom: crate::Atom::from_str(ctx.clone(), "hello")?,
1152 is_enumerable: true,
1153 },
1154 super::PropertyName {
1155 atom: crate::Atom::from_str(ctx.clone(), "i")?,
1156 is_enumerable: true,
1157 },
1158 ])
1159 }
1160 }
1161
1162 test_with(|ctx| {
1163 let exotic = Class::<Exotic>::instance(ctx.clone(), Exotic { i: 0 }).unwrap();
1164 ctx.globals().set("exotic", exotic).unwrap();
1165 ctx.globals()
1166 .set(
1167 "assert",
1168 Function::new(
1169 ctx.clone(),
1170 |ctx: crate::Ctx<'_>, cond: bool, msg: String| {
1171 if !cond {
1172 let err_val =
1173 crate::String::from_str(ctx.clone(), &msg)?.into_value();
1174 return Err(ctx.throw(err_val));
1175 }
1176 Ok(())
1177 },
1178 ),
1179 )
1180 .unwrap();
1181
1182 let v = ctx
1183 .eval::<String, _>(
1184 r"
1185 if(exotic.foo !== null) {
1186 throw new Error('foo should be null');
1187 }
1188 try {
1189 exotic.foo = 1
1190 } catch(e) {
1191 if (e?.toString() !== 'Properties are read-only') {
1192 throw new Error('wrong error message: ' + e?.toString());
1193 }
1194 }
1195 if (exotic.foo !== null) {
1196 throw new Error('foo should be null');
1197 }
1198 exotic.i = 42;
1199 if (exotic.hello === 42) {
1200 throw new Error('i should be 42');
1201 }
1202 assert(exotic?.toString() === 'class Exotic { [native code] }', `exotic.toString() should be 'class Exotic { [native code] }' but is ${exotic?.toString()}`);
1203 assert('i' in exotic, 'i should be in exotic');
1204 assert('hello' in exotic, 'hello should be in exotic');
1205 assert(!('foo' in exotic), 'foo should not be in exotic');
1206
1207 try {
1208 delete exotic.i;
1209 } catch(e) {
1210 if (e?.toString() !== 'Properties cannot be deleted') {
1211 throw new Error('wrong error message: ' + e?.toString());
1212 }
1213 }
1214
1215 let resp = []
1216 for (let [objKey, value] of exotic) {
1217 if (objKey !== 'i' && objKey !== 'hello') {
1218 throw new Error('only i and hello should be enumerable, got ' + objKey);
1219 }
1220 resp.push(`${objKey}:${value}`);
1221 }
1222
1223 assert(resp.toString() === 'hello:1292,i:43', `${resp.toString()} with length ${resp.length} should be [] as properties are not enumerable`);
1224
1225 // Test Object.getOwnPropertyNames() (uses get_own_property_names)
1226 let ownNames = Object.getOwnPropertyNames(exotic);
1227 assert(ownNames.length === 2, `getOwnPropertyNames should return 2, got ${ownNames.length}`);
1228 assert(ownNames.includes('hello'), 'getOwnPropertyNames should include hello');
1229 assert(ownNames.includes('i'), 'getOwnPropertyNames should include i');
1230
1231 // Test Object.keys() (uses get_own_property_names + get_own_property)
1232 let keys = Object.keys(exotic);
1233 assert(keys.length === 2, `Object.keys should return 2 keys, got ${keys.length}`);
1234
1235 // Test Object.getOwnPropertyDescriptor() (uses get_own_property)
1236 let desc = Object.getOwnPropertyDescriptor(exotic, 'hello');
1237 assert(desc !== undefined, 'descriptor for hello should exist');
1238 assert(desc.value === 'world', `descriptor value should be world, got ${desc.value}`);
1239 assert(desc.configurable === true, 'hello should be configurable');
1240 assert(desc.enumerable === true, 'hello should be enumerable');
1241 assert(desc.writable === false, 'hello should not be writable');
1242
1243 // Non-existent property returns undefined descriptor
1244 assert(Object.getOwnPropertyDescriptor(exotic, 'nonexistent') === undefined, 'nonexistent should be undefined');
1245
1246 exotic.hello
1247 ",
1248 )
1249 .catch(&ctx)
1250 .unwrap();
1251
1252 assert_eq!(v, "world");
1253 })
1254 }
1255}