nova_vm 1.0.0

Nova Virtual Machine
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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.

use core::{marker::PhantomData, ops::Deref};
use std::{borrow::Cow, ptr::NonNull};

use crate::{
    ecmascript::{
        Agent, BUILTIN_STRING_MEMORY, BuiltinFunctionHeapData, ExceptionType, ExecutionContext,
        Function, FunctionInternalProperties, InternalSlots, JsResult, Object, OrdinaryObject,
        PropertyKey, Realm, ScopedValuesIterator, String, Value, function_handle,
    },
    engine::{Bindable, GcScope, HeapRootCollection, NoGcScope, bindable_handle},
    heap::{
        ArenaAccess, ArenaAccessMut, BaseIndex, CompactionLists, CreateHeapData, Heap,
        HeapMarkAndSweep, HeapSweepWeakReference, IntrinsicConstructorIndexes,
        IntrinsicFunctionIndexes, ObjectEntry, ObjectEntryPropertyDescriptor, WorkQueues,
        arena_vec_access,
    },
    ndt,
};

/// A list of [ECMAScript language values](Value).
///
/// Garbage collection invalidates the [`Value`](Value)s in the list but does
/// not automatically make it impossible to extract them from it. Thus, when
/// received as a parameter the list should immediately be [bound](Bindable) to
/// the [`GcScope`](GcScope)'s GC lifetime to ensure that it is not used after
/// garbage collection.
#[derive(Default)]
#[repr(transparent)]
pub struct ArgumentsList<'slice, 'value> {
    slice: &'slice mut [Value<'static>],
    value: PhantomData<Value<'value>>,
}

impl core::fmt::Debug for ArgumentsList<'_, '_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        self.slice.fmt(f)
    }
}

impl<'slice, 'value> ArgumentsList<'slice, 'value> {
    /// Create an ArgumentsList from a single Value.
    pub(crate) fn from_mut_value(value: &'slice mut Value<'value>) -> Self {
        Self {
            // SAFETY: The Value lifetime is moved over to the PhantomData.
            slice: core::slice::from_mut(unsafe {
                core::mem::transmute::<&'slice mut Value<'value>, &'slice mut Value<'static>>(value)
            }),
            value: PhantomData,
        }
    }

    /// Create an ArgumentsList from a Value slice.
    pub(crate) fn from_mut_slice(slice: &'slice mut [Value<'value>]) -> Self {
        Self {
            // SAFETY: The Value lifetime is moved over to the PhantomData.
            slice: unsafe {
                core::mem::transmute::<&'slice mut [Value<'value>], &'slice mut [Value<'static>]>(
                    slice,
                )
            },
            value: PhantomData,
        }
    }

    /// Temporarily store the list on the [`Agent`](Agent) heap for the duration
    /// of a callback, ensuring that garbage collection does not invalidate any
    /// of the [`Value`](Value)s within.
    ///
    /// See [`ScopedArgumentsList`](ScopedArgumentsList) for accessing the
    /// [`Value`](Value)s within the callback.
    pub fn with_scoped<'a, R>(
        &mut self,
        agent: &mut Agent,
        work: impl FnOnce(&mut Agent, ScopedArgumentsList<'_>, GcScope<'a, '_>) -> R,
        mut gc: GcScope<'a, '_>,
    ) -> R
    where
        R: 'a,
    {
        // First take the arguments from ArgumentsList. Note: This is
        // strictly extra work from a computational standpoint, but makes
        // the code safer from a memory stand point. Any errors will also
        // become more obvious.
        let slice = core::mem::take(&mut self.slice);
        // SAFETY: We push the slice to the heap temporarily, for which we
        // need to transmute its lifetime to static. This is strictly not
        // correct: The slice points either to the stack or to a Vec owned
        // by an above call frame. But! We give our best possible guarantee
        // that the slice will be taken out of the heap before the end of
        // this call. As long as that holds, then this is all perfectly
        // legal. Note that unwinding of panics will break that guarantee
        // currently.
        let slice = unsafe {
            std::mem::transmute::<&mut [Value<'static>], &'static mut [Value<'static>]>(slice)
        };
        // Store the slice's end pointer for validity checking later.
        let slice_end_ptr = slice.as_ptr_range().end;
        let slice_len = slice.len();
        // Now we push the slice onto the heap.
        let (stack_refs_len, len) = {
            let stack_refs_len = u32::try_from(agent.stack_refs.borrow().len())
                .expect("Stack references overflowed");
            let mut stack_ref_collections = agent.stack_ref_collections.borrow_mut();
            let len = stack_ref_collections.len();
            stack_ref_collections.push(HeapRootCollection::ArgumentsList(slice.into()));
            // Elsewhere we make assumptions about the size of the stack.
            // Thus check it here as well.
            (
                stack_refs_len,
                u32::try_from(len).expect("Stack reference collections overflowed"),
            )
        };
        let result = {
            let sub_gc = gc.subscope();
            let scoped_args = ScopedArgumentsList::new(len, sub_gc.nogc());
            // Once the slice is on the heap, we can perform the user's work.
            work(agent, scoped_args, sub_gc)
        };
        // After the user's work is done, we can get to work returning the
        // slice from the heap.
        let mut slice = {
            agent
                .stack_refs
                .borrow_mut()
                .truncate(stack_refs_len as usize);

            // We look at the slot where we put the slice in and check that
            // it contains an arguments list.
            let mut stack_ref_collections = agent.stack_ref_collections.borrow_mut();
            debug_assert!(stack_ref_collections.len() >= len as usize);
            let stack_slot = &mut stack_ref_collections[len as usize];
            // We take the slice back from the heap by replacing the data
            // with an empty collection, and then truncate the heap stack
            // to its previous size.
            let HeapRootCollection::ArgumentsList(slice) =
                core::mem::replace(stack_slot, HeapRootCollection::Empty)
            else {
                unreachable!()
            };
            stack_ref_collections.truncate(len as usize);
            slice
        };
        // Confirm that we have the right slice and that only valid subslicing
        // has occurred.
        // SAFETY: We had exclusive access to the slice and we've checked that it's
        let post_work_slice_len = slice.len();
        // SAFETY: This computes the end pointer of the slice meaning that we
        // necessarily do not wrap around or go out of bounds (by more than 1).
        let post_work_slice_end_ptr = unsafe {
            slice
                .as_ptr()
                .cast::<Value<'static>>()
                .add(post_work_slice_len)
        };
        assert!(slice_len >= post_work_slice_len);
        assert_eq!(slice_end_ptr, post_work_slice_end_ptr);
        // Now that we have our slice back, we can place it back where it
        // came from. The end result is that the slice has temporarily been
        // held by the heap and has been given back to the caller. While
        // the heap held it, the caller couldn't have done so, and thus the
        // exclusive reference requirement cannot have been broken by this
        // method.
        // The only thing we can break here is the lifetime requirement,
        // and that is only possible if the user method panicked and that
        // panic was caught and recovered from above us. ie. We're not
        // panic safe currently.
        // SAFETY: We've confirmed that this slice is the same slice that we
        // got originally in self.slice; it may have become a subslice of the
        // original slice but otherwise it is the same. Thus converting it
        // back to a mutable slice is safe.
        let slice = core::mem::replace(&mut self.slice, unsafe { slice.as_mut() });
        debug_assert!(slice.is_empty());
        result
    }

    pub(crate) fn slice_from(self, start: usize) -> ArgumentsList<'slice, 'value> {
        ArgumentsList {
            slice: self
                .slice
                .split_at_mut_checked(start)
                .map_or(&mut [], |(_, tail)| tail),
            value: PhantomData,
        }
    }

    /// Access the Values in an ArgumentsList as a slice.
    pub fn as_slice(&self) -> &[Value<'value>] {
        self.slice
    }

    /// Access the Values in an ArgumentsList as a mut slice.
    pub(crate) fn as_mut_slice(&mut self) -> &mut [Value<'static>] {
        self.slice
    }

    /// Get a Value by index from an ArgumentsList.
    ///
    /// If a Value with that index isn't present, `undefined` is returned.
    ///
    /// If the list itself has not been [bound](Bindable) then the returned
    /// Value should immediately be bound.
    #[inline]
    pub fn get(&self, index: usize) -> Value<'value> {
        *self.slice.get(index).unwrap_or(&Value::Undefined)
    }

    /// Get a Value by index from an ArgumentsList if present.
    ///
    /// If a Value with that index isn't present, None.
    ///
    /// If the list itself has not been [bound](Bindable) then the returned
    /// Value should immediately be bound.
    #[inline]
    pub fn get_if_present(&self, index: usize) -> Option<Value<'value>> {
        self.slice.get(index).copied()
    }
}

// SAFETY: Properly implemented as a lifetime transmute.
unsafe impl<'slice> Bindable for ArgumentsList<'slice, '_> {
    type Of<'a> = ArgumentsList<'slice, 'a>;

    #[inline(always)]
    fn unbind(self) -> Self::Of<'static> {
        unsafe {
            core::mem::transmute::<ArgumentsList<'slice, '_>, ArgumentsList<'slice, 'static>>(self)
        }
    }

    #[inline(always)]
    fn bind<'a>(self, _gc: NoGcScope<'a, '_>) -> Self::Of<'a> {
        unsafe {
            core::mem::transmute::<ArgumentsList<'slice, '_>, ArgumentsList<'slice, 'a>>(self)
        }
    }
}

impl<'value> Deref for ArgumentsList<'_, 'value> {
    type Target = [Value<'value>];

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

/// Arguments list stored temporarily on the Agent's heap.
///
/// The arguments can be accessed through the Agent for the duration of the
/// function call.
pub struct ScopedArgumentsList<'scope> {
    index: u32,
    value: PhantomData<Value<'scope>>,
}

impl<'scope> ScopedArgumentsList<'scope> {
    pub(crate) fn new(index: u32, _: NoGcScope<'_, 'scope>) -> Self {
        Self {
            index,
            value: PhantomData,
        }
    }

    /// Get a Value by index from an ArgumentsList.
    ///
    /// If a Value with that index isn't present, `undefined` is returned.
    ///
    /// If the list itself has not been [bound](Bindable) then the returned
    /// Value should immediately be bound.
    pub fn get<'gc>(&self, agent: &Agent, index: u32, gc: NoGcScope<'gc, '_>) -> Value<'gc> {
        if let HeapRootCollection::ArgumentsList(args) = agent
            .stack_ref_collections
            .borrow()
            .get(self.index as usize)
            .unwrap()
        {
            // SAFETY: The arguments list slice is guaranteed to be held
            // exclusively by an above call frame, and placed onto the heap as
            // a NonNull slice. Creating a temporary slice of it is safe.
            // Exception: if a panic has occurred then we could theoretically
            // be looking at an invalid slice, but in that case we shouldn't
            // have access to the ScopedArgumentsList anymore either.
            unsafe {
                args.as_ref()
                    .get(index as usize)
                    .unwrap_or(&Value::Undefined)
                    .bind(gc)
            }
        } else {
            unreachable!()
        }
    }

    /// Get the number of provided arguments.
    pub fn len(&self, agent: &Agent) -> usize {
        if let HeapRootCollection::ArgumentsList(args) = agent
            .stack_ref_collections
            .borrow()
            .get(self.index as usize)
            .unwrap()
        {
            args.len()
        } else {
            unreachable!()
        }
    }

    pub(crate) fn unshift<'gc>(&self, agent: &Agent, gc: NoGcScope<'gc, '_>) -> Option<Value<'gc>> {
        let mut collections = agent.stack_ref_collections.borrow_mut();
        let collection_data: &mut HeapRootCollection =
            collections.get_mut(self.index as usize).unwrap();
        if let HeapRootCollection::ArgumentsList(args_ref) = collection_data {
            // SAFETY: args_ref points to a valid exclusively held slice in an
            // above call frame.
            let args: &mut [Value<'static>] = unsafe { args_ref.as_mut() };
            if let Some((first, rest)) = args.split_first_mut() {
                let result = first.unbind().bind(gc);
                let rest = NonNull::from(rest);
                *args_ref = rest;
                Some(result)
            } else {
                None
            }
        } else {
            unreachable!()
        }
    }

    pub(crate) fn iter(&self, agent: &mut Agent) -> ScopedValuesIterator<'_> {
        if let HeapRootCollection::ArgumentsList(args) = agent
            .stack_ref_collections
            .borrow()
            .get(self.index as usize)
            .unwrap()
        {
            // SAFETY: args points to a uniquely owned slice in an above
            // call frame, we can safely dereference it.
            ScopedValuesIterator::from_slice(unsafe { args.as_ref() })
        } else {
            unreachable!()
        }
    }

    /// Get access to the backing reference slice as a pointer slice.
    ///
    /// ## Safety
    ///
    /// Garbage collection must not be called while this slice is exposed.
    ///
    /// Stack values must not be accessed while this slice is exposed.
    pub(crate) unsafe fn as_non_null_slice(&self, agent: &Agent) -> NonNull<[Value<'static>]> {
        if let HeapRootCollection::ArgumentsList(args) = agent
            .stack_ref_collections
            .borrow()
            .get(self.index as usize)
            .unwrap()
        {
            *args
        } else {
            unreachable!()
        }
    }
}

impl core::fmt::Debug for ScopedArgumentsList<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "ScopedArgumentsList({})", self.index)
    }
}

/// Calling convention of a builtin method.
pub type RegularFn =
    for<'gc> fn(&mut Agent, Value, ArgumentsList, GcScope<'gc, '_>) -> JsResult<'gc, Value<'gc>>;
/// Calling convention of a builtin constructor.
pub type ConstructorFn = for<'gc> fn(
    &mut Agent,
    Value,
    ArgumentsList,
    Option<Object>,
    GcScope<'gc, '_>,
) -> JsResult<'gc, Value<'gc>>;

/// Calling convention of a builtin function.
#[allow(unpredictable_function_pointer_comparisons)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Behaviour {
    /// Regular JavaScript function not callable with the `new` keyword.
    Regular(RegularFn),
    /// JavaScript function callable with the `new` keyword, and possibly
    /// without it.
    Constructor(ConstructorFn),
}

impl Behaviour {
    pub(crate) fn is_constructor(&self) -> bool {
        matches!(self, Behaviour::Constructor(_))
    }
}

/// Helper trait for defining builtin functions using the
/// [`BuiltinFunctionBuilder`].
///
/// [`BuiltinFunctionBuilder`]: crate::ecmascript::builders::BuiltinFunctionBuilder
pub trait Builtin {
    /// Name of the function
    ///
    /// This currently has to be a statically knowable name, which makes this
    /// trait mostly useless for embedders. This name also controls the property
    /// key that this function is assigned to if used to create a property.
    const NAME: String<'static>;
    /// Length of the function
    ///
    /// This is reported into JavaScript when the function object's `length`
    /// property is read.
    const LENGTH: u8;
    /// Behaviour of the function
    ///
    /// A builtin function can either be a normal function (not callable using
    /// `new ff`) or a constructor function (callable using `new f`). The enum
    /// choice here dictates which one it is, and the function pointer dictates
    /// the Rust code to run when JavaScript calls the function.
    const BEHAVIOUR: Behaviour;

    /// If the builtin function is created as a property then setting this to
    /// Some can be used to override the property key is this is assigned to. By
    /// default the `NAME` value is used.
    const KEY: Option<PropertyKey<'static>> = None;

    /// If the builtin function is created as a property then this controls the
    /// property's `[[Writable]]` value.
    const WRITABLE: bool = true;
    /// If the builtin function is created as a property then this controls the
    /// property's `[[Enumerable]]` value.
    const ENUMERABLE: bool = false;
    /// If the builtin function is created as a property then this controls the
    /// property's `[[Configurable]]` value.
    const CONFIGURABLE: bool = true;
}

pub(crate) trait BuiltinIntrinsicConstructor: Builtin {
    const INDEX: IntrinsicConstructorIndexes;
}

pub(crate) trait BuiltinIntrinsic: Builtin {
    const INDEX: IntrinsicFunctionIndexes;
}
/// Helper trait for defining builtin getter function properties.
pub trait BuiltinGetter: Builtin {
    /// Accessor property's getter function's `name` property value.
    const GETTER_NAME: String<'static> = Self::NAME;
    /// Accessor property's getter function's call behaviour.
    const GETTER_BEHAVIOUR: Behaviour = Self::BEHAVIOUR;
}
/// Helper trait for defining builtin setter function properties.
pub trait BuiltinSetter: Builtin {
    /// Accessor property's setter function's `name` property value.
    const SETTER_NAME: String<'static> = Self::NAME;
    /// Accessor property's setter function's call behaviour.
    const SETTER_BEHAVIOUR: Behaviour = Self::BEHAVIOUR;
}

/// Builtin function creation arguments.
#[derive(Debug, Default)]
pub struct BuiltinFunctionArgs<'a> {
    /// The builtin function's `length` property initial value.
    pub length: u32,
    /// The builtin function's `name` property initial value.
    pub name: &'static str,
    /// The builtin function's Realm. Defaults to the current Realm.
    pub realm: Option<Realm<'a>>,
    /// The builtin function's prototype. Defaults to the current Realm's
    /// `Function.prototype`
    pub prototype: Option<Object<'a>>,
    /// An optional prefix for the builtin function's name.
    pub prefix: Option<&'static str>,
}

impl<'a> BuiltinFunctionArgs<'a> {
    /// Create new builtin function creation arguments with length and name.
    pub fn new(length: u32, name: &'static str) -> Self {
        Self {
            length,
            name,
            ..Default::default()
        }
    }

    /// Create new builtin function creation arguments with length, name, and a realm.
    pub fn new_with_realm(length: u32, name: &'static str, realm: Realm<'a>) -> Self {
        Self {
            length,
            name,
            realm: Some(realm),
            ..Default::default()
        }
    }
}

/// ## [10.3 Built-in Function Objects](https://tc39.es/ecma262/#sec-built-in-function-objects)
///
/// A built-in function object is an ordinary object; it must satisfy the
/// requirements for ordinary objects set out in [10.1].
///
/// In addition to the internal slots required of every ordinary object (see
/// [10.1]), a built-in function object must also have the following internal
/// slots:
///
/// * \[\[Realm]], a Realm Record that represents the realm in which the
///   function was created.
/// * \[\[InitialName]], a String that is the initial name of the function. It
///   is used by [20.2.3.5].
/// * \[\[Async]], a Boolean that indicates whether the function has async
///   function call and construct behaviour in BuiltinCallOrConstruct.
///
/// [10.1]: https://tc39.es/ecma262/#sec-ordinary-object-internal-methods-and-internal-slots
/// [20.2.3.5]: https://tc39.es/ecma262/#sec-function.prototype.tostring
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct BuiltinFunction<'a>(BaseIndex<'a, BuiltinFunctionHeapData<'static>>);
arena_vec_access!(
    BuiltinFunction,
    'a,
    BuiltinFunctionHeapData,
    builtin_functions
);

impl<'f> BuiltinFunction<'f> {
    /// Allocate a a new uninitialised (None) BuiltinFunction and return its reference.
    pub(crate) fn new_uninitialised(agent: &mut Agent) -> Self {
        agent
            .heap
            .builtin_functions
            .push(BuiltinFunctionHeapData::BLANK);
        BuiltinFunction(BaseIndex::last(&agent.heap.builtin_functions))
    }

    /// Returns `true` if the builtin function is also callable as a constructor
    /// function.
    pub fn is_constructor(self, agent: &Agent) -> bool {
        // A builtin function has the [[Construct]] method if its behaviour is
        // a constructor behaviour.
        self.get(agent).behaviour.is_constructor()
    }

    /// ### \[\[Realm]]
    pub fn realm(self, agent: &Agent) -> Realm<'f> {
        self.get(agent).realm
    }
}
function_handle!(BuiltinFunction);

impl IntrinsicFunctionIndexes {
    pub(crate) const fn get_builtin_function<'a>(
        self,
        base: BaseIndex<'a, BuiltinFunctionHeapData<'static>>,
    ) -> BuiltinFunction<'a> {
        BuiltinFunction(BaseIndex::from_index_u32_const(
            self as u32 + base.get_index_u32_const() + Self::BUILTIN_FUNCTION_INDEX_OFFSET,
        ))
    }
}

impl IntrinsicConstructorIndexes {
    pub(crate) const fn get_builtin_function<'a>(
        self,
        base: BaseIndex<'a, BuiltinFunctionHeapData<'static>>,
    ) -> BuiltinFunction<'a> {
        BuiltinFunction(BaseIndex::from_index_u32_const(
            self as u32 + base.get_index_u32_const() + Self::BUILTIN_FUNCTION_INDEX_OFFSET,
        ))
    }
}

impl<'a> FunctionInternalProperties<'a> for BuiltinFunction<'a> {
    fn get_name(self, agent: &Agent) -> &String<'a> {
        self.get(agent)
            .initial_name
            .as_ref()
            .unwrap_or(&String::EMPTY_STRING)
    }

    fn get_length(self, agent: &Agent) -> u8 {
        self.get(agent).length
    }

    #[inline(always)]
    fn get_function_backing_object(self, agent: &Agent) -> Option<OrdinaryObject<'static>> {
        self.get(agent).object_index.unbind()
    }

    fn set_function_backing_object(
        self,
        agent: &mut Agent,
        backing_object: OrdinaryObject<'static>,
    ) {
        assert!(
            self.get_mut(agent)
                .object_index
                .replace(backing_object.unbind())
                .is_none()
        );
    }

    /// ### [10.3.1 \[\[Call\]\] ( thisArgument, argumentsList )](https://tc39.es/ecma262/#sec-built-in-function-objects-call-thisargument-argumentslist)
    ///
    /// The [[Call]] internal method of a built-in function object F takes
    /// arguments thisArgument (an ECMAScript language value) and argumentsList
    /// (a List of ECMAScript language values) and returns either a normal
    /// completion containing an ECMAScript language value or a throw
    /// completion.
    fn function_call<'gc>(
        self,
        agent: &mut Agent,
        this_argument: Value,
        arguments_list: ArgumentsList,
        gc: GcScope<'gc, '_>,
    ) -> JsResult<'gc, Value<'gc>> {
        let mut id = 0;
        ndt::builtin_call_start!(|| {
            let args = create_name_and_id(agent, self);
            id = args.1;
            args
        });
        // 1. Return ? BuiltinCallOrConstruct(F, thisArgument, argumentsList, undefined).
        let result =
            builtin_call_or_construct(agent, self, Some(this_argument), arguments_list, None, gc);
        ndt::builtin_call_done!(|| id);
        result
    }

    /// ### [10.3.2 \[\[Construct\]\] ( argumentsList, newTarget )](https://tc39.es/ecma262/#sec-built-in-function-objects-construct-argumentslist-newtarget)
    ///
    /// The [[Construct]] internal method of a built-in function object F (when
    /// the method is present) takes arguments argumentsList (a List of
    /// ECMAScript language values) and newTarget (a constructor) and returns
    /// either a normal completion containing an Object or a throw completion.
    fn function_construct<'gc>(
        self,
        agent: &mut Agent,
        arguments_list: ArgumentsList,
        new_target: Function,
        gc: GcScope<'gc, '_>,
    ) -> JsResult<'gc, Object<'gc>> {
        let mut id = 0;
        ndt::builtin_constructor_start!(|| {
            let args = create_name_and_id(agent, self);
            id = args.1;
            args
        });
        // 1. Return ? BuiltinCallOrConstruct(F, uninitialized, argumentsList, newTarget).
        let result =
            builtin_call_or_construct(agent, self, None, arguments_list, Some(new_target), gc)
                .map(|result| result.try_into().unwrap());
        ndt::builtin_constructor_done!(|| id);
        result
    }
}

#[inline(never)]
fn create_name_and_id<'a>(agent: &'a Agent, f: BuiltinFunction<'a>) -> (Cow<'a, str>, u64) {
    let id = match f.get(agent).behaviour {
        Behaviour::Regular(f) => f as usize as u64,
        Behaviour::Constructor(f) => f as usize as u64,
    };
    let name = f.get_name(agent).to_string_lossy_(agent);
    (name, id)
}

/// ### [10.3.3 BuiltinCallOrConstruct ( F, thisArgument, argumentsList, newTarget )](https://tc39.es/ecma262/#sec-builtincallorconstruct)
///
/// The abstract operation BuiltinCallOrConstruct takes arguments F (a built-in
/// function object), thisArgument (an ECMAScript language value or
/// uninitialized), argumentsList (a List of ECMAScript language values), and
/// newTarget (a constructor or undefined) and returns either a normal
/// completion containing an ECMAScript language value or a throw completion.
fn builtin_call_or_construct<'gc>(
    agent: &mut Agent,
    f: BuiltinFunction,
    this_argument: Option<Value>,
    arguments_list: ArgumentsList,
    new_target: Option<Function>,
    gc: GcScope<'gc, '_>,
) -> JsResult<'gc, Value<'gc>> {
    agent.check_call_depth(gc.nogc()).unbind()?;

    let f = f.bind(gc.nogc());
    let this_argument = this_argument.bind(gc.nogc());
    let arguments_list = arguments_list.bind(gc.nogc());
    let new_target = new_target.bind(gc.nogc());
    // 1. Let callerContext be the running execution context.
    let caller_context = agent.running_execution_context();
    // 2. If callerContext is not already suspended, suspend callerContext.
    caller_context.suspend();
    // 5. Let calleeRealm be F.[[Realm]].
    let heap_data = &f.get(agent);
    let callee_realm = heap_data.realm;
    let func = heap_data.behaviour;
    // 3. Let calleeContext be a new execution context.
    let callee_context = ExecutionContext {
        // 8. Perform any necessary implementation-defined initialization of calleeContext.
        ecmascript_code: None,
        // 4. Set the Function of calleeContext to F.
        function: Some(f.unbind().into()),
        // 6. Set the Realm of calleeContext to calleeRealm.
        realm: callee_realm.unbind(),
        // 7. Set the ScriptOrModule of calleeContext to null.
        script_or_module: None,
    };
    // 9. Push calleeContext onto the execution context stack; calleeContext is now the running execution context.
    agent.push_execution_context(callee_context);
    // 10. Let result be the Completion Record that is the result of evaluating F in a manner that conforms to
    // the specification of F. If thisArgument is uninitialized, the this value is uninitialized; otherwise,
    // thisArgument provides the this value. argumentsList provides the named parameters. newTarget provides the NewTarget value.
    let result = match func {
        Behaviour::Regular(func) => {
            if new_target.is_some() {
                Err(agent.throw_exception_with_static_message(
                    ExceptionType::TypeError,
                    "Not a constructor",
                    gc.into_nogc(),
                ))
            } else {
                func(
                    agent,
                    this_argument.unwrap_or(Value::Undefined).unbind(),
                    arguments_list.unbind(),
                    gc,
                )
            }
        }
        Behaviour::Constructor(func) => func(
            agent,
            this_argument.unwrap_or(Value::Undefined).unbind(),
            arguments_list.unbind(),
            new_target.map(|target| target.unbind().into()),
            gc,
        ),
    };
    // 11. NOTE: If F is defined in this document, “the specification of F” is the behaviour specified for it via
    // algorithm steps or other means.
    // 12. Remove calleeContext from the execution context stack and restore callerContext as the running
    // execution context.
    // Note
    // When calleeContext is removed from the execution context stack it must not be destroyed if it has been
    // suspended and retained by an accessible Generator for later resumption.
    let _callee_context = agent.pop_execution_context();
    // 13. Return ? result.
    result
}

/// ### [10.3.4 CreateBuiltinFunction ( behaviour, length, name, additionalInternalSlotsList \[ , realm \[ , prototype \[ , prefix \] \] \] )](https://tc39.es/ecma262/#sec-createbuiltinfunction)
///
/// The abstract operation CreateBuiltinFunction takes arguments behaviour (an
/// Abstract Closure, a set of algorithm steps, or some other definition of a
/// function's behaviour provided in this specification), length (a
/// non-negative integer or +∞), name (a property key or a Private Name), and
/// additionalInternalSlotsList (a List of names of internal slots) and
/// optional arguments realm (a Realm Record), prototype (an Object or null),
/// and prefix (a String) and returns a function object.
/// additionalInternalSlotsList contains the names of additional internal slots
/// that must be defined as part of the object. This operation creates a
/// built-in function object.
pub fn create_builtin_function<'a>(
    agent: &mut Agent,
    behaviour: Behaviour,
    args: BuiltinFunctionArgs,
    gc: NoGcScope<'a, '_>,
) -> BuiltinFunction<'a> {
    // 1. If realm is not present, set realm to the current Realm Record.
    let realm = args.realm.unwrap_or(agent.current_realm(gc));

    // 9. Set func.[[InitialName]] to null.
    // Note: SetFunctionName inlined here: We know name is a string
    let initial_name = if let Some(prefix) = args.prefix {
        // 12. Else,
        // a. Perform SetFunctionName(func, name, prefix).
        String::from_string(agent, format!("{} {}", args.name, prefix), gc)
    } else {
        // 11. If prefix is not present, then
        // a. Perform SetFunctionName(func, name).
        String::from_str(agent, args.name, gc)
    };

    // 2. If prototype is not present, set prototype to realm.[[Intrinsics]].[[%Function.prototype%]].

    // 3. Let internalSlotsList be a List containing the names of all the internal slots that 10.3
    //    requires for the built-in function object that is about to be created.
    // 4. Append to internalSlotsList the elements of additionalInternalSlotsList.
    // Note: The BuiltinFunctionHeapData implements all internal slots that 10.3 requires.
    // The currently appearing spec-defined additional slots are:
    // * [[ConstructorKind]] and [[SourceText]] for class constructors.
    // * [[Promise]] and [[AlreadyResolved]] for Promise resolver functions
    // * [[AlreadyCalled]], [[Index]], [[Values]], [[Capability]], and [[RemainingElements]] for
    //   Promise.all's onFulfilled function.
    // We do not yet support these, and how these end up supported is not yet fully clear.

    // 5. Let func be a new built-in function object that, when called, performs the action
    //    described by behaviour using the provided arguments as the values of the corresponding
    //    parameters specified by behaviour. The new function object has internal slots whose names
    //    are the elements of internalSlotsList, and an [[InitialName]] internal slot.
    let object_index = if let Some(prototype) = args.prototype {
        // If a prototype is set, then check that it is not the %Function.prototype%
        let realm_function_prototype = agent
            .get_realm_record_by_id(realm)
            .intrinsics()
            .get_intrinsic_default_proto(BuiltinFunction::DEFAULT_PROTOTYPE);
        if prototype == realm_function_prototype {
            // If the prototype matched the realm function prototype, then ignore it
            // as the BuiltinFunctionHeapData indirectly implies this prototype.
            None
        } else {
            // If some other prototype is defined then we need to create a backing object.
            // 6. Set func.[[Prototype]] to prototype.
            // 7. Set func.[[Extensible]] to true.
            let length_entry = ObjectEntry {
                key: PropertyKey::from(BUILTIN_STRING_MEMORY.length),
                value: ObjectEntryPropertyDescriptor::Data {
                    value: args.length.into(),
                    writable: false,
                    enumerable: false,
                    configurable: true,
                },
            };
            let name_entry = ObjectEntry {
                key: PropertyKey::from(BUILTIN_STRING_MEMORY.name),
                value: ObjectEntryPropertyDescriptor::Data {
                    value: initial_name.into(),
                    writable: false,
                    enumerable: false,
                    configurable: true,
                },
            };
            Some(
                OrdinaryObject::create_object(agent, Some(prototype), &[length_entry, name_entry])
                    .expect("Should perform GC here"),
            )
        }
    } else {
        None
    };

    // 13. Return func.
    agent
        .heap
        .create(BuiltinFunctionHeapData {
            behaviour,
            initial_name: Some(initial_name),
            // 10. Perform SetFunctionLength(func, length).
            length: args.length as u8,
            // 8. Set func.[[Realm]] to realm.
            realm,
            object_index,
        })
        .bind(gc)
}

impl<'a> CreateHeapData<BuiltinFunctionHeapData<'a>, BuiltinFunction<'a>> for Heap {
    fn create(&mut self, data: BuiltinFunctionHeapData<'a>) -> BuiltinFunction<'a> {
        self.builtin_functions.push(data.unbind());
        self.alloc_counter += core::mem::size_of::<BuiltinFunctionHeapData<'static>>();
        BuiltinFunction(BaseIndex::last(&self.builtin_functions))
    }
}

impl HeapMarkAndSweep for BuiltinFunction<'static> {
    fn mark_values(&self, queues: &mut WorkQueues) {
        queues.builtin_functions.push(*self);
    }

    fn sweep_values(&mut self, compactions: &CompactionLists) {
        compactions.builtin_functions.shift_index(&mut self.0);
    }
}

impl HeapSweepWeakReference for BuiltinFunction<'static> {
    fn sweep_weak_reference(self, compactions: &CompactionLists) -> Option<Self> {
        compactions
            .builtin_functions
            .shift_weak_index(self.0)
            .map(Self)
    }
}

bindable_handle!(BuiltinFunctionHeapData);

impl HeapMarkAndSweep for BuiltinFunctionHeapData<'static> {
    fn mark_values(&self, queues: &mut WorkQueues) {
        let Self {
            object_index,
            length: _,
            realm,
            initial_name,
            behaviour: _,
        } = self;
        realm.mark_values(queues);
        initial_name.mark_values(queues);
        object_index.mark_values(queues);
    }

    fn sweep_values(&mut self, compactions: &CompactionLists) {
        let Self {
            object_index,
            length: _,
            realm,
            initial_name,
            behaviour: _,
        } = self;
        realm.sweep_values(compactions);
        initial_name.sweep_values(compactions);
        object_index.sweep_values(compactions);
    }
}