quickjs-oxide-core 0.4.0

The new quickjs-oxide core: 8-byte values, typed arenas and a mark-sweep heap
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
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
//! The embedder's entries: the object, property, conversion and
//! value-construction operations the root crate's API exposes, each one engine
//! entry over the internal operations the loop uses. They are implemented
//! once, on [`NativeCx`], which a [`Runtime`] lends between entries
//! ([`Runtime::native_cx`]) and the loop lends to a host function while it
//! runs; `Runtime` keeps each as a delegation.
//!
//! Rooting: every `Value` passed in must be rooted by the caller (a handle
//! from [`Runtime::hold`], a fixed root, or a value the caller just received
//! and holds before its next entry). Results are unrooted; hold them before
//! the next call that can allocate.

use std::any::Any;
use std::rc::Rc;

use crate::bytecode::CodeStore;
use crate::heap::atom::{KeyKind, PropertyKey};
use crate::heap::object::{InternalData, InternalTag, flags};
use crate::heap::string::StringRepr;
use crate::runtime::{Realm, Runtime, WellKnown};
use crate::value::{Kind, ObjectId, Value};
use crate::vm::native::{HostBody, HostFn};
use crate::vm::object::Descriptor;
use crate::vm::{Cx, ErrorKind, Services, Throw, ops};
use crate::{Heap, HeapError, ObjectKind};

/// A property descriptor: absent fields are `None`. An accessor has `get`
/// or `set` and no `value` or `writable`.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct PropertyDescriptor {
    pub value: Option<Value>,
    pub get: Option<Value>,
    pub set: Option<Value>,
    pub writable: Option<bool>,
    pub enumerable: Option<bool>,
    pub configurable: Option<bool>,
}

impl PropertyDescriptor {
    pub fn is_accessor(&self) -> bool {
        self.get.is_some() || self.set.is_some()
    }

    fn to_internal(self) -> Descriptor {
        Descriptor {
            value: self.value,
            get: self.get,
            set: self.set,
            writable: self.writable,
            enumerable: self.enumerable,
            configurable: self.configurable,
        }
    }

    fn from_internal(descriptor: Descriptor) -> Self {
        PropertyDescriptor {
            value: descriptor.value,
            get: descriptor.get,
            set: descriptor.set,
            writable: descriptor.writable,
            enumerable: descriptor.enumerable,
            configurable: descriptor.configurable,
        }
    }
}

/// What a property key names, read without running JavaScript.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum KeyName {
    Index(u32),
    String(Vec<u16>),
    /// A symbol key: the symbol itself (a fixed or otherwise rooted value
    /// whenever the key came from a rooted object).
    Symbol(Value),
}

/// The embedder's view of a running engine: the heap, the realm, the
/// services and the code store, owned (`Runtime::native_cx`) or borrowed
/// (inside a host function).
pub struct NativeCx<'a> {
    pub(crate) heap: &'a mut Heap,
    code: CodeView<'a>,
    pub(crate) realm: &'a Realm,
    pub(crate) host: &'a mut Services,
}

/// The code store a [`NativeCx`] holds: the runtime's own between entries,
/// or the running loop's, shared, inside a host function.
enum CodeView<'a> {
    Owned(&'a mut CodeStore),
    Shared(&'a CodeStore),
}

impl Runtime {
    /// The embedder's view of the runtime between entries.
    #[inline]
    pub fn native_cx(&mut self) -> NativeCx<'_> {
        NativeCx {
            heap: &mut self.heap,
            code: CodeView::Owned(&mut self.code),
            realm: &self.realm,
            host: &mut self.host,
        }
    }
}

/// [`NativeCx::new_host_function`] over the heap and the realm alone (a
/// module loader's compile-time view makes them too).
pub(crate) fn host_function(
    heap: &mut Heap,
    realm: &Realm,
    name: &str,
    length: u32,
    constructor: bool,
    data: &[Value],
    body: Rc<HostFn>,
) -> Result<ObjectId, HeapError> {
    let record = heap.alloc_internal(
        ObjectKind::Builtin,
        InternalTag::NativeData,
        None,
        0,
        data,
        InternalData::HostFn(HostBody(body)),
        0,
    )?;
    let mark = heap.roots().mark();
    heap.roots().push(Value::object(record));
    let result = (|| {
        let native = if constructor {
            crate::builtins::Native::HostConstructor
        } else {
            crate::builtins::Native::HostFunction
        };
        let prototype = realm.intrinsic(crate::Intrinsic::FunctionPrototype);
        let function = heap.alloc_native_closure(Some(prototype), native.index(), Some(record))?;
        heap.roots().push(Value::object(function));
        if constructor {
            heap.set_object_flag(function, flags::CONSTRUCTOR);
        }
        let name = heap.alloc_string(name)?;
        crate::builtins::define_name_length(
            heap,
            &realm.names,
            function,
            Value::string(name),
            length,
        )?;
        Ok(function)
    })();
    heap.roots().truncate(mark);
    result
}

/// [`NativeCx::new_host_object`] over the heap alone.
pub(crate) fn host_object(
    heap: &mut Heap,
    prototype: Option<ObjectId>,
    data: Rc<dyn Any>,
) -> Result<ObjectId, HeapError> {
    heap.alloc_internal(
        ObjectKind::Builtin,
        InternalTag::HostData,
        prototype,
        4,
        &[],
        InternalData::HostData(data),
        0,
    )
}

impl<'a> NativeCx<'a> {
    /// The same view for a shorter borrow.
    pub fn reborrow(&mut self) -> NativeCx<'_> {
        NativeCx {
            heap: self.heap,
            code: match &mut self.code {
                CodeView::Owned(code) => CodeView::Owned(code),
                CodeView::Shared(code) => CodeView::Shared(code),
            },
            realm: self.realm,
            host: self.host,
        }
    }

    /// The view of the loop's context, for a host function.
    pub(crate) fn from_cx<'b>(cx: &'b mut Cx<'_>) -> NativeCx<'b> {
        NativeCx {
            heap: cx.heap,
            code: CodeView::Shared(cx.static_code),
            realm: cx.realm,
            host: cx.host,
        }
    }

    /// The loop's context for one operation.
    #[inline]
    pub(crate) fn cx(&mut self) -> Cx<'_> {
        let static_code: &CodeStore = match &self.code {
            CodeView::Owned(code) => code,
            CodeView::Shared(code) => code,
        };
        Cx {
            heap: self.heap,
            static_code,
            realm: self.realm,
            host: self.host,
        }
    }

    /// The heap, the code store and the realm for a compilation. Its units
    /// go in the code store when the store is owned and `transient` is
    /// false, else in the heap: inside a host function the running loop
    /// borrows the store, so code compiled there is transient whatever
    /// `transient` says.
    pub fn compiler(&mut self, transient: bool) -> crate::vm::compile::Compiler<'_> {
        match &mut self.code {
            CodeView::Owned(code) => {
                if transient {
                    crate::vm::compile::Compiler::new(self.heap, code, self.realm)
                } else {
                    crate::vm::compile::Compiler::owned(self.heap, code, self.realm)
                }
            }
            CodeView::Shared(code) => {
                crate::vm::compile::Compiler::new(self.heap, code, self.realm)
            }
        }
    }

    /// Whether the code store is the runtime's own (between entries), not
    /// the running loop's (inside a host function).
    pub fn owns_code(&self) -> bool {
        matches!(self.code, CodeView::Owned(_))
    }

    #[inline]
    pub fn heap(&self) -> &Heap {
        self.heap
    }

    #[inline]
    pub fn heap_mut(&mut self) -> &mut Heap {
        self.heap
    }

    #[inline]
    pub fn realm(&self) -> &'a Realm {
        self.realm
    }

    /// The flag another thread sets to interrupt the running script.
    pub fn interrupt_flag(&self) -> std::sync::Arc<std::sync::atomic::AtomicBool> {
        std::sync::Arc::clone(&self.host.interrupt)
    }

    /// Whether an interrupt is unwinding (the last throw was one).
    pub fn is_interrupted(&self) -> bool {
        self.heap.vm.interrupted
    }

    /// Ends an interrupt's unwinding, at the outermost entry: the runtime
    /// runs scripts again.
    pub fn clear_interrupted(&mut self) {
        self.heap.vm.interrupted = false;
        self.heap.vm.poll = crate::vm::INTERRUPT_INTERVAL;
    }

    /// Runs `install` with the atoms it interns pinned, as the builtins'
    /// are.
    pub(crate) fn installing<T>(&mut self, install: impl FnOnce(&mut Cx<'_>) -> T) -> T {
        let mode = self.heap.set_atom_mode(crate::heap::AtomMode::Pin);
        let result = install(&mut self.cx());
        self.heap.set_atom_mode(mode);
        result
    }

    /// [`Runtime::install_std`].
    pub fn install_std(&mut self) -> Result<(), HeapError> {
        self.installing(crate::builtins::install_std)
    }

    /// [`Runtime::install_qjs_helpers`].
    pub fn install_qjs_helpers(&mut self, script_args: Option<&[String]>) -> Result<(), HeapError> {
        self.installing(|cx| crate::builtins::install_qjs_helpers(cx, script_args))
    }

    /// The bytes of host stack nested re-entries into the loop may use.
    pub fn set_native_stack_budget(&mut self, bytes: usize) {
        self.heap.vm.native_budget = bytes;
    }
}

impl NativeCx<'_> {
    // ---- calls and handles ----

    /// Calls `function`; the result or the thrown value is unrooted. The
    /// caller keeps `function` alive (a handle or a rooted object).
    pub fn call(&mut self, function: Value, this: Value, args: &[Value]) -> Result<Value, Throw> {
        crate::vm::call(&mut self.cx(), function, this, args)
    }

    /// Runs a script function with the global object as `this`.
    pub fn run_script(&mut self, script: ObjectId) -> Result<Value, Throw> {
        let global = Value::object(self.realm.global());
        self.call(Value::object(script), global, &[])
    }

    /// Holds `value` for the embedder until [`NativeCx::release`].
    pub fn hold(&mut self, value: Value) -> crate::Handle {
        self.heap.handles().create(value)
    }

    pub fn held(&self, handle: crate::Handle) -> Value {
        self.heap.handles_ref().get(handle)
    }

    pub fn release(&mut self, handle: crate::Handle) {
        self.heap.handles().release(handle);
    }

    pub fn global_object(&self) -> ObjectId {
        self.realm.global()
    }

    pub fn intrinsic(&self, intrinsic: crate::Intrinsic) -> ObjectId {
        self.realm.intrinsic(intrinsic)
    }

    /// An ordinary object inheriting from `%Object.prototype%`.
    pub fn new_object(&mut self) -> Result<ObjectId, HeapError> {
        let prototype = self.intrinsic(crate::Intrinsic::ObjectPrototype);
        self.heap
            .alloc_object(ObjectKind::Ordinary, Some(prototype), 4)
    }

    // ---- host functions and host objects ----

    /// A host function named `name` with `length`, whose body is `body`
    /// and whose captured values are `data` (read through
    /// [`NativeCall::data`](crate::vm::native::NativeCall::data)). A
    /// `constructor` may be called by `new`; it gets no `prototype`
    /// property (the embedder defines one). `data` must be rooted by the
    /// caller.
    pub fn new_host_function(
        &mut self,
        name: &str,
        length: u32,
        constructor: bool,
        data: &[Value],
        body: Rc<HostFn>,
    ) -> Result<ObjectId, HeapError> {
        host_function(self.heap, self.realm, name, length, constructor, data, body)
    }

    /// An object inheriting from `prototype` (`None` for null) that holds
    /// the embedder's `data`, read back by [`NativeCx::host_data`]. The datum
    /// drops when the object is collected.
    pub fn new_host_object(
        &mut self,
        prototype: Option<ObjectId>,
        data: Rc<dyn Any>,
    ) -> Result<ObjectId, HeapError> {
        host_object(self.heap, prototype, data)
    }

    /// The datum of a host object, whatever its type; `None` for any other
    /// object.
    pub fn host_data(&self, object: ObjectId) -> Option<Rc<dyn Any>> {
        if self.heap.internal_tag(object) != InternalTag::HostData {
            return None;
        }
        match &self.heap.internal(object).data {
            InternalData::HostData(data) => Some(Rc::clone(data)),
            _ => None,
        }
    }

    // ---- keys ----

    /// The property key of the string `units` (an array index when it is
    /// one's canonical form).
    pub fn key_from_units(&mut self, units: &[u16]) -> Result<PropertyKey, HeapError> {
        self.heap.property_key_units(units)
    }

    /// The key of a symbol value; `None` for any other value.
    pub fn key_from_symbol(&self, symbol: Value) -> Option<PropertyKey> {
        symbol.as_symbol().map(PropertyKey::symbol)
    }

    /// `ToPropertyKey(value)`.
    pub fn to_property_key(&mut self, value: Value) -> Result<PropertyKey, Throw> {
        ops::to_property_key(&mut self.cx(), value)
    }

    pub fn key_name(&self, key: PropertyKey) -> KeyName {
        match key.kind() {
            KeyKind::Index(index) => KeyName::Index(index),
            KeyKind::String(id) => KeyName::String(self.heap.string(id).repr().units().collect()),
            KeyKind::Symbol(id) => KeyName::Symbol(Value::symbol(id)),
        }
    }

    // ---- objects ----

    /// `object.[[Get]](key, receiver)`.
    pub fn get(
        &mut self,
        object: ObjectId,
        key: PropertyKey,
        receiver: Value,
    ) -> Result<Value, Throw> {
        crate::vm::object::get(&mut self.cx(), object, key, receiver)
    }

    /// `object.[[Set]](key, value, receiver)`.
    pub fn set(
        &mut self,
        object: ObjectId,
        key: PropertyKey,
        value: Value,
        receiver: Value,
    ) -> Result<bool, Throw> {
        crate::vm::object::set(&mut self.cx(), object, key, value, receiver)
    }

    /// `object.[[GetOwnProperty]](key)`.
    pub fn get_own_property(
        &mut self,
        object: ObjectId,
        key: PropertyKey,
    ) -> Result<Option<PropertyDescriptor>, Throw> {
        Ok(
            crate::vm::object::get_own_property(&mut self.cx(), object, key)?
                .map(PropertyDescriptor::from_internal),
        )
    }

    /// `object.[[DefineOwnProperty]](key, descriptor)`.
    pub fn define_own_property(
        &mut self,
        object: ObjectId,
        key: PropertyKey,
        descriptor: &PropertyDescriptor,
    ) -> Result<bool, Throw> {
        crate::vm::object::define_own_property(
            &mut self.cx(),
            object,
            key,
            &descriptor.to_internal(),
        )
    }

    /// `object.[[Delete]](key)`.
    pub fn delete_property(&mut self, object: ObjectId, key: PropertyKey) -> Result<bool, Throw> {
        crate::vm::object::delete(&mut self.cx(), object, key)
    }

    /// `HasProperty(object, key)`.
    pub fn has_property(&mut self, object: ObjectId, key: PropertyKey) -> Result<bool, Throw> {
        crate::vm::object::has_property(&mut self.cx(), object, key)
    }

    /// `HasOwnProperty(object, key)`.
    pub fn has_own_property(&mut self, object: ObjectId, key: PropertyKey) -> Result<bool, Throw> {
        crate::vm::object::has_own_property(&mut self.cx(), object, key)
    }

    /// `object.[[OwnPropertyKeys]]()`.
    pub fn own_property_keys(&mut self, object: ObjectId) -> Result<Vec<PropertyKey>, Throw> {
        crate::vm::object::own_property_keys(&mut self.cx(), object)
    }

    /// `object.[[GetPrototypeOf]]()`.
    pub fn get_prototype_of(&mut self, object: ObjectId) -> Result<Option<ObjectId>, Throw> {
        Ok(crate::vm::object::get_prototype_of(&mut self.cx(), object)?.as_object())
    }

    /// `object.[[SetPrototypeOf]](prototype)`.
    pub fn set_prototype_of(
        &mut self,
        object: ObjectId,
        prototype: Option<ObjectId>,
    ) -> Result<bool, Throw> {
        let prototype = prototype.map_or(Value::NULL, Value::object);
        crate::vm::object::set_prototype_of(&mut self.cx(), object, prototype)
    }

    /// `object.[[PreventExtensions]]()`.
    pub fn prevent_extensions(&mut self, object: ObjectId) -> Result<bool, Throw> {
        crate::vm::object::prevent_extensions(&mut self.cx(), object)
    }

    /// `Construct(function, args, new_target)`; `new_target` is `function`
    /// itself for a plain `new`.
    pub fn construct(
        &mut self,
        function: Value,
        args: &[Value],
        new_target: Value,
    ) -> Result<Value, Throw> {
        crate::vm::construct(&mut self.cx(), function, args, new_target)
    }

    /// `IsCallable(value)`.
    pub fn is_callable(&self, value: Value) -> bool {
        ops::is_callable(self.heap, value)
    }

    /// `IsConstructor(value)`.
    pub fn is_constructor(&self, value: Value) -> bool {
        value
            .as_object()
            .is_some_and(|object| self.heap.header(object).has(flags::CONSTRUCTOR))
    }

    /// `IsArray(value)`: throws for a revoked proxy.
    pub fn is_array(&mut self, value: Value) -> Result<bool, Throw> {
        crate::vm::object::is_array(&mut self.cx(), value)
    }

    /// Whether `value` is an Error instance (has `[[ErrorData]]`).
    pub fn is_error(&self, value: Value) -> bool {
        value
            .as_object()
            .is_some_and(|object| self.heap.header(object).has(flags::ERROR))
    }

    /// Whether `value` is a promise.
    pub fn is_promise(&mut self, value: Value) -> bool {
        crate::vm::jobs::is_promise(&self.cx(), value)
    }

    pub fn object_kind(&self, object: ObjectId) -> ObjectKind {
        self.heap.object_kind(object)
    }

    /// An ordinary object inheriting from `prototype` (`None` for null).
    pub fn new_object_with_prototype(
        &mut self,
        prototype: Option<ObjectId>,
    ) -> Result<ObjectId, HeapError> {
        self.heap.alloc_object(ObjectKind::Ordinary, prototype, 4)
    }

    /// `CreateArrayFromList(values)`.
    pub fn new_array_from(&mut self, values: &[Value]) -> Result<ObjectId, Throw> {
        let mut cx = self.cx();
        let length = u32::try_from(values.len()).unwrap_or(u32::MAX);
        let prototype = cx.realm.intrinsic(crate::Intrinsic::ArrayPrototype);
        let array = cx
            .heap
            .alloc_array(Some(prototype), length)
            .map_err(|error| crate::vm::error::heap_error(&cx, error))?;
        let mark = cx.heap.roots().mark();
        cx.heap.roots().push(Value::object(array));
        let mut result = Ok(array);
        for (index, &value) in values.iter().enumerate() {
            let key = crate::vm::object::index_key(&mut cx, index as u32);
            if let Err(error) = key.and_then(|key| {
                crate::vm::object::create_data_property_or_throw(&mut cx, array, key, value)
            }) {
                result = Err(error);
                break;
            }
        }
        cx.heap.roots().truncate(mark);
        result
    }

    /// A new error object of `kind` with `message`, a `stack` from the
    /// running frames.
    pub fn new_error(&mut self, kind: ErrorKind, message: &str) -> Result<Value, HeapError> {
        let message = self.heap.alloc_string(message)?;
        crate::vm::error::new_error(&mut self.cx(), kind, Value::string(message))
    }

    /// A new error object located at `file:line:column` (a compile error):
    /// `fileName`, `lineNumber` and `columnNumber`, and a `stack` that
    /// starts there, the running frames after it.
    pub fn new_located_error(
        &mut self,
        kind: ErrorKind,
        message: &str,
        file: &str,
        line: u32,
        column: u32,
    ) -> Result<Value, HeapError> {
        let message = self.heap.alloc_string(message)?;
        let location = crate::vm::error::Location { file, line, column };
        crate::vm::error::new_error_at(
            &mut self.cx(),
            kind,
            Value::string(message),
            Some(location),
            0,
        )
    }

    /// `NewPromiseCapability(%Promise%)`: the promise and its resolving
    /// functions, unrooted.
    pub fn new_promise_capability(&mut self) -> Result<(ObjectId, ObjectId, ObjectId), Throw> {
        let mut cx = self.cx();
        let prototype = cx.realm.intrinsic(crate::Intrinsic::PromisePrototype);
        let promise = crate::vm::jobs::new_promise(&mut cx, prototype)?;
        let mark = cx.heap.roots().mark();
        cx.heap.roots().push(Value::object(promise));
        let functions = crate::vm::jobs::resolving_functions(&mut cx, promise);
        cx.heap.roots().truncate(mark);
        let (resolve, reject) = functions?;
        Ok((promise, resolve, reject))
    }

    /// A pending promise of `%Promise.prototype%`.
    pub fn new_promise(&mut self) -> Result<ObjectId, Throw> {
        let prototype = self.realm.intrinsic(crate::Intrinsic::PromisePrototype);
        crate::vm::jobs::new_promise(&mut self.cx(), prototype)
    }

    // ---- buffers ----

    /// A new `ArrayBuffer` of `len` zero bytes; a `RangeError` past
    /// [`MAX_BUFFER_LENGTH`](crate::heap::buffer::MAX_BUFFER_LENGTH).
    pub fn new_array_buffer(&mut self, len: usize) -> Result<ObjectId, Throw> {
        let mut cx = self.cx();
        let mark = cx.heap.roots().mark();
        let buffer = crate::builtins::new_array_buffer(&mut cx, len);
        cx.heap.roots().truncate(mark);
        buffer
    }

    /// The buffer record of an `ArrayBuffer` or `SharedArrayBuffer`.
    fn buffer(&self, object: ObjectId) -> Option<&crate::heap::buffer::Buffer> {
        match self.heap.internal_tag(object) {
            InternalTag::ArrayBuffer | InternalTag::SharedArrayBuffer => {
                Some(crate::vm::typed::buffer(self.heap, object))
            }
            _ => None,
        }
    }

    /// A buffer's length in bytes; `None` when `object` is not a buffer or
    /// is detached.
    pub fn array_buffer_len(&self, object: ObjectId) -> Option<usize> {
        self.buffer(object)
            .filter(|buffer| !buffer.detached)
            .map(crate::heap::buffer::Buffer::len)
    }

    /// Checks that `offset..offset + len` is in an attached buffer: a
    /// `TypeError` for anything else, a `RangeError` past its end.
    fn buffer_range(&mut self, object: ObjectId, offset: usize, len: usize) -> Result<(), Throw> {
        let Some(buffer) = self.buffer(object) else {
            return Err(crate::vm::error::type_error(
                &mut self.cx(),
                "not an ArrayBuffer",
            ));
        };
        if buffer.detached {
            return Err(crate::vm::error::type_error(
                &mut self.cx(),
                "ArrayBuffer is detached",
            ));
        }
        if offset.checked_add(len).is_none_or(|end| end > buffer.len()) {
            return Err(crate::vm::error::range_error(
                &mut self.cx(),
                "out of bound",
            ));
        }
        Ok(())
    }

    /// Copies `out.len()` bytes of the buffer from `offset` (a shared
    /// buffer's byte by byte through its atomics).
    pub fn array_buffer_read(
        &mut self,
        object: ObjectId,
        offset: usize,
        out: &mut [u8],
    ) -> Result<(), Throw> {
        self.buffer_range(object, offset, out.len())?;
        crate::vm::typed::buffer(self.heap, object).read(offset, out);
        Ok(())
    }

    /// Writes `data` into the buffer at `offset`.
    pub fn array_buffer_write(
        &mut self,
        object: ObjectId,
        offset: usize,
        data: &[u8],
    ) -> Result<(), Throw> {
        self.buffer_range(object, offset, data.len())?;
        crate::vm::typed::buffer_mut(self.heap, object).write(offset, data);
        Ok(())
    }

    /// The bytes of an attached `ArrayBuffer`; `None` for anything else,
    /// a `SharedArrayBuffer` included (its bytes are atomics).
    pub fn array_buffer_bytes(&self, object: ObjectId) -> Option<&[u8]> {
        self.buffer(object)
            .filter(|buffer| !buffer.detached)
            .and_then(crate::heap::buffer::Buffer::owned_slice)
    }

    /// A typed array's element kind, buffer, byte offset and current
    /// length (`None` when it is out of bounds of its buffer or the buffer
    /// is detached); `None` for anything but a typed array.
    pub fn typed_array_view(
        &self,
        object: ObjectId,
    ) -> Option<(
        crate::heap::buffer::ElementKind,
        ObjectId,
        usize,
        Option<usize>,
    )> {
        if self.heap.internal_tag(object) != InternalTag::TypedArray {
            return None;
        }
        let (view, buffer) = crate::vm::typed::view(self.heap, object);
        Some((
            view.kind,
            buffer,
            view.byte_offset,
            crate::vm::typed::length(self.heap, object),
        ))
    }

    /// QuickJS's `JS_DetachArrayBuffer`: detaches an ArrayBuffer; anything
    /// else is ignored.
    pub fn detach_array_buffer(&mut self, value: Value) -> Result<(), Throw> {
        let is_buffer = value.as_object().is_some_and(|object| {
            self.heap.internal_tag(object) == crate::heap::object::InternalTag::ArrayBuffer
        });
        if is_buffer {
            crate::builtins::detach_buffer(&mut self.cx(), value)?;
        }
        Ok(())
    }

    // ---- primitives ----

    pub fn new_string(&mut self, text: &str) -> Result<Value, HeapError> {
        self.heap.alloc_string(text).map(Value::string)
    }

    pub fn new_string_units(&mut self, units: &[u16]) -> Result<Value, HeapError> {
        self.heap.alloc_string_units(units).map(Value::string)
    }

    /// A string of `repr`, which the caller made canonical (`OneByte`
    /// whenever every unit fits in a byte).
    pub fn new_string_repr(&mut self, repr: StringRepr) -> Result<Value, HeapError> {
        self.heap.alloc_string_repr(repr).map(Value::string)
    }

    /// A string value's code units, flattened; `None` for any other value.
    pub fn string_repr(&self, value: Value) -> Option<&StringRepr> {
        value.as_string().map(|id| self.heap.string(id).repr())
    }

    /// A string value as Rust text (lone surrogates replaced).
    pub fn string_lossy(&self, value: Value) -> Option<String> {
        value.as_string().map(|id| self.heap.string_text(id))
    }

    /// The BigInt of the decimal text `decimal` (an optional `-`, then
    /// digits); `None` when it does not parse.
    pub fn new_bigint(&mut self, decimal: &str) -> Option<Result<Value, HeapError>> {
        let big = crate::vm::bigint::Big::parse(decimal)?;
        Some(
            self.heap
                .alloc_bigint(big.negative, &big.limbs)
                .map(Value::bigint),
        )
    }

    /// A BigInt value in decimal; `None` for any other value.
    pub fn bigint_decimal(&self, value: Value) -> Option<String> {
        value.as_bigint()?;
        Some(ops::big(self.heap, value).to_string_radix10())
    }

    /// A new symbol with `description` (`Symbol(description)`).
    pub fn new_symbol(&mut self, description: Option<&[u16]>) -> Result<Value, HeapError> {
        let description = match description {
            Some(units) => Some(self.heap.alloc_string_units(units)?),
            None => None,
        };
        self.heap
            .alloc_symbol(description, false)
            .map(Value::symbol)
    }

    /// A symbol's `[[Description]]`; `None` when it is undefined or `value`
    /// is not a symbol.
    pub fn symbol_description(&self, value: Value) -> Option<Vec<u16>> {
        let record = self.heap.symbol(value.as_symbol()?);
        (record.description != crate::heap::object::NONE).then(|| {
            self.heap
                .string(crate::value::StringId(record.description))
                .repr()
                .units()
                .collect()
        })
    }

    /// The well-known symbol `Symbol.<name>` (`"iterator"`, …).
    pub fn well_known_symbol(&self, name: &str) -> Option<Value> {
        self.realm
            .symbols
            .all()
            .into_iter()
            .find(|&(candidate, _)| candidate == name)
            .map(|(_, id)| Value::symbol(id))
    }

    pub fn well_known_symbol_key(&self, name: &str) -> Option<PropertyKey> {
        self.well_known_symbol(name)
            .and_then(|symbol| symbol.as_symbol())
            .map(WellKnown::key)
    }

    // ---- conversions ----

    /// `ToString(value)`.
    pub fn to_string(&mut self, value: Value) -> Result<Value, Throw> {
        ops::to_string(&mut self.cx(), value)
    }

    /// `ToNumber(value)`.
    pub fn to_number(&mut self, value: Value) -> Result<f64, Throw> {
        ops::to_number(&mut self.cx(), value)
    }

    /// `ToBoolean(value)`.
    pub fn to_boolean(&self, value: Value) -> bool {
        ops::to_boolean(self.heap, value)
    }

    /// `ToObject(value)`.
    pub fn to_object(&mut self, value: Value) -> Result<ObjectId, Throw> {
        crate::vm::object::to_object(&mut self.cx(), value)
    }

    /// `IsStrictlyEqual(x, y)`.
    pub fn strict_equals(&self, x: Value, y: Value) -> bool {
        ops::strict_eq(self.heap, x, y)
    }

    /// `IsLooselyEqual(x, y)`.
    pub fn loose_equals(&mut self, x: Value, y: Value) -> Result<bool, Throw> {
        ops::loose_eq(&mut self.cx(), x, y)
    }

    /// `SameValue(x, y)`.
    pub fn same_value(&mut self, x: Value, y: Value) -> bool {
        crate::vm::object::same_value(&self.cx(), x, y)
    }

    /// `SameValueZero(x, y)`.
    pub fn same_value_zero(&self, x: Value, y: Value) -> bool {
        ops::same_value_zero_heap(self.heap, x, y)
    }

    /// `typeof value`.
    pub fn type_of(&mut self, value: Value) -> String {
        let cx = self.cx();
        let text = ops::type_of(&cx, value);
        self.heap
            .string_text(text.as_string().expect("a typeof atom"))
    }

    /// The kind of a value without running JavaScript.
    pub fn kind_of(&self, value: Value) -> Kind {
        value.kind()
    }

    // ---- collection ----

    /// Runs a full collection. Only between entries: the embedder's handles
    /// and the fixed roots are the roots.
    pub fn run_gc(&mut self) {
        self.heap.collect();
    }
}

impl Runtime {
    // ---- keys ----

    /// [`NativeCx::key_from_units`].
    pub fn key_from_units(&mut self, units: &[u16]) -> Result<PropertyKey, HeapError> {
        self.native_cx().key_from_units(units)
    }

    /// The key of a symbol value; `None` for any other value.
    pub fn key_from_symbol(&self, symbol: Value) -> Option<PropertyKey> {
        symbol.as_symbol().map(PropertyKey::symbol)
    }

    /// [`NativeCx::to_property_key`].
    pub fn to_property_key(&mut self, value: Value) -> Result<PropertyKey, Throw> {
        self.native_cx().to_property_key(value)
    }

    pub fn key_name(&self, key: PropertyKey) -> KeyName {
        match key.kind() {
            KeyKind::Index(index) => KeyName::Index(index),
            KeyKind::String(id) => KeyName::String(self.heap.string(id).repr().units().collect()),
            KeyKind::Symbol(id) => KeyName::Symbol(Value::symbol(id)),
        }
    }

    // ---- objects ----

    /// [`NativeCx::get`].
    pub fn get(
        &mut self,
        object: ObjectId,
        key: PropertyKey,
        receiver: Value,
    ) -> Result<Value, Throw> {
        self.native_cx().get(object, key, receiver)
    }

    /// [`NativeCx::set`].
    pub fn set(
        &mut self,
        object: ObjectId,
        key: PropertyKey,
        value: Value,
        receiver: Value,
    ) -> Result<bool, Throw> {
        self.native_cx().set(object, key, value, receiver)
    }

    /// [`NativeCx::get_own_property`].
    pub fn get_own_property(
        &mut self,
        object: ObjectId,
        key: PropertyKey,
    ) -> Result<Option<PropertyDescriptor>, Throw> {
        self.native_cx().get_own_property(object, key)
    }

    /// [`NativeCx::define_own_property`].
    pub fn define_own_property(
        &mut self,
        object: ObjectId,
        key: PropertyKey,
        descriptor: &PropertyDescriptor,
    ) -> Result<bool, Throw> {
        self.native_cx()
            .define_own_property(object, key, descriptor)
    }

    /// [`NativeCx::delete_property`].
    pub fn delete_property(&mut self, object: ObjectId, key: PropertyKey) -> Result<bool, Throw> {
        self.native_cx().delete_property(object, key)
    }

    /// [`NativeCx::has_property`].
    pub fn has_property(&mut self, object: ObjectId, key: PropertyKey) -> Result<bool, Throw> {
        self.native_cx().has_property(object, key)
    }

    /// [`NativeCx::has_own_property`].
    pub fn has_own_property(&mut self, object: ObjectId, key: PropertyKey) -> Result<bool, Throw> {
        self.native_cx().has_own_property(object, key)
    }

    /// [`NativeCx::own_property_keys`].
    pub fn own_property_keys(&mut self, object: ObjectId) -> Result<Vec<PropertyKey>, Throw> {
        self.native_cx().own_property_keys(object)
    }

    /// [`NativeCx::get_prototype_of`].
    pub fn get_prototype_of(&mut self, object: ObjectId) -> Result<Option<ObjectId>, Throw> {
        self.native_cx().get_prototype_of(object)
    }

    /// [`NativeCx::set_prototype_of`].
    pub fn set_prototype_of(
        &mut self,
        object: ObjectId,
        prototype: Option<ObjectId>,
    ) -> Result<bool, Throw> {
        self.native_cx().set_prototype_of(object, prototype)
    }

    /// [`NativeCx::prevent_extensions`].
    pub fn prevent_extensions(&mut self, object: ObjectId) -> Result<bool, Throw> {
        self.native_cx().prevent_extensions(object)
    }

    /// [`NativeCx::construct`].
    pub fn construct(
        &mut self,
        function: Value,
        args: &[Value],
        new_target: Value,
    ) -> Result<Value, Throw> {
        self.native_cx().construct(function, args, new_target)
    }

    /// `IsCallable(value)`.
    pub fn is_callable(&self, value: Value) -> bool {
        ops::is_callable(&self.heap, value)
    }

    /// `IsConstructor(value)`.
    pub fn is_constructor(&self, value: Value) -> bool {
        value
            .as_object()
            .is_some_and(|object| self.heap.header(object).has(flags::CONSTRUCTOR))
    }

    /// [`NativeCx::is_array`].
    pub fn is_array(&mut self, value: Value) -> Result<bool, Throw> {
        self.native_cx().is_array(value)
    }

    /// Whether `value` is an Error instance (has `[[ErrorData]]`).
    pub fn is_error(&self, value: Value) -> bool {
        value
            .as_object()
            .is_some_and(|object| self.heap.header(object).has(flags::ERROR))
    }

    /// [`NativeCx::is_promise`].
    pub fn is_promise(&mut self, value: Value) -> bool {
        self.native_cx().is_promise(value)
    }

    pub fn object_kind(&self, object: ObjectId) -> ObjectKind {
        self.heap.object_kind(object)
    }

    /// [`NativeCx::new_object_with_prototype`].
    pub fn new_object_with_prototype(
        &mut self,
        prototype: Option<ObjectId>,
    ) -> Result<ObjectId, HeapError> {
        self.native_cx().new_object_with_prototype(prototype)
    }

    /// [`NativeCx::new_array_from`].
    pub fn new_array_from(&mut self, values: &[Value]) -> Result<ObjectId, Throw> {
        self.native_cx().new_array_from(values)
    }

    /// [`NativeCx::new_error`].
    pub fn new_error(&mut self, kind: ErrorKind, message: &str) -> Result<Value, HeapError> {
        self.native_cx().new_error(kind, message)
    }

    /// [`NativeCx::new_located_error`].
    pub fn new_located_error(
        &mut self,
        kind: ErrorKind,
        message: &str,
        file: &str,
        line: u32,
        column: u32,
    ) -> Result<Value, HeapError> {
        self.native_cx()
            .new_located_error(kind, message, file, line, column)
    }

    /// [`NativeCx::new_promise`].
    pub fn new_promise(&mut self) -> Result<ObjectId, Throw> {
        self.native_cx().new_promise()
    }

    /// [`NativeCx::detach_array_buffer`].
    pub fn detach_array_buffer(&mut self, value: Value) -> Result<(), Throw> {
        self.native_cx().detach_array_buffer(value)
    }

    // ---- primitives ----

    /// [`NativeCx::new_string`].
    pub fn new_string(&mut self, text: &str) -> Result<Value, HeapError> {
        self.native_cx().new_string(text)
    }

    /// [`NativeCx::new_string_units`].
    pub fn new_string_units(&mut self, units: &[u16]) -> Result<Value, HeapError> {
        self.native_cx().new_string_units(units)
    }

    /// [`NativeCx::new_string_repr`].
    pub fn new_string_repr(&mut self, repr: StringRepr) -> Result<Value, HeapError> {
        self.native_cx().new_string_repr(repr)
    }

    /// A string value's code units, flattened; `None` for any other value.
    pub fn string_repr(&self, value: Value) -> Option<&StringRepr> {
        value.as_string().map(|id| self.heap.string(id).repr())
    }

    /// A string value as Rust text (lone surrogates replaced).
    pub fn string_lossy(&self, value: Value) -> Option<String> {
        value.as_string().map(|id| self.heap.string_text(id))
    }

    /// [`NativeCx::new_bigint`].
    pub fn new_bigint(&mut self, decimal: &str) -> Option<Result<Value, HeapError>> {
        self.native_cx().new_bigint(decimal)
    }

    /// A BigInt value in decimal; `None` for any other value.
    pub fn bigint_decimal(&self, value: Value) -> Option<String> {
        value.as_bigint()?;
        Some(ops::big(&self.heap, value).to_string_radix10())
    }

    /// [`NativeCx::new_symbol`].
    pub fn new_symbol(&mut self, description: Option<&[u16]>) -> Result<Value, HeapError> {
        self.native_cx().new_symbol(description)
    }

    /// A symbol's `[[Description]]`; `None` when it is undefined or `value`
    /// is not a symbol.
    pub fn symbol_description(&self, value: Value) -> Option<Vec<u16>> {
        let record = self.heap.symbol(value.as_symbol()?);
        (record.description != crate::heap::object::NONE).then(|| {
            self.heap
                .string(crate::value::StringId(record.description))
                .repr()
                .units()
                .collect()
        })
    }

    /// The well-known symbol `Symbol.<name>` (`"iterator"`, …).
    pub fn well_known_symbol(&self, name: &str) -> Option<Value> {
        self.realm
            .symbols
            .all()
            .into_iter()
            .find(|&(candidate, _)| candidate == name)
            .map(|(_, id)| Value::symbol(id))
    }

    pub fn well_known_symbol_key(&self, name: &str) -> Option<PropertyKey> {
        self.well_known_symbol(name)
            .and_then(|symbol| symbol.as_symbol())
            .map(WellKnown::key)
    }

    // ---- conversions ----

    /// [`NativeCx::to_string`].
    pub fn to_string(&mut self, value: Value) -> Result<Value, Throw> {
        self.native_cx().to_string(value)
    }

    /// [`NativeCx::to_number`].
    pub fn to_number(&mut self, value: Value) -> Result<f64, Throw> {
        self.native_cx().to_number(value)
    }

    /// `ToBoolean(value)`.
    pub fn to_boolean(&self, value: Value) -> bool {
        ops::to_boolean(&self.heap, value)
    }

    /// [`NativeCx::to_object`].
    pub fn to_object(&mut self, value: Value) -> Result<ObjectId, Throw> {
        self.native_cx().to_object(value)
    }

    /// `IsStrictlyEqual(x, y)`.
    pub fn strict_equals(&self, x: Value, y: Value) -> bool {
        ops::strict_eq(&self.heap, x, y)
    }

    /// [`NativeCx::loose_equals`].
    pub fn loose_equals(&mut self, x: Value, y: Value) -> Result<bool, Throw> {
        self.native_cx().loose_equals(x, y)
    }

    /// [`NativeCx::same_value`].
    pub fn same_value(&mut self, x: Value, y: Value) -> bool {
        self.native_cx().same_value(x, y)
    }

    /// `SameValueZero(x, y)`.
    pub fn same_value_zero(&self, x: Value, y: Value) -> bool {
        ops::same_value_zero_heap(&self.heap, x, y)
    }

    /// [`NativeCx::type_of`].
    pub fn type_of(&mut self, value: Value) -> String {
        self.native_cx().type_of(value)
    }

    /// The kind of a value without running JavaScript.
    pub fn kind_of(&self, value: Value) -> Kind {
        value.kind()
    }

    // ---- collection ----

    /// [`NativeCx::run_gc`].
    pub fn run_gc(&mut self) {
        self.native_cx().run_gc()
    }
}