quickjs-pure 0.14.4

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
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
//! Host classes: the engine's half of `JS_NewClass`, `JS_SetOpaque` and
//! `JSClassExoticMethods`.
//!
//! Every assertion here is about something a wrapping C API cannot fix on its own, which is
//! why it is tested at the engine level rather than against a `.so`:
//!
//! * the finalizer runs **exactly once**, on the refcount path and on the collector path;
//! * the opaque payload comes back as the same pointer, and only for its own class;
//! * the exotic traps are what `[[Get]]`, `in`, `delete`, `Object.defineProperty` and the
//!   prototype operations actually consult;
//! * `gc_mark` is what keeps a value reachable *through* an opaque pointer, and without it a
//!   cycle closed through one is immortal.
//!
//! # Why the payloads are `Rc`
//!
//! `point.c` finalizes by calling `js_free_rt(rt, JS_GetOpaque(val, id))`, i.e. freeing the
//! pointer. Reproducing that here would need `unsafe` (`Rc::from_raw`), and this file has to
//! stay out of `unsafe` to keep `scripts/check-unsafe.sh` meaningful — a test is no reason
//! to widen the gate. So the engine's ownership is modelled with a strong reference the
//! finalizer releases instead: the same lifetime contract (exactly one release, on exactly
//! one thread of control), checked with [`Rc::strong_count`] rather than a freed pointer.

use std::cell::{Cell, RefCell};
use std::rc::Rc;

use quickjs::interp::{Interp, JsResult};
use quickjs::object::{ClassDef, ClassId, Exotic, JsObject, Opaque, Property, PropertyKey};
use quickjs::{Context, Gc, Runtime, Trace, Value};

/// The engine's view of a host payload: one strong reference, released by the finalizer.
type Payload = Rc<Cell<i32>>;

fn payload(value: i32) -> Payload {
    Rc::new(Cell::new(value))
}

/// The pointer form of a payload. Safe to take because the test keeps the `Rc` alive, and
/// stable because an `Rc`'s pointee does not move.
fn opaque_of(payload: &Payload) -> Opaque {
    Opaque::new(Rc::as_ptr(payload).cast_mut().cast::<()>())
}

/// A finalizer the test can inspect afterwards: how many times it ran, and what it was
/// handed. It also releases the engine's strong reference to the payload, which is
/// `js_free_rt`'s job.
#[derive(Clone, Default)]
struct Finalizer {
    calls: Rc<Cell<u32>>,
    seen: Rc<RefCell<Vec<Opaque>>>,
    owned: Rc<RefCell<Option<Payload>>>,
}

impl Finalizer {
    /// A class definition whose finalizer is this recorder.
    fn class(&self, name: &str) -> ClassDef {
        let calls = self.calls.clone();
        let seen = self.seen.clone();
        let owned = self.owned.clone();
        ClassDef::new(name).with_finalizer(move |_id, opaque| {
            calls.set(calls.get() + 1);
            seen.borrow_mut().push(opaque);
            drop(owned.borrow_mut().take());
        })
    }

    /// Record the engine's reference to `payload` as the one the finalizer should release.
    fn own(&self, payload: &Payload) {
        *self.owned.borrow_mut() = Some(payload.clone());
    }

    fn calls(&self) -> u32 {
        self.calls.get()
    }

    /// The class registered by `ctx`.
    fn register(self: &Rc<Self>, ctx: &mut Context<'_>, name: &str) -> ClassId {
        ctx.register_class(self.class(name))
    }
}

// ---------------------------------------------------------------------------
// The finalizer runs exactly once
// ---------------------------------------------------------------------------

#[test]
fn finalizer_runs_once_when_the_last_reference_dies() {
    let runtime = Runtime::new();
    let mut ctx = Context::new(&runtime);
    let fin = Rc::new(Finalizer::default());
    let id = fin.register(&mut ctx, "Point");

    let point = payload(7);
    fin.own(&point);
    let object = ctx.new_class_instance(id, None).expect("registered class");
    assert!(ctx.set_class_opaque(&object, opaque_of(&point)));

    // Two handles on one object: neither dropping alone may finalize it.
    let second = object.clone();
    assert_eq!(fin.calls(), 0, "a live instance must not be finalized");
    drop(object);
    assert_eq!(fin.calls(), 0, "one handle left, so still live");

    drop(second);
    assert_eq!(fin.calls(), 1, "the last handle finalizes exactly once");
    assert_eq!(
        fin.seen.borrow().as_slice(),
        [opaque_of(&point)],
        "the finalizer is handed the payload the object carried"
    );
    // The engine released its reference and the test's is the only one left: the finalizer
    // ran, and it ran on the right payload.
    assert_eq!(Rc::strong_count(&point), 1);
}

#[test]
fn finalizer_runs_once_per_instance() {
    let runtime = Runtime::new();
    let mut ctx = Context::new(&runtime);
    let fin = Rc::new(Finalizer::default());
    let id = fin.register(&mut ctx, "Point");

    let objects: Vec<Value> = (0..3)
        .map(|i| {
            let point = payload(i);
            fin.own(&point);
            let object = ctx.new_class_instance(id, None).expect("registered class");
            ctx.set_class_opaque(&object, opaque_of(&point));
            object
        })
        .collect();
    assert_eq!(fin.calls(), 0);
    drop(objects);
    assert_eq!(fin.calls(), 3, "one call per instance, no more");
}

#[test]
fn finalizer_runs_when_the_collector_reclaims_a_cycle() {
    // The reference implementation runs `JSClassDef::finalizer` at both release points: the
    // last reference going away, and the cycle collector. This is the second one.
    let runtime = Runtime::new();
    let mut ctx = Context::new(&runtime);
    let fin = Rc::new(Finalizer::default());
    let id = fin.register(&mut ctx, "Point");

    let point = payload(1);
    fin.own(&point);
    let outer = ctx.new_class_instance(id, None).expect("registered class");
    ctx.set_class_opaque(&outer, opaque_of(&point));
    let inner = ctx.new_object();
    // A cycle that never leaves the heap: `inner` points back at `outer`, and `outer`
    // reaches `inner` only through its opaque payload.
    ctx.set_property(&inner, "host", outer.clone()).unwrap();

    assert_eq!(fin.calls(), 0);
    // Reachable from the Rust side, so neither may be reclaimed yet.
    runtime.run_gc();
    assert_eq!(fin.calls(), 0, "a live cycle is not garbage");

    drop(outer);
    drop(inner);
    runtime.run_gc();
    assert_eq!(fin.calls(), 1, "the collector finalizes what it reclaims");
}

#[test]
fn an_instance_without_a_payload_still_finalizes() {
    // `point.c`'s finalizer carries a note that `JS_GetOpaque` may be null because
    // `JS_SetOpaque` never ran; the class has to be finalized all the same.
    let runtime = Runtime::new();
    let mut ctx = Context::new(&runtime);
    let fin = Rc::new(Finalizer::default());
    let id = fin.register(&mut ctx, "Point");

    let object = ctx.new_class_instance(id, None).expect("registered class");
    assert_eq!(ctx.class_opaque(&object, id), Some(Opaque::NULL));
    drop(object);
    assert_eq!(fin.calls(), 1);
    assert_eq!(fin.seen.borrow().as_slice(), [Opaque::NULL]);
}

// ---------------------------------------------------------------------------
// The opaque payload
// ---------------------------------------------------------------------------

#[test]
fn opaque_round_trips_as_the_same_pointer() {
    let runtime = Runtime::new();
    let mut ctx = Context::new(&runtime);
    let fin = Rc::new(Finalizer::default());
    let id = fin.register(&mut ctx, "Point");

    let point = payload(7);
    fin.own(&point);
    let object = ctx.new_class_instance(id, None).expect("registered class");
    assert!(ctx.set_class_opaque(&object, opaque_of(&point)));

    let back = ctx.class_opaque(&object, id).expect("it is a Point");
    assert!(
        std::ptr::eq(back.as_ptr().cast_const(), Rc::as_ptr(&point).cast()),
        "the payload must come back as the pointer it was given"
    );
    assert_eq!(back, opaque_of(&point));
}

#[test]
fn opaque_is_class_scoped() {
    let runtime = Runtime::new();
    let mut ctx = Context::new(&runtime);
    let fin = Rc::new(Finalizer::default());
    let point_id = fin.register(&mut ctx, "Point");
    // A second class with the same shape: the ids are what keep them apart, not the pointer
    // and not the name.
    let other_id = fin.register(&mut ctx, "Point");
    assert_ne!(point_id, other_id);

    let point = payload(7);
    fin.own(&point);
    let object = ctx
        .new_class_instance(point_id, None)
        .expect("registered class");
    assert!(ctx.set_class_opaque(&object, opaque_of(&point)));

    assert!(ctx.class_opaque(&object, point_id).is_some());
    assert!(
        ctx.class_opaque(&object, other_id).is_none(),
        "another class must not see this payload"
    );
    let plain = ctx.new_object();
    assert!(
        ctx.class_opaque(&plain, point_id).is_none(),
        "an ordinary object is not an instance of any host class"
    );
    // Nor is a host instance of one class an instance of another.
    let other = ctx.new_class_instance(other_id, None).expect("registered");
    assert!(ctx.class_opaque(&other, point_id).is_none());
}

#[test]
fn unset_opaque_is_null_and_settable_later() {
    let runtime = Runtime::new();
    let mut ctx = Context::new(&runtime);
    let fin = Rc::new(Finalizer::default());
    let id = fin.register(&mut ctx, "Point");

    let object = ctx.new_class_instance(id, None).expect("registered class");
    assert_eq!(ctx.class_opaque(&object, id), Some(Opaque::NULL));

    let point = payload(1);
    fin.own(&point);
    assert!(ctx.set_class_opaque(&object, opaque_of(&point)));
    assert!(
        ctx.class_opaque(&object, id)
            .is_some_and(|it| !it.is_null())
    );
}

#[test]
fn an_unregistered_class_has_no_instances() {
    let runtime = Runtime::new();
    let mut ctx = Context::new(&runtime);
    let never = ClassId::from_raw(999);
    assert!(ctx.new_class_instance(never, None).is_err());
    // Id 0 is `JS_INVALID_CLASS_ID`: it must never name a class, not even the first one
    // that was registered.
    assert!(!ClassId::INVALID.is_valid());
    let _ = ctx.register_class(ClassDef::new("first"));
    assert!(ctx.new_class_instance(ClassId::INVALID, None).is_err());
}

#[test]
fn class_ids_start_at_one_and_do_not_repeat() {
    let runtime = Runtime::new();
    let mut ctx = Context::new(&runtime);
    let first = ctx.register_class(ClassDef::new("a"));
    let second = ctx.register_class(ClassDef::new("b"));
    assert_eq!(first.get(), 1, "id 0 is reserved for JS_INVALID_CLASS_ID");
    assert_eq!(second.get(), 2);
}

#[test]
fn instances_inherit_the_registered_prototype() {
    let runtime = Runtime::new();
    let mut ctx = Context::new(&runtime);
    let id = ctx.register_class(ClassDef::new("Point"));

    let proto = ctx.new_object();
    let kind = ctx.new_string("point");
    ctx.set_property(&proto, "kind", kind).unwrap();
    ctx.set_class_proto(id, &proto).unwrap();
    ctx.set_global("Point", proto).unwrap();

    let object = ctx.new_class_instance(id, None).expect("registered class");
    ctx.set_global("p", object).unwrap();
    assert_eq!(
        ctx.eval("p.kind + '/' + (Object.getPrototypeOf(p) === Point)")
            .unwrap()
            .to_js_string(),
        "point/true"
    );

    // An explicit prototype wins, which is what `new.target.prototype` is for.
    let subclass = ctx.new_object();
    let kind = ctx.new_string("sub");
    ctx.set_property(&subclass, "kind", kind).unwrap();
    let derived = ctx
        .new_class_instance(id, Some(&subclass))
        .expect("registered");
    ctx.set_global("d", derived).unwrap();
    assert_eq!(ctx.eval("d.kind").unwrap().to_js_string(), "sub");
    // The prototype the host passed is the *prototype*, not the class's registered one.
    assert_eq!(
        ctx.eval("Object.getPrototypeOf(d) === Point")
            .unwrap()
            .to_js_string(),
        "false"
    );
}

#[test]
fn a_host_object_is_an_ordinary_object_to_the_rest_of_the_language() {
    let runtime = Runtime::new();
    let mut ctx = Context::new(&runtime);
    let id = ctx.register_class(ClassDef::new("Point"));
    let object = ctx.new_class_instance(id, None).expect("registered class");
    ctx.set_global("p", object).unwrap();
    // The reference answers `[object Object]` for a host object, not `[object Point]`: its
    // `Object.prototype.toString` names only the built-in class ids. Checked against
    // `qjs -m` with `examples/point.c` built as a module.
    assert_eq!(
        ctx.eval("[typeof p, Object.prototype.toString.call(p), JSON.stringify(p)].join()")
            .unwrap()
            .to_js_string(),
        "object,[object Object],{}"
    );
    // A host object is extensible and takes ordinary properties like any other object.
    assert_eq!(
        ctx.eval("p.z = 1; Object.isExtensible(p) + '/' + p.z")
            .unwrap()
            .to_js_string(),
        "true/1"
    );
}

// ---------------------------------------------------------------------------
// The exotic traps
// ---------------------------------------------------------------------------

/// A class with one virtual own property, `answer`, that exists nowhere in a property
/// table: the traps are the only reason it can be seen at all.
struct Answer {
    /// How many times the write trap was asked.
    writes: Rc<Cell<u32>>,
    /// The prototype the `get_prototype` trap reports.
    proto: RefCell<Option<Value>>,
    /// Whether the class answers `has_property` for every string key or only its own.
    /// `true` is the shape a native proxy has; `false` leaves the rest to the property
    /// table.
    opinionated: bool,
}

impl Exotic for Answer {
    fn get_own_property(
        &self,
        _interp: &mut Interp<'_>,
        _object: &Gc<JsObject>,
        key: &PropertyKey,
    ) -> JsResult<Option<Option<Property>>> {
        if key.as_str() != Some("answer") {
            return Ok(None);
        }
        Ok(Some(Some(Property {
            value: Some(Value::Int(42)),
            writable: true,
            enumerable: true,
            configurable: true,
            getter: None,
            setter: None,
        })))
    }

    fn has_property(
        &self,
        _interp: &mut Interp<'_>,
        _object: &Gc<JsObject>,
        key: &PropertyKey,
    ) -> JsResult<Option<bool>> {
        match key.as_str() {
            Some("answer") => Ok(Some(true)),
            // A class that answers every key has to answer `false` for the ones it does not
            // have; falling through would be indistinguishable from not implementing `has`.
            Some(_) if self.opinionated => Ok(Some(false)),
            _ => Ok(None),
        }
    }

    fn set_property(
        &self,
        _interp: &mut Interp<'_>,
        _object: &Gc<JsObject>,
        key: &PropertyKey,
        _value: &Value,
        _receiver: &Value,
    ) -> JsResult<Option<bool>> {
        if key.as_str() != Some("answer") {
            return Ok(None);
        }
        self.writes.set(self.writes.get() + 1);
        // Read-only, the way a native accessor with no setter is.
        Ok(Some(false))
    }

    fn delete_property(
        &self,
        _interp: &mut Interp<'_>,
        _object: &Gc<JsObject>,
        key: &PropertyKey,
    ) -> JsResult<Option<bool>> {
        match key.as_str() {
            Some("answer") => Ok(Some(false)),
            _ => Ok(None),
        }
    }

    fn get_prototype(
        &self,
        _interp: &mut Interp<'_>,
        _object: &Gc<JsObject>,
    ) -> JsResult<Option<Option<Gc<JsObject>>>> {
        let remembered = self.proto.borrow();
        let Some(value) = remembered.as_ref() else {
            return Ok(None);
        };
        Ok(Some(value.as_object().cloned()))
    }
}

/// Install an `Answer` class, returning its id and the state the test can inspect.
fn install_answer(ctx: &mut Context<'_>, opinionated: bool) -> (ClassId, Rc<Answer>) {
    let answer = Rc::new(Answer {
        writes: Rc::new(Cell::new(0)),
        proto: RefCell::new(None),
        opinionated,
    });
    let id = ctx.register_class(ClassDef::new("Answer").with_exotic(answer.clone()));
    (id, answer)
}

#[test]
fn exotic_get_and_own_property_are_consulted() {
    let runtime = Runtime::new();
    let mut ctx = Context::new(&runtime);
    let (id, _) = install_answer(&mut ctx, false);
    let object = ctx.new_class_instance(id, None).expect("registered class");
    ctx.set_global("a", object).unwrap();

    assert_eq!(
        ctx.eval("a.answer + '/' + ('answer' in a)")
            .unwrap()
            .to_js_string(),
        "42/true"
    );
    // The descriptor comes from `get_own_property`, so `Object.getOwnPropertyDescriptor`
    // and `Object.hasOwn` see the same properties a read does.
    assert_eq!(
        ctx.eval("Object.getOwnPropertyDescriptor(a, 'answer').value")
            .unwrap()
            .to_js_string(),
        "42"
    );
    assert_eq!(
        ctx.eval("Object.hasOwn(a, 'answer')")
            .unwrap()
            .to_js_string(),
        "true"
    );
    // A key the trap has no opinion about behaves ordinarily: it is simply absent.
    assert_eq!(
        ctx.eval("Object.hasOwn(a, 'nope')").unwrap().to_js_string(),
        "false"
    );
    assert_eq!(
        ctx.eval("a.missing === undefined").unwrap().to_js_string(),
        "true"
    );
}

/// A class that implements **only** `get_own_property`. The reference's `JS_HasProperty`
/// asks `JS_GetOwnPropertyInternal`, so `in` and `Object.hasOwn` reach the hook even with no
/// `has_property` trap; a hand-built C module with this exact shape answers `true`, `true`
/// and `42` for `'x' in o`, `Object.hasOwn(o, 'x')` and `o.x`.
struct OnlyOwn;

impl Exotic for OnlyOwn {
    fn get_own_property(
        &self,
        _interp: &mut Interp<'_>,
        _object: &Gc<JsObject>,
        key: &PropertyKey,
    ) -> JsResult<Option<Option<Property>>> {
        if key.as_str() != Some("x") {
            return Ok(None);
        }
        Ok(Some(Some(Property::data(Value::Int(42)))))
    }
}

/// A class that reports `x` as an own, read-only data property through
/// `get_own_property` and nothing else.
///
/// The reference's `JS_SetPropertyInternal` asks the `set_property` trap — absent here — and
/// then `JS_GetOwnPropertyInternal` for the descriptor, so the write is refused by the
/// attribute rather than creating a shadowing own property. `qjs -m` on a hand-built module
/// of this shape answers `TypeError: 'answer' is read-only`.
struct ReadOnly;

impl Exotic for ReadOnly {
    fn get_own_property(
        &self,
        _interp: &mut Interp<'_>,
        _object: &Gc<JsObject>,
        key: &PropertyKey,
    ) -> JsResult<Option<Option<Property>>> {
        if key.as_str() != Some("x") {
            return Ok(None);
        }
        Ok(Some(Some(Property {
            value: Some(Value::Int(42)),
            writable: false,
            enumerable: true,
            configurable: true,
            getter: None,
            setter: None,
        })))
    }
}

#[test]
fn get_own_property_alone_makes_a_write_read_only() {
    let runtime = Runtime::new();
    let mut ctx = Context::new(&runtime);
    let id = ctx.register_class(ClassDef::new("ReadOnly").with_exotic(Rc::new(ReadOnly)));
    let object = ctx.new_class_instance(id, None).unwrap();
    ctx.set_global("o", object).unwrap();

    // Sloppy mode: silent, and no shadowing own property appears.
    assert_eq!(
        ctx.eval("o.x = 9; [o.x, Object.hasOwn(o, 'x'), Object.getOwnPropertyDescriptor(o, 'x').value].join()")
            .unwrap()
            .to_js_string(),
        "42,true,42"
    );
    let error = ctx.eval_strict("o.x = 9").unwrap_err().to_string();
    assert!(error.contains("TypeError"), "{error}");
    assert!(error.contains("read-only"), "{error}");
}

#[test]
fn get_own_property_alone_answers_in_and_has_own() {
    let runtime = Runtime::new();
    let mut ctx = Context::new(&runtime);
    let id = ctx.register_class(ClassDef::new("OnlyOwn").with_exotic(Rc::new(OnlyOwn)));
    let object = ctx.new_class_instance(id, None).unwrap();
    ctx.set_global("o", object).unwrap();
    assert_eq!(
        ctx.eval("['x' in o, Object.hasOwn(o, 'x'), o.x, 'y' in o].join()")
            .unwrap()
            .to_js_string(),
        "true,true,42,false"
    );
}

#[test]
fn exotic_has_property_answers_every_key_a_class_claims() {
    let runtime = Runtime::new();
    let mut ctx = Context::new(&runtime);
    let (id, _) = install_answer(&mut ctx, true);
    let object = ctx.new_class_instance(id, None).expect("registered class");
    ctx.set_global("a", object).unwrap();
    // `in` is the trap's answer even for a key no property table holds, in both directions.
    assert_eq!(
        ctx.eval("['answer' in a, 'nope' in a, Symbol.iterator in a].join()")
            .unwrap()
            .to_js_string(),
        "true,false,false"
    );
}

#[test]
fn exotic_set_and_delete_decide() {
    let runtime = Runtime::new();
    let mut ctx = Context::new(&runtime);
    let (id, answer) = install_answer(&mut ctx, false);
    let object = ctx.new_class_instance(id, None).unwrap();
    ctx.set_global("a", object).unwrap();

    // Sloppy mode: a refusal is silent, and the value never lands.
    assert_eq!(
        ctx.eval("a.answer = 1; a.answer").unwrap().to_js_string(),
        "42"
    );
    assert_eq!(answer.writes.get(), 1, "the trap saw the write");
    // Strict mode: the same refusal is a TypeError.
    let error = ctx.eval_strict("a.answer = 1").unwrap_err().to_string();
    assert!(error.contains("TypeError"), "{error}");
    assert_eq!(answer.writes.get(), 2);

    // `delete` answers the trap's `false` rather than removing anything.
    assert_eq!(ctx.eval("delete a.answer").unwrap().to_js_string(), "false");
    assert_eq!(ctx.eval("a.answer").unwrap().to_js_string(), "42");

    // A key the trap declines is written and deleted ordinarily.
    assert_eq!(
        ctx.eval("a.plain = 1; [a.plain, delete a.plain, 'plain' in a].join()")
            .unwrap()
            .to_js_string(),
        "1,true,false"
    );
}

#[test]
fn exotic_get_prototype_is_consulted() {
    let runtime = Runtime::new();
    let mut ctx = Context::new(&runtime);
    let (id, answer) = install_answer(&mut ctx, false);
    let object = ctx.new_class_instance(id, None).unwrap();
    ctx.set_global("a", object).unwrap();

    let target = ctx.new_object();
    let tag = ctx.new_string("from-trap");
    ctx.set_property(&target, "tag", tag).unwrap();
    ctx.set_global("target", target.clone()).unwrap();
    *answer.proto.borrow_mut() = Some(target);

    assert_eq!(
        ctx.eval("Object.getPrototypeOf(a) === target")
            .unwrap()
            .to_js_string(),
        "true"
    );
    // The trap answers `[[GetPrototypeOf]]` and nothing else: a *read* walks the stored
    // prototype, so `a.tag` is `undefined` even though the reported prototype has a `tag`.
    //
    // That is the reference's behaviour, not an oversight here: `JS_GetPropertyInternal`
    // walks `p->shape->proto` and never calls the `get_prototype` exotic (quickjs.c:8612),
    // and a hand-built module with only these two exotic methods confirms it —
    // `Object.getPrototypeOf(o) === target` is `true` while `o.tag` is `undefined`. A class
    // that wants reads to follow its virtual prototype has to implement `get_property`.
    assert_eq!(
        ctx.eval("String(a.tag)").unwrap().to_js_string(),
        "undefined"
    );

    // The trap is a property of the *class*, so every instance reports the same prototype.
    let bare = ctx.new_class_instance(id, None).unwrap();
    ctx.set_global("b", bare).unwrap();
    assert_eq!(
        ctx.eval("Object.getPrototypeOf(b) === target")
            .unwrap()
            .to_js_string(),
        "true"
    );
}

#[test]
fn exotic_define_own_property_is_consulted() {
    let runtime = Runtime::new();
    let mut ctx = Context::new(&runtime);
    let id = ctx.register_class(ClassDef::new("NoDefine").with_exotic(Rc::new(RefuseDefine)));
    let object = ctx.new_class_instance(id, None).unwrap();
    ctx.set_global("n", object).unwrap();

    // Refusing `defineProperty` has to make the whole operation fail, not fall through to
    // the property table.
    assert_eq!(
        ctx.eval("try { Object.defineProperty(n, 'x', {value: 1}) } catch (e) { e.name }")
            .unwrap()
            .to_js_string(),
        "TypeError"
    );
    assert_eq!(ctx.eval("'x' in n").unwrap().to_js_string(), "false");
}

/// The smallest possible exotic class: it refuses every definition.
struct RefuseDefine;

impl Exotic for RefuseDefine {
    fn define_own_property(
        &self,
        _interp: &mut Interp<'_>,
        _object: &Gc<JsObject>,
        _key: &PropertyKey,
        _property: &Property,
    ) -> JsResult<Option<bool>> {
        Ok(Some(false))
    }
}

// ---------------------------------------------------------------------------
// gc_mark
// ---------------------------------------------------------------------------

#[test]
fn gc_mark_keeps_a_cycle_through_the_payload_collectable() {
    // Two realms, one with a `gc_mark` and one without, running the same script. The
    // difference has to be observable, or the test proves nothing: without the callback the
    // value in the payload counts as a reference from outside the heap, so the cycle it
    // closes never dies.
    fn run(with_mark: bool) -> u32 {
        let runtime = Runtime::new();
        let mut ctx = Context::new(&runtime);
        let fin = Rc::new(Finalizer::default());
        let held: Rc<RefCell<Option<Value>>> = Rc::new(RefCell::new(None));

        let mut def = fin.class("Holder");
        if with_mark {
            let marked = held.clone();
            def = def.with_gc_mark(move |_opaque, tracer| {
                if let Some(value) = marked.borrow().as_ref() {
                    value.trace(tracer);
                }
            });
        }
        let id = ctx.register_class(def);

        let point = payload(1);
        fin.own(&point);
        let outer = ctx.new_class_instance(id, None).unwrap();
        ctx.set_class_opaque(&outer, opaque_of(&point));
        let inner = ctx.new_object();
        // `inner` points back at `outer`; `outer` reaches `inner` only through its payload.
        ctx.set_property(&inner, "host", outer.clone()).unwrap();
        *held.borrow_mut() = Some(inner.clone());

        drop(outer);
        drop(inner);
        runtime.run_gc();
        fin.calls()
    }

    assert_eq!(run(true), 1, "gc_mark makes the cycle collectable");
    assert_eq!(run(false), 0, "without it the cycle is immortal");
}