rquickjs-core 0.12.0

High level bindings to the QuickJS JavaScript engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
//! JavaScript classes defined from Rust.

use crate::{
    function::Params,
    qjs::{self},
    value::Constructor,
    Atom, Ctx, Error, FromJs, IntoJs, JsLifetime, Object, Result, Value,
};
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::{hash::Hash, marker::PhantomData, mem, ops::Deref, ptr::NonNull};

mod cell;
mod trace;

pub(crate) mod ffi;

pub use cell::{
    Borrow, BorrowMut, JsCell, Mutability, OwnedBorrow, OwnedBorrowMut, Readable, Writable,
};
use ffi::{ClassCell, VTable};
pub use trace::{Trace, Tracer};
#[doc(hidden)]
pub mod impl_;

/// The kind of a JavaScript class.
///
/// A class can't be both callable and exotic, so this enum encodes that constraint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ClassKind {
    /// A regular class.
    Plain,
    /// A callable class (i.e. can be used as a function).
    Callable,
    /// An exotic class (i.e. has custom property access behavior).
    Exotic,
}

/// A JavaScript property descriptor returned from [`JsClass::exotic_get_own_property`].
pub struct PropertyDescriptor<'js> {
    /// The property value (for data descriptors).
    pub value: Value<'js>,
    /// The getter function (for accessor descriptors).
    pub getter: Value<'js>,
    /// The setter function (for accessor descriptors).
    pub setter: Value<'js>,
    /// Whether the property is configurable.
    pub configurable: bool,
    /// Whether the property is enumerable.
    pub enumerable: bool,
    /// Whether the property is writable (data descriptors only).
    pub writable: bool,
    /// Whether this is a getter/setter descriptor.
    pub is_getset: bool,
}

impl<'js> PropertyDescriptor<'js> {
    /// Create a simple value property descriptor.
    pub fn new_value(
        value: Value<'js>,
        configurable: bool,
        enumerable: bool,
        writable: bool,
    ) -> Self {
        let ctx = value.ctx().clone();
        PropertyDescriptor {
            value,
            getter: Value::new_undefined(ctx.clone()),
            setter: Value::new_undefined(ctx),
            configurable,
            enumerable,
            writable,
            is_getset: false,
        }
    }
}

/// A property name entry returned from [`JsClass::exotic_get_own_property_names`].
pub struct PropertyName<'js> {
    /// The atom identifying the property.
    pub atom: Atom<'js>,
    /// Whether this property is enumerable.
    pub is_enumerable: bool,
}

/// The trait which allows Rust types to be used from JavaScript.
pub trait JsClass<'js>: Trace<'js> + JsLifetime<'js> + Sized {
    /// The name the constructor has in JavaScript
    const NAME: &'static str;

    /// The kind of this class (plain, callable, or exotic).
    const KIND: ClassKind = ClassKind::Plain;

    /// Can the type be mutated while a JavaScript value.
    ///
    /// This should either be [`Readable`] or [`Writable`].
    type Mutable: Mutability;

    /// Returns the class prototype,
    fn prototype(ctx: &Ctx<'js>) -> Result<Option<Object<'js>>> {
        Object::new(ctx.clone()).map(Some)
    }

    /// Returns a predefined constructor for this specific class type if there is one.
    fn constructor(ctx: &Ctx<'js>) -> Result<Option<Constructor<'js>>>;

    /// The function which will be called if [`Self::KIND`] is [`ClassKind::Callable`] and an object with this
    /// class is called as if it is a function.
    fn call<'a>(this: &JsCell<'js, Self>, params: Params<'a, 'js>) -> Result<Value<'js>> {
        let _ = this;
        Ok(Value::new_undefined(params.ctx().clone()))
    }

    /// The function which will be called if a get property is performed on an object with this class
    fn exotic_get_property(
        this: &JsCell<'js, Self>,
        ctx: &Ctx<'js>,
        _atom: Atom<'js>,
        _receiver: Value<'js>,
    ) -> Result<Value<'js>> {
        let _ = this;
        Ok(Value::new_undefined(ctx.clone()))
    }

    /// The function which will be called if a set property is performed on an object with this class
    fn exotic_set_property(
        this: &JsCell<'js, Self>,
        _ctx: &Ctx<'js>,
        _atom: Atom<'js>,
        _receiver: Value<'js>,
        _value: Value<'js>,
    ) -> Result<bool> {
        let _ = this;
        Ok(false)
    }

    /// The function which will be called if a delete property is performed on an object with this class
    fn exotic_delete_property(
        this: &JsCell<'js, Self>,
        _ctx: &Ctx<'js>,
        _atom: Atom<'js>,
    ) -> Result<bool> {
        let _ = this;
        Ok(false)
    }

    /// The function which will be called if has property or similar is called on an object with this class
    fn exotic_has_property(
        this: &JsCell<'js, Self>,
        _ctx: &Ctx<'js>,
        _atom: Atom<'js>,
    ) -> Result<bool> {
        let _ = this;
        Ok(false)
    }

    /// Called to get the own property descriptor for a given property name.
    ///
    /// Return `Ok(Some(descriptor))` if the property exists, `Ok(None)` if it doesn't.
    fn exotic_get_own_property(
        this: &JsCell<'js, Self>,
        _ctx: &Ctx<'js>,
        _atom: Atom<'js>,
    ) -> Result<Option<PropertyDescriptor<'js>>> {
        let _ = this;
        Ok(None)
    }

    /// Called to enumerate the own property names of this object.
    ///
    /// Return a list of property names.
    fn exotic_get_own_property_names(
        this: &JsCell<'js, Self>,
        _ctx: &Ctx<'js>,
    ) -> Result<Vec<PropertyName<'js>>> {
        let _ = this;
        Ok(Vec::new())
    }
}

/// A object which is instance of a Rust class.
#[repr(transparent)]
pub struct Class<'js, C: JsClass<'js>>(pub(crate) Object<'js>, PhantomData<C>);

impl<'js, C: JsClass<'js>> Clone for Class<'js, C> {
    fn clone(&self) -> Self {
        Class(self.0.clone(), PhantomData)
    }
}

impl<'js, C: JsClass<'js>> PartialEq for Class<'js, C> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<'js, C: JsClass<'js>> Eq for Class<'js, C> {}

impl<'js, C: JsClass<'js>> Hash for Class<'js, C> {
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.0.hash(state)
    }
}

unsafe impl<'js, C> JsLifetime<'js> for Class<'js, C>
where
    C: JsClass<'js> + JsLifetime<'js>,
    for<'to> C::Changed<'to>: JsClass<'to>,
{
    type Changed<'to> = Class<'to, C::Changed<'to>>;
}

impl<'js, C: JsClass<'js>> Deref for Class<'js, C> {
    type Target = Object<'js>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'js, C: JsClass<'js>> Class<'js, C> {
    /// Create a class from a Rust object.
    pub fn instance(ctx: Ctx<'js>, value: C) -> Result<Class<'js, C>> {
        let id = unsafe { class_id::<C>(&ctx)? };

        let prototype = Self::prototype(&ctx)?;

        let prototype = prototype.map(|x| x.as_js_value()).unwrap_or(qjs::JS_NULL);
        let val = unsafe {
            ctx.handle_exception(qjs::JS_NewObjectProtoClass(ctx.as_ptr(), prototype, id))?
        };

        let ptr = Box::into_raw(Box::new(ClassCell::new(value)));
        unsafe { qjs::JS_SetOpaque(val, ptr.cast()) };
        Ok(Self(
            unsafe { Object::from_js_value(ctx, val) },
            PhantomData,
        ))
    }

    /// Create a class from a Rust object with a given prototype.
    pub fn instance_proto(value: C, proto: Object<'js>) -> Result<Class<'js, C>> {
        let id = unsafe { class_id::<C>(proto.ctx())? };

        let val = unsafe {
            proto.ctx.handle_exception(qjs::JS_NewObjectProtoClass(
                proto.ctx().as_ptr(),
                proto.0.as_js_value(),
                id,
            ))?
        };
        let ptr = Box::into_raw(Box::new(ClassCell::new(value)));
        unsafe { qjs::JS_SetOpaque(val, ptr.cast()) };
        Ok(Self(
            unsafe { Object::from_js_value(proto.ctx.clone(), val) },
            PhantomData,
        ))
    }

    /// Returns the prototype for the class.
    ///
    /// Returns `None` if the class is not yet registered or if the class doesn't have a prototype.
    pub fn prototype(ctx: &Ctx<'js>) -> Result<Option<Object<'js>>> {
        unsafe { ctx.get_opaque().get_or_insert_prototype::<C>(ctx) }
    }

    /// Create a constructor for the current class using its definition.
    pub fn create_constructor(ctx: &Ctx<'js>) -> Result<Option<Constructor<'js>>> {
        C::constructor(ctx)
    }

    /// Defines the predefined constructor of this class, if there is one, onto the given object.
    pub fn define(object: &Object<'js>) -> Result<()> {
        if let Some(constructor) = Self::create_constructor(object.ctx())? {
            object.set(C::NAME, constructor)?;
        }
        Ok(())
    }

    /// Returns a reference to the underlying object contained in a cell.
    #[inline]
    pub(crate) fn get_class_cell<'a>(&self) -> &'a ClassCell<JsCell<'js, C>> {
        unsafe { self.get_class_ptr().as_ref() }
    }

    /// Returns a reference to the underlying object contained in a cell.
    #[inline]
    pub fn get_cell<'a>(&self) -> &'a JsCell<'js, C> {
        &self.get_class_cell().data
    }

    /// Borrow the Rust class type.
    ///
    /// JavaScript classes behave similar to [`Rc`](std::rc::Rc) in Rust, you can essentially think
    /// of a class object as a `Rc<RefCell<C>>` and with similar borrowing functionality.
    ///
    /// # Panic
    /// This function panics if the class is already borrowed mutably.
    #[inline]
    pub fn borrow<'a>(&'a self) -> Borrow<'a, 'js, C> {
        self.get_cell().borrow()
    }

    /// Borrow the Rust class type mutably.
    ///
    /// JavaScript classes behave similar to [`Rc`](std::rc::Rc) in Rust, you can essentially think
    /// of a class object as a `Rc<RefCell<C>>` and with similar borrowing functionality.
    ///
    /// # Panic
    /// This function panics if the class is already borrowed mutably or immutably, or the Class
    /// can't be borrowed mutably.
    #[inline]
    pub fn borrow_mut<'a>(&'a self) -> BorrowMut<'a, 'js, C> {
        self.get_cell().borrow_mut()
    }

    /// Try to borrow the Rust class type.
    ///
    /// JavaScript classes behave similar to [`Rc`](std::rc::Rc) in Rust, you can essentially think
    /// of a class object as a `Rc<RefCell<C>>` and with similar borrowing functionality.
    ///
    /// This returns an error when the class is already borrowed mutably.
    #[inline]
    pub fn try_borrow<'a>(&'a self) -> Result<Borrow<'a, 'js, C>> {
        self.get_cell().try_borrow().map_err(Error::ClassBorrow)
    }

    /// Try to borrow the Rust class type mutably.
    ///
    /// JavaScript classes behave similar to [`Rc`](std::rc::Rc) in Rust, you can essentially think
    /// of a class object as a `Rc<RefCell<C>>` and with similar borrowing functionality.
    ///
    /// This returns an error when the class is already borrowed mutably, immutably or the class
    /// can't be borrowed mutably.
    #[inline]
    pub fn try_borrow_mut<'a>(&'a self) -> Result<BorrowMut<'a, 'js, C>> {
        self.get_cell().try_borrow_mut().map_err(Error::ClassBorrow)
    }

    /// returns a pointer to the class object.
    #[inline]
    pub(crate) fn get_class_ptr(&self) -> NonNull<ClassCell<JsCell<'js, C>>> {
        let id = unsafe { class_id::<C>(&self.ctx).expect("invalid class") };

        let ptr = unsafe { qjs::JS_GetOpaque2(self.0.ctx.as_ptr(), self.0 .0.as_js_value(), id) };

        NonNull::new(ptr.cast()).expect("invalid class object, object didn't have opaque value")
    }

    /// Turns the class back into a generic object.
    #[inline]
    pub fn into_inner(self) -> Object<'js> {
        self.0
    }

    /// Turns the class back into a generic object.
    #[inline]
    pub fn as_inner(&self) -> &Object<'js> {
        &self.0
    }

    /// Convert from value.
    #[inline]
    pub fn from_value(value: &Value<'js>) -> Result<Self> {
        if let Some(cls) = value.as_object().and_then(Self::from_object) {
            return Ok(cls);
        }
        Err(Error::FromJs {
            from: value.type_name(),
            to: C::NAME,
            message: None,
        })
    }

    /// Turn the class into a value.
    #[inline]
    pub fn into_value(self) -> Value<'js> {
        self.0.into_value()
    }

    /// Converts a generic object into a class if the object is of the right class.
    #[inline]
    pub fn from_object(object: &Object<'js>) -> Option<Self> {
        object.into_class().ok()
    }
}

impl<'js> Object<'js> {
    /// Returns if the object is of a certain Rust class.
    pub fn instance_of<C: JsClass<'js>>(&self) -> bool {
        let Ok(id) = (unsafe { class_id::<C>(&self.ctx) }) else {
            return false;
        };

        // This checks if the class is of the right class id.
        let Some(x) = NonNull::new(unsafe {
            qjs::JS_GetOpaque2(self.0.ctx.as_ptr(), self.0.as_js_value(), id)
        }) else {
            return false;
        };

        let v_table = unsafe { x.cast::<ClassCell<()>>().as_ref().v_table };

        // If the pointer is equal it must be of the right type, as the inclusion of a call to
        // generate a TypeId means that each type must have a unique v table.
        // however if it is not equal then it can still be the right type if the v_table is
        // duplicated, which is possible when compilation with multiple code-gen units.
        //
        // Doing check avoids a lookup and an dynamic function call in some cases.
        if core::ptr::eq(v_table, VTable::get::<C>()) {
            return true;
        }

        v_table.is_of_class::<C>()
    }

    /// Turn the object into the class if it is an instance of that class.
    pub fn into_class<C: JsClass<'js>>(&self) -> core::result::Result<Class<'js, C>, &Self> {
        if self.instance_of::<C>() {
            Ok(Class(self.clone(), PhantomData))
        } else {
            Err(self)
        }
    }

    /// Turn the object into the class if it is an instance of that class.
    pub fn as_class<C: JsClass<'js>>(&self) -> Option<&Class<'js, C>> {
        if self.instance_of::<C>() {
            // SAFETY:
            // Safe because class is a transparent wrapper
            unsafe { Some(mem::transmute::<&Object<'js>, &Class<'js, C>>(self)) }
        } else {
            None
        }
    }
}

impl<'js, C: JsClass<'js>> FromJs<'js> for Class<'js, C> {
    fn from_js(_ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
        Self::from_value(&value)
    }
}

impl<'js, C: JsClass<'js>> IntoJs<'js> for Class<'js, C> {
    fn into_js(self, _ctx: &Ctx<'js>) -> Result<Value<'js>> {
        Ok(self.0 .0)
    }
}

unsafe fn class_id<'js, C: JsClass<'js>>(ctx: &Ctx<'js>) -> Result<qjs::JSClassID> {
    match C::KIND {
        ClassKind::Plain => Ok(ctx.get_opaque().get_class_id()),
        ClassKind::Callable => Ok(ctx.get_opaque().get_callable_id()),
        ClassKind::Exotic => Ok(ctx.get_opaque().get_exotic_id()),
    }
}

#[cfg(test)]
mod test {
    use core::sync::atomic::AtomicI32;
    use std::sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    };

    use crate::{
        class::{ClassKind, JsClass, Readable, Trace, Tracer, Writable},
        function::This,
        test_with,
        value::Constructor,
        CatchResultExt, Class, Context, FromIteratorJs, FromJs, Function, IntoJs, JsLifetime,
        Object, Runtime,
    };

    /// Test circular references.
    #[test]
    fn trace() {
        pub struct Container<'js> {
            inner: Vec<Class<'js, Container<'js>>>,
            test: Arc<AtomicBool>,
        }

        impl<'js> Drop for Container<'js> {
            fn drop(&mut self) {
                self.test.store(true, Ordering::SeqCst);
            }
        }

        impl<'js> Trace<'js> for Container<'js> {
            fn trace<'a>(&self, tracer: Tracer<'a, 'js>) {
                self.inner.iter().for_each(|x| x.trace(tracer))
            }
        }

        unsafe impl<'js> JsLifetime<'js> for Container<'js> {
            type Changed<'to> = Container<'to>;
        }

        impl<'js> JsClass<'js> for Container<'js> {
            const NAME: &'static str = "Container";

            type Mutable = Writable;

            fn prototype(ctx: &crate::Ctx<'js>) -> crate::Result<Option<crate::Object<'js>>> {
                Ok(Some(Object::new(ctx.clone())?))
            }

            fn constructor(
                _ctx: &crate::Ctx<'js>,
            ) -> crate::Result<Option<crate::value::Constructor<'js>>> {
                Ok(None)
            }
        }

        let rt = Runtime::new().unwrap();
        let ctx = Context::full(&rt).unwrap();

        let drop_test = Arc::new(AtomicBool::new(false));

        ctx.with(|ctx| {
            let cls = Class::instance(
                ctx.clone(),
                Container {
                    inner: Vec::new(),
                    test: drop_test.clone(),
                },
            )
            .unwrap();

            assert!(cls.instance_of::<Container>());

            let cls_clone = cls.clone();
            cls.borrow_mut().inner.push(cls_clone);
        });
        rt.run_gc();
        assert!(drop_test.load(Ordering::SeqCst));
        ctx.with(|ctx| {
            let cls = Class::instance(
                ctx.clone(),
                Container {
                    inner: Vec::new(),
                    test: drop_test.clone(),
                },
            )
            .unwrap();
            let cls_clone = cls.clone();
            cls.borrow_mut().inner.push(cls_clone);
            ctx.globals().set("t", cls).unwrap();
        });
    }

    #[derive(Clone, Copy)]
    pub struct Vec3 {
        x: f32,
        y: f32,
        z: f32,
    }

    impl Vec3 {
        pub fn new(x: f32, y: f32, z: f32) -> Self {
            Vec3 { x, y, z }
        }

        pub fn add(self, v: Vec3) -> Self {
            Vec3 {
                x: self.x + v.x,
                y: self.y + v.y,
                z: self.z + v.z,
            }
        }
    }

    impl<'js> Trace<'js> for Vec3 {
        fn trace<'a>(&self, _tracer: Tracer<'a, 'js>) {}
    }

    impl<'js> FromJs<'js> for Vec3 {
        fn from_js(ctx: &crate::Ctx<'js>, value: crate::Value<'js>) -> crate::Result<Self> {
            Ok(*Class::<Vec3>::from_js(ctx, value)?.try_borrow()?)
        }
    }

    impl<'js> IntoJs<'js> for Vec3 {
        fn into_js(self, ctx: &crate::Ctx<'js>) -> crate::Result<crate::Value<'js>> {
            Class::instance(ctx.clone(), self).into_js(ctx)
        }
    }

    unsafe impl<'js> JsLifetime<'js> for Vec3 {
        type Changed<'to> = Vec3;
    }

    impl<'js> JsClass<'js> for Vec3 {
        const NAME: &'static str = "Vec3";

        type Mutable = Writable;

        fn prototype(ctx: &crate::Ctx<'js>) -> crate::Result<Option<crate::Object<'js>>> {
            let proto = Object::new(ctx.clone())?;
            let func = Function::new(ctx.clone(), |this: This<Vec3>, other: Vec3| this.add(other))?
                .with_name("add")?;

            proto.set("add", func)?;
            Ok(Some(proto))
        }

        fn constructor(
            ctx: &crate::Ctx<'js>,
        ) -> crate::Result<Option<crate::value::Constructor<'js>>> {
            let constr =
                Constructor::new_class::<Vec3, _, _>(ctx.clone(), |x: f32, y: f32, z: f32| {
                    Vec3::new(x, y, z)
                })?;

            Ok(Some(constr))
        }
    }

    #[test]
    fn constructor() {
        test_with(|ctx| {
            Class::<Vec3>::define(&ctx.globals()).unwrap();

            let v = ctx
                .eval::<Vec3, _>(
                    r"
                let a = new Vec3(1,2,3);
                let b = new Vec3(4,2,8);
                a.add(b)
            ",
                )
                .catch(&ctx)
                .unwrap();

            approx::assert_abs_diff_eq!(v.x, 5.0);
            approx::assert_abs_diff_eq!(v.y, 4.0);
            approx::assert_abs_diff_eq!(v.z, 11.0);

            let name: String = ctx.eval("new Vec3(1,2,3).constructor.name").unwrap();
            assert_eq!(name, Vec3::NAME);
        })
    }

    #[test]
    fn extend_class() {
        test_with(|ctx| {
            Class::<Vec3>::define(&ctx.globals()).unwrap();

            let v = ctx
                .eval::<Vec3, _>(
                    r"
                    class Vec4 extends Vec3 {
                        w = 0;
                        constructor(x,y,z,w){
                            super(x,y,z);
                            this.w
                        }
                    }

                    new Vec4(1,2,3,4);
                ",
                )
                .catch(&ctx)
                .unwrap();

            approx::assert_abs_diff_eq!(v.x, 1.0);
            approx::assert_abs_diff_eq!(v.y, 2.0);
            approx::assert_abs_diff_eq!(v.z, 3.0);
        })
    }

    #[test]
    fn get_prototype() {
        pub struct X;

        impl<'js> Trace<'js> for X {
            fn trace<'a>(&self, _tracer: Tracer<'a, 'js>) {}
        }

        unsafe impl<'js> JsLifetime<'js> for X {
            type Changed<'to> = X;
        }

        impl<'js> JsClass<'js> for X {
            const NAME: &'static str = "X";

            type Mutable = Readable;

            fn prototype(ctx: &crate::Ctx<'js>) -> crate::Result<Option<Object<'js>>> {
                let object = Object::new(ctx.clone())?;
                object.set("foo", "bar")?;
                Ok(Some(object))
            }

            fn constructor(_ctx: &crate::Ctx<'js>) -> crate::Result<Option<Constructor<'js>>> {
                Ok(None)
            }
        }

        test_with(|ctx| {
            let proto = Class::<X>::prototype(&ctx).unwrap().unwrap();
            assert_eq!(proto.get::<_, String>("foo").unwrap(), "bar")
        })
    }

    #[test]
    fn generic_types() {
        pub struct DebugPrinter<D: std::fmt::Debug> {
            d: D,
        }

        impl<'js, D: std::fmt::Debug> Trace<'js> for DebugPrinter<D> {
            fn trace<'a>(&self, _tracer: Tracer<'a, 'js>) {}
        }

        unsafe impl<'js, D: std::fmt::Debug + 'static> JsLifetime<'js> for DebugPrinter<D> {
            type Changed<'to> = DebugPrinter<D>;
        }

        impl<'js, D: std::fmt::Debug + 'static> JsClass<'js> for DebugPrinter<D> {
            const NAME: &'static str = "DebugPrinter";

            type Mutable = Readable;

            fn prototype(ctx: &crate::Ctx<'js>) -> crate::Result<Option<Object<'js>>> {
                let object = Object::new(ctx.clone())?;
                object.set(
                    "to_debug_string",
                    Function::new(
                        ctx.clone(),
                        |this: This<Class<DebugPrinter<D>>>| -> crate::Result<String> {
                            Ok(format!("{:?}", this.0.borrow().d))
                        },
                    ),
                )?;
                Ok(Some(object))
            }

            fn constructor(_ctx: &crate::Ctx<'js>) -> crate::Result<Option<Constructor<'js>>> {
                Ok(None)
            }
        }

        test_with(|ctx| {
            let a = Class::instance(ctx.clone(), DebugPrinter { d: 42usize });
            let b = Class::instance(
                ctx.clone(),
                DebugPrinter {
                    d: "foo".to_string(),
                },
            );

            ctx.globals().set("a", a).unwrap();
            ctx.globals().set("b", b).unwrap();

            assert_eq!(
                ctx.eval::<String, _>(r#" a.to_debug_string() "#)
                    .catch(&ctx)
                    .unwrap(),
                "42"
            );
            assert_eq!(
                ctx.eval::<String, _>(r#" b.to_debug_string() "#)
                    .catch(&ctx)
                    .unwrap(),
                "\"foo\""
            );

            if ctx
                .globals()
                .get::<_, Class<DebugPrinter<String>>>("a")
                .is_ok()
            {
                panic!("Conversion should fail")
            }
            if ctx
                .globals()
                .get::<_, Class<DebugPrinter<usize>>>("b")
                .is_ok()
            {
                panic!("Conversion should fail")
            }

            ctx.globals()
                .get::<_, Class<DebugPrinter<usize>>>("a")
                .unwrap();
            ctx.globals()
                .get::<_, Class<DebugPrinter<String>>>("b")
                .unwrap();
        })
    }

    #[test]
    fn exotic() {
        pub struct ExoticIterator {
            curr_state: Arc<AtomicI32>,
        }

        impl<'js> Trace<'js> for ExoticIterator {
            fn trace<'a>(&self, _tracer: Tracer<'a, 'js>) {}
        }

        unsafe impl<'js> JsLifetime<'js> for ExoticIterator {
            type Changed<'to> = ExoticIterator;
        }

        impl<'js> JsClass<'js> for ExoticIterator {
            const NAME: &'static str = "ExoticIterator";

            type Mutable = Readable;

            const KIND: ClassKind = ClassKind::Exotic;

            fn prototype(ctx: &crate::Ctx<'js>) -> crate::Result<Option<crate::Object<'js>>> {
                Ok(Some(crate::Object::new(ctx.clone())?))
            }

            fn constructor(
                _ctx: &crate::Ctx<'js>,
            ) -> crate::Result<Option<crate::value::Constructor<'js>>> {
                Ok(None)
            }

            fn exotic_get_property(
                this: &crate::class::JsCell<'js, Self>,
                ctx: &crate::Ctx<'js>,
                atom: crate::Atom<'js>,
                _receiver: crate::Value<'js>,
            ) -> crate::Result<crate::Value<'js>> {
                println!("Get property [iter]: {}", atom.to_string()?);
                if atom.to_string()? == "next" {
                    let state = this.borrow().curr_state.clone();
                    Ok(Function::new(ctx.clone(), move |ctx: crate::Ctx<'js>| {
                        // A really awful iterator thats implemented as a handwritten state machine
                        //
                        // Do not use this in production
                        if state.load(Ordering::SeqCst) <= 1 {
                            state.store(2, Ordering::SeqCst);

                            let val = crate::Object::from_iter_js(
                                &ctx,
                                [
                                    ("done", false.into_js(&ctx)?),
                                    ("value", vec!["hello", "1292"].into_js(&ctx)?),
                                ],
                            )?
                            .into_value();

                            Ok::<crate::Value<'_>, crate::Error>(val)
                        } else if state.load(Ordering::SeqCst) == 2 {
                            state.fetch_add(1, Ordering::SeqCst);

                            let val = crate::Object::from_iter_js(
                                &ctx,
                                [
                                    ("done", false.into_js(&ctx)?),
                                    (
                                        "value",
                                        vec!["i".into_js(&ctx)?, 43.into_js(&ctx)?]
                                            .into_js(&ctx)?,
                                    ),
                                ],
                            )?
                            .into_value();

                            Ok(val)
                        } else {
                            state.fetch_add(1, Ordering::SeqCst);

                            let val = crate::Object::from_iter_js(
                                &ctx,
                                [
                                    ("done", true.into_js(&ctx)?),
                                    ("value", crate::Value::new_undefined(ctx.clone())),
                                ],
                            )?
                            .into_value();

                            Ok(val)
                        }
                    })?
                    .into_value())
                } else {
                    Ok(crate::Value::new_undefined(ctx.clone()))
                }
            }

            fn exotic_has_property(
                this: &super::JsCell<'js, Self>,
                _ctx: &crate::Ctx<'js>,
                atom: crate::Atom<'js>,
            ) -> crate::Result<bool> {
                let _ = this;
                if atom.to_string()? == "next" {
                    return Ok(true);
                }

                Ok(false)
            }
        }

        #[derive(Clone)]
        pub struct Exotic {
            pub i: i32,
        }

        impl<'js> Trace<'js> for Exotic {
            fn trace<'a>(&self, _tracer: Tracer<'a, 'js>) {}
        }

        unsafe impl<'js> JsLifetime<'js> for Exotic {
            type Changed<'to> = Exotic;
        }

        impl<'js> JsClass<'js> for Exotic {
            const NAME: &'static str = "Exotic";

            type Mutable = Writable;

            const KIND: ClassKind = ClassKind::Exotic;

            fn prototype(ctx: &crate::Ctx<'js>) -> crate::Result<Option<crate::Object<'js>>> {
                Ok(Some(crate::Object::new(ctx.clone())?))
            }

            fn constructor(
                _ctx: &crate::Ctx<'js>,
            ) -> crate::Result<Option<crate::value::Constructor<'js>>> {
                Ok(None)
            }

            fn exotic_get_property(
                this: &crate::class::JsCell<'js, Self>,
                ctx: &crate::Ctx<'js>,
                atom: crate::Atom<'js>,
                _receiver: crate::Value<'js>,
            ) -> crate::Result<crate::Value<'js>> {
                let symbol_iterator = crate::Atom::from_predefined(
                    ctx.clone(),
                    crate::atom::PredefinedAtom::SymbolIterator,
                );
                println!("Get property: {}", atom.to_string()?);
                if atom.to_string()? == "hello" {
                    assert!(this.borrow().i == 42);
                    Ok("world".into_js(ctx)?)
                } else if atom.to_string()? == "toString" {
                    Ok(Function::new(ctx.clone(), || {
                        let f = "class Exotic { [native code] }";
                        Ok::<&'static str, crate::Error>(f)
                    })?
                    .into_value())
                } else if atom == symbol_iterator {
                    println!("Getting iterator");
                    let exotic = Class::<ExoticIterator>::instance(
                        ctx.clone(),
                        ExoticIterator {
                            curr_state: Arc::default(),
                        },
                    )?;
                    println!("Returning ExoticIterator");
                    Ok(Function::new(ctx.clone(), move || {
                        Ok::<crate::Value<'_>, crate::Error>(exotic.clone().into_value())
                    })?
                    .into_value())
                } else {
                    Ok(crate::Value::new_null(ctx.clone()))
                }
            }

            fn exotic_set_property(
                this: &super::JsCell<'js, Self>,
                ctx: &crate::Ctx<'js>,
                atom: crate::Atom<'js>,
                _receiver: crate::Value<'js>,
                _value: crate::Value<'js>,
            ) -> crate::Result<bool> {
                let _ = this;
                if atom.to_string()? == "i" {
                    let Some(new_i) = _value.as_int() else {
                        let err_val = crate::String::from_str(ctx.clone(), "i must be an integer")?
                            .into_value();
                        return Err(ctx.throw(err_val));
                    };
                    this.borrow_mut().i = new_i;
                    return Ok(true);
                }
                let err_val =
                    crate::String::from_str(ctx.clone(), "Properties are read-only")?.into_value();
                Err(ctx.throw(err_val))
            }

            fn exotic_has_property(
                this: &super::JsCell<'js, Self>,
                _ctx: &crate::Ctx<'js>,
                atom: crate::Atom<'js>,
            ) -> crate::Result<bool> {
                let _ = this;
                println!("Got atom: {}", atom.to_string()?);
                if atom.to_string()? == "hello"
                    || atom.to_string()? == "i"
                    || atom.to_string()? == "toString"
                {
                    return Ok(true);
                }

                Ok(false)
            }

            fn exotic_delete_property(
                _this: &super::JsCell<'js, Self>,
                ctx: &crate::Ctx<'js>,
                _atom: crate::Atom<'js>,
            ) -> crate::Result<bool> {
                let err_val = crate::String::from_str(ctx.clone(), "Properties cannot be deleted")?
                    .into_value();
                Err(ctx.throw(err_val))
            }

            fn exotic_get_own_property(
                this: &super::JsCell<'js, Self>,
                ctx: &crate::Ctx<'js>,
                atom: crate::Atom<'js>,
            ) -> crate::Result<Option<super::PropertyDescriptor<'js>>> {
                let name = atom.to_string()?;
                if name == "hello" || name == "i" {
                    let value = if name == "hello" {
                        "world".into_js(ctx)?
                    } else {
                        this.borrow().i.into_js(ctx)?
                    };
                    Ok(Some(super::PropertyDescriptor::new_value(
                        value, true, true, false,
                    )))
                } else {
                    Ok(None)
                }
            }

            fn exotic_get_own_property_names(
                _this: &super::JsCell<'js, Self>,
                ctx: &crate::Ctx<'js>,
            ) -> crate::Result<Vec<super::PropertyName<'js>>> {
                Ok(vec![
                    super::PropertyName {
                        atom: crate::Atom::from_str(ctx.clone(), "hello")?,
                        is_enumerable: true,
                    },
                    super::PropertyName {
                        atom: crate::Atom::from_str(ctx.clone(), "i")?,
                        is_enumerable: true,
                    },
                ])
            }
        }

        test_with(|ctx| {
            let exotic = Class::<Exotic>::instance(ctx.clone(), Exotic { i: 0 }).unwrap();
            ctx.globals().set("exotic", exotic).unwrap();
            ctx.globals()
                .set(
                    "assert",
                    Function::new(
                        ctx.clone(),
                        |ctx: crate::Ctx<'_>, cond: bool, msg: String| {
                            if !cond {
                                let err_val =
                                    crate::String::from_str(ctx.clone(), &msg)?.into_value();
                                return Err(ctx.throw(err_val));
                            }
                            Ok(())
                        },
                    ),
                )
                .unwrap();

            let v = ctx
                .eval::<String, _>(
                    r"
                if(exotic.foo !== null) {
                    throw new Error('foo should be null');
                }
                try {
                    exotic.foo = 1
                } catch(e) {
                    if (e?.toString() !== 'Properties are read-only') {
                        throw new Error('wrong error message: ' + e?.toString());
                    }
                }
                if (exotic.foo !== null) {
                    throw new Error('foo should be null');
                }
                exotic.i = 42;
                if (exotic.hello === 42) {
                    throw new Error('i should be 42');
                }
                assert(exotic?.toString() === 'class Exotic { [native code] }', `exotic.toString() should be 'class Exotic { [native code] }' but is ${exotic?.toString()}`);
                assert('i' in exotic, 'i should be in exotic');
                assert('hello' in exotic, 'hello should be in exotic');
                assert(!('foo' in exotic), 'foo should not be in exotic');

                try {
                    delete exotic.i;
                } catch(e) {
                    if (e?.toString() !== 'Properties cannot be deleted') {
                        throw new Error('wrong error message: ' + e?.toString());
                    }
                }

                let resp = []
                for (let [objKey, value] of exotic) {
                    if (objKey !== 'i' && objKey !== 'hello') {
                        throw new Error('only i and hello should be enumerable, got ' + objKey);
                    }
                    resp.push(`${objKey}:${value}`);
                }

                assert(resp.toString() === 'hello:1292,i:43', `${resp.toString()} with length ${resp.length} should be [] as properties are not enumerable`);

                // Test Object.getOwnPropertyNames() (uses get_own_property_names)
                let ownNames = Object.getOwnPropertyNames(exotic);
                assert(ownNames.length === 2, `getOwnPropertyNames should return 2, got ${ownNames.length}`);
                assert(ownNames.includes('hello'), 'getOwnPropertyNames should include hello');
                assert(ownNames.includes('i'), 'getOwnPropertyNames should include i');

                // Test Object.keys() (uses get_own_property_names + get_own_property)
                let keys = Object.keys(exotic);
                assert(keys.length === 2, `Object.keys should return 2 keys, got ${keys.length}`);

                // Test Object.getOwnPropertyDescriptor() (uses get_own_property)
                let desc = Object.getOwnPropertyDescriptor(exotic, 'hello');
                assert(desc !== undefined, 'descriptor for hello should exist');
                assert(desc.value === 'world', `descriptor value should be world, got ${desc.value}`);
                assert(desc.configurable === true, 'hello should be configurable');
                assert(desc.enumerable === true, 'hello should be enumerable');
                assert(desc.writable === false, 'hello should not be writable');

                // Non-existent property returns undefined descriptor
                assert(Object.getOwnPropertyDescriptor(exotic, 'nonexistent') === undefined, 'nonexistent should be undefined');

                exotic.hello
            ",
                )
                .catch(&ctx)
                .unwrap();

            assert_eq!(v, "world");
        })
    }
}